content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.yusufarisoy.n11case.data.entity import android.os.Parcelable import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.parcelize.Parcelize @Parcelize @Entity(tableName = "users") data class LocalUser( @ColumnInfo(name = "login") val login: String, @PrimaryKey @ColumnInfo(name = "id") val id: Int, @ColumnInfo(name = "avatar") val avatar: String, @ColumnInfo(name = "favorite") val favorite: Boolean, @ColumnInfo(name = "name") val name: String? = null, @ColumnInfo(name = "followers") val followers: Int? = null, @ColumnInfo(name = "following") val following: Int? = null ) : Parcelable
n11-case/app/src/main/java/com/yusufarisoy/n11case/data/entity/LocalUser.kt
1136493355
package com.yusufarisoy.n11case.data.entity import com.google.gson.annotations.SerializedName data class UserDetailResponse( @SerializedName("login") val login: String, @SerializedName("id") val id: Int, @SerializedName("node_id") val nodeId: String, @SerializedName("avatar_url") val avatarUrl: String, @SerializedName("gravatar_id") val gravatarId: String, @SerializedName("url") val url: String, @SerializedName("html_url") val htmlUrl: String, @SerializedName("followers_url") val followersUrl: String, @SerializedName("following_url") val followingUrl: String, @SerializedName("gists_url") val gistsUrl: String, @SerializedName("starred_url") val starredUrl: String, @SerializedName("subscriptions_url") val subscriptionsUrl: String, @SerializedName("organizations_url") val organizationsUrl: String, @SerializedName("repos_url") val reposUrl: String, @SerializedName("events_url") val eventsUrl: String, @SerializedName("received_events_url") val receivedEventsUrl: String, @SerializedName("type") val type: String, @SerializedName("site_admin") val siteAdmin: Boolean, @SerializedName("name") val name: String, @SerializedName("company") val company: String, @SerializedName("blog") val blog: String, @SerializedName("location") val location: String, @SerializedName("email") val email: Any?, @SerializedName("hireable") val hireable: Any?, @SerializedName("bio") val bio: String, @SerializedName("twitter_username") val twitterUsername: Any?, @SerializedName("public_repos") val publicRepos: Int, @SerializedName("public_gists") val publicGists: Int, @SerializedName("followers") val followers: Int, @SerializedName("following") val following: Int, @SerializedName("created_at") val createdAt: String, @SerializedName("updated_at") val updatedAt: String )
n11-case/app/src/main/java/com/yusufarisoy/n11case/data/entity/UserDetailResponse.kt
766721064
package com.yusufarisoy.n11case.data.entity import com.google.gson.annotations.SerializedName data class SearchResponse( @SerializedName("total_count") val totalCount: Int, @SerializedName("incomplete_results") val incompleteResults: Boolean, @SerializedName("items") val users: List<UserResponse> )
n11-case/app/src/main/java/com/yusufarisoy/n11case/data/entity/SearchResponse.kt
1804098854
package com.yusufarisoy.n11case.data.entity import com.google.gson.annotations.SerializedName data class UserResponse( @SerializedName("login") val login: String, @SerializedName("id") val id: Int, @SerializedName("node_id") val nodeId: String, @SerializedName("avatar_url") val avatarUrl: String, @SerializedName("gravatar_id") val gravatarId: String, @SerializedName("url") val url: String, @SerializedName("html_url") val htmlUrl: String, @SerializedName("followers_url") val followersUrl: String, @SerializedName("following_url") val followingUrl: String, @SerializedName("gists_url") val gistsUrl: String, @SerializedName("starred_url") val starredUrl: String, @SerializedName("subscriptions_url") val subscriptionsUrl: String, @SerializedName("organizations_url") val organizationsUrl: String, @SerializedName("repos_url") val reposUrl: String, @SerializedName("events_url") val eventsUrl: String, @SerializedName("received_events_url") val receivedEventsUrl: String, @SerializedName("type") val type: String, @SerializedName("site_admin") val siteAdmin: Boolean, @SerializedName("score") val score: Double? = null )
n11-case/app/src/main/java/com/yusufarisoy/n11case/data/entity/UserResponse.kt
738964534
package com.yusufarisoy.n11case.data.local import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update import com.yusufarisoy.n11case.data.entity.LocalUser @Dao interface UsersDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(users: List<LocalUser>) @Query("SELECT * FROM users") suspend fun getUsers(): List<LocalUser> @Query("SELECT * FROM users WHERE id = :id") suspend fun getUserById(id: Int): LocalUser @Update suspend fun update(user: LocalUser) @Delete suspend fun delete(user: LocalUser) @Query("DELETE FROM users") suspend fun clear() }
n11-case/app/src/main/java/com/yusufarisoy/n11case/data/local/UsersDao.kt
2127539221
package com.yusufarisoy.n11case.data.local import androidx.room.Database import androidx.room.RoomDatabase import com.yusufarisoy.n11case.data.entity.LocalUser @Database(entities = [LocalUser::class], version = 1) abstract class UsersDatabase : RoomDatabase() { abstract fun usersDao(): UsersDao }
n11-case/app/src/main/java/com/yusufarisoy/n11case/data/local/UsersDatabase.kt
1321368293
package com.yusufarisoy.n11case.data.api import com.yusufarisoy.n11case.data.entity.SearchResponse import com.yusufarisoy.n11case.data.entity.UserDetailResponse import com.yusufarisoy.n11case.data.entity.UserResponse import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface GithubApi { @GET(Endpoints.USERS) suspend fun getUsers( @Query(Queries.PER_PAGE) perPage: Int ): Response<List<UserResponse>> @GET(Endpoints.SEARCH) suspend fun searchUsers( @Query(Queries.QUERY) query: String ): Response<SearchResponse> @GET(Endpoints.USER_DETAIL) suspend fun getUserDetail( @Path(Paths.USERNAME) username: String ): Response<UserDetailResponse> companion object { private object Endpoints { const val USERS = "users" const val SEARCH = "search/users" const val USER_DETAIL = "users/{${Paths.USERNAME}}" } private object Queries { const val QUERY = "q" const val PER_PAGE = "per_page" } private object Paths { const val USERNAME = "username" } } }
n11-case/app/src/main/java/com/yusufarisoy/n11case/data/api/GithubApi.kt
1701703783
package com.yusufarisoy.n11case.domain.mapper import com.yusufarisoy.n11case.core.Mapper import com.yusufarisoy.n11case.data.entity.UserResponse import com.yusufarisoy.n11case.domain.model.UserUiModel import javax.inject.Inject class UserResponseToUserUiModelMapper @Inject constructor() : Mapper<List<UserResponse>, List<UserUiModel>> { override fun map(input: List<UserResponse>): List<UserUiModel> { return input.map { response -> UserUiModel( login = response.login, id = response.id, avatar = response.avatarUrl, favorite = false, score = response.score ) } } }
n11-case/app/src/main/java/com/yusufarisoy/n11case/domain/mapper/UserResponseToUserUiModelMapper.kt
4215355496
package com.yusufarisoy.n11case.domain.mapper import com.yusufarisoy.n11case.core.Mapper import com.yusufarisoy.n11case.data.entity.SearchResponse import com.yusufarisoy.n11case.domain.model.SearchUiModel import javax.inject.Inject class SearchResponseToSearchUiModelMapper @Inject constructor( private val userResponseToUserUiModelMapper: UserResponseToUserUiModelMapper ) : Mapper<SearchResponse, SearchUiModel> { override fun map(input: SearchResponse): SearchUiModel { return SearchUiModel( totalCount = input.totalCount, users = userResponseToUserUiModelMapper.map(input.users) ) } }
n11-case/app/src/main/java/com/yusufarisoy/n11case/domain/mapper/SearchResponseToSearchUiModelMapper.kt
3147713775
package com.yusufarisoy.n11case.domain.mapper import com.yusufarisoy.n11case.core.Mapper import com.yusufarisoy.n11case.data.entity.LocalUser import com.yusufarisoy.n11case.domain.model.UserUiModel import javax.inject.Inject class UserUiModelToLocalUserMapper @Inject constructor() : Mapper<UserUiModel, LocalUser> { override fun map(input: UserUiModel): LocalUser { return with(input) { LocalUser(login, id, avatar, favorite) } } }
n11-case/app/src/main/java/com/yusufarisoy/n11case/domain/mapper/UserUiModelToLocalUserMapper.kt
3654224782
package com.yusufarisoy.n11case.domain.mapper import com.yusufarisoy.n11case.core.Mapper import com.yusufarisoy.n11case.data.entity.LocalUser import com.yusufarisoy.n11case.domain.model.UserUiModel import javax.inject.Inject class LocalUserToUserUiModelMapper @Inject constructor() : Mapper<LocalUser, UserUiModel> { override fun map(input: LocalUser): UserUiModel { return UserUiModel( login = input.login, id = input.id, avatar = input.avatar, favorite = input.favorite, name = input.name, followers = input.followers, following = input.following ) } }
n11-case/app/src/main/java/com/yusufarisoy/n11case/domain/mapper/LocalUserToUserUiModelMapper.kt
3334338125
package com.yusufarisoy.n11case.domain.mapper import com.yusufarisoy.n11case.core.Mapper import com.yusufarisoy.n11case.data.entity.UserDetailResponse import com.yusufarisoy.n11case.domain.model.UserUiModel import javax.inject.Inject class UserDetailResponseToUserUiModelMapper @Inject constructor() : Mapper<UserDetailResponse, UserUiModel> { override fun map(input: UserDetailResponse): UserUiModel { return with(input) { UserUiModel( login = login, id = id, avatar = avatarUrl, name = name, followers = followers, following = following, favorite = false ) } } }
n11-case/app/src/main/java/com/yusufarisoy/n11case/domain/mapper/UserDetailResponseToUserUiModelMapper.kt
1958325749
package com.yusufarisoy.n11case.domain.model data class UserUiModel( val login: String, val id: Int, val avatar: String, val favorite: Boolean, val score: Double? = null, val name: String? = null, val followers: Int? = null, val following: Int? = null )
n11-case/app/src/main/java/com/yusufarisoy/n11case/domain/model/UserUiModel.kt
1487803200
package com.yusufarisoy.n11case.domain.model data class SearchUiModel( val totalCount: Int = -1, val users: List<UserUiModel> = emptyList() )
n11-case/app/src/main/java/com/yusufarisoy/n11case/domain/model/SearchUiModel.kt
1707236702
object Versions { const val hilt = "2.50" const val room = "2.6.1" const val retrofit = "2.9.0" const val lifecycle = "2.4.1" const val coroutines = "1.5.2" const val navigationComponent = "2.7.6" } object Libs { // Ktx const val coreKtx = "androidx.core:core-ktx:1.12.0" const val fragment = "androidx.fragment:fragment-ktx:1.4.1" // AppCompat const val appCompat = "androidx.appcompat:appcompat:1.6.1" // Material const val material = "com.google.android.material:material:1.11.0" // ConstraintLayout const val constraintLayout = "androidx.constraintlayout:constraintlayout:2.1.4" // Gson const val gson = "com.google.code.gson:gson:2.8.7" // Lifecycle const val lifecycleRunTime = "androidx.lifecycle:lifecycle-runtime-ktx:2.5.0-alpha02" const val lifecycleCommon = "androidx.lifecycle:lifecycle-common-java8:${Versions.lifecycle}" const val lifecycleViewModel = "androidx.lifecycle:lifecycle-viewmodel-ktx:${Versions.lifecycle}" // Coroutines const val coroutinesCore = "org.jetbrains.kotlinx:kotlinx-coroutines-core:${Versions.coroutines}" const val coroutinesAndroid = "org.jetbrains.kotlinx:kotlinx-coroutines-android:${Versions.coroutines}" // Retrofit const val retrofit = "com.squareup.retrofit2:retrofit:${Versions.retrofit}" const val retrofitConverterGson = "com.squareup.retrofit2:converter-gson:${Versions.retrofit}" // Hilt const val hiltAndroid = "com.google.dagger:hilt-android:${Versions.hilt}" const val hiltAndroidCompiler = "com.google.dagger:hilt-android-compiler:${Versions.hilt}" // NavigationComponent const val navigationFragment = "androidx.navigation:navigation-fragment-ktx:${Versions.navigationComponent}" const val navigationUi = "androidx.navigation:navigation-ui-ktx:${Versions.navigationComponent}" // Room const val roomRuntime = "androidx.room:room-runtime:${Versions.room}" const val roomCompiler = "androidx.room:room-compiler:${Versions.room}" const val roomKtx = "androidx.room:room-ktx:${Versions.room}" // Glide const val glide = "com.github.bumptech.glide:glide:4.16.0" // Test const val junit = "junit:junit:4.13.2" const val extJunit = "androidx.test.ext:junit:1.1.5" const val espressoCore = "androidx.test.espresso:espresso-core:3.5.1" }
n11-case/buildSrc/src/main/java/Dependencies.kt
1702982965
package daniel.pena.garcia.grupo_jima_repartidores_app import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("daniel.pena.garcia.grupo_jima_repartidores_app", appContext.packageName) } }
grupo-jima-repartidores-app/app/src/androidTest/java/daniel/pena/garcia/grupo_jima_repartidores_app/ExampleInstrumentedTest.kt
826902138
package daniel.pena.garcia.grupo_jima_repartidores_app import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
grupo-jima-repartidores-app/app/src/test/java/daniel/pena/garcia/grupo_jima_repartidores_app/ExampleUnitTest.kt
3078344276
package daniel.pena.garcia.grupo_jima_repartidores_app.ui.home import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class HomeViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is home Fragment" } val text: LiveData<String> = _text }
grupo-jima-repartidores-app/app/src/main/java/daniel/pena/garcia/grupo_jima_repartidores_app/ui/home/HomeViewModel.kt
4168874578
package daniel.pena.garcia.grupo_jima_repartidores_app.ui.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import daniel.pena.garcia.grupo_jima_repartidores_app.databinding.FragmentHomeBinding class HomeFragment : Fragment() { private var _binding: FragmentHomeBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java) _binding = FragmentHomeBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textHome homeViewModel.text.observe(viewLifecycleOwner) { textView.text = it } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
grupo-jima-repartidores-app/app/src/main/java/daniel/pena/garcia/grupo_jima_repartidores_app/ui/home/HomeFragment.kt
162287024
package daniel.pena.garcia.grupo_jima_repartidores_app.ui.signUp import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase import daniel.pena.garcia.grupo_jima_repartidores_app.R class SignUp : AppCompatActivity() { lateinit var auth: FirebaseAuth; lateinit var btn_sign_up: Button; override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_sign_up) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } this.auth = Firebase.auth; this.btn_sign_up = findViewById(R.id.btn_first_sign_up); this.btn_sign_up.setOnClickListener { signUp(); } } private fun signUp(){ val etEmail = findViewById<EditText>(R.id.et_signup_email); val etPassword = findViewById<EditText>(R.id.et_signup_password); val email = etEmail.text.toString(); val password = etPassword.text.toString(); if(email.isNotEmpty() && password.isNotEmpty()){ auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this) { task -> if(task.isSuccessful){ Log.d("Successful", "createUserWithEmail:success") print(task.result.user); }else{ // If sign in fails, display a message to the user. Log.w("Error", "createUserWithEmail:failure", task.exception) Toast.makeText( baseContext, "Authentication failed.", Toast.LENGTH_SHORT, ).show() } } } else { Toast.makeText( baseContext, "Ningún campo debe estar vacío", Toast.LENGTH_SHORT).show(); } } }
grupo-jima-repartidores-app/app/src/main/java/daniel/pena/garcia/grupo_jima_repartidores_app/ui/signUp/SignUp.kt
782323968
package daniel.pena.garcia.grupo_jima_repartidores_app.ui.dashboard import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import daniel.pena.garcia.grupo_jima_repartidores_app.databinding.FragmentDashboardBinding class DashboardFragment : Fragment() { private var _binding: FragmentDashboardBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val dashboardViewModel = ViewModelProvider(this).get(DashboardViewModel::class.java) _binding = FragmentDashboardBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textDashboard dashboardViewModel.text.observe(viewLifecycleOwner) { textView.text = it } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
grupo-jima-repartidores-app/app/src/main/java/daniel/pena/garcia/grupo_jima_repartidores_app/ui/dashboard/DashboardFragment.kt
3451706478
package daniel.pena.garcia.grupo_jima_repartidores_app.ui.dashboard import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class DashboardViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is dashboard Fragment" } val text: LiveData<String> = _text }
grupo-jima-repartidores-app/app/src/main/java/daniel/pena/garcia/grupo_jima_repartidores_app/ui/dashboard/DashboardViewModel.kt
2376800553
package daniel.pena.garcia.grupo_jima_repartidores_app.ui.notifications import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class NotificationsViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is notifications Fragment" } val text: LiveData<String> = _text }
grupo-jima-repartidores-app/app/src/main/java/daniel/pena/garcia/grupo_jima_repartidores_app/ui/notifications/NotificationsViewModel.kt
1249810830
package daniel.pena.garcia.grupo_jima_repartidores_app.ui.notifications import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import daniel.pena.garcia.grupo_jima_repartidores_app.databinding.FragmentNotificationsBinding class NotificationsFragment : Fragment() { private var _binding: FragmentNotificationsBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val notificationsViewModel = ViewModelProvider(this).get(NotificationsViewModel::class.java) _binding = FragmentNotificationsBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textNotifications notificationsViewModel.text.observe(viewLifecycleOwner) { textView.text = it } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
grupo-jima-repartidores-app/app/src/main/java/daniel/pena/garcia/grupo_jima_repartidores_app/ui/notifications/NotificationsFragment.kt
288993451
package daniel.pena.garcia.grupo_jima_repartidores_app.ui.login import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase import daniel.pena.garcia.grupo_jima_repartidores_app.MainActivity import daniel.pena.garcia.grupo_jima_repartidores_app.R import daniel.pena.garcia.grupo_jima_repartidores_app.ui.signUp.SignUp class Login : AppCompatActivity() { lateinit var btn_sign_in: Button; lateinit var btn_sign_up: Button; lateinit var auth: FirebaseAuth; override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_login) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } btn_sign_in = findViewById(R.id.btn_sign_in); btn_sign_up = findViewById(R.id.btn_sign_up); auth = Firebase.auth; btn_sign_in.setOnClickListener{ signIn(); } btn_sign_up.setOnClickListener { var intent = Intent(this, SignUp::class.java); startActivity(intent); } } private fun signIn(){ val etEmail = findViewById<EditText>(R.id.et_email); val etPassword = findViewById<EditText>(R.id.et_password); val email = etEmail.text.toString(); val password = etPassword.text.toString(); if(email.isNotEmpty() && password.isNotEmpty()){ auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d("Successful", "signInWithEmail:success") print(task.result.user); Toast.makeText( baseContext, auth.currentUser?.uid.toString(), Toast.LENGTH_SHORT, ).show() var intent = Intent(this, MainActivity::class.java); startActivity(intent); } else { // If sign in fails, display a message to the user. Log.w("Error", "signInWithEmail:failure", task.exception) Toast.makeText( baseContext, "Authentication failed.", Toast.LENGTH_SHORT, ).show() } } } else { Toast.makeText( baseContext, "Ningún campo debe estar vacío", Toast.LENGTH_SHORT).show(); } } }
grupo-jima-repartidores-app/app/src/main/java/daniel/pena/garcia/grupo_jima_repartidores_app/ui/login/Login.kt
437515973
package daniel.pena.garcia.grupo_jima_repartidores_app import android.os.Bundle import com.google.android.material.bottomnavigation.BottomNavigationView import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import daniel.pena.garcia.grupo_jima_repartidores_app.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val navView: BottomNavigationView = binding.navView val navController = findNavController(R.id.nav_host_fragment_activity_main) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. val appBarConfiguration = AppBarConfiguration( setOf( R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications ) ) setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) } }
grupo-jima-repartidores-app/app/src/main/java/daniel/pena/garcia/grupo_jima_repartidores_app/MainActivity.kt
617102664
package Fernanda.Hernandez.poofernanda import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //variables var dia: String var edad: Int = 22 var velocidad: Double var temperatura: Float = 30.0f //valores (constantes) val pi: Double = 3.1416 val DUI: String = "0930203-8" val fechaN: String = "8 de octubre " //variables nulas var tel: Int? = null //comprobar si la variable es nula, y asi la aplicacion no se cierre; si tiene el signo de pregunta la variable puede tener datos nulos pero primero se comprueba si es nulo o no //objetos val objCalc = Calcu () objCalc.suma(8, 4 ) println( objCalc.suma(8, 4 )) val itzferhdz = Usuario() itzferhdz.darlike() itzferhdz.follow() // arrays val listado = arrayOf("Yun", "Chae", "Eun", "Zuha", "Saku chan", 8 ) } //clases class personas { } class newUser { } class leSserafim { } }
poo-fer/MainActivity.kt
2954331155
package Fernanda.Hernandez.poofernanda class conexionYJ { // Funciones fun Conectar (nombreYJ: String) { } fun Sumar ( num1: Int, num2: Int) { } fun Restar ( num1: Int, num2: Int) { } Sumar (2, 3) // es el q espera // funciones con retorno fun multiplicar(num1: Int, num2: Int): Int{ val resultado = num1*num2 return resultado } }
poo-fer/conexionYJ.kt
3303841043
package Fernanda.Hernandez.poofernanda class Calcu { fun suma(num1: Int, num2: Int): Int{ val resultado = num1+num2 return resultado } fun multiplicar(num1: Int, num2: Int): Int{ val resultado = num1*num2 return resultado } fun resta(num1: Int, num2: Int): Int{ val resultado = num1-num2 return resultado } fun dividir(num1: Int, num2: Int): Int{ val resultado = num1/num2 return resultado } }
poo-fer/Calcu.kt
3652545884
package Fernanda.Hernandez.poofernanda class Usuario { fun darlike () { } fun follow () { } }
poo-fer/Usuario.kt
174872144
package com.example.submissionaplikasistory import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.submissionaplikasistory", appContext.packageName) } }
Story-App/app/src/androidTest/java/com/example/submissionaplikasistory/ExampleInstrumentedTest.kt
299103363
package com.example.submissionaplikasistory import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.rules.TestWatcher import org.junit.runner.Description @OptIn(ExperimentalCoroutinesApi::class) class MainDispatcherRule ( private val testDispatcher: TestDispatcher = UnconfinedTestDispatcher() ) : TestWatcher() { override fun starting(description: Description) { Dispatchers.setMain(testDispatcher) } override fun finished(description: Description) { Dispatchers.resetMain() } }
Story-App/app/src/test/java/com/example/submissionaplikasistory/MainDispatcherRule.kt
2509890451
package com.example.submissionaplikasistory import com.example.submissionaplikasistory.datasource.local.EntityDaoStory object DataDummy { fun generateEntityResponse(): List<EntityDaoStory> { val items: MutableList<EntityDaoStory> = arrayListOf() for (i in 0..100) { val quote = EntityDaoStory( id = "story-JpTtDha5AxTFJT9q", name = "Dicoding", description = "1. Miliki Motivasi yang Tinggi 2. Bersikap Persisten saat dalam Berlatih dan Menghadapi Tantangan 3. Selalu Percaya Diri dan Mencari Apa Passion Kita", photoUrl = "https://story-api.dicoding.dev/images/stories/photos-1687835950650_XvmTvFBv.jpg", createdAt = "2023-06-27T03:19:10.651Z", lat = -8.8540315, lon = 121.6438983 ) items.add(quote) } return items } }
Story-App/app/src/test/java/com/example/submissionaplikasistory/DataDummy.kt
361634708
package com.example.submissionaplikasistory.view.viewmodel import android.annotation.SuppressLint import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.paging.AsyncPagingDataDiffer import androidx.paging.PagingData import androidx.paging.PagingSource import androidx.paging.PagingState import androidx.recyclerview.widget.ListUpdateCallback import com.example.submissionaplikasistory.DataDummy import com.example.submissionaplikasistory.LiveDataTestUtil.getOrAwaitValue import com.example.submissionaplikasistory.MainDispatcherRule import com.example.submissionaplikasistory.datasource.local.EntityDaoStory import com.example.submissionaplikasistory.repository.StoryRepository import com.example.submissionaplikasistory.view.adapter.StoryAdapter import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.Assert import org.junit.Assert.* import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito import org.mockito.junit.MockitoJUnitRunner import kotlin.math.exp @ExperimentalCoroutinesApi @RunWith(MockitoJUnitRunner::class) class StoryViewModelTest { @get:Rule val instantExecutorRule = InstantTaskExecutorRule() @get:Rule val mainDispatcherRules = MainDispatcherRule() @Mock private lateinit var storyRepository: StoryRepository @Test() fun `not null when get story and return the output`() = runTest { val getDummyEntity = DataDummy.generateEntityResponse() val data = QuotePagingSource.snapshot(getDummyEntity) val expected = MutableLiveData<PagingData<EntityDaoStory>>() val token = mutableMapOf(Pair("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyLTY4XzZWLXpDT3ctYmgyUHIiLCJpYXQiOjE3MTQxMTE2NzN9.0khGdVcWtpI8ZGSNpMc2_RKee6c8q5fHR_RSKd4iLe0")) expected.value = data Mockito.`when`(storyRepository.getStoryFromDatabaseDao(token)).thenReturn(expected) val storyViewModel = StoryViewModel(storyRepository) val result : LiveData<PagingData<EntityDaoStory>> = storyViewModel.getStoryDao(token) val resultPagingDataFromViewModel : PagingData<EntityDaoStory> = result.getOrAwaitValue() val dif = AsyncPagingDataDiffer( diffCallback = StoryAdapter.diffUtil, updateCallback = noopListUpdateCallback, workerDispatcher = Dispatchers.Main, ) dif.submitData(resultPagingDataFromViewModel) assertNotNull(dif.snapshot()) assertEquals(getDummyEntity.size, dif.snapshot().size) assertEquals(getDummyEntity[0], dif.snapshot()[0]) } @Test() fun `should null when get story and return the output size 0`() = runTest { val data : PagingData<EntityDaoStory> = PagingData.from(emptyList()) val expected = MutableLiveData<PagingData<EntityDaoStory>>() val token = mutableMapOf(Pair("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyLTY4XzZWLXpDT3ctYmgyUHIiLCJpYXQiOjE3MTQxMTE2NzN9.0khGdVcWtpI8ZGSNpMc2_RKee6c8q5fHR_RSKd4iLe0")) expected.value = data Mockito.`when`(storyRepository.getStoryFromDatabaseDao(token)).thenReturn(expected) val storyViewModel = StoryViewModel(storyRepository) val result : LiveData<PagingData<EntityDaoStory>> = storyViewModel.getStoryDao(token) val resultPagingDataFromViewModel : PagingData<EntityDaoStory> = result.getOrAwaitValue() val dif = AsyncPagingDataDiffer( diffCallback = StoryAdapter.diffUtil, updateCallback = noopListUpdateCallback, workerDispatcher = Dispatchers.Main, ) dif.submitData(resultPagingDataFromViewModel) assertEquals(0, dif.snapshot().size) } } class QuotePagingSource : PagingSource<Int, LiveData<List<EntityDaoStory>>>() { companion object { fun snapshot(items: List<EntityDaoStory>): PagingData<EntityDaoStory> { return PagingData.from(items) } } override fun getRefreshKey(state: PagingState<Int, LiveData<List<EntityDaoStory>>>): Int { return 0 } override suspend fun load(params: LoadParams<Int>): LoadResult<Int, LiveData<List<EntityDaoStory>>> { return LoadResult.Page(emptyList(), 0, 1) } } val noopListUpdateCallback = object : ListUpdateCallback { override fun onInserted(position: Int, count: Int) {} override fun onRemoved(position: Int, count: Int) {} override fun onMoved(fromPosition: Int, toPosition: Int) {} override fun onChanged(position: Int, count: Int, payload: Any?) {} }
Story-App/app/src/test/java/com/example/submissionaplikasistory/view/viewmodel/StoryViewModelTest.kt
1846523244
package com.example.submissionaplikasistory import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException object LiveDataTestUtil { fun <T> LiveData<T>.getOrAwaitValue( time: Long = 2, timeUnit: TimeUnit = TimeUnit.SECONDS, afterObserve: () -> Unit = {} ): T { var data: T? = null val latch = CountDownLatch(1) val observer = object : Observer<T> { override fun onChanged(value: T) { data = value latch.countDown() this@getOrAwaitValue.removeObserver(this) } } this.observeForever(observer) try { afterObserve.invoke() // Don't wait indefinitely if the LiveData is not set. if (!latch.await(time, timeUnit)) { throw TimeoutException("LiveData value was never set.") } } finally { this.removeObserver(observer) } @Suppress("UNCHECKED_CAST") return data as T } }
Story-App/app/src/test/java/com/example/submissionaplikasistory/LiveDataTestUtil.kt
4193091397
package com.example.submissionaplikasistory.datasource import androidx.paging.PagingSource import androidx.paging.PagingState import com.example.submissionaplikasistory.datasource.api.ApiService import com.example.submissionaplikasistory.datasource.model.ListStoryItem class StoryPagingSource( private val apiService: ApiService, private val token: Map<String, String> ): PagingSource<Int, ListStoryItem>() { private companion object { const val INITIAL_PAGE_INDEX = 1 } override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ListStoryItem> { return try { val page = params.key ?: INITIAL_PAGE_INDEX val responseData = apiService.getStories(token ,page, params.loadSize).body()?.listStory LoadResult.Page( data = responseData!!, prevKey = if (page == 1) null else page - 1, nextKey = if (responseData.isNullOrEmpty()) null else page + 1 ) } catch (exception: Exception) { return LoadResult.Error(exception) } } override fun getRefreshKey(state: PagingState<Int, ListStoryItem>): Int? { return state.anchorPosition?.let { anchorPosition -> val anchorPage = state.closestPageToPosition(anchorPosition) anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1) } } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/datasource/StoryPagingSource.kt
2732967856
package com.example.submissionaplikasistory.datasource.local import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query @Dao interface RemoteKeysDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertAll(remoteKeys: List<RemoteKeys>) @Query("SELECT * FROM remotekeys WHERE id = :id") suspend fun getRemoteById(id: String): RemoteKeys? @Query("DELETE FROM remotekeys") suspend fun delete() }
Story-App/app/src/main/java/com/example/submissionaplikasistory/datasource/local/RemoteKeysDao.kt
2316677158
package com.example.submissionaplikasistory.datasource.local import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database(entities = [EntityDaoStory::class, RemoteKeys::class], version = 2, exportSchema = false) abstract class DaoStoryConfig : RoomDatabase() { abstract fun getService(): DaoService abstract fun remoteKeyDao(): RemoteKeysDao companion object { private var instance: DaoStoryConfig? = null fun getInstance(context: Context) = instance ?: synchronized(this) { instance ?: Room.databaseBuilder( context.applicationContext, DaoStoryConfig::class.java, "Story Config Database" ).fallbackToDestructiveMigration().build() .also { instance = it } } } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/datasource/local/DaoStoryConfig.kt
1651662887
package com.example.submissionaplikasistory.datasource.local import android.os.Parcelable import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize import kotlinx.parcelize.RawValue @Entity @Parcelize data class EntityDaoStory( val photoUrl: String? = null, val createdAt: String? = null, val name: String? = null, val description: String? = null, val lon: Double? = null, @PrimaryKey val id: String, val lat: Double? = null ) : Parcelable
Story-App/app/src/main/java/com/example/submissionaplikasistory/datasource/local/EntityDaoStory.kt
3974547419
package com.example.submissionaplikasistory.datasource.local import androidx.lifecycle.LiveData import androidx.paging.PagingSource import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query @Dao interface DaoService { @Query("SELECT * FROM ENTITYDAOSTORY") fun getStory() : PagingSource<Int, EntityDaoStory> @Query("SELECT * FROM ENTITYDAOSTORY") suspend fun getStoryListEntityDaoStory() : List<EntityDaoStory> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun addStory(story: List<EntityDaoStory>) @Query("DELETE FROM EntityDaoStory") suspend fun deleteAll() }
Story-App/app/src/main/java/com/example/submissionaplikasistory/datasource/local/DaoService.kt
3887878398
package com.example.submissionaplikasistory.datasource.local import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class RemoteKeys ( @PrimaryKey val id: String, val prevKey: Int?, val nextKey: Int? )
Story-App/app/src/main/java/com/example/submissionaplikasistory/datasource/local/RemoteKeys.kt
3206816446
package com.example.submissionaplikasistory.datasource.model import com.google.gson.annotations.SerializedName data class RegisterResponse( @field:SerializedName("error") val error: Boolean? = null, @field:SerializedName("message") val message: String? = null )
Story-App/app/src/main/java/com/example/submissionaplikasistory/datasource/model/RegisterResponse.kt
133400448
package com.example.submissionaplikasistory.datasource.model import com.google.gson.annotations.SerializedName data class ErrorResponse ( @field:SerializedName("error") val error: Boolean? = null, @field:SerializedName("message") val message: String? = null )
Story-App/app/src/main/java/com/example/submissionaplikasistory/datasource/model/ErrorResponse.kt
561253742
package com.example.submissionaplikasistory.datasource.model import com.google.gson.annotations.SerializedName data class PostResponse( @field:SerializedName("error") val error: Boolean? = null, @field:SerializedName("message") val message: String? = null )
Story-App/app/src/main/java/com/example/submissionaplikasistory/datasource/model/PostResponse.kt
2442454687
package com.example.submissionaplikasistory.datasource.model import com.google.gson.annotations.SerializedName data class DetailStoryResponse( @field:SerializedName("error") val error: Boolean? = null, @field:SerializedName("message") val message: String? = null, @field:SerializedName("story") val story: Story? = null ) data class Story( @field:SerializedName("photoUrl") val photoUrl: String? = null, @field:SerializedName("createdAt") val createdAt: String? = null, @field:SerializedName("name") val name: String? = null, @field:SerializedName("description") val description: String? = null, @field:SerializedName("lon") val lon: Any? = null, @field:SerializedName("id") val id: String? = null, @field:SerializedName("lat") val lat: Any? = null )
Story-App/app/src/main/java/com/example/submissionaplikasistory/datasource/model/DetailStoryResponse.kt
4107062772
package com.example.submissionaplikasistory.datasource.model import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize import kotlinx.parcelize.RawValue data class StoryResponse( @field:SerializedName("listStory") val listStory: List<ListStoryItem>, @field:SerializedName("error") val error: Boolean? = null, @field:SerializedName("message") val message: String? = null ) @Parcelize data class ListStoryItem( @field:SerializedName("photoUrl") val photoUrl: String? = null, @field:SerializedName("createdAt") val createdAt: String? = null, @field:SerializedName("name") val name: String? = null, @field:SerializedName("description") val description: String? = null, @field:SerializedName("lon") val lon: Double? = null, @field:SerializedName("id") val id: String? = null, @field:SerializedName("lat") val lat: Double? = null ): Parcelable
Story-App/app/src/main/java/com/example/submissionaplikasistory/datasource/model/StoryResponse.kt
3566248555
package com.example.submissionaplikasistory.datasource.model import com.google.gson.annotations.SerializedName data class LoginResponse( @field:SerializedName("loginResult") val loginResult: LoginResult? = null, @field:SerializedName("error") val error: Boolean? = null, @field:SerializedName("message") val message: String? = null ) data class LoginResult( @field:SerializedName("name") val name: String? = null, @field:SerializedName("userId") val userId: String? = null, @field:SerializedName("token") val token: String? = null )
Story-App/app/src/main/java/com/example/submissionaplikasistory/datasource/model/LoginResponse.kt
1071138991
package com.example.submissionaplikasistory.datasource.api import com.example.submissionaplikasistory.BuildConfig import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object ApiConfiguration { fun getApiService(): ApiService { val loggingInterceptor = HttpLoggingInterceptor() loggingInterceptor.level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE val client = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() val retrofit = Retrofit.Builder() .baseUrl(BuildConfig.BASE_URL_API_STORY) .client(client) .addConverterFactory(GsonConverterFactory.create()) .build() return retrofit.create(ApiService::class.java) } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/datasource/api/ApiConfiguration.kt
3393518412
package com.example.submissionaplikasistory.datasource.api import com.example.submissionaplikasistory.datasource.model.DetailStoryResponse import com.example.submissionaplikasistory.datasource.model.LoginResponse import com.example.submissionaplikasistory.datasource.model.PostResponse import com.example.submissionaplikasistory.datasource.model.RegisterResponse import com.example.submissionaplikasistory.datasource.model.StoryResponse import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Response import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.GET import retrofit2.http.HeaderMap import retrofit2.http.Multipart import retrofit2.http.POST import retrofit2.http.Part import retrofit2.http.Path import retrofit2.http.Query interface ApiService { @FormUrlEncoded @POST("register") suspend fun register( @Field("name") name: String, @Field("email") email: String, @Field("password") password: String ): Response<RegisterResponse> @FormUrlEncoded @POST("login") suspend fun login( @Field("email") email: String, @Field("password") password: String ): Response<LoginResponse> @GET("stories") suspend fun getStories( @HeaderMap headerMap: Map<String,String>, @Query("page") page: Int = 1, @Query("size") size: Int = 10, @Query("location") location: Int = 1 ): Response<StoryResponse> @GET("stories/{id}") suspend fun getDetailStory( @HeaderMap headerMap: Map<String,String>, @Path("id") id: String ): Response<DetailStoryResponse> @Multipart @POST("stories") suspend fun postStory( @HeaderMap header: Map<String, String>, @Part("description") description: RequestBody, @Part file : MultipartBody.Part ): Response<PostResponse> }
Story-App/app/src/main/java/com/example/submissionaplikasistory/datasource/api/ApiService.kt
3724923647
package com.example.submissionaplikasistory.datasource import androidx.paging.ExperimentalPagingApi import androidx.paging.LoadType import androidx.paging.PagingState import androidx.paging.RemoteMediator import androidx.room.withTransaction import com.example.submissionaplikasistory.datasource.api.ApiService import com.example.submissionaplikasistory.datasource.local.DaoStoryConfig import com.example.submissionaplikasistory.datasource.local.EntityDaoStory import com.example.submissionaplikasistory.datasource.local.RemoteKeys import com.example.submissionaplikasistory.utils.Utils @OptIn(ExperimentalPagingApi::class) class StoryRemoteMediator( private val db : DaoStoryConfig, private val apiService: ApiService, private val token: Map<String, String>, ): RemoteMediator<Int, EntityDaoStory>() { private companion object { const val INITIAL_PAGE_VALUE = 1 } override suspend fun initialize(): InitializeAction { return InitializeAction.LAUNCH_INITIAL_REFRESH } override suspend fun load( loadType: LoadType, state: PagingState<Int, EntityDaoStory> ): MediatorResult { val page = when (loadType) { LoadType.REFRESH ->{ val remoteKeys = getRemoteKeyClosestToCurrentPosition(state) remoteKeys?.nextKey?.minus(1) ?: INITIAL_PAGE_VALUE } LoadType.PREPEND -> { val remoteKeys = getRemoteKeyForFirstItem(state) val prevKey = remoteKeys?.prevKey ?: return MediatorResult.Success(endOfPaginationReached = remoteKeys != null) prevKey } LoadType.APPEND -> { val remoteKeys = getRemoteKeyForLastItem(state) val nextKey = remoteKeys?.nextKey ?: return MediatorResult.Success(endOfPaginationReached = remoteKeys != null) nextKey } } try { val response = apiService.getStories(token, page, state.config.pageSize) val endOfPagination = response.body()?.listStory?.isEmpty() db.withTransaction { if (loadType == LoadType.REFRESH) { db.remoteKeyDao().delete() db.getService().deleteAll() } val prevKey = if (page == 1) null else page - 1 val nextKey = if (endOfPagination!!) null else page + 1 val keys = response.body()?.listStory?.map { RemoteKeys(id = it.id!!, prevKey = prevKey, nextKey = nextKey) } val body = Utils().convertResponseStoryEntityDaoStory(response.body()) db.remoteKeyDao().insertAll(keys!!) db.getService().addStory(body) } return MediatorResult.Success(endOfPaginationReached = endOfPagination!!) } catch(e: Exception) { return MediatorResult.Error(e) } } private suspend fun getRemoteKeyForLastItem(state: PagingState<Int, EntityDaoStory>): RemoteKeys? { return state.pages.lastOrNull { it.data.isNotEmpty() }?.data?.lastOrNull()?.let { data -> db.remoteKeyDao().getRemoteById(data.id) } } private suspend fun getRemoteKeyForFirstItem(state: PagingState<Int, EntityDaoStory>): RemoteKeys? { return state.pages.firstOrNull { it.data.isNotEmpty() }?.data?.firstOrNull()?.let { data -> db.remoteKeyDao().getRemoteById(data.id) } } private suspend fun getRemoteKeyClosestToCurrentPosition(state: PagingState<Int, EntityDaoStory>): RemoteKeys? { return state.anchorPosition?.let { position -> state.closestItemToPosition(position)?.id?.let { id -> db.remoteKeyDao().getRemoteById(id) } } } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/datasource/StoryRemoteMediator.kt
4035782643
package com.example.submissionaplikasistory.repository import com.example.submissionaplikasistory.datasource.api.ApiConfiguration import com.example.submissionaplikasistory.datasource.model.LoginResponse import com.example.submissionaplikasistory.datasource.model.RegisterResponse import retrofit2.Response class UserRepository { suspend fun userRegister( name: String, email: String, password: String ) : Response<RegisterResponse> { return ApiConfiguration.getApiService().register(name, email, password) } suspend fun userLogin( email: String, password: String ): Response<LoginResponse> { return ApiConfiguration.getApiService().login(email, password) } companion object { @Volatile private var instance: UserRepository? = null fun getInstance() : UserRepository? { return instance ?: synchronized(this) { instance = UserRepository() instance } } } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/repository/UserRepository.kt
632141663
package com.example.submissionaplikasistory.repository import android.annotation.SuppressLint import androidx.lifecycle.LiveData import androidx.paging.ExperimentalPagingApi import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import androidx.paging.PagingSource import androidx.paging.liveData import com.example.submissionaplikasistory.datasource.StoryPagingSource import com.example.submissionaplikasistory.datasource.StoryRemoteMediator import com.example.submissionaplikasistory.datasource.api.ApiConfiguration import com.example.submissionaplikasistory.datasource.api.ApiService import com.example.submissionaplikasistory.datasource.local.DaoStoryConfig import com.example.submissionaplikasistory.datasource.local.EntityDaoStory import com.example.submissionaplikasistory.datasource.model.DetailStoryResponse import com.example.submissionaplikasistory.datasource.model.ListStoryItem import com.example.submissionaplikasistory.datasource.model.PostResponse import com.example.submissionaplikasistory.datasource.model.StoryResponse import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow import okhttp3.MultipartBody import okhttp3.RequestBody import org.w3c.dom.Entity import retrofit2.Response class StoryRepository( private val db : DaoStoryConfig, private val apiService: ApiService ) { suspend fun getAllStories(header: Map<String, String>): Response<StoryResponse> { return ApiConfiguration.getApiService().getStories(header) } suspend fun getDetailStory(header: Map<String, String>, id: String): Response<DetailStoryResponse> { return ApiConfiguration.getApiService().getDetailStory(header, id) } suspend fun postStory(header: Map<String, String>, description: RequestBody, file: MultipartBody.Part): Response<PostResponse> { return ApiConfiguration.getApiService().postStory(header, description, file) } @OptIn(ExperimentalPagingApi::class) fun getStoryFromDatabaseDao(token: Map<String, String>): LiveData<PagingData<EntityDaoStory>>{ return Pager( config = PagingConfig( pageSize = 5, maxSize = 15 ), remoteMediator = StoryRemoteMediator(db, apiService, token), pagingSourceFactory = { db.getService().getStory() } ).liveData } suspend fun getOnlyStory(): List<EntityDaoStory> { return db.getService().getStoryListEntityDaoStory() } companion object { @SuppressLint("StaticFieldLeak") private var instance: StoryRepository? = null fun getInstance(daoStoryConfig: DaoStoryConfig, apiService: ApiService) = instance ?: synchronized(this) { val ins = StoryRepository(daoStoryConfig, apiService) instance = ins instance } } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/repository/StoryRepository.kt
2825272172
package com.example.submissionaplikasistory.di import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import com.example.submissionaplikasistory.datasource.api.ApiConfiguration import com.example.submissionaplikasistory.datasource.local.DaoStoryConfig import com.example.submissionaplikasistory.repository.StoryRepository import com.example.submissionaplikasistory.repository.UserRepository import com.example.submissionaplikasistory.utils.SettingPreference import com.example.submissionaplikasistory.view.viewmodel.ViewModelProviderFactory object Injection { fun getUserRepositoryInstance(dataStore: DataStore<Preferences>) : ViewModelProviderFactory { val repo = UserRepository.getInstance() val pref = SettingPreference.getInstance(dataStore)!! return ViewModelProviderFactory(repo, pref) } fun getStoryRepositoryInstance(context: Context): ViewModelProviderFactory { val dao = DaoStoryConfig.getInstance(context) val service = ApiConfiguration.getApiService() val repo = StoryRepository.getInstance(dao, service) return ViewModelProviderFactory(repo, null) } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/di/Injection.kt
1335209842
package com.example.submissionaplikasistory.utils sealed class Resources<T> { data class OnSuccess <T>(val data: T): Resources<T>() data class OnFailure <T>(val message: String): Resources<T>() class Loading<T>() : Resources<T>() }
Story-App/app/src/main/java/com/example/submissionaplikasistory/utils/Resources.kt
3688221392
package com.example.submissionaplikasistory.utils import android.app.Dialog import android.content.ContentValues import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import android.net.Uri import android.os.Build import android.os.Environment import android.provider.MediaStore import android.view.Gravity import android.view.ViewGroup import android.view.Window import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import androidx.exifinterface.media.ExifInterface import androidx.paging.PagingSource import com.example.submissionaplikasistory.BuildConfig import com.example.submissionaplikasistory.R import com.example.submissionaplikasistory.datasource.local.EntityDaoStory import com.example.submissionaplikasistory.datasource.model.StoryResponse import java.io.ByteArrayOutputStream import java.io.File import java.io.FileOutputStream import java.io.InputStream import java.text.SimpleDateFormat import java.util.Date import java.util.Locale class Utils { companion object { private val FILENAME_FORMAT = "yyyMMdd_HHmmss" private val timeStamp: String = SimpleDateFormat(FILENAME_FORMAT, Locale.US).format(Date()) private const val MAXIMAL_SIZE = 1000000 fun dialogInstance(applicationContext: Context): Dialog { val dialog = Dialog(applicationContext) val window: Window? = dialog.window window?.setLayout( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) window?.setBackgroundDrawable( ContextCompat.getDrawable( applicationContext, R.drawable.background_dialog ) ) window?.attributes?.gravity = Gravity.BOTTOM dialog.setCancelable(false) return dialog } fun getHeader(token: String): Map<String, String> { val header = mutableMapOf<String, String>() header["Authorization"] = "Bearer $token" return header } fun getImageUri(context: Context): Uri { var uri: Uri? = null if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { val contentValue = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, "$timeStamp.jpg") put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg") put(MediaStore.MediaColumns.RELATIVE_PATH, "Pictures/MyCamera/") } uri = context.contentResolver.insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValue ) } return uri ?: getImageUriForPreQ(context) } private fun getImageUriForPreQ(context: Context): Uri { val fileDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) val imageFile = File(fileDir, "/MyCamera/$timeStamp.jpg") if (imageFile.parentFile?.exists() == false) imageFile.parentFile?.mkdir() return FileProvider.getUriForFile( context, "${BuildConfig.APPLICATION_ID}.fileProvider", imageFile ) } private fun createCustomTempFile(context: Context): File { val fileDir = context.externalCacheDir return File.createTempFile(timeStamp, ".jpg", fileDir) } fun uriToFile(imageUri: Uri, context: Context): File { val myFile = createCustomTempFile(context) val inputStream = context.contentResolver.openInputStream(imageUri) as InputStream val outputStream = FileOutputStream(myFile) val buffer = ByteArray(1000) var length: Int while (inputStream.read(buffer).also { length = it } > 0) outputStream.write(buffer, 0, length) outputStream.close() inputStream.close() return myFile } fun File.reduceImage(): File { val file = this val bitmap = BitmapFactory.decodeFile(file.path).getRotatedBitmap(file) var compressQuality: Int = 100 var streamLength: Int do { val bmpStream = ByteArrayOutputStream() bitmap?.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream) val bmpPicByteArray = bmpStream.toByteArray() streamLength = bmpPicByteArray.size compressQuality -= 5 } while (streamLength > MAXIMAL_SIZE) bitmap?.compress(Bitmap.CompressFormat.JPEG, compressQuality, FileOutputStream(file)) return file } fun Bitmap.getRotatedBitmap(file: File): Bitmap? { val orientation = ExifInterface(file).getAttributeInt( ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED ) return when (orientation) { ExifInterface.ORIENTATION_ROTATE_90 -> rotateImage(this, 90F) ExifInterface.ORIENTATION_ROTATE_180 -> rotateImage(this, 180F) ExifInterface.ORIENTATION_ROTATE_270 -> rotateImage(this, 270F) ExifInterface.ORIENTATION_NORMAL -> this else -> this } } fun rotateImage(source: Bitmap, angle: Float): Bitmap { val matrix = Matrix() matrix.postRotate(angle) return Bitmap.createBitmap( source, 0, 0, source.width, source.height, matrix, true ) } } fun convertResponseStoryEntityDaoStory(response: StoryResponse?) : List<EntityDaoStory> { val resultListEntityDaoStory = mutableListOf<EntityDaoStory>() val listResponse = response?.listStory listResponse?.map { val value = EntityDaoStory( it?.photoUrl, it?.createdAt, it?.name, it?.description, it?.lon, it?.id.toString(), it?.lat ) resultListEntityDaoStory.add(value) } return resultListEntityDaoStory } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/utils/Utils.kt
1751705353
package com.example.submissionaplikasistory.utils.addscustomview import android.content.Context import android.graphics.Canvas import android.text.Editable import android.text.TextWatcher import android.util.AttributeSet import androidx.core.content.ContextCompat import com.example.submissionaplikasistory.R import com.google.android.material.textfield.TextInputEditText class CustomPasswordEditText(context: Context, attr: AttributeSet?) : TextInputEditText(context, attr) { init { addTextChangedListener(object: TextWatcher{ override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { if (s.toString().length < 8) { setError(ContextCompat.getString(context, R.string.error_edit_text_password), null) } } override fun afterTextChanged(s: Editable?) { } }) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/utils/addscustomview/CustomPasswordEditText.kt
1886535558
package com.example.submissionaplikasistory.utils.addscustomview import android.content.Context import android.graphics.Canvas import android.text.Editable import android.text.TextWatcher import android.util.AttributeSet import android.util.Patterns import androidx.core.content.ContextCompat import com.example.submissionaplikasistory.R import com.google.android.material.textfield.TextInputEditText class CustomEmailEditText (context: Context, attr: AttributeSet?): TextInputEditText(context, attr) { init { addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { val pattern = Patterns.EMAIL_ADDRESS if (!pattern.matcher(s.toString()).matches()) { setError(ContextCompat.getString(context, R.string.email_error)) } } override fun afterTextChanged(s: Editable?) { } }) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/utils/addscustomview/CustomEmailEditText.kt
3684428017
package com.example.submissionaplikasistory.utils import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.example.submissionaplikasistory.datasource.model.LoginResult import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "user_active") class SettingPreference private constructor(private val dataStore: DataStore<Preferences>) { object PreferenceKey { val userId = stringPreferencesKey("user_id") val name = stringPreferencesKey("name") val token = stringPreferencesKey("token") } fun getUserActive(): Flow<LoginResult> { return dataStore.data.map { preference -> val userId = preference[PreferenceKey.userId] val name = preference[PreferenceKey.name] val token = preference[PreferenceKey.token] LoginResult(userId, name, token) } } suspend fun saveUserSession(loginResult: LoginResult) { dataStore.edit { preferences -> preferences[PreferenceKey.userId] = loginResult.userId!! preferences[PreferenceKey.name] = loginResult.name!! preferences[PreferenceKey.token] = loginResult.token!! } } suspend fun deleteUserSession() { dataStore.edit { preferences -> preferences.clear() } } companion object { @Volatile private var instance: SettingPreference? = null fun getInstance(dataStore: DataStore<Preferences>) = instance ?: synchronized(this) { val ins = SettingPreference(dataStore) instance = ins instance } } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/utils/SettingPreference.kt
3434626090
package com.example.submissionaplikasistory.view.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.submissionaplikasistory.repository.StoryRepository import com.example.submissionaplikasistory.repository.UserRepository import com.example.submissionaplikasistory.utils.SettingPreference class ViewModelProviderFactory(private val repo: Any?, private val preference: SettingPreference?): ViewModelProvider.NewInstanceFactory() { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(UserViewModel::class.java)) { return UserViewModel(repo as UserRepository, preference!!) as T } else if (modelClass.isAssignableFrom(StoryViewModel::class.java)) { return StoryViewModel(repo as StoryRepository) as T } throw IllegalStateException("Can't instance view model because repository not found") } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/view/viewmodel/VIewModelProviderFactory.kt
2067306692
package com.example.submissionaplikasistory.view.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import androidx.lifecycle.viewModelScope import androidx.paging.PagingData import androidx.paging.cachedIn import com.example.submissionaplikasistory.datasource.local.EntityDaoStory import com.example.submissionaplikasistory.datasource.model.ErrorResponse import com.example.submissionaplikasistory.datasource.model.ListStoryItem import com.example.submissionaplikasistory.datasource.model.PostResponse import com.example.submissionaplikasistory.datasource.model.Story import com.example.submissionaplikasistory.repository.StoryRepository import com.example.submissionaplikasistory.utils.Resources import com.example.submissionaplikasistory.utils.Utils import com.google.gson.Gson import kotlinx.coroutines.launch import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.HttpException class StoryViewModel( private val storyRepository: StoryRepository, ) : ViewModel() { private val _story : MutableLiveData<Resources<List<ListStoryItem>>> = MutableLiveData() val story: LiveData<Resources<List<ListStoryItem>>> = _story private val _detailStory: MutableLiveData<Resources<Story>> = MutableLiveData() val detailStory: LiveData<Resources<Story>> = _detailStory private val _postResult: MutableLiveData<Resources<PostResponse>> = MutableLiveData() val postResult: LiveData<Resources<PostResponse>> = _postResult val getAllStoryFromDatabase : MutableLiveData<List<EntityDaoStory>> = MutableLiveData() init { getDataStoryNotPaging() } fun getDetailStory(token: String, id: String) = viewModelScope.launch { val header = Utils.getHeader(token) val responseResult = storyRepository.getDetailStory(header, id) try { if (responseResult.isSuccessful && responseResult.body()?.error == false) { responseResult.body()?.story?.let { val result = Resources.OnSuccess(it) _detailStory.postValue(result) } } } catch (e: HttpException) { val jsonInString = e.response()?.errorBody()?.string() val errorBody = Gson().fromJson(jsonInString, ErrorResponse::class.java) val errorMessage = errorBody.message errorMessage?.let { _detailStory.postValue(Resources.OnFailure(errorMessage)) } } } fun postStory(token: String, description: RequestBody, file: MultipartBody.Part) = viewModelScope.launch { val header = Utils.getHeader(token) try { val responseResult = storyRepository.postStory(header, description, file) if (responseResult.isSuccessful && responseResult.body()?.error == false) { responseResult.body()?.let { val result = Resources.OnSuccess(it) _postResult.postValue(result) } } } catch (e: HttpException) { val jsonInString = e.response()?.errorBody()?.string() val errorBody = Gson().fromJson(jsonInString, ErrorResponse::class.java) val errorMessage = errorBody.message errorMessage?.let { _postResult.postValue(Resources.OnFailure(errorMessage)) } } } fun getStoryDao(token: Map<String, String>) : LiveData<PagingData<EntityDaoStory>> = storyRepository.getStoryFromDatabaseDao(token).cachedIn(viewModelScope) private fun getDataStoryNotPaging() = viewModelScope.launch { getAllStoryFromDatabase.postValue(storyRepository.getOnlyStory()) } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/view/viewmodel/StoryViewModel.kt
1514857079
package com.example.submissionaplikasistory.view.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import androidx.lifecycle.viewModelScope import com.example.submissionaplikasistory.datasource.model.ErrorResponse import com.example.submissionaplikasistory.datasource.model.LoginResponse import com.example.submissionaplikasistory.datasource.model.LoginResult import com.example.submissionaplikasistory.datasource.model.RegisterResponse import com.example.submissionaplikasistory.repository.UserRepository import com.example.submissionaplikasistory.utils.Resources import com.example.submissionaplikasistory.utils.SettingPreference import com.google.gson.Gson import kotlinx.coroutines.launch import retrofit2.HttpException import retrofit2.Response class UserViewModel( private val userRepository: UserRepository, private val preference: SettingPreference ) : ViewModel() { private val registerResult: MutableLiveData<Resources<RegisterResponse>> = MutableLiveData() val getRegisterResponseResult: LiveData<Resources<RegisterResponse>> = registerResult private val loginResult: MutableLiveData<Resources<LoginResponse>> = MutableLiveData() val getLoginResponseResult: LiveData<Resources<LoginResponse>> = loginResult fun requestRegisterAccountStory( name: String, email: String, password: String ) = viewModelScope.launch { registerResult.postValue(Resources.Loading()) try { val response = userRepository.userRegister(name, email, password) registerResult.postValue(handlerRegisterAccountStory(response)) } catch (e: HttpException) { registerResult.postValue(Resources.OnFailure(e.message().toString())) } } fun requestLoginAccountStory( email: String, password: String ) = viewModelScope.launch { loginResult.postValue(Resources.Loading()) try { val response = userRepository.userLogin(email, password) loginResult.postValue(handlerLoginAccountStory(response)) } catch (e: HttpException) { loginResult.postValue(Resources.OnFailure(e.message().toString())) } } fun getUserSession() : LiveData<LoginResult> { return preference.getUserActive().asLiveData() } fun saveUserSession(loginResult: LoginResult) = viewModelScope.launch { preference.saveUserSession(loginResult) } fun deleteUserSession() = viewModelScope.launch { preference.deleteUserSession() } private fun handlerRegisterAccountStory(response: Response<RegisterResponse>) : Resources<RegisterResponse> { try { if (response.isSuccessful && response.body()?.error == false) { val body = response.body() body?.let { return Resources.OnSuccess(body) } } } catch (e: HttpException) { val jsonInString = e.response()?.errorBody()?.string() val errorBody = Gson().fromJson(jsonInString, ErrorResponse::class.java) val errorMessage = errorBody.message errorMessage?.let { return Resources.OnFailure(errorMessage) } } val jsonInString = response.errorBody()?.string() val errorBody = Gson().fromJson(jsonInString, ErrorResponse::class.java) return Resources.OnFailure(errorBody.message!!) } private fun handlerLoginAccountStory(response: Response<LoginResponse>) : Resources<LoginResponse> { try { if (response.isSuccessful && response.body()?.error == false) { val body = response.body() body?.let { return Resources.OnSuccess(body) } } } catch (e: HttpException) { val jsonInString = e.response()?.errorBody()?.string() val errorBody = Gson().fromJson(jsonInString, ErrorResponse::class.java) val errorMessage = errorBody.message errorMessage?.let { return Resources.OnFailure(errorMessage) } } val jsonInString = response.errorBody()?.string() val errorBody = Gson().fromJson(jsonInString, ErrorResponse::class.java) return Resources.OnFailure(errorBody.message!!) } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/view/viewmodel/UserViewModel.kt
540357464
package com.example.submissionaplikasistory.view.home import android.content.Intent import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.paging.LoadStateAdapter import androidx.paging.PagingData import androidx.paging.map import androidx.recyclerview.widget.LinearLayoutManager import com.example.submissionaplikasistory.R import com.example.submissionaplikasistory.databinding.ActivityMainBinding import com.example.submissionaplikasistory.datasource.local.EntityDaoStory import com.example.submissionaplikasistory.datasource.model.ListStoryItem import com.example.submissionaplikasistory.di.Injection import com.example.submissionaplikasistory.utils.Resources import com.example.submissionaplikasistory.utils.Utils import com.example.submissionaplikasistory.utils.dataStore import com.example.submissionaplikasistory.view.LoginActivity import com.example.submissionaplikasistory.view.adapter.LoadingStateAdapter import com.example.submissionaplikasistory.view.adapter.StoryAdapter import com.example.submissionaplikasistory.view.adapter.StoryAdapter2 import com.example.submissionaplikasistory.view.viewmodel.StoryViewModel import com.example.submissionaplikasistory.view.viewmodel.UserViewModel import com.google.gson.Gson class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private lateinit var adapterRc: StoryAdapter private val userViewModel: UserViewModel by viewModels { Injection.getUserRepositoryInstance(application.dataStore) } private val storyViewModel: StoryViewModel by viewModels { Injection.getStoryRepositoryInstance(applicationContext) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val action = supportActionBar action?.title = ContextCompat.getString(this, R.string.story) // Check user session userViewModel.getUserSession().observe(this) { if (it.token == null) { goToLoginPage() } } binding.apply { rvList.apply { layoutManager = LinearLayoutManager(this@MainActivity) } floatingAddPost.setOnClickListener { goToAddPostPage() } } setUpRecyclerView() } private fun goToLoginPage() { val intent = Intent(this@MainActivity, LoginActivity::class.java) startActivity(intent) finish() } private fun goToAddPostPage() { val intent = Intent(this@MainActivity, PostActivity::class.java) startActivity(intent) } private fun setUpRecyclerView() { adapterRc = StoryAdapter { goToDetailPost(it) } binding.rvList.adapter = adapterRc.withLoadStateFooter( footer = LoadingStateAdapter { adapterRc.retry() } ) userViewModel.getUserSession().observe(this) { println(it.token!!) storyViewModel.getStoryDao(Utils.getHeader(it.token)).observe(this) { result -> adapterRc.submitData(lifecycle, result) binding.loading.visibility = View.GONE } } userViewModel.getUserSession() } private fun actionLogout() { userViewModel.deleteUserSession() } private fun goToDetailPost(id: String?){ val intent = Intent(this@MainActivity, DetailPostActivity::class.java) id?.let { intent.putExtra(DetailPostActivity.ID_POST, it) } startActivity(intent) } private fun actionMap() { val intent = Intent(this, MapsCoverageStoryActivity::class.java) storyViewModel.getAllStoryFromDatabase.observe(this) { intent.putParcelableArrayListExtra(INTENT_MAPS, ArrayList(it)) } startActivity(intent) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_actionbar, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_logout -> { actionLogout() } R.id.action_map -> ( actionMap() ) } return super.onOptionsItemSelected(item) } companion object { const val INTENT_MAPS = "intent_maps" } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/view/home/MainActivity.kt
977756653
package com.example.submissionaplikasistory.view.home import android.os.Bundle import android.view.View import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import com.bumptech.glide.Glide import com.example.submissionaplikasistory.databinding.ActivityDetailPostBinding import com.example.submissionaplikasistory.di.Injection import com.example.submissionaplikasistory.utils.Resources import com.example.submissionaplikasistory.utils.dataStore import com.example.submissionaplikasistory.view.viewmodel.StoryViewModel import com.example.submissionaplikasistory.view.viewmodel.UserViewModel class DetailPostActivity : AppCompatActivity() { private lateinit var binding: ActivityDetailPostBinding private val storyViewModel: StoryViewModel by viewModels { Injection.getStoryRepositoryInstance(applicationContext) } private val userViewModel: UserViewModel by viewModels { Injection.getUserRepositoryInstance(application.dataStore) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDetailPostBinding.inflate(layoutInflater) setContentView(binding.root) if (intent.hasExtra(ID_POST)) { userViewModel.getUserSession().observe(this) { val id = intent.getStringExtra(ID_POST) println(it.token) println(id) if (it.token != null && id != null) storyViewModel.getDetailStory(it.token, id) } } attachDataToDisplay() } private fun attachDataToDisplay() { storyViewModel.detailStory.observe(this) { binding.loading.visibility = View.VISIBLE when(it) { is Resources.Loading -> { binding.loading.visibility = View.VISIBLE } is Resources.OnFailure -> { binding.loading.visibility = View.GONE } is Resources.OnSuccess -> { binding.loading.visibility = View.GONE binding.apply { Glide.with(this@DetailPostActivity) .load(it.data.photoUrl) .into(ivDetailPhoto) tvDetailName.text = it.data.name tvDetailDate.text = it.data.createdAt tvDetailDescription.text = it.data.description } } } } } companion object { const val ID_POST = "ID credential post" } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/view/home/DetailPostActivity.kt
2581943308
package com.example.submissionaplikasistory.view.home import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels import androidx.annotation.RequiresApi import com.example.submissionaplikasistory.R import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import com.example.submissionaplikasistory.databinding.ActivityMapsCoverageStoryBinding import com.example.submissionaplikasistory.datasource.local.EntityDaoStory import com.example.submissionaplikasistory.datasource.model.ListStoryItem import com.example.submissionaplikasistory.di.Injection import com.example.submissionaplikasistory.utils.Resources import com.example.submissionaplikasistory.utils.dataStore import com.example.submissionaplikasistory.view.viewmodel.StoryViewModel import com.example.submissionaplikasistory.view.viewmodel.UserViewModel import com.google.android.gms.maps.CameraUpdate import com.google.android.gms.maps.model.LatLngBounds import com.google.android.gms.maps.model.MapStyleOptions import com.google.gson.Gson import com.google.gson.reflect.TypeToken class MapsCoverageStoryActivity : AppCompatActivity(), OnMapReadyCallback { private lateinit var mMap: GoogleMap private lateinit var binding: ActivityMapsCoverageStoryBinding private val boundsBuilder = LatLngBounds.Builder() private var dataStory: List<EntityDaoStory>? = null private val storyViewModel : StoryViewModel by viewModels { Injection.getStoryRepositoryInstance(applicationContext) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMapsCoverageStoryBinding.inflate(layoutInflater) enableEdgeToEdge() setContentView(binding.root) // Obtain the SupportMapFragment and get notified when the map is ready to be used. val mapFragment = supportFragmentManager .findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) if (intent.hasExtra(MainActivity.INTENT_MAPS)){ fetchDataStory() } } override fun onMapReady(googleMap: GoogleMap) { mMap = googleMap mMap.uiSettings.apply { isMapToolbarEnabled = true isZoomControlsEnabled = true isCompassEnabled = true } dataStory?.let { markLocation(it) } setMapStyle() } private fun setMapStyle() { try { val success = mMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.map_style)) if (!success) { Log.e(TAG, "Style can't implement.") } } catch (exception: Exception) { Log.e(TAG, "Error load message: ", exception) } } private fun fetchDataStory() { val getIntent = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableArrayListExtra(MainActivity.INTENT_MAPS, EntityDaoStory::class.java) else intent.getParcelableExtra(MainActivity.INTENT_MAPS) dataStory = getIntent } private fun markLocation(data: List<EntityDaoStory>) { data.forEach { val latLong = LatLng(it.lat!!, it.lon!!) mMap.addMarker( MarkerOptions() .position(latLong) .title(it.name) .snippet(it.description) ) boundsBuilder.include(latLong) } val bounds = boundsBuilder.build() mMap.animateCamera( CameraUpdateFactory.newLatLngBounds( bounds, resources.displayMetrics.widthPixels, resources.displayMetrics.heightPixels, 300 ) ) } companion object { private const val TAG = "Map Activity" } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/view/home/MapsCoverageStoryActivity.kt
2712161843
package com.example.submissionaplikasistory.view.home import android.Manifest import android.app.Dialog import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import android.view.View import android.widget.Toast import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import com.example.submissionaplikasistory.R import com.example.submissionaplikasistory.databinding.ActivityPostBinding import com.example.submissionaplikasistory.databinding.DialogCustomResponseBinding import com.example.submissionaplikasistory.di.Injection import com.example.submissionaplikasistory.utils.Resources import com.example.submissionaplikasistory.utils.Utils import com.example.submissionaplikasistory.utils.Utils.Companion.reduceImage import com.example.submissionaplikasistory.utils.dataStore import com.example.submissionaplikasistory.view.viewmodel.StoryViewModel import com.example.submissionaplikasistory.view.viewmodel.UserViewModel import okhttp3.MediaType.Companion.toMediaType import okhttp3.MultipartBody import okhttp3.RequestBody.Companion.asRequestBody import okhttp3.RequestBody.Companion.toRequestBody class PostActivity : AppCompatActivity() { private lateinit var binding: ActivityPostBinding private lateinit var bindingDialog: DialogCustomResponseBinding private val storyViewModel: StoryViewModel by viewModels { Injection.getStoryRepositoryInstance(applicationContext) } private val userViewModel: UserViewModel by viewModels { Injection.getUserRepositoryInstance(application.dataStore) } private var currentImage: Uri? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityPostBinding.inflate(layoutInflater) bindingDialog = DialogCustomResponseBinding.inflate(layoutInflater) setContentView(binding.root) val dialog = Utils.dialogInstance(this) if (!checkPermission()) { requestPermission.launch(Manifest.permission.CAMERA) } supportActionBar?.title = resources.getString(R.string.add_new_story) storyViewModel.postResult.observe(this) { when (it) { is Resources.Loading -> { binding.loading.visibility = View.VISIBLE } is Resources.OnFailure -> { binding.loading.visibility = View.GONE dialog.show() dialog.setContentView(bindingDialog.root) showSnackBar (it.message, dialog, false, bindingDialog) } is Resources.OnSuccess -> { binding.loading.visibility = View.GONE dialog.show() dialog.setContentView(bindingDialog.root) it.data.message?.let { it1 -> showSnackBar(it1, dialog, true, bindingDialog) } } } } binding.apply { btnCamera.setOnClickListener { openCamera() } btnGallery.setOnClickListener { openGallery() } userViewModel.getUserSession().observe(this@PostActivity) { value -> buttonAdd.setOnClickListener { uploadImage(value.token) } } } } private fun showSnackBar(messages: String, dialog: Dialog, isSuccess: Boolean, bindingDialog: DialogCustomResponseBinding) { dialog.setCancelable(false) if (isSuccess) { bindingDialog.apply { message.text = messages imageStatus.setImageResource(R.drawable.icon_check) actionButton.text = ContextCompat.getString(this@PostActivity, R.string.show_post) actionButton.setOnClickListener { dialog.dismiss() this@PostActivity.finish() } } } else { bindingDialog.apply { imageStatus.setImageResource(R.drawable.icon_close) message.text = messages actionButton.text = ContextCompat.getString(this@PostActivity, R.string.back) actionButton.setOnClickListener { dialog.dismiss() } } } } private fun uploadImage(token: String?) { binding.loading.visibility = View.VISIBLE if (token != null && currentImage != null) { val fileImage = Utils.uriToFile(currentImage!!, this@PostActivity).reduceImage() val tokenUser = token val description = binding.edAddDescription.text?.toString()?.trim() val requestBodyDescription = description?.toRequestBody("text/plain".toMediaType()) val requestImageBody = fileImage.asRequestBody("image/*".toMediaType()) val multipartImage = MultipartBody.Part.createFormData( "photo", fileImage.name, requestImageBody ) if (requestBodyDescription != null) { storyViewModel.postStory(tokenUser, requestBodyDescription, multipartImage) } } else { Toast.makeText(this@PostActivity, resources.getString(R.string.warning), Toast.LENGTH_SHORT).show() } } private fun openCamera() { currentImage = Utils.getImageUri(this@PostActivity) requestOpenCamera.launch(currentImage) } private fun checkPermission() = ContextCompat.checkSelfPermission( this, Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED private val requestPermission = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { if (it) { Toast.makeText(this@PostActivity, resources.getString(R.string.granted), Toast.LENGTH_SHORT).show() } else { Toast.makeText(this@PostActivity, resources.getString(R.string.denied), Toast.LENGTH_SHORT).show() } } private val requestOpenCamera = registerForActivityResult( ActivityResultContracts.TakePicture() ) { if (it) { showImage() } } private fun openGallery() { requestOpenGallery.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) } private val requestOpenGallery = registerForActivityResult( ActivityResultContracts.PickVisualMedia() ) { if (it != null) { currentImage = it showImage() } } private fun showImage() { currentImage?.let { binding.ivImagePost.setImageURI(it) } } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/view/home/PostActivity.kt
286526891
package com.example.submissionaplikasistory.view import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.app.Dialog import android.os.Bundle import android.view.View import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import com.example.submissionaplikasistory.R import com.example.submissionaplikasistory.databinding.ActivityRegisterBinding import com.example.submissionaplikasistory.databinding.DialogCustomResponseBinding import com.example.submissionaplikasistory.di.Injection import com.example.submissionaplikasistory.utils.Resources import com.example.submissionaplikasistory.utils.Utils import com.example.submissionaplikasistory.utils.dataStore import com.example.submissionaplikasistory.view.viewmodel.UserViewModel class RegisterActivity : AppCompatActivity() { private lateinit var binding: ActivityRegisterBinding private lateinit var dialogBinding: DialogCustomResponseBinding private val userViewModel: UserViewModel by viewModels { Injection.getUserRepositoryInstance(application.dataStore) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() binding = ActivityRegisterBinding.inflate(layoutInflater) dialogBinding = DialogCustomResponseBinding.inflate(layoutInflater) setContentView(binding.root) showAnimation() val customDialog = Utils.dialogInstance(this) userViewModel.getRegisterResponseResult.observe(this) { when (it) { is Resources.Loading -> { binding.loadingProcess.visibility = View.VISIBLE } is Resources.OnFailure -> { binding.loadingProcess.visibility = View.GONE customDialog.show() customDialog.setContentView(dialogBinding.root) dialogAction(dialogBinding, false, customDialog, it.message) } is Resources.OnSuccess -> { binding.loadingProcess.visibility = View.GONE it.data.message?.let { value -> customDialog.show() customDialog.setContentView(dialogBinding.root) dialogAction(dialogBinding, true, customDialog, value) } } } } binding.btnRegister.setOnClickListener { actionRegister() } } private fun actionRegister() { val name = binding.edRegisterName.text.toString().trim() val email = binding.edRegisterEmail.text.toString().trim() val password = binding.edRegisterPassword.text.toString().trim() userViewModel.requestRegisterAccountStory(name, email, password) } private fun dialogAction(dialogCustomResponseBinding: DialogCustomResponseBinding, isSuccess: Boolean, dialog: Dialog, messages: String) { dialog.setCancelable(false) if (isSuccess) { dialogCustomResponseBinding.apply { message.text = messages imageStatus.setImageResource(R.drawable.icon_check) actionButton.text = ContextCompat.getString(this@RegisterActivity, R.string.login) actionButton.setOnClickListener { dialog.dismiss() this@RegisterActivity.finish() } } } else { dialogCustomResponseBinding.apply { imageStatus.setImageResource(R.drawable.icon_close) message.text = messages actionButton.text = ContextCompat.getString(this@RegisterActivity, R.string.back) actionButton.setOnClickListener { dialog.dismiss() } } } } private fun showAnimation() { ObjectAnimator.ofFloat(binding.dicodingBanner, View.TRANSLATION_X, -20f, 20f).apply { duration = 50000 repeatCount = ObjectAnimator.INFINITE repeatMode = ObjectAnimator.REVERSE }.start() val labelName = ObjectAnimator.ofFloat(binding.nameIdentifier, View.ALPHA, 1f).setDuration(1000) val labelEmail = ObjectAnimator.ofFloat(binding.emailIdentifier, View.ALPHA, 1f).setDuration(1000) val labelPassword = ObjectAnimator.ofFloat(binding.passwordIdentifier, View.ALPHA, 1f).setDuration(1000) val email = ObjectAnimator.ofFloat(binding.emailLayout, View.ALPHA, 1f).setDuration(1000) val password = ObjectAnimator.ofFloat(binding.passwordLayout, View.ALPHA, 1f).setDuration(1000) val name = ObjectAnimator.ofFloat(binding.nameLayout, View.ALPHA, 1f).setDuration(1000) val button = ObjectAnimator.ofFloat(binding.btnRegister, View.ALPHA, 1f).setDuration(1000) val tName = AnimatorSet().apply { playTogether(labelName, name) } val tEmail = AnimatorSet().apply { playTogether(labelEmail, email) } val tPassword = AnimatorSet().apply { playTogether(labelPassword, password) } AnimatorSet().apply { playSequentially(tName, tEmail, tPassword, button) }.start() } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/view/RegisterActivity.kt
123396635
package com.example.submissionaplikasistory.view.adapter import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.ViewGroup import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.AsyncListDiffer import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.submissionaplikasistory.databinding.ItemPostWidgetBinding import com.example.submissionaplikasistory.datasource.local.EntityDaoStory import com.example.submissionaplikasistory.datasource.model.ListStoryItem class StoryAdapter( val callback: (String?) -> Unit ): PagingDataAdapter<EntityDaoStory, StoryAdapter.StoryViewHolder>(diffUtil) { companion object { val diffUtil = object : DiffUtil.ItemCallback<EntityDaoStory>() { override fun areItemsTheSame( oldItem: EntityDaoStory, newItem: EntityDaoStory ): Boolean { return newItem == oldItem } override fun areContentsTheSame( oldItem: EntityDaoStory, newItem: EntityDaoStory ): Boolean { return newItem.id == oldItem.id } } } class StoryViewHolder(private val binding: ItemPostWidgetBinding): RecyclerView.ViewHolder(binding.root) { fun bind(data: EntityDaoStory, call: (String) -> Unit) { binding.apply { tvItemName.text = data.name tvDate.text = data.createdAt tvDescriptionPost.text = data.description Glide.with(itemView.context) .load(data.photoUrl) .into(ivItemPhoto) itemView.setOnClickListener { call(data.id) } } } } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): StoryViewHolder { val view = ItemPostWidgetBinding.inflate(LayoutInflater.from(parent.context), parent, false) return StoryViewHolder(view) } @SuppressLint("NewApi") override fun onBindViewHolder(holder: StoryViewHolder, position: Int) { val data = getItem(position) if (data != null) { holder.bind(data) { callback(it) } } } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/view/adapter/StoryAdapter.kt
907936509
package com.example.submissionaplikasistory.view.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.view.isVisible import androidx.paging.LoadState import androidx.paging.LoadStateAdapter import androidx.recyclerview.widget.RecyclerView import com.example.submissionaplikasistory.databinding.ItemLoadingBinding class LoadingStateAdapter (private val retry: () -> Unit): LoadStateAdapter<LoadingStateAdapter.LoadingViewHolder>() { class LoadingViewHolder(private val binding: ItemLoadingBinding, retry: () -> Unit) : RecyclerView.ViewHolder(binding.root) { init { binding.retryButton.setOnClickListener { retry.invoke() } } fun bind(loadState: LoadState) { if (loadState is LoadState.Error) { binding.errorMsg.text = loadState.error.localizedMessage } binding.apply { errorMsg.isVisible = loadState is LoadState.Error retryButton.isVisible = loadState is LoadState.Error progressBar.isVisible = loadState is LoadState.Loading } } } override fun onBindViewHolder( holder: LoadingStateAdapter.LoadingViewHolder, loadState: LoadState ) { holder.bind(loadState) } override fun onCreateViewHolder( parent: ViewGroup, loadState: LoadState ): LoadingStateAdapter.LoadingViewHolder { val binding = ItemLoadingBinding.inflate(LayoutInflater.from(parent.context), parent, false) return LoadingViewHolder(binding, retry) } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/view/adapter/LoadingStateAdapter.kt
920480967
package com.example.submissionaplikasistory.view.adapter import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.ViewGroup import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.submissionaplikasistory.databinding.ItemPostWidgetBinding import com.example.submissionaplikasistory.datasource.model.ListStoryItem class StoryAdapter2( val callback: (String?) -> Unit ): PagingDataAdapter<ListStoryItem, StoryAdapter2.StoryViewHolder>(diffUtil) { companion object { private val diffUtil = object : DiffUtil.ItemCallback<ListStoryItem>() { override fun areItemsTheSame( oldItem: ListStoryItem, newItem: ListStoryItem ): Boolean { return newItem == oldItem } override fun areContentsTheSame( oldItem: ListStoryItem, newItem: ListStoryItem ): Boolean { return newItem.id == oldItem.id } } } class StoryViewHolder(private val binding: ItemPostWidgetBinding): RecyclerView.ViewHolder(binding.root) { fun bind(data: ListStoryItem) { println("data $data") binding.apply { tvItemName.text = data.name tvDate.text = data.createdAt tvDescriptionPost.text = data.description Glide.with(itemView.context) .load(data.photoUrl) .into(ivItemPhoto) } } } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): StoryViewHolder { val view = ItemPostWidgetBinding.inflate(LayoutInflater.from(parent.context), parent, false) return StoryViewHolder(view) } @SuppressLint("NewApi") override fun onBindViewHolder(holder: StoryViewHolder, position: Int) { val data = getItem(position) println("adapter $data") if (data != null) { holder.bind(data) holder.itemView.setOnClickListener { callback(data.id) } } } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/view/adapter/StoryAdapter2.kt
1912780198
package com.example.submissionaplikasistory.view import android.annotation.SuppressLint import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.content.Intent import android.os.Build import android.widget.RemoteViews import android.widget.Toast import androidx.core.net.toUri import com.example.submissionaplikasistory.R import com.example.submissionaplikasistory.view.service.StackWidgetService /** * Implementation of App Widget functionality. */ class PostWidget : AppWidgetProvider() { override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { // There may be multiple widgets active, so update all of them for (appWidgetId in appWidgetIds) { updateAppWidget(context, appWidgetManager, appWidgetId) } } @SuppressLint("StringFormatMatches") override fun onReceive(context: Context?, intent: Intent?) { super.onReceive(context, intent) if (intent?.action != null ) { if (intent.action == TOAST_ACTION) { val viewIndex = intent.getStringExtra(EXTRA_ITEM) Toast.makeText(context, context?.getString(R.string.pick_stack_widget, viewIndex), Toast.LENGTH_SHORT).show() } } } companion object { private const val TOAST_ACTION = "com.unknown.submission_aplikasi_story.TOAST.ACTION" const val EXTRA_ITEM = "com.unknown.submission_aplikasi_story.EXTRA_ITEM" private fun updateAppWidget( context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int ) { val intent = Intent(context, StackWidgetService::class.java) intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) intent.data = intent.toUri(Intent.URI_INTENT_SCHEME).toUri() val views = RemoteViews(context.packageName, R.layout.post_widget) views.setRemoteAdapter(R.id.stack_view, intent) views.setEmptyView(R.id.stack_view, R.id.empty_view) val toastIntent = Intent(context, PostWidget::class.java) toastIntent.action = TOAST_ACTION toastIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) val toastPending = PendingIntent.getBroadcast( context, 0, toastIntent, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE } else 0 ) views.setPendingIntentTemplate(R.id.stack_view , toastPending) appWidgetManager.updateAppWidget(appWidgetId, views) } } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/view/PostWidget.kt
3320441260
package com.example.submissionaplikasistory.view.service import android.content.Context import android.content.Intent import android.widget.RemoteViews import android.widget.RemoteViewsService import androidx.core.os.bundleOf import androidx.paging.PagingSource import com.bumptech.glide.Glide import com.example.submissionaplikasistory.R import com.example.submissionaplikasistory.datasource.local.DaoService import com.example.submissionaplikasistory.datasource.local.DaoStoryConfig import com.example.submissionaplikasistory.datasource.local.EntityDaoStory import com.example.submissionaplikasistory.view.PostWidget import kotlinx.coroutines.runBlocking internal class StackRemoteViewsFactory(private val context: Context) : RemoteViewsService.RemoteViewsFactory { private var currentList = listOf<EntityDaoStory>() private lateinit var connection: DaoService override fun onCreate() { connection = DaoStoryConfig.getInstance(context).getService() } override fun onDataSetChanged() { fetchData() } fun fetchData() { runBlocking { currentList = connection.getStoryListEntityDaoStory() println(currentList) } } override fun onDestroy() { } override fun getCount() = currentList.size override fun getViewAt(position: Int): RemoteViews { val rv = RemoteViews(context.packageName, R.layout.item_stack_widget) try { val bitmap = Glide.with(context) .asBitmap() .load(currentList[position].photoUrl) .submit() .get() rv.setImageViewBitmap(R.id.widget_iamgeView, bitmap) } catch (e: Exception) { println(e) } val extras = bundleOf( PostWidget.EXTRA_ITEM to position ) val fillInIntent = Intent() fillInIntent.putExtras(extras) rv.setOnClickFillInIntent(R.id.widget_iamgeView, fillInIntent) return rv } override fun getLoadingView(): RemoteViews? = null override fun getViewTypeCount(): Int = 1 override fun getItemId(position: Int): Long = 0 override fun hasStableIds(): Boolean = false }
Story-App/app/src/main/java/com/example/submissionaplikasistory/view/service/StackRemoteViewsFactory.kt
1796208337
package com.example.submissionaplikasistory.view.service import android.content.Intent import android.widget.RemoteViewsService class StackWidgetService : RemoteViewsService() { override fun onGetViewFactory(intent: Intent?): RemoteViewsFactory { return StackRemoteViewsFactory(this.application) } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/view/service/StackWidgetService.kt
3300015241
package com.example.submissionaplikasistory.view import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import com.example.submissionaplikasistory.R import com.example.submissionaplikasistory.databinding.ActivityLoginBinding import com.example.submissionaplikasistory.databinding.DialogCustomResponseBinding import com.example.submissionaplikasistory.di.Injection import com.example.submissionaplikasistory.utils.Resources import com.example.submissionaplikasistory.utils.dataStore import com.example.submissionaplikasistory.view.home.MainActivity import com.example.submissionaplikasistory.view.viewmodel.UserViewModel class LoginActivity : AppCompatActivity() { private lateinit var binding: ActivityLoginBinding private lateinit var dialogBinding: DialogCustomResponseBinding private val userViewModel: UserViewModel by viewModels{ Injection.getUserRepositoryInstance(application.dataStore) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() binding = ActivityLoginBinding.inflate(layoutInflater) dialogBinding = DialogCustomResponseBinding.inflate(layoutInflater) setContentView(binding.root) binding.apply { directRegister.setOnClickListener { goRegister() } btnLogin.setOnClickListener { actionLogin() } } showAnimation() userViewModel.getLoginResponseResult.observe(this) { when (it) { is Resources.Loading -> { binding.loading.visibility = View.VISIBLE } is Resources.OnFailure -> { binding.loading.visibility = View.GONE showToast(false) } is Resources.OnSuccess -> { binding.loading.visibility = View.GONE it.data.loginResult.let { userViewModel.saveUserSession(it!!) } it.data.message?.let { value -> showToast(true) } goToHomeScreen() } } } } private fun showAnimation() { ObjectAnimator.ofFloat(binding.bannerImageLogin, View.TRANSLATION_X, -20f, 20f).apply { duration = 5000 repeatCount =ObjectAnimator.INFINITE repeatMode = ObjectAnimator.REVERSE }.start() val greeting = ObjectAnimator.ofFloat(binding.greetingLayout, View.ALPHA, 1f).setDuration(1000) val labelEmail = ObjectAnimator.ofFloat(binding.tvEmail, View.ALPHA, 1f).setDuration(1000) val labelPassword = ObjectAnimator.ofFloat(binding.tvPassword, View.ALPHA, 1f).setDuration(1000) val email = ObjectAnimator.ofFloat(binding.emailLayout, View.ALPHA, 1f).setDuration(1000) val password = ObjectAnimator.ofFloat(binding.passwordLayout, View.ALPHA, 1f).setDuration(1000) val register_access = ObjectAnimator.ofFloat(binding.accountLayout, View.ALPHA, 1f).setDuration(1000) val button_signin = ObjectAnimator.ofFloat(binding.btnLogin, View.ALPHA, 1f).setDuration(1000) val tEmail = AnimatorSet().apply { playTogether(labelEmail, email) } val tPassword = AnimatorSet().apply { playTogether(labelPassword, password) } AnimatorSet().apply { playSequentially(greeting, tEmail, tPassword, register_access, button_signin) }.start() } private fun showToast(isLogged: Boolean) { if (isLogged) { Toast.makeText(this@LoginActivity, resources.getString(R.string.value_login), Toast.LENGTH_SHORT).show() } else { Toast.makeText(this@LoginActivity, resources.getString(R.string.warning), Toast.LENGTH_SHORT).show() } } private fun actionLogin() { val email = binding.edLoginEmail.text.toString().trim() val password = binding.edLoginPassword.text.toString().trim() userViewModel.requestLoginAccountStory(email, password) } private fun goRegister() { val intent = Intent(this, RegisterActivity::class.java) startActivity(intent) } private fun goToHomeScreen() { val intent = Intent(this, MainActivity::class.java) startActivity(intent) finishAffinity() } }
Story-App/app/src/main/java/com/example/submissionaplikasistory/view/LoginActivity.kt
4045906238
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.reader import android.os.Bundle import android.view.View import android.view.WindowInsets import org.readium.r2.testapp.utils.clearPadding import org.readium.r2.testapp.utils.padSystemUi import org.readium.r2.testapp.utils.showSystemUi /** * Adds fullscreen support to the ReaderActivity */ open class VisualReaderActivity : ReaderActivity() { private val visualReaderFragment: VisualReaderFragment get() = readerFragment as VisualReaderFragment override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Without this, activity_reader_container receives the insets only once, // although we need a call every time the reader is hidden window.decorView.setOnApplyWindowInsetsListener { view, insets -> val newInsets = view.onApplyWindowInsets(insets) binding.activityContainer.dispatchApplyWindowInsets(newInsets) } binding.activityContainer.setOnApplyWindowInsetsListener { container, insets -> updateSystemUiPadding(container, insets) insets } supportFragmentManager.addOnBackStackChangedListener { updateSystemUiVisibility() } } override fun onStart() { super.onStart() updateSystemUiVisibility() } private fun updateSystemUiVisibility() { if (visualReaderFragment.isHidden) showSystemUi() else visualReaderFragment.updateSystemUiVisibility() // Seems to be required to adjust padding when transitioning from the outlines to the screen reader binding.activityContainer.requestApplyInsets() } private fun updateSystemUiPadding(container: View, insets: WindowInsets) { if (visualReaderFragment.isHidden) container.padSystemUi(insets, this) else container.clearPadding() } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/reader/VisualReaderActivity.kt
1631228564
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.reader import android.graphics.PointF import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.commitNow import androidx.lifecycle.ViewModelProvider import org.readium.r2.navigator.Navigator import org.readium.r2.navigator.pdf.PdfNavigatorFragment import org.readium.r2.shared.fetcher.Resource import org.readium.r2.shared.publication.Link import org.readium.r2.shared.publication.Publication import org.readium.r2.testapp.R import org.readium.r2.testapp.utils.toggleSystemUi class PdfReaderFragment : VisualReaderFragment(), PdfNavigatorFragment.Listener { override lateinit var model: ReaderViewModel override lateinit var navigator: Navigator private lateinit var publication: Publication override fun onCreate(savedInstanceState: Bundle?) { ViewModelProvider(requireActivity()).get(ReaderViewModel::class.java).let { model = it publication = it.publication } childFragmentManager.fragmentFactory = PdfNavigatorFragment.createFactory(publication, model.initialLocation, this) super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = super.onCreateView(inflater, container, savedInstanceState) if (savedInstanceState == null) { childFragmentManager.commitNow { add(R.id.fragment_reader_container, PdfNavigatorFragment::class.java, Bundle(), NAVIGATOR_FRAGMENT_TAG) } } navigator = childFragmentManager.findFragmentByTag(NAVIGATOR_FRAGMENT_TAG)!! as Navigator return view } override fun onResourceLoadFailed(link: Link, error: Resource.Exception) { val message = when (error) { is Resource.Exception.OutOfMemory -> "The PDF is too large to be rendered on this device" else -> "Failed to render this PDF" } Toast.makeText(requireActivity(), message, Toast.LENGTH_LONG).show() // There's nothing we can do to recover, so we quit the Activity. requireActivity().finish() } override fun onTap(point: PointF): Boolean { val viewWidth = requireView().width val leftRange = 0.0..(0.2 * viewWidth) when { leftRange.contains(point.x) -> navigator.goBackward() leftRange.contains(viewWidth - point.x) -> navigator.goForward() else -> requireActivity().toggleSystemUi() } return true } companion object { const val NAVIGATOR_FRAGMENT_TAG = "navigator" } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/reader/PdfReaderFragment.kt
2955192478
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.reader import android.content.Context import android.graphics.Color import android.os.Bundle import androidx.annotation.ColorInt import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import androidx.paging.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import org.readium.r2.navigator.Decoration import org.readium.r2.navigator.ExperimentalDecorator import org.readium.r2.shared.Search import org.readium.r2.shared.UserException import org.readium.r2.shared.publication.Locator import org.readium.r2.shared.publication.LocatorCollection import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.PublicationId import org.readium.r2.shared.publication.services.search.SearchIterator import org.readium.r2.shared.publication.services.search.SearchTry import org.readium.r2.shared.publication.services.search.search import org.readium.r2.shared.util.Try import org.readium.r2.testapp.bookshelf.BookRepository import org.readium.r2.testapp.db.BookDatabase import org.readium.r2.testapp.domain.model.Highlight import org.readium.r2.testapp.search.SearchPagingSource import org.readium.r2.testapp.utils.EventChannel @OptIn(Search::class, ExperimentalDecorator::class) class ReaderViewModel(context: Context, arguments: ReaderContract.Input) : ViewModel() { val publication: Publication = arguments.publication val initialLocation: Locator? = arguments.initialLocator val channel = EventChannel(Channel<Event>(Channel.BUFFERED), viewModelScope) val fragmentChannel = EventChannel(Channel<FeedbackEvent>(Channel.BUFFERED), viewModelScope) val bookId = arguments.bookId private val repository: BookRepository val publicationId: PublicationId get() = bookId.toString() init { val booksDao = BookDatabase.getDatabase(context).booksDao() repository = BookRepository(booksDao) } fun saveProgression(locator: Locator) = viewModelScope.launch { repository.saveProgression(locator, bookId) } fun getBookmarks() = repository.bookmarksForBook(bookId) fun insertBookmark(locator: Locator) = viewModelScope.launch { val id = repository.insertBookmark(bookId, publication, locator) if (id != -1L) { fragmentChannel.send(FeedbackEvent.BookmarkSuccessfullyAdded) } else { fragmentChannel.send(FeedbackEvent.BookmarkFailed) } } fun deleteBookmark(id: Long) = viewModelScope.launch { repository.deleteBookmark(id) } // Highlights val highlights: Flow<List<Highlight>> by lazy { repository.highlightsForBook(bookId) } /** * Database ID of the active highlight for the current highlight pop-up. This is used to show * the highlight decoration in an "active" state. */ var activeHighlightId = MutableStateFlow<Long?>(null) /** * Current state of the highlight decorations. * * It will automatically be updated when the highlights database table or the current * [activeHighlightId] change. */ val highlightDecorations: Flow<List<Decoration>> by lazy { highlights.combine(activeHighlightId) { highlights, activeId -> highlights.flatMap { highlight -> highlight.toDecorations(isActive = (highlight.id == activeId)) } } } /** * Creates a list of [Decoration] for the receiver [Highlight]. */ private fun Highlight.toDecorations(isActive: Boolean): List<Decoration> { fun createDecoration(idSuffix: String, style: Decoration.Style) = Decoration( id = "$id-$idSuffix", locator = locator, style = style, extras = Bundle().apply { // We store the highlight's database ID in the extras bundle, for easy retrieval // later. You can store arbitrary information in the bundle. putLong("id", id) } ) return listOfNotNull( // Decoration for the actual highlight / underline. createDecoration( idSuffix = "highlight", style = when (style) { Highlight.Style.HIGHLIGHT -> Decoration.Style.Highlight(tint = tint, isActive = isActive) Highlight.Style.UNDERLINE -> Decoration.Style.Underline(tint = tint, isActive = isActive) } ), // Additional page margin icon decoration, if the highlight has an associated note. annotation.takeIf { it.isNotEmpty() }?.let { createDecoration( idSuffix = "annotation", style = DecorationStyleAnnotationMark(tint = tint), ) } ) } suspend fun highlightById(id: Long): Highlight? = repository.highlightById(id) fun addHighlight(locator: Locator, style: Highlight.Style, @ColorInt tint: Int, annotation: String = "") = viewModelScope.launch { repository.addHighlight(bookId, style, tint, locator, annotation) } fun updateHighlightAnnotation(id: Long, annotation: String) = viewModelScope.launch { repository.updateHighlightAnnotation(id, annotation) } fun updateHighlightStyle(id: Long, style: Highlight.Style, @ColorInt tint: Int) = viewModelScope.launch { repository.updateHighlightStyle(id, style, tint) } fun deleteHighlight(id: Long) = viewModelScope.launch { repository.deleteHighlight(id) } fun search(query: String) = viewModelScope.launch { if (query == lastSearchQuery) return@launch lastSearchQuery = query _searchLocators.value = emptyList() searchIterator = publication.search(query) .onFailure { channel.send(Event.Failure(it)) } .getOrNull() pagingSourceFactory.invalidate() channel.send(Event.StartNewSearch) } fun cancelSearch() = viewModelScope.launch { _searchLocators.value = emptyList() searchIterator?.close() searchIterator = null pagingSourceFactory.invalidate() } val searchLocators: StateFlow<List<Locator>> get() = _searchLocators private var _searchLocators = MutableStateFlow<List<Locator>>(emptyList()) /** * Maps the current list of search result locators into a list of [Decoration] objects to * underline the results in the navigator. */ val searchDecorations: Flow<List<Decoration>> by lazy { searchLocators.map { it.mapIndexed { index, locator -> Decoration( // The index in the search result list is a suitable Decoration ID, as long as // we clear the search decorations between two searches. id = index.toString(), locator = locator, style = Decoration.Style.Underline(tint = Color.RED) ) } } } private var lastSearchQuery: String? = null private var searchIterator: SearchIterator? = null private val pagingSourceFactory = InvalidatingPagingSourceFactory { SearchPagingSource(listener = PagingSourceListener()) } inner class PagingSourceListener : SearchPagingSource.Listener { override suspend fun next(): SearchTry<LocatorCollection?> { val iterator = searchIterator ?: return Try.success(null) return iterator.next().onSuccess { _searchLocators.value += (it?.locators ?: emptyList()) } } } val searchResult: Flow<PagingData<Locator>> = Pager(PagingConfig(pageSize = 20), pagingSourceFactory = pagingSourceFactory) .flow.cachedIn(viewModelScope) class Factory(private val context: Context, private val arguments: ReaderContract.Input) : ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel?> create(modelClass: Class<T>): T = modelClass.getDeclaredConstructor(Context::class.java, ReaderContract.Input::class.java) .newInstance(context.applicationContext, arguments) } sealed class Event { object OpenOutlineRequested : Event() object OpenDrmManagementRequested : Event() object StartNewSearch : Event() class Failure(val error: UserException) : Event() } sealed class FeedbackEvent { object BookmarkSuccessfullyAdded : FeedbackEvent() object BookmarkFailed : FeedbackEvent() } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/reader/ReaderViewModel.kt
189057322
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.reader import android.content.Context import android.graphics.Color import android.graphics.PointF import android.os.Bundle import android.view.* import android.view.accessibility.AccessibilityManager import android.view.inputmethod.InputMethodManager import android.widget.ImageView import androidx.annotation.ColorInt import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.toBitmap import androidx.fragment.app.FragmentResultListener import androidx.fragment.app.commit import androidx.fragment.app.commitNow import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.delay import org.readium.r2.navigator.ExperimentalDecorator import org.readium.r2.navigator.Navigator import org.readium.r2.navigator.epub.EpubNavigatorFragment import org.readium.r2.navigator.html.HtmlDecorationTemplate import org.readium.r2.navigator.html.HtmlDecorationTemplates import org.readium.r2.navigator.html.toCss import org.readium.r2.shared.APPEARANCE_REF import org.readium.r2.shared.ReadiumCSSName import org.readium.r2.shared.SCROLL_REF import org.readium.r2.shared.publication.Locator import org.readium.r2.shared.publication.Publication import org.readium.r2.testapp.R import org.readium.r2.testapp.R2App import org.readium.r2.testapp.epub.UserSettings import org.readium.r2.testapp.search.SearchFragment import org.readium.r2.testapp.tts.ScreenReaderContract import org.readium.r2.testapp.tts.ScreenReaderFragment import org.readium.r2.testapp.utils.extensions.toDataUrl import org.readium.r2.testapp.utils.toggleSystemUi import java.net.URL @OptIn(ExperimentalDecorator::class) class EpubReaderFragment : VisualReaderFragment(), EpubNavigatorFragment.Listener { override lateinit var model: ReaderViewModel override lateinit var navigator: Navigator private lateinit var publication: Publication lateinit var navigatorFragment: EpubNavigatorFragment private lateinit var menuScreenReader: MenuItem private lateinit var menuSearch: MenuItem lateinit var menuSearchView: SearchView private lateinit var userSettings: UserSettings private var isScreenReaderVisible = false private var isSearchViewIconified = true // Accessibility private var isExploreByTouchEnabled = false override fun onCreate(savedInstanceState: Bundle?) { check(R2App.isServerStarted) val activity = requireActivity() if (savedInstanceState != null) { isScreenReaderVisible = savedInstanceState.getBoolean(IS_SCREEN_READER_VISIBLE_KEY) isSearchViewIconified = savedInstanceState.getBoolean(IS_SEARCH_VIEW_ICONIFIED) } ViewModelProvider(requireActivity()).get(ReaderViewModel::class.java).let { model = it publication = it.publication } val baseUrl = checkNotNull(requireArguments().getString(BASE_URL_ARG)) childFragmentManager.fragmentFactory = EpubNavigatorFragment.createFactory( publication = publication, baseUrl = baseUrl, initialLocator = model.initialLocation, listener = this, config = EpubNavigatorFragment.Configuration().apply { // Register the HTML template for our custom [DecorationStyleAnnotationMark]. decorationTemplates[DecorationStyleAnnotationMark::class] = annotationMarkTemplate(activity) selectionActionModeCallback = customSelectionActionModeCallback } ) childFragmentManager.setFragmentResultListener( SearchFragment::class.java.name, this, FragmentResultListener { _, result -> menuSearch.collapseActionView() result.getParcelable<Locator>(SearchFragment::class.java.name)?.let { navigatorFragment.go(it) } } ) childFragmentManager.setFragmentResultListener( ScreenReaderContract.REQUEST_KEY, this, FragmentResultListener { _, result -> val locator = ScreenReaderContract.parseResult(result).locator if (locator.href != navigator.currentLocator.value.href) { navigator.go(locator) } } ) setHasOptionsMenu(true) super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = super.onCreateView(inflater, container, savedInstanceState) val navigatorFragmentTag = getString(R.string.epub_navigator_tag) if (savedInstanceState == null) { childFragmentManager.commitNow { add(R.id.fragment_reader_container, EpubNavigatorFragment::class.java, Bundle(), navigatorFragmentTag) } } navigator = childFragmentManager.findFragmentByTag(navigatorFragmentTag) as Navigator navigatorFragment = navigator as EpubNavigatorFragment return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val activity = requireActivity() userSettings = UserSettings(navigatorFragment.preferences, activity, publication.userSettingsUIPreset) // This is a hack to draw the right background color on top and bottom blank spaces navigatorFragment.lifecycleScope.launchWhenStarted { val appearancePref = navigatorFragment.preferences.getInt(APPEARANCE_REF, 0) val backgroundsColors = mutableListOf("#ffffff", "#faf4e8", "#000000") navigatorFragment.resourcePager.setBackgroundColor(Color.parseColor(backgroundsColors[appearancePref])) } } override fun onResume() { super.onResume() val activity = requireActivity() userSettings.resourcePager = navigatorFragment.resourcePager // If TalkBack or any touch exploration service is activated we force scroll mode (and // override user preferences) val am = activity.getSystemService(AppCompatActivity.ACCESSIBILITY_SERVICE) as AccessibilityManager isExploreByTouchEnabled = am.isTouchExplorationEnabled if (isExploreByTouchEnabled) { // Preset & preferences adapted publication.userSettingsUIPreset[ReadiumCSSName.ref(SCROLL_REF)] = true navigatorFragment.preferences.edit().putBoolean(SCROLL_REF, true).apply() //overriding user preferences userSettings.saveChanges() lifecycleScope.launchWhenResumed { delay(500) userSettings.updateViewCSS(SCROLL_REF) } } else { if (publication.cssStyle != "cjk-vertical") { publication.userSettingsUIPreset.remove(ReadiumCSSName.ref(SCROLL_REF)) } } } override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) { super.onCreateOptionsMenu(menu, menuInflater) menuInflater.inflate(R.menu.menu_epub, menu) menuScreenReader = menu.findItem(R.id.screen_reader) menuSearch = menu.findItem(R.id.search) menuSearchView = menuSearch.actionView as SearchView connectSearch() if (!isSearchViewIconified) menuSearch.expandActionView() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putBoolean(IS_SCREEN_READER_VISIBLE_KEY, isScreenReaderVisible) outState.putBoolean(IS_SEARCH_VIEW_ICONIFIED, isSearchViewIconified) } private fun connectSearch() { menuSearch.setOnActionExpandListener(object : MenuItem.OnActionExpandListener { override fun onMenuItemActionExpand(item: MenuItem?): Boolean { if (isSearchViewIconified) { // It is not a state restoration. showSearchFragment() } isSearchViewIconified = false return true } override fun onMenuItemActionCollapse(item: MenuItem?): Boolean { isSearchViewIconified = true childFragmentManager.popBackStack() menuSearchView.clearFocus() return true } }) menuSearchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { model.search(query) menuSearchView.clearFocus() return false } override fun onQueryTextChange(s: String): Boolean { return false } }) menuSearchView.findViewById<ImageView>(R.id.search_close_btn).setOnClickListener { menuSearchView.requestFocus() model.cancelSearch() menuSearchView.setQuery("", false) (activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.showSoftInput( this.view, InputMethodManager.SHOW_FORCED ) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (super.onOptionsItemSelected(item)) { return true } return when (item.itemId) { R.id.settings -> { userSettings.userSettingsPopUp().showAsDropDown(requireActivity().findViewById(R.id.settings), 0, 0, Gravity.END) true } R.id.search -> { super.onOptionsItemSelected(item) } android.R.id.home -> { menuSearch.collapseActionView() true } R.id.screen_reader -> { if (isScreenReaderVisible) { closeScreenReaderFragment() } else { showScreenReaderFragment() } true } else -> false } } override fun onTap(point: PointF): Boolean { requireActivity().toggleSystemUi() return true } private fun showSearchFragment() { childFragmentManager.commit { childFragmentManager.findFragmentByTag(SEARCH_FRAGMENT_TAG)?.let { remove(it) } add(R.id.fragment_reader_container, SearchFragment::class.java, Bundle(), SEARCH_FRAGMENT_TAG) hide(navigatorFragment) addToBackStack(SEARCH_FRAGMENT_TAG) } } private fun showScreenReaderFragment() { menuScreenReader.title = resources.getString(R.string.epubactivity_read_aloud_stop) isScreenReaderVisible = true val arguments = ScreenReaderContract.createArguments(navigator.currentLocator.value) childFragmentManager.commit { add(R.id.fragment_reader_container, ScreenReaderFragment::class.java, arguments) hide(navigatorFragment) addToBackStack(null) } } private fun closeScreenReaderFragment() { menuScreenReader.title = resources.getString(R.string.epubactivity_read_aloud_start) isScreenReaderVisible = false childFragmentManager.popBackStack() } companion object { private const val BASE_URL_ARG = "baseUrl" private const val SEARCH_FRAGMENT_TAG = "search" private const val IS_SCREEN_READER_VISIBLE_KEY = "isScreenReaderVisible" private const val IS_SEARCH_VIEW_ICONIFIED = "isSearchViewIconified" fun newInstance(baseUrl: URL): EpubReaderFragment { return EpubReaderFragment().apply { arguments = Bundle().apply { putString(BASE_URL_ARG, baseUrl.toString()) } } } } } /** * Example of an HTML template for a custom Decoration Style. * * This one will display a tinted "pen" icon in the page margin to show that a highlight has an * associated note. */ @OptIn(ExperimentalDecorator::class) private fun annotationMarkTemplate(context: Context, @ColorInt defaultTint: Int = Color.YELLOW): HtmlDecorationTemplate { // Converts the pen icon to a base 64 data URL, to be embedded in the decoration stylesheet. // Alternatively, serve the image with the local HTTP server and use its URL. val imageUrl = ContextCompat.getDrawable(context, R.drawable.ic_pen) ?.toBitmap()?.toDataUrl() requireNotNull(imageUrl) val className = "testapp-annotation-mark" return HtmlDecorationTemplate( layout = HtmlDecorationTemplate.Layout.BOUNDS, width = HtmlDecorationTemplate.Width.PAGE, element = { decoration -> val style = decoration.style as? DecorationStyleAnnotationMark val tint = style?.tint ?: defaultTint // Using `data-activable=1` prevents the whole decoration container from being // clickable. Only the icon will respond to activation events. """ <div><div data-activable="1" class="$className" style="background-color: ${tint.toCss()} !important"/></div>" """ }, stylesheet = """ .$className { float: left; margin-left: 8px; width: 30px; height: 30px; border-radius: 50%; background: url('$imageUrl') no-repeat center; background-size: auto 50%; opacity: 0.8; } """ ) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/reader/EpubReaderFragment.kt
1888624092
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.reader import android.app.Activity import android.os.Build import android.os.Bundle import android.view.WindowManager import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentResultListener import androidx.fragment.app.commit import androidx.fragment.app.commitNow import androidx.lifecycle.ViewModelProvider import org.readium.r2.shared.publication.Locator import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.allAreAudio import org.readium.r2.shared.publication.allAreBitmap import org.readium.r2.shared.util.mediatype.MediaType import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.ActivityReaderBinding import org.readium.r2.testapp.drm.DrmManagementContract import org.readium.r2.testapp.drm.DrmManagementFragment import org.readium.r2.testapp.outline.OutlineContract import org.readium.r2.testapp.outline.OutlineFragment /* * An activity to read a publication * * This class can be used as it is or be inherited from. */ open class ReaderActivity : AppCompatActivity() { protected lateinit var readerFragment: BaseReaderFragment private lateinit var modelFactory: ReaderViewModel.Factory private lateinit var publication: Publication lateinit var binding: ActivityReaderBinding override fun onCreate(savedInstanceState: Bundle?) { val inputData = ReaderContract.parseIntent(this) modelFactory = ReaderViewModel.Factory(applicationContext, inputData) super.onCreate(savedInstanceState) binding = ActivityReaderBinding.inflate(layoutInflater) val view = binding.root setContentView(view) ViewModelProvider(this).get(ReaderViewModel::class.java).let { model -> publication = model.publication model.channel.receive(this) { handleReaderFragmentEvent(it) } } if (savedInstanceState == null) { if (publication.type == Publication.TYPE.EPUB) { val baseUrl = requireNotNull(inputData.baseUrl) readerFragment = EpubReaderFragment.newInstance(baseUrl) supportFragmentManager.commitNow { replace(R.id.activity_container, readerFragment, READER_FRAGMENT_TAG) } } else { val readerClass: Class<out Fragment> = when { publication.readingOrder.all { it.mediaType == MediaType.PDF } -> PdfReaderFragment::class.java publication.readingOrder.allAreBitmap -> ImageReaderFragment::class.java publication.readingOrder.allAreAudio -> AudioReaderFragment::class.java else -> throw IllegalArgumentException("Cannot render publication") } supportFragmentManager.commitNow { replace(R.id.activity_container, readerClass, Bundle(), READER_FRAGMENT_TAG) } } } readerFragment = supportFragmentManager.findFragmentByTag(READER_FRAGMENT_TAG) as BaseReaderFragment supportFragmentManager.setFragmentResultListener( OutlineContract.REQUEST_KEY, this, FragmentResultListener { _, result -> val locator = OutlineContract.parseResult(result).destination closeOutlineFragment(locator) } ) supportFragmentManager.setFragmentResultListener( DrmManagementContract.REQUEST_KEY, this, FragmentResultListener { _, result -> if (DrmManagementContract.parseResult(result).hasReturned) finish() } ) supportFragmentManager.addOnBackStackChangedListener { updateActivityTitle() } // Add support for display cutout. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES } } override fun onStart() { super.onStart() updateActivityTitle() } private fun updateActivityTitle() { title = when (supportFragmentManager.fragments.last()) { is OutlineFragment -> publication.metadata.title is DrmManagementFragment -> getString(R.string.title_fragment_drm_management) else -> null } } override fun getDefaultViewModelProviderFactory(): ViewModelProvider.Factory { return modelFactory } override fun finish() { setResult(Activity.RESULT_OK, intent) super.finish() } private fun handleReaderFragmentEvent(event: ReaderViewModel.Event) { when(event) { is ReaderViewModel.Event.OpenOutlineRequested -> showOutlineFragment() is ReaderViewModel.Event.OpenDrmManagementRequested -> showDrmManagementFragment() is ReaderViewModel.Event.Failure -> { Toast.makeText(this, event.error.getUserMessage(this), Toast.LENGTH_LONG).show() } } } private fun showOutlineFragment() { supportFragmentManager.commit { add(R.id.activity_container, OutlineFragment::class.java, Bundle(), OUTLINE_FRAGMENT_TAG) hide(readerFragment) addToBackStack(null) } } private fun closeOutlineFragment(locator: Locator) { readerFragment.go(locator, true) supportFragmentManager.popBackStack() } private fun showDrmManagementFragment() { supportFragmentManager.commit { add(R.id.activity_container, DrmManagementFragment::class.java, Bundle(), DRM_FRAGMENT_TAG) hide(readerFragment) addToBackStack(null) } } companion object { const val READER_FRAGMENT_TAG = "reader" const val OUTLINE_FRAGMENT_TAG = "outline" const val DRM_FRAGMENT_TAG = "drm" } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/reader/ReaderActivity.kt
591461666
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.reader import android.app.AlertDialog import android.content.Context import android.graphics.Color import android.graphics.RectF import android.os.Bundle import android.view.* import android.view.inputmethod.InputMethodManager import android.widget.* import androidx.annotation.ColorInt import androidx.annotation.IdRes import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.parcelize.Parcelize import org.readium.r2.lcp.lcpLicense import org.readium.r2.navigator.* import org.readium.r2.navigator.util.BaseActionModeCallback import org.readium.r2.shared.publication.Locator import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.services.isProtected import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentReaderBinding import org.readium.r2.testapp.domain.model.Highlight /* * Base reader fragment class * * Provides common menu items and saves last location on stop. */ @OptIn(ExperimentalDecorator::class) abstract class BaseReaderFragment : Fragment() { protected abstract val model: ReaderViewModel protected abstract val navigator: Navigator override fun onCreate(savedInstanceState: Bundle?) { setHasOptionsMenu(true) super.onCreate(savedInstanceState) model.fragmentChannel.receive(this) { event -> val message = when (event) { is ReaderViewModel.FeedbackEvent.BookmarkFailed -> R.string.bookmark_exists is ReaderViewModel.FeedbackEvent.BookmarkSuccessfullyAdded -> R.string.bookmark_added } Toast.makeText(requireContext(), getString(message), Toast.LENGTH_SHORT).show() } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val viewScope = viewLifecycleOwner.lifecycleScope navigator.currentLocator .onEach { model.saveProgression(it) } .launchIn(viewScope) (navigator as? DecorableNavigator)?.let { navigator -> navigator.addDecorationListener("highlights", decorationListener) model.highlightDecorations .onEach { navigator.applyDecorations(it, "highlights") } .launchIn(viewScope) model.searchDecorations .onEach { navigator.applyDecorations(it, "search") } .launchIn(viewScope) } } override fun onDestroyView() { (navigator as? DecorableNavigator)?.removeDecorationListener(decorationListener) super.onDestroyView() } override fun onHiddenChanged(hidden: Boolean) { super.onHiddenChanged(hidden) setMenuVisibility(!hidden) requireActivity().invalidateOptionsMenu() } override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.menu_reader, menu) menu.findItem(R.id.drm).isVisible = model.publication.lcpLicense != null } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.toc -> { model.channel.send(ReaderViewModel.Event.OpenOutlineRequested) true } R.id.bookmark -> { model.insertBookmark(navigator.currentLocator.value) true } R.id.drm -> { model.channel.send(ReaderViewModel.Event.OpenDrmManagementRequested) true } else -> false } } fun go(locator: Locator, animated: Boolean) = navigator.go(locator, animated) // DecorableNavigator.Listener private val decorationListener by lazy { DecorationListener() } inner class DecorationListener : DecorableNavigator.Listener { override fun onDecorationActivated(event: DecorableNavigator.OnActivatedEvent): Boolean { val decoration = event.decoration // We stored the highlight's database ID in the `Decoration.extras` bundle, for // easy retrieval. You can store arbitrary information in the bundle. val id = decoration.extras.getLong("id") .takeIf { it > 0 } ?: return false // This listener will be called when tapping on any of the decorations in the // "highlights" group. To differentiate between the page margin icon and the // actual highlight, we check for the type of `decoration.style`. But you could // use any other information, including the decoration ID or the extras bundle. if (decoration.style is DecorationStyleAnnotationMark) { showAnnotationPopup(id) } else { event.rect?.let { rect -> val isUnderline = (decoration.style is Decoration.Style.Underline) showHighlightPopup(rect, style = if (isUnderline) Highlight.Style.UNDERLINE else Highlight.Style.HIGHLIGHT, highlightId = id ) } } return true } } // Highlights private var popupWindow: PopupWindow? = null private var mode: ActionMode? = null // Available tint colors for highlight and underline annotations. private val highlightTints = mapOf<@IdRes Int, @ColorInt Int>( R.id.red to Color.rgb(247, 124, 124), R.id.green to Color.rgb(173, 247, 123), R.id.blue to Color.rgb(124, 198, 247), R.id.yellow to Color.rgb(249, 239, 125), R.id.purple to Color.rgb(182, 153, 255), ) val customSelectionActionModeCallback: ActionMode.Callback by lazy { SelectionActionModeCallback() } private inner class SelectionActionModeCallback : BaseActionModeCallback() { override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { mode.menuInflater.inflate(R.menu.menu_action_mode, menu) if (navigator is DecorableNavigator) { menu.findItem(R.id.highlight).isVisible = true menu.findItem(R.id.underline).isVisible = true menu.findItem(R.id.note).isVisible = true } return true } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { when (item.itemId) { R.id.highlight -> showHighlightPopupWithStyle(Highlight.Style.HIGHLIGHT) R.id.underline -> showHighlightPopupWithStyle(Highlight.Style.UNDERLINE) R.id.note -> showAnnotationPopup() else -> return false } mode.finish() return true } } private fun showHighlightPopupWithStyle(style: Highlight.Style) = viewLifecycleOwner.lifecycleScope.launchWhenResumed { // Get the rect of the current selection to know where to position the highlight // popup. (navigator as? SelectableNavigator)?.currentSelection()?.rect?.let { selectionRect -> showHighlightPopup(selectionRect, style) } } private fun showHighlightPopup(rect: RectF, style: Highlight.Style, highlightId: Long? = null) = viewLifecycleOwner.lifecycleScope.launchWhenResumed { if (popupWindow?.isShowing == true) return@launchWhenResumed model.activeHighlightId.value = highlightId val isReverse = (rect.top > 60) val popupView = layoutInflater.inflate( if (isReverse) R.layout.view_action_mode_reverse else R.layout.view_action_mode, null, false ) popupView.measure( View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) ) popupWindow = PopupWindow( popupView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ).apply { isFocusable = true setOnDismissListener { model.activeHighlightId.value = null } } val x = rect.left val y = if (isReverse) rect.top else rect.bottom + rect.height() popupWindow?.showAtLocation(popupView, Gravity.NO_GRAVITY, x.toInt(), y.toInt()) val highlight = highlightId?.let { model.highlightById(it) } popupView.run { findViewById<View>(R.id.notch).run { setX(rect.left * 2) } fun selectTint(view: View) { val tint = highlightTints[view.id] ?: return selectHighlightTint(highlightId, style, tint) } findViewById<View>(R.id.red).setOnClickListener(::selectTint) findViewById<View>(R.id.green).setOnClickListener(::selectTint) findViewById<View>(R.id.blue).setOnClickListener(::selectTint) findViewById<View>(R.id.yellow).setOnClickListener(::selectTint) findViewById<View>(R.id.purple).setOnClickListener(::selectTint) findViewById<View>(R.id.annotation).setOnClickListener { popupWindow?.dismiss() showAnnotationPopup(highlightId) } findViewById<View>(R.id.del).run { visibility = if (highlight != null) View.VISIBLE else View.GONE setOnClickListener { highlightId?.let { model.deleteHighlight(highlightId) } popupWindow?.dismiss() mode?.finish() } } } } private fun selectHighlightTint(highlightId: Long? = null, style: Highlight.Style, @ColorInt tint: Int) = viewLifecycleOwner.lifecycleScope.launchWhenResumed { if (highlightId != null) { model.updateHighlightStyle(highlightId, style, tint) } else { (navigator as? SelectableNavigator)?.let { navigator -> navigator.currentSelection()?.let { selection -> model.addHighlight(locator = selection.locator, style = style, tint = tint) } navigator.clearSelection() } } popupWindow?.dismiss() mode?.finish() } private fun showAnnotationPopup(highlightId: Long? = null) = viewLifecycleOwner.lifecycleScope.launchWhenResumed { val activity = activity ?: return@launchWhenResumed val view = layoutInflater.inflate(R.layout.popup_note, null, false) val note = view.findViewById<EditText>(R.id.note) val alert = AlertDialog.Builder(activity) .setView(view) .create() fun dismiss() { alert.dismiss() mode?.finish() (activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow(note.applicationWindowToken, InputMethodManager.HIDE_NOT_ALWAYS) } with(view) { val highlight = highlightId?.let { model.highlightById(it) } if (highlight != null) { note.setText(highlight.annotation) findViewById<View>(R.id.sidemark).setBackgroundColor(highlight.tint) findViewById<TextView>(R.id.select_text).text = highlight.locator.text.highlight findViewById<TextView>(R.id.positive).setOnClickListener { val text = note.text.toString() model.updateHighlightAnnotation(highlight.id, annotation = text) dismiss() } } else { val tint = highlightTints.values.random() findViewById<View>(R.id.sidemark).setBackgroundColor(tint) val navigator = navigator as? SelectableNavigator ?: return@launchWhenResumed val selection = navigator.currentSelection() ?: return@launchWhenResumed navigator.clearSelection() findViewById<TextView>(R.id.select_text).text = selection.locator.text.highlight findViewById<TextView>(R.id.positive).setOnClickListener { model.addHighlight(locator = selection.locator, style = Highlight.Style.HIGHLIGHT, tint = tint, annotation = note.text.toString()) dismiss() } } findViewById<TextView>(R.id.negative).setOnClickListener { dismiss() } } alert.show() } } /** * Decoration Style for a page margin icon. * * This is an example of a custom Decoration Style declaration. */ @Parcelize @OptIn(ExperimentalDecorator::class) data class DecorationStyleAnnotationMark(@ColorInt val tint: Int) : Decoration.Style
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/reader/BaseReaderFragment.kt
1218000085
package org.readium.r2.testapp.reader import android.media.AudioManager import android.os.Bundle import android.text.format.DateUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.SeekBar import androidx.activity.addCallback import androidx.fragment.app.activityViewModels import androidx.lifecycle.asLiveData import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.launch import org.readium.r2.navigator.ExperimentalAudiobook import org.readium.r2.navigator.MediaNavigator import org.readium.r2.navigator.Navigator import org.readium.r2.navigator.media.MediaService import org.readium.r2.shared.publication.services.cover import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentAudiobookBinding import kotlin.time.Duration import kotlin.time.DurationUnit import kotlin.time.ExperimentalTime @OptIn(ExperimentalAudiobook::class, ExperimentalTime::class) class AudioReaderFragment : BaseReaderFragment() { override val model: ReaderViewModel by activityViewModels() override val navigator: Navigator get() = mediaNavigator private lateinit var mediaNavigator: MediaNavigator private lateinit var mediaService: MediaService.Connection private var binding: FragmentAudiobookBinding? = null private var isSeeking = false override fun onCreate(savedInstanceState: Bundle?) { val context = requireContext() mediaService = MediaService.connect(AudiobookService::class.java) // Get the currently playing navigator from the media service, if it is the same pub ID. // Otherwise, ask to switch to the new publication. mediaNavigator = mediaService.currentNavigator.value?.takeIf { it.publicationId == model.publicationId } ?: mediaService.getNavigator(context, model.publication, model.publicationId, model.initialLocation) mediaNavigator.play() super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentAudiobookBinding.inflate(inflater, container, false) return binding?.root } override fun onDestroyView() { binding = null super.onDestroyView() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding?.run { publicationTitle.text = model.publication.metadata.title viewLifecycleOwner.lifecycleScope.launch { model.publication.cover()?.let { coverView.setImageBitmap(it) } } mediaNavigator.playback.asLiveData().observe(viewLifecycleOwner) { playback -> playPause.setImageResource( if (playback.isPlaying) R.drawable.ic_baseline_pause_24 else R.drawable.ic_baseline_play_arrow_24 ) with(playback.timeline) { if (!isSeeking) { timelineBar.max = duration?.inWholeSeconds?.toInt() ?: 0 timelineBar.progress = position.inWholeSeconds.toInt() buffered?.let { timelineBar.secondaryProgress = it.inWholeSeconds.toInt() } } timelinePosition.text = position.formatElapsedTime() timelineDuration.text = duration?.formatElapsedTime() ?: "" } } timelineBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {} override fun onStartTrackingTouch(p0: SeekBar?) { isSeeking = true } override fun onStopTrackingTouch(p0: SeekBar?) { isSeeking = false p0?.let { seekBar -> mediaNavigator.seekTo(Duration.seconds(seekBar.progress)) } } }) playPause.setOnClickListener { mediaNavigator.playPause() } skipForward.setOnClickListener { mediaNavigator.goForward() } skipBackward.setOnClickListener { mediaNavigator.goBackward() } } } override fun onResume() { super.onResume() activity?.volumeControlStream = AudioManager.STREAM_MUSIC } } @ExperimentalTime private fun Duration.formatElapsedTime(): String = DateUtils.formatElapsedTime(toLong(DurationUnit.SECONDS))
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/reader/AudioReaderFragment.kt
325696290
/* * Module: r2-testapp-kotlin * Developers: Quentin Gliosca * * Copyright (c) 2020. European Digital Reading Lab. All rights reserved. * Licensed to the Readium Foundation under one or more contributor license agreements. * Use of this source code is governed by a BSD-style license which is detailed in the * LICENSE file present in the project repository where this source code is maintained. */ package org.readium.r2.testapp.reader import android.app.Activity import android.content.Context import android.content.Intent import androidx.activity.result.contract.ActivityResultContract import org.readium.r2.shared.extensions.destroyPublication import org.readium.r2.shared.extensions.getPublication import org.readium.r2.shared.extensions.putPublication import org.readium.r2.shared.publication.Locator import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.util.mediatype.MediaType import java.io.File import java.net.URL class ReaderContract : ActivityResultContract<ReaderContract.Input, ReaderContract.Output>() { data class Input( val mediaType: MediaType?, val publication: Publication, val bookId: Long, val initialLocator: Locator? = null, val baseUrl: URL? = null ) data class Output( val publication: Publication ) override fun createIntent(context: Context, input: Input): Intent { val intent = Intent( context, when (input.mediaType) { MediaType.ZAB, MediaType.READIUM_AUDIOBOOK, MediaType.READIUM_AUDIOBOOK_MANIFEST, MediaType.LCP_PROTECTED_AUDIOBOOK -> ReaderActivity::class.java MediaType.EPUB, MediaType.READIUM_WEBPUB_MANIFEST, MediaType.READIUM_WEBPUB, MediaType.CBZ, MediaType.DIVINA, MediaType.DIVINA_MANIFEST, MediaType.PDF, MediaType.LCP_PROTECTED_PDF -> VisualReaderActivity::class.java else -> throw IllegalArgumentException("Unknown [mediaType]") } ) return intent.apply { putPublication(input.publication) putExtra("bookId", input.bookId) putExtra("baseUrl", input.baseUrl?.toString()) putExtra("locator", input.initialLocator) } } override fun parseResult(resultCode: Int, intent: Intent?): Output? { if (intent == null) return null intent.destroyPublication(null) return Output( publication = intent.getPublication(null), ) } companion object { fun parseIntent(activity: Activity): Input = with(activity) { Input( mediaType = null, publication = intent.getPublication(activity), bookId = intent.getLongExtra("bookId", -1), initialLocator = intent.getParcelableExtra("locator"), baseUrl = intent.getStringExtra("baseUrl")?.let { URL(it) } ) } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/reader/ReaderContract.kt
3743930740
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.reader import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowInsets import android.widget.FrameLayout import androidx.fragment.app.Fragment import org.readium.r2.navigator.DecorableNavigator import org.readium.r2.navigator.ExperimentalDecorator import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentReaderBinding import org.readium.r2.testapp.utils.clearPadding import org.readium.r2.testapp.utils.hideSystemUi import org.readium.r2.testapp.utils.padSystemUi import org.readium.r2.testapp.utils.showSystemUi /* * Adds fullscreen support to the BaseReaderFragment */ abstract class VisualReaderFragment : BaseReaderFragment() { private lateinit var navigatorFragment: Fragment private var _binding: FragmentReaderBinding? = null val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentReaderBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) navigatorFragment = navigator as Fragment childFragmentManager.addOnBackStackChangedListener { updateSystemUiVisibility() } binding.fragmentReaderContainer.setOnApplyWindowInsetsListener { container, insets -> updateSystemUiPadding(container, insets) insets } } override fun onDestroyView() { _binding = null super.onDestroyView() } fun updateSystemUiVisibility() { if (navigatorFragment.isHidden) requireActivity().showSystemUi() else requireActivity().hideSystemUi() requireView().requestApplyInsets() } private fun updateSystemUiPadding(container: View, insets: WindowInsets) { if (navigatorFragment.isHidden) { container.padSystemUi(insets, requireActivity()) } else { container.clearPadding() } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/reader/VisualReaderFragment.kt
1404378585
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.reader import android.app.PendingIntent import android.content.Intent import android.os.Build import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import org.readium.r2.navigator.ExperimentalAudiobook import org.readium.r2.navigator.media.MediaService import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.PublicationId import org.readium.r2.testapp.bookshelf.BookRepository import org.readium.r2.testapp.db.BookDatabase @OptIn(ExperimentalAudiobook::class, ExperimentalCoroutinesApi::class) class AudiobookService : MediaService() { private val books by lazy { BookRepository(BookDatabase.getDatabase(this).booksDao()) } override fun onCreate() { super.onCreate() // Save the current locator in the database. We can't do this in the [ReaderActivity] since // the playback can continue in the background without any [Activity]. launch { navigator .flatMapLatest { navigator -> navigator ?: return@flatMapLatest emptyFlow() navigator.currentLocator .map { Pair(navigator.publicationId, it) } } .collect { (pubId, locator) -> books.saveProgression(locator, pubId.toLong()) } } } override suspend fun onCreateNotificationIntent(publicationId: PublicationId, publication: Publication): PendingIntent? { val bookId = publicationId.toLong() val book = books.get(bookId) ?: return null var flags = PendingIntent.FLAG_UPDATE_CURRENT if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { flags = flags or PendingIntent.FLAG_IMMUTABLE } val intent = ReaderContract().createIntent(this, ReaderContract.Input( mediaType = book.mediaType(), publication = publication, bookId = bookId, )) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) return PendingIntent.getActivity(this, 0, intent, flags) } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/reader/AudiobookService.kt
3695904369
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.reader import android.graphics.PointF import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.commitNow import androidx.lifecycle.ViewModelProvider import org.readium.r2.navigator.Navigator import org.readium.r2.navigator.image.ImageNavigatorFragment import org.readium.r2.shared.publication.Publication import org.readium.r2.testapp.R import org.readium.r2.testapp.utils.toggleSystemUi class ImageReaderFragment : VisualReaderFragment(), ImageNavigatorFragment.Listener { override lateinit var model: ReaderViewModel override lateinit var navigator: Navigator private lateinit var publication: Publication override fun onCreate(savedInstanceState: Bundle?) { ViewModelProvider(requireActivity()).get(ReaderViewModel::class.java).let { model = it publication = it.publication } childFragmentManager.fragmentFactory = ImageNavigatorFragment.createFactory(publication, model.initialLocation, this) super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = super.onCreateView(inflater, container, savedInstanceState) if (savedInstanceState == null) { childFragmentManager.commitNow { add(R.id.fragment_reader_container, ImageNavigatorFragment::class.java, Bundle(), NAVIGATOR_FRAGMENT_TAG) } } navigator = childFragmentManager.findFragmentByTag(NAVIGATOR_FRAGMENT_TAG)!! as Navigator return view } override fun onTap(point: PointF): Boolean { val viewWidth = requireView().width val leftRange = 0.0..(0.2 * viewWidth) when { leftRange.contains(point.x) -> navigator.goBackward(animated = true) leftRange.contains(viewWidth - point.x) -> navigator.goForward(animated = true) else -> requireActivity().toggleSystemUi() } return true } companion object { const val NAVIGATOR_FRAGMENT_TAG = "navigator" } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/reader/ImageReaderFragment.kt
102167718
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.drm import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import org.readium.r2.lcp.LcpLicense import org.readium.r2.lcp.MaterialRenewListener import org.readium.r2.shared.util.Try import java.util.* class LcpManagementViewModel( private val lcpLicense: LcpLicense, private val renewListener: LcpLicense.RenewListener, ) : DrmManagementViewModel() { class Factory( private val lcpLicense: LcpLicense, private val renewListener: LcpLicense.RenewListener, ) : ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel?> create(modelClass: Class<T>): T = modelClass.getDeclaredConstructor(LcpLicense::class.java, LcpLicense.RenewListener::class.java) .newInstance(lcpLicense, renewListener) } override val type: String = "LCP" override val state: String? get() = lcpLicense.status?.status?.rawValue override val provider: String? get() = lcpLicense.license.provider override val issued: Date? get() = lcpLicense.license.issued override val updated: Date? get() = lcpLicense.license.updated override val start: Date? get() = lcpLicense.license.rights.start override val end: Date? get() = lcpLicense.license.rights.end override val copiesLeft: String = lcpLicense.charactersToCopyLeft ?.let { "$it characters" } ?: super.copiesLeft override val printsLeft: String = lcpLicense.pagesToPrintLeft ?.let { "$it pages" } ?: super.printsLeft override val canRenewLoan: Boolean get() = lcpLicense.canRenewLoan override suspend fun renewLoan(fragment: Fragment): Try<Date?, Exception> { return lcpLicense.renewLoan(renewListener) } override val canReturnPublication: Boolean get() = lcpLicense.canReturnPublication override suspend fun returnPublication(): Try<Unit, Exception> = lcpLicense.returnPublication() }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/drm/LcpManagementViewModel.kt
3495228888
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.drm import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.setFragmentResult import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import kotlinx.coroutines.launch import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import org.readium.r2.lcp.MaterialRenewListener import org.readium.r2.lcp.lcpLicense import org.readium.r2.shared.UserException import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentDrmManagementBinding import org.readium.r2.testapp.reader.ReaderViewModel import timber.log.Timber import java.util.* class DrmManagementFragment : Fragment() { private lateinit var model: DrmManagementViewModel private var _binding: FragmentDrmManagementBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val publication = ViewModelProvider(requireActivity()).get(ReaderViewModel::class.java).publication val license = checkNotNull(publication.lcpLicense) val renewListener = MaterialRenewListener( license = license, caller = this, fragmentManager = this.childFragmentManager ) val modelFactory = LcpManagementViewModel.Factory(license, renewListener) model = ViewModelProvider(this, modelFactory).get(LcpManagementViewModel::class.java) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentDrmManagementBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Information binding.drmValueLicenseType.text = model.type binding.drmValueState.text = model.state binding.drmValueProvider.text = model.provider binding.drmValueIssued.text = model.issued.toFormattedString() binding.drmValueUpdated.text = model.updated.toFormattedString() // Rights binding.drmValuePrintsLeft.text = model.printsLeft binding.drmValueCopiesLeft.text = model.copiesLeft val datesVisibility = if (model.start != null && model.end != null && model.start != model.end) View.VISIBLE else View.GONE binding.drmStart.visibility = datesVisibility binding.drmValueStart.text = model.start.toFormattedString() binding.drmEnd.visibility = datesVisibility binding.drmValueEnd.text = model.end?.toFormattedString() // Actions binding.drmLabelActions.visibility = if (model.canRenewLoan || model.canReturnPublication) View.VISIBLE else View.GONE binding.drmButtonRenew.run { visibility = if (model.canRenewLoan) View.VISIBLE else View.GONE setOnClickListener { onRenewLoanClicked() } } binding.drmButtonReturn.run { visibility = if (model.canReturnPublication) View.VISIBLE else View.GONE setOnClickListener { onReturnPublicationClicked() } } } private fun onRenewLoanClicked() { lifecycleScope.launch { model.renewLoan(this@DrmManagementFragment) .onSuccess { newDate -> binding.drmValueEnd.text = newDate.toFormattedString() }.onFailure { exception -> exception.toastUserMessage(requireView()) } } } private fun onReturnPublicationClicked() { MaterialAlertDialogBuilder(requireContext()) .setTitle(getString(R.string.return_publication)) .setNegativeButton(getString(R.string.cancel)) { dialog, _ -> dialog.cancel() } .setPositiveButton(getString(R.string.return_button)) { _, _ -> lifecycleScope.launch { model.returnPublication() .onSuccess { val result = DrmManagementContract.createResult(hasReturned = true) setFragmentResult(DrmManagementContract.REQUEST_KEY, result) }.onFailure { exception -> exception.toastUserMessage(requireView()) } } } .show() } override fun onDestroyView() { _binding = null super.onDestroyView() } } private fun Date?.toFormattedString() = DateTime(this).toString(DateTimeFormat.shortDateTime()).orEmpty() // FIXME: the toast is drawn behind the navigation bar private fun Exception.toastUserMessage(view: View) { if (this is UserException) Snackbar.make(view, getUserMessage(view.context), Snackbar.LENGTH_LONG).show() Timber.d(this) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/drm/DrmManagementFragment.kt
2084927548
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.drm import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import org.readium.r2.shared.util.Try import java.util.* abstract class DrmManagementViewModel : ViewModel() { abstract val type: String open val state: String? = null open val provider: String? = null open val issued: Date? = null open val updated: Date? = null open val start: Date? = null open val end: Date? = null open val copiesLeft: String = "unlimited" open val printsLeft: String = "unlimited" open val canRenewLoan: Boolean = false open suspend fun renewLoan(fragment: Fragment): Try<Date?, Exception> = Try.failure(Exception("Renewing a loan is not supported")) open val canReturnPublication: Boolean = false open suspend fun returnPublication(): Try<Unit, Exception> = Try.failure(Exception("Returning a publication is not supported")) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/drm/DrmManagementViewModel.kt
2306533786
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.drm import android.os.Bundle object DrmManagementContract { private const val HAS_RETURNED_KEY = "hasReturned" val REQUEST_KEY: String = DrmManagementContract::class.java.name data class Result(val hasReturned: Boolean) fun createResult(hasReturned: Boolean): Bundle { return Bundle().apply { putBoolean(HAS_RETURNED_KEY, hasReturned) } } fun parseResult(result: Bundle): Result { val hasReturned = requireNotNull(result.getBoolean(HAS_RETURNED_KEY)) return Result(hasReturned) } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/drm/DrmManagementContract.kt
3886605322
/* * Module: r2-testapp-kotlin * Developers: Aferdita Muriqi, Clément Baumann * * Copyright (c) 2018. European Digital Reading Lab. All rights reserved. * Licensed to the Readium Foundation under one or more contributor license agreements. * Use of this source code is governed by a BSD-style license which is detailed in the * LICENSE file present in the project repository where this source code is maintained. */ package org.readium.r2.testapp.opds import android.content.Context import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ensureActive import kotlinx.coroutines.withContext import org.readium.r2.shared.util.Try import org.readium.r2.shared.util.flatMap import org.readium.r2.shared.util.http.* import org.readium.r2.shared.util.mediatype.MediaType import org.readium.r2.testapp.BuildConfig.DEBUG import timber.log.Timber import java.io.File import java.io.FileOutputStream import java.util.* class OPDSDownloader(context: Context) { private val useExternalFileDir = useExternalDir(context) private val rootDir: String = if (useExternalFileDir) { context.getExternalFilesDir(null)?.path + "/" } else { context.filesDir.path + "/" } private fun useExternalDir(context: Context): Boolean { val properties = Properties() val inputStream = context.assets.open("configs/config.properties") properties.load(inputStream) return properties.getProperty("useExternalFileDir", "false")!!.toBoolean() } suspend fun publicationUrl( url: String ): Try<Pair<String, String>, Exception> { val fileName = UUID.randomUUID().toString() if (DEBUG) Timber.i("download url %s", url) return DefaultHttpClient().download(HttpRequest(url), File(rootDir, fileName)) .flatMap { try { if (DEBUG) Timber.i("response url %s", it.url) if (DEBUG) Timber.i("download destination %s %s %s", "%s%s", rootDir, fileName) if (url == it.url) { Try.success(Pair(rootDir + fileName, fileName)) } else { redirectedDownload(it.url, fileName) } } catch (e: Exception) { Try.failure(e) } } } private suspend fun redirectedDownload( responseUrl: String, fileName: String ): Try<Pair<String, String>, Exception> { return DefaultHttpClient().download(HttpRequest(responseUrl), File(rootDir, fileName)) .flatMap { if (DEBUG) Timber.i("response url %s", it.url) if (DEBUG) Timber.i("download destination %s %s %s", "%s%s", rootDir, fileName) try { Try.success(Pair(rootDir + fileName, fileName)) } catch (e: Exception) { Try.failure(e) } } } private suspend fun HttpClient.download( request: HttpRequest, destination: File, ): HttpTry<HttpResponse> = try { stream(request).flatMap { res -> withContext(Dispatchers.IO) { res.body.use { input -> FileOutputStream(destination).use { output -> val buf = ByteArray(1024 * 8) var n: Int var downloadedBytes = 0 while (-1 != input.read(buf).also { n = it }) { ensureActive() downloadedBytes += n output.write(buf, 0, n) } } } var response = res.response if (response.mediaType.matches(MediaType.BINARY)) { response = response.copy( mediaType = MediaType.ofFile(destination) ?: response.mediaType ) } Try.success(response) } } } catch (e: Exception) { Try.failure(HttpException.wrap(e)) } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/opds/OPDSDownloader.kt
2467585669
/* * Module: r2-testapp-kotlin * Developers: Aferdita Muriqi, Clément Baumann * * Copyright (c) 2018. European Digital Reading Lab. All rights reserved. * Licensed to the Readium Foundation under one or more contributor license agreements. * Use of this source code is governed by a BSD-style license which is detailed in the * LICENSE file present in the project repository where this source code is maintained. */ package org.readium.r2.testapp.opds import android.content.Context import android.util.TypedValue import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import kotlin.math.max class GridAutoFitLayoutManager : GridLayoutManager { private var mColumnWidth: Int = 0 private var mColumnWidthChanged = true private var mWidthChanged = true private var mWidth: Int = 0 constructor(context: Context, columnWidth: Int) : super(context, 1) { setColumnWidth(checkedColumnWidth(context, columnWidth)) }/* Initially set spanCount to 1, will be changed automatically later. */ constructor(context: Context, columnWidth: Int, orientation: Int, reverseLayout: Boolean) : super(context, 1, orientation, reverseLayout) { setColumnWidth(checkedColumnWidth(context, columnWidth)) }/* Initially set spanCount to 1, will be changed automatically later. */ private fun checkedColumnWidth(context: Context, columnWidth: Int): Int { var width = columnWidth width = if (width <= 0) { TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, sColumnWidth.toFloat(), context.resources.displayMetrics).toInt() } else { TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, width.toFloat(), context.resources.displayMetrics).toInt() } return width } private fun setColumnWidth(newColumnWidth: Int) { if (newColumnWidth > 0 && newColumnWidth != mColumnWidth) { mColumnWidth = newColumnWidth mColumnWidthChanged = true } } override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State) { val width = width val height = height if (width != mWidth) { mWidthChanged = true mWidth = width } if (mColumnWidthChanged && mColumnWidth > 0 && width > 0 && height > 0 || mWidthChanged) { val totalSpace: Int = if (orientation == LinearLayoutManager.VERTICAL) { width - paddingRight - paddingLeft } else { height - paddingTop - paddingBottom } val spanCount = max(1, totalSpace / mColumnWidth) setSpanCount(spanCount) mColumnWidthChanged = false mWidthChanged = false } super.onLayoutChildren(recycler, state) } companion object { private const val sColumnWidth = 200 // assume cell width of 200dp } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/opds/GridAutoFitLayoutManager.kt
3931919757
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.google.android.material.bottomnavigation.BottomNavigationView import org.readium.r2.testapp.bookshelf.BookshelfViewModel class MainActivity : AppCompatActivity() { private lateinit var navController: NavController private lateinit var viewModel: BookshelfViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) viewModel = ViewModelProvider(this).get(BookshelfViewModel::class.java) intent.data?.let { viewModel.importPublicationFromUri(it) } val navView: BottomNavigationView = findViewById(R.id.nav_view) val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment navController = navHostFragment.navController val appBarConfiguration = AppBarConfiguration( setOf( R.id.navigation_bookshelf, R.id.navigation_catalog_list, R.id.navigation_about ) ) setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) } override fun onSupportNavigateUp(): Boolean { return navController.navigateUp() || super.onSupportNavigateUp() } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/MainActivity.kt
1324370418
/* * Module: r2-testapp-kotlin * Developers: Aferdita Muriqi, Clément Baumann * * Copyright (c) 2018. European Digital Reading Lab. All rights reserved. * Licensed to the Readium Foundation under one or more contributor license agreements. * Use of this source code is governed by a BSD-style license which is detailed in the * LICENSE file present in the project repository where this source code is maintained. */ package org.readium.r2.testapp import android.annotation.SuppressLint import android.app.Application import android.content.ContentResolver import android.content.Context import org.readium.r2.shared.Injectable import org.readium.r2.streamer.server.Server import org.readium.r2.testapp.BuildConfig.DEBUG import timber.log.Timber import java.io.IOException import java.net.ServerSocket import java.util.* class R2App : Application() { override fun onCreate() { super.onCreate() if (DEBUG) Timber.plant(Timber.DebugTree()) val s = ServerSocket(if (DEBUG) 8080 else 0) s.close() server = Server(s.localPort, applicationContext) startServer() R2DIRECTORY = r2Directory } companion object { @SuppressLint("StaticFieldLeak") lateinit var server: Server private set lateinit var R2DIRECTORY: String private set var isServerStarted = false private set } override fun onTerminate() { super.onTerminate() stopServer() } private fun startServer() { if (!server.isAlive) { try { server.start() } catch (e: IOException) { // do nothing if (DEBUG) Timber.e(e) } if (server.isAlive) { // // Add your own resources here // server.loadCustomResource(assets.open("scripts/test.js"), "test.js") // server.loadCustomResource(assets.open("styles/test.css"), "test.css") // server.loadCustomFont(assets.open("fonts/test.otf"), applicationContext, "test.otf") isServerStarted = true } } } private fun stopServer() { if (server.isAlive) { server.stop() isServerStarted = false } } private val r2Directory: String get() { val properties = Properties() val inputStream = applicationContext.assets.open("configs/config.properties") properties.load(inputStream) val useExternalFileDir = properties.getProperty("useExternalFileDir", "false")!!.toBoolean() return if (useExternalFileDir) { applicationContext.getExternalFilesDir(null)?.path + "/" } else { applicationContext.filesDir?.path + "/" } } } val Context.resolver: ContentResolver get() = applicationContext.contentResolver
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/R2App.kt
3154975226
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.bookshelf import androidx.annotation.ColorInt import androidx.lifecycle.LiveData import kotlinx.coroutines.flow.Flow import org.joda.time.DateTime import org.readium.r2.shared.publication.Locator import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.indexOfFirstWithHref import org.readium.r2.shared.util.mediatype.MediaType import org.readium.r2.testapp.db.BooksDao import org.readium.r2.testapp.domain.model.Book import org.readium.r2.testapp.domain.model.Bookmark import org.readium.r2.testapp.domain.model.Highlight import org.readium.r2.testapp.utils.extensions.authorName import java.util.* import org.readium.r2.navigator.epub.Highlight as NavigatorHighlight class BookRepository(private val booksDao: BooksDao) { fun books(): LiveData<List<Book>> = booksDao.getAllBooks() suspend fun get(id: Long) = booksDao.get(id) suspend fun insertBook(href: String, mediaType: MediaType, publication: Publication): Long { val book = Book( creation = DateTime().toDate().time, title = publication.metadata.title, author = publication.metadata.authorName, href = href, identifier = publication.metadata.identifier ?: "", type = mediaType.toString(), progression = "{}" ) return booksDao.insertBook(book) } suspend fun deleteBook(id: Long) = booksDao.deleteBook(id) suspend fun saveProgression(locator: Locator, bookId: Long) = booksDao.saveProgression(locator.toJSON().toString(), bookId) suspend fun insertBookmark(bookId: Long, publication: Publication, locator: Locator): Long { val resource = publication.readingOrder.indexOfFirstWithHref(locator.href)!! val bookmark = Bookmark( creation = DateTime().toDate().time, bookId = bookId, publicationId = publication.metadata.identifier ?: publication.metadata.title, resourceIndex = resource.toLong(), resourceHref = locator.href, resourceType = locator.type, resourceTitle = locator.title.orEmpty(), location = locator.locations.toJSON().toString(), locatorText = Locator.Text().toJSON().toString() ) return booksDao.insertBookmark(bookmark) } fun bookmarksForBook(bookId: Long): LiveData<MutableList<Bookmark>> = booksDao.getBookmarksForBook(bookId) suspend fun deleteBookmark(bookmarkId: Long) = booksDao.deleteBookmark(bookmarkId) suspend fun highlightById(id: Long): Highlight? = booksDao.getHighlightById(id) fun highlightsForBook(bookId: Long): Flow<List<Highlight>> = booksDao.getHighlightsForBook(bookId) suspend fun addHighlight(bookId: Long, style: Highlight.Style, @ColorInt tint: Int, locator: Locator, annotation: String): Long = booksDao.insertHighlight(Highlight(bookId, style, tint, locator, annotation)) suspend fun deleteHighlight(id: Long) = booksDao.deleteHighlight(id) suspend fun updateHighlightAnnotation(id: Long, annotation: String) { booksDao.updateHighlightAnnotation(id, annotation) } suspend fun updateHighlightStyle(id: Long, style: Highlight.Style, @ColorInt tint: Int) { booksDao.updateHighlightStyle(id, style, tint) } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/bookshelf/BookRepository.kt
1201523084
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.bookshelf import android.app.Application import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import androidx.databinding.ObservableBoolean import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.readium.r2.lcp.LcpService import org.readium.r2.shared.Injectable import org.readium.r2.shared.extensions.mediaType import org.readium.r2.shared.extensions.tryOrNull import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.asset.FileAsset import org.readium.r2.shared.publication.services.cover import org.readium.r2.shared.publication.services.isRestricted import org.readium.r2.shared.publication.services.protectionError import org.readium.r2.shared.util.Try import org.readium.r2.shared.util.flatMap import org.readium.r2.shared.util.mediatype.MediaType import org.readium.r2.streamer.Streamer import org.readium.r2.streamer.server.Server import org.readium.r2.testapp.BuildConfig import org.readium.r2.testapp.R2App import org.readium.r2.testapp.db.BookDatabase import org.readium.r2.testapp.domain.model.Book import org.readium.r2.testapp.utils.EventChannel import org.readium.r2.testapp.utils.extensions.copyToTempFile import org.readium.r2.testapp.utils.extensions.moveTo import timber.log.Timber import java.io.File import java.io.FileOutputStream import java.io.IOException import java.net.HttpURLConnection import java.net.URL import java.util.* class BookshelfViewModel(application: Application) : AndroidViewModel(application) { private val r2Application = application private val booksDao = BookDatabase.getDatabase(application).booksDao() private val repository = BookRepository(booksDao) private val preferences = application.getSharedPreferences("org.readium.r2.settings", Context.MODE_PRIVATE) private var server: Server = R2App.server private var lcpService = LcpService(application) ?.let { Try.success(it) } ?: Try.failure(Exception("liblcp is missing on the classpath")) private var streamer = Streamer( application, contentProtections = listOfNotNull( lcpService.getOrNull()?.contentProtection() ) ) private var r2Directory: String = R2App.R2DIRECTORY val channel = EventChannel(Channel<Event>(Channel.BUFFERED), viewModelScope) val showProgressBar = ObservableBoolean() val books = repository.books() fun deleteBook(book: Book) = viewModelScope.launch { book.id?.let { repository.deleteBook(it) } tryOrNull { File(book.href).delete() } tryOrNull { File("${R2App.R2DIRECTORY}covers/${book.id}.png").delete() } } private suspend fun addPublicationToDatabase( href: String, mediaType: MediaType, publication: Publication ): Long { val id = repository.insertBook(href, mediaType, publication) storeCoverImage(publication, id.toString()) return id } fun copySamplesFromAssetsToStorage() = viewModelScope.launch(Dispatchers.IO) { withContext(Dispatchers.IO) { if (!preferences.contains("samples")) { val dir = File(r2Directory) if (!dir.exists()) { dir.mkdirs() } val samples = r2Application.assets.list("Samples")?.filterNotNull().orEmpty() for (element in samples) { val file = r2Application.assets.open("Samples/$element").copyToTempFile(r2Directory) if (file != null) importPublication(file) else if (BuildConfig.DEBUG) error("Unable to load sample into the library") } preferences.edit().putBoolean("samples", true).apply() } } } fun importPublicationFromUri( uri: Uri, sourceUrl: String? = null ) = viewModelScope.launch { showProgressBar.set(true) uri.copyToTempFile(r2Application, r2Directory) ?.let { importPublication(it, sourceUrl) } } private suspend fun importPublication( sourceFile: File, sourceUrl: String? = null ) { val sourceMediaType = sourceFile.mediaType() val publicationAsset: FileAsset = if (sourceMediaType != MediaType.LCP_LICENSE_DOCUMENT) FileAsset(sourceFile, sourceMediaType) else { lcpService .flatMap { it.acquirePublication(sourceFile) } .fold( { val mediaType = MediaType.of(fileExtension = File(it.suggestedFilename).extension) FileAsset(it.localFile, mediaType) }, { tryOrNull { sourceFile.delete() } Timber.d(it) showProgressBar.set(false) channel.send(Event.ImportPublicationFailed(it.message)) return } ) } val mediaType = publicationAsset.mediaType() val fileName = "${UUID.randomUUID()}.${mediaType.fileExtension}" val libraryAsset = FileAsset(File(r2Directory + fileName), mediaType) try { publicationAsset.file.moveTo(libraryAsset.file) } catch (e: Exception) { Timber.d(e) tryOrNull { publicationAsset.file.delete() } showProgressBar.set(false) channel.send(Event.UnableToMovePublication) return } streamer.open(libraryAsset, allowUserInteraction = false, sender = r2Application) .onSuccess { addPublicationToDatabase(libraryAsset.file.path, libraryAsset.mediaType(), it).let { id -> showProgressBar.set(false) if (id != -1L) channel.send(Event.ImportPublicationSuccess) else channel.send(Event.ImportDatabaseFailed) } } .onFailure { tryOrNull { libraryAsset.file.delete() } Timber.d(it) showProgressBar.set(false) channel.send(Event.ImportPublicationFailed(it.getUserMessage(r2Application))) } } fun openBook( context: Context, bookId: Long, callback: suspend (book: Book, file: FileAsset, publication: Publication, url: URL?) -> Unit ) = viewModelScope.launch { val book = booksDao.get(bookId) ?: return@launch val file = File(book.href) require(file.exists()) val asset = FileAsset(file) streamer.open(asset, allowUserInteraction = true, sender = context) .onFailure { Timber.d(it) channel.send(Event.OpenBookError(it.getUserMessage(r2Application))) } .onSuccess { if (it.isRestricted) { it.protectionError?.let { error -> Timber.d(error) channel.send(Event.OpenBookError(error.getUserMessage(r2Application))) } } else { val url = prepareToServe(it) callback.invoke(book, asset, it, url) } } } private fun prepareToServe(publication: Publication): URL? { val userProperties = r2Application.filesDir.path + "/" + Injectable.Style.rawValue + "/UserProperties.json" return server.addPublication(publication, userPropertiesFile = File(userProperties)) } private fun storeCoverImage(publication: Publication, imageName: String) = viewModelScope.launch(Dispatchers.IO) { // TODO Figure out where to store these cover images val coverImageDir = File("${r2Directory}covers/") if (!coverImageDir.exists()) { coverImageDir.mkdirs() } val coverImageFile = File("${r2Directory}covers/${imageName}.png") val bitmap: Bitmap? = publication.cover() val resized = bitmap?.let { Bitmap.createScaledBitmap(it, 120, 200, true) } val fos = FileOutputStream(coverImageFile) resized?.compress(Bitmap.CompressFormat.PNG, 80, fos) fos.flush() fos.close() } private fun getBitmapFromURL(src: String): Bitmap? { return try { val url = URL(src) val connection = url.openConnection() as HttpURLConnection connection.doInput = true connection.connect() val input = connection.inputStream BitmapFactory.decodeStream(input) } catch (e: IOException) { e.printStackTrace() null } } sealed class Event { class ImportPublicationFailed(val errorMessage: String?) : Event() object UnableToMovePublication : Event() object ImportPublicationSuccess : Event() object ImportDatabaseFailed : Event() class OpenBookError(val errorMessage: String?) : Event() } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/bookshelf/BookshelfViewModel.kt
3879537422
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.bookshelf import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.graphics.Rect import android.net.Uri import android.os.Bundle import android.provider.Settings import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.URLUtil import android.widget.EditText import android.widget.ImageView import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat import androidx.databinding.BindingAdapter import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.recyclerview.widget.RecyclerView import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import com.squareup.picasso.Picasso import org.json.JSONObject import org.readium.r2.shared.extensions.tryOrLog import org.readium.r2.shared.publication.Locator import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentBookshelfBinding import org.readium.r2.testapp.domain.model.Book import org.readium.r2.testapp.opds.GridAutoFitLayoutManager import org.readium.r2.testapp.reader.ReaderContract import java.io.File class BookshelfFragment : Fragment() { private val bookshelfViewModel: BookshelfViewModel by viewModels() private lateinit var bookshelfAdapter: BookshelfAdapter private lateinit var documentPickerLauncher: ActivityResultLauncher<String> private lateinit var readerLauncher: ActivityResultLauncher<ReaderContract.Input> private var permissionAsked: Boolean = false private var _binding: FragmentBookshelfBinding? = null private val binding get() = _binding!! private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { importBooks() } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { bookshelfViewModel.channel.receive(this) { handleEvent(it) } _binding = FragmentBookshelfBinding.inflate( inflater, container, false ) binding.viewModel = bookshelfViewModel return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) bookshelfAdapter = BookshelfAdapter(onBookClick = { book -> openBook(book.id) }, onBookLongClick = { book -> confirmDeleteBook(book) }) documentPickerLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? -> uri?.let { bookshelfViewModel.importPublicationFromUri(it) } } readerLauncher = registerForActivityResult(ReaderContract()) { pubData: ReaderContract.Output? -> tryOrLog { pubData?.publication?.close() } } binding.bookshelfBookList.apply { setHasFixedSize(true) layoutManager = GridAutoFitLayoutManager(requireContext(), 120) adapter = bookshelfAdapter addItemDecoration( VerticalSpaceItemDecoration( 10 ) ) } bookshelfViewModel.books.observe(viewLifecycleOwner, { bookshelfAdapter.submitList(it) }) importBooks() // FIXME embedded dialogs like this are ugly binding.bookshelfAddBookFab.setOnClickListener { var selected = 0 MaterialAlertDialogBuilder(requireContext()) .setTitle(getString(R.string.add_book)) .setNegativeButton(getString(R.string.cancel)) { dialog, _ -> dialog.cancel() } .setPositiveButton(getString(R.string.ok)) { _, _ -> if (selected == 0) { documentPickerLauncher.launch("*/*") } else { val urlEditText = EditText(requireContext()) val urlDialog = MaterialAlertDialogBuilder(requireContext()) .setTitle(getString(R.string.add_book)) .setMessage(R.string.enter_url) .setView(urlEditText) .setNegativeButton(R.string.cancel) { dialog, _ -> dialog.cancel() } .setPositiveButton(getString(R.string.ok), null) .show() urlDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { if (TextUtils.isEmpty(urlEditText.text)) { urlEditText.error = getString(R.string.invalid_url) } else if (!URLUtil.isValidUrl(urlEditText.text.toString())) { urlEditText.error = getString(R.string.invalid_url) } else { val url = urlEditText.text.toString() val uri = Uri.parse(url) bookshelfViewModel.importPublicationFromUri(uri, url) urlDialog.dismiss() } } } } .setSingleChoiceItems(R.array.documentSelectorArray, 0) { _, which -> selected = which } .show() } } private fun handleEvent(event: BookshelfViewModel.Event) { val message = when (event) { is BookshelfViewModel.Event.ImportPublicationFailed -> { "Error: " + event.errorMessage } is BookshelfViewModel.Event.UnableToMovePublication -> getString(R.string.unable_to_move_pub) is BookshelfViewModel.Event.ImportPublicationSuccess -> getString(R.string.import_publication_success) is BookshelfViewModel.Event.ImportDatabaseFailed -> getString(R.string.unable_add_pub_database) is BookshelfViewModel.Event.OpenBookError -> { "Error: " + event.errorMessage } } Snackbar.make( requireView(), message, Snackbar.LENGTH_LONG ).show() } class VerticalSpaceItemDecoration(private val verticalSpaceHeight: Int) : RecyclerView.ItemDecoration() { override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { outRect.bottom = verticalSpaceHeight } } private fun requestStoragePermission() { if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { Snackbar.make( this.requireView(), R.string.permission_external_new_explanation, Snackbar.LENGTH_LONG ) .setAction(R.string.permission_retry) { requestPermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE) } .show() } else { // FIXME this is an ugly hack for when user has said don't ask again if (permissionAsked) { Snackbar.make( this.requireView(), R.string.permission_external_new_explanation, Snackbar.LENGTH_INDEFINITE ) .setAction(R.string.action_settings) { Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { addCategory(Intent.CATEGORY_DEFAULT) data = Uri.parse("package:${view?.context?.packageName}") }.run(::startActivity) } .setActionTextColor( ContextCompat.getColor( requireContext(), R.color.snackbar_text_color ) ) .show() } else { permissionAsked = true requestPermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE) } } } private fun importBooks() { if (ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED ) { bookshelfViewModel.copySamplesFromAssetsToStorage() } else requestStoragePermission() } private fun deleteBook(book: Book) { bookshelfViewModel.deleteBook(book) } private fun openBook(bookId: Long?) { bookId ?: return bookshelfViewModel.openBook(requireContext(), bookId) { book, asset, publication, url -> readerLauncher.launch(ReaderContract.Input( mediaType = asset.mediaType(), publication = publication, bookId = bookId, initialLocator = book.progression?.let { Locator.fromJSON(JSONObject(it)) }, baseUrl = url )) } } private fun confirmDeleteBook(book: Book) { MaterialAlertDialogBuilder(requireContext()) .setTitle(getString(R.string.confirm_delete_book_title)) .setMessage(getString(R.string.confirm_delete_book_text)) .setNegativeButton(getString(R.string.cancel)) { dialog, _ -> dialog.cancel() } .setPositiveButton(getString(R.string.delete)) { dialog, _ -> deleteBook(book) dialog.dismiss() } .show() } } @BindingAdapter("coverImage") fun loadImage(view: ImageView, bookId: Long?) { val coverImageFile = File("${view.context?.filesDir?.path}/covers/${bookId}.png") Picasso.with(view.context) .load(coverImageFile) .placeholder(R.drawable.cover) .into(view) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/bookshelf/BookshelfFragment.kt
120569605
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.bookshelf import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.ItemRecycleBookBinding import org.readium.r2.testapp.domain.model.Book import org.readium.r2.testapp.utils.singleClick class BookshelfAdapter( private val onBookClick: (Book) -> Unit, private val onBookLongClick: (Book) -> Unit ) : ListAdapter<Book, BookshelfAdapter.ViewHolder>(BookListDiff()) { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): ViewHolder { return ViewHolder( DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.item_recycle_book, parent, false ) ) } override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) { val book = getItem(position) viewHolder.bind(book) } inner class ViewHolder(private val binding: ItemRecycleBookBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(book: Book) { binding.book = book binding.root.singleClick { onBookClick(book) } binding.root.setOnLongClickListener { onBookLongClick(book) true } } } private class BookListDiff : DiffUtil.ItemCallback<Book>() { override fun areItemsTheSame( oldItem: Book, newItem: Book ): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame( oldItem: Book, newItem: Book ): Boolean { return oldItem.title == newItem.title && oldItem.href == newItem.href && oldItem.author == newItem.author && oldItem.identifier == newItem.identifier } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/bookshelf/BookshelfAdapter.kt
3242030104
/* * Module: r2-testapp-kotlin * Developers: Aferdita Muriqi, Clément Baumann * * Copyright (c) 2018. European Digital Reading Lab. All rights reserved. * Licensed to the Readium Foundation under one or more contributor license agreements. * Use of this source code is governed by a BSD-style license which is detailed in the * LICENSE file present in the project repository where this source code is maintained. */ package org.readium.r2.testapp.utils import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Bundle import org.readium.r2.testapp.MainActivity import timber.log.Timber class R2DispatcherActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) dispatchIntent(intent) finish() } private fun dispatchIntent(intent: Intent) { val uri = uriFromIntent(intent) ?: run { Timber.d("Got an empty intent.") return } val newIntent = Intent(this, MainActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) data = uri } startActivity(newIntent) } private fun uriFromIntent(intent: Intent): Uri? = when (intent.action) { Intent.ACTION_SEND -> { if ("text/plain" == intent.type) { intent.getStringExtra(Intent.EXTRA_TEXT).let { Uri.parse(it) } } else { intent.getParcelableExtra(Intent.EXTRA_STREAM) } } else -> { intent.data } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/R2DispatcherActivity.kt
1266163263
/* * Copyright 2021 Readium Foundation. All rights reserved. * Use of this source code is governed by the BSD-style license * available in the top-level LICENSE file of the project. */ package org.readium.r2.testapp.utils import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.core.view.children import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.NO_POSITION import org.readium.r2.testapp.databinding.SectionHeaderBinding class SectionDecoration( private val context: Context, private val listener: Listener ) : RecyclerView.ItemDecoration() { interface Listener { fun isStartOfSection(itemPos: Int): Boolean fun sectionTitle(itemPos: Int): String } private lateinit var headerView: View private lateinit var sectionTitleView: TextView override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { super.getItemOffsets(outRect, view, parent, state) val pos = parent.getChildAdapterPosition(view) initHeaderViewIfNeeded(parent) if (listener.sectionTitle(pos) != "" && listener.isStartOfSection(pos)) { sectionTitleView.text = listener.sectionTitle(pos) fixLayoutSize(headerView, parent) outRect.top = headerView.height } } override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { super.onDrawOver(c, parent, state) initHeaderViewIfNeeded(parent) val children = parent.children.toList() children.forEach { child -> val pos = parent.getChildAdapterPosition(child) if (pos != NO_POSITION && listener.sectionTitle(pos) != "" && (listener.isStartOfSection(pos) || isTopChild(child, children))) { sectionTitleView.text = listener.sectionTitle(pos) fixLayoutSize(headerView, parent) drawHeader(c, child, headerView) } } } private fun initHeaderViewIfNeeded(parent: RecyclerView) { if (::headerView.isInitialized) return SectionHeaderBinding.inflate( LayoutInflater.from(context), parent, false ).apply { headerView = root sectionTitleView = header } } private fun fixLayoutSize(v: View, parent: ViewGroup) { val widthSpec = View.MeasureSpec.makeMeasureSpec(parent.width, View.MeasureSpec.EXACTLY) val heightSpec = View.MeasureSpec.makeMeasureSpec(parent.height, View.MeasureSpec.UNSPECIFIED) val childWidth = ViewGroup.getChildMeasureSpec(widthSpec, parent.paddingStart + parent.paddingEnd, v.layoutParams.width) val childHeight = ViewGroup.getChildMeasureSpec(heightSpec, parent.paddingTop + parent.paddingBottom, v.layoutParams.height) v.measure(childWidth, childHeight) v.layout(0, 0, v.measuredWidth, v.measuredHeight) } private fun drawHeader(c: Canvas, child: View, headerView: View) { c.run { save() translate(0F, maxOf(0, child.top - headerView.height).toFloat()) headerView.draw(this) restore() } } private fun isTopChild(child: View, children: List<View>): Boolean { var tmp = child.top children.forEach { c -> tmp = minOf(c.top, tmp) } return child.top == tmp } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/SectionDecoration.kt
2024147231
/* * Module: r2-testapp-kotlin * Developers: Aferdita Muriqi, Clément Baumann * * Copyright (c) 2018. European Digital Reading Lab. All rights reserved. * Licensed to the Readium Foundation under one or more contributor license agreements. * Use of this source code is governed by a BSD-style license which is detailed in the * LICENSE file present in the project repository where this source code is maintained. */ package org.readium.r2.testapp.utils import android.content.ContentUris import android.content.Context import android.net.Uri import android.provider.DocumentsContract import android.provider.MediaStore import android.text.TextUtils import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.readium.r2.testapp.utils.extensions.toFile import java.io.File import java.io.FileNotFoundException import java.io.InputStream import java.net.URL object ContentResolverUtil { suspend fun getContentInputStream(context: Context, uri: Uri, publicationPath: String) { withContext(Dispatchers.IO) { try { val path = getRealPath(context, uri) if (path != null) { File(path).copyTo(File(publicationPath)) } else { val input = URL(uri.toString()).openStream() input.toFile(publicationPath) } } catch (e: Exception) { val input = getInputStream(context, uri) input?.let { input.toFile(publicationPath) } } } } private fun getInputStream(context: Context, uri: Uri): InputStream? { return try { context.contentResolver.openInputStream(uri) } catch (e: FileNotFoundException) { e.printStackTrace() null } } private fun getRealPath(context: Context, uri: Uri): String? { // DocumentProvider if (DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { val docId = DocumentsContract.getDocumentId(uri) val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val type = split[0] if ("primary".equals(type, ignoreCase = true)) { return context.getExternalFilesDir(null).toString() + "/" + split[1] } // TODO handle non-primary volumes } else if (isDownloadsDocument(uri)) { val id = DocumentsContract.getDocumentId(uri) if (!TextUtils.isEmpty(id)) { if (id.startsWith("raw:")) { return id.replaceFirst("raw:".toRegex(), "") } return try { val contentUri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id)) getDataColumn(context, contentUri, null, null) } catch (e: NumberFormatException) { null } } } else if (isMediaDocument(uri)) { val docId = DocumentsContract.getDocumentId(uri) val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val type = split[0] var contentUri: Uri? = null when (type) { "image" -> contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI "video" -> contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI "audio" -> contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI } val selection = "_id=?" val selectionArgs = arrayOf(split[1]) return getDataColumn(context, contentUri, selection, selectionArgs) } } else if ("content".equals(uri.scheme!!, ignoreCase = true)) { // Return the remote address return getDataColumn(context, uri, null, null) } else if ("file".equals(uri.scheme!!, ignoreCase = true)) { return uri.path } return null } /** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context The context. * @param uri The Uri to query. * @param selection (Optional) Filter used in the query. * @param selectionArgs (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. */ private fun getDataColumn(context: Context, uri: Uri?, selection: String?, selectionArgs: Array<String>?): String? { val column = "_data" val projection = arrayOf(column) context.contentResolver.query(uri!!, projection, selection, selectionArgs, null).use { cursor -> cursor?.let { if (cursor.moveToFirst()) { val index = cursor.getColumnIndexOrThrow(column) return cursor.getString(index) } } } return null } /** * @param uri The Uri to check. * @return Whether the Uri authority is ExternalStorageProvider. */ private fun isExternalStorageDocument(uri: Uri): Boolean { return "com.android.externalstorage.documents" == uri.authority } /** * @param uri The Uri to check. * @return Whether the Uri authority is DownloadsProvider. */ private fun isDownloadsDocument(uri: Uri): Boolean { return "com.android.providers.downloads.documents" == uri.authority } /** * @param uri The Uri to check. * @return Whether the Uri authority is MediaProvider. */ private fun isMediaDocument(uri: Uri): Boolean { return "com.android.providers.media.documents" == uri.authority } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/ContentResolverUtil.kt
2610311180
package org.readium.r2.testapp.utils import android.view.View /** * Prevents from double clicks on a view, which could otherwise lead to unpredictable states. Useful * while transitioning to another activity for instance. */ class SingleClickListener(private val click: (v: View) -> Unit) : View.OnClickListener { companion object { private const val DOUBLE_CLICK_TIMEOUT = 2500 } private var lastClick: Long = 0 override fun onClick(v: View) { if (getLastClickTimeout() > DOUBLE_CLICK_TIMEOUT) { lastClick = System.currentTimeMillis() click(v) } } private fun getLastClickTimeout(): Long { return System.currentTimeMillis() - lastClick } } fun View.singleClick(l: (View) -> Unit) { setOnClickListener(SingleClickListener(l)) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/SingleClickListener.kt
413034623