This commit is contained in:
HapeLee
2025-06-04 13:33:51 +08:00
parent b86d90021c
commit 6c0757c91b
972 changed files with 6885 additions and 7321 deletions
@@ -0,0 +1,84 @@
package io.legato.kazusa
import cn.hutool.core.lang.JarClassLoader
import com.script.ScriptBindings
import com.script.rhino.RhinoScriptEngine
import dalvik.system.DexClassLoader
import org.intellij.lang.annotations.Language
import org.junit.Assert
import org.junit.Test
import org.mozilla.javascript.DefiningClassLoader
import java.net.URLClassLoader
class AndroidJsTest {
@Test
fun testPackages() {
@Language("js")
val js = """
var accessKeyId = '1111';
var accessKeySecret = '2222';
var timestamp = '3333';
var aly = new JavaImporter(Packages.javax.crypto.Mac, Packages.javax.crypto.spec.SecretKeySpec, Packages.javax.xml.bind.DatatypeConverter, Packages.java.net.URLEncoder, Packages.java.lang.String, Packages.android.util.Base64);
with (aly) {
function percentEncode(value) {
return URLEncoder.encode(value, "UTF-8").replace("+", "%20")
.replace("*", "%2A").replace("%7E", "~")
}
function sign(stringToSign, accessKeySecret) {
var mac = Mac.getInstance('HmacSHA1');
mac.init(new SecretKeySpec(String(accessKeySecret + '&').getBytes("UTF-8"), "HmacSHA1"));
var signData = mac.doFinal(String(stringToSign).getBytes("UTF-8"));
var signBase64 = Base64.encodeToString(signData, Base64.NO_WRAP);
var signUrlEncode = percentEncode(signBase64);
return signUrlEncode;
}
}
var query = 'AccessKeyId=' + accessKeyId + '&Action=CreateToken&Format=JSON&RegionId=cn-shanghai&SignatureMethod=HMAC-SHA1&SignatureNonce=' + "xxccrr" + '&SignatureVersion=1.0&Timestamp=' + percentEncode(timestamp) + '&Version=2019-02-28';
var signStr = sign('GET&' + percentEncode('/') + '&' + percentEncode(query), accessKeySecret);
var queryStringWithSign = "Signature=" + signStr + "&" + query;
queryStringWithSign
""".trimIndent()
RhinoScriptEngine.eval(js)
@Language("js")
val js1 = """
var returnData = new Packages.io.legado.app.api.ReturnData()
returnData.getErrorMsg()
""".trimIndent()
val result1 = RhinoScriptEngine.eval(js1)
Assert.assertEquals(result1, "未知错误,请联系开发者!")
}
@Test
fun testPackages1() {
URLClassLoader.getSystemClassLoader()
DefiningClassLoader.getSystemClassLoader()
JarClassLoader.getSystemClassLoader()
DexClassLoader.getSystemClassLoader()
@Language("js")
val js = """
var ji = new JavaImporter(Packages.org.mozilla.javascript.DefiningClassLoader)
with(ji) {
let x = DefiningClassLoader.getSystemClassLoader()
}
""".trimIndent()
RhinoScriptEngine.eval(js)
}
@Test
fun testMap() {
val map = hashMapOf("id" to "3242532321")
val bindings = ScriptBindings()
bindings["result"] = map
@Language("js")
val jsMap = "$=result;id=$.id;id"
val result = RhinoScriptEngine.eval(jsMap, bindings)
Assert.assertEquals("3242532321", result)
@Language("js")
val jsMap1 = """result.get("id")"""
val result1 = RhinoScriptEngine.eval(jsMap1, bindings)
Assert.assertEquals("3242532321", result1)
}
}
@@ -0,0 +1,34 @@
package io.legato.kazusa
import android.content.Context
import android.net.Uri
import android.util.Log
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
/**
* 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 testContentProvider() {
// Context of the app under test.
val appContext = ApplicationProvider.getApplicationContext<Context>()
Log.d(
"test",
appContext.contentResolver.query(
Uri.parse("content://io.legado.app.api.ReaderProvider/sources/query"),
null,
null,
null,
null
)
!!.getString(0)
)
}
}
@@ -0,0 +1,83 @@
package io.legato.kazusa
import android.app.DownloadManager
import android.net.Uri
import android.os.Environment
import android.webkit.WebSettings
import android.webkit.WebView
import io.legato.kazusa.help.config.AppConfig
import io.legato.kazusa.utils.runOnUI
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.junit.Test
import splitties.init.appCtx
import splitties.systemservices.downloadManager
class HttpTest {
@Test
fun test() {
webViewDownloadTest()
}
private fun webViewDownloadTest() {
runOnUI {
val webView = WebView(appCtx)
val settings = webView.settings
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
settings.blockNetworkImage = true
settings.userAgentString = AppConfig.userAgent
settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
webView.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
print(url)
webView.destroy()
}
webView.loadUrl("https://gj.legado.cc/legado/?url=https://miaogongzi.lanzout.com/iITmP0s7y26d&type=down")
}
}
private fun downloadManagerTest() {
runBlocking {
val request =
DownloadManager.Request(Uri.parse("https://gj.legado.cc/legado/?url=https://miaogongzi.lanzout.com/iITmP0s7y26d&type=down"))
// 设置通知
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN)
// 设置下载文件保存的路径和文件名
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "test.txt")
// 添加一个下载任务
val downloadId = downloadManager.enqueue(request)
val query = DownloadManager.Query()
query.setFilterById(downloadId)
repeat(30) {
downloadManager.query(query).use { cursor ->
if (cursor.moveToFirst()) {
val progressIndex =
cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
val fileSizeIndex =
cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
val statusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)
val progress = cursor.getInt(progressIndex)
val max = cursor.getInt(fileSizeIndex)
val status = when (cursor.getInt(statusIndex)) {
DownloadManager.STATUS_PAUSED -> appCtx.getString(R.string.pause)
DownloadManager.STATUS_PENDING -> appCtx.getString(R.string.wait_download)
DownloadManager.STATUS_RUNNING -> appCtx.getString(R.string.downloading)
DownloadManager.STATUS_SUCCESSFUL -> {
appCtx.getString(R.string.download_success)
}
DownloadManager.STATUS_FAILED -> appCtx.getString(R.string.download_error)
else -> appCtx.getString(R.string.unknown_state)
}
print(status)
delay(1000)
} else {
return@runBlocking
}
}
}
}
}
}
@@ -0,0 +1,26 @@
package io.legato.kazusa
import io.legato.kazusa.help.config.AppConfig
import io.legato.kazusa.model.analyzeRule.AnalyzeUrl
import kotlinx.coroutines.runBlocking
import org.junit.Test
class HttpTtsTest {
@Test
fun test() {
val url = """
http://tsn.baidu.com/text2audio,{
"method": "POST",
"body": "tex={{java.encodeURI(java.encodeURI(speakText))}}&spd={{(speakSpeed + 5) / 10 + 4}}&per=4114&cuid=baidu_speech_demo&idx=1&cod=2&lan=zh&ctp=1&pdt=220&vol=5&aue=6&pit=5&_res_tag_=audio"
}
""".trimIndent()
val analyzeUrl =
AnalyzeUrl(url, speakText = "魔神", speakSpeed = AppConfig.speechRatePlay + 5)
runBlocking {
val response = analyzeUrl.getResponseAwait()
response.headers
}
}
}
@@ -0,0 +1,51 @@
package io.legato.kazusa
import androidx.room.Room
import androidx.room.migration.Migration
import androidx.room.testing.MigrationTestHelper
import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import io.legato.kazusa.data.AppDatabase
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.io.IOException
@RunWith(AndroidJUnit4::class)
class MigrationTest {
private val TEST_DB = "migration-test"
private val ALL_MIGRATIONS = arrayOf<Migration>(
)
@get:Rule
val helper: MigrationTestHelper = MigrationTestHelper(
InstrumentationRegistry.getInstrumentation(),
AppDatabase::class.java.canonicalName,
FrameworkSQLiteOpenHelperFactory()
)
@Test
@Throws(IOException::class)
fun migrateAll() {
// Create earliest version of the database.
helper.createDatabase(TEST_DB, 50).apply {
close()
}
// Open latest version of the database. Room will validate the schema
// once all migrations execute.
Room.databaseBuilder(
InstrumentationRegistry.getInstrumentation().targetContext,
AppDatabase::class.java,
TEST_DB
).addMigrations(*ALL_MIGRATIONS)
.build().apply {
openHelper.writableDatabase
close()
}
}
}
@@ -0,0 +1,54 @@
package io.legato.kazusa
import com.google.gson.Gson
import io.legato.kazusa.exception.NoStackTraceException
import io.legato.kazusa.help.http.okHttpClient
import io.legato.kazusa.help.update.GithubRelease
import io.legato.kazusa.utils.fromJsonObject
import okhttp3.Request
import org.junit.Assert.assertTrue
import org.junit.Test
class UpdateTest {
private val lastReleaseUrl =
"https://api.github.com/repos/gedoor/legado/releases/latest"
private val lastBetaReleaseUrl =
"https://api.github.com/repos/gedoor/legado/releases/tags/beta"
@Test
fun updateApp_beta() {
val body = okHttpClient.newCall(Request.Builder().url(lastBetaReleaseUrl).build()).execute()
.body!!.string()
val releaseList = Gson().fromJsonObject<GithubRelease>(body)
.getOrElse {
throw NoStackTraceException("获取新版本出错 " + it.localizedMessage)
}
.gitReleaseToAppReleaseInfo()
.sortedByDescending { it.createdAt }
assertTrue(releaseList.size == 2)
assertTrue(releaseList.all { it.downloadUrl.isNotBlank() })
assertTrue(releaseList.all { it.versionName.isNotBlank() })
}
@Test
fun updateApp() {
val body = okHttpClient.newCall(Request.Builder().url(lastReleaseUrl).build()).execute()
.body!!.string()
val releaseList = Gson().fromJsonObject<GithubRelease>(body)
.getOrElse {
throw NoStackTraceException("获取新版本出错 " + it.localizedMessage)
}
.gitReleaseToAppReleaseInfo()
.sortedByDescending { it.createdAt }
assertTrue(releaseList.size == 1)
assertTrue(releaseList.all { it.downloadUrl.isNotBlank() })
assertTrue(releaseList.all { it.versionName.isNotBlank() })
}
}