-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathOSIABPdfHelper.kt
More file actions
65 lines (58 loc) · 2.24 KB
/
OSIABPdfHelper.kt
File metadata and controls
65 lines (58 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.outsystems.plugins.inappbrowser.osinappbrowserlib.helpers
import android.content.Context
import java.io.File
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
object OSIABPdfHelper {
interface UrlFactory {
fun create(url: String): URL
}
private class DefaultUrlFactory : UrlFactory {
override fun create(url: String): URL = URL(url)
}
fun isContentTypeApplicationPdf(urlString: String): Boolean {
return try {
// Try to identify if the URL is a PDF using a HEAD request.
// If the server does not implement HEAD correctly or does not return the expected content-type,
// fall back to a GET request, since some servers only return the correct type for GET.
if (checkPdfByRequest(urlString, method = "HEAD")) {
true
} else {
checkPdfByRequest(urlString, method = "GET")
}
} catch (_: Exception) {
false
}
}
fun checkPdfByRequest(urlString: String, method: String, urlFactory: UrlFactory = DefaultUrlFactory()): Boolean {
var conn: HttpURLConnection? = null
return try {
conn = (urlFactory.create(urlString).openConnection() as? HttpURLConnection)
conn?.run {
instanceFollowRedirects = true
requestMethod = method
if (method == "GET") {
setRequestProperty("Range", "bytes=0-0")
}
connect()
val type = contentType?.lowercase()
val disposition = getHeaderField("Content-Disposition")?.lowercase()
type == "application/pdf" ||
(type.isNullOrEmpty() && disposition?.contains(".pdf") == true)
} ?: false
} finally {
conn?.disconnect()
}
}
@Throws(IOException::class)
fun downloadPdfToCache(context: Context, url: String): File {
val pdfFile = File(context.cacheDir, "temp_${System.currentTimeMillis()}.pdf")
URL(url).openStream().use { input ->
pdfFile.outputStream().use { output ->
input.copyTo(output)
}
}
return pdfFile
}
}