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

Download images #68

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ plugins {
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
id("com.google.devtools.ksp")
id("kotlin-parcelize")
}

android {
Expand Down
26 changes: 26 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="32"
Expand Down Expand Up @@ -37,12 +40,35 @@

<data android:scheme="https" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />

<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />

<data
android:host="downloads"
android:scheme="hviewer" />

</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
<service
android:name=".ui.page.post.DownloadService"
android:foregroundServiceType="dataSync" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
</application>

</manifest>
13 changes: 13 additions & 0 deletions app/src/main/java/com/paulcoding/hviewer/helper/File.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.paulcoding.hviewer.helper

import android.content.Context
import android.os.Environment
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.File
Expand All @@ -19,9 +20,21 @@ val Context.crashLogDir
val Context.configFile
get() = File(scriptsDir, CONFIG_FILE)

val downloadDir: File = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "HViewer"
)

fun Context.setupPaths() {
scriptsDir.mkdir()
crashLogDir.mkdir()

if (!downloadDir.exists()) {
downloadDir.mkdirs()
val nomediaFile = File(downloadDir, ".nomedia")
if (!nomediaFile.exists()) {
nomediaFile.createNewFile()
}
}
}

fun Context.writeFile(data: String, fileName: String, fileDir: File = scriptsDir): File {
Expand Down
35 changes: 35 additions & 0 deletions app/src/main/java/com/paulcoding/hviewer/helper/ImageDownloader.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.paulcoding.hviewer.helper

import kotlinx.coroutines.*
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream

object ImageDownloader {
private val client = OkHttpClient()

suspend fun downloadImage(url: String, outputFile: File): Boolean {
return withContext(Dispatchers.IO) {
try {
val request = Request.Builder().url(url).build()
val response = client.newCall(request).execute()

if (!response.isSuccessful) return@withContext false

val inputStream: InputStream? = response.body?.byteStream()
val outputStream = FileOutputStream(outputFile)

inputStream?.copyTo(outputStream)
outputStream.close()
inputStream?.close()

return@withContext true
} catch (e: Exception) {
e.printStackTrace()
return@withContext false
}
}
}
}
4 changes: 3 additions & 1 deletion app/src/main/java/com/paulcoding/hviewer/model/SiteModel.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.paulcoding.hviewer.model

import android.os.Parcelable
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
Expand All @@ -12,11 +13,12 @@ import androidx.compose.ui.unit.dp
import coil3.compose.AsyncImage
import com.paulcoding.hviewer.R

@kotlinx.parcelize.Parcelize
data class SiteConfig(
val baseUrl: String = "",
val scriptFile: String = "",
val tags: Map<String, String> = mapOf(),
) {
) : Parcelable {
private val icon
get() = "https://www.google.com/s2/favicons?sz=64&domain=$baseUrl"

Expand Down
27 changes: 26 additions & 1 deletion app/src/main/java/com/paulcoding/hviewer/ui/page/AppEntry.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@ import androidx.navigation.NamedNavArgument
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavDeepLink
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import androidx.navigation.navDeepLink
import com.paulcoding.hviewer.R
import com.paulcoding.hviewer.helper.makeToast
import com.paulcoding.hviewer.model.PostItem
Expand All @@ -31,6 +34,7 @@ import com.paulcoding.hviewer.model.Tag
import com.paulcoding.hviewer.network.Github
import com.paulcoding.hviewer.preference.Preferences
import com.paulcoding.hviewer.ui.favorite.FavoritePage
import com.paulcoding.hviewer.ui.page.downloads.DownloadsPage
import com.paulcoding.hviewer.ui.page.editor.EditorPage
import com.paulcoding.hviewer.ui.page.editor.ListScriptPage
import com.paulcoding.hviewer.ui.page.history.HistoryPage
Expand Down Expand Up @@ -82,6 +86,7 @@ fun AppEntry(intent: Intent?) {
}

LaunchedEffect(updatedIntent) {

updatedIntent?.apply {
when (action) {
Intent.ACTION_SEND -> {
Expand All @@ -93,7 +98,13 @@ fun AppEntry(intent: Intent?) {
}

Intent.ACTION_VIEW -> {
handleIntentUrl(data.toString())
// TODO: why deeplink not working
if (data.toString().startsWith("hviewer://")) {
val route = data.toString().substringAfter("hviewer://")
navController.navigate(route)
} else {
handleIntentUrl(data.toString())
}
}

else -> {
Expand All @@ -120,6 +131,9 @@ fun AppEntry(intent: Intent?) {
navToHistory = {
navController.navigate(Route.HISTORY)
},
navToDownloads = {
navController.navigate("downloads/")
},
goBack = { navController.popBackStack() })
}
animatedComposable(Route.SETTINGS) {
Expand Down Expand Up @@ -250,6 +264,17 @@ fun AppEntry(intent: Intent?) {
appViewModel = appViewModel, siteConfigs = siteConfigs
)
}
animatedComposable(
route = "downloads/{path}",
arguments = listOf(navArgument("path") { type = NavType.StringType }),
deepLinks = listOf(navDeepLink { uriPattern = "hviewer://downloads/{path}" })
) { backStackEntry ->
val path = backStackEntry.arguments?.getString("path")
DownloadsPage(
goBack = navController::popBackStack,
initialDir = path
)
}
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
package com.paulcoding.hviewer.ui.page.downloads

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Folder
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.paulcoding.hviewer.R
import com.paulcoding.hviewer.helper.downloadDir
import com.paulcoding.hviewer.ui.component.HBackIcon
import com.paulcoding.hviewer.ui.component.HEmpty
import com.paulcoding.hviewer.ui.component.HIcon
import com.paulcoding.hviewer.ui.page.post.ImageModal
import com.paulcoding.hviewer.ui.page.post.PostImage
import java.io.File

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DownloadsPage(
goBack: () -> Unit,
initialDir: String? = null,
) {
var dirs by remember { mutableStateOf(emptyList<File>()) }
var selectedDir by remember { mutableStateOf<File?>(null) }

LaunchedEffect(Unit) {
downloadDir.listFiles()?.filter { it.isDirectory }?.toList()?.let {
dirs = it
}
initialDir?.let {
if (File(it).exists()) selectedDir = File(it)
}
}
Scaffold(topBar = {
TopAppBar(title = { Text(stringResource(R.string.downloads)) }, navigationIcon = {
HBackIcon { goBack() }
}, actions = {
if (selectedDir != null) HIcon(
Icons.Outlined.Close,
) { selectedDir = null }
})
}) { paddings ->
Column(modifier = Modifier.padding(paddings)) {
if (selectedDir == null) LazyColumn(
modifier = Modifier.padding(horizontal = 12.dp),
contentPadding = PaddingValues(vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
items(dirs) {
Row(
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.clickable {
selectedDir = it
},
) {
Icon(Icons.Outlined.Folder, it.name)
Text(
it.name, modifier = Modifier.padding(12.dp)
)
}
}
if (dirs.isEmpty()) item {
HEmpty()
}
}
else {
ImageList(selectedDir!!)
}
}
}
}

@Composable
internal fun ImageList(selectedDir: File) {
var selectedImage by remember { mutableStateOf<String?>(null) }
var isSystemBarHidden by remember { mutableStateOf(false) }
val listState = rememberLazyListState()

val images by remember {
derivedStateOf {
selectedDir.listFiles()?.map { it.absolutePath } ?: emptyList()
}
}

LazyColumn(
state = listState, verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(images, key = { it }) { image ->
PostImage(
url = image,
onDoubleTap = {
selectedImage = image
},
onTap = {
isSystemBarHidden = !isSystemBarHidden
},
)
}
if (images.isEmpty()) item {
HEmpty()
}
}
if (selectedImage != null) {
ImageModal(url = selectedImage!!) {
selectedImage = null
}
}
}
Loading