path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
Story-App/app/src/main/java/com/example/submissionaplikasistory/utils/addscustomview/CustomEmailEditText.kt
3684428017
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/SettingPreference.kt
3434626090
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/view/viewmodel/VIewModelProviderFactory.kt
2067306692
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/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 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/UserViewModel.kt
540357464
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/home/MainActivity.kt
977756653
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/DetailPostActivity.kt
2581943308
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/MapsCoverageStoryActivity.kt
2712161843
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/PostActivity.kt
286526891
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() [email protected]() } } } 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/RegisterActivity.kt
123396635
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() [email protected]() } } } 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/adapter/StoryAdapter.kt
907936509
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/LoadingStateAdapter.kt
920480967
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/StoryAdapter2.kt
1912780198
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/PostWidget.kt
3320441260
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/service/StackRemoteViewsFactory.kt
1796208337
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/StackWidgetService.kt
3300015241
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/LoginActivity.kt
4045906238
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() } }
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.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/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.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/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.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/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.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/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.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/BaseReaderFragment.kt
1218000085
/* * 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/AudioReaderFragment.kt
325696290
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/ReaderContract.kt
3743930740
/* * 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/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.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/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.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/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.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/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 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/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 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/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 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/DrmManagementContract.kt
3886605322
/* * 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/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 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/GridAutoFitLayoutManager.kt
3931919757
/* * 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/MainActivity.kt
1324370418
/* * 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/R2App.kt
3154975226
/* * 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/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 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/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.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/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.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/BookshelfAdapter.kt
3242030104
/* * 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/utils/R2DispatcherActivity.kt
1266163263
/* * 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/SectionDecoration.kt
2024147231
/* * 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/ContentResolverUtil.kt
2610311180
/* * 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/SingleClickListener.kt
413034623
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/extensions/Uri.kt
3734368706
/* * 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.extensions import android.content.Context import android.net.Uri import org.readium.r2.shared.extensions.tryOrNull import org.readium.r2.shared.util.mediatype.MediaType import org.readium.r2.testapp.utils.ContentResolverUtil import java.io.File import java.util.* suspend fun Uri.copyToTempFile(context: Context, dir: String): File? = tryOrNull { val filename = UUID.randomUUID().toString() val mediaType = MediaType.ofUri(this, context.contentResolver) val path = "$dir$filename.${mediaType?.fileExtension ?: "tmp"}" ContentResolverUtil.getContentInputStream(context, this, path) return@tryOrNull File(path) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/extensions/URL.kt
837749763
/* 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.utils.extensions import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.readium.r2.shared.extensions.extension import org.readium.r2.shared.extensions.tryOr import org.readium.r2.shared.extensions.tryOrNull import java.io.File import java.io.FileOutputStream import java.net.URL import java.util.* suspend fun URL.download(path: String): File? = tryOr(null) { val file = File(path) withContext(Dispatchers.IO) { openStream().use { input -> FileOutputStream(file).use { output -> input.copyTo(output) } } } file } suspend fun URL.copyToTempFile(dir: String): File? = tryOrNull { val filename = UUID.randomUUID().toString() val path = "$dir$filename.$extension" download(path) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/extensions/Context.kt
180714804
/* * 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.extensions import android.content.Context import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.core.content.ContextCompat /** * Extensions */ @ColorInt fun Context.color(@ColorRes id: Int): Int { return ContextCompat.getColor(this, id) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/extensions/File.kt
2966336976
/* Module: r2-testapp-kotlin * Developers: Quentin Gliosca, Aferdita Muriqi, Clément Baumann * * 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.utils.extensions import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File import java.io.FileFilter import java.io.IOException suspend fun File.moveTo(target: File) = withContext(Dispatchers.IO) { if ([email protected](target)) throw IOException() } /** * As there are cases where [File.listFiles] returns null even though it is a directory, we return * an empty list instead. */ fun File.listFilesSafely(filter: FileFilter? = null): List<File> { val array: Array<File>? = if (filter == null) listFiles() else listFiles(filter) return array?.toList() ?: emptyList() }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/extensions/Bitmap.kt
428728235
/* * 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.extensions import android.graphics.Bitmap import android.util.Base64 import timber.log.Timber import java.io.ByteArrayOutputStream /** * Converts the receiver bitmap into a data URL ready to be used in HTML or CSS. * * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs */ fun Bitmap.toDataUrl(): String? = try { val stream = ByteArrayOutputStream() compress(Bitmap.CompressFormat.PNG, 100, stream) .also { success -> if (!success) throw Exception("Can't compress image to PNG") } val b64 = Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT) "data:image/png;base64,$b64" } catch (e: Exception) { Timber.e(e) null }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/extensions/Metadata.kt
3941181849
/* * Module: r2-testapp-kotlin * Developers: Mickaël Menu * * Copyright (c) 2020. Readium Foundation. All rights reserved. * 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.extensions import org.readium.r2.shared.publication.Metadata val Metadata.authorName: String get() = authors.firstOrNull()?.name ?: ""
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/extensions/InputStream.kt
1510309123
/* * 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.extensions import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.readium.r2.shared.extensions.tryOrNull import java.io.File import java.io.InputStream import java.util.* suspend fun InputStream.toFile(path: String) { withContext(Dispatchers.IO) { use { input -> File(path).outputStream().use { input.copyTo(it) } } } } suspend fun InputStream.copyToTempFile(dir: String): File? = tryOrNull { val filename = UUID.randomUUID().toString() File(dir + filename) .also { toFile(it.path) } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/extensions/Link.kt
639819915
package org.readium.r2.testapp.utils.extensions import org.readium.r2.shared.publication.Link val Link.outlineTitle: String get() = title ?: href
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/FragmentFactory.kt
4187447666
/* * Copyright 2020 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 androidx.fragment.app.Fragment import androidx.fragment.app.FragmentFactory import org.readium.r2.shared.extensions.tryOrNull /** * Creates a [FragmentFactory] for a single type of [Fragment] using the result of the given * [factory] closure. */ inline fun <reified T : Fragment> createFragmentFactory(crossinline factory: () -> T): FragmentFactory = object : FragmentFactory() { override fun instantiate(classLoader: ClassLoader, className: String): Fragment { return when (className) { T::class.java.name -> factory() else -> super.instantiate(classLoader, className) } } } /** * A [FragmentFactory] which will iterate over a provided list of [factories] until finding one * instantiating successfully the requested [Fragment]. * * ``` * supportFragmentManager.fragmentFactory = CompositeFragmentFactory( * EpubNavigatorFragment.createFactory(publication, baseUrl, initialLocator, this), * PdfNavigatorFragment.createFactory(publication, initialLocator, this) * ) * ``` */ class CompositeFragmentFactory(private val factories: List<FragmentFactory>) : FragmentFactory() { constructor(vararg factories: FragmentFactory) : this(factories.toList()) override fun instantiate(classLoader: ClassLoader, className: String): Fragment { for (factory in factories) { tryOrNull { factory.instantiate(classLoader, className) } ?.let { return it } } return super.instantiate(classLoader, className) } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/EventChannel.kt
4225782394
/* * 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. */ // See https://proandroiddev.com/android-singleliveevent-redux-with-kotlin-flow-b755c70bb055 package org.readium.r2.testapp.utils import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.OnLifecycleEvent import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch class EventChannel<T>(private val channel: Channel<T>, private val sendScope: CoroutineScope) { fun send(event: T) { sendScope.launch { channel.send(event) } } fun receive(lifecycleOwner: LifecycleOwner, callback: suspend (T) -> Unit) { val observer = FlowObserver(lifecycleOwner, channel.receiveAsFlow(), callback) lifecycleOwner.lifecycle.addObserver(observer) } } class FlowObserver<T> ( private val lifecycleOwner: LifecycleOwner, private val flow: Flow<T>, private val collector: suspend (T) -> Unit ) : LifecycleObserver { private var job: Job? = null @OnLifecycleEvent(Lifecycle.Event.ON_START) fun onStart() { if (job == null) { job = lifecycleOwner.lifecycleScope.launch { flow.collect { collector(it) } } } } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onStop() { job?.cancel() job = null } } inline fun <reified T> Flow<T>.observeWhenStarted( lifecycleOwner: LifecycleOwner, noinline collector: suspend (T) -> Unit ) { val observer = FlowObserver(lifecycleOwner, this, collector) lifecycleOwner.lifecycle.addObserver(observer) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/utils/SystemUiManagement.kt
3709392840
/* * 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.app.Activity import android.view.View import android.view.WindowInsets import androidx.appcompat.app.AppCompatActivity import androidx.core.view.WindowInsetsCompat // Using ViewCompat and WindowInsetsCompat does not work properly in all versions of Android @Suppress("DEPRECATION") /** Returns `true` if fullscreen or immersive mode is not set. */ private fun Activity.isSystemUiVisible(): Boolean { return this.window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_FULLSCREEN == 0 } // Using ViewCompat and WindowInsetsCompat does not work properly in all versions of Android @Suppress("DEPRECATION") /** Enable fullscreen or immersive mode. */ fun Activity.hideSystemUi() { this.window.decorView.systemUiVisibility = ( View.SYSTEM_UI_FLAG_IMMERSIVE or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN ) } // Using ViewCompat and WindowInsetsCompat does not work properly in all versions of Android @Suppress("DEPRECATION") /** Disable fullscreen or immersive mode. */ fun Activity.showSystemUi() { this.window.decorView.systemUiVisibility = ( View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN ) } /** Toggle fullscreen or immersive mode. */ fun Activity.toggleSystemUi() { if (this.isSystemUiVisible()) { this.hideSystemUi() } else { this.showSystemUi() } } /** Set padding around view so that content doesn't overlap system UI */ fun View.padSystemUi(insets: WindowInsets, activity: Activity) = WindowInsetsCompat.toWindowInsetsCompat(insets, this) .getInsets(WindowInsetsCompat.Type.statusBars()).apply { setPadding( left, top + (activity as AppCompatActivity).supportActionBar!!.height, right, bottom ) } /** Clear padding around view */ fun View.clearPadding() = setPadding(0, 0, 0, 0)
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/about/AboutFragment.kt
2347446097
/* * 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.about import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import org.readium.r2.testapp.R class AboutFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_about, container, false) } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/search/SearchPagingSource.kt
4044823683
/* * 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.search import androidx.paging.PagingSource import androidx.paging.PagingState import org.readium.r2.shared.Search import org.readium.r2.shared.publication.Locator import org.readium.r2.shared.publication.LocatorCollection import org.readium.r2.shared.publication.services.search.SearchIterator import org.readium.r2.shared.publication.services.search.SearchTry @OptIn(Search::class) class SearchPagingSource( private val listener: Listener? ) : PagingSource<Unit, Locator>() { interface Listener { suspend fun next(): SearchTry<LocatorCollection?> } override val keyReuseSupported: Boolean get() = true override fun getRefreshKey(state: PagingState<Unit, Locator>): Unit? = null override suspend fun load(params: LoadParams<Unit>): LoadResult<Unit, Locator> { listener ?: return LoadResult.Page(data = emptyList(), prevKey = null, nextKey = null) return try { val page = listener.next().getOrThrow() LoadResult.Page( data = page?.locators ?: emptyList(), prevKey = null, nextKey = if (page == null) null else Unit ) } catch (e: Exception) { LoadResult.Error(e) } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/search/SearchResultAdapter.kt
1889688067
/* * 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.search import android.os.Build import android.text.Html import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import org.readium.r2.shared.publication.Locator import org.readium.r2.testapp.databinding.ItemRecycleSearchBinding import org.readium.r2.testapp.utils.singleClick /** * This class is an adapter for Search results' recycler view. */ class SearchResultAdapter(private var listener: Listener) : PagingDataAdapter<Locator, SearchResultAdapter.ViewHolder>(ItemCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( ItemRecycleSearchBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val locator = getItem(position) ?: return val html = "${locator.text.before}<span style=\"background:yellow;\"><b>${locator.text.highlight}</b></span>${locator.text.after}" holder.textView.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT) } else { @Suppress("DEPRECATION") Html.fromHtml(html) } holder.itemView.singleClick { v -> listener.onItemClicked(v, locator) } } inner class ViewHolder(val binding: ItemRecycleSearchBinding) : RecyclerView.ViewHolder(binding.root) { val textView = binding.text } interface Listener { fun onItemClicked(v: View, locator: Locator) } private class ItemCallback : DiffUtil.ItemCallback<Locator>() { override fun areItemsTheSame(oldItem: Locator, newItem: Locator): Boolean = oldItem == newItem override fun areContentsTheSame(oldItem: Locator, newItem: Locator): Boolean = oldItem == newItem } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/search/SearchFragment.kt
2443852028
/* * 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.search import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.setFragmentResult import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import org.readium.r2.shared.publication.Locator import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentSearchBinding import org.readium.r2.testapp.reader.ReaderViewModel import org.readium.r2.testapp.utils.SectionDecoration class SearchFragment : Fragment(R.layout.fragment_search) { private val viewModel: ReaderViewModel by activityViewModels() private var _binding: FragmentSearchBinding? = null private val binding get() = _binding!! override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val viewScope = viewLifecycleOwner.lifecycleScope val searchAdapter = SearchResultAdapter(object : SearchResultAdapter.Listener { override fun onItemClicked(v: View, locator: Locator) { val result = Bundle().apply { putParcelable(SearchFragment::class.java.name, locator) } setFragmentResult(SearchFragment::class.java.name, result) } }) viewModel.searchResult .onEach { searchAdapter.submitData(it) } .launchIn(viewScope) viewModel.searchLocators .onEach { binding.noResultLabel.isVisible = it.isEmpty() } .launchIn(viewScope) viewModel.channel .receive(viewLifecycleOwner) { event -> when (event) { ReaderViewModel.Event.StartNewSearch -> binding.searchRecyclerView.scrollToPosition(0) else -> {} } } binding.searchRecyclerView.apply { adapter = searchAdapter layoutManager = LinearLayoutManager(activity) addItemDecoration(SectionDecoration(context, object : SectionDecoration.Listener { override fun isStartOfSection(itemPos: Int): Boolean = viewModel.searchLocators.value.run { when { itemPos == 0 -> true itemPos < 0 -> false itemPos >= size -> false else -> getOrNull(itemPos)?.title != getOrNull(itemPos-1)?.title } } override fun sectionTitle(itemPos: Int): String = viewModel.searchLocators.value.getOrNull(itemPos)?.title ?: "" })) addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSearchBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/outline/NavigationFragment.kt
2027551679
/* * 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.outline import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import androidx.fragment.app.Fragment import androidx.fragment.app.setFragmentResult import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import org.readium.r2.shared.publication.Link import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.toLocator import org.readium.r2.testapp.databinding.FragmentListviewBinding import org.readium.r2.testapp.databinding.ItemRecycleNavigationBinding import org.readium.r2.testapp.reader.ReaderViewModel import org.readium.r2.testapp.utils.extensions.outlineTitle /* * Fragment to show navigation links (Table of Contents, Page lists & Landmarks) */ class NavigationFragment : Fragment() { private lateinit var publication: Publication private lateinit var links: List<Link> private lateinit var navAdapter: NavigationAdapter private var _binding: FragmentListviewBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ViewModelProvider(requireActivity()).get(ReaderViewModel::class.java).let { publication = it.publication } links = requireNotNull(requireArguments().getParcelableArrayList(LINKS_ARG)) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentListviewBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) navAdapter = NavigationAdapter(onLinkSelected = { link -> onLinkSelected(link) }) val flatLinks = mutableListOf<Pair<Int, Link>>() for (link in links) { val children = childrenOf(Pair(0, link)) // Append parent. flatLinks.add(Pair(0, link)) // Append children, and their children... recursive. flatLinks.addAll(children) } binding.listView.apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(requireContext()) adapter = navAdapter } navAdapter.submitList(flatLinks) } override fun onDestroyView() { _binding = null super.onDestroyView() } private fun onLinkSelected(link: Link) { val locator = link.toLocator().let { // progression is mandatory in some contexts if (it.locations.fragments.isEmpty()) it.copyWithLocations(progression = 0.0) else it } setFragmentResult( OutlineContract.REQUEST_KEY, OutlineContract.createResult(locator) ) } companion object { private const val LINKS_ARG = "links" fun newInstance(links: List<Link>) = NavigationFragment().apply { arguments = Bundle().apply { putParcelableArrayList(LINKS_ARG, if (links is ArrayList<Link>) links else ArrayList(links)) } } } } class NavigationAdapter(private val onLinkSelected: (Link) -> Unit) : ListAdapter<Pair<Int, Link>, NavigationAdapter.ViewHolder>(NavigationDiff()) { init { setHasStableIds(true) } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): ViewHolder { return ViewHolder( ItemRecycleNavigationBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun getItemId(position: Int): Long = position.toLong() override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = getItem(position) holder.bind(item) } inner class ViewHolder(val binding: ItemRecycleNavigationBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: Pair<Int, Link>) { binding.navigationTextView.text = item.second.outlineTitle binding.indentation.layoutParams = LinearLayout.LayoutParams(item.first * 50, ViewGroup.LayoutParams.MATCH_PARENT) binding.root.setOnClickListener { onLinkSelected(item.second) } } } } private class NavigationDiff : DiffUtil.ItemCallback<Pair<Int, Link>>() { override fun areItemsTheSame( oldItem: Pair<Int, Link>, newItem: Pair<Int, Link> ): Boolean { return oldItem.first == newItem.first && oldItem.second == newItem.second } override fun areContentsTheSame( oldItem: Pair<Int, Link>, newItem: Pair<Int, Link> ): Boolean { return oldItem.first == newItem.first && oldItem.second == newItem.second } } fun childrenOf(parent: Pair<Int, Link>): MutableList<Pair<Int, Link>> { val indentation = parent.first + 1 val children = mutableListOf<Pair<Int, Link>>() for (link in parent.second.children) { children.add(Pair(indentation, link)) children.addAll(childrenOf(Pair(indentation, link))) } return children }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/outline/BookmarksFragment.kt
1685889148
/* * 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.outline import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.PopupMenu import androidx.fragment.app.Fragment import androidx.fragment.app.setFragmentResult import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import org.readium.r2.shared.publication.Publication import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentListviewBinding import org.readium.r2.testapp.databinding.ItemRecycleBookmarkBinding import org.readium.r2.testapp.domain.model.Bookmark import org.readium.r2.testapp.reader.ReaderViewModel import org.readium.r2.testapp.utils.extensions.outlineTitle import kotlin.math.roundToInt class BookmarksFragment : Fragment() { lateinit var publication: Publication lateinit var viewModel: ReaderViewModel private lateinit var bookmarkAdapter: BookmarkAdapter private var _binding: FragmentListviewBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ViewModelProvider(requireActivity()).get(ReaderViewModel::class.java).let { publication = it.publication viewModel = it } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentListviewBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) bookmarkAdapter = BookmarkAdapter(publication, onBookmarkDeleteRequested = { bookmark -> viewModel.deleteBookmark(bookmark.id!!) }, onBookmarkSelectedRequested = { bookmark -> onBookmarkSelected(bookmark) }) binding.listView.apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(requireContext()) adapter = bookmarkAdapter } val comparator: Comparator<Bookmark> = compareBy({ it.resourceIndex }, { it.locator.locations.progression }) viewModel.getBookmarks().observe(viewLifecycleOwner, { val bookmarks = it.sortedWith(comparator).toMutableList() bookmarkAdapter.submitList(bookmarks) }) } override fun onDestroyView() { _binding = null super.onDestroyView() } private fun onBookmarkSelected(bookmark: Bookmark) { setFragmentResult( OutlineContract.REQUEST_KEY, OutlineContract.createResult(bookmark.locator) ) } } class BookmarkAdapter(private val publication: Publication, private val onBookmarkDeleteRequested: (Bookmark) -> Unit, private val onBookmarkSelectedRequested: (Bookmark) -> Unit) : ListAdapter<Bookmark, BookmarkAdapter.ViewHolder>(BookmarksDiff()) { init { setHasStableIds(true) } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): ViewHolder { return ViewHolder( ItemRecycleBookmarkBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun getItemId(position: Int): Long = position.toLong() override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = getItem(position) holder.bind(item) } inner class ViewHolder(val binding: ItemRecycleBookmarkBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(bookmark: Bookmark) { val title = getBookSpineItem(bookmark.resourceHref) ?: "*Title Missing*" binding.bookmarkChapter.text = title bookmark.locator.locations.progression?.let { progression -> val formattedProgression = "${(progression * 100).roundToInt()}% through resource" binding.bookmarkProgression.text = formattedProgression } val formattedDate = DateTime(bookmark.creation).toString(DateTimeFormat.shortDateTime()) binding.bookmarkTimestamp.text = formattedDate binding.overflow.setOnClickListener { val popupMenu = PopupMenu(binding.overflow.context, binding.overflow) popupMenu.menuInflater.inflate(R.menu.menu_bookmark, popupMenu.menu) popupMenu.show() popupMenu.setOnMenuItemClickListener { item -> if (item.itemId == R.id.delete) { onBookmarkDeleteRequested(bookmark) } false } } binding.root.setOnClickListener { onBookmarkSelectedRequested(bookmark) } } } private fun getBookSpineItem(href: String): String? { for (link in publication.tableOfContents) { if (link.href == href) { return link.outlineTitle } } for (link in publication.readingOrder) { if (link.href == href) { return link.outlineTitle } } return null } } private class BookmarksDiff : DiffUtil.ItemCallback<Bookmark>() { override fun areItemsTheSame( oldItem: Bookmark, newItem: Bookmark ): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame( oldItem: Bookmark, newItem: Bookmark ): Boolean { return oldItem.bookId == newItem.bookId && oldItem.location == newItem.location } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/outline/OutlineFragment.kt
2947580352
/* * 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.outline 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.FragmentResultListener import androidx.fragment.app.setFragmentResult import androidx.lifecycle.ViewModelProvider import androidx.viewpager2.adapter.FragmentStateAdapter import com.google.android.material.tabs.TabLayoutMediator import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.epub.landmarks import org.readium.r2.shared.publication.epub.pageList import org.readium.r2.shared.publication.opds.images import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentOutlineBinding import org.readium.r2.testapp.reader.ReaderViewModel class OutlineFragment : Fragment() { lateinit var publication: Publication private var _binding: FragmentOutlineBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ViewModelProvider(requireActivity()).get(ReaderViewModel::class.java).let { publication = it.publication } childFragmentManager.setFragmentResultListener( OutlineContract.REQUEST_KEY, this, FragmentResultListener { requestKey, bundle -> setFragmentResult(requestKey, bundle) } ) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentOutlineBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val outlines: List<Outline> = when (publication.type) { Publication.TYPE.EPUB -> listOf(Outline.Contents, Outline.Bookmarks, Outline.Highlights, Outline.PageList, Outline.Landmarks) else -> listOf(Outline.Contents, Outline.Bookmarks) } binding.outlinePager.adapter = OutlineFragmentStateAdapter(this, publication, outlines) TabLayoutMediator(binding.outlineTabLayout, binding.outlinePager) { tab, idx -> tab.setText(outlines[idx].label) }.attach() } override fun onDestroyView() { _binding = null super.onDestroyView() } } private class OutlineFragmentStateAdapter(fragment: Fragment, val publication: Publication, val outlines: List<Outline>) : FragmentStateAdapter(fragment) { override fun getItemCount(): Int { return outlines.size } override fun createFragment(position: Int): Fragment { return when (this.outlines[position]) { Outline.Bookmarks -> BookmarksFragment() Outline.Highlights -> HighlightsFragment() Outline.Landmarks -> createLandmarksFragment() Outline.Contents -> createContentsFragment() Outline.PageList -> createPageListFragment() } } private fun createContentsFragment() = NavigationFragment.newInstance(when { publication.tableOfContents.isNotEmpty() -> publication.tableOfContents publication.readingOrder.isNotEmpty() -> publication.readingOrder publication.images.isNotEmpty() -> publication.images else -> mutableListOf() }) private fun createPageListFragment() = NavigationFragment.newInstance(publication.pageList) private fun createLandmarksFragment() = NavigationFragment.newInstance(publication.landmarks) } private enum class Outline(val label: Int) { Contents(R.string.contents_tab_label), Bookmarks(R.string.bookmarks_tab_label), Highlights(R.string.highlights_tab_label), PageList(R.string.pagelist_tab_label), Landmarks(R.string.landmarks_tab_label) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/outline/HighlightsFragment.kt
1485027986
/* * 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.outline import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.PopupMenu import androidx.fragment.app.Fragment import androidx.fragment.app.setFragmentResult import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import org.readium.r2.shared.publication.Publication import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentListviewBinding import org.readium.r2.testapp.databinding.ItemRecycleHighlightBinding import org.readium.r2.testapp.domain.model.Highlight import org.readium.r2.testapp.reader.ReaderViewModel import org.readium.r2.testapp.utils.extensions.outlineTitle class HighlightsFragment : Fragment() { lateinit var publication: Publication lateinit var viewModel: ReaderViewModel private lateinit var highlightAdapter: HighlightAdapter private var _binding: FragmentListviewBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ViewModelProvider(requireActivity()).get(ReaderViewModel::class.java).let { publication = it.publication viewModel = it } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentListviewBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) highlightAdapter = HighlightAdapter(publication, onDeleteHighlightRequested = { highlight -> viewModel.deleteHighlight(highlight.id) }, onHighlightSelectedRequested = { highlight -> onHighlightSelected(highlight) }) binding.listView.apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(requireContext()) adapter = highlightAdapter } viewModel.highlights .onEach { highlightAdapter.submitList(it) } .launchIn(viewLifecycleOwner.lifecycleScope) } override fun onDestroyView() { _binding = null super.onDestroyView() } private fun onHighlightSelected(highlight: Highlight) { setFragmentResult( OutlineContract.REQUEST_KEY, OutlineContract.createResult(highlight.locator) ) } } class HighlightAdapter(private val publication: Publication, private val onDeleteHighlightRequested: (Highlight) -> Unit, private val onHighlightSelectedRequested: (Highlight) -> Unit) : ListAdapter<Highlight, HighlightAdapter.ViewHolder>(HighlightsDiff()) { init { setHasStableIds(true) } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): ViewHolder { return ViewHolder( ItemRecycleHighlightBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun getItemId(position: Int): Long = position.toLong() override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = getItem(position) holder.bind(item) } inner class ViewHolder(val binding: ItemRecycleHighlightBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(highlight: Highlight) { binding.highlightChapter.text = highlight.title binding.highlightText.text = highlight.locator.text.highlight binding.annotation.text = highlight.annotation val formattedDate = DateTime(highlight.creation).toString(DateTimeFormat.shortDateTime()) binding.highlightTimeStamp.text = formattedDate binding.highlightOverflow.setOnClickListener { val popupMenu = PopupMenu(binding.highlightOverflow.context, binding.highlightOverflow) popupMenu.menuInflater.inflate(R.menu.menu_bookmark, popupMenu.menu) popupMenu.show() popupMenu.setOnMenuItemClickListener { item -> if (item.itemId == R.id.delete) { onDeleteHighlightRequested(highlight) } false } } binding.root.setOnClickListener { onHighlightSelectedRequested(highlight) } } } } private class HighlightsDiff : DiffUtil.ItemCallback<Highlight>() { override fun areItemsTheSame(oldItem: Highlight, newItem: Highlight): Boolean = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: Highlight, newItem: Highlight): Boolean = oldItem == newItem }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/outline/OutlineContract.kt
237565236
/* * 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.outline import android.os.Bundle import org.readium.r2.shared.publication.Locator object OutlineContract { private const val DESTINATION_KEY = "locator" val REQUEST_KEY: String = OutlineContract::class.java.name data class Result(val destination: Locator) fun createResult(locator: Locator): Bundle = Bundle().apply { putParcelable(DESTINATION_KEY, locator) } fun parseResult(result: Bundle): Result { val destination = requireNotNull(result.getParcelable<Locator>(DESTINATION_KEY)) return Result(destination) } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/catalogs/CatalogRepository.kt
2883945364
/* * 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.catalogs import androidx.lifecycle.LiveData import org.readium.r2.testapp.db.CatalogDao import org.readium.r2.testapp.domain.model.Catalog class CatalogRepository(private val catalogDao: CatalogDao) { suspend fun insertCatalog(catalog: Catalog): Long { return catalogDao.insertCatalog(catalog) } fun getCatalogsFromDatabase(): LiveData<List<Catalog>> = catalogDao.getCatalogModels() suspend fun deleteCatalog(id: Long) = catalogDao.deleteCatalog(id) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/catalogs/CatalogDetailFragment.kt
4259353571
/* * 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.catalogs import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.google.android.material.snackbar.Snackbar import com.squareup.picasso.Picasso import org.readium.r2.shared.extensions.getPublicationOrNull import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.opds.images import org.readium.r2.testapp.MainActivity import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentCatalogDetailBinding class CatalogDetailFragment : Fragment() { private var publication: Publication? = null private val catalogViewModel: CatalogViewModel by viewModels() private var _binding: FragmentCatalogDetailBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = DataBindingUtil.inflate( LayoutInflater.from(context), R.layout.fragment_catalog_detail, container, false ) catalogViewModel.detailChannel.receive(this) { handleEvent(it) } publication = arguments?.getPublicationOrNull() binding.publication = publication binding.viewModel = catalogViewModel return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) (activity as MainActivity).supportActionBar?.title = publication?.metadata?.title Picasso.with(requireContext()).load(publication?.images?.first()?.href) .into(binding.catalogDetailCoverImage) binding.catalogDetailDownloadButton.setOnClickListener { publication?.let { it1 -> catalogViewModel.downloadPublication( it1 ) } } } private fun handleEvent(event: CatalogViewModel.Event.DetailEvent) { val message = when (event) { is CatalogViewModel.Event.DetailEvent.ImportPublicationSuccess -> getString(R.string.import_publication_success) is CatalogViewModel.Event.DetailEvent.ImportPublicationFailed -> getString(R.string.unable_add_pub_database) } Snackbar.make( requireView(), message, Snackbar.LENGTH_LONG ).show() } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/catalogs/CatalogViewModel.kt
3376533546
/* * 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.catalogs import android.app.Application import android.graphics.Bitmap import android.graphics.BitmapFactory import androidx.databinding.ObservableBoolean import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.launch import org.readium.r2.opds.OPDS1Parser import org.readium.r2.opds.OPDS2Parser import org.readium.r2.shared.opds.ParseData import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.opds.images import org.readium.r2.shared.publication.services.cover import org.readium.r2.shared.util.Try import org.readium.r2.shared.util.http.HttpRequest import org.readium.r2.shared.util.mediatype.MediaType import org.readium.r2.testapp.R2App import org.readium.r2.testapp.bookshelf.BookRepository import org.readium.r2.testapp.db.BookDatabase import org.readium.r2.testapp.domain.model.Catalog import org.readium.r2.testapp.opds.OPDSDownloader import org.readium.r2.testapp.utils.EventChannel import timber.log.Timber import java.io.File import java.io.FileOutputStream import java.io.IOException import java.net.HttpURLConnection import java.net.MalformedURLException import java.net.URL class CatalogViewModel(application: Application) : AndroidViewModel(application) { private val bookDao = BookDatabase.getDatabase(application).booksDao() private val bookRepository = BookRepository(bookDao) private var opdsDownloader = OPDSDownloader(application.applicationContext) private var r2Directory = R2App.R2DIRECTORY val detailChannel = EventChannel(Channel<Event.DetailEvent>(Channel.BUFFERED), viewModelScope) val eventChannel = EventChannel(Channel<Event.FeedEvent>(Channel.BUFFERED), viewModelScope) val parseData = MutableLiveData<ParseData>() val showProgressBar = ObservableBoolean() fun parseCatalog(catalog: Catalog) = viewModelScope.launch { var parseRequest: Try<ParseData, Exception>? = null catalog.href.let { val request = HttpRequest(it) try { parseRequest = if (catalog.type == 1) { OPDS1Parser.parseRequest(request) } else { OPDS2Parser.parseRequest(request) } } catch (e: MalformedURLException) { eventChannel.send(Event.FeedEvent.CatalogParseFailed) } } parseRequest?.onSuccess { parseData.postValue(it) } parseRequest?.onFailure { Timber.e(it) eventChannel.send(Event.FeedEvent.CatalogParseFailed) } } fun downloadPublication(publication: Publication) = viewModelScope.launch { showProgressBar.set(true) val downloadUrl = getDownloadURL(publication) val publicationUrl = opdsDownloader.publicationUrl(downloadUrl.toString()) publicationUrl.onSuccess { val id = addPublicationToDatabase(it.first, MediaType.EPUB, publication) if (id != -1L) { detailChannel.send(Event.DetailEvent.ImportPublicationSuccess) } else { detailChannel.send(Event.DetailEvent.ImportPublicationFailed) } } .onFailure { detailChannel.send(Event.DetailEvent.ImportPublicationFailed) } showProgressBar.set(false) } private fun getDownloadURL(publication: Publication): URL? = publication.links .firstOrNull { it.mediaType.isPublication } ?.let { URL(it.href) } private suspend fun addPublicationToDatabase( href: String, mediaType: MediaType, publication: Publication ): Long { val id = bookRepository.insertBook(href, mediaType, publication) storeCoverImage(publication, id.toString()) return id } 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() ?: getBitmapFromURL(publication.images.first().href) 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 { sealed class FeedEvent : Event() { object CatalogParseFailed : FeedEvent() } sealed class DetailEvent : Event() { object ImportPublicationSuccess : DetailEvent() object ImportPublicationFailed : DetailEvent() } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/catalogs/CatalogFragment.kt
3621607906
/* * 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.catalogs import android.os.Bundle import android.view.* import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import androidx.core.os.bundleOf import androidx.core.view.setPadding import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.Navigation import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.snackbar.Snackbar import org.readium.r2.shared.opds.Facet import org.readium.r2.testapp.MainActivity import org.readium.r2.testapp.R import org.readium.r2.testapp.bookshelf.BookshelfFragment import org.readium.r2.testapp.catalogs.CatalogFeedListAdapter.Companion.CATALOGFEED import org.readium.r2.testapp.databinding.FragmentCatalogBinding import org.readium.r2.testapp.domain.model.Catalog import org.readium.r2.testapp.opds.GridAutoFitLayoutManager class CatalogFragment : Fragment() { private val catalogViewModel: CatalogViewModel by viewModels() private lateinit var catalogListAdapter: CatalogListAdapter private lateinit var catalog: Catalog private var showFacetMenu = false private lateinit var facets: MutableList<Facet> private var _binding: FragmentCatalogBinding? = null private val binding get() = _binding!! // FIXME the entire way this fragment is built feels like a hack. Need a cleaner UI override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { catalogViewModel.eventChannel.receive(this) { handleEvent(it) } catalog = arguments?.get(CATALOGFEED) as Catalog _binding = FragmentCatalogBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) catalogListAdapter = CatalogListAdapter() setHasOptionsMenu(true) binding.catalogDetailList.apply { layoutManager = GridAutoFitLayoutManager(requireContext(), 120) adapter = catalogListAdapter addItemDecoration( BookshelfFragment.VerticalSpaceItemDecoration( 10 ) ) } (activity as MainActivity).supportActionBar?.title = catalog.title // TODO this feels hacky, I don't want to parse the file if it has not changed if (catalogViewModel.parseData.value == null) { binding.catalogProgressBar.visibility = View.VISIBLE catalogViewModel.parseCatalog(catalog) } catalogViewModel.parseData.observe(viewLifecycleOwner, { result -> facets = result.feed?.facets ?: mutableListOf() if (facets.size > 0) { showFacetMenu = true } requireActivity().invalidateOptionsMenu() result.feed!!.navigation.forEachIndexed { index, navigation -> val button = Button(requireContext()) button.apply { layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) text = navigation.title setOnClickListener { val catalog1 = Catalog( href = navigation.href, title = navigation.title!!, type = catalog.type ) val bundle = bundleOf(CATALOGFEED to catalog1) Navigation.findNavController(it) .navigate(R.id.action_navigation_catalog_self, bundle) } } binding.catalogLinearLayout.addView(button, index) } if (result.feed!!.publications.isNotEmpty()) { catalogListAdapter.submitList(result.feed!!.publications) } for (group in result.feed!!.groups) { if (group.publications.isNotEmpty()) { val linearLayout = LinearLayout(requireContext()).apply { orientation = LinearLayout.HORIZONTAL setPadding(10) layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f ) weightSum = 2f addView(TextView(requireContext()).apply { text = group.title layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f ) }) if (group.links.size > 0) { addView(TextView(requireContext()).apply { text = getString(R.string.catalog_list_more) gravity = Gravity.END layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f ) setOnClickListener { val catalog1 = Catalog( href = group.links.first().href, title = group.title, type = catalog.type ) val bundle = bundleOf(CATALOGFEED to catalog1) Navigation.findNavController(it) .navigate(R.id.action_navigation_catalog_self, bundle) } }) } } val publicationRecyclerView = RecyclerView(requireContext()).apply { layoutManager = LinearLayoutManager(requireContext()) (layoutManager as LinearLayoutManager).orientation = LinearLayoutManager.HORIZONTAL adapter = CatalogListAdapter().apply { submitList(group.publications) } } binding.catalogLinearLayout.addView(linearLayout) binding.catalogLinearLayout.addView(publicationRecyclerView) } if (group.navigation.isNotEmpty()) { for (navigation in group.navigation) { val button = Button(requireContext()) button.apply { layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) text = navigation.title setOnClickListener { val catalog1 = Catalog( href = navigation.href, title = navigation.title!!, type = catalog.type ) val bundle = bundleOf(CATALOGFEED to catalog1) Navigation.findNavController(it) .navigate(R.id.action_navigation_catalog_self, bundle) } } binding.catalogLinearLayout.addView(button) } } } binding.catalogProgressBar.visibility = View.GONE }) } override fun onDestroyView() { _binding = null super.onDestroyView() } private fun handleEvent(event: CatalogViewModel.Event.FeedEvent) { val message = when (event) { is CatalogViewModel.Event.FeedEvent.CatalogParseFailed -> getString(R.string.failed_parsing_catalog) } binding.catalogProgressBar.visibility = View.GONE Snackbar.make( requireView(), message, Snackbar.LENGTH_LONG ).show() } override fun onPrepareOptionsMenu(menu: Menu) { menu.clear() if (showFacetMenu) { facets.let { for (i in facets.indices) { val submenu = menu.addSubMenu(facets[i].title) for (link in facets[i].links) { val item = submenu.add(link.title) item.setOnMenuItemClickListener { val catalog1 = Catalog( title = link.title!!, href = link.href, type = catalog.type ) val bundle = bundleOf(CATALOGFEED to catalog1) Navigation.findNavController(requireView()) .navigate(R.id.action_navigation_catalog_self, bundle) true } } } } } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/catalogs/CatalogFeedListAdapter.kt
2892746881
/* * 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.catalogs import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.os.bundleOf import androidx.databinding.DataBindingUtil import androidx.navigation.Navigation 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.ItemRecycleCatalogListBinding import org.readium.r2.testapp.domain.model.Catalog class CatalogFeedListAdapter(private val onLongClick: (Catalog) -> Unit) : ListAdapter<Catalog, CatalogFeedListAdapter.ViewHolder>(CatalogListDiff()) { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): ViewHolder { return ViewHolder( DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.item_recycle_catalog_list, parent, false ) ) } override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) { val catalog = getItem(position) viewHolder.bind(catalog) } inner class ViewHolder(private val binding: ItemRecycleCatalogListBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(catalog: Catalog) { binding.catalog = catalog binding.catalogListButton.setOnClickListener { val bundle = bundleOf(CATALOGFEED to catalog) Navigation.findNavController(it) .navigate(R.id.action_navigation_catalog_list_to_navigation_catalog, bundle) } binding.catalogListButton.setOnLongClickListener { onLongClick(catalog) true } } } companion object { const val CATALOGFEED = "catalogFeed" } private class CatalogListDiff : DiffUtil.ItemCallback<Catalog>() { override fun areItemsTheSame( oldItem: Catalog, newItem: Catalog ): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame( oldItem: Catalog, newItem: Catalog ): Boolean { return oldItem.title == newItem.title && oldItem.href == newItem.href && oldItem.type == newItem.type } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/catalogs/CatalogFeedListFragment.kt
2571393462
/* * 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.catalogs import android.content.Context import android.graphics.Rect import android.os.Bundle 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 androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentCatalogFeedListBinding import org.readium.r2.testapp.domain.model.Catalog class CatalogFeedListFragment : Fragment() { private val catalogFeedListViewModel: CatalogFeedListViewModel by viewModels() private lateinit var catalogsAdapter: CatalogFeedListAdapter private var _binding: FragmentCatalogFeedListBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { catalogFeedListViewModel.eventChannel.receive(this) { handleEvent(it) } _binding = FragmentCatalogFeedListBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val preferences = requireContext().getSharedPreferences("org.readium.r2.testapp", Context.MODE_PRIVATE) catalogsAdapter = CatalogFeedListAdapter(onLongClick = { catalog -> onLongClick(catalog) }) binding.catalogFeedList.apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(requireContext()) adapter = catalogsAdapter addItemDecoration( VerticalSpaceItemDecoration( 10 ) ) } catalogFeedListViewModel.catalogs.observe(viewLifecycleOwner, { catalogsAdapter.submitList(it) }) val version = 2 val VERSION_KEY = "OPDS_CATALOG_VERSION" if (preferences.getInt(VERSION_KEY, 0) < version) { preferences.edit().putInt(VERSION_KEY, version).apply() val oPDS2Catalog = Catalog( title = "OPDS 2.0 Test Catalog", href = "https://test.opds.io/2.0/home.json", type = 2 ) val oTBCatalog = Catalog( title = "Open Textbooks Catalog", href = "http://open.minitex.org/textbooks/", type = 1 ) val sEBCatalog = Catalog( title = "Standard eBooks Catalog", href = "https://standardebooks.org/opds/all", type = 1 ) catalogFeedListViewModel.insertCatalog(oPDS2Catalog) catalogFeedListViewModel.insertCatalog(oTBCatalog) catalogFeedListViewModel.insertCatalog(sEBCatalog) } binding.catalogFeedAddCatalogFab.setOnClickListener { val alertDialog = MaterialAlertDialogBuilder(requireContext()) .setTitle(getString(R.string.add_catalog)) .setView(R.layout.add_catalog_dialog) .setNegativeButton(getString(R.string.cancel)) { dialog, _ -> dialog.cancel() } .setPositiveButton(getString(R.string.save), null) .show() alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { val title = alertDialog.findViewById<EditText>(R.id.catalogTitle) val url = alertDialog.findViewById<EditText>(R.id.catalogUrl) if (TextUtils.isEmpty(title?.text)) { title?.error = getString(R.string.invalid_title) } else if (TextUtils.isEmpty(url?.text)) { url?.error = getString(R.string.invalid_url) } else if (!URLUtil.isValidUrl(url?.text.toString())) { url?.error = getString(R.string.invalid_url) } else { catalogFeedListViewModel.parseCatalog( url?.text.toString(), title?.text.toString() ) alertDialog.dismiss() } } } } override fun onDestroyView() { _binding = null super.onDestroyView() } private fun handleEvent(event: CatalogFeedListViewModel.Event) { val message = when (event) { is CatalogFeedListViewModel.Event.FeedListEvent.CatalogParseFailed -> getString(R.string.catalog_parse_error) } Snackbar.make( requireView(), message, Snackbar.LENGTH_LONG ).show() } private fun deleteCatalogModel(catalogModelId: Long) { catalogFeedListViewModel.deleteCatalog(catalogModelId) } private fun onLongClick(catalog: Catalog) { MaterialAlertDialogBuilder(requireContext()) .setTitle(getString(R.string.confirm_delete_catalog_title)) .setMessage(getString(R.string.confirm_delete_catalog_text)) .setNegativeButton(getString(R.string.cancel)) { dialog, _ -> dialog.cancel() } .setPositiveButton(getString(R.string.delete)) { dialog, _ -> catalog.id?.let { deleteCatalogModel(it) } dialog.dismiss() } .show() } class VerticalSpaceItemDecoration(private val verticalSpaceHeight: Int) : RecyclerView.ItemDecoration() { override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { outRect.bottom = verticalSpaceHeight } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/catalogs/CatalogFeedListViewModel.kt
2135652928
/* * 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.catalogs import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.launch import org.json.JSONObject import org.readium.r2.opds.OPDS1Parser import org.readium.r2.opds.OPDS2Parser import org.readium.r2.shared.opds.ParseData import org.readium.r2.shared.util.Try import org.readium.r2.shared.util.http.DefaultHttpClient import org.readium.r2.shared.util.http.HttpRequest import org.readium.r2.shared.util.http.fetchWithDecoder import org.readium.r2.testapp.db.BookDatabase import org.readium.r2.testapp.domain.model.Catalog import org.readium.r2.testapp.utils.EventChannel import java.net.URL class CatalogFeedListViewModel(application: Application) : AndroidViewModel(application) { private val catalogDao = BookDatabase.getDatabase(application).catalogDao() private val repository = CatalogRepository(catalogDao) val eventChannel = EventChannel(Channel<Event>(Channel.BUFFERED), viewModelScope) val catalogs = repository.getCatalogsFromDatabase() fun insertCatalog(catalog: Catalog) = viewModelScope.launch { repository.insertCatalog(catalog) } fun deleteCatalog(id: Long) = viewModelScope.launch { repository.deleteCatalog(id) } fun parseCatalog(url: String, title: String) = viewModelScope.launch { val parseData = parseURL(URL(url)) parseData.onSuccess { data -> val catalog = Catalog( title = title, href = url, type = data.type ) insertCatalog(catalog) } parseData.onFailure { eventChannel.send(Event.FeedListEvent.CatalogParseFailed) } } private suspend fun parseURL(url: URL): Try<ParseData, Exception> { return DefaultHttpClient().fetchWithDecoder(HttpRequest(url.toString())) { val result = it.body if (isJson(result)) { OPDS2Parser.parse(result, url) } else { OPDS1Parser.parse(result, url) } } } private fun isJson(byteArray: ByteArray): Boolean { return try { JSONObject(String(byteArray)) true } catch (e: Exception) { false } } sealed class Event { sealed class FeedListEvent : Event() { object CatalogParseFailed : FeedListEvent() } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/catalogs/CatalogListAdapter.kt
1358629104
/* * 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.catalogs import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.navigation.Navigation import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.squareup.picasso.Picasso import org.readium.r2.shared.extensions.putPublication import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.opds.images import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.ItemRecycleCatalogBinding class CatalogListAdapter : ListAdapter<Publication, CatalogListAdapter.ViewHolder>(PublicationListDiff()) { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): ViewHolder { return ViewHolder( DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.item_recycle_catalog, parent, false ) ) } override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) { val publication = getItem(position) viewHolder.bind(publication) } inner class ViewHolder(private val binding: ItemRecycleCatalogBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(publication: Publication) { binding.catalogListTitleText.text = publication.metadata.title publication.linkWithRel("http://opds-spec.org/image/thumbnail")?.let { link -> Picasso.with(binding.catalogListCoverImage.context).load(link.href) .into(binding.catalogListCoverImage) } ?: run { if (publication.images.isNotEmpty()) { Picasso.with(binding.catalogListCoverImage.context) .load(publication.images.first().href).into(binding.catalogListCoverImage) } } binding.root.setOnClickListener { val bundle = Bundle().apply { putPublication(publication) } Navigation.findNavController(it) .navigate(R.id.action_navigation_catalog_to_navigation_catalog_detail, bundle) } } } private class PublicationListDiff : DiffUtil.ItemCallback<Publication>() { override fun areItemsTheSame( oldItem: Publication, newItem: Publication ): Boolean { return oldItem.metadata.identifier == newItem.metadata.identifier } override fun areContentsTheSame( oldItem: Publication, newItem: Publication ): Boolean { return oldItem.jsonManifest == newItem.jsonManifest } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/tts/ScreenReaderFragment.kt
52956030
/* * 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.tts import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.widget.TextViewCompat import androidx.fragment.app.Fragment import androidx.fragment.app.setFragmentResult import androidx.lifecycle.ViewModelProvider import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.indexOfFirstWithHref import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.FragmentScreenReaderBinding import org.readium.r2.testapp.reader.ReaderViewModel class ScreenReaderFragment : Fragment(), ScreenReaderEngine.Listener { private lateinit var preferences: SharedPreferences private lateinit var publication: Publication private lateinit var screenReader: ScreenReaderEngine private var _binding: FragmentScreenReaderBinding? = null private val binding get() = _binding!! // A reference to the listener must be kept in order to prevent garbage collection // See https://developer.android.com/reference/android/content/SharedPreferences#registerOnSharedPreferenceChangeListener(android.content.SharedPreferences.OnSharedPreferenceChangeListener) private val preferencesListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> if (key == "reader_TTS_speed") { updateScreenReaderSpeed(restart = true) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val activity = requireActivity() preferences = activity.getSharedPreferences("org.readium.r2.settings", Context.MODE_PRIVATE) ViewModelProvider(activity).get(ReaderViewModel::class.java).let { publication = it.publication } screenReader = ScreenReaderEngine(activity, publication) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentScreenReaderBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) screenReader.addListener(this) binding.titleView.text = publication.metadata.title binding.playPause.setOnClickListener { if (screenReader.isPaused) { screenReader.resumeReading() } else { screenReader.pauseReading() } } binding.fastForward.setOnClickListener { if (!screenReader.nextSentence()) { binding.nextChapter.callOnClick() } } binding.nextChapter.setOnClickListener { screenReader.nextResource() } binding.fastBack.setOnClickListener { if (!screenReader.previousSentence()) { binding.prevChapter.callOnClick() } } binding.prevChapter.setOnClickListener { screenReader.previousResource() } updateScreenReaderSpeed(restart = false) preferences.registerOnSharedPreferenceChangeListener(preferencesListener) val initialLocator = ScreenReaderContract.parseArguments(requireArguments()).locator val resourceIndex = requireNotNull(publication.readingOrder.indexOfFirstWithHref(initialLocator.href)) screenReader.goTo(resourceIndex) } override fun onPlayStateChanged(playing: Boolean) { if (playing) { binding.playPause.setImageResource(R.drawable.ic_baseline_pause_24) } else { binding.playPause.setImageResource(R.drawable.ic_baseline_play_arrow_24) } } override fun onEndReached() { Toast.makeText(requireActivity().applicationContext, "No further chapter contains text to read", Toast.LENGTH_LONG).show() } override fun onPlayTextChanged(text: String) { binding.ttsTextView.text = text TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(binding.ttsTextView, 1, 30, 1, TypedValue.COMPLEX_UNIT_DIP) } override fun onDestroyView() { screenReader.removeListener(this) _binding = null super.onDestroyView() } override fun onDestroy() { super.onDestroy() try { screenReader.shutdown() } catch (e: Exception) { } } override fun onPause() { super.onPause() screenReader.pauseReading() } override fun onStop() { super.onStop() screenReader.stopReading() val result = ScreenReaderContract.createResult(screenReader.currentLocator) setFragmentResult(ScreenReaderContract.REQUEST_KEY, result) } private fun updateScreenReaderSpeed(restart: Boolean) { // Get user settings speed when opening the screen reader. Get a neutral percentage (corresponding to // the normal speech speed) if no user settings exist. val speed = preferences.getInt( "reader_TTS_speed", (2.75 * 3.toDouble() / 11.toDouble() * 100).toInt() ) // Convert percentage to a float value between 0.25 and 3.0 val ttsRate = 0.25.toFloat() + (speed.toFloat() / 100.toFloat()) * 2.75.toFloat() screenReader.setSpeechSpeed(ttsRate, restart) } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/tts/ScreenReaderEngine.kt
4180017824
/* * 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.tts import android.content.Context import android.os.Handler import android.os.Looper import android.speech.tts.TextToSpeech import android.speech.tts.UtteranceProgressListener import android.widget.Toast import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.jsoup.Jsoup import org.jsoup.select.Elements import org.readium.r2.shared.publication.Link import org.readium.r2.shared.publication.Locator import org.readium.r2.shared.publication.Publication import org.readium.r2.shared.publication.toLocator import org.readium.r2.testapp.BuildConfig.DEBUG import timber.log.Timber import java.io.IOException import java.util.* /** * ScreenReader * * Basic screen reader engine that uses Android's TextToSpeech */ class ScreenReaderEngine(val context: Context, val publication: Publication) { interface Listener { fun onPlayTextChanged(text: String) fun onPlayStateChanged(playing: Boolean) fun onEndReached() } private var listeners: MutableList<Listener> = mutableListOf() fun addListener(listener: Listener) { listeners.add(listener) } fun removeListener(listener: Listener) { listeners.remove(listener) } // To avoid lifecycle issues, all `notify` functions will be called on the UI thread and // dispatch events to every listener attached at this time. private fun notifyPlayTextChanged(text: String) { for (listener in listeners) { listener.onPlayTextChanged(text) } } private fun notifyPlayStateChanged(playing: Boolean) { for (listener in listeners) { listener.onPlayStateChanged(playing) } } private fun notifyEndReached() { for (listener in listeners) { listener.onEndReached() } } private enum class PlaySentence(val value: Int) { SAME(0), NEXT(1), PREV(-1) } var isPaused: Boolean = false private var initialized = false private var pendingStartReadingResource = false private val items = publication.readingOrder private var resourceIndex = 0 set(value) { when { value >= items.size -> { field = items.size - 1 currentUtterance = 0 } value < 0 -> { field = 0 currentUtterance = 0 } else -> { field = value } } } private var utterances = mutableListOf<String>() var currentUtterance: Int = 0 get() = if (field != -1) field else 0 set(value) { field = when { value == -1 -> 0 value == 0 -> 0 value > utterances.size - 1 -> utterances.size - 1 value < 0 -> 0 else -> value } if (DEBUG) Timber.d("Current utterance index: $currentUtterance") } private var textToSpeech: TextToSpeech = TextToSpeech(context, TextToSpeech.OnInitListener { status -> initialized = (status != TextToSpeech.ERROR) onPrepared() }) private fun onPrepared() { if (DEBUG) Timber.d("textToSpeech initialization status: $initialized") if (!initialized) { Toast.makeText( context.applicationContext, "There was an error with the TTS initialization", Toast.LENGTH_LONG ).show() } if (pendingStartReadingResource) { pendingStartReadingResource = false startReadingResource() } } val currentLocator: Locator get() = publication.readingOrder[resourceIndex].toLocator() /** * - Update the resource index. * - Mark [textToSpeech] as reading. * - Stop [textToSpeech] if it is reading. * - Start [textToSpeech] setup. * * @param resource: Int - The index of the resource we want read. */ fun goTo(resource: Int) { resourceIndex = resource isPaused = false if (textToSpeech.isSpeaking) { textToSpeech.stop() } startReadingResource() } fun previousResource() { resourceIndex-- isPaused = false if (textToSpeech.isSpeaking) { textToSpeech.stop() } startReadingResource() } fun nextResource() { resourceIndex++ isPaused = false if (textToSpeech.isSpeaking) { textToSpeech.stop() } startReadingResource() } private fun setTTSLanguage() { val language = textToSpeech.setLanguage(Locale(publication.metadata.languages.firstOrNull() ?: "")) if (language == TextToSpeech.LANG_MISSING_DATA || language == TextToSpeech.LANG_NOT_SUPPORTED) { Toast.makeText( context.applicationContext, "There was an error with the TTS language, switching " + "to EN-US", Toast.LENGTH_LONG ).show() textToSpeech.language = Locale.US } } /** * Inner function that sets the utterances variable. * * @return: Boolean - Whether utterances was able to be filled or not. */ private suspend fun setUtterances(): Boolean { //Load resource as sentences utterances = mutableListOf() splitResourceAndAddToUtterances(items[resourceIndex]) return utterances.size != 0 } /** * Call the core setup functions to set the language, the utterances and the callbacks. * * @return: Boolean - Whether executing the function was successful or not. */ private suspend fun configure(): Boolean { setTTSLanguage() return withContext(Dispatchers.Default) { setUtterances() } && flushUtterancesQueue() && setTTSCallbacks() } /** * Set the TTS callbacks. * * @return: Boolean - Whether setting the callbacks was successful or not. */ private fun setTTSCallbacks(): Boolean { val res = textToSpeech.setOnUtteranceProgressListener(object : UtteranceProgressListener() { /** * Called when an utterance "starts" as perceived by the caller. This will * be soon before audio is played back in the case of a [TextToSpeech.speak] * or before the first bytes of a file are written to the file system in the case * of [TextToSpeech.synthesizeToFile]. * * @param utteranceId The utterance ID of the utterance. */ override fun onStart(utteranceId: String?) { Handler(Looper.getMainLooper()).post { currentUtterance = utteranceId!!.toInt() notifyPlayTextChanged(utterances[currentUtterance]) } } /** * Called when an utterance has successfully completed processing. * All audio will have been played back by this point for audible output, and all * output will have been written to disk for file synthesis requests. * * This request is guaranteed to be called after [.onStart]. * * @param utteranceId The utterance ID of the utterance. */ override fun onDone(utteranceId: String?) { Handler(Looper.getMainLooper()).post { if (utteranceId.equals((utterances.size - 1).toString())) { if (items.size - 1 == resourceIndex) { stopReading() Handler(Looper.getMainLooper()).post { notifyPlayStateChanged(false) } } else { nextResource() } } } } /** * Called when an error has occurred during processing. This can be called * at any point in the synthesis process. Note that there might be calls * to [.onStart] for specified utteranceId but there will never * be a call to both [.onDone] and [.onError] for * the same utterance. * * @param utteranceId The utterance ID of the utterance. */ override fun onError(utteranceId: String?) { if (DEBUG) Timber .e("Error saying: ${utterances[utteranceId!!.toInt()]}") } }) if (res == TextToSpeech.ERROR) { if (DEBUG) Timber.e("TTS failed to set callbacks") return false } return true } /** * Stop reading and destroy the [textToSpeech]. */ fun shutdown() { initialized = false stopReading() textToSpeech.shutdown() } /** * Set [isPaused] to false and add the [utterances] to the [textToSpeech] queue if [configure] worked * successfully */ private fun startReadingResource() { if (!initialized) { pendingStartReadingResource = true return } isPaused = false notifyPlayStateChanged(true) if (runBlocking { configure() }) { if (currentUtterance >= utterances.size) { if (DEBUG) Timber .e("Invalid currentUtterance value: $currentUtterance . Expected less than $utterances.size") currentUtterance = 0 } val index = currentUtterance for (i in index until utterances.size) { addToUtterancesQueue(utterances[i], i) } } else if ((items.size - 1) > resourceIndex) { nextResource() } else { Handler(Looper.getMainLooper()).post { notifyPlayStateChanged(false) notifyEndReached() } } } /** * Stop text to speech and set [isPaused] to true so that subsequent playing of TTS will not automatically * start playing. */ fun pauseReading() { isPaused = true textToSpeech.stop() notifyPlayStateChanged(false) } /** * Stop text to speech and set [isPaused] to false so that subsequent playing of TTS will automatically * start playing. */ fun stopReading() { isPaused = false textToSpeech.stop() notifyPlayStateChanged(false) } /** * Allow to resume playing from the start of the current track while still being in a completely black box. * * @return Boolean - Whether resuming playing from the start of the current track was successful. */ fun resumeReading() { playSentence(PlaySentence.SAME) notifyPlayStateChanged(true) } /** * Allow to go the next sentence while still being in a completely black box. * * @return Boolean - Whether moving to the next sentence was successful. */ fun nextSentence(): Boolean { return playSentence(PlaySentence.NEXT) } /** * Allow to go the previous sentence while still being in a completely black box. * * @return Boolean - Whether moving to the previous sentence was successful. */ fun previousSentence(): Boolean { return playSentence(PlaySentence.PREV) } /** * The entry point for the hosting activity to adjust speech speed. Input is considered valid and within arbitrary * set boundaries. The update is not instantaneous and [TextToSpeech] needs to be paused and resumed for it to work. * * Print an exception if [textToSpeech.setSpeechRate(speed)] fails. * * @param speed: Float - The speech speed we wish to use with Android's [TextToSpeech]. */ fun setSpeechSpeed(speed: Float, restart: Boolean): Boolean { try { if (textToSpeech.setSpeechRate(speed) == TextToSpeech.ERROR) throw Exception("Failed to update speech speed") if (restart) { pauseReading() resumeReading() } } catch (e: Exception) { if (DEBUG) Timber.e(e.toString()) return false } return true } /** * Reorder the text to speech queue (after flushing it) according to the current track and the argument value. * * @param playSentence: [PlaySentence] - The track to play (relative to the current track). * * @return Boolean - Whether the function was executed successfully. */ private fun playSentence(playSentence: PlaySentence): Boolean { isPaused = false val index = currentUtterance + playSentence.value if (index >= utterances.size || index < 0) return false if (!flushUtterancesQueue()) return false for (i in index until utterances.size) { if (!addToUtterancesQueue(utterances[i], i)) { return false } } return true } /** * Helper function that manages adding an utterance to the Text To Speech for us. * * @return: Boolean - Whether adding the utterance to the Text To Speech queue was successful. */ private fun addToUtterancesQueue(utterance: String, index: Int): Boolean { if (textToSpeech.speak(utterance, TextToSpeech.QUEUE_ADD, null, index.toString()) == TextToSpeech.ERROR) { if (DEBUG) Timber .e("Error while adding utterance: $utterance to the TTS queue") return false } return true } /** * Helper function that manages flushing the Text To Speech for us. * * @return: Boolean - Whether flushing the Text To Speech queue was successful. */ private fun flushUtterancesQueue(): Boolean { if (textToSpeech.speak("", TextToSpeech.QUEUE_FLUSH, null, null) == TextToSpeech.ERROR) { if (DEBUG) Timber.e("Error while flushing TTS queue.") return false } return true } /** * Split all the paragraphs of the resource into sentences. The sentences are then added to the [utterances] list. * * @param elements: Elements - The list of elements (paragraphs) */ private fun splitParagraphAndAddToUtterances(elements: Elements) { val elementSize = elements.size var index = 0 for (i in 0 until elementSize) { val element = elements.eq(i) if (element.`is`("p") || element.`is`("h1") || element.`is`("h2") || element.`is`("h3") || element.`is`("div") || element.`is`("span") ) { //val sentences = element.text().split(Regex("(?<=\\. |(,{1}))")) val sentences = element.text().split(Regex("(?<=\\.)")) for (sentence in sentences) { var sentenceCleaned = sentence if (sentenceCleaned.isNotEmpty()) { if (sentenceCleaned.first() == ' ') sentenceCleaned = sentenceCleaned.removeRange(0, 1) if (sentenceCleaned.last() == ' ') sentenceCleaned = sentenceCleaned.removeRange(sentenceCleaned.length - 1, sentenceCleaned.length) utterances.add(sentenceCleaned) index++ } } } } } /** * Fetch a resource and get short sentences from it. * * @param link: String - A link to the html resource to fetch, containing the text to be voiced. * * @return: Boolean - Whether the function executed successfully. */ private suspend fun splitResourceAndAddToUtterances(link: Link): Boolean { return try { val resource = publication.get(link).readAsString(charset = null).getOrThrow() val document = Jsoup.parse(resource) val elements = document.select("*") splitParagraphAndAddToUtterances(elements) true } catch (e: IOException) { if (DEBUG) Timber.e(e.toString()) false } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/tts/ScreenReaderContract.kt
4174439663
/* * 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.tts import android.os.Bundle import org.readium.r2.shared.publication.Locator object ScreenReaderContract { private const val LOCATOR_KEY = "locator" val REQUEST_KEY: String = ScreenReaderContract::class.java.name data class Arguments(val locator: Locator) fun createArguments(locator: Locator): Bundle = Bundle().apply { putParcelable(LOCATOR_KEY, locator) } fun parseArguments(result: Bundle): Arguments { val locator = requireNotNull(result.getParcelable<Locator>(LOCATOR_KEY)) return Arguments(locator) } data class Result(val locator: Locator) fun createResult(locator: Locator): Bundle = Bundle().apply { putParcelable(LOCATOR_KEY, locator) } fun parseResult(result: Bundle): Result { val destination = requireNotNull(result.getParcelable<Locator>(LOCATOR_KEY)) return Result(destination) } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/db/CatalogDao.kt
1463906175
/* * 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.db import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import org.readium.r2.testapp.domain.model.Catalog @Dao interface CatalogDao { /** * Inserts an Catalog * @param catalog The Catalog model to insert * @return ID of the Catalog model that was added (primary key) */ @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertCatalog(catalog: Catalog): Long /** * Retrieve list of Catalog models based on Catalog model * @return List of Catalog models as LiveData */ @Query("SELECT * FROM " + Catalog.TABLE_NAME + " WHERE " + Catalog.TITLE + " = :title AND " + Catalog.HREF + " = :href AND " + Catalog.TYPE + " = :type") fun getCatalogModels(title: String, href: String, type: Int): LiveData<List<Catalog>> /** * Retrieve list of all Catalog models * @return List of Catalog models as LiveData */ @Query("SELECT * FROM " + Catalog.TABLE_NAME) fun getCatalogModels(): LiveData<List<Catalog>> /** * Deletes an Catalog model * @param id The id of the Catalog model to delete */ @Query("DELETE FROM " + Catalog.TABLE_NAME + " WHERE " + Catalog.ID + " = :id") suspend fun deleteCatalog(id: Long) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/db/BooksDao.kt
3495697265
/* * 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.db import androidx.annotation.ColorInt import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import kotlinx.coroutines.flow.Flow import org.readium.r2.testapp.domain.model.Book import org.readium.r2.testapp.domain.model.Bookmark import org.readium.r2.testapp.domain.model.Highlight @Dao interface BooksDao { /** * Inserts a book * @param book The book to insert * @return ID of the book that was added (primary key) */ @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertBook(book: Book): Long /** * Deletes a book * @param bookId The ID of the book */ @Query("DELETE FROM " + Book.TABLE_NAME + " WHERE " + Book.ID + " = :bookId") suspend fun deleteBook(bookId: Long) /** * Retrieve a book from its ID. */ @Query("SELECT * FROM " + Book.TABLE_NAME + " WHERE " + Book.ID + " = :id") suspend fun get(id: Long): Book? /** * Retrieve all books * @return List of books as LiveData */ @Query("SELECT * FROM " + Book.TABLE_NAME + " ORDER BY " + Book.CREATION_DATE + " desc") fun getAllBooks(): LiveData<List<Book>> /** * Retrieve all bookmarks for a specific book * @param bookId The ID of the book * @return List of bookmarks for the book as LiveData */ @Query("SELECT * FROM " + Bookmark.TABLE_NAME + " WHERE " + Bookmark.BOOK_ID + " = :bookId") fun getBookmarksForBook(bookId: Long): LiveData<MutableList<Bookmark>> /** * Retrieve all highlights for a specific book */ @Query("SELECT * FROM ${Highlight.TABLE_NAME} WHERE ${Highlight.BOOK_ID} = :bookId ORDER BY ${Highlight.TOTAL_PROGRESSION} ASC") fun getHighlightsForBook(bookId: Long): Flow<List<Highlight>> /** * Retrieves the highlight with the given ID. */ @Query("SELECT * FROM ${Highlight.TABLE_NAME} WHERE ${Highlight.ID} = :highlightId") suspend fun getHighlightById(highlightId: Long): Highlight? /** * Inserts a bookmark * @param bookmark The bookmark to insert * @return The ID of the bookmark that was added (primary key) */ @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertBookmark(bookmark: Bookmark): Long /** * Inserts a highlight * @param highlight The highlight to insert * @return The ID of the highlight that was added (primary key) */ @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertHighlight(highlight: Highlight): Long /** * Updates a highlight's annotation. */ @Query("UPDATE ${Highlight.TABLE_NAME} SET ${Highlight.ANNOTATION} = :annotation WHERE ${Highlight.ID} = :id") suspend fun updateHighlightAnnotation(id: Long, annotation: String) /** * Updates a highlight's tint and style. */ @Query("UPDATE ${Highlight.TABLE_NAME} SET ${Highlight.TINT} = :tint, ${Highlight.STYLE} = :style WHERE ${Highlight.ID} = :id") suspend fun updateHighlightStyle(id: Long, style: Highlight.Style, @ColorInt tint: Int) /** * Deletes a bookmark */ @Query("DELETE FROM " + Bookmark.TABLE_NAME + " WHERE " + Bookmark.ID + " = :id") suspend fun deleteBookmark(id: Long) /** * Deletes the highlight with given id. */ @Query("DELETE FROM ${Highlight.TABLE_NAME} WHERE ${Highlight.ID} = :id") suspend fun deleteHighlight(id: Long) /** * Saves book progression * @param locator Location of the book * @param id The book to update */ @Query("UPDATE " + Book.TABLE_NAME + " SET " + Book.PROGRESSION + " = :locator WHERE " + Book.ID + "= :id") suspend fun saveProgression(locator: String, id: Long) }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/db/Database.kt
3435371980
/* * 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.db import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters import org.readium.r2.testapp.domain.model.* @Database( entities = [Book::class, Bookmark::class, Highlight::class, Catalog::class], version = 1, exportSchema = false ) @TypeConverters(HighlightConverters::class) abstract class BookDatabase : RoomDatabase() { abstract fun booksDao(): BooksDao abstract fun catalogDao(): CatalogDao companion object { @Volatile private var INSTANCE: BookDatabase? = null fun getDatabase(context: Context): BookDatabase { val tempInstance = INSTANCE if (tempInstance != null) { return tempInstance } synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, BookDatabase::class.java, "books_database" ).build() INSTANCE = instance return instance } } } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/domain/model/Book.kt
1676128334
/* * 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.domain.model import android.net.Uri import android.os.Build import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import org.readium.r2.shared.util.mediatype.MediaType import java.net.URI import java.nio.file.Paths @Entity(tableName = Book.TABLE_NAME) data class Book( @PrimaryKey @ColumnInfo(name = ID) var id: Long? = null, @ColumnInfo(name = Bookmark.CREATION_DATE, defaultValue = "CURRENT_TIMESTAMP") val creation: Long? = null, @ColumnInfo(name = HREF) val href: String, @ColumnInfo(name = TITLE) val title: String, @ColumnInfo(name = AUTHOR) val author: String? = null, @ColumnInfo(name = IDENTIFIER) val identifier: String, @ColumnInfo(name = PROGRESSION) val progression: String? = null, @ColumnInfo(name = TYPE) val type: String ) { val fileName: String? get() { val url = URI(href) if (!url.scheme.isNullOrEmpty() && url.isAbsolute) { val uri = Uri.parse(href) return uri.lastPathSegment } return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val path = Paths.get(href) path.fileName.toString() } else { val uri = Uri.parse(href) uri.lastPathSegment } } val url: URI? get() { val url = URI(href) if (url.isAbsolute && url.scheme.isNullOrEmpty()) { return null } return url } suspend fun mediaType(): MediaType? = MediaType.of(type) companion object { const val TABLE_NAME = "books" const val ID = "id" const val CREATION_DATE = "creation_date" const val HREF = "href" const val TITLE = "title" const val AUTHOR = "author" const val IDENTIFIER = "identifier" const val PROGRESSION = "progression" const val TYPE = "type" } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/domain/model/Bookmark.kt
2758096399
/* * 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.domain.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey import org.json.JSONObject import org.readium.r2.shared.publication.Locator @Entity( tableName = Bookmark.TABLE_NAME, indices = [Index( value = ["BOOK_ID", "LOCATION"], unique = true )] ) data class Bookmark( @PrimaryKey @ColumnInfo(name = ID) var id: Long? = null, @ColumnInfo(name = CREATION_DATE, defaultValue = "CURRENT_TIMESTAMP") var creation: Long? = null, @ColumnInfo(name = BOOK_ID) val bookId: Long, @ColumnInfo(name = PUBLICATION_ID) val publicationId: String, @ColumnInfo(name = RESOURCE_INDEX) val resourceIndex: Long, @ColumnInfo(name = RESOURCE_HREF) val resourceHref: String, @ColumnInfo(name = RESOURCE_TYPE) val resourceType: String, @ColumnInfo(name = RESOURCE_TITLE) val resourceTitle: String, @ColumnInfo(name = LOCATION) val location: String, @ColumnInfo(name = LOCATOR_TEXT) val locatorText: String ) { val locator get() = Locator( href = resourceHref, type = resourceType, title = resourceTitle, locations = Locator.Locations.fromJSON(JSONObject(location)), text = Locator.Text.fromJSON(JSONObject(locatorText)) ) companion object { const val TABLE_NAME = "BOOKMARKS" const val ID = "ID" const val CREATION_DATE = "CREATION_DATE" const val BOOK_ID = "BOOK_ID" const val PUBLICATION_ID = "PUBLICATION_ID" const val RESOURCE_INDEX = "RESOURCE_INDEX" const val RESOURCE_HREF = "RESOURCE_HREF" const val RESOURCE_TYPE = "RESOURCE_TYPE" const val RESOURCE_TITLE = "RESOURCE_TITLE" const val LOCATION = "LOCATION" const val LOCATOR_TEXT = "LOCATOR_TEXT" } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/domain/model/Highlight.kt
1406578602
/* * 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.domain.model import androidx.annotation.ColorInt import androidx.room.* import org.json.JSONObject import org.readium.r2.shared.publication.Locator import org.readium.r2.shared.util.MapWithDefaultCompanion /** * @param id Primary key, auto-incremented * @param style Look and feel of this annotation (highlight, underline) * @param title Provides additional context about the annotation * @param tint Color associated with the annotation * @param bookId Foreign key to the book * @param href References a resource within a publication * @param type References the media type of a resource within a publication * @param totalProgression Overall progression in the publication * @param locations Locator locations object * @param text Locator text object * @param annotation User-provided note attached to the annotation */ @Entity( tableName = "highlights", foreignKeys = [ ForeignKey(entity = Book::class, parentColumns = [Book.ID], childColumns = [Highlight.BOOK_ID], onDelete = ForeignKey.CASCADE) ], ) data class Highlight( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = ID) var id: Long = 0, @ColumnInfo(name = CREATION_DATE, defaultValue = "CURRENT_TIMESTAMP") var creation: Long? = null, @ColumnInfo(name = BOOK_ID) val bookId: Long, @ColumnInfo(name = STYLE) var style: Style, @ColumnInfo(name = TINT, defaultValue = "0") @ColorInt var tint: Int, @ColumnInfo(name = HREF) var href: String, @ColumnInfo(name = TYPE) var type: String, @ColumnInfo(name = TITLE, defaultValue = "NULL") var title: String? = null, @ColumnInfo(name = TOTAL_PROGRESSION, defaultValue = "0") var totalProgression: Double = 0.0, @ColumnInfo(name = LOCATIONS, defaultValue = "{}") var locations: Locator.Locations = Locator.Locations(), @ColumnInfo(name = TEXT, defaultValue = "{}") var text: Locator.Text = Locator.Text(), @ColumnInfo(name = ANNOTATION, defaultValue = "") var annotation: String = "", ) { constructor(bookId: Long, style: Style, @ColorInt tint: Int, locator: Locator, annotation: String) : this( bookId = bookId, style = style, tint = tint, href = locator.href, type = locator.type, title = locator.title, totalProgression = locator.locations.totalProgression ?: 0.0, locations = locator.locations, text = locator.text, annotation = annotation ) val locator: Locator get() = Locator( href = href, type = type, title = title, locations = locations, text = text, ) enum class Style(val value: String) { HIGHLIGHT("highlight"), UNDERLINE("underline"); companion object : MapWithDefaultCompanion<String, Style>(values(), Style::value, HIGHLIGHT) } companion object { const val TABLE_NAME = "HIGHLIGHTS" const val ID = "ID" const val CREATION_DATE = "CREATION_DATE" const val BOOK_ID = "BOOK_ID" const val STYLE = "STYLE" const val TINT = "TINT" const val HREF = "HREF" const val TYPE = "TYPE" const val TITLE = "TITLE" const val TOTAL_PROGRESSION = "TOTAL_PROGRESSION" const val LOCATIONS = "LOCATIONS" const val TEXT = "TEXT" const val ANNOTATION = "ANNOTATION" } } class HighlightConverters { @TypeConverter fun styleFromString(value: String?): Highlight.Style = Highlight.Style(value) @TypeConverter fun styleToString(style: Highlight.Style): String = style.value @TypeConverter fun textFromString(value: String?): Locator.Text = Locator.Text.fromJSON(value?.let { JSONObject(it) }) @TypeConverter fun textToString(text: Locator.Text): String = text.toJSON().toString() @TypeConverter fun locationsFromString(value: String?): Locator.Locations = Locator.Locations.fromJSON(value?.let { JSONObject(it) }) @TypeConverter fun locationsToString(text: Locator.Locations): String = text.toJSON().toString() }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/domain/model/Catalog.kt
2229768703
/* * 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.domain.model import android.os.Parcelable import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.parcelize.Parcelize @Parcelize @Entity(tableName = Catalog.TABLE_NAME) data class Catalog( @PrimaryKey @ColumnInfo(name = ID) var id: Long? = null, @ColumnInfo(name = TITLE) var title: String, @ColumnInfo(name = HREF) var href: String, @ColumnInfo(name = TYPE) var type: Int ) : Parcelable { companion object { const val TABLE_NAME = "CATALOG" const val ID = "ID" const val TITLE = "TITLE" const val HREF = "HREF" const val TYPE = "TYPE" } }
readium-testapp-droid/r2-testapp/src/main/java/org/readium/r2/testapp/epub/UserSettings.kt
2378335890
/* * Module: r2-navigator-kotlin * Developers: Aferdita Muriqi, Clément Baumann, Mostapha Idoubihi, Paul Stoica * * 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.epub import android.content.Context import android.content.SharedPreferences import android.graphics.Color import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import androidx.appcompat.app.AppCompatActivity import org.json.JSONArray import org.readium.r2.navigator.R2BasicWebView import org.readium.r2.navigator.R2WebView import org.readium.r2.navigator.epub.fxl.R2FXLLayout import org.readium.r2.navigator.pager.R2EpubPageFragment import org.readium.r2.navigator.pager.R2PagerAdapter import org.readium.r2.navigator.pager.R2ViewPager import org.readium.r2.shared.* import org.readium.r2.testapp.R import org.readium.r2.testapp.databinding.PopupWindowUserSettingsBinding import org.readium.r2.testapp.utils.extensions.color import java.io.File class UserSettings(var preferences: SharedPreferences, val context: Context, private val UIPreset: MutableMap<ReadiumCSSName, Boolean>) { lateinit var resourcePager: R2ViewPager private val appearanceValues = listOf("readium-default-on", "readium-sepia-on", "readium-night-on") private val fontFamilyValues = listOf("Original", "PT Serif", "Roboto", "Source Sans Pro", "Vollkorn", "OpenDyslexic", "AccessibleDfA", "IA Writer Duospace") private val textAlignmentValues = listOf("justify", "start") private val columnCountValues = listOf("auto", "1", "2") private var fontSize = 100f private var fontOverride = false private var fontFamily = 0 private var appearance = 0 private var verticalScroll = false //Advanced settings private var publisherDefaults = false private var textAlignment = 0 private var columnCount = 0 private var wordSpacing = 0f private var letterSpacing = 0f private var pageMargins = 2f private var lineHeight = 1f private var userProperties: UserProperties init { appearance = preferences.getInt(APPEARANCE_REF, appearance) verticalScroll = preferences.getBoolean(SCROLL_REF, verticalScroll) fontFamily = preferences.getInt(FONT_FAMILY_REF, fontFamily) if (fontFamily != 0) { fontOverride = true } publisherDefaults = preferences.getBoolean(PUBLISHER_DEFAULT_REF, publisherDefaults) textAlignment = preferences.getInt(TEXT_ALIGNMENT_REF, textAlignment) columnCount = preferences.getInt(COLUMN_COUNT_REF, columnCount) fontSize = preferences.getFloat(FONT_SIZE_REF, fontSize) wordSpacing = preferences.getFloat(WORD_SPACING_REF, wordSpacing) letterSpacing = preferences.getFloat(LETTER_SPACING_REF, letterSpacing) pageMargins = preferences.getFloat(PAGE_MARGINS_REF, pageMargins) lineHeight = preferences.getFloat(LINE_HEIGHT_REF, lineHeight) userProperties = getUserSettings() //Setting up screen brightness val backLightValue = preferences.getInt("reader_brightness", 50).toFloat() / 100 val layoutParams = (context as AppCompatActivity).window.attributes layoutParams.screenBrightness = backLightValue context.window.attributes = layoutParams } private fun getUserSettings(): UserProperties { val userProperties = UserProperties() // Publisher default system userProperties.addSwitchable("readium-advanced-off", "readium-advanced-on", publisherDefaults, PUBLISHER_DEFAULT_REF, PUBLISHER_DEFAULT_NAME) // Font override userProperties.addSwitchable("readium-font-on", "readium-font-off", fontOverride, FONT_OVERRIDE_REF, FONT_OVERRIDE_NAME) // Column count userProperties.addEnumerable(columnCount, columnCountValues, COLUMN_COUNT_REF, COLUMN_COUNT_NAME) // Appearance userProperties.addEnumerable(appearance, appearanceValues, APPEARANCE_REF, APPEARANCE_NAME) // Page margins userProperties.addIncremental(pageMargins, 0.5f, 4f, 0.25f, "", PAGE_MARGINS_REF, PAGE_MARGINS_NAME) // Text alignment userProperties.addEnumerable(textAlignment, textAlignmentValues, TEXT_ALIGNMENT_REF, TEXT_ALIGNMENT_NAME) // Font family userProperties.addEnumerable(fontFamily, fontFamilyValues, FONT_FAMILY_REF, FONT_FAMILY_NAME) // Font size userProperties.addIncremental(fontSize, 100f, 300f, 25f, "%", FONT_SIZE_REF, FONT_SIZE_NAME) // Line height userProperties.addIncremental(lineHeight, 1f, 2f, 0.25f, "", LINE_HEIGHT_REF, LINE_HEIGHT_NAME) // Word spacing userProperties.addIncremental(wordSpacing, 0f, 0.5f, 0.25f, "rem", WORD_SPACING_REF, WORD_SPACING_NAME) // Letter spacing userProperties.addIncremental(letterSpacing, 0f, 0.5f, 0.0625f, "em", LETTER_SPACING_REF, LETTER_SPACING_NAME) // Scroll userProperties.addSwitchable("readium-scroll-on", "readium-scroll-off", verticalScroll, SCROLL_REF, SCROLL_NAME) return userProperties } private fun makeJson(): JSONArray { val array = JSONArray() for (userProperty in userProperties.properties) { array.put(userProperty.getJson()) } return array } fun saveChanges() { val json = makeJson() val dir = File(context.filesDir.path + "/" + Injectable.Style.rawValue + "/") dir.mkdirs() val file = File(dir, "UserProperties.json") file.printWriter().use { out -> out.println(json) } } private fun updateEnumerable(enumerable: Enumerable) { preferences.edit().putInt(enumerable.ref, enumerable.index).apply() saveChanges() } private fun updateSwitchable(switchable: Switchable) { preferences.edit().putBoolean(switchable.ref, switchable.on).apply() saveChanges() } private fun updateIncremental(incremental: Incremental) { preferences.edit().putFloat(incremental.ref, incremental.value).apply() saveChanges() } fun updateViewCSS(ref: String) { for (i in 0 until resourcePager.childCount) { val webView = resourcePager.getChildAt(i).findViewById(R.id.webView) as? R2WebView webView?.let { applyCSS(webView, ref) } ?: run { val zoomView = resourcePager.getChildAt(i).findViewById(R.id.r2FXLLayout) as R2FXLLayout val webView1 = zoomView.findViewById(R.id.firstWebView) as? R2BasicWebView val webView2 = zoomView.findViewById(R.id.secondWebView) as? R2BasicWebView val webViewSingle = zoomView.findViewById(R.id.webViewSingle) as? R2BasicWebView webView1?.let { applyCSS(webView1, ref) } webView2?.let { applyCSS(webView2, ref) } webViewSingle?.let { applyCSS(webViewSingle, ref) } } } } private fun applyCSS(view: R2BasicWebView, ref: String) { val userSetting = userProperties.getByRef<UserProperty>(ref) view.setProperty(userSetting.name, userSetting.toString()) } // There isn't an easy way to migrate from TabHost/TabWidget to TabLayout @Suppress("DEPRECATION") fun userSettingsPopUp(): PopupWindow { val layoutInflater = LayoutInflater.from(context) val layout = PopupWindowUserSettingsBinding.inflate(layoutInflater) val userSettingsPopup = PopupWindow(context) userSettingsPopup.contentView = layout.root userSettingsPopup.width = ListPopupWindow.WRAP_CONTENT userSettingsPopup.height = ListPopupWindow.WRAP_CONTENT userSettingsPopup.isOutsideTouchable = true userSettingsPopup.isFocusable = true val host = layout.tabhost host.setup() //Tab 1 var spec: TabHost.TabSpec = host.newTabSpec("Settings") spec.setContent(R.id.SettingsTab) spec.setIndicator("Settings") host.addTab(spec) //Tab 2 spec = host.newTabSpec("Advanced") spec.setContent(R.id.Advanced) spec.setIndicator("Advanced") host.addTab(spec) val tw = host.findViewById(android.R.id.tabs) as TabWidget (tw.getChildTabViewAt(0).findViewById(android.R.id.title) as TextView).textSize = 10f (tw.getChildTabViewAt(1).findViewById(android.R.id.title) as TextView).textSize = 10f val fontFamily = (userProperties.getByRef<Enumerable>(FONT_FAMILY_REF)) val fontOverride = (userProperties.getByRef<Switchable>(FONT_OVERRIDE_REF)) val appearance = userProperties.getByRef<Enumerable>(APPEARANCE_REF) val fontSize = userProperties.getByRef<Incremental>(FONT_SIZE_REF) val publisherDefault = userProperties.getByRef<Switchable>(PUBLISHER_DEFAULT_REF) val scrollMode = userProperties.getByRef<Switchable>(SCROLL_REF) val alignment = userProperties.getByRef<Enumerable>(TEXT_ALIGNMENT_REF) val columnsCount = userProperties.getByRef<Enumerable>(COLUMN_COUNT_REF) val pageMargins = userProperties.getByRef<Incremental>(PAGE_MARGINS_REF) val wordSpacing = userProperties.getByRef<Incremental>(WORD_SPACING_REF) val letterSpacing = userProperties.getByRef<Incremental>(LETTER_SPACING_REF) val lineHeight = userProperties.getByRef<Incremental>(LINE_HEIGHT_REF) val fontSpinner: Spinner = layout.spinnerActionSettingsIntervallValues val fonts = context.resources.getStringArray(R.array.font_list) val dataAdapter = object : ArrayAdapter<String>(context, R.layout.item_spinner_font, fonts) { override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View { val v: View? = super.getDropDownView(position, null, parent) // Makes the selected font appear in dark // If this is the selected item position if (position == fontFamily.index) { v!!.setBackgroundColor(context.color(R.color.colorPrimaryDark)) v.findViewById<TextView>(android.R.id.text1).setTextColor(Color.WHITE) } else { // for other views v!!.setBackgroundColor(Color.WHITE) v.findViewById<TextView>(android.R.id.text1).setTextColor(Color.BLACK) } return v } } fun findIndexOfId(id: Int, list: MutableList<RadioButton>): Int { for (i in 0..list.size) { if (list[i].id == id) { return i } } return 0 } // Font family dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) fontSpinner.adapter = dataAdapter fontSpinner.setSelection(fontFamily.index) fontSpinner.contentDescription = "Font Family" fontSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, pos: Int, id: Long) { fontFamily.index = pos fontOverride.on = (pos != 0) updateSwitchable(fontOverride) updateEnumerable(fontFamily) updateViewCSS(FONT_OVERRIDE_REF) updateViewCSS(FONT_FAMILY_REF) } override fun onNothingSelected(parent: AdapterView<out Adapter>?) { // fontSpinner.setSelection(selectedFontIndex) } } // Appearance val appearanceGroup = layout.appearance val appearanceRadios = mutableListOf<RadioButton>() appearanceRadios.add(layout.appearanceDefault) layout.appearanceDefault.contentDescription = "Appearance Default" appearanceRadios.add(layout.appearanceSepia) layout.appearanceSepia.contentDescription = "Appearance Sepia" appearanceRadios.add(layout.appearanceNight) layout.appearanceNight.contentDescription = "Appearance Night" UIPreset[ReadiumCSSName.appearance]?.let { appearanceGroup.isEnabled = false for (appearanceRadio in appearanceRadios) { appearanceRadio.isEnabled = false } } ?: run { appearanceRadios[appearance.index].isChecked = true appearanceGroup.setOnCheckedChangeListener { _, id -> val i = findIndexOfId(id, list = appearanceRadios) appearance.index = i when (i) { 0 -> { resourcePager.setBackgroundColor(Color.parseColor("#ffffff")) //(resourcePager.focusedChild?.findViewById(R.id.book_title) as? TextView)?.setTextColor(Color.parseColor("#000000")) } 1 -> { resourcePager.setBackgroundColor(Color.parseColor("#faf4e8")) //(resourcePager.focusedChild?.findViewById(R.id.book_title) as? TextView)?.setTextColor(Color.parseColor("#000000")) } 2 -> { resourcePager.setBackgroundColor(Color.parseColor("#000000")) //(resourcePager.focusedChild?.findViewById(R.id.book_title) as? TextView)?.setTextColor(Color.parseColor("#ffffff")) } } updateEnumerable(appearance) updateViewCSS(APPEARANCE_REF) } } // Font size val fontDecreaseButton = layout.fontDecrease val fontIncreaseButton = layout.fontIncrease UIPreset[ReadiumCSSName.fontSize]?.let { fontDecreaseButton.isEnabled = false fontIncreaseButton.isEnabled = false } ?: run { fontDecreaseButton.setOnClickListener { fontSize.decrement() updateIncremental(fontSize) updateViewCSS(FONT_SIZE_REF) } fontIncreaseButton.setOnClickListener { fontSize.increment() updateIncremental(fontSize) updateViewCSS(FONT_SIZE_REF) } } // Publisher defaults val publisherDefaultSwitch = layout.publisherDefault publisherDefaultSwitch.contentDescription = "\u00A0" publisherDefaultSwitch.isChecked = publisherDefault.on publisherDefaultSwitch.setOnCheckedChangeListener { _, b -> publisherDefault.on = b updateSwitchable(publisherDefault) updateViewCSS(PUBLISHER_DEFAULT_REF) } // Vertical scroll val scrollModeSwitch = layout.scrollMode UIPreset[ReadiumCSSName.scroll]?.let { isSet -> scrollModeSwitch.isChecked = isSet scrollModeSwitch.isEnabled = false } ?: run { scrollModeSwitch.isChecked = scrollMode.on scrollModeSwitch.setOnCheckedChangeListener { _, b -> scrollMode.on = scrollModeSwitch.isChecked updateSwitchable(scrollMode) updateViewCSS(SCROLL_REF) val currentFragment = (resourcePager.adapter as R2PagerAdapter).getCurrentFragment() val previousFragment = (resourcePager.adapter as R2PagerAdapter).getPreviousFragment() val nextFragment = (resourcePager.adapter as R2PagerAdapter).getNextFragment() if (currentFragment is R2EpubPageFragment) { currentFragment.webView?.let { webView -> webView.scrollToPosition(webView.progression) (previousFragment as? R2EpubPageFragment)?.webView?.scrollToEnd() (nextFragment as? R2EpubPageFragment)?.webView?.scrollToStart() webView.setScrollMode(b) (previousFragment as? R2EpubPageFragment)?.webView?.setScrollMode(b) (nextFragment as? R2EpubPageFragment)?.webView?.setScrollMode(b) } } } } // Text alignment val alignmentGroup = layout.TextAlignment val alignmentRadios = mutableListOf<RadioButton>() alignmentRadios.add(layout.alignmentLeft) (layout.alignmentLeft).contentDescription = "Alignment Left" alignmentRadios.add(layout.alignmentJustify) layout.alignmentJustify.contentDescription = "Alignment Justified" UIPreset[ReadiumCSSName.textAlignment]?.let { alignmentGroup.isEnabled = false alignmentGroup.isActivated = false for (alignmentRadio in alignmentRadios) { alignmentRadio.isEnabled = false } } ?: run { alignmentRadios[alignment.index].isChecked = true alignmentGroup.setOnCheckedChangeListener { _, i -> alignment.index = findIndexOfId(i, alignmentRadios) publisherDefaultSwitch.isChecked = false updateEnumerable(alignment) updateViewCSS(TEXT_ALIGNMENT_REF) } } // Column count val columnsCountGroup = layout.columns val columnsRadios = mutableListOf<RadioButton>() columnsRadios.add(layout.columnAuto) layout.columnAuto.contentDescription = "Columns Auto" columnsRadios.add(layout.columnOne) layout.columnOne.contentDescription = "Columns 1" columnsRadios.add(layout.columnTwo) layout.columnTwo.contentDescription = "Columns 2" UIPreset[ReadiumCSSName.columnCount]?.let { columnsCountGroup.isEnabled = false columnsCountGroup.isActivated = false for (columnRadio in columnsRadios) { columnRadio.isEnabled = false } } ?: run { columnsRadios[columnsCount.index].isChecked = true columnsCountGroup.setOnCheckedChangeListener { _, id -> val i = findIndexOfId(id, columnsRadios) columnsCount.index = i publisherDefaultSwitch.isChecked = false updateEnumerable(columnsCount) updateViewCSS(COLUMN_COUNT_REF) } } // Page margins val pageMarginsDecreaseButton = layout.pmDecrease val pageMarginsIncreaseButton = layout.pmIncrease val pageMarginsDisplay = layout.pmDisplay pageMarginsDisplay.text = pageMargins.value.toString() UIPreset[ReadiumCSSName.pageMargins]?.let { pageMarginsDecreaseButton.isEnabled = false pageMarginsIncreaseButton.isEnabled = false } ?: run { pageMarginsDecreaseButton.setOnClickListener { pageMargins.decrement() pageMarginsDisplay.text = pageMargins.value.toString() publisherDefaultSwitch.isChecked = false updateIncremental(pageMargins) updateViewCSS(PAGE_MARGINS_REF) } pageMarginsIncreaseButton.setOnClickListener { pageMargins.increment() pageMarginsDisplay.text = pageMargins.value.toString() publisherDefaultSwitch.isChecked = false updateIncremental(pageMargins) updateViewCSS(PAGE_MARGINS_REF) } } // Word spacing val wordSpacingDecreaseButton = layout.wsDecrease val wordSpacingIncreaseButton = layout.wsIncrease val wordSpacingDisplay = layout.wsDisplay wordSpacingDisplay.text = (if (wordSpacing.value == wordSpacing.min) "auto" else wordSpacing.value.toString()) UIPreset[ReadiumCSSName.wordSpacing]?.let { wordSpacingDecreaseButton.isEnabled = false wordSpacingIncreaseButton.isEnabled = false } ?: run { wordSpacingDecreaseButton.setOnClickListener { wordSpacing.decrement() wordSpacingDisplay.text = (if (wordSpacing.value == wordSpacing.min) "auto" else wordSpacing.value.toString()) publisherDefaultSwitch.isChecked = false updateIncremental(wordSpacing) updateViewCSS(WORD_SPACING_REF) } wordSpacingIncreaseButton.setOnClickListener { wordSpacing.increment() wordSpacingDisplay.text = wordSpacing.value.toString() publisherDefaultSwitch.isChecked = false updateIncremental(wordSpacing) updateViewCSS(WORD_SPACING_REF) } } // Letter spacing val letterSpacingDecreaseButton = layout.lsDecrease val letterSpacingIncreaseButton = layout.lsIncrease val letterSpacingDisplay = layout.lsDisplay letterSpacingDisplay.text = (if (letterSpacing.value == letterSpacing.min) "auto" else letterSpacing.value.toString()) UIPreset[ReadiumCSSName.letterSpacing]?.let { letterSpacingDecreaseButton.isEnabled = false letterSpacingIncreaseButton.isEnabled = false } ?: run { letterSpacingDecreaseButton.setOnClickListener { letterSpacing.decrement() letterSpacingDisplay.text = (if (letterSpacing.value == letterSpacing.min) "auto" else letterSpacing.value.toString()) publisherDefaultSwitch.isChecked = false updateIncremental(letterSpacing) updateViewCSS(LETTER_SPACING_REF) } letterSpacingIncreaseButton.setOnClickListener { letterSpacing.increment() letterSpacingDisplay.text = (if (letterSpacing.value == letterSpacing.min) "auto" else letterSpacing.value.toString()) publisherDefaultSwitch.isChecked = false updateIncremental(letterSpacing) updateViewCSS(LETTER_SPACING_REF) } } // Line height val lineHeightDecreaseButton = layout.lhDecrease val lineHeightIncreaseButton = layout.lhIncrease val lineHeightDisplay = layout.lhDisplay lineHeightDisplay.text = (if (lineHeight.value == lineHeight.min) "auto" else lineHeight.value.toString()) UIPreset[ReadiumCSSName.lineHeight]?.let { lineHeightDecreaseButton.isEnabled = false lineHeightIncreaseButton.isEnabled = false } ?: run { lineHeightDecreaseButton.setOnClickListener { lineHeight.decrement() lineHeightDisplay.text = (if (lineHeight.value == lineHeight.min) "auto" else lineHeight.value.toString()) publisherDefaultSwitch.isChecked = false updateIncremental(lineHeight) updateViewCSS(LINE_HEIGHT_REF) } lineHeightIncreaseButton.setOnClickListener { lineHeight.increment() lineHeightDisplay.text = (if (lineHeight.value == lineHeight.min) "auto" else lineHeight.value.toString()) publisherDefaultSwitch.isChecked = false updateIncremental(lineHeight) updateViewCSS(LINE_HEIGHT_REF) } } // Brightness val brightnessSeekbar = layout.brightness val brightness = preferences.getInt("reader_brightness", 50) brightnessSeekbar.progress = brightness brightnessSeekbar.setOnSeekBarChangeListener( object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(bar: SeekBar, progress: Int, from_user: Boolean) { val backLightValue = progress.toFloat() / 100 val layoutParams = (context as AppCompatActivity).window.attributes layoutParams.screenBrightness = backLightValue context.window.attributes = layoutParams preferences.edit().putInt("reader_brightness", progress).apply() } override fun onStartTrackingTouch(bar: SeekBar) { // Nothing } override fun onStopTrackingTouch(bar: SeekBar) { // Nothing } }) // Speech speed val speechSeekBar = layout.TTSSpeechSpeed //Get the user settings value or set the progress bar to a neutral position (1 time speech speed). val speed = preferences.getInt("reader_TTS_speed", (2.75 * 3.toDouble() / 11.toDouble() * 100).toInt()) speechSeekBar.progress = speed speechSeekBar.setOnSeekBarChangeListener( object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(bar: SeekBar, progress: Int, from_user: Boolean) { // Nothing } override fun onStartTrackingTouch(bar: SeekBar) { // Nothing } override fun onStopTrackingTouch(bar: SeekBar) { preferences.edit().putInt("reader_TTS_speed", bar.progress).apply() } }) return userSettingsPopup } }
social_login/android/app/src/main/java/com/sociallogin/MainActivity.kt
1404469896
package com.sociallogin import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled import com.facebook.react.defaults.DefaultReactActivityDelegate class MainActivity : ReactActivity() { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ override fun getMainComponentName(): String = "SocialLogin" /** * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] */ override fun createReactActivityDelegate(): ReactActivityDelegate = DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) }
social_login/android/app/src/main/java/com/sociallogin/MainApplication.kt
1603675876
package com.sociallogin import android.app.Application import com.facebook.react.PackageList import com.facebook.react.ReactApplication import com.facebook.react.ReactHost import com.facebook.react.ReactNativeHost import com.facebook.react.ReactPackage import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost import com.facebook.react.defaults.DefaultReactNativeHost import com.facebook.react.flipper.ReactNativeFlipper import com.facebook.soloader.SoLoader class MainApplication : Application(), ReactApplication { override val reactNativeHost: ReactNativeHost = object : DefaultReactNativeHost(this) { override fun getPackages(): List<ReactPackage> = PackageList(this).packages.apply { // Packages that cannot be autolinked yet can be added manually here, for example: // add(MyReactNativePackage()) } override fun getJSMainModuleName(): String = "index" override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED } override val reactHost: ReactHost get() = getDefaultReactHost(this.applicationContext, reactNativeHost) override fun onCreate() { super.onCreate() SoLoader.init(this, false) if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { // If you opted-in for the New Architecture, we load the native entry point for this app. load() } ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager) } }
MyAmplifyApp3/app/src/androidTest/java/com/aaa/myamplifyapp3/ExampleInstrumentedTest.kt
3808022553
package com.aaa.myamplifyapp3 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.aaa.myamplifyapp3", appContext.packageName) } }
MyAmplifyApp3/app/src/test/java/com/aaa/myamplifyapp3/ExampleUnitTest.kt
1911691643
package com.aaa.myamplifyapp3 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) } }
MyAmplifyApp3/app/src/main/java/com/aaa/myamplifyapp3/MainActivity.kt
3836325986
package com.aaa.myamplifyapp3 import android.content.Context import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.amazonaws.mobile.client.AWSMobileClient import com.amazonaws.mobile.client.Callback import com.amazonaws.mobile.client.UserStateDetails import com.amazonaws.mobile.config.AWSConfiguration import com.amazonaws.mobileconnectors.pinpoint.PinpointConfiguration import com.amazonaws.mobileconnectors.pinpoint.PinpointManager import com.amazonaws.mobileconnectors.pinpoint.analytics.AnalyticsEvent import com.amazonaws.mobileconnectors.pinpoint.targeting.notification.NotificationClient import com.amazonaws.mobileconnectors.pinpoint.targeting.notification.NotificationDetails import com.google.android.gms.tasks.OnCompleteListener import com.google.firebase.messaging.FirebaseMessaging import com.google.firebase.messaging.RemoteMessage class MainActivity : AppCompatActivity() { companion object { const val TAG = "MyAmplifyApp3" } private lateinit var mPinpointManager: PinpointManager private fun getPinpointManager(applicationContext: Context): PinpointManager { if (!this::mPinpointManager.isInitialized) { // Initialize the AWS Mobile Client val awsConfig = AWSConfiguration(applicationContext) println("★★★ awsConfig $awsConfig") AWSMobileClient.getInstance() .initialize(applicationContext, awsConfig, object : Callback<UserStateDetails> { override fun onResult(userStateDetails: UserStateDetails) { Log.i("INIT", userStateDetails.userState.toString()) } override fun onError(e: Exception) { Log.e("INIT", "Initialization error.", e) } }) val pinpointConfig = PinpointConfiguration( applicationContext, AWSMobileClient.getInstance(), awsConfig ) println("★★★ pinpointConfig $pinpointConfig") mPinpointManager = PinpointManager(pinpointConfig) } return mPinpointManager } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun onStart() { super.onStart() // FCMトークン取得 FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task -> if (!task.isSuccessful) { Log.w(TAG, "Fetching FCM registration token failed", task.exception) return@OnCompleteListener } // Get new FCM registration token val token = task.result // Log and toast val msg = getString(R.string.msg_token_fmt, token) Log.d(TAG, msg) Toast.makeText(baseContext, msg, Toast.LENGTH_LONG).show() }) try { // https://qiita.com/Idenon/items/a77f2da4de78dd0db74d mPinpointManager = getPinpointManager(applicationContext) mPinpointManager.sessionClient.startSession() println("★★★ pinpointManager $mPinpointManager") println("★★★ pinpointManager complete") // プッシュ通知からアプリを開いた場合intentにデータが入っている val campaignId = intent.getStringExtra("campaignId") val treatmentId = intent.getStringExtra("treatmentId") val campaignActivityId = intent.getStringExtra("campaignActivityId") val title = intent.getStringExtra("title") val body = intent.getStringExtra("body") if(campaignId != null && treatmentId != null && campaignActivityId != null && title != null && body != null){ notificationOpenedEvent(campaignId, treatmentId, campaignActivityId, title, body) } }catch (e: Exception){ e.printStackTrace() } val button: Button = findViewById<Button>(R.id.button2) button.setOnClickListener { // submitEvent() } } override fun onStop() { super.onStop() mPinpointManager.sessionClient.stopSession() mPinpointManager.analyticsClient.submitEvents() } private fun submitEvent(){ mPinpointManager.analyticsClient?.submitEvents() println("★★★ submitEvent pinpointManager.analyticsClient ${mPinpointManager.analyticsClient}") println("★★★ submitEvent pinpointManager.analyticsClient.allEvents ${mPinpointManager.analyticsClient.allEvents}") } private fun notificationOpenedEvent(campaignId: String, treatmentId: String, campaignActivityId: String, title: String, body: String){ println("★★★ notificationOpenedEvent") val event: AnalyticsEvent? = mPinpointManager.analyticsClient.createEvent("_campaign.opened_notification") .withAttribute("_campaign_id", campaignId) .withAttribute("treatment_id", treatmentId) .withAttribute("campaign_activity_id", campaignActivityId) .withAttribute("notification_title", title) .withAttribute("notification_body", body) .withMetric("Opened", 1.0) println("★★★ notificationOpenedEvent event $event") mPinpointManager.analyticsClient?.recordEvent(event) submitEvent() } }
MyAmplifyApp3/app/src/main/java/com/aaa/myamplifyapp3/MyAmplifyApp3.kt
3945365821
package com.aaa.myamplifyapp3 import android.app.Application class MyAmplifyApp3: Application() { override fun onCreate() { super.onCreate() // try { // Amplify.addPlugin(AWSCognitoAuthPlugin()) // Amplify.addPlugin(AWSPinpointPushNotificationsPlugin()) // Amplify.addPlugin(AWSPinpointAnalyticsPlugin()) // // 分析で使用する // Amplify.addPlugin(AWSDataStorePlugin()) // Amplify.configure(applicationContext) // Log.i("MyAmplifyApp", "Initialized Amplify") // // val event = AnalyticsEvent.builder() // .name("PasswordReset") // .addProperty("Channel", "SMS") // .addProperty("Successful", true) // .addProperty("ProcessDuration", 792) // .addProperty("UserAge", 120.3) // .build() // Amplify.Analytics.recordEvent(event) // } catch (error: AmplifyException) { // Log.e("MyAmplifyApp", "Could not initialize Amplify", error) // } } }
MyAmplifyApp3/app/src/main/java/com/aaa/myamplifyapp3/AuthorityRequestActivity.kt
3563982986
package com.aaa.myamplifyapp3 import android.Manifest import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity class AuthorityRequestActivity : AppCompatActivity() { private val mIsGrantedMap: MutableMap<String, Boolean> = mutableMapOf() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // 権限要求 requestPermission() } private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions() ) { permissions -> permissions.entries.forEach { val permissionName = it.key val isGranted = it.value mIsGrantedMap[permissionName] = isGranted } // 権限がすべて許可されていた場合は待機画面に遷移する。 if (checkAllPermissionsGranted()) { showStandbyScreenActivity() } else { Toast.makeText( this, "権限を許可してください。", Toast.LENGTH_LONG ).show() finish() } } private fun checkAllPermissionsGranted(): Boolean { // すべての値がtrueかどうかを確認 return mIsGrantedMap.values.all { it } } private fun requestPermission() { requestPermissionLauncher.launch( arrayOf( // 通知 Manifest.permission.POST_NOTIFICATIONS, Manifest.permission.FOREGROUND_SERVICE, Manifest.permission.ACCESS_NETWORK_STATE, ) ) } private fun showStandbyScreenActivity() { startActivity(Intent(this, MainActivity::class.java)) finish() } }
MyAmplifyApp3/app/src/main/java/com/aaa/myamplifyapp3/MyFirebaseMessagingService.kt
1461722042
package com.aaa.myamplifyapp3 import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.media.RingtoneManager import android.os.Build import android.util.Log import androidx.core.app.NotificationCompat import com.amazonaws.mobileconnectors.pinpoint.analytics.AnalyticsEvent //import com.amplifyframework.core.Amplify //import com.amplifyframework.notifications.pushnotifications.NotificationContentProvider //import com.amplifyframework.notifications.pushnotifications.NotificationPayload import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage class MyFirebaseMessagingService: FirebaseMessagingService() { companion object { private const val TAG = "MyFirebaseMsgService" // var notificationPayload: NotificationPayload? = null } private data class MessageFCM( var messageTitle: String = "", var messageBody: String = "", ) // [START receive_message] override fun onMessageReceived(remoteMessage: RemoteMessage) { super.onMessageReceived(remoteMessage) println("★★★ remoteMessage: $remoteMessage") // メッセージが届いていない場合は、こちらを参照してください: https://goo.gl/39bRNJ Log.d(TAG, "From: ${remoteMessage.from}") // メッセージがデータペイロードを含んでいるか確認します。 if (remoteMessage.data.isNotEmpty()) { // データが長時間実行されるジョブによって処理される必要があるか確認します // if (needsToBeScheduled()) { // // 長時間実行されるタスク(10秒以上)の場合は WorkManager を使用します。 //// scheduleJob() // } else { // // 10秒以内にメッセージを処理します // handleNow() // } handleNow() } // 通知の生成 sendNotification(remoteMessage) } // [END receive_message] private fun needsToBeScheduled() = true // [START on_new_token] /** * Called if the FCM registration token is updated. This may occur if the security of * the previous token had been compromised. Note that this is called when the * FCM registration token is initially generated so this is where you would retrieve the token. */ override fun onNewToken(token: String) { Log.d(TAG, "Refreshed token: $token") // Register device with Pinpoint // Amplify.Notifications.Push.registerDevice(token, // { Log.i(TAG, "Successfully registered device") }, // { error -> Log.e(TAG, "Error registering device", error) } // ) sendRegistrationToServer(token) } private fun handleNow() { Log.d(TAG, "Short lived task is done.") } private fun sendRegistrationToServer(token: String?) { // TODO: Implement this method to send token to your app server. Log.d(TAG, "sendRegistrationTokenToServer($token)") } private fun sendNotification(remoteMessage: RemoteMessage) { // RemoteMessage を NoticePayload に変換する // val notificationPayload = NotificationPayload(NotificationContentProvider.FCM(remoteMessage.data)) // Pinpoint から送信された通知を Amplify で処理する必要がある // val isAmplifyMessage = Amplify.Notifications.Push.shouldHandleNotification(notificationPayload!!) // if (isAmplifyMessage) { // // Record notification received with Amplify // Amplify.Notifications.Push.recordNotificationReceived(notificationPayload, // { Log.i(TAG, "Successfully recorded a notification received") }, // { error -> Log.e(TAG, "Error recording notification received", error) } // ) // } var campaignId: String = "" var treatmentId: String = "" var campaignActivityId: String = "" var title: String = "" var body: String = "" try { // PinPointからのメッセージ取得 campaignId = remoteMessage.data.getValue("pinpoint.campaign.campaign_id") ?: "" treatmentId = remoteMessage.data.getValue("pinpoint.campaign.treatment_id") ?: "" campaignActivityId = remoteMessage.data.getValue("pinpoint.campaign.campaign_activity_id") ?: "" title = remoteMessage.data.getValue("pinpoint.notification.title") ?: "" body = remoteMessage.data.getValue("pinpoint.notification.body") ?: "" }catch (e: NoSuchElementException){ e.printStackTrace() } try { // PinPointからのメッセージ取得 title = remoteMessage.data.getValue("pinpoint.notification.title") ?: "" body = remoteMessage.data.getValue("pinpoint.notification.body") ?: "" }catch (e: NoSuchElementException){ e.printStackTrace() } val messageFCM = MessageFCM() messageFCM.messageTitle = title messageFCM.messageBody = body println("★★★ remoteMessage.data: ${remoteMessage.data}") val notificationId = System.currentTimeMillis().toInt() // val intent = Intent(this, MainActivity::class.java) // intent.putExtra("notificationPayload", notificationPayload) // PinPointの情報をintentに設定(起動時にMainActivityで受け取る) val intent = Intent(this, MainActivity::class.java) intent.putExtra("campaignId", campaignId) intent.putExtra("treatmentId", treatmentId) intent.putExtra("campaignActivityId", campaignActivityId) intent.putExtra("title", title) intent.putExtra("body", body) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) val requestCode = 100 val pendingIntent = PendingIntent.getActivity( this, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE // intentを保持するために必要。(notificationPayloadの受け渡しのため) // PendingIntent.FLAG_IMMUTABLE, // これは既存のインテントが保持されない。 ) val channelId = "fcm_default_channel" val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) val notificationBuilder = NotificationCompat.Builder(this, channelId) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(messageFCM.messageTitle) .setContentText(messageFCM.messageBody) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent) .setPriority(NotificationCompat.PRIORITY_DEFAULT) // 通知の優先度 val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // Since android Oreo notification channel is needed. val channel = NotificationChannel( channelId, "Channel human readable title", NotificationManager.IMPORTANCE_DEFAULT, ) notificationManager.createNotificationChannel(channel) // val notificationId = System.currentTimeMillis().toInt() notificationManager.notify(notificationId, notificationBuilder.build()) } // internal class MyWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) { // override fun doWork(): Result { // // TODO(developer): add long running task here. // return Result.success() // } // } }
Brainshop-chatbot-app/app/src/androidTest/java/com/thezayin/chatbottesting/ExampleInstrumentedTest.kt
1044688423
package com.thezayin.chatbottesting import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.thezayin.chatbottesting", appContext.packageName) } }
Brainshop-chatbot-app/app/src/test/java/com/thezayin/chatbottesting/ExampleUnitTest.kt
107884769
package com.thezayin.chatbottesting 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) } }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/ui/theme/Color.kt
3709419459
package com.thezayin.chatbottesting.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/ui/theme/Theme.kt
2662248087
package com.thezayin.chatbottesting.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun ChatbottestingTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/ui/theme/Type.kt
3369376514
package com.thezayin.chatbottesting.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/MainActivity.kt
2411475134
package com.thezayin.chatbottesting import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.annotation.RequiresExtension import androidx.hilt.navigation.compose.hiltViewModel import com.thezayin.chatbottesting.domain.model.Message import com.thezayin.chatbottesting.presentation.ChatScreen import com.thezayin.chatbottesting.presentation.ChatViewModel import com.thezayin.chatbottesting.ui.theme.ChatbottestingTheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { @RequiresExtension(extension = Build.VERSION_CODES.S, version = 7) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ChatbottestingTheme { ChatScreen() } } } }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/di/AppModule.kt
2472087001
package com.thezayin.chatbottesting.di import com.thezayin.chatbottesting.data.BotRepositoryImpl import com.thezayin.chatbottesting.data.botapi.BotApi import com.thezayin.chatbottesting.domain.repo.BotRepository import com.thezayin.chatbottesting.domain.usecase.BotUseCase import com.thezayin.chatbottesting.domain.usecase.MessageUseCases import com.thezayin.chatbottesting.utils.Constants.BASE_URL import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Singleton @Provides fun provideBotApi(): BotApi { return Retrofit.Builder().baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()).build() .create(BotApi::class.java) } @Provides @Singleton fun provideBotRepository(botApi: BotApi): BotRepository { return BotRepositoryImpl(botApi) } @Provides @Singleton fun provideUseCase(repository: BotRepository) = MessageUseCases(botUseCase = BotUseCase(repository)) }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/utils/Application.kt
686880067
package com.thezayin.chatbottesting.utils import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class Application:Application() { }
Brainshop-chatbot-app/app/src/main/java/com/thezayin/chatbottesting/utils/Response.kt
1943579850
package com.thezayin.chatbottesting.utils sealed class Response<out T> { object Loading : Response<Nothing>() data class Failure(val e: String) : Response<Nothing>() data class Success<out T>(val data: T) : Response<T>() }