├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── font
│ │ │ │ ├── poppins_black.ttf
│ │ │ │ ├── poppins_bold.ttf
│ │ │ │ ├── poppins_light.ttf
│ │ │ │ ├── poppins_medium.ttf
│ │ │ │ └── poppins_regular.ttf
│ │ │ ├── drawable
│ │ │ │ ├── il_placeholder.png
│ │ │ │ ├── bg_image_button.xml
│ │ │ │ ├── text_button.xml
│ │ │ │ ├── ic_add.xml
│ │ │ │ ├── bg_button.xml
│ │ │ │ ├── ic_exit.xml
│ │ │ │ ├── bg_edit_text_error.xml
│ │ │ │ ├── ic_map.xml
│ │ │ │ ├── bg_edit_text.xml
│ │ │ │ ├── ic_login.xml
│ │ │ │ ├── ic_message.xml
│ │ │ │ ├── ic_language.xml
│ │ │ │ ├── ic_lock.xml
│ │ │ │ ├── ic_account.xml
│ │ │ │ ├── ic_password.xml
│ │ │ │ ├── il_logo.xml
│ │ │ │ └── ic_launcher_background.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── xml
│ │ │ │ ├── file_paths.xml
│ │ │ │ ├── backup_rules.xml
│ │ │ │ └── data_extraction_rules.xml
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── values
│ │ │ │ ├── attrs.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ ├── themes.xml
│ │ │ │ ├── colors.xml
│ │ │ │ ├── styles.xml
│ │ │ │ └── strings.xml
│ │ │ ├── mipmap-anydpi-v33
│ │ │ │ └── ic_launcher.xml
│ │ │ ├── layout
│ │ │ │ ├── activity_welcome.xml
│ │ │ │ ├── widget_progress_button.xml
│ │ │ │ ├── item_loading.xml
│ │ │ │ ├── activity_maps.xml
│ │ │ │ ├── item_story.xml
│ │ │ │ ├── activity_login.xml
│ │ │ │ ├── activity_story_detail.xml
│ │ │ │ ├── activity_add_story.xml
│ │ │ │ ├── activity_register.xml
│ │ │ │ └── activity_story.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ ├── values-in-rID
│ │ │ │ └── strings.xml
│ │ │ └── raw
│ │ │ │ ├── map_style.json
│ │ │ │ └── lottie_loader.json
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── mirz
│ │ │ │ └── storyapp
│ │ │ │ ├── data
│ │ │ │ ├── response
│ │ │ │ │ ├── GeneralResponse.kt
│ │ │ │ │ ├── StoryDetailResponse.kt
│ │ │ │ │ ├── StoryListResponse.kt
│ │ │ │ │ ├── LoginResponse.kt
│ │ │ │ │ └── StoryResponse.kt
│ │ │ │ ├── source
│ │ │ │ │ ├── database
│ │ │ │ │ │ ├── RemoteKeys.kt
│ │ │ │ │ │ ├── RemoteKeysDao.kt
│ │ │ │ │ │ ├── StoryDao.kt
│ │ │ │ │ │ └── StoryDatabase.kt
│ │ │ │ │ ├── remote
│ │ │ │ │ │ ├── AuthInterceptor.kt
│ │ │ │ │ │ ├── RetrofitBuilder.kt
│ │ │ │ │ │ └── ApiServices.kt
│ │ │ │ │ └── local
│ │ │ │ │ │ └── UserPreferenceImpl.kt
│ │ │ │ ├── repository
│ │ │ │ │ ├── AuthRepositoryImpl.kt
│ │ │ │ │ └── StoryRepositoryImpl.kt
│ │ │ │ └── paging
│ │ │ │ │ ├── StoryPagingSource.kt
│ │ │ │ │ └── StoryRemoteMediator.kt
│ │ │ │ ├── domain
│ │ │ │ ├── contract
│ │ │ │ │ ├── LogoutUseCaseContract.kt
│ │ │ │ │ ├── GetUserUseCaseContract.kt
│ │ │ │ │ ├── LoginUseCaseContract.kt
│ │ │ │ │ ├── RegisterUseCaseContract.kt
│ │ │ │ │ ├── GetStoriesUseCaseContract.kt
│ │ │ │ │ ├── GetStoryDetailUseCaseContract.kt
│ │ │ │ │ ├── GetStoriesLocationUseCaseContract.kt
│ │ │ │ │ └── AddStoryUseCaseContract.kt
│ │ │ │ ├── entity
│ │ │ │ │ ├── UserEntity.kt
│ │ │ │ │ └── StoryEntity.kt
│ │ │ │ ├── interfaces
│ │ │ │ │ ├── UserPreferenceRepository.kt
│ │ │ │ │ ├── AuthRepository.kt
│ │ │ │ │ └── StoryRepository.kt
│ │ │ │ ├── usecase
│ │ │ │ │ ├── LogoutUseCase.kt
│ │ │ │ │ ├── GetUserUseCase.kt
│ │ │ │ │ ├── GetStoriesUseCase.kt
│ │ │ │ │ ├── GetStoryDetailUseCase.kt
│ │ │ │ │ ├── AddStoryUseCase.kt
│ │ │ │ │ ├── GetStoriesLocationUseCase.kt
│ │ │ │ │ ├── RegisterUseCase.kt
│ │ │ │ │ └── LoginUseCase.kt
│ │ │ │ └── mapper
│ │ │ │ │ └── StoryMapper.kt
│ │ │ │ ├── utils
│ │ │ │ ├── Constant.kt
│ │ │ │ ├── ResultState.kt
│ │ │ │ └── Extensions.kt
│ │ │ │ ├── App.kt
│ │ │ │ ├── ui
│ │ │ │ ├── login
│ │ │ │ │ ├── LoginViewState.kt
│ │ │ │ │ ├── LoginViewModel.kt
│ │ │ │ │ └── LoginActivity.kt
│ │ │ │ ├── add_story
│ │ │ │ │ ├── AddStoryViewState.kt
│ │ │ │ │ ├── AddStoryViewModel.kt
│ │ │ │ │ └── AddStoryActivity.kt
│ │ │ │ ├── register
│ │ │ │ │ ├── RegisterViewState.kt
│ │ │ │ │ ├── RegisterViewModel.kt
│ │ │ │ │ └── RegisterActivity.kt
│ │ │ │ ├── welcome
│ │ │ │ │ ├── WelcomeViewState.kt
│ │ │ │ │ ├── WelcomeViewModel.kt
│ │ │ │ │ └── WelcomeActivity.kt
│ │ │ │ ├── maps
│ │ │ │ │ ├── MapsViewState.kt
│ │ │ │ │ ├── MapsViewModel.kt
│ │ │ │ │ └── MapsActivity.kt
│ │ │ │ ├── detail_story
│ │ │ │ │ ├── StoryDetailViewState.kt
│ │ │ │ │ ├── StoryDetailViewModel.kt
│ │ │ │ │ └── StoryDetailActivity.kt
│ │ │ │ ├── story
│ │ │ │ │ ├── StoryViewState.kt
│ │ │ │ │ ├── StoryViewModel.kt
│ │ │ │ │ └── StoryActivity.kt
│ │ │ │ └── adapter
│ │ │ │ │ ├── LoadingStateAdapter.kt
│ │ │ │ │ └── StoryAdapter.kt
│ │ │ │ ├── widget
│ │ │ │ ├── EditText.kt
│ │ │ │ └── ProgressButton.kt
│ │ │ │ └── Locator.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── mirz
│ │ │ └── storyapp
│ │ │ ├── fake
│ │ │ ├── FakeLogoutUseCase.kt
│ │ │ ├── FakeGetUserUseCase.kt
│ │ │ └── FakeGetStoriesUseCase.kt
│ │ │ ├── utils
│ │ │ ├── FakeFlowDelegate.kt
│ │ │ ├── DataDummy.kt
│ │ │ └── MainDispatcherRule.kt
│ │ │ ├── ExampleUnitTest.kt
│ │ │ └── ui
│ │ │ └── story
│ │ │ └── StoryViewModelTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── mirz
│ │ └── storyapp
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── settings.gradle
├── gradle.properties
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MirzaUkas/StoryApp/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/font/poppins_black.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MirzaUkas/StoryApp/HEAD/app/src/main/res/font/poppins_black.ttf
--------------------------------------------------------------------------------
/app/src/main/res/font/poppins_bold.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MirzaUkas/StoryApp/HEAD/app/src/main/res/font/poppins_bold.ttf
--------------------------------------------------------------------------------
/app/src/main/res/font/poppins_light.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MirzaUkas/StoryApp/HEAD/app/src/main/res/font/poppins_light.ttf
--------------------------------------------------------------------------------
/app/src/main/res/font/poppins_medium.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MirzaUkas/StoryApp/HEAD/app/src/main/res/font/poppins_medium.ttf
--------------------------------------------------------------------------------
/app/src/main/res/font/poppins_regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MirzaUkas/StoryApp/HEAD/app/src/main/res/font/poppins_regular.ttf
--------------------------------------------------------------------------------
/app/src/main/res/drawable/il_placeholder.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MirzaUkas/StoryApp/HEAD/app/src/main/res/drawable/il_placeholder.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MirzaUkas/StoryApp/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MirzaUkas/StoryApp/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MirzaUkas/StoryApp/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MirzaUkas/StoryApp/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MirzaUkas/StoryApp/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MirzaUkas/StoryApp/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MirzaUkas/StoryApp/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MirzaUkas/StoryApp/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MirzaUkas/StoryApp/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MirzaUkas/StoryApp/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/xml/file_paths.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 | .cxx
10 | local.properties
11 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/data/response/GeneralResponse.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.data.response
2 |
3 | data class GeneralResponse(
4 | val error: Boolean,
5 | val message: String
6 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/contract/LogoutUseCaseContract.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.contract
2 |
3 | interface LogoutUseCaseContract {
4 | suspend operator fun invoke()
5 |
6 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/entity/UserEntity.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.entity
2 |
3 | data class UserEntity(
4 | val id: String,
5 | val name: String,
6 | val token: String,
7 | )
8 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/utils/Constant.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.utils
2 |
3 | object Constant {
4 | const val PREF_ID = "id"
5 | const val PREF_NAME = "name"
6 | const val PREF_TOKEN = "token"
7 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/data/response/StoryDetailResponse.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.data.response
2 |
3 |
4 | data class StoryDetailResponse(
5 | val error: Boolean,
6 | val message: String,
7 | val story: StoryResponse
8 | )
--------------------------------------------------------------------------------
/app/src/main/res/drawable/bg_image_button.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/data/response/StoryListResponse.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.data.response
2 |
3 |
4 | data class StoryListResponse(
5 | val error: Boolean,
6 | val message: String,
7 | val listStory: List
8 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/App.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp
2 |
3 | import android.app.Application
4 |
5 | class App : Application() {
6 | override fun onCreate() {
7 | super.onCreate()
8 | Locator.initWith(this)
9 | }
10 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/login/LoginViewState.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.login
2 |
3 | import com.mirz.storyapp.utils.ResultState
4 |
5 | data class LoginViewState(
6 | val resultVerifyUser: ResultState = ResultState.Idle()
7 | )
8 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/add_story/AddStoryViewState.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.add_story
2 |
3 | import com.mirz.storyapp.utils.ResultState
4 |
5 | data class AddStoryViewState(
6 | val resultAddStory: ResultState = ResultState.Idle()
7 | )
8 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/register/RegisterViewState.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.register
2 |
3 | import com.mirz.storyapp.utils.ResultState
4 |
5 | data class RegisterViewState(
6 | val resultRegisterUser: ResultState = ResultState.Idle()
7 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/welcome/WelcomeViewState.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.welcome
2 |
3 | import com.mirz.storyapp.utils.ResultState
4 |
5 | data class WelcomeViewState(
6 | val resultIsLoggedIn: ResultState = ResultState.Idle()
7 | )
8 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Apr 07 21:19:26 WIB 2023
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/app/src/test/java/com/mirz/storyapp/fake/FakeLogoutUseCase.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.fake
2 |
3 | import com.mirz.storyapp.domain.contract.LogoutUseCaseContract
4 |
5 | class FakeLogoutUseCase : LogoutUseCaseContract {
6 |
7 |
8 | override suspend fun invoke() = Unit
9 |
10 |
11 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/mirz/storyapp/utils/FakeFlowDelegate.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.utils
2 |
3 | import kotlinx.coroutines.flow.MutableSharedFlow
4 |
5 | class FakeFlowDelegate {
6 | val flow: MutableSharedFlow = MutableSharedFlow()
7 |
8 | suspend fun emit(value: T) = flow.emit(value)
9 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/contract/GetUserUseCaseContract.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.contract
2 |
3 | import com.mirz.storyapp.domain.entity.UserEntity
4 | import kotlinx.coroutines.flow.Flow
5 |
6 | interface GetUserUseCaseContract {
7 | operator fun invoke(): Flow
8 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/entity/StoryEntity.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.entity
2 |
3 | data class StoryEntity(
4 | val id: String,
5 | val name: String,
6 | val description: String,
7 | val photoUrl: String,
8 | val lat: Double,
9 | val lng: Double,
10 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/maps/MapsViewState.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.maps
2 |
3 | import com.mirz.storyapp.domain.entity.StoryEntity
4 | import com.mirz.storyapp.utils.ResultState
5 |
6 | data class MapsViewState(
7 | val resultStories: ResultState> = ResultState.Idle(),
8 | )
--------------------------------------------------------------------------------
/app/src/main/res/drawable/text_button.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/detail_story/StoryDetailViewState.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.detail_story
2 |
3 | import com.mirz.storyapp.domain.entity.StoryEntity
4 | import com.mirz.storyapp.utils.ResultState
5 |
6 | data class StoryDetailViewState(
7 | val resultStory: ResultState = ResultState.Idle()
8 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/contract/LoginUseCaseContract.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.contract
2 |
3 | import com.mirz.storyapp.utils.ResultState
4 | import kotlinx.coroutines.flow.Flow
5 |
6 | interface LoginUseCaseContract {
7 | operator fun invoke(email: String, password: String): Flow>
8 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/story/StoryViewState.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.story
2 |
3 | import androidx.paging.PagingData
4 | import com.mirz.storyapp.domain.entity.StoryEntity
5 |
6 | data class StoryViewState(
7 | val resultStories: PagingData = PagingData.empty(),
8 | val username: String = "",
9 | )
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/data/source/database/RemoteKeys.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.data.source.database
2 |
3 | import androidx.room.Entity
4 | import androidx.room.PrimaryKey
5 |
6 | @Entity(tableName = "remote_keys")
7 | data class RemoteKeys(
8 | @PrimaryKey val id: String,
9 | val prevKey: Int?,
10 | val nextKey: Int?
11 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/contract/RegisterUseCaseContract.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.contract
2 |
3 | import com.mirz.storyapp.utils.ResultState
4 | import kotlinx.coroutines.flow.Flow
5 |
6 | interface RegisterUseCaseContract {
7 | operator fun invoke(name: String, email: String, password: String): Flow>
8 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/data/response/LoginResponse.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.data.response
2 |
3 | data class LoginResponse(
4 | val error: Boolean,
5 | val loginResult: LoginResult,
6 | val message: String
7 | )
8 |
9 | data class LoginResult(
10 | val name: String,
11 | val token: String,
12 | val userId: String
13 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/contract/GetStoriesUseCaseContract.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.contract
2 |
3 | import androidx.paging.PagingData
4 | import com.mirz.storyapp.domain.entity.StoryEntity
5 | import kotlinx.coroutines.flow.Flow
6 |
7 | interface GetStoriesUseCaseContract {
8 | operator fun invoke(): Flow>
9 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_add.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/attrs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/contract/GetStoryDetailUseCaseContract.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.contract
2 |
3 | import com.mirz.storyapp.domain.entity.StoryEntity
4 | import com.mirz.storyapp.utils.ResultState
5 | import kotlinx.coroutines.flow.Flow
6 |
7 | interface GetStoryDetailUseCaseContract {
8 | operator fun invoke(id: String): Flow>
9 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/contract/GetStoriesLocationUseCaseContract.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.contract
2 |
3 | import com.mirz.storyapp.domain.entity.StoryEntity
4 | import com.mirz.storyapp.utils.ResultState
5 | import kotlinx.coroutines.flow.Flow
6 |
7 | interface GetStoriesLocationUseCaseContract {
8 | operator fun invoke(): Flow>>
9 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/interfaces/UserPreferenceRepository.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.interfaces
2 |
3 | import com.mirz.storyapp.domain.entity.UserEntity
4 | import kotlinx.coroutines.flow.Flow
5 |
6 | interface UserPreferenceRepository {
7 | val userData: Flow
8 | suspend fun saveUser(userEntity: UserEntity)
9 | suspend fun clearUser()
10 | }
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v33/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google()
4 | mavenCentral()
5 | gradlePluginPortal()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 | rootProject.name = "StoryApp"
16 | include ':app'
17 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 8dp
4 | 16dp
5 | 30dp
6 | 40dp
7 |
8 | 12sp
9 | 16sp
10 | 20sp
11 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/contract/AddStoryUseCaseContract.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.contract
2 |
3 | import com.google.android.gms.maps.model.LatLng
4 | import com.mirz.storyapp.utils.ResultState
5 | import kotlinx.coroutines.flow.Flow
6 | import java.io.File
7 |
8 | interface AddStoryUseCaseContract {
9 | operator fun invoke(file: File, description: String, latLng: LatLng?): Flow>
10 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/usecase/LogoutUseCase.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.usecase
2 |
3 | import com.mirz.storyapp.domain.contract.LogoutUseCaseContract
4 | import com.mirz.storyapp.domain.interfaces.UserPreferenceRepository
5 |
6 | class LogoutUseCase(private val userPreferenceRepository: UserPreferenceRepository) :
7 | LogoutUseCaseContract {
8 | override suspend fun invoke() = userPreferenceRepository.clearUser()
9 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/mirz/storyapp/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/utils/ResultState.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.utils
2 |
3 | sealed class ResultState(
4 | val data: T? = null,
5 | val message: String = "",
6 | ) {
7 | class Success(data: T) : ResultState(data)
8 |
9 | class Loading : ResultState()
10 |
11 | class Idle : ResultState()
12 |
13 | class Error(message: String, data: T? = null) :
14 | ResultState(data, message)
15 | }
16 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/interfaces/AuthRepository.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.interfaces
2 |
3 | import com.mirz.storyapp.data.response.GeneralResponse
4 | import com.mirz.storyapp.data.response.LoginResponse
5 | import kotlinx.coroutines.flow.Flow
6 |
7 | interface AuthRepository {
8 | fun register(email: String, password: String, name: String): Flow
9 | fun login(email: String, password: String): Flow
10 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/mirz/storyapp/fake/FakeGetUserUseCase.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.fake
2 |
3 | import com.mirz.storyapp.domain.contract.GetUserUseCaseContract
4 | import com.mirz.storyapp.domain.entity.UserEntity
5 | import com.mirz.storyapp.utils.FakeFlowDelegate
6 | import kotlinx.coroutines.flow.Flow
7 |
8 | class FakeGetUserUseCase : GetUserUseCaseContract {
9 |
10 | val fakeDelegate = FakeFlowDelegate()
11 |
12 | override fun invoke(): Flow = fakeDelegate.flow
13 |
14 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/bg_button.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | -
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/data/response/StoryResponse.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.data.response
2 |
3 | import androidx.room.Entity
4 | import androidx.room.PrimaryKey
5 | import com.google.gson.annotations.SerializedName
6 |
7 |
8 | @Entity(tableName = "story")
9 | data class StoryResponse(
10 | @PrimaryKey @field:SerializedName("id") val id: String,
11 | val createdAt: String,
12 | val description: String,
13 | val lat: Double,
14 | val lon: Double,
15 | val name: String,
16 | val photoUrl: String
17 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/usecase/GetUserUseCase.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.usecase
2 |
3 | import com.mirz.storyapp.domain.contract.GetUserUseCaseContract
4 | import com.mirz.storyapp.domain.entity.UserEntity
5 | import com.mirz.storyapp.domain.interfaces.UserPreferenceRepository
6 | import kotlinx.coroutines.flow.Flow
7 |
8 | class GetUserUseCase(private val userPreferenceRepository: UserPreferenceRepository) :
9 | GetUserUseCaseContract {
10 | override fun invoke(): Flow = userPreferenceRepository.userData
11 | }
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_exit.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/usecase/GetStoriesUseCase.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.usecase
2 |
3 | import com.mirz.storyapp.domain.contract.GetStoriesUseCaseContract
4 | import com.mirz.storyapp.domain.interfaces.StoryRepository
5 | import com.mirz.storyapp.domain.mapper.map
6 | import kotlinx.coroutines.flow.map
7 |
8 | class GetStoriesUseCase(private val storyRepository: StoryRepository) : GetStoriesUseCaseContract {
9 | override fun invoke() = storyRepository.getStories().map { pagingData ->
10 | pagingData.map()
11 | }
12 |
13 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/bg_edit_text_error.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | -
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/test/java/com/mirz/storyapp/fake/FakeGetStoriesUseCase.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.fake
2 |
3 | import androidx.paging.PagingData
4 | import com.mirz.storyapp.domain.contract.GetStoriesUseCaseContract
5 | import com.mirz.storyapp.domain.entity.StoryEntity
6 | import com.mirz.storyapp.utils.FakeFlowDelegate
7 | import kotlinx.coroutines.flow.Flow
8 |
9 | class FakeGetStoriesUseCase : GetStoriesUseCaseContract {
10 |
11 | val fakeDelegate = FakeFlowDelegate>()
12 |
13 | override fun invoke(): Flow> = fakeDelegate.flow
14 |
15 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_map.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/data/source/database/RemoteKeysDao.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.data.source.database
2 |
3 | import androidx.room.Dao
4 | import androidx.room.Insert
5 | import androidx.room.OnConflictStrategy
6 | import androidx.room.Query
7 |
8 | @Dao
9 | interface RemoteKeysDao {
10 | @Insert(onConflict = OnConflictStrategy.REPLACE)
11 | suspend fun insertAll(remoteKey: List)
12 |
13 | @Query("SELECT * FROM remote_keys WHERE id = :id")
14 | suspend fun getRemoteKeysId(id: String): RemoteKeys?
15 |
16 | @Query("DELETE FROM remote_keys")
17 | suspend fun deleteRemoteKeys()
18 | }
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/data/source/database/StoryDao.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.data.source.database
2 |
3 | import androidx.paging.PagingSource
4 | import androidx.room.Dao
5 | import androidx.room.Insert
6 | import androidx.room.OnConflictStrategy
7 | import androidx.room.Query
8 | import com.mirz.storyapp.data.response.StoryResponse
9 |
10 | @Dao
11 | interface StoryDao {
12 | @Insert(onConflict = OnConflictStrategy.REPLACE)
13 | suspend fun insertStories(quote: List)
14 |
15 | @Query("SELECT * FROM story")
16 | fun getAllStories(): PagingSource
17 |
18 | @Query("DELETE FROM story")
19 | suspend fun deleteAll()
20 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/mirz/storyapp/utils/DataDummy.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.utils
2 |
3 | import com.mirz.storyapp.data.response.StoryResponse
4 |
5 | object DataDummy {
6 |
7 | fun generateDummyStoryResponse(): List {
8 | val items: MutableList = arrayListOf()
9 | for (i in 0..100) {
10 | val quote = StoryResponse(
11 | i.toString(),
12 | "createdAt + $i",
13 | "description $i",
14 | 0.0,
15 | 0.0,
16 | "name $i",
17 | "photoUrl $i",
18 | )
19 | items.add(quote)
20 | }
21 | return items
22 | }
23 | }
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/mirz/storyapp/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.mirz.storyapp", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/interfaces/StoryRepository.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.interfaces
2 |
3 | import androidx.paging.PagingData
4 | import com.google.android.gms.maps.model.LatLng
5 | import com.mirz.storyapp.data.response.GeneralResponse
6 | import com.mirz.storyapp.data.response.StoryDetailResponse
7 | import com.mirz.storyapp.data.response.StoryListResponse
8 | import com.mirz.storyapp.data.response.StoryResponse
9 | import kotlinx.coroutines.flow.Flow
10 | import java.io.File
11 |
12 | interface StoryRepository {
13 | fun getStories(): Flow>
14 | fun getStory(id: String): Flow
15 | fun addStory(file: File, description: String, latLng: LatLng?): Flow
16 | fun getStoriesLocation(id: Int): Flow
17 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/bg_edit_text.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | -
4 |
5 |
6 |
7 |
8 |
9 |
10 | -
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/test/java/com/mirz/storyapp/utils/MainDispatcherRule.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.utils
2 |
3 | import kotlinx.coroutines.Dispatchers
4 | import kotlinx.coroutines.ExperimentalCoroutinesApi
5 | import kotlinx.coroutines.test.TestDispatcher
6 | import kotlinx.coroutines.test.UnconfinedTestDispatcher
7 | import kotlinx.coroutines.test.resetMain
8 | import kotlinx.coroutines.test.setMain
9 | import org.junit.rules.TestWatcher
10 | import org.junit.runner.Description
11 |
12 | @ExperimentalCoroutinesApi
13 | class MainDispatcherRule(
14 | private val testDispatcher: TestDispatcher = UnconfinedTestDispatcher()
15 | ) : TestWatcher() {
16 | override fun starting(description: Description) {
17 | Dispatchers.setMain(testDispatcher)
18 | }
19 |
20 | override fun finished(description: Description) {
21 | Dispatchers.resetMain()
22 | }
23 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
17 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_login.xml:
--------------------------------------------------------------------------------
1 |
6 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_welcome.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
19 |
20 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #92A3FD
7 | #C58BF2
8 | #9DCEFF
9 | #FF03DAC5
10 | #FF018786
11 | #1D1617
12 | #FF000000
13 | #FFFFFFFF
14 | #FF29B6F6
15 | #FF039BE5
16 | #FFBDBDBD
17 | #FF757575
18 | #F7F8F8
19 | #ADA4A5
20 | #CF212A
21 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_message.xml:
--------------------------------------------------------------------------------
1 |
6 |
13 |
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/usecase/GetStoryDetailUseCase.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.usecase
2 |
3 | import com.mirz.storyapp.domain.contract.GetStoryDetailUseCaseContract
4 | import com.mirz.storyapp.domain.entity.StoryEntity
5 | import com.mirz.storyapp.domain.interfaces.StoryRepository
6 | import com.mirz.storyapp.domain.mapper.map
7 | import com.mirz.storyapp.utils.ResultState
8 | import kotlinx.coroutines.flow.Flow
9 | import kotlinx.coroutines.flow.catch
10 | import kotlinx.coroutines.flow.flow
11 | import kotlinx.coroutines.flow.map
12 |
13 | class GetStoryDetailUseCase(private val storyRepository: StoryRepository) :
14 | GetStoryDetailUseCaseContract {
15 | override operator fun invoke(id: String): Flow> = flow {
16 | emit(ResultState.Loading())
17 | storyRepository.getStory(id).map {
18 | it.story.map()
19 | }.catch {
20 | emit(ResultState.Error(message = it.message.toString()))
21 | }.collect {
22 | emit(ResultState.Success(it))
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/usecase/AddStoryUseCase.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.usecase
2 |
3 | import com.google.android.gms.maps.model.LatLng
4 | import com.mirz.storyapp.domain.contract.AddStoryUseCaseContract
5 | import com.mirz.storyapp.domain.interfaces.StoryRepository
6 | import com.mirz.storyapp.utils.ResultState
7 | import kotlinx.coroutines.flow.Flow
8 | import kotlinx.coroutines.flow.catch
9 | import kotlinx.coroutines.flow.flow
10 | import java.io.File
11 |
12 | class AddStoryUseCase(private val storyRepository: StoryRepository) : AddStoryUseCaseContract {
13 | override operator fun invoke(
14 | file: File,
15 | description: String,
16 | latLng: LatLng?
17 | ): Flow> =
18 | flow {
19 | emit(ResultState.Loading())
20 | storyRepository.addStory(file, description, latLng).catch {
21 | emit(ResultState.Error(message = it.message.toString()))
22 | }.collect {
23 | emit(ResultState.Success(it.message))
24 | }
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/data/source/remote/AuthInterceptor.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.data.source.remote
2 |
3 | import androidx.datastore.core.DataStore
4 | import androidx.datastore.preferences.core.Preferences
5 | import androidx.datastore.preferences.core.stringPreferencesKey
6 | import kotlinx.coroutines.flow.first
7 | import kotlinx.coroutines.runBlocking
8 | import okhttp3.Interceptor
9 | import okhttp3.Response
10 |
11 | class AuthInterceptor(private val dataStore: DataStore) : Interceptor {
12 |
13 | override fun intercept(chain: Interceptor.Chain): Response {
14 | val original = chain.request()
15 | val token = runBlocking {
16 | dataStore.data.first()[stringPreferencesKey("token")]
17 | }
18 |
19 | return if (!token.isNullOrEmpty()) {
20 | val authorized = original.newBuilder()
21 | .addHeader("Authorization", "Bearer $token")
22 | .build()
23 | chain.proceed(authorized)
24 | } else {
25 | chain.proceed(original)
26 | }
27 | }
28 |
29 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/usecase/GetStoriesLocationUseCase.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.usecase
2 |
3 | import com.mirz.storyapp.domain.contract.GetStoriesLocationUseCaseContract
4 | import com.mirz.storyapp.domain.entity.StoryEntity
5 | import com.mirz.storyapp.domain.interfaces.StoryRepository
6 | import com.mirz.storyapp.domain.mapper.map
7 | import com.mirz.storyapp.utils.ResultState
8 | import kotlinx.coroutines.flow.Flow
9 | import kotlinx.coroutines.flow.catch
10 | import kotlinx.coroutines.flow.flow
11 | import kotlinx.coroutines.flow.map
12 |
13 | class GetStoriesLocationUseCase(private val storyRepository: StoryRepository) :
14 | GetStoriesLocationUseCaseContract {
15 |
16 | override operator fun invoke(): Flow>> = flow {
17 | emit(ResultState.Loading())
18 | storyRepository.getStoriesLocation(1).map {
19 | it.listStory.map()
20 | }.catch {
21 | emit(ResultState.Error(message = it.message.toString()))
22 | }.collect {
23 | emit(ResultState.Success(it))
24 | }
25 | }
26 |
27 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/widget_progress_button.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
16 |
17 |
18 |
27 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/mapper/StoryMapper.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.mapper
2 |
3 | import androidx.paging.PagingData
4 | import androidx.paging.map
5 | import com.mirz.storyapp.data.response.StoryResponse
6 | import com.mirz.storyapp.domain.entity.StoryEntity
7 |
8 |
9 | fun StoryResponse.map() = let { story ->
10 | StoryEntity(
11 | id = story.id,
12 | name = story.name,
13 | description = story.description,
14 | photoUrl = story.photoUrl,
15 | lat = story.lat,
16 | lng = story.lon,
17 | )
18 | }
19 |
20 | fun List.map() = map { story ->
21 | StoryEntity(
22 | id = story.id,
23 | name = story.name,
24 | description = story.description,
25 | photoUrl = story.photoUrl,
26 | lat = story.lat,
27 | lng = story.lon,
28 | )
29 | }
30 |
31 | fun PagingData.map() = map { story ->
32 | StoryEntity(
33 | id = story.id,
34 | name = story.name,
35 | description = story.description,
36 | photoUrl = story.photoUrl,
37 | lat = story.lat,
38 | lng = story.lon,
39 | )
40 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/data/repository/AuthRepositoryImpl.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.data.repository
2 |
3 | import com.mirz.storyapp.data.source.remote.ApiServices
4 | import com.mirz.storyapp.domain.interfaces.AuthRepository
5 | import kotlinx.coroutines.Dispatchers
6 | import kotlinx.coroutines.flow.flow
7 | import kotlinx.coroutines.flow.flowOn
8 |
9 | class AuthRepositoryImpl(private val api: ApiServices) : AuthRepository {
10 |
11 | override fun register(email: String, password: String, name: String) = flow {
12 | emit(
13 | api.register(
14 | hashMapOf(
15 | Pair("name", name),
16 | Pair("password", password),
17 | Pair("email", email),
18 | )
19 | )
20 | )
21 | }.flowOn(Dispatchers.IO)
22 |
23 | override fun login(email: String, password: String) = flow {
24 | emit(
25 | api.login(
26 | hashMapOf(
27 | Pair("password", password),
28 | Pair("email", email),
29 | )
30 | )
31 | )
32 | }.flowOn(Dispatchers.IO)
33 |
34 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/usecase/RegisterUseCase.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.usecase
2 |
3 | import com.mirz.storyapp.domain.contract.RegisterUseCaseContract
4 | import com.mirz.storyapp.domain.interfaces.AuthRepository
5 | import com.mirz.storyapp.utils.ResultState
6 | import kotlinx.coroutines.flow.Flow
7 | import kotlinx.coroutines.flow.catch
8 | import kotlinx.coroutines.flow.flow
9 |
10 | class RegisterUseCase(
11 | private val authRepository: AuthRepository,
12 | ) : RegisterUseCaseContract {
13 | override operator fun invoke(
14 | name: String,
15 | email: String,
16 | password: String
17 | ): Flow> =
18 | flow {
19 | emit(ResultState.Loading())
20 | authRepository.register(
21 | email, password, name
22 | ).catch {
23 | emit(ResultState.Error(it.message.toString()))
24 | }.collect { result ->
25 | if (result.error) {
26 | emit(ResultState.Error(result.message))
27 | } else {
28 | emit(ResultState.Success(result.message))
29 | }
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/data/source/remote/RetrofitBuilder.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.data.source.remote
2 |
3 | import androidx.datastore.core.DataStore
4 | import androidx.datastore.preferences.core.Preferences
5 | import com.mirz.storyapp.BuildConfig
6 | import okhttp3.OkHttpClient
7 | import okhttp3.logging.HttpLoggingInterceptor
8 | import retrofit2.Retrofit
9 | import retrofit2.converter.gson.GsonConverterFactory
10 |
11 | class RetrofitBuilder(private val dataStore: DataStore) {
12 |
13 | private fun getRetrofit(): Retrofit {
14 | return Retrofit.Builder()
15 | .baseUrl(BuildConfig.BASE_URL)
16 | .client(
17 | OkHttpClient.Builder()
18 | .addInterceptor(
19 | HttpLoggingInterceptor()
20 | .setLevel(HttpLoggingInterceptor.Level.BODY)
21 | )
22 | .addInterceptor(AuthInterceptor(dataStore))
23 | .build()
24 | )
25 | .addConverterFactory(GsonConverterFactory.create())
26 | .build()
27 | }
28 |
29 | val apiService: ApiServices = getRetrofit().create(ApiServices::class.java)
30 |
31 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/data/source/database/StoryDatabase.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.data.source.database
2 |
3 | import android.content.Context
4 | import androidx.room.Database
5 | import androidx.room.Room
6 | import androidx.room.RoomDatabase
7 | import com.mirz.storyapp.data.response.StoryResponse
8 |
9 | @Database(
10 | entities = [StoryResponse::class, RemoteKeys::class],
11 | version = 1,
12 | exportSchema = false
13 | )
14 | abstract class StoryDatabase : RoomDatabase() {
15 | abstract fun storyDao(): StoryDao
16 | abstract fun remoteKeysDao(): RemoteKeysDao
17 |
18 | companion object {
19 | @Volatile
20 | private var INSTANCE: StoryDatabase? = null
21 |
22 | @JvmStatic
23 | fun getDatabase(context: Context): StoryDatabase {
24 | return INSTANCE ?: synchronized(this) {
25 | INSTANCE ?: Room.databaseBuilder(
26 | context.applicationContext,
27 | StoryDatabase::class.java, "story_database"
28 | )
29 | .fallbackToDestructiveMigration()
30 | .build()
31 | .also { INSTANCE = it }
32 | }
33 | }
34 | }
35 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/item_loading.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
17 |
18 |
24 |
25 |
31 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_language.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_lock.xml:
--------------------------------------------------------------------------------
1 |
6 |
13 |
21 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
8 |
9 |
13 |
14 |
18 |
19 |
23 |
24 |
25 |
30 |
33 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/login/LoginViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.login
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.ViewModelProvider
5 | import androidx.lifecycle.viewModelScope
6 | import com.mirz.storyapp.domain.contract.LoginUseCaseContract
7 | import com.mirz.storyapp.domain.usecase.LoginUseCase
8 | import kotlinx.coroutines.flow.*
9 |
10 | class LoginViewModel(
11 | private val loginUseCase: LoginUseCaseContract
12 | ) : ViewModel() {
13 | private val _loginState = MutableStateFlow(LoginViewState())
14 | val loginState = _loginState.asStateFlow()
15 |
16 |
17 | fun doLogin(email: String, password: String) {
18 | loginUseCase(email, password)
19 | .onEach { result ->
20 | _loginState.update {
21 | it.copy(resultVerifyUser = result)
22 | }
23 | }.launchIn(viewModelScope)
24 | }
25 |
26 | class Factory(
27 | private val loginUseCase: LoginUseCase
28 | ) : ViewModelProvider.Factory {
29 | @Suppress("UNCHECKED_CAST")
30 | override fun create(modelClass: Class): T {
31 | if (modelClass.isAssignableFrom(LoginViewModel::class.java)) {
32 | return LoginViewModel(loginUseCase) as T
33 | }
34 | error("Unknown ViewModel class: $modelClass")
35 | }
36 | }
37 |
38 | }
39 |
40 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_account.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
10 |
14 |
15 |
16 |
19 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/data/source/remote/ApiServices.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.data.source.remote
2 |
3 | import com.mirz.storyapp.data.response.GeneralResponse
4 | import com.mirz.storyapp.data.response.LoginResponse
5 | import com.mirz.storyapp.data.response.StoryDetailResponse
6 | import com.mirz.storyapp.data.response.StoryListResponse
7 | import okhttp3.MultipartBody
8 | import okhttp3.RequestBody
9 | import retrofit2.http.*
10 |
11 | interface ApiServices {
12 | @POST("register")
13 | suspend fun register(
14 | @Body requestBody: HashMap
15 | ): GeneralResponse
16 |
17 | @POST("login")
18 | suspend fun login(
19 | @Body requestBody: HashMap
20 | ): LoginResponse
21 |
22 | @GET("stories")
23 | suspend fun stories(
24 | @Query("page") page: Int,
25 | @Query("size") size: Int
26 | ): StoryListResponse
27 |
28 | @GET("stories/{id}")
29 | suspend fun storyDetail(
30 | @Path("id") id: String
31 | ): StoryDetailResponse
32 |
33 | @Multipart
34 | @POST("stories")
35 | suspend fun addStory(
36 | @Part file: MultipartBody.Part,
37 | @Part("description") description: RequestBody,
38 | @Part("lat") lat: Float?,
39 | @Part("lon") lon: Float?,
40 | ): GeneralResponse
41 |
42 | @GET("stories")
43 | suspend fun storiesLocation(
44 | @Query("location") id: Int
45 | ): StoryListResponse
46 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/register/RegisterViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.register
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.ViewModelProvider
5 | import androidx.lifecycle.viewModelScope
6 | import com.mirz.storyapp.domain.contract.RegisterUseCaseContract
7 | import com.mirz.storyapp.domain.usecase.RegisterUseCase
8 | import kotlinx.coroutines.flow.*
9 |
10 | class RegisterViewModel(
11 | private val registerUseCase: RegisterUseCaseContract
12 | ) : ViewModel() {
13 |
14 | private val _registerViewState = MutableStateFlow(RegisterViewState())
15 | val registerViewState = _registerViewState.asStateFlow()
16 |
17 | fun registerUser(name: String, email: String, password: String) {
18 | registerUseCase(name, email, password).onEach { result ->
19 | _registerViewState.update {
20 | it.copy(resultRegisterUser = result)
21 | }
22 | }.launchIn(viewModelScope)
23 | }
24 |
25 | class Factory(
26 | private val registerUseCase: RegisterUseCase
27 | ) : ViewModelProvider.Factory {
28 | @Suppress("UNCHECKED_CAST")
29 | override fun create(modelClass: Class): T {
30 | if (modelClass.isAssignableFrom(RegisterViewModel::class.java)) {
31 | return RegisterViewModel(registerUseCase) as T
32 | }
33 | error("Unknown ViewModel class: $modelClass")
34 | }
35 | }
36 | }
37 |
38 |
39 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
24 | BASE_URL_DICODING="https://story-api.dicoding.dev/v1/"
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/detail_story/StoryDetailViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.detail_story
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.ViewModelProvider
5 | import androidx.lifecycle.viewModelScope
6 | import com.mirz.storyapp.domain.contract.GetStoryDetailUseCaseContract
7 | import com.mirz.storyapp.domain.usecase.GetStoryDetailUseCase
8 | import kotlinx.coroutines.flow.*
9 |
10 | class StoryDetailViewModel(private val getStoryDetailUseCase: GetStoryDetailUseCaseContract) :
11 | ViewModel() {
12 | private val _storyDetailViewState = MutableStateFlow(StoryDetailViewState())
13 | val storyDetailViewState
14 | get() = _storyDetailViewState.asStateFlow()
15 |
16 | fun getStoryDetail(id: String) {
17 | getStoryDetailUseCase(id).onEach { result ->
18 | _storyDetailViewState.update {
19 | it.copy(resultStory = result)
20 | }
21 | }.launchIn(viewModelScope)
22 | }
23 |
24 | class Factory(
25 | private val getStoryDetailUseCase: GetStoryDetailUseCase
26 | ) : ViewModelProvider.Factory {
27 | @Suppress("UNCHECKED_CAST")
28 | override fun create(modelClass: Class): T {
29 | if (modelClass.isAssignableFrom(StoryDetailViewModel::class.java)) {
30 | return StoryDetailViewModel(getStoryDetailUseCase) as T
31 | }
32 | error("Unknown ViewModel class: $modelClass")
33 | }
34 | }
35 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/data/paging/StoryPagingSource.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.data.paging
2 |
3 | import androidx.paging.PagingSource
4 | import androidx.paging.PagingState
5 | import com.mirz.storyapp.data.response.StoryResponse
6 | import com.mirz.storyapp.data.source.remote.ApiServices
7 |
8 | class StoryPagingSource(private val apiService: ApiServices) : PagingSource() {
9 |
10 |
11 | override fun getRefreshKey(state: PagingState): Int? {
12 | return state.anchorPosition?.let { anchorPosition ->
13 | val anchorPage = state.closestPageToPosition(anchorPosition)
14 | anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
15 | }
16 | }
17 |
18 | override suspend fun load(params: LoadParams): LoadResult {
19 | return try {
20 | val position = params.key ?: INITIAL_PAGE_INDEX
21 | val responseData = apiService.stories(position, params.loadSize)
22 | LoadResult.Page(
23 | data = responseData.listStory,
24 | prevKey = if (position == INITIAL_PAGE_INDEX) null else position - 1,
25 | nextKey = if (responseData.listStory.isEmpty()) null else position + 1
26 | )
27 | } catch (exception: Exception) {
28 | return LoadResult.Error(exception)
29 | }
30 | }
31 |
32 |
33 | private companion object {
34 | const val INITIAL_PAGE_INDEX = 1
35 | }
36 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/add_story/AddStoryViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.add_story
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.ViewModelProvider
5 | import androidx.lifecycle.viewModelScope
6 | import com.google.android.gms.maps.model.LatLng
7 | import com.mirz.storyapp.domain.contract.AddStoryUseCaseContract
8 | import com.mirz.storyapp.domain.usecase.AddStoryUseCase
9 | import kotlinx.coroutines.flow.*
10 | import java.io.File
11 |
12 | class AddStoryViewModel(private val addStoryUseCase: AddStoryUseCaseContract) : ViewModel() {
13 | private val _addStoryState = MutableStateFlow(AddStoryViewState())
14 | val addStoryState = _addStoryState.asStateFlow()
15 |
16 | fun addStory(file: File, description: String, latLng: LatLng?) {
17 | addStoryUseCase(file, description, latLng).onEach { result ->
18 | _addStoryState.update {
19 | it.copy(resultAddStory = result)
20 | }
21 | }.launchIn(viewModelScope)
22 | }
23 |
24 | class Factory(
25 | private val addStoryUseCase: AddStoryUseCase
26 | ) : ViewModelProvider.Factory {
27 | @Suppress("UNCHECKED_CAST")
28 | override fun create(modelClass: Class): T {
29 | if (modelClass.isAssignableFrom(AddStoryViewModel::class.java)) {
30 | return AddStoryViewModel(addStoryUseCase) as T
31 | }
32 | error("Unknown ViewModel class: $modelClass")
33 | }
34 | }
35 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_maps.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
18 |
19 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/domain/usecase/LoginUseCase.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.domain.usecase
2 |
3 | import com.mirz.storyapp.domain.contract.LoginUseCaseContract
4 | import com.mirz.storyapp.domain.entity.UserEntity
5 | import com.mirz.storyapp.domain.interfaces.AuthRepository
6 | import com.mirz.storyapp.domain.interfaces.UserPreferenceRepository
7 | import com.mirz.storyapp.utils.ResultState
8 | import kotlinx.coroutines.flow.Flow
9 | import kotlinx.coroutines.flow.catch
10 | import kotlinx.coroutines.flow.flow
11 |
12 | class LoginUseCase(
13 | private val userPreferenceRepository: UserPreferenceRepository,
14 | private val authRepository: AuthRepository,
15 | ) : LoginUseCaseContract {
16 | override operator fun invoke(email: String, password: String): Flow> =
17 | flow {
18 | emit(ResultState.Loading())
19 | authRepository.login(email, password).catch {
20 | emit(ResultState.Error(it.message.toString()))
21 | }.collect { result ->
22 | if (result.error) {
23 | emit(ResultState.Error(result.message))
24 | } else {
25 | result.loginResult.let {
26 | userPreferenceRepository.saveUser(
27 | UserEntity(
28 | it.userId, it.name, it.token
29 | )
30 | )
31 | }
32 | emit(ResultState.Success(result.message))
33 | }
34 | }
35 | }
36 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/maps/MapsViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.maps
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.ViewModelProvider
5 | import androidx.lifecycle.viewModelScope
6 | import com.mirz.storyapp.domain.contract.GetStoriesLocationUseCaseContract
7 | import com.mirz.storyapp.domain.usecase.GetStoriesLocationUseCase
8 | import kotlinx.coroutines.flow.MutableStateFlow
9 | import kotlinx.coroutines.flow.asStateFlow
10 | import kotlinx.coroutines.flow.update
11 | import kotlinx.coroutines.launch
12 |
13 | class MapsViewModel(
14 | private val getStoriesLocationUseCase: GetStoriesLocationUseCaseContract,
15 | ) : ViewModel() {
16 | private val _mapsState = MutableStateFlow(MapsViewState())
17 | val mapsState = _mapsState.asStateFlow()
18 |
19 | fun getStories() {
20 | viewModelScope.launch {
21 | getStoriesLocationUseCase().collect { stories ->
22 | _mapsState.update {
23 | it.copy(resultStories = stories)
24 | }
25 | }
26 | }
27 | }
28 |
29 | class Factory(
30 | private val getStoriesLocationUseCase: GetStoriesLocationUseCase
31 | ) : ViewModelProvider.Factory {
32 | @Suppress("UNCHECKED_CAST")
33 | override fun create(modelClass: Class): T {
34 | if (modelClass.isAssignableFrom(MapsViewModel::class.java)) {
35 | return MapsViewModel(getStoriesLocationUseCase) as T
36 | }
37 | error("Unknown ViewModel class: $modelClass")
38 | }
39 | }
40 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/welcome/WelcomeViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.welcome
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.ViewModelProvider
5 | import androidx.lifecycle.viewModelScope
6 | import com.mirz.storyapp.domain.usecase.GetUserUseCase
7 | import com.mirz.storyapp.utils.ResultState
8 | import kotlinx.coroutines.delay
9 | import kotlinx.coroutines.flow.MutableStateFlow
10 | import kotlinx.coroutines.flow.asStateFlow
11 | import kotlinx.coroutines.flow.update
12 | import kotlinx.coroutines.launch
13 |
14 | class WelcomeViewModel(
15 | private val getUserUseCase: GetUserUseCase
16 | ) : ViewModel() {
17 | private val _welcomeState = MutableStateFlow(WelcomeViewState())
18 | val welcomeState = _welcomeState.asStateFlow()
19 |
20 | init {
21 | getIsLoggedIn()
22 | }
23 |
24 | private fun getIsLoggedIn() {
25 | viewModelScope.launch {
26 | getUserUseCase().collect { user ->
27 | delay(3000)
28 | _welcomeState.update {
29 | it.copy(resultIsLoggedIn = ResultState.Success(user.token.isNotEmpty()))
30 | }
31 | }
32 | }
33 | }
34 |
35 | class Factory(
36 | private val getUserUseCase: GetUserUseCase
37 | ) : ViewModelProvider.Factory {
38 | @Suppress("UNCHECKED_CAST")
39 | override fun create(modelClass: Class): T {
40 | if (modelClass.isAssignableFrom(WelcomeViewModel::class.java)) {
41 | return WelcomeViewModel(getUserUseCase) as T
42 | }
43 | error("Unknown ViewModel class: $modelClass")
44 | }
45 | }
46 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/adapter/LoadingStateAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.adapter
2 |
3 | import android.view.LayoutInflater
4 | import android.view.ViewGroup
5 | import androidx.core.view.isVisible
6 | import androidx.paging.LoadState
7 | import androidx.paging.LoadStateAdapter
8 | import androidx.recyclerview.widget.RecyclerView
9 | import com.mirz.storyapp.databinding.ItemLoadingBinding
10 |
11 | class LoadingStateAdapter(private val retry: () -> Unit) :
12 | LoadStateAdapter() {
13 | override fun onCreateViewHolder(
14 | parent: ViewGroup,
15 | loadState: LoadState
16 | ): LoadingStateViewHolder {
17 | val binding = ItemLoadingBinding.inflate(LayoutInflater.from(parent.context), parent, false)
18 | return LoadingStateViewHolder(binding, retry)
19 | }
20 |
21 | override fun onBindViewHolder(holder: LoadingStateViewHolder, loadState: LoadState) {
22 | holder.bind(loadState)
23 | }
24 |
25 | class LoadingStateViewHolder(private val binding: ItemLoadingBinding, retry: () -> Unit) :
26 | RecyclerView.ViewHolder(binding.root) {
27 | init {
28 | binding.retryButton.setOnClickListener { retry.invoke() }
29 | }
30 |
31 | fun bind(loadState: LoadState) {
32 | if (loadState is LoadState.Error) {
33 | binding.errorMsg.text = loadState.error.localizedMessage
34 | }
35 | binding.progressBar.isVisible = loadState is LoadState.Loading
36 | binding.retryButton.isVisible = loadState is LoadState.Error
37 | binding.errorMsg.isVisible = loadState is LoadState.Error
38 | }
39 | }
40 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_password.xml:
--------------------------------------------------------------------------------
1 |
6 |
13 |
20 |
27 |
34 |
41 |
42 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | StoryApp
3 | Don\'t have an account yet? Register
4 | Login
5 | Password
6 | Email
7 | Welcome Back
8 | Hey there,
9 | Password must be at least 8 characters
10 | Create an Account
11 | Name
12 | Already have an account? Login
13 | Login Failed, Please Try Again..
14 | Register Failed, Please Try Again..
15 | Register Success, Please Login..
16 | Register
17 | Description
18 | Upload
19 | Camera
20 | Gallery
21 | Please choose an image file first.
22 | Success add story!
23 | Did not get camera permissions.
24 | Did not get location permissions.
25 | Try Again
26 | Detail Story Photo
27 | Location is not found. Try Again
28 | Enable Location
29 | Input Invalid
30 |
--------------------------------------------------------------------------------
/app/src/main/res/values-in-rID/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | StoryApp
4 | Belum punya akun? Daftar
5 | Masuk
6 | Kata Sandi
7 | Email
8 | Selamat Datang
9 | Hai Kamu,
10 | Kata sandi harus minimal 8 karakter
11 | Buat sebuah akun
12 | Nama
13 | Sudah memiliki akun? Masuk
14 | Login Gagal, Silahkan coba lagi..
15 | Register Gagal, Silahkan coba lagi..
16 | Register Sukses, Silahkan Login..
17 | Register
18 | Deskripsi
19 | Unggah
20 | Kamera
21 | Galeri
22 | Silakan pilih file gambar terlebih dahulu.
23 | Sukses tambah cerita!
24 | Gagal mendapatkan izin kamera.
25 | Gagal mendapatkan izin lokasi.
26 | Coba Lagi
27 | Gambar Detail Story
28 | Lokasi tidak ditemukan. Coba lagi
29 | Aktifkan Lokasi
30 | Input Invalid!
31 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/data/source/local/UserPreferenceImpl.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.data.source.local
2 |
3 | import androidx.datastore.core.DataStore
4 | import androidx.datastore.preferences.core.Preferences
5 | import androidx.datastore.preferences.core.edit
6 | import androidx.datastore.preferences.core.stringPreferencesKey
7 | import com.mirz.storyapp.domain.entity.UserEntity
8 | import com.mirz.storyapp.domain.interfaces.UserPreferenceRepository
9 | import com.mirz.storyapp.utils.Constant.PREF_ID
10 | import com.mirz.storyapp.utils.Constant.PREF_NAME
11 | import com.mirz.storyapp.utils.Constant.PREF_TOKEN
12 | import kotlinx.coroutines.flow.Flow
13 | import kotlinx.coroutines.flow.distinctUntilChanged
14 | import kotlinx.coroutines.flow.map
15 |
16 | class UserPreferenceImpl(private val dataStore: DataStore) : UserPreferenceRepository {
17 |
18 | private object Keys {
19 | val id = stringPreferencesKey(PREF_ID)
20 | val name = stringPreferencesKey(PREF_NAME)
21 | val token = stringPreferencesKey(PREF_TOKEN)
22 | }
23 |
24 | private inline val Preferences.id
25 | get() = this[Keys.id] ?: ""
26 | private inline val Preferences.name
27 | get() = this[Keys.name] ?: ""
28 | private inline val Preferences.token
29 | get() = this[Keys.token] ?: ""
30 |
31 | override val userData: Flow = dataStore.data.map {
32 | UserEntity(
33 | id = it.id,
34 | name = it.name,
35 | token = it.token
36 | )
37 | }.distinctUntilChanged()
38 |
39 | override suspend fun saveUser(userEntity: UserEntity) {
40 | dataStore.edit {
41 | it[Keys.id] = userEntity.id
42 | it[Keys.name] = userEntity.name
43 | it[Keys.token] = userEntity.token
44 | }
45 | }
46 |
47 |
48 | override suspend fun clearUser() {
49 | dataStore.edit {
50 | it.clear()
51 | }
52 | }
53 |
54 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/widget/EditText.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.widget
2 |
3 | import android.content.Context
4 | import android.graphics.Canvas
5 | import android.graphics.drawable.Drawable
6 | import android.text.TextUtils
7 | import android.util.AttributeSet
8 | import androidx.appcompat.widget.AppCompatEditText
9 | import androidx.core.content.ContextCompat
10 | import androidx.core.widget.addTextChangedListener
11 | import com.mirz.storyapp.R
12 |
13 | class EditText : AppCompatEditText {
14 | private lateinit var editTextBackground: Drawable
15 | private lateinit var editTextErrorBackground: Drawable
16 | private var isError = false
17 |
18 | constructor(context: Context) : super(context) {
19 | init()
20 | }
21 |
22 | constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
23 | init()
24 | }
25 |
26 | constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
27 | context, attrs, defStyleAttr
28 | ) {
29 | init()
30 | }
31 |
32 | override fun onDraw(canvas: Canvas?) {
33 | super.onDraw(canvas)
34 | background = if (isError) editTextErrorBackground else editTextBackground
35 | addTextChangedListener(onTextChanged = { text, _, _, _ ->
36 | if (!TextUtils.isEmpty(text) && text.toString().length < 8 && compoundDrawables[DRAWABLE_RIGHT] != null) {
37 | error = resources.getString(R.string.password_minimum_character)
38 | isError = true
39 | } else {
40 | error = null
41 | isError = false
42 | }
43 | })
44 | }
45 |
46 | private fun init() {
47 | editTextBackground = ContextCompat.getDrawable(context, R.drawable.bg_edit_text) as Drawable
48 | editTextErrorBackground =
49 | ContextCompat.getDrawable(context, R.drawable.bg_edit_text_error) as Drawable
50 | }
51 |
52 | companion object {
53 | const val DRAWABLE_RIGHT = 2
54 |
55 | }
56 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/detail_story/StoryDetailActivity.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.detail_story
2 |
3 | import android.os.Bundle
4 | import android.widget.Toast
5 | import androidx.activity.viewModels
6 | import androidx.appcompat.app.AppCompatActivity
7 | import com.bumptech.glide.Glide
8 | import com.mirz.storyapp.Locator
9 | import com.mirz.storyapp.databinding.ActivityStoryDetailBinding
10 | import com.mirz.storyapp.domain.entity.StoryEntity
11 | import com.mirz.storyapp.utils.ResultState
12 | import com.mirz.storyapp.utils.launchAndCollectIn
13 |
14 | class StoryDetailActivity : AppCompatActivity() {
15 | private val binding by lazy { ActivityStoryDetailBinding.inflate(layoutInflater) }
16 | private val viewModel by viewModels(factoryProducer = { Locator.storyDetailViewModelFactory })
17 |
18 | override fun onCreate(savedInstanceState: Bundle?) {
19 | super.onCreate(savedInstanceState)
20 | setContentView(binding.root)
21 |
22 | intent.getStringExtra(EXTRA_STORY_ID)?.let {
23 | viewModel.getStoryDetail(it)
24 | }
25 |
26 | viewModel.storyDetailViewState.launchAndCollectIn(this) { state ->
27 | when (state.resultStory) {
28 | is ResultState.Success -> {
29 | binding.progressBar.visibility = android.view.View.GONE
30 | state.resultStory.data?.let {
31 | binding.tvDetailName.text = it.name
32 | binding.tvDetailDescription.text = it.description
33 | Glide.with(this@StoryDetailActivity)
34 | .load(it.photoUrl)
35 | .into(binding.ivDetailPhoto)
36 | }
37 |
38 | }
39 | is ResultState.Loading -> binding.progressBar.visibility = android.view.View.VISIBLE
40 | is ResultState.Error -> {
41 | binding.progressBar.visibility = android.view.View.GONE
42 | Toast.makeText(
43 | this@StoryDetailActivity, state.resultStory.message, Toast.LENGTH_SHORT
44 | ).show()
45 | }
46 | else -> Unit
47 | }
48 | }
49 | }
50 |
51 | companion object {
52 | const val EXTRA_STORY_ID = "STORY_ID"
53 | }
54 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/welcome/WelcomeActivity.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.welcome
2 |
3 | import android.content.Intent
4 | import android.os.Bundle
5 | import androidx.activity.viewModels
6 | import androidx.appcompat.app.AppCompatActivity
7 | import androidx.core.view.WindowCompat
8 | import androidx.core.view.WindowInsetsCompat
9 | import androidx.core.view.WindowInsetsControllerCompat
10 | import com.mirz.storyapp.Locator
11 | import com.mirz.storyapp.databinding.ActivityWelcomeBinding
12 | import com.mirz.storyapp.ui.login.LoginActivity
13 | import com.mirz.storyapp.ui.story.StoryActivity
14 | import com.mirz.storyapp.utils.ResultState
15 | import com.mirz.storyapp.utils.launchAndCollectIn
16 |
17 | class WelcomeActivity : AppCompatActivity() {
18 | private val binding by lazy { ActivityWelcomeBinding.inflate(layoutInflater) }
19 | private val viewModel by viewModels(factoryProducer = { Locator.welcomeViewModelFactory })
20 | override fun onCreate(savedInstanceState: Bundle?) {
21 | super.onCreate(savedInstanceState)
22 | setContentView(binding.root)
23 | hideSystemUI()
24 | viewModel.welcomeState.launchAndCollectIn(this) {
25 | if (it.resultIsLoggedIn is ResultState.Success) {
26 | if (it.resultIsLoggedIn.data == true) {
27 | startActivity(
28 | Intent(this@WelcomeActivity, StoryActivity::class.java).addFlags(
29 | Intent.FLAG_ACTIVITY_CLEAR_TOP
30 | )
31 | )
32 | finish()
33 | } else {
34 | startActivity(
35 | Intent(this@WelcomeActivity, LoginActivity::class.java).addFlags(
36 | Intent.FLAG_ACTIVITY_CLEAR_TOP
37 | )
38 | )
39 | finish()
40 | }
41 | }
42 | }
43 |
44 | }
45 |
46 | private fun hideSystemUI() {
47 | WindowCompat.setDecorFitsSystemWindows(window, false)
48 | WindowInsetsControllerCompat(window, binding.root).let { controller ->
49 | controller.hide(WindowInsetsCompat.Type.systemBars())
50 | controller.systemBarsBehavior =
51 | WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
52 | }
53 | }
54 |
55 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/data/repository/StoryRepositoryImpl.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.data.repository
2 |
3 | import androidx.paging.ExperimentalPagingApi
4 | import androidx.paging.Pager
5 | import androidx.paging.PagingConfig
6 | import androidx.paging.PagingData
7 | import com.google.android.gms.maps.model.LatLng
8 | import com.mirz.storyapp.data.paging.StoryRemoteMediator
9 | import com.mirz.storyapp.data.response.StoryResponse
10 | import com.mirz.storyapp.data.source.database.StoryDatabase
11 | import com.mirz.storyapp.data.source.remote.ApiServices
12 | import com.mirz.storyapp.domain.interfaces.StoryRepository
13 | import kotlinx.coroutines.Dispatchers
14 | import kotlinx.coroutines.flow.Flow
15 | import kotlinx.coroutines.flow.flow
16 | import kotlinx.coroutines.flow.flowOn
17 | import okhttp3.MediaType.Companion.toMediaType
18 | import okhttp3.MediaType.Companion.toMediaTypeOrNull
19 | import okhttp3.MultipartBody
20 | import okhttp3.RequestBody.Companion.asRequestBody
21 | import okhttp3.RequestBody.Companion.toRequestBody
22 | import java.io.File
23 |
24 | class StoryRepositoryImpl(
25 | private val storyDatabase: StoryDatabase, private val api: ApiServices
26 | ) : StoryRepository {
27 | override fun getStories(): Flow> {
28 | @OptIn(ExperimentalPagingApi::class) return Pager(config = PagingConfig(
29 | pageSize = 5
30 | ), remoteMediator = StoryRemoteMediator(storyDatabase, api), pagingSourceFactory = {
31 | storyDatabase.storyDao().getAllStories()
32 | }).flow
33 | }
34 |
35 | override fun getStory(id: String) = flow {
36 | emit(
37 | api.storyDetail(id)
38 | )
39 | }.flowOn(Dispatchers.IO)
40 |
41 | override fun addStory(file: File, description: String, latLng: LatLng?) = flow {
42 | val requestBody = MultipartBody.Part.createFormData(
43 | "photo", file.name, file.asRequestBody("image/jpeg".toMediaTypeOrNull())
44 | )
45 | val desc = description.toRequestBody("text/plain".toMediaType())
46 | val lat = latLng?.latitude?.toFloat()
47 | val lng = latLng?.longitude?.toFloat()
48 |
49 | emit(
50 | api.addStory(requestBody, desc, lat, lng)
51 | )
52 | }.flowOn(Dispatchers.IO)
53 |
54 | override fun getStoriesLocation(id: Int) = flow {
55 | emit(
56 | api.storiesLocation(id)
57 | )
58 | }.flowOn(Dispatchers.IO)
59 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/widget/ProgressButton.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.widget
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import android.view.LayoutInflater
6 | import android.view.View
7 | import android.widget.RelativeLayout
8 | import android.widget.TextView
9 | import com.airbnb.lottie.LottieAnimationView
10 | import com.mirz.storyapp.R
11 |
12 | class ProgressButton @JvmOverloads constructor(
13 | context: Context,
14 | attrs: AttributeSet? = null,
15 | defStyleAttr: Int = 0
16 | ) : RelativeLayout(context, attrs, defStyleAttr) {
17 |
18 | private val progressBar: LottieAnimationView
19 | private val buttonTextView: TextView
20 |
21 | init {
22 | val root = LayoutInflater.from(context).inflate(R.layout.widget_progress_button, this, true)
23 | buttonTextView = root.findViewById(R.id.button_text)
24 | progressBar = root.findViewById(R.id.progress_indicator)
25 | loadAttr(attrs, defStyleAttr)
26 | }
27 |
28 | private fun loadAttr(attrs: AttributeSet?, defStyleAttr: Int) {
29 | val arr = context.obtainStyledAttributes(
30 | attrs,
31 | R.styleable.ProgressButton,
32 | defStyleAttr,
33 | 0
34 | )
35 |
36 | val buttonText = arr.getString(R.styleable.ProgressButton_text)
37 | val loading = arr.getBoolean(R.styleable.ProgressButton_loading, false)
38 | val enabled = arr.getBoolean(R.styleable.ProgressButton_enabled, true)
39 | val lottieResId = arr.getResourceId(R.styleable.ProgressButton_lottie_resId, R.raw.lottie_loader)
40 | arr.recycle()
41 | isEnabled = enabled
42 | buttonTextView.isEnabled = enabled
43 | setText(buttonText)
44 | progressBar.setAnimation(lottieResId)
45 | setLoading(loading)
46 | }
47 |
48 | fun setLoading(loading: Boolean){
49 | isClickable = !loading //Disable clickable when loading
50 | if(loading){
51 | buttonTextView.visibility = View.GONE
52 | progressBar.visibility = View.VISIBLE
53 | } else {
54 | buttonTextView.visibility = View.VISIBLE
55 | progressBar.visibility = View.GONE
56 | }
57 | }
58 |
59 | fun setText(text : String?) {
60 | buttonTextView.text = text
61 | }
62 |
63 | override fun setEnabled(enabled: Boolean) {
64 | super.setEnabled(enabled)
65 | buttonTextView.isEnabled = enabled
66 | }
67 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/item_story.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
16 |
17 |
27 |
28 |
39 |
40 |
53 |
54 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/story/StoryViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.story
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.ViewModelProvider
5 | import androidx.lifecycle.viewModelScope
6 | import androidx.paging.cachedIn
7 | import com.mirz.storyapp.domain.contract.GetStoriesUseCaseContract
8 | import com.mirz.storyapp.domain.contract.GetUserUseCaseContract
9 | import com.mirz.storyapp.domain.contract.LogoutUseCaseContract
10 | import com.mirz.storyapp.domain.usecase.GetStoriesUseCase
11 | import com.mirz.storyapp.domain.usecase.GetUserUseCase
12 | import com.mirz.storyapp.domain.usecase.LogoutUseCase
13 | import kotlinx.coroutines.flow.MutableStateFlow
14 | import kotlinx.coroutines.flow.asStateFlow
15 | import kotlinx.coroutines.flow.update
16 | import kotlinx.coroutines.launch
17 |
18 | class StoryViewModel(
19 | private val getStoriesUseCase: GetStoriesUseCaseContract,
20 | private val getUserUseCase: GetUserUseCaseContract,
21 | private val logoutUseCase: LogoutUseCaseContract
22 | ) : ViewModel() {
23 | private val _storyState = MutableStateFlow(StoryViewState())
24 | val storyState = _storyState.asStateFlow()
25 |
26 | fun getStories() {
27 | viewModelScope.launch {
28 | getStoriesUseCase().cachedIn(viewModelScope).collect { stories ->
29 | _storyState.update {
30 | it.copy(resultStories = stories)
31 | }
32 | }
33 | }
34 | }
35 |
36 | fun logout() {
37 | viewModelScope.launch {
38 | logoutUseCase()
39 | }
40 | }
41 |
42 | fun getUser() {
43 | viewModelScope.launch {
44 | getUserUseCase().collect { user ->
45 | _storyState.update {
46 | it.copy(username = user.name)
47 | }
48 | }
49 | }
50 | }
51 |
52 | class Factory(
53 | private val getStoriesUseCase: GetStoriesUseCase,
54 | private val getUserUseCase: GetUserUseCase,
55 | private val logoutUseCase: LogoutUseCase
56 | ) : ViewModelProvider.Factory {
57 | @Suppress("UNCHECKED_CAST")
58 | override fun create(modelClass: Class): T {
59 | if (modelClass.isAssignableFrom(StoryViewModel::class.java)) {
60 | return StoryViewModel(getStoriesUseCase, getUserUseCase, logoutUseCase) as T
61 | }
62 | error("Unknown ViewModel class: $modelClass")
63 | }
64 | }
65 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/story/StoryActivity.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.story
2 |
3 | import android.content.Intent
4 | import android.os.Bundle
5 | import android.provider.Settings
6 | import androidx.activity.viewModels
7 | import androidx.appcompat.app.AppCompatActivity
8 | import androidx.recyclerview.widget.LinearLayoutManager
9 | import com.mirz.storyapp.Locator
10 | import com.mirz.storyapp.databinding.ActivityStoryBinding
11 | import com.mirz.storyapp.ui.adapter.LoadingStateAdapter
12 | import com.mirz.storyapp.ui.adapter.StoryAdapter
13 | import com.mirz.storyapp.ui.add_story.AddStoryActivity
14 | import com.mirz.storyapp.ui.login.LoginActivity
15 | import com.mirz.storyapp.ui.maps.MapsActivity
16 | import com.mirz.storyapp.utils.launchAndCollectIn
17 |
18 | class StoryActivity : AppCompatActivity() {
19 | private val binding by lazy { ActivityStoryBinding.inflate(layoutInflater) }
20 | private val viewModel by viewModels(factoryProducer = { Locator.storyViewModelFactory })
21 | private val adapter by lazy { StoryAdapter() }
22 |
23 | override fun onCreate(savedInstanceState: Bundle?) {
24 | super.onCreate(savedInstanceState)
25 | setContentView(binding.root)
26 | initAdapter()
27 | viewModel.storyState.launchAndCollectIn(this) {
28 | adapter.submitData(lifecycle, it.resultStories)
29 | binding.tvName.text = it.username
30 | }
31 |
32 | binding.fabAddStory.setOnClickListener {
33 | startActivity(Intent(this@StoryActivity, AddStoryActivity::class.java))
34 | }
35 | binding.actionLogout.setOnClickListener {
36 | viewModel.logout()
37 | startActivity(Intent(this@StoryActivity, LoginActivity::class.java))
38 | finish()
39 | }
40 |
41 | binding.actionChangeLanguage.setOnClickListener {
42 | startActivity(Intent(Settings.ACTION_LOCALE_SETTINGS))
43 | }
44 | binding.actionMaps.setOnClickListener {
45 | startActivity(Intent(this@StoryActivity, MapsActivity::class.java))
46 | }
47 |
48 | }
49 |
50 | override fun onResume() {
51 | super.onResume()
52 | viewModel.getStories()
53 | viewModel.getUser()
54 | }
55 |
56 | private fun initAdapter() {
57 | binding.rvStory.adapter = adapter.withLoadStateFooter(footer = LoadingStateAdapter {
58 | adapter.retry()
59 | })
60 | binding.rvStory.layoutManager = LinearLayoutManager(this)
61 | }
62 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/login/LoginActivity.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.login
2 |
3 | import android.content.Intent
4 | import android.os.Bundle
5 | import android.widget.Toast
6 | import androidx.activity.viewModels
7 | import androidx.appcompat.app.AppCompatActivity
8 | import com.mirz.storyapp.Locator
9 | import com.mirz.storyapp.R
10 | import com.mirz.storyapp.databinding.ActivityLoginBinding
11 | import com.mirz.storyapp.ui.register.RegisterActivity
12 | import com.mirz.storyapp.ui.story.StoryActivity
13 | import com.mirz.storyapp.utils.ResultState
14 | import com.mirz.storyapp.utils.launchAndCollectIn
15 |
16 | class LoginActivity : AppCompatActivity() {
17 | private val binding by lazy { ActivityLoginBinding.inflate(layoutInflater) }
18 | private val viewModel by viewModels(factoryProducer = { Locator.loginViewModelFactory })
19 | override fun onCreate(savedInstanceState: Bundle?) {
20 | super.onCreate(savedInstanceState)
21 | setContentView(binding.root)
22 |
23 | viewModel.loginState.launchAndCollectIn(this) { state ->
24 | when (state.resultVerifyUser) {
25 | is ResultState.Success -> {
26 | binding.btLogin.setLoading(false)
27 | startActivity(
28 | Intent(
29 | this@LoginActivity, StoryActivity::class.java
30 | )
31 | )
32 | finish()
33 | }
34 |
35 | is ResultState.Loading -> binding.btLogin.setLoading(true)
36 | is ResultState.Error -> {
37 | binding.btLogin.setLoading(false)
38 | Toast.makeText(
39 | this@LoginActivity, state.resultVerifyUser.message, Toast.LENGTH_SHORT
40 | ).show()
41 | }
42 |
43 | else -> Unit
44 | }
45 |
46 | }
47 |
48 | binding.btLogin.setOnClickListener {
49 | if (binding.edLoginEmail.error != null && binding.edLoginPassword.error != null) {
50 | viewModel.doLogin(
51 | email = binding.edLoginEmail.text.toString(),
52 | password = binding.edLoginPassword.text.toString()
53 | )
54 | } else {
55 | Toast.makeText(this, getString(R.string.input_invalid), Toast.LENGTH_SHORT).show()
56 | }
57 | }
58 |
59 | binding.tvDonTHaveAnAccount.setOnClickListener {
60 | startActivity(
61 | Intent(
62 | this, RegisterActivity::class.java
63 | )
64 | )
65 | }
66 | }
67 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
24 |
25 |
28 |
29 |
32 |
35 |
38 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
50 |
53 |
56 |
57 |
62 |
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/adapter/StoryAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.adapter
2 |
3 | import android.app.Activity
4 | import android.content.Intent
5 | import android.view.LayoutInflater
6 | import android.view.ViewGroup
7 | import androidx.core.app.ActivityOptionsCompat
8 | import androidx.core.util.Pair
9 | import androidx.paging.PagingDataAdapter
10 | import androidx.recyclerview.widget.DiffUtil
11 | import androidx.recyclerview.widget.RecyclerView
12 | import com.bumptech.glide.Glide
13 | import com.mirz.storyapp.databinding.ItemStoryBinding
14 | import com.mirz.storyapp.domain.entity.StoryEntity
15 | import com.mirz.storyapp.ui.detail_story.StoryDetailActivity
16 |
17 | class StoryAdapter : PagingDataAdapter(DIFF_CALLBACK) {
18 |
19 |
20 | class MyViewHolder(private val binding: ItemStoryBinding) :
21 | RecyclerView.ViewHolder(binding.root) {
22 | fun bind(item: StoryEntity) {
23 | binding.tvItemName.text = item.name
24 | binding.tvItemDesc.text = item.description
25 | Glide.with(binding.root.context).load(item.photoUrl).into(binding.ivItemPhoto)
26 | binding.root.setOnClickListener {
27 | val optionsCompat: ActivityOptionsCompat =
28 | ActivityOptionsCompat.makeSceneTransitionAnimation(
29 | binding.root.context as Activity,
30 | Pair(binding.ivItemPhoto, "photo"),
31 | Pair(binding.tvItemName, "name"),
32 | Pair(binding.tvItemDesc, "description"),
33 | )
34 |
35 | binding.root.context.startActivity(
36 | Intent(
37 | binding.root.context, StoryDetailActivity::class.java
38 | ).putExtra(StoryDetailActivity.EXTRA_STORY_ID, item.id),
39 | optionsCompat.toBundle()
40 | )
41 | }
42 | }
43 | }
44 |
45 | override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
46 | val data = getItem(position)
47 | if (data != null) {
48 | holder.bind(data)
49 | }
50 | }
51 |
52 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
53 | val binding = ItemStoryBinding.inflate(LayoutInflater.from(parent.context), parent, false)
54 | return MyViewHolder(binding)
55 | }
56 |
57 | companion object {
58 | val DIFF_CALLBACK = object : DiffUtil.ItemCallback() {
59 | override fun areItemsTheSame(oldItem: StoryEntity, newItem: StoryEntity): Boolean {
60 | return oldItem == newItem
61 | }
62 |
63 | override fun areContentsTheSame(oldItem: StoryEntity, newItem: StoryEntity): Boolean {
64 | return oldItem.id == newItem.id
65 | }
66 | }
67 | }
68 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/utils/Extensions.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.utils
2 |
3 | import android.content.ContentResolver
4 | import android.content.Context
5 | import android.content.pm.PackageManager
6 | import android.graphics.Bitmap
7 | import android.graphics.BitmapFactory
8 | import android.net.Uri
9 | import android.os.Environment
10 | import androidx.core.content.ContextCompat
11 | import androidx.lifecycle.Lifecycle
12 | import androidx.lifecycle.LifecycleOwner
13 | import androidx.lifecycle.lifecycleScope
14 | import androidx.lifecycle.repeatOnLifecycle
15 | import kotlinx.coroutines.CoroutineScope
16 | import kotlinx.coroutines.flow.Flow
17 | import kotlinx.coroutines.launch
18 | import java.io.ByteArrayOutputStream
19 | import java.io.File
20 | import java.io.FileOutputStream
21 | import java.io.InputStream
22 | import java.io.OutputStream
23 | import java.text.SimpleDateFormat
24 | import java.util.Locale
25 |
26 |
27 | private const val FILENAME_FORMAT = "dd-MMM-yyyy"
28 |
29 | val timeStamp: String = SimpleDateFormat(
30 | FILENAME_FORMAT, Locale.US
31 | ).format(System.currentTimeMillis())
32 |
33 |
34 | inline fun Flow.launchAndCollectIn(
35 | owner: LifecycleOwner,
36 | minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
37 | crossinline action: suspend CoroutineScope.(T) -> Unit
38 | ) = owner.lifecycleScope.launch {
39 | owner.repeatOnLifecycle(minActiveState) {
40 | collect {
41 | action(it)
42 | }
43 | }
44 | }
45 |
46 | fun File.reduceFileImage(): File {
47 | val bitmap = BitmapFactory.decodeFile(path)
48 | var compressQuality = 100
49 | var streamLength: Int
50 | do {
51 | val bmpStream = ByteArrayOutputStream()
52 | bitmap.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream)
53 | val bmpPicByteArray = bmpStream.toByteArray()
54 | streamLength = bmpPicByteArray.size
55 | compressQuality -= 5
56 | } while (streamLength > 1000000)
57 | bitmap.compress(Bitmap.CompressFormat.JPEG, compressQuality, FileOutputStream(this))
58 | return this
59 | }
60 |
61 | fun Uri.uriToFile(context: Context): File {
62 | val contentResolver: ContentResolver = context.contentResolver
63 | val myFile = createCustomTempFile(context)
64 |
65 | val inputStream = contentResolver.openInputStream(this) as InputStream
66 | val outputStream: OutputStream = FileOutputStream(myFile)
67 | val buf = ByteArray(1024)
68 | var len: Int
69 | while (inputStream.read(buf).also { len = it } > 0) outputStream.write(buf, 0, len)
70 | outputStream.close()
71 | inputStream.close()
72 |
73 | return myFile
74 | }
75 |
76 |
77 | fun createCustomTempFile(context: Context): File {
78 | val storageDir: File? = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
79 | return File.createTempFile(timeStamp, ".jpg", storageDir)
80 | }
81 |
82 |
83 | fun Array.checkPermissionsGranted(context: Context) = this.all {
84 | ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
85 | }
86 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/maps/MapsActivity.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.maps
2 |
3 | import android.os.Bundle
4 | import android.widget.Toast
5 | import androidx.activity.viewModels
6 | import androidx.appcompat.app.AppCompatActivity
7 | import com.google.android.gms.maps.CameraUpdateFactory
8 | import com.google.android.gms.maps.GoogleMap
9 | import com.google.android.gms.maps.OnMapReadyCallback
10 | import com.google.android.gms.maps.SupportMapFragment
11 | import com.google.android.gms.maps.model.LatLng
12 | import com.google.android.gms.maps.model.MapStyleOptions
13 | import com.google.android.gms.maps.model.MarkerOptions
14 | import com.mirz.storyapp.Locator
15 | import com.mirz.storyapp.R
16 | import com.mirz.storyapp.databinding.ActivityMapsBinding
17 | import com.mirz.storyapp.utils.ResultState
18 | import com.mirz.storyapp.utils.launchAndCollectIn
19 |
20 |
21 | class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
22 |
23 | private lateinit var mMap: GoogleMap
24 | private val binding by lazy { ActivityMapsBinding.inflate(layoutInflater) }
25 | private val viewModel by viewModels(factoryProducer = { Locator.mapsViewModelFactory })
26 |
27 | override fun onCreate(savedInstanceState: Bundle?) {
28 | super.onCreate(savedInstanceState)
29 |
30 | setContentView(binding.root)
31 |
32 | // Obtain the SupportMapFragment and get notified when the map is ready to be used.
33 | val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
34 |
35 | mapFragment.getMapAsync(this@MapsActivity)
36 | viewModel.getStories()
37 |
38 | }
39 |
40 | override fun onMapReady(googleMap: GoogleMap) {
41 | mMap = googleMap
42 | mMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this@MapsActivity, R.raw.map_style))
43 | displayMarker()
44 | }
45 |
46 | override fun onResume() {
47 | super.onResume()
48 | }
49 |
50 | private fun displayMarker() {
51 | viewModel.mapsState.launchAndCollectIn(this) {
52 | when (it.resultStories) {
53 | is ResultState.Success -> {
54 | binding.progressBar.visibility = android.view.View.GONE
55 | it.resultStories.data?.forEach { story ->
56 | val position = LatLng(story.lat, story.lng)
57 | mMap.addMarker(MarkerOptions().position(position).title(story.name))
58 | mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(position, 5f))
59 | }
60 | }
61 |
62 | is ResultState.Error -> {
63 | binding.progressBar.visibility = android.view.View.GONE
64 | Toast.makeText(this@MapsActivity, it.resultStories.message, Toast.LENGTH_SHORT)
65 | .show()
66 | }
67 |
68 | is ResultState.Loading -> binding.progressBar.visibility = android.view.View.VISIBLE
69 |
70 | else -> Unit
71 | }
72 | }
73 | }
74 |
75 |
76 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/register/RegisterActivity.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.register
2 |
3 | import android.content.Intent
4 | import android.os.Bundle
5 | import android.widget.Toast
6 | import androidx.activity.viewModels
7 | import androidx.appcompat.app.AppCompatActivity
8 | import com.mirz.storyapp.Locator
9 | import com.mirz.storyapp.R
10 | import com.mirz.storyapp.databinding.ActivityRegisterBinding
11 | import com.mirz.storyapp.ui.login.LoginActivity
12 | import com.mirz.storyapp.utils.ResultState
13 | import com.mirz.storyapp.utils.launchAndCollectIn
14 |
15 | class RegisterActivity : AppCompatActivity() {
16 | private val binding by lazy { ActivityRegisterBinding.inflate(layoutInflater) }
17 | private val viewModel by viewModels(factoryProducer = { Locator.registerViewModelFactory })
18 | override fun onCreate(savedInstanceState: Bundle?) {
19 | super.onCreate(savedInstanceState)
20 | setContentView(binding.root)
21 |
22 | viewModel.registerViewState.launchAndCollectIn(this) {
23 | when (it.resultRegisterUser) {
24 | is ResultState.Success -> {
25 | binding.btRegister.setLoading(false)
26 | Toast.makeText(
27 | this@RegisterActivity,
28 | getString(R.string.register_success),
29 | Toast.LENGTH_SHORT
30 | ).show()
31 | startActivity(
32 | Intent(
33 | this@RegisterActivity, LoginActivity::class.java
34 | ).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
35 | )
36 | finish()
37 | }
38 |
39 | is ResultState.Loading -> binding.btRegister.setLoading(true)
40 | is ResultState.Error -> {
41 | binding.btRegister.setLoading(false)
42 | Toast.makeText(
43 | this@RegisterActivity, it.resultRegisterUser.message, Toast.LENGTH_SHORT
44 | ).show()
45 | }
46 |
47 | else -> Unit
48 | }
49 | }
50 | binding.btRegister.setOnClickListener {
51 | if (binding.edRegisterName.error != null && binding.edRegisterEmail.error != null && binding.edRegisterPassword.error != null) {
52 | viewModel.registerUser(
53 | name = binding.edRegisterName.text.toString(),
54 | email = binding.edRegisterEmail.text.toString(),
55 | password = binding.edRegisterPassword.text.toString()
56 | )
57 | } else {
58 | Toast.makeText(this, getString(R.string.input_invalid), Toast.LENGTH_SHORT).show()
59 | }
60 | }
61 | binding.tvAlreadyHaveAnAccount.setOnClickListener {
62 | startActivity(
63 | Intent(
64 | this, LoginActivity::class.java
65 | ).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
66 | )
67 | finish()
68 | }
69 | }
70 | }
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'org.jetbrains.kotlin.android'
4 | id 'kotlin-kapt'
5 | id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
6 | }
7 |
8 | android {
9 | namespace 'com.mirz.storyapp'
10 | compileSdk 33
11 |
12 | defaultConfig {
13 | applicationId "com.mirz.storyapp"
14 | minSdk 24
15 | targetSdk 33
16 | versionCode 1
17 | versionName "1.0"
18 | buildConfigField "String", 'BASE_URL', BASE_URL_DICODING
19 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
20 | }
21 |
22 | buildTypes {
23 | release {
24 | minifyEnabled false
25 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
26 | }
27 | }
28 | compileOptions {
29 | sourceCompatibility JavaVersion.VERSION_1_8
30 | targetCompatibility JavaVersion.VERSION_1_8
31 | }
32 | kotlinOptions {
33 | jvmTarget = '1.8'
34 | }
35 | viewBinding {
36 | enabled true
37 | }
38 | buildFeatures {
39 | viewBinding true
40 | }
41 | }
42 |
43 | dependencies {
44 | implementation(platform("org.jetbrains.kotlin:kotlin-bom:1.8.0"))
45 | implementation 'androidx.core:core-ktx:1.7.0'
46 | implementation 'androidx.appcompat:appcompat:1.6.1'
47 | implementation 'com.google.android.material:material:1.8.0'
48 | implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
49 | implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.1"
50 | implementation "androidx.activity:activity-ktx:1.7.0"
51 | implementation "androidx.recyclerview:recyclerview:1.3.0"
52 |
53 | //UI Helpers
54 | implementation 'com.github.bumptech.glide:glide:4.11.0'
55 | implementation 'com.airbnb.android:lottie:6.0.0'
56 |
57 | // Network
58 | implementation 'com.squareup.retrofit2:retrofit:2.9.0'
59 | implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
60 | implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0'
61 | // Data Store
62 | implementation "androidx.datastore:datastore-preferences:1.0.0"
63 | implementation 'com.google.android.gms:play-services-maps:18.1.0'
64 | // Paging
65 | implementation "androidx.paging:paging-runtime-ktx:3.1.1"
66 | //Room
67 | implementation 'androidx.room:room-paging:2.5.1'
68 | implementation 'androidx.room:room-ktx:2.5.1'
69 | kapt 'androidx.room:room-compiler:2.5.1'
70 | //Location
71 | implementation 'com.google.android.gms:play-services-location:18.0.0'
72 |
73 | // Test Dependencies
74 | testImplementation 'junit:junit:4.13.2'
75 | testImplementation "androidx.arch.core:core-testing:2.2.0" // InstantTaskExecutorRule
76 | testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.1" //TestDispatcher
77 | testImplementation 'org.mockito:mockito-core:4.0.0'
78 | testImplementation 'org.mockito:mockito-inline:4.0.0'
79 | androidTestImplementation 'androidx.test.ext:junit:1.1.5'
80 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
81 |
82 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/il_logo.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
12 |
13 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/data/paging/StoryRemoteMediator.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.data.paging
2 |
3 | import androidx.paging.ExperimentalPagingApi
4 | import androidx.paging.LoadType
5 | import androidx.paging.PagingState
6 | import androidx.paging.RemoteMediator
7 | import androidx.room.withTransaction
8 | import com.mirz.storyapp.data.response.StoryResponse
9 | import com.mirz.storyapp.data.source.database.RemoteKeys
10 | import com.mirz.storyapp.data.source.database.StoryDatabase
11 | import com.mirz.storyapp.data.source.remote.ApiServices
12 |
13 | @OptIn(ExperimentalPagingApi::class)
14 | class StoryRemoteMediator(
15 | private val database: StoryDatabase,
16 | private val apiService: ApiServices
17 | ) : RemoteMediator() {
18 |
19 | override suspend fun initialize(): InitializeAction {
20 | return InitializeAction.LAUNCH_INITIAL_REFRESH
21 | }
22 |
23 | override suspend fun load(
24 | loadType: LoadType,
25 | state: PagingState
26 | ): MediatorResult {
27 | val page = when (loadType) {
28 | LoadType.REFRESH -> {
29 | val remoteKeys = getRemoteKeyClosestToCurrentPosition(state)
30 | remoteKeys?.nextKey?.minus(1) ?: INITIAL_PAGE_INDEX
31 | }
32 |
33 | LoadType.PREPEND -> {
34 | val remoteKeys = getRemoteKeyForFirstItem(state)
35 | val prevKey = remoteKeys?.prevKey
36 | ?: return MediatorResult.Success(endOfPaginationReached = remoteKeys != null)
37 | prevKey
38 | }
39 |
40 | LoadType.APPEND -> {
41 | val remoteKeys = getRemoteKeyForLastItem(state)
42 | val nextKey = remoteKeys?.nextKey
43 | ?: return MediatorResult.Success(endOfPaginationReached = remoteKeys != null)
44 | nextKey
45 | }
46 | }
47 |
48 | return try {
49 | val responseData = apiService.stories(page, state.config.pageSize)
50 | val endOfPaginationReached = responseData.listStory.isEmpty()
51 | database.withTransaction {
52 | if (loadType == LoadType.REFRESH) {
53 | database.storyDao().deleteAll()
54 | database.remoteKeysDao().deleteRemoteKeys()
55 | }
56 | val prevKey = if (page == 1) null else page - 1
57 | val nextKey = if (endOfPaginationReached) null else page + 1
58 | val keys = responseData.listStory.map {
59 | RemoteKeys(id = it.id, prevKey = prevKey, nextKey = nextKey)
60 | }
61 | database.remoteKeysDao().insertAll(keys)
62 | database.storyDao().insertStories(responseData.listStory)
63 | }
64 | MediatorResult.Success(endOfPaginationReached = endOfPaginationReached)
65 | } catch (exception: Exception) {
66 | MediatorResult.Error(exception)
67 | }
68 | }
69 |
70 |
71 | private suspend fun getRemoteKeyForLastItem(state: PagingState): RemoteKeys? {
72 | return state.pages.lastOrNull { it.data.isNotEmpty() }?.data?.lastOrNull()?.let { data ->
73 | database.remoteKeysDao().getRemoteKeysId(data.id)
74 | }
75 | }
76 |
77 | private suspend fun getRemoteKeyForFirstItem(state: PagingState): RemoteKeys? {
78 | return state.pages.firstOrNull { it.data.isNotEmpty() }?.data?.firstOrNull()?.let { data ->
79 | database.remoteKeysDao().getRemoteKeysId(data.id)
80 | }
81 | }
82 |
83 | private suspend fun getRemoteKeyClosestToCurrentPosition(state: PagingState): RemoteKeys? {
84 | return state.anchorPosition?.let { position ->
85 | state.closestItemToPosition(position)?.id?.let { id ->
86 | database.remoteKeysDao().getRemoteKeysId(id)
87 | }
88 | }
89 | }
90 |
91 |
92 | private companion object {
93 | const val INITIAL_PAGE_INDEX = 1
94 | }
95 |
96 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/Locator.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp
2 |
3 | import android.app.Application
4 | import android.content.Context
5 | import androidx.datastore.preferences.preferencesDataStore
6 | import com.mirz.storyapp.data.repository.AuthRepositoryImpl
7 | import com.mirz.storyapp.data.repository.StoryRepositoryImpl
8 | import com.mirz.storyapp.data.source.database.StoryDatabase
9 | import com.mirz.storyapp.data.source.local.UserPreferenceImpl
10 | import com.mirz.storyapp.data.source.remote.RetrofitBuilder
11 | import com.mirz.storyapp.domain.usecase.AddStoryUseCase
12 | import com.mirz.storyapp.domain.usecase.GetStoriesLocationUseCase
13 | import com.mirz.storyapp.domain.usecase.GetStoriesUseCase
14 | import com.mirz.storyapp.domain.usecase.GetStoryDetailUseCase
15 | import com.mirz.storyapp.domain.usecase.GetUserUseCase
16 | import com.mirz.storyapp.domain.usecase.LoginUseCase
17 | import com.mirz.storyapp.domain.usecase.LogoutUseCase
18 | import com.mirz.storyapp.domain.usecase.RegisterUseCase
19 | import com.mirz.storyapp.ui.add_story.AddStoryViewModel
20 | import com.mirz.storyapp.ui.detail_story.StoryDetailViewModel
21 | import com.mirz.storyapp.ui.login.LoginViewModel
22 | import com.mirz.storyapp.ui.maps.MapsViewModel
23 | import com.mirz.storyapp.ui.register.RegisterViewModel
24 | import com.mirz.storyapp.ui.story.StoryViewModel
25 | import com.mirz.storyapp.ui.welcome.WelcomeViewModel
26 |
27 | object Locator {
28 | private var application: Application? = null
29 |
30 | private inline val requireApplication
31 | get() = application ?: error("Missing call: initWith(application)")
32 |
33 | fun initWith(application: Application) {
34 | this.application = application
35 | }
36 |
37 | // Data Store
38 | private val Context.dataStore by preferencesDataStore(name = "user_preferences")
39 |
40 | // ViewModel Factory
41 | val loginViewModelFactory
42 | get() = LoginViewModel.Factory(
43 | loginUseCase = loginUseCase
44 | )
45 | val registerViewModelFactory
46 | get() = RegisterViewModel.Factory(
47 | registerUseCase = registerUseCase
48 | )
49 | val welcomeViewModelFactory
50 | get() = WelcomeViewModel.Factory(
51 | getUserUseCase = getUserUseCase
52 | )
53 | val storyViewModelFactory
54 | get() = StoryViewModel.Factory(
55 | getStoriesUseCase = getStoriesUseCase,
56 | getUserUseCase = getUserUseCase,
57 | logoutUseCase = logoutUseCase
58 | )
59 | val storyDetailViewModelFactory
60 | get() = StoryDetailViewModel.Factory(
61 | getStoryDetailUseCase = getStoryDetailUseCase
62 | )
63 | val addStoryViewModelFactory
64 | get() = AddStoryViewModel.Factory(
65 | addStoryUseCase = addStoryUseCase
66 | )
67 | val mapsViewModelFactory
68 | get() = MapsViewModel.Factory(
69 | getStoriesLocationUseCase = getStoriesLocationUseCase
70 | )
71 |
72 | // UseCases Injection
73 | private val loginUseCase get() = LoginUseCase(userPreferencesRepository, authRepository)
74 | private val registerUseCase get() = RegisterUseCase(authRepository)
75 | private val getUserUseCase get() = GetUserUseCase(userPreferencesRepository)
76 | private val getStoriesUseCase get() = GetStoriesUseCase(storyRepository)
77 | private val logoutUseCase get() = LogoutUseCase(userPreferencesRepository)
78 | private val getStoryDetailUseCase get() = GetStoryDetailUseCase(storyRepository)
79 | private val addStoryUseCase get() = AddStoryUseCase(storyRepository)
80 | private val getStoriesLocationUseCase get() = GetStoriesLocationUseCase(storyRepository)
81 |
82 | // Repository Injection
83 | private val userPreferencesRepository by lazy {
84 | UserPreferenceImpl(requireApplication.dataStore)
85 | }
86 | private val authRepository by lazy {
87 | AuthRepositoryImpl(RetrofitBuilder(requireApplication.dataStore).apiService)
88 | }
89 | private val storyRepository by lazy {
90 | StoryRepositoryImpl(
91 | StoryDatabase.getDatabase(requireApplication),
92 | RetrofitBuilder(requireApplication.dataStore).apiService
93 | )
94 | }
95 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_login.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
22 |
23 |
37 |
38 |
55 |
56 |
75 |
76 |
77 |
88 |
89 |
99 |
100 |
--------------------------------------------------------------------------------
/app/src/test/java/com/mirz/storyapp/ui/story/StoryViewModelTest.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.story
2 |
3 | import androidx.arch.core.executor.testing.InstantTaskExecutorRule
4 | import androidx.lifecycle.LiveData
5 | import androidx.paging.AsyncPagingDataDiffer
6 | import androidx.paging.PagingData
7 | import androidx.paging.PagingSource
8 | import androidx.paging.PagingState
9 | import androidx.recyclerview.widget.ListUpdateCallback
10 | import com.mirz.storyapp.data.response.StoryResponse
11 | import com.mirz.storyapp.domain.entity.StoryEntity
12 | import com.mirz.storyapp.domain.mapper.map
13 | import com.mirz.storyapp.fake.FakeGetStoriesUseCase
14 | import com.mirz.storyapp.fake.FakeGetUserUseCase
15 | import com.mirz.storyapp.fake.FakeLogoutUseCase
16 | import com.mirz.storyapp.ui.adapter.StoryAdapter
17 | import com.mirz.storyapp.utils.DataDummy
18 | import com.mirz.storyapp.utils.MainDispatcherRule
19 | import kotlinx.coroutines.Dispatchers
20 | import kotlinx.coroutines.ExperimentalCoroutinesApi
21 | import kotlinx.coroutines.test.runTest
22 | import org.junit.Assert
23 | import org.junit.Rule
24 | import org.junit.Test
25 | import org.junit.runner.RunWith
26 | import org.mockito.junit.MockitoJUnitRunner
27 |
28 | @OptIn(ExperimentalCoroutinesApi::class)
29 | @RunWith(MockitoJUnitRunner::class)
30 | internal class StoryViewModelTest {
31 | @get:Rule
32 | val instantExecutorRule = InstantTaskExecutorRule()
33 |
34 | @get:Rule
35 | val mainDispatcherRules = MainDispatcherRule()
36 |
37 | private val getStoriesUseCase = FakeGetStoriesUseCase()
38 |
39 | private val getUserUseCase = FakeGetUserUseCase()
40 |
41 | private val getLogoutUseCase = FakeLogoutUseCase()
42 |
43 |
44 | @Test
45 | fun `when Get Story Should Not Null and Return Data`() = runTest {
46 | //Given
47 | val dummyStory = DataDummy.generateDummyStoryResponse()
48 | val data: PagingData = StoryPagingSource.snapshot(dummyStory)
49 | val storyViewModel = StoryViewModel(getStoriesUseCase, getUserUseCase, getLogoutUseCase)
50 | val differ = AsyncPagingDataDiffer(
51 | diffCallback = StoryAdapter.DIFF_CALLBACK,
52 | updateCallback = noopListUpdateCallback,
53 | workerDispatcher = Dispatchers.Main,
54 | )
55 |
56 |
57 | //When
58 | storyViewModel.getStories()
59 | getStoriesUseCase.fakeDelegate.emit(data.map())
60 | differ.submitData(storyViewModel.storyState.value.resultStories)
61 |
62 | //Then
63 | Assert.assertNotNull(differ.snapshot())
64 | Assert.assertEquals(dummyStory.size, differ.snapshot().size)
65 | Assert.assertEquals(dummyStory.map().first(), differ.snapshot().first())
66 | // Checking the type of both expected and actual data isn't possible in my code, because a mapping process in domain layer.
67 | // Workaround I mapping it first to from StoryResponse into StoryEntity
68 |
69 | }
70 |
71 | @Test
72 | fun `when Get Story Empty Should Return No Data`() = runTest {
73 |
74 | //Given
75 | val data: PagingData = PagingData.empty()
76 | val storyViewModel = StoryViewModel(getStoriesUseCase, getUserUseCase, getLogoutUseCase)
77 | val differ = AsyncPagingDataDiffer(
78 | diffCallback = StoryAdapter.DIFF_CALLBACK,
79 | updateCallback = noopListUpdateCallback,
80 | workerDispatcher = Dispatchers.Main,
81 | )
82 |
83 | //When
84 | storyViewModel.getStories()
85 | getStoriesUseCase.fakeDelegate.emit(data)
86 | differ.submitData(storyViewModel.storyState.value.resultStories)
87 |
88 | //Then
89 | Assert.assertEquals(0, differ.snapshot().size)
90 | }
91 |
92 | }
93 |
94 |
95 | class StoryPagingSource : PagingSource>>() {
96 | companion object {
97 | fun snapshot(items: List): PagingData {
98 | return PagingData.from(items)
99 | }
100 | }
101 |
102 | override fun getRefreshKey(state: PagingState>>): Int {
103 | return 0
104 | }
105 |
106 | override suspend fun load(params: LoadParams): LoadResult>> {
107 | return LoadResult.Page(emptyList(), 0, 1)
108 | }
109 | }
110 |
111 |
112 | val noopListUpdateCallback = object : ListUpdateCallback {
113 | override fun onInserted(position: Int, count: Int) {}
114 | override fun onRemoved(position: Int, count: Int) {}
115 | override fun onMoved(fromPosition: Int, toPosition: Int) {}
116 | override fun onChanged(position: Int, count: Int, payload: Any?) {}
117 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_story_detail.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
19 |
20 |
27 |
28 |
29 |
30 |
46 |
47 |
60 |
61 |
76 |
77 |
90 |
91 |
101 |
102 |
103 |
--------------------------------------------------------------------------------
/app/src/main/res/raw/map_style.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "elementType": "geometry",
4 | "stylers": [
5 | {
6 | "color": "#1d2c4d"
7 | }
8 | ]
9 | },
10 | {
11 | "elementType": "labels.text.fill",
12 | "stylers": [
13 | {
14 | "color": "#8ec3b9"
15 | }
16 | ]
17 | },
18 | {
19 | "elementType": "labels.text.stroke",
20 | "stylers": [
21 | {
22 | "color": "#1a3646"
23 | }
24 | ]
25 | },
26 | {
27 | "featureType": "administrative.country",
28 | "elementType": "geometry.stroke",
29 | "stylers": [
30 | {
31 | "color": "#4b6878"
32 | }
33 | ]
34 | },
35 | {
36 | "featureType": "administrative.land_parcel",
37 | "elementType": "labels.text.fill",
38 | "stylers": [
39 | {
40 | "color": "#64779e"
41 | }
42 | ]
43 | },
44 | {
45 | "featureType": "administrative.province",
46 | "elementType": "geometry.stroke",
47 | "stylers": [
48 | {
49 | "color": "#4b6878"
50 | }
51 | ]
52 | },
53 | {
54 | "featureType": "landscape.man_made",
55 | "elementType": "geometry.stroke",
56 | "stylers": [
57 | {
58 | "color": "#334e87"
59 | }
60 | ]
61 | },
62 | {
63 | "featureType": "landscape.natural",
64 | "elementType": "geometry",
65 | "stylers": [
66 | {
67 | "color": "#023e58"
68 | }
69 | ]
70 | },
71 | {
72 | "featureType": "poi",
73 | "elementType": "geometry",
74 | "stylers": [
75 | {
76 | "color": "#283d6a"
77 | }
78 | ]
79 | },
80 | {
81 | "featureType": "poi",
82 | "elementType": "labels.text.fill",
83 | "stylers": [
84 | {
85 | "color": "#6f9ba5"
86 | }
87 | ]
88 | },
89 | {
90 | "featureType": "poi",
91 | "elementType": "labels.text.stroke",
92 | "stylers": [
93 | {
94 | "color": "#1d2c4d"
95 | }
96 | ]
97 | },
98 | {
99 | "featureType": "poi.park",
100 | "elementType": "geometry.fill",
101 | "stylers": [
102 | {
103 | "color": "#023e58"
104 | }
105 | ]
106 | },
107 | {
108 | "featureType": "poi.park",
109 | "elementType": "labels.text.fill",
110 | "stylers": [
111 | {
112 | "color": "#3C7680"
113 | }
114 | ]
115 | },
116 | {
117 | "featureType": "road",
118 | "elementType": "geometry",
119 | "stylers": [
120 | {
121 | "color": "#304a7d"
122 | }
123 | ]
124 | },
125 | {
126 | "featureType": "road",
127 | "elementType": "labels.text.fill",
128 | "stylers": [
129 | {
130 | "color": "#98a5be"
131 | }
132 | ]
133 | },
134 | {
135 | "featureType": "road",
136 | "elementType": "labels.text.stroke",
137 | "stylers": [
138 | {
139 | "color": "#1d2c4d"
140 | }
141 | ]
142 | },
143 | {
144 | "featureType": "road.highway",
145 | "elementType": "geometry",
146 | "stylers": [
147 | {
148 | "color": "#2c6675"
149 | }
150 | ]
151 | },
152 | {
153 | "featureType": "road.highway",
154 | "elementType": "geometry.stroke",
155 | "stylers": [
156 | {
157 | "color": "#255763"
158 | }
159 | ]
160 | },
161 | {
162 | "featureType": "road.highway",
163 | "elementType": "labels.text.fill",
164 | "stylers": [
165 | {
166 | "color": "#b0d5ce"
167 | }
168 | ]
169 | },
170 | {
171 | "featureType": "road.highway",
172 | "elementType": "labels.text.stroke",
173 | "stylers": [
174 | {
175 | "color": "#023e58"
176 | }
177 | ]
178 | },
179 | {
180 | "featureType": "transit",
181 | "elementType": "labels.text.fill",
182 | "stylers": [
183 | {
184 | "color": "#98a5be"
185 | }
186 | ]
187 | },
188 | {
189 | "featureType": "transit",
190 | "elementType": "labels.text.stroke",
191 | "stylers": [
192 | {
193 | "color": "#1d2c4d"
194 | }
195 | ]
196 | },
197 | {
198 | "featureType": "transit.line",
199 | "elementType": "geometry.fill",
200 | "stylers": [
201 | {
202 | "color": "#283d6a"
203 | }
204 | ]
205 | },
206 | {
207 | "featureType": "transit.station",
208 | "elementType": "geometry",
209 | "stylers": [
210 | {
211 | "color": "#3a4762"
212 | }
213 | ]
214 | },
215 | {
216 | "featureType": "water",
217 | "elementType": "geometry",
218 | "stylers": [
219 | {
220 | "color": "#0e1626"
221 | }
222 | ]
223 | },
224 | {
225 | "featureType": "water",
226 | "elementType": "labels.text.fill",
227 | "stylers": [
228 | {
229 | "color": "#4e6d70"
230 | }
231 | ]
232 | }
233 | ]
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_add_story.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
19 |
20 |
28 |
29 |
30 |
41 |
42 |
53 |
54 |
66 |
67 |
72 |
73 |
74 |
75 |
86 |
87 |
93 |
94 |
108 |
109 |
118 |
119 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_register.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
22 |
23 |
37 |
38 |
55 |
56 |
73 |
74 |
93 |
94 |
106 |
107 |
117 |
--------------------------------------------------------------------------------
/app/src/main/res/raw/lottie_loader.json:
--------------------------------------------------------------------------------
1 | {"v":"4.8.0","meta":{"g":"LottieFiles AE ","a":"","k":"","d":"","tc":""},"fr":60,"ip":0,"op":323,"w":100,"h":100,"nm":"Progress indicator - Indeterminate - Circular","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"4","parent":5,"sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":243,"s":[787.1]},{"t":323,"s":[804.2]}],"ix":10},"p":{"a":0,"k":[0,0,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"d":1,"ty":"el","s":{"a":0,"k":[70,70],"ix":2},"p":{"a":0,"k":[0,0],"ix":3},"nm":"Ellipse Path 1","mn":"ADBE Vector Shape - Ellipse","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":8,"ix":5},"lc":1,"lj":2,"bm":0,"nm":"Stroke 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Ellipse 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.2],"y":[1]},"o":{"x":[0.4],"y":[0]},"t":283,"s":[0]},{"t":323,"s":[69.5]}],"ix":1},"e":{"a":1,"k":[{"i":{"x":[0.2],"y":[1]},"o":{"x":[0.4],"y":[0]},"t":243,"s":[5.5]},{"t":283,"s":[75]}],"ix":2},"o":{"a":0,"k":1,"ix":3},"m":1,"ix":2,"nm":"Trim Paths 1","mn":"ADBE Vector Filter - Trim","hd":false}],"ip":243,"op":324,"st":243,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"3","parent":5,"sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":162,"s":[519]},{"t":242,"s":[536]}],"ix":10},"p":{"a":0,"k":[0,0,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"d":1,"ty":"el","s":{"a":0,"k":[70,70],"ix":2},"p":{"a":0,"k":[0,0],"ix":3},"nm":"Ellipse Path 1","mn":"ADBE Vector Shape - Ellipse","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":8,"ix":5},"lc":1,"lj":2,"bm":0,"nm":"Stroke 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Ellipse 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.2],"y":[1]},"o":{"x":[0.4],"y":[0]},"t":202,"s":[0]},{"t":242,"s":[69.5]}],"ix":1},"e":{"a":1,"k":[{"i":{"x":[0.2],"y":[1]},"o":{"x":[0.4],"y":[0]},"t":162,"s":[5.5]},{"t":202,"s":[75]}],"ix":2},"o":{"a":0,"k":1,"ix":3},"m":1,"ix":2,"nm":"Trim Paths 1","mn":"ADBE Vector Filter - Trim","hd":false}],"ip":162,"op":243,"st":162,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"2","parent":5,"sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":81,"s":[249]},{"t":162,"s":[268]}],"ix":10},"p":{"a":0,"k":[0,0,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"d":1,"ty":"el","s":{"a":0,"k":[70,70],"ix":2},"p":{"a":0,"k":[0,0],"ix":3},"nm":"Ellipse Path 1","mn":"ADBE Vector Shape - Ellipse","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":8,"ix":5},"lc":1,"lj":2,"bm":0,"nm":"Stroke 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Ellipse 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.2],"y":[1]},"o":{"x":[0.4],"y":[0]},"t":121,"s":[0]},{"t":161,"s":[69.5]}],"ix":1},"e":{"a":1,"k":[{"i":{"x":[0.2],"y":[1]},"o":{"x":[0.4],"y":[0]},"t":81,"s":[5.5]},{"t":121,"s":[75]}],"ix":2},"o":{"a":0,"k":1,"ix":3},"m":1,"ix":2,"nm":"Trim Paths 1","mn":"ADBE Vector Filter - Trim","hd":false}],"ip":81,"op":162,"st":81,"bm":0},{"ddd":0,"ind":4,"ty":4,"nm":"1","parent":5,"sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":0,"s":[-26]},{"t":81,"s":[0]}],"ix":10},"p":{"a":0,"k":[0,0,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"d":1,"ty":"el","s":{"a":0,"k":[70,70],"ix":2},"p":{"a":0,"k":[0,0],"ix":3},"nm":"Ellipse Path 1","mn":"ADBE Vector Shape - Ellipse","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":8,"ix":5},"lc":1,"lj":2,"bm":0,"nm":"Stroke 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Ellipse 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.2],"y":[1]},"o":{"x":[0.4],"y":[0]},"t":40,"s":[0]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":80,"s":[69]},{"t":81,"s":[69]}],"ix":1},"e":{"a":1,"k":[{"i":{"x":[0.2],"y":[1]},"o":{"x":[0.4],"y":[0]},"t":0,"s":[5.5]},{"t":40,"s":[75]}],"ix":2},"o":{"a":0,"k":1,"ix":3},"m":1,"ix":2,"nm":"Trim Paths 1","mn":"ADBE Vector Filter - Trim","hd":false}],"ip":0,"op":81,"st":0,"bm":0},{"ddd":0,"ind":5,"ty":4,"nm":"Rotator","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":0,"s":[0]},{"t":323,"s":[1444]}],"ix":10},"p":{"a":0,"k":[50,50,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[],"ip":0,"op":324,"st":0,"bm":0}],"markers":[]}
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_story.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
22 |
23 |
35 |
49 |
50 |
64 |
65 |
79 |
80 |
81 |
94 |
95 |
107 |
108 |
122 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mirz/storyapp/ui/add_story/AddStoryActivity.kt:
--------------------------------------------------------------------------------
1 | package com.mirz.storyapp.ui.add_story
2 |
3 | import android.Manifest
4 | import android.annotation.SuppressLint
5 | import android.content.Intent
6 | import android.graphics.BitmapFactory
7 | import android.location.Location
8 | import android.net.Uri
9 | import android.os.Bundle
10 | import android.provider.MediaStore
11 | import android.widget.Toast
12 | import androidx.activity.result.contract.ActivityResultContracts
13 | import androidx.activity.viewModels
14 | import androidx.appcompat.app.AppCompatActivity
15 | import androidx.core.app.ActivityCompat
16 | import androidx.core.content.FileProvider
17 | import com.google.android.gms.location.FusedLocationProviderClient
18 | import com.google.android.gms.location.LocationServices
19 | import com.google.android.gms.maps.model.LatLng
20 | import com.mirz.storyapp.Locator
21 | import com.mirz.storyapp.R
22 | import com.mirz.storyapp.databinding.ActivityAddStoryBinding
23 | import com.mirz.storyapp.utils.*
24 | import java.io.File
25 |
26 | class AddStoryActivity : AppCompatActivity() {
27 | private val binding by lazy { ActivityAddStoryBinding.inflate(layoutInflater) }
28 | private val viewModel by viewModels(factoryProducer = { Locator.addStoryViewModelFactory })
29 | private lateinit var fusedLocationClient: FusedLocationProviderClient
30 | private var latLng: LatLng? = null
31 | private var getFile: File? = null
32 | private lateinit var currentPhotoPath: String
33 |
34 |
35 | override fun onCreate(savedInstanceState: Bundle?) {
36 | super.onCreate(savedInstanceState)
37 | setContentView(binding.root)
38 |
39 | if (!REQUIRED_CAMERA_PERMISSIONS.checkPermissionsGranted(baseContext)) {
40 | ActivityCompat.requestPermissions(
41 | this, REQUIRED_CAMERA_PERMISSIONS, REQUEST_CODE_CAMERA_PERMISSION
42 | )
43 | }
44 | fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
45 |
46 |
47 | binding.btGallery.setOnClickListener { startGallery() }
48 | binding.switchLocation.setOnCheckedChangeListener { _, isChecked ->
49 | if (isChecked) {
50 | getMyLastLocation()
51 | }
52 | }
53 | binding.btCamera.setOnClickListener {
54 | startTakePhoto()
55 | }
56 | binding.btAddStory.setOnClickListener {
57 | if (getFile != null) {
58 | getFile?.let {
59 | viewModel.addStory(
60 | it.reduceFileImage(), binding.edAddDescription.text.toString(),
61 | latLng
62 | )
63 | }
64 | } else {
65 | Toast.makeText(this, getString(R.string.please_choose_image), Toast.LENGTH_SHORT)
66 | .show()
67 | }
68 | }
69 |
70 | viewModel.addStoryState.launchAndCollectIn(this@AddStoryActivity) { state ->
71 | when (state.resultAddStory) {
72 | is ResultState.Success -> {
73 | binding.btAddStory.setLoading(false)
74 | Toast.makeText(
75 | this@AddStoryActivity,
76 | getString(R.string.add_story_success),
77 | Toast.LENGTH_SHORT
78 | ).show()
79 | finish()
80 | }
81 |
82 | is ResultState.Loading -> binding.btAddStory.setLoading(true)
83 | is ResultState.Error -> {
84 | binding.btAddStory.setLoading(false)
85 | Toast.makeText(
86 | this@AddStoryActivity, state.resultAddStory.message, Toast.LENGTH_SHORT
87 | ).show()
88 | }
89 |
90 | else -> Unit
91 | }
92 | }
93 | }
94 |
95 | @SuppressLint("MissingPermission")
96 | private fun getMyLastLocation() {
97 | if (REQUIRED_LOCATION_PERMISSIONS.checkPermissionsGranted(baseContext)) {
98 | fusedLocationClient.lastLocation.addOnSuccessListener { location: Location? ->
99 | if (location != null) {
100 | latLng = LatLng(location.latitude, location.longitude)
101 | } else {
102 | binding.switchLocation.isEnabled = false
103 | Toast.makeText(
104 | this@AddStoryActivity,
105 | getString(R.string.location_not_found),
106 | Toast.LENGTH_SHORT
107 | ).show()
108 | }
109 | }
110 | } else {
111 | requestPermissionLauncher.launch(
112 | arrayOf(
113 | Manifest.permission.ACCESS_FINE_LOCATION,
114 | Manifest.permission.ACCESS_COARSE_LOCATION
115 | )
116 | )
117 | }
118 | }
119 |
120 |
121 | @SuppressLint("QueryPermissionsNeeded")
122 | private fun startTakePhoto() {
123 | val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
124 | intent.resolveActivity(packageManager)
125 |
126 | createCustomTempFile(application).also {
127 | val photoURI: Uri = FileProvider.getUriForFile(
128 | this@AddStoryActivity, packageName, it
129 | )
130 | currentPhotoPath = it.absolutePath
131 | intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
132 | launcherIntentCamera.launch(intent)
133 | }
134 | }
135 |
136 | private fun startGallery() {
137 | val intent = Intent()
138 | intent.action = Intent.ACTION_GET_CONTENT
139 | intent.type = "image/*"
140 | val chooser = Intent.createChooser(intent, "Choose a Picture")
141 | launcherIntentGallery.launch(chooser)
142 | }
143 |
144 |
145 | private val launcherIntentCamera = registerForActivityResult(
146 | ActivityResultContracts.StartActivityForResult()
147 | ) {
148 | if (it.resultCode == RESULT_OK) {
149 | val myFile = File(currentPhotoPath)
150 | getFile = myFile
151 | val result = BitmapFactory.decodeFile(myFile.path)
152 | binding.ivPreviewPhoto.setImageBitmap(result)
153 | }
154 | }
155 |
156 | private val launcherIntentGallery = registerForActivityResult(
157 | ActivityResultContracts.StartActivityForResult()
158 | ) { result ->
159 | if (result.resultCode == RESULT_OK) {
160 | val selectedImg: Uri = result.data?.data as Uri
161 | val myFile = selectedImg.uriToFile(this@AddStoryActivity)
162 | getFile = myFile
163 | binding.ivPreviewPhoto.setImageURI(selectedImg)
164 | }
165 | }
166 |
167 | private val requestPermissionLauncher = registerForActivityResult(
168 | ActivityResultContracts.RequestMultiplePermissions()
169 | ) { permissions ->
170 | when {
171 | permissions[Manifest.permission.ACCESS_FINE_LOCATION] ?: false -> {
172 | // Precise location access granted.
173 | getMyLastLocation()
174 | }
175 |
176 | permissions[Manifest.permission.ACCESS_COARSE_LOCATION] ?: false -> {
177 | // Only approximate location access granted.
178 | getMyLastLocation()
179 | }
180 |
181 | else -> {
182 | // No location access granted.
183 | }
184 | }
185 | }
186 |
187 | override fun onRequestPermissionsResult(
188 | requestCode: Int, permissions: Array, grantResults: IntArray
189 | ) {
190 | super.onRequestPermissionsResult(requestCode, permissions, grantResults)
191 | if (requestCode == REQUEST_CODE_CAMERA_PERMISSION) {
192 | if (!REQUIRED_CAMERA_PERMISSIONS.checkPermissionsGranted(baseContext)) {
193 | Toast.makeText(
194 | this, getString(R.string.cant_get_camera_permission), Toast.LENGTH_SHORT
195 | ).show()
196 | finish()
197 | }
198 | } else if (requestCode == REQUEST_CODE_LOCATION_PERMISSIONS) {
199 | if (!REQUIRED_LOCATION_PERMISSIONS.checkPermissionsGranted(baseContext)) {
200 | Toast.makeText(
201 | this, getString(R.string.cant_get_location_permission), Toast.LENGTH_SHORT
202 | ).show()
203 | finish()
204 | }
205 | }
206 |
207 |
208 | }
209 |
210 | companion object {
211 | private val REQUIRED_CAMERA_PERMISSIONS = arrayOf(
212 | Manifest.permission.CAMERA
213 | )
214 | private val REQUIRED_LOCATION_PERMISSIONS = arrayOf(
215 | Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
216 | )
217 |
218 | private const val REQUEST_CODE_CAMERA_PERMISSION = 10
219 | private const val REQUEST_CODE_LOCATION_PERMISSIONS = 11
220 | }
221 | }
--------------------------------------------------------------------------------