Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix crash when opening epub books from shared storage #75

Merged
merged 3 commits into from
Sep 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .idea/deploymentTargetDropDown.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 17 additions & 5 deletions app/src/main/java/com/starry/myne/repo/BookRepository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ import com.starry.myne.repo.models.BookSet
import com.starry.myne.repo.models.ExtraInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.*
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
Expand Down Expand Up @@ -110,8 +114,7 @@ class BookRepository {

suspend fun getExtraInfo(bookName: String): ExtraInfo? = suspendCoroutine { continuation ->
val encodedName = URLEncoder.encode(bookName, "UTF-8")
val url =
"${googleBooksUrl}?q=$encodedName&startIndex=0&maxResults=1&apiKey=$googleApiKey"
val url = "${googleBooksUrl}?q=$encodedName&startIndex=0&maxResults=1&key=$googleApiKey"
val request = Request.Builder().get().url(url).build()
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Expand Down Expand Up @@ -140,13 +143,22 @@ class BookRepository {
val imageLinks = volumeInfo.getJSONObject("imageLinks")
// Build Extra info.
val coverImage = imageLinks.getString("thumbnail")
val pageCount = volumeInfo.getInt("pageCount")
val description = volumeInfo.getString("description")
val pageCount = try {
volumeInfo.getInt("pageCount")
} catch (exc: JSONException) {
0
}
val description = try {
volumeInfo.getString("description")
} catch (exc: JSONException) {
""
}
ExtraInfo(coverImage, pageCount, description)
} else {
null
}
} catch (exc: JSONException) {
exc.printStackTrace()
null
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,11 @@ fun NavGraph(
},
) { backStackEntry ->
val bookId = backStackEntry.arguments!!.getString(BOOK_ID_ARG_KEY)!!
ReaderDetailScreen(bookId = bookId, navController = navController)
ReaderDetailScreen(
bookId = bookId,
navController = navController,
networkStatus = networkStatus
)
}

/** Settings Screen */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.starry.myne.R
import com.starry.myne.ui.common.CustomTopAppBar
import com.starry.myne.ui.navigation.Screens
import com.starry.myne.ui.common.CustomTopAppBar
import com.starry.myne.ui.screens.categories.viewmodels.CategoryViewModel
import com.starry.myne.ui.theme.figeronaFont
import java.util.Locale
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,11 @@ import coil.annotation.ExperimentalCoilApi
import com.starry.myne.R
import com.starry.myne.others.BookLanguage
import com.starry.myne.others.NetworkObserver
import com.starry.myne.ui.navigation.Screens
import com.starry.myne.ui.common.BookItemCard
import com.starry.myne.ui.common.CustomTopAppBar
import com.starry.myne.ui.common.NoBooksAvailable
import com.starry.myne.ui.common.ProgressDots
import com.starry.myne.ui.navigation.Screens
import com.starry.myne.ui.screens.categories.viewmodels.CategoryViewModel
import com.starry.myne.ui.screens.home.composables.LanguageItem
import com.starry.myne.ui.screens.other.NetworkError
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,9 @@ import coil.annotation.ExperimentalCoilApi
import com.starry.myne.R
import com.starry.myne.others.BookLanguage
import com.starry.myne.others.NetworkObserver
import com.starry.myne.ui.navigation.Screens
import com.starry.myne.ui.common.BookItemCard
import com.starry.myne.ui.common.ProgressDots
import com.starry.myne.ui.navigation.Screens
import com.starry.myne.ui.screens.home.viewmodels.HomeViewModel
import com.starry.myne.ui.screens.home.viewmodels.UserAction
import com.starry.myne.ui.screens.other.NetworkError
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ import com.airbnb.lottie.compose.rememberLottieComposition
import com.starry.myne.BuildConfig
import com.starry.myne.MainActivity
import com.starry.myne.R
import com.starry.myne.ui.common.CustomTopAppBar
import com.starry.myne.ui.navigation.Screens
import com.starry.myne.ui.common.CustomTopAppBar
import com.starry.myne.ui.screens.library.viewmodels.LibraryViewModel
import com.starry.myne.ui.screens.settings.viewmodels.ThemeMode
import com.starry.myne.ui.theme.figeronaFont
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import java.io.FileInputStream
import kotlin.properties.Delegates

@AndroidEntryPoint
Expand Down Expand Up @@ -212,10 +213,13 @@ class ReaderActivity : AppCompatActivity(), ReaderClickListener {

// External book.
} else if (isExternalBook) {
intent.data!!.path?.let {
viewModel.loadEpubBookExternal(it, onLoaded = { res ->
adapter.allChapters = res.epubBook!!.chapters
})
intent?.data?.let {
contentResolver.openInputStream(it)?.let { ips ->
viewModel.loadEpubBookExternal(ips as FileInputStream, onLoaded = { epubBook ->
adapter.allChapters = epubBook.chapters
ips.close()
})
}
}
} else {
getString(R.string.error).toToast(this, Toast.LENGTH_LONG)
Expand Down Expand Up @@ -265,8 +269,9 @@ class ReaderActivity : AppCompatActivity(), ReaderClickListener {
super.onPause()
val layoutManager = (binding.readerRecyclerView.layoutManager as LinearLayoutManager)
val currentPosition = layoutManager.findLastVisibleItemPosition()
val currentOffset = layoutManager.findViewByPosition(currentPosition)!!.top
mRVPositionAndOffset = Pair(currentPosition, currentOffset)
layoutManager.findViewByPosition(currentPosition)?.let {
mRVPositionAndOffset = Pair(currentPosition, it.top)
}
}

override fun onConfigurationChanged(newConfig: Configuration) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.starry.myne.MainActivity
import com.starry.myne.R
import com.starry.myne.others.NetworkObserver
import com.starry.myne.ui.common.CustomTopAppBar
import com.starry.myne.ui.common.ProgressDots
import com.starry.myne.ui.common.simpleVerticalScrollbar
Expand All @@ -94,11 +95,15 @@ import com.starry.myne.utils.getActivity
@ExperimentalMaterial3Api
@ExperimentalMaterialApi
@Composable
fun ReaderDetailScreen(bookId: String, navController: NavController) {
fun ReaderDetailScreen(
bookId: String,
navController: NavController,
networkStatus: NetworkObserver.Status
) {
val viewModel: ReaderDetailViewModel = hiltViewModel()
val state = viewModel.state

LaunchedEffect(key1 = true) { viewModel.loadEbookData(bookId) }
LaunchedEffect(key1 = true) { viewModel.loadEbookData(bookId, networkStatus) }

val context = LocalContext.current
val settingsVM = (context.getActivity() as MainActivity).settingsViewModel
Expand Down Expand Up @@ -448,6 +453,6 @@ fun ReaderError(navController: NavController) {
@Preview(showBackground = true)
@Composable
fun EpubDetailScreenPV() {
ReaderDetailScreen("", rememberNavController())
ReaderDetailScreen("", rememberNavController(), NetworkObserver.Status.Available)
//ReaderError(rememberNavController())
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import com.starry.myne.database.reader.ReaderDao
import com.starry.myne.database.reader.ReaderItem
import com.starry.myne.epub.createEpubBook
import com.starry.myne.epub.models.EpubBook
import com.starry.myne.others.NetworkObserver
import com.starry.myne.repo.BookRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
Expand Down Expand Up @@ -61,13 +62,15 @@ class ReaderDetailViewModel @Inject constructor(
}

var state by mutableStateOf(ReaderDetailScreenState())
fun loadEbookData(bookId: String) {
fun loadEbookData(bookId: String, networkStatus: NetworkObserver.Status) {
viewModelScope.launch(Dispatchers.IO) {
// build EbookData.
val libraryItem = libraryDao.getItemById(bookId.toInt())!!
state = try {
val coverImage: String? = try {
bookRepository.getExtraInfo(libraryItem.title)?.coverImage
if (networkStatus == NetworkObserver.Status.Available) bookRepository.getExtraInfo(
libraryItem.title
)?.coverImage else null
} catch (exc: Exception) {
null
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.FileInputStream
import javax.inject.Inject


Expand Down Expand Up @@ -101,12 +102,12 @@ class ReaderViewModel @Inject constructor(
}
}

fun loadEpubBookExternal(filePath: String, onLoaded: (ReaderScreenState) -> Unit) {
fun loadEpubBookExternal(fileStream: FileInputStream, onLoaded: (EpubBook) -> Unit) {
viewModelScope.launch(Dispatchers.IO) {
// parse and create epub book
val epubBook = createEpubBook(filePath)
val epubBook = createEpubBook(fileStream)
state = state.copy(epubBook = epubBook)
onLoaded(state)
onLoaded(state.epubBook!!)
// Added some delay to avoid choppy animation.
delay(200L)
state = state.copy(isLoading = false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ import coil.annotation.ExperimentalCoilApi
import com.starry.myne.BuildConfig
import com.starry.myne.MainActivity
import com.starry.myne.R
import com.starry.myne.ui.common.CustomTopAppBar
import com.starry.myne.ui.navigation.Screens
import com.starry.myne.ui.common.CustomTopAppBar
import com.starry.myne.ui.screens.settings.viewmodels.SettingsViewModel
import com.starry.myne.ui.screens.settings.viewmodels.ThemeMode
import com.starry.myne.ui.theme.figeronaFont
Expand Down