parent
acaed246cc
commit
055796fceb
@ -0,0 +1,54 @@ |
||||
package xyz.fycz.myreader.greendao.entity; |
||||
|
||||
import org.greenrobot.greendao.annotation.Entity; |
||||
import org.greenrobot.greendao.annotation.Id; |
||||
import org.greenrobot.greendao.annotation.Generated; |
||||
|
||||
/** |
||||
* @author fengyue |
||||
* @date 2022/1/18 10:20 |
||||
*/ |
||||
@Entity |
||||
public class Cache { |
||||
@Id |
||||
private String key; |
||||
|
||||
private String value; |
||||
|
||||
private long deadLine; |
||||
|
||||
@Generated(hash = 1252535078) |
||||
public Cache(String key, String value, long deadLine) { |
||||
this.key = key; |
||||
this.value = value; |
||||
this.deadLine = deadLine; |
||||
} |
||||
|
||||
@Generated(hash = 1305017356) |
||||
public Cache() { |
||||
} |
||||
|
||||
public String getKey() { |
||||
return this.key; |
||||
} |
||||
|
||||
public void setKey(String key) { |
||||
this.key = key; |
||||
} |
||||
|
||||
public String getValue() { |
||||
return this.value; |
||||
} |
||||
|
||||
public void setValue(String value) { |
||||
this.value = value; |
||||
} |
||||
|
||||
public long getDeadLine() { |
||||
return this.deadLine; |
||||
} |
||||
|
||||
public void setDeadLine(long deadLine) { |
||||
this.deadLine = deadLine; |
||||
} |
||||
} |
@ -0,0 +1,83 @@ |
||||
package xyz.fycz.myreader.greendao.service |
||||
|
||||
import android.database.Cursor |
||||
import xyz.fycz.myreader.application.App |
||||
import xyz.fycz.myreader.greendao.DbManager |
||||
import xyz.fycz.myreader.greendao.entity.Cache |
||||
import xyz.fycz.myreader.model.third3.analyzeRule.QueryTTF |
||||
import xyz.fycz.myreader.util.utils.ACache |
||||
import java.lang.Exception |
||||
|
||||
|
||||
@Suppress("unused") |
||||
object CacheManager { |
||||
|
||||
private val queryTTFMap = hashMapOf<String, Pair<Long, QueryTTF>>() |
||||
|
||||
/** |
||||
* saveTime 单位为秒 |
||||
*/ |
||||
@JvmOverloads |
||||
fun put(key: String, value: Any, saveTime: Int = 0) { |
||||
val deadline = |
||||
if (saveTime == 0) 0 else System.currentTimeMillis() + saveTime * 1000 |
||||
when (value) { |
||||
is QueryTTF -> queryTTFMap[key] = Pair(deadline, value) |
||||
is ByteArray -> ACache.get(App.getmContext()).put(key, value, saveTime) |
||||
else -> { |
||||
val cache = Cache(key, value.toString(), deadline) |
||||
DbManager.getDaoSession().cacheDao.insertOrReplace(cache) |
||||
} |
||||
} |
||||
} |
||||
|
||||
fun get(key: String): String? { |
||||
var str: String? = null |
||||
try { |
||||
val sql = "select VALUE from CACHE where key = ? and (DEAD_LINE = 0 or DEAD_LINE > ?)" |
||||
val cursor: Cursor = DbManager.getDaoSession().database.rawQuery( |
||||
sql, |
||||
arrayOf(key, "" + System.currentTimeMillis()) |
||||
) ?: return null |
||||
if (cursor.moveToNext()) { |
||||
str = cursor.getColumnName(0) |
||||
} |
||||
} catch (e: Exception) { |
||||
e.printStackTrace() |
||||
} |
||||
return str |
||||
} |
||||
|
||||
fun getInt(key: String): Int? { |
||||
return get(key)?.toIntOrNull() |
||||
} |
||||
|
||||
fun getLong(key: String): Long? { |
||||
return get(key)?.toLongOrNull() |
||||
} |
||||
|
||||
fun getDouble(key: String): Double? { |
||||
return get(key)?.toDoubleOrNull() |
||||
} |
||||
|
||||
fun getFloat(key: String): Float? { |
||||
return get(key)?.toFloatOrNull() |
||||
} |
||||
|
||||
fun getByteArray(key: String): ByteArray? { |
||||
return ACache.get(App.getmContext()).getAsBinary(key) |
||||
} |
||||
|
||||
fun getQueryTTF(key: String): QueryTTF? { |
||||
val cache = queryTTFMap[key] ?: return null |
||||
if (cache.first == 0L || cache.first > System.currentTimeMillis()) { |
||||
return cache.second |
||||
} |
||||
return null |
||||
} |
||||
|
||||
fun delete(key: String) { |
||||
DbManager.getDaoSession().cacheDao.deleteByKey(key) |
||||
ACache.get(App.getmContext()).remove(key) |
||||
} |
||||
} |
@ -0,0 +1,91 @@ |
||||
package xyz.fycz.myreader.model.third3.http |
||||
|
||||
import okhttp3.ConnectionSpec |
||||
import okhttp3.Credentials |
||||
import okhttp3.Interceptor |
||||
import okhttp3.OkHttpClient |
||||
import java.net.InetSocketAddress |
||||
import java.net.Proxy |
||||
import java.util.concurrent.ConcurrentHashMap |
||||
import java.util.concurrent.TimeUnit |
||||
|
||||
private val proxyClientCache: ConcurrentHashMap<String, OkHttpClient> by lazy { |
||||
ConcurrentHashMap() |
||||
} |
||||
|
||||
val okHttpClient: OkHttpClient by lazy { |
||||
val specs = arrayListOf( |
||||
ConnectionSpec.MODERN_TLS, |
||||
ConnectionSpec.COMPATIBLE_TLS, |
||||
ConnectionSpec.CLEARTEXT |
||||
) |
||||
|
||||
val builder = OkHttpClient.Builder() |
||||
.connectTimeout(15, TimeUnit.SECONDS) |
||||
.writeTimeout(15, TimeUnit.SECONDS) |
||||
.readTimeout(15, TimeUnit.SECONDS) |
||||
.callTimeout(60,TimeUnit.SECONDS) |
||||
.sslSocketFactory(SSLHelper.unsafeSSLSocketFactory, SSLHelper.unsafeTrustManager) |
||||
.retryOnConnectionFailure(true) |
||||
.hostnameVerifier(SSLHelper.unsafeHostnameVerifier) |
||||
.connectionSpecs(specs) |
||||
.followRedirects(true) |
||||
.followSslRedirects(true) |
||||
.addInterceptor(Interceptor { chain -> |
||||
val request = chain.request() |
||||
.newBuilder() |
||||
.addHeader("Keep-Alive", "300") |
||||
.addHeader("Connection", "Keep-Alive") |
||||
.addHeader("Cache-Control", "no-cache") |
||||
.build() |
||||
chain.proceed(request) |
||||
}) |
||||
/*if (AppConfig.isCronet && CronetLoader.install() && !AppConfig.isGooglePlay) { |
||||
builder.addInterceptor(CronetInterceptor(null)) |
||||
}*/ |
||||
builder.build() |
||||
} |
||||
|
||||
/** |
||||
* 缓存代理okHttp |
||||
*/ |
||||
fun getProxyClient(proxy: String? = null): OkHttpClient { |
||||
if (proxy.isNullOrBlank()) { |
||||
return okHttpClient |
||||
} |
||||
proxyClientCache[proxy]?.let { |
||||
return it |
||||
} |
||||
val r = Regex("(http|socks4|socks5)://(.*):(\\d{2,5})(@.*@.*)?") |
||||
val ms = r.findAll(proxy) |
||||
val group = ms.first() |
||||
var username = "" //代理服务器验证用户名 |
||||
var password = "" //代理服务器验证密码 |
||||
val type = if (group.groupValues[1] == "http") "http" else "socks" |
||||
val host = group.groupValues[2] |
||||
val port = group.groupValues[3].toInt() |
||||
if (group.groupValues[4] != "") { |
||||
username = group.groupValues[4].split("@")[1] |
||||
password = group.groupValues[4].split("@")[2] |
||||
} |
||||
if (type != "direct" && host != "") { |
||||
val builder = okHttpClient.newBuilder() |
||||
if (type == "http") { |
||||
builder.proxy(Proxy(Proxy.Type.HTTP, InetSocketAddress(host, port))) |
||||
} else { |
||||
builder.proxy(Proxy(Proxy.Type.SOCKS, InetSocketAddress(host, port))) |
||||
} |
||||
if (username != "" && password != "") { |
||||
builder.proxyAuthenticator { _, response -> //设置代理服务器账号密码 |
||||
val credential: String = Credentials.basic(username, password) |
||||
response.request.newBuilder() |
||||
.header("Proxy-Authorization", credential) |
||||
.build() |
||||
} |
||||
} |
||||
val proxyClient = builder.build() |
||||
proxyClientCache[proxy] = proxyClient |
||||
return proxyClient |
||||
} |
||||
return okHttpClient |
||||
} |
@ -1,4 +1,4 @@ |
||||
package io.legado.app.help.http |
||||
package xyz.fycz.myreader.model.third3.http |
||||
|
||||
enum class RequestMethod { |
||||
GET, POST |
||||
|
@ -0,0 +1,785 @@ |
||||
//Copyright (c) 2017. 章钦豪. All rights reserved. |
||||
package xyz.fycz.myreader.util.utils |
||||
|
||||
import android.content.Context |
||||
import android.graphics.Bitmap |
||||
import android.graphics.BitmapFactory |
||||
import android.graphics.Canvas |
||||
import android.graphics.PixelFormat |
||||
import android.graphics.drawable.BitmapDrawable |
||||
import android.graphics.drawable.Drawable |
||||
import android.util.Log |
||||
import org.json.JSONArray |
||||
import org.json.JSONObject |
||||
import xyz.fycz.myreader.application.App |
||||
import java.io.* |
||||
import java.util.* |
||||
import java.util.concurrent.atomic.AtomicInteger |
||||
import java.util.concurrent.atomic.AtomicLong |
||||
import kotlin.math.min |
||||
|
||||
|
||||
/** |
||||
* 本地缓存 |
||||
*/ |
||||
@Suppress("unused", "MemberVisibilityCanBePrivate") |
||||
class ACache private constructor(cacheDir: File, max_size: Long, max_count: Int) { |
||||
|
||||
val TAG = ACache::class.simpleName |
||||
|
||||
companion object { |
||||
const val TIME_HOUR = 60 * 60 |
||||
const val TIME_DAY = TIME_HOUR * 24 |
||||
private const val MAX_SIZE = 1000 * 1000 * 50 // 50 mb |
||||
private const val MAX_COUNT = Integer.MAX_VALUE // 不限制存放数据的数量 |
||||
private val mInstanceMap = HashMap<String, ACache>() |
||||
|
||||
@JvmOverloads |
||||
fun get( |
||||
ctx: Context, |
||||
cacheName: String = "ACache", |
||||
maxSize: Long = MAX_SIZE.toLong(), |
||||
maxCount: Int = MAX_COUNT, |
||||
cacheDir: Boolean = true |
||||
): ACache { |
||||
val f = if (cacheDir) File(ctx.cacheDir, cacheName) else File(ctx.filesDir, cacheName) |
||||
return get(f, maxSize, maxCount) |
||||
} |
||||
|
||||
@JvmOverloads |
||||
fun get( |
||||
cacheDir: File, |
||||
maxSize: Long = MAX_SIZE.toLong(), |
||||
maxCount: Int = MAX_COUNT |
||||
): ACache { |
||||
synchronized(this) { |
||||
var manager = mInstanceMap[cacheDir.absoluteFile.toString() + myPid()] |
||||
if (manager == null) { |
||||
manager = ACache(cacheDir, maxSize, maxCount) |
||||
mInstanceMap[cacheDir.absolutePath + myPid()] = manager |
||||
} |
||||
return manager |
||||
} |
||||
} |
||||
|
||||
private fun myPid(): String { |
||||
return "_" + android.os.Process.myPid() |
||||
} |
||||
} |
||||
|
||||
private var mCache: ACacheManager? = null |
||||
|
||||
init { |
||||
try { |
||||
if (!cacheDir.exists() && !cacheDir.mkdirs()) { |
||||
Log.i(TAG, "can't make dirs in %s" + cacheDir.absolutePath) |
||||
} |
||||
mCache = ACacheManager(cacheDir, max_size, max_count) |
||||
} catch (e: Exception) { |
||||
Log.e(TAG, "" + e.localizedMessage) |
||||
} |
||||
|
||||
} |
||||
|
||||
// ======================================= |
||||
// ============ String数据 读写 ============== |
||||
// ======================================= |
||||
|
||||
/** |
||||
* 保存 String数据 到 缓存中 |
||||
* |
||||
* @param key 保存的key |
||||
* @param value 保存的String数据 |
||||
*/ |
||||
fun put(key: String, value: String) { |
||||
mCache?.let { mCache -> |
||||
try { |
||||
val file = mCache.newFile(key) |
||||
file.writeText(value) |
||||
mCache.put(file) |
||||
} catch (e: Exception) { |
||||
Log.e(TAG, "" + e.localizedMessage) |
||||
} |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* 保存 String数据 到 缓存中 |
||||
* |
||||
* @param key 保存的key |
||||
* @param value 保存的String数据 |
||||
* @param saveTime 保存的时间,单位:秒 |
||||
*/ |
||||
fun put(key: String, value: String, saveTime: Int) { |
||||
put(key, Utils.newStringWithDateInfo(saveTime, value)) |
||||
} |
||||
|
||||
/** |
||||
* 读取 String数据 |
||||
* |
||||
* @return String 数据 |
||||
*/ |
||||
fun getAsString(key: String): String? { |
||||
mCache?.let { mCache -> |
||||
val file = mCache[key] |
||||
if (!file.exists()) |
||||
return null |
||||
var removeFile = false |
||||
try { |
||||
val text = file.readText() |
||||
if (!Utils.isDue(text)) { |
||||
return Utils.clearDateInfo(text) |
||||
} else { |
||||
removeFile = true |
||||
} |
||||
} catch (e: IOException) { |
||||
Log.e(TAG, "" + e.localizedMessage) |
||||
} finally { |
||||
if (removeFile) |
||||
remove(key) |
||||
} |
||||
} |
||||
return null |
||||
} |
||||
|
||||
// ======================================= |
||||
// ========== JSONObject 数据 读写 ========= |
||||
// ======================================= |
||||
|
||||
/** |
||||
* 保存 JSONObject数据 到 缓存中 |
||||
* |
||||
* @param key 保存的key |
||||
* @param value 保存的JSON数据 |
||||
*/ |
||||
fun put(key: String, value: JSONObject) { |
||||
put(key, value.toString()) |
||||
} |
||||
|
||||
/** |
||||
* 保存 JSONObject数据 到 缓存中 |
||||
* |
||||
* @param key 保存的key |
||||
* @param value 保存的JSONObject数据 |
||||
* @param saveTime 保存的时间,单位:秒 |
||||
*/ |
||||
fun put(key: String, value: JSONObject, saveTime: Int) { |
||||
put(key, value.toString(), saveTime) |
||||
} |
||||
|
||||
/** |
||||
* 读取JSONObject数据 |
||||
* |
||||
* @return JSONObject数据 |
||||
*/ |
||||
fun getAsJSONObject(key: String): JSONObject? { |
||||
val json = getAsString(key) ?: return null |
||||
return try { |
||||
JSONObject(json) |
||||
} catch (e: Exception) { |
||||
null |
||||
} |
||||
} |
||||
|
||||
// ======================================= |
||||
// ============ JSONArray 数据 读写 ============= |
||||
// ======================================= |
||||
|
||||
/** |
||||
* 保存 JSONArray数据 到 缓存中 |
||||
* |
||||
* @param key 保存的key |
||||
* @param value 保存的JSONArray数据 |
||||
*/ |
||||
fun put(key: String, value: JSONArray) { |
||||
put(key, value.toString()) |
||||
} |
||||
|
||||
/** |
||||
* 保存 JSONArray数据 到 缓存中 |
||||
* |
||||
* @param key 保存的key |
||||
* @param value 保存的JSONArray数据 |
||||
* @param saveTime 保存的时间,单位:秒 |
||||
*/ |
||||
fun put(key: String, value: JSONArray, saveTime: Int) { |
||||
put(key, value.toString(), saveTime) |
||||
} |
||||
|
||||
/** |
||||
* 读取JSONArray数据 |
||||
* |
||||
* @return JSONArray数据 |
||||
*/ |
||||
fun getAsJSONArray(key: String): JSONArray? { |
||||
val json = getAsString(key) |
||||
return try { |
||||
JSONArray(json) |
||||
} catch (e: Exception) { |
||||
null |
||||
} |
||||
|
||||
} |
||||
|
||||
// ======================================= |
||||
// ============== byte 数据 读写 ============= |
||||
// ======================================= |
||||
|
||||
/** |
||||
* 保存 byte数据 到 缓存中 |
||||
* |
||||
* @param key 保存的key |
||||
* @param value 保存的数据 |
||||
*/ |
||||
fun put(key: String, value: ByteArray) { |
||||
mCache?.let { mCache -> |
||||
val file = mCache.newFile(key) |
||||
file.writeBytes(value) |
||||
mCache.put(file) |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* 保存 byte数据 到 缓存中 |
||||
* |
||||
* @param key 保存的key |
||||
* @param value 保存的数据 |
||||
* @param saveTime 保存的时间,单位:秒 |
||||
*/ |
||||
fun put(key: String, value: ByteArray, saveTime: Int) { |
||||
put(key, Utils.newByteArrayWithDateInfo(saveTime, value)) |
||||
} |
||||
|
||||
/** |
||||
* 获取 byte 数据 |
||||
* |
||||
* @return byte 数据 |
||||
*/ |
||||
fun getAsBinary(key: String): ByteArray? { |
||||
mCache?.let { mCache -> |
||||
var removeFile = false |
||||
try { |
||||
val file = mCache[key] |
||||
if (!file.exists()) |
||||
return null |
||||
|
||||
val byteArray = file.readBytes() |
||||
return if (!Utils.isDue(byteArray)) { |
||||
Utils.clearDateInfo(byteArray) |
||||
} else { |
||||
removeFile = true |
||||
null |
||||
} |
||||
} catch (e: Exception) { |
||||
Log.e(TAG, "" + e.localizedMessage) |
||||
} finally { |
||||
if (removeFile) |
||||
remove(key) |
||||
} |
||||
} |
||||
return null |
||||
} |
||||
|
||||
/** |
||||
* 保存 Serializable数据到 缓存中 |
||||
* |
||||
* @param key 保存的key |
||||
* @param value 保存的value |
||||
* @param saveTime 保存的时间,单位:秒 |
||||
*/ |
||||
@JvmOverloads |
||||
fun put(key: String, value: Serializable, saveTime: Int = -1) { |
||||
try { |
||||
val byteArrayOutputStream = ByteArrayOutputStream() |
||||
ObjectOutputStream(byteArrayOutputStream).use { oos -> |
||||
oos.writeObject(value) |
||||
val data = byteArrayOutputStream.toByteArray() |
||||
if (saveTime != -1) { |
||||
put(key, data, saveTime) |
||||
} else { |
||||
put(key, data) |
||||
} |
||||
} |
||||
} catch (e: Exception) { |
||||
Log.e(TAG, "" + e.localizedMessage) |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* 读取 Serializable数据 |
||||
* |
||||
* @return Serializable 数据 |
||||
*/ |
||||
fun getAsObject(key: String): Any? { |
||||
val data = getAsBinary(key) |
||||
if (data != null) { |
||||
var bis: ByteArrayInputStream? = null |
||||
var ois: ObjectInputStream? = null |
||||
try { |
||||
bis = ByteArrayInputStream(data) |
||||
ois = ObjectInputStream(bis) |
||||
return ois.readObject() |
||||
} catch (e: Exception) { |
||||
Log.e(TAG, "" + e.localizedMessage) |
||||
} finally { |
||||
try { |
||||
bis?.close() |
||||
} catch (e: IOException) { |
||||
Log.e(TAG, "" + e.localizedMessage) |
||||
} |
||||
|
||||
try { |
||||
ois?.close() |
||||
} catch (e: IOException) { |
||||
Log.e(TAG, "" + e.localizedMessage) |
||||
} |
||||
|
||||
} |
||||
} |
||||
return null |
||||
|
||||
} |
||||
|
||||
// ======================================= |
||||
// ============== bitmap 数据 读写 ============= |
||||
// ======================================= |
||||
|
||||
/** |
||||
* 保存 bitmap 到 缓存中 |
||||
* |
||||
* @param key 保存的key |
||||
* @param value 保存的bitmap数据 |
||||
*/ |
||||
fun put(key: String, value: Bitmap) { |
||||
put(key, Utils.bitmap2Bytes(value)) |
||||
} |
||||
|
||||
/** |
||||
* 保存 bitmap 到 缓存中 |
||||
* |
||||
* @param key 保存的key |
||||
* @param value 保存的 bitmap 数据 |
||||
* @param saveTime 保存的时间,单位:秒 |
||||
*/ |
||||
fun put(key: String, value: Bitmap, saveTime: Int) { |
||||
put(key, Utils.bitmap2Bytes(value), saveTime) |
||||
} |
||||
|
||||
/** |
||||
* 读取 bitmap 数据 |
||||
* |
||||
* @return bitmap 数据 |
||||
*/ |
||||
fun getAsBitmap(key: String): Bitmap? { |
||||
return if (getAsBinary(key) == null) { |
||||
null |
||||
} else Utils.bytes2Bitmap(getAsBinary(key)!!) |
||||
} |
||||
|
||||
// ======================================= |
||||
// ============= drawable 数据 读写 ============= |
||||
// ======================================= |
||||
|
||||
/** |
||||
* 保存 drawable 到 缓存中 |
||||
* |
||||
* @param key 保存的key |
||||
* @param value 保存的drawable数据 |
||||
*/ |
||||
fun put(key: String, value: Drawable) { |
||||
put(key, Utils.drawable2Bitmap(value)) |
||||
} |
||||
|
||||
/** |
||||
* 保存 drawable 到 缓存中 |
||||
* |
||||
* @param key 保存的key |
||||
* @param value 保存的 drawable 数据 |
||||
* @param saveTime 保存的时间,单位:秒 |
||||
*/ |
||||
fun put(key: String, value: Drawable, saveTime: Int) { |
||||
put(key, Utils.drawable2Bitmap(value), saveTime) |
||||
} |
||||
|
||||
/** |
||||
* 读取 Drawable 数据 |
||||
* |
||||
* @return Drawable 数据 |
||||
*/ |
||||
fun getAsDrawable(key: String): Drawable? { |
||||
return if (getAsBinary(key) == null) { |
||||
null |
||||
} else Utils.bitmap2Drawable( |
||||
Utils.bytes2Bitmap( |
||||
getAsBinary(key)!! |
||||
) |
||||
) |
||||
} |
||||
|
||||
/** |
||||
* 获取缓存文件 |
||||
* |
||||
* @return value 缓存的文件 |
||||
*/ |
||||
fun file(key: String): File? { |
||||
mCache?.let { mCache -> |
||||
try { |
||||
val f = mCache.newFile(key) |
||||
if (f.exists()) { |
||||
return f |
||||
} else { |
||||
return null |
||||
} |
||||
} catch (e: Exception) { |
||||
Log.e(TAG, "" + e.localizedMessage) |
||||
} |
||||
} |
||||
return null |
||||
} |
||||
|
||||
/** |
||||
* 移除某个key |
||||
* |
||||
* @return 是否移除成功 |
||||
*/ |
||||
fun remove(key: String): Boolean { |
||||
return mCache?.remove(key) == true |
||||
} |
||||
|
||||
/** |
||||
* 清除所有数据 |
||||
*/ |
||||
fun clear() { |
||||
mCache?.clear() |
||||
} |
||||
|
||||
/** |
||||
* @author 杨福海(michael) www.yangfuhai.com |
||||
* @version 1.0 |
||||
* title 时间计算工具类 |
||||
*/ |
||||
private object Utils { |
||||
|
||||
private const val mSeparator = ' ' |
||||
|
||||
/** |
||||
* 判断缓存的String数据是否到期 |
||||
* |
||||
* @return true:到期了 false:还没有到期 |
||||
*/ |
||||
fun isDue(str: String): Boolean { |
||||
return isDue(str.toByteArray()) |
||||
} |
||||
|
||||
/** |
||||
* 判断缓存的byte数据是否到期 |
||||
* |
||||
* @return true:到期了 false:还没有到期 |
||||
*/ |
||||
fun isDue(data: ByteArray): Boolean { |
||||
try { |
||||
val text = getDateInfoFromDate(data) |
||||
if (text != null && text.size == 2) { |
||||
var saveTimeStr = text[0] |
||||
while (saveTimeStr.startsWith("0")) { |
||||
saveTimeStr = saveTimeStr |
||||
.substring(1) |
||||
} |
||||
val saveTime = java.lang.Long.valueOf(saveTimeStr) |
||||
val deleteAfter = java.lang.Long.valueOf(text[1]) |
||||
if (System.currentTimeMillis() > saveTime + deleteAfter * 1000) { |
||||
return true |
||||
} |
||||
} |
||||
} catch (e: Exception) { |
||||
Log.e("ACache", "" + e.localizedMessage) |
||||
} |
||||
|
||||
return false |
||||
} |
||||
|
||||
fun newStringWithDateInfo(second: Int, strInfo: String): String { |
||||
return createDateInfo(second) + strInfo |
||||
} |
||||
|
||||
fun newByteArrayWithDateInfo(second: Int, data2: ByteArray): ByteArray { |
||||
val data1 = createDateInfo(second).toByteArray() |
||||
val retData = ByteArray(data1.size + data2.size) |
||||
System.arraycopy(data1, 0, retData, 0, data1.size) |
||||
System.arraycopy(data2, 0, retData, data1.size, data2.size) |
||||
return retData |
||||
} |
||||
|
||||
fun clearDateInfo(strInfo: String?): String? { |
||||
strInfo?.let { |
||||
if (hasDateInfo(strInfo.toByteArray())) { |
||||
return strInfo.substring(strInfo.indexOf(mSeparator) + 1) |
||||
} |
||||
} |
||||
return strInfo |
||||
} |
||||
|
||||
fun clearDateInfo(data: ByteArray): ByteArray { |
||||
return if (hasDateInfo(data)) { |
||||
copyOfRange( |
||||
data, indexOf(data, mSeparator) + 1, |
||||
data.size |
||||
) |
||||
} else data |
||||
} |
||||
|
||||
fun hasDateInfo(data: ByteArray?): Boolean { |
||||
return (data != null && data.size > 15 && data[13] == '-'.code.toByte() |
||||
&& indexOf(data, mSeparator) > 14) |
||||
} |
||||
|
||||
fun getDateInfoFromDate(data: ByteArray): Array<String>? { |
||||
if (hasDateInfo(data)) { |
||||
val saveDate = String(copyOfRange(data, 0, 13)) |
||||
val deleteAfter = String( |
||||
copyOfRange( |
||||
data, 14, |
||||
indexOf(data, mSeparator) |
||||
) |
||||
) |
||||
return arrayOf(saveDate, deleteAfter) |
||||
} |
||||
return null |
||||
} |
||||
|
||||
@Suppress("SameParameterValue") |
||||
private fun indexOf(data: ByteArray, c: Char): Int { |
||||
for (i in data.indices) { |
||||
if (data[i] == c.code.toByte()) { |
||||
return i |
||||
} |
||||
} |
||||
return -1 |
||||
} |
||||
|
||||
private fun copyOfRange(original: ByteArray, from: Int, to: Int): ByteArray { |
||||
val newLength = to - from |
||||
require(newLength >= 0) { "$from > $to" } |
||||
val copy = ByteArray(newLength) |
||||
System.arraycopy( |
||||
original, from, copy, 0, |
||||
min(original.size - from, newLength) |
||||
) |
||||
return copy |
||||
} |
||||
|
||||
private fun createDateInfo(second: Int): String { |
||||
val currentTime = StringBuilder(System.currentTimeMillis().toString() + "") |
||||
while (currentTime.length < 13) { |
||||
currentTime.insert(0, "0") |
||||
} |
||||
return "$currentTime-$second$mSeparator" |
||||
} |
||||
|
||||
/* |
||||
* Bitmap → byte[] |
||||
*/ |
||||
fun bitmap2Bytes(bm: Bitmap): ByteArray { |
||||
val byteArrayOutputStream = ByteArrayOutputStream() |
||||
bm.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream) |
||||
return byteArrayOutputStream.toByteArray() |
||||
} |
||||
|
||||
/* |
||||
* byte[] → Bitmap |
||||
*/ |
||||
fun bytes2Bitmap(b: ByteArray): Bitmap? { |
||||
return if (b.isEmpty()) { |
||||
null |
||||
} else BitmapFactory.decodeByteArray(b, 0, b.size) |
||||
} |
||||
|
||||
/* |
||||
* Drawable → Bitmap |
||||
*/ |
||||
fun drawable2Bitmap(drawable: Drawable): Bitmap { |
||||
// 取 drawable 的长宽 |
||||
val w = drawable.intrinsicWidth |
||||
val h = drawable.intrinsicHeight |
||||
// 取 drawable 的颜色格式 |
||||
@Suppress("DEPRECATION") |
||||
val config = if (drawable.opacity != PixelFormat.OPAQUE) |
||||
Bitmap.Config.ARGB_8888 |
||||
else |
||||
Bitmap.Config.RGB_565 |
||||
// 建立对应 bitmap |
||||
val bitmap = Bitmap.createBitmap(w, h, config) |
||||
// 建立对应 bitmap 的画布 |
||||
val canvas = Canvas(bitmap) |
||||
drawable.setBounds(0, 0, w, h) |
||||
// 把 drawable 内容画到画布中 |
||||
drawable.draw(canvas) |
||||
return bitmap |
||||
} |
||||
|
||||
/* |
||||
* Bitmap → Drawable |
||||
*/ |
||||
fun bitmap2Drawable(bm: Bitmap?): Drawable? { |
||||
return if (bm == null) { |
||||
null |
||||
} else BitmapDrawable(App.getmContext().resources, bm) |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* @author 杨福海(michael) www.yangfuhai.com |
||||
* @version 1.0 |
||||
* title 缓存管理器 |
||||
*/ |
||||
open inner class ACacheManager( |
||||
private var cacheDir: File, |
||||
private val sizeLimit: Long, |
||||
private val countLimit: Int |
||||
) { |
||||
private val cacheSize: AtomicLong = AtomicLong() |
||||
private val cacheCount: AtomicInteger = AtomicInteger() |
||||
private val lastUsageDates = Collections |
||||
.synchronizedMap(HashMap<File, Long>()) |
||||
|
||||
init { |
||||
calculateCacheSizeAndCacheCount() |
||||
} |
||||
|
||||
/** |
||||
* 计算 cacheSize和cacheCount |
||||
*/ |
||||
private fun calculateCacheSizeAndCacheCount() { |
||||
Thread { |
||||
|
||||
try { |
||||
var size = 0 |
||||
var count = 0 |
||||
val cachedFiles = cacheDir.listFiles() |
||||
if (cachedFiles != null) { |
||||
for (cachedFile in cachedFiles) { |
||||
size += calculateSize(cachedFile).toInt() |
||||
count += 1 |
||||
lastUsageDates[cachedFile] = cachedFile.lastModified() |
||||
} |
||||
cacheSize.set(size.toLong()) |
||||
cacheCount.set(count) |
||||
} |
||||
} catch (e: Exception) { |
||||
Log.e(TAG, "" + e.localizedMessage) |
||||
} |
||||
|
||||
|
||||
}.start() |
||||
} |
||||
|
||||
fun put(file: File) { |
||||
|
||||
try { |
||||
var curCacheCount = cacheCount.get() |
||||
while (curCacheCount + 1 > countLimit) { |
||||
val freedSize = removeNext() |
||||
cacheSize.addAndGet(-freedSize) |
||||
|
||||
curCacheCount = cacheCount.addAndGet(-1) |
||||
} |
||||
cacheCount.addAndGet(1) |
||||
|
||||
val valueSize = calculateSize(file) |
||||
var curCacheSize = cacheSize.get() |
||||
while (curCacheSize + valueSize > sizeLimit) { |
||||
val freedSize = removeNext() |
||||
curCacheSize = cacheSize.addAndGet(-freedSize) |
||||
} |
||||
cacheSize.addAndGet(valueSize) |
||||
|
||||
val currentTime = System.currentTimeMillis() |
||||
file.setLastModified(currentTime) |
||||
lastUsageDates[file] = currentTime |
||||
} catch (e: Exception) { |
||||
Log.e(TAG, "" + e.localizedMessage) |
||||
} |
||||
|
||||
} |
||||
|
||||
operator fun get(key: String): File { |
||||
val file = newFile(key) |
||||
val currentTime = System.currentTimeMillis() |
||||
file.setLastModified(currentTime) |
||||
lastUsageDates[file] = currentTime |
||||
|
||||
return file |
||||
} |
||||
|
||||
fun newFile(key: String): File { |
||||
return File(cacheDir, key.hashCode().toString() + "") |
||||
} |
||||
|
||||
fun remove(key: String): Boolean { |
||||
val image = get(key) |
||||
return image.delete() |
||||
} |
||||
|
||||
fun clear() { |
||||
try { |
||||
lastUsageDates.clear() |
||||
cacheSize.set(0) |
||||
val files = cacheDir.listFiles() |
||||
if (files != null) { |
||||
for (f in files) { |
||||
f.delete() |
||||
} |
||||
} |
||||
} catch (e: Exception) { |
||||
Log.e(TAG, "" + e.localizedMessage) |
||||
} |
||||
|
||||
} |
||||
|
||||
/** |
||||
* 移除旧的文件 |
||||
*/ |
||||
private fun removeNext(): Long { |
||||
try { |
||||
if (lastUsageDates.isEmpty()) { |
||||
return 0 |
||||
} |
||||
|
||||
var oldestUsage: Long? = null |
||||
var mostLongUsedFile: File? = null |
||||
val entries = lastUsageDates.entries |
||||
synchronized(lastUsageDates) { |
||||
for ((key, lastValueUsage) in entries) { |
||||
if (mostLongUsedFile == null) { |
||||
mostLongUsedFile = key |
||||
oldestUsage = lastValueUsage |
||||
} else { |
||||
if (lastValueUsage < oldestUsage!!) { |
||||
oldestUsage = lastValueUsage |
||||
mostLongUsedFile = key |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
var fileSize: Long = 0 |
||||
if (mostLongUsedFile != null) { |
||||
fileSize = calculateSize(mostLongUsedFile!!) |
||||
if (mostLongUsedFile!!.delete()) { |
||||
lastUsageDates.remove(mostLongUsedFile) |
||||
} |
||||
} |
||||
return fileSize |
||||
} catch (e: Exception) { |
||||
Log.e(TAG, "" + e.localizedMessage) |
||||
return 0 |
||||
} |
||||
|
||||
} |
||||
|
||||
private fun calculateSize(file: File): Long { |
||||
return file.length() |
||||
} |
||||
} |
||||
|
||||
} |
@ -0,0 +1,176 @@ |
||||
package xyz.fycz.myreader.util.utils |
||||
|
||||
import android.annotation.SuppressLint |
||||
import android.content.ContentUris |
||||
import android.content.Context |
||||
import android.database.Cursor |
||||
import android.net.Uri |
||||
import android.os.Build |
||||
import android.os.Environment |
||||
import android.provider.DocumentsContract |
||||
import android.provider.MediaStore |
||||
import android.util.Log |
||||
import java.io.File |
||||
import java.io.FileInputStream |
||||
import java.io.FileOutputStream |
||||
import java.io.IOException |
||||
|
||||
@Suppress("unused") |
||||
object RealPathUtil { |
||||
/** |
||||
* Method for return file path of Gallery image |
||||
* @return path of the selected image file from gallery |
||||
*/ |
||||
private var filePathUri: Uri? = null |
||||
|
||||
@Suppress("DEPRECATION") |
||||
fun getPath(context: Context, uri: Uri): String? { |
||||
//check here to KITKAT or new version |
||||
@SuppressLint("ObsoleteSdkInt") |
||||
val isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT |
||||
filePathUri = uri |
||||
// DocumentProvider |
||||
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider |
||||
if (isExternalStorageDocument(uri)) { |
||||
val docId = DocumentsContract.getDocumentId(uri) |
||||
val split = docId.split(":").toTypedArray() |
||||
val type = split[0] |
||||
if ("primary".equals(type, ignoreCase = true)) { |
||||
return Environment.getExternalStorageDirectory().toString() + "/" + split[1] |
||||
} |
||||
} else if (isDownloadsDocument(uri)) { |
||||
val id = DocumentsContract.getDocumentId(uri) |
||||
val contentUri = ContentUris.withAppendedId( |
||||
Uri.parse("content://downloads/public_downloads"), |
||||
java.lang.Long.valueOf(id) |
||||
) |
||||
//return getDataColumn(context, uri, null, null); |
||||
return getDataColumn(context, contentUri, null, null) |
||||
} else if (isMediaDocument(uri)) { |
||||
val docId = DocumentsContract.getDocumentId(uri) |
||||
val split = docId.split(":").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 if (isGooglePhotosUri(uri)) uri.lastPathSegment else 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? { |
||||
var cursor: Cursor? = null |
||||
val column = "_data" |
||||
val projection = arrayOf( |
||||
column |
||||
) |
||||
try { |
||||
cursor = |
||||
context.contentResolver.query(uri!!, projection, selection, selectionArgs, null) |
||||
if (cursor != null && cursor.moveToFirst()) { |
||||
val index = cursor.getColumnIndexOrThrow(column) |
||||
return cursor.getString(index) |
||||
} |
||||
} catch (e: IllegalArgumentException) { |
||||
Log.e("RealPathUtil", "" + e.localizedMessage) |
||||
val file = File(context.cacheDir, "tmp") |
||||
val filePath = file.absolutePath |
||||
var input: FileInputStream? = null |
||||
var output: FileOutputStream? = null |
||||
try { |
||||
val pfd = |
||||
context.contentResolver.openFileDescriptor(filePathUri!!, "r") |
||||
?: return null |
||||
val fd = pfd.fileDescriptor |
||||
input = FileInputStream(fd) |
||||
output = FileOutputStream(filePath) |
||||
var read: Int |
||||
val bytes = ByteArray(4096) |
||||
while (input.read(bytes).also { read = it } != -1) { |
||||
output.write(bytes, 0, read) |
||||
} |
||||
return File(filePath).absolutePath |
||||
} catch (e: IOException) { |
||||
Log.e("RealPathUtil", "" + e.localizedMessage) |
||||
} finally { |
||||
input?.close() |
||||
output?.close() |
||||
} |
||||
} finally { |
||||
cursor?.close() |
||||
} |
||||
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 |
||||
} |
||||
|
||||
/** |
||||
* @param uri The Uri to check. |
||||
* @return Whether the Uri authority is Google Photos. |
||||
*/ |
||||
private fun isGooglePhotosUri(uri: Uri): Boolean { |
||||
return "com.google.android.apps.photos.content" == uri.authority |
||||
} |
||||
} |
@ -0,0 +1,81 @@ |
||||
@file:Suppress("unused") |
||||
|
||||
package xyz.fycz.myreader.util.utils |
||||
|
||||
import android.icu.text.Collator |
||||
import android.icu.util.ULocale |
||||
import android.net.Uri |
||||
import java.io.File |
||||
import java.util.* |
||||
|
||||
fun String?.safeTrim() = if (this.isNullOrBlank()) null else this.trim() |
||||
|
||||
fun String?.isContentScheme(): Boolean = this?.startsWith("content://") == true |
||||
|
||||
fun String.parseToUri(): Uri { |
||||
return if (isContentScheme()) { |
||||
Uri.parse(this) |
||||
} else { |
||||
Uri.fromFile(File(this)) |
||||
} |
||||
} |
||||
|
||||
fun String?.isAbsUrl() = |
||||
this?.let { |
||||
it.startsWith("http://", true) || it.startsWith("https://", true) |
||||
} ?: false |
||||
|
||||
fun String?.isJson(): Boolean = |
||||
this?.run { |
||||
val str = this.trim() |
||||
when { |
||||
str.startsWith("{") && str.endsWith("}") -> true |
||||
str.startsWith("[") && str.endsWith("]") -> true |
||||
else -> false |
||||
} |
||||
} ?: false |
||||
|
||||
fun String?.isJsonObject(): Boolean = |
||||
this?.run { |
||||
val str = this.trim() |
||||
str.startsWith("{") && str.endsWith("}") |
||||
} ?: false |
||||
|
||||
fun String?.isJsonArray(): Boolean = |
||||
this?.run { |
||||
val str = this.trim() |
||||
str.startsWith("[") && str.endsWith("]") |
||||
} ?: false |
||||
|
||||
fun String.splitNotBlank(vararg delimiter: String): Array<String> = run { |
||||
this.split(*delimiter).map { it.trim() }.filterNot { it.isBlank() }.toTypedArray() |
||||
} |
||||
|
||||
fun String.splitNotBlank(regex: Regex, limit: Int = 0): Array<String> = run { |
||||
this.split(regex, limit).map { it.trim() }.filterNot { it.isBlank() }.toTypedArray() |
||||
} |
||||
|
||||
fun String.cnCompare(other: String): Int { |
||||
return if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { |
||||
Collator.getInstance(ULocale.SIMPLIFIED_CHINESE).compare(this, other) |
||||
} else { |
||||
java.text.Collator.getInstance(Locale.CHINA).compare(this, other) |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* 将字符串拆分为单个字符,包含emoji |
||||
*/ |
||||
fun String.toStringArray(): Array<String> { |
||||
var codePointIndex = 0 |
||||
return try { |
||||
Array(codePointCount(0, length)) { |
||||
val start = codePointIndex |
||||
codePointIndex = offsetByCodePoints(start, 1) |
||||
substring(start, codePointIndex) |
||||
} |
||||
} catch (e: Exception) { |
||||
split("").toTypedArray() |
||||
} |
||||
} |
||||
|
Loading…
Reference in new issue