content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package io.nekohasekai.sagernet.ktx
import android.graphics.Rect
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ui.MainActivity
class FixedLinearLayoutManager(val recyclerView: RecyclerView) :
LinearLayoutManager(recyclerView.context, RecyclerView.VERTICAL, false) {
override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
try {
super.onLayoutChildren(recycler, state)
} catch (ignored: IndexOutOfBoundsException) {
}
}
private var listenerDisabled = false
override fun scrollVerticallyBy(
dx: Int, recycler: RecyclerView.Recycler,
state: RecyclerView.State
): Int {
// Matsuri style
if (!DataStore.showBottomBar) return super.scrollVerticallyBy(dx, recycler, state)
// SagerNet Style
val scrollRange = super.scrollVerticallyBy(dx, recycler, state)
if (listenerDisabled) return scrollRange
val activity = recyclerView.context as? MainActivity
if (activity == null) {
listenerDisabled = true
return scrollRange
}
val overscroll = dx - scrollRange
if (overscroll > 0) {
val view =
(recyclerView.findViewHolderForAdapterPosition(findLastVisibleItemPosition())
?: return scrollRange).itemView
val itemLocation = Rect().also { view.getGlobalVisibleRect(it) }
val fabLocation = Rect().also { activity.binding.fab.getGlobalVisibleRect(it) }
if (!itemLocation.contains(fabLocation.left, fabLocation.top) && !itemLocation.contains(
fabLocation.right,
fabLocation.bottom
)
) {
return scrollRange
}
activity.binding.fab.apply {
if (isShown) hide()
}
} else {
/*val screen = Rect().also { activity.window.decorView.getGlobalVisibleRect(it) }
val location = Rect().also { activity.stats.getGlobalVisibleRect(it) }
if (screen.bottom < location.bottom) {
return scrollRange
}
val height = location.bottom - location.top
val mH = activity.stats.measuredHeight
if (mH > height) {
return scrollRange
}*/
activity.binding.fab.apply {
if (!isShown) show()
}
}
return scrollRange
}
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/ktx/Layouts.kt | 2390426311 |
@file:Suppress("EXPERIMENTAL_API_USAGE")
package io.nekohasekai.sagernet.ktx
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.*
fun block(block: suspend CoroutineScope.() -> Unit): suspend CoroutineScope.() -> Unit {
return block
}
fun runOnDefaultDispatcher(block: suspend CoroutineScope.() -> Unit) =
GlobalScope.launch(Dispatchers.Default, block = block)
fun Fragment.runOnLifecycleDispatcher(block: suspend CoroutineScope.() -> Unit) =
lifecycleScope.launch(Dispatchers.Default, block = block)
suspend fun <T> onDefaultDispatcher(block: suspend CoroutineScope.() -> T) =
withContext(Dispatchers.Default, block = block)
fun runOnIoDispatcher(block: suspend CoroutineScope.() -> Unit) =
GlobalScope.launch(Dispatchers.IO, block = block)
suspend fun <T> onIoDispatcher(block: suspend CoroutineScope.() -> T) =
withContext(Dispatchers.IO, block = block)
fun runOnMainDispatcher(block: suspend CoroutineScope.() -> Unit) =
GlobalScope.launch(Dispatchers.Main.immediate, block = block)
suspend fun <T> onMainDispatcher(block: suspend CoroutineScope.() -> T) =
withContext(Dispatchers.Main.immediate, block = block)
fun runBlockingOnMainDispatcher(block: suspend CoroutineScope.() -> Unit) {
runBlocking {
GlobalScope.launch(Dispatchers.Main.immediate, block = block)
}
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/ktx/Asyncs.kt | 1694228162 |
package io.nekohasekai.sagernet.ktx
import androidx.preference.PreferenceDataStore
import kotlin.reflect.KProperty
fun PreferenceDataStore.string(
name: String,
defaultValue: () -> String = { "" },
) = PreferenceProxy(name, defaultValue, ::getString, ::putString)
fun PreferenceDataStore.boolean(
name: String,
defaultValue: () -> Boolean = { false },
) = PreferenceProxy(name, defaultValue, ::getBoolean, ::putBoolean)
fun PreferenceDataStore.int(
name: String,
defaultValue: () -> Int = { 0 },
) = PreferenceProxy(name, defaultValue, ::getInt, ::putInt)
fun PreferenceDataStore.stringSet(
name: String,
defaultValue: () -> Set<String> = { setOf() },
) = PreferenceProxy(name, defaultValue, ::getStringSet, ::putStringSet)
fun PreferenceDataStore.stringToInt(
name: String,
defaultValue: () -> Int = { 0 },
) = PreferenceProxy(name, defaultValue, { key, default ->
getString(key, "$default")?.toIntOrNull() ?: default
}, { key, value -> putString(key, "$value") })
fun PreferenceDataStore.stringToIntIfExists(
name: String,
defaultValue: () -> Int = { 0 },
) = PreferenceProxy(name, defaultValue, { key, default ->
getString(key, "$default")?.toIntOrNull() ?: default
}, { key, value -> putString(key, value.takeIf { it > 0 }?.toString() ?: "") })
fun PreferenceDataStore.long(
name: String,
defaultValue: () -> Long = { 0L },
) = PreferenceProxy(name, defaultValue, ::getLong, ::putLong)
fun PreferenceDataStore.stringToLong(
name: String,
defaultValue: () -> Long = { 0L },
) = PreferenceProxy(name, defaultValue, { key, default ->
getString(key, "$default")?.toLongOrNull() ?: default
}, { key, value -> putString(key, "$value") })
class PreferenceProxy<T>(
val name: String,
val defaultValue: () -> T,
val getter: (String, T) -> T?,
val setter: (String, value: T) -> Unit,
) {
operator fun setValue(thisObj: Any?, property: KProperty<*>, value: T) = setter(name, value)
operator fun getValue(thisObj: Any?, property: KProperty<*>) = getter(name, defaultValue())!!
} | nacs/app/src/main/java/io/nekohasekai/sagernet/ktx/Preferences.kt | 45294926 |
package io.nekohasekai.sagernet.ktx
import android.os.Parcel
import android.os.Parcelable
import com.esotericsoftware.kryo.io.ByteBufferInput
import com.esotericsoftware.kryo.io.ByteBufferOutput
import java.io.InputStream
import java.io.OutputStream
fun InputStream.byteBuffer() = ByteBufferInput(this)
fun OutputStream.byteBuffer() = ByteBufferOutput(this)
fun ByteBufferInput.readStringList(): List<String> {
return mutableListOf<String>().apply {
repeat(readInt()) {
add(readString())
}
}
}
fun ByteBufferInput.readStringSet(): Set<String> {
return linkedSetOf<String>().apply {
repeat(readInt()) {
add(readString())
}
}
}
fun ByteBufferOutput.writeStringList(list: List<String>) {
writeInt(list.size)
for (str in list) writeString(str)
}
fun ByteBufferOutput.writeStringList(list: Set<String>) {
writeInt(list.size)
for (str in list) writeString(str)
}
fun Parcelable.marshall(): ByteArray {
val parcel = Parcel.obtain()
writeToParcel(parcel, 0)
val bytes = parcel.marshall()
parcel.recycle()
return bytes
}
fun ByteArray.unmarshall(): Parcel {
val parcel = Parcel.obtain()
parcel.unmarshall(this, 0, size)
parcel.setDataPosition(0) // This is extremely important!
return parcel
}
fun <T> ByteArray.unmarshall(constructor: (Parcel) -> T): T {
val parcel = unmarshall()
val result = constructor(parcel)
parcel.recycle()
return result
} | nacs/app/src/main/java/io/nekohasekai/sagernet/ktx/Kryos.kt | 576632215 |
package io.nekohasekai.sagernet.plugin
import android.content.pm.ComponentInfo
import android.content.pm.ProviderInfo
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.bg.BaseService
import io.nekohasekai.sagernet.ktx.Logs
import moe.matsuri.nb4a.plugin.Plugins
import java.io.File
import java.io.FileNotFoundException
object PluginManager {
class PluginNotFoundException(val plugin: String) : FileNotFoundException(plugin),
BaseService.ExpectedException {
override fun getLocalizedMessage() =
SagerNet.application.getString(R.string.plugin_unknown, plugin)
}
data class InitResult(
val path: String,
val info: ProviderInfo,
)
@Throws(Throwable::class)
fun init(pluginId: String): InitResult? {
if (pluginId.isEmpty()) return null
var throwable: Throwable? = null
try {
val result = initNative(pluginId)
if (result != null) return result
} catch (t: Throwable) {
throwable = t
Logs.w(t)
}
throw throwable ?: PluginNotFoundException(pluginId)
}
private fun initNative(pluginId: String): InitResult? {
val info = Plugins.getPlugin(pluginId) ?: return null
// internal so
if (info.applicationInfo == null) {
try {
initNativeInternal(pluginId)?.let { return InitResult(it, info) }
} catch (t: Throwable) {
Logs.w("initNativeInternal failed", t)
}
return null
}
try {
initNativeFaster(info)?.let { return InitResult(it, info) }
} catch (t: Throwable) {
Logs.w("initNativeFaster failed", t)
}
Logs.w("Init native returns empty result")
return null
}
private fun initNativeInternal(pluginId: String): String? {
fun soIfExist(soName: String): String? {
val f = File(SagerNet.application.applicationInfo.nativeLibraryDir, soName)
if (f.canExecute()) {
return f.absolutePath
}
return null
}
return when (pluginId) {
"hysteria-plugin" -> soIfExist("libhysteria.so")
"hysteria2-plugin" -> soIfExist("libhysteria2.so")
else -> null
}
}
private fun initNativeFaster(provider: ProviderInfo): String? {
return provider.loadString(Plugins.METADATA_KEY_EXECUTABLE_PATH)
?.let { relativePath ->
File(provider.applicationInfo.nativeLibraryDir).resolve(relativePath).apply {
check(canExecute())
}.absolutePath
}
}
fun ComponentInfo.loadString(key: String) = when (val value = metaData.get(key)) {
is String -> value
is Int -> SagerNet.application.packageManager.getResourcesForApplication(applicationInfo)
.getString(value)
null -> null
else -> error("meta-data $key has invalid type ${value.javaClass}")
}
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/plugin/PluginManager.kt | 1935463820 |
package io.nekohasekai.sagernet.utils
import android.annotation.TargetApi
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.Build
import android.os.Handler
import android.os.Looper
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.ktx.Logs
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.actor
import kotlinx.coroutines.runBlocking
import java.net.UnknownHostException
object DefaultNetworkListener {
private sealed class NetworkMessage {
class Start(val key: Any, val listener: (Network?) -> Unit) : NetworkMessage()
class Get : NetworkMessage() {
val response = CompletableDeferred<Network>()
}
class Stop(val key: Any) : NetworkMessage()
class Put(val network: Network) : NetworkMessage()
class Update(val network: Network) : NetworkMessage()
class Lost(val network: Network) : NetworkMessage()
}
private val networkActor = GlobalScope.actor<NetworkMessage>(Dispatchers.Unconfined) {
val listeners = mutableMapOf<Any, (Network?) -> Unit>()
var network: Network? = null
val pendingRequests = arrayListOf<NetworkMessage.Get>()
for (message in channel) when (message) {
is NetworkMessage.Start -> {
if (listeners.isEmpty()) register()
listeners[message.key] = message.listener
if (network != null) message.listener(network)
}
is NetworkMessage.Get -> {
check(listeners.isNotEmpty()) { "Getting network without any listeners is not supported" }
if (network == null) pendingRequests += message else message.response.complete(
network
)
}
is NetworkMessage.Stop -> if (listeners.isNotEmpty() && // was not empty
listeners.remove(message.key) != null && listeners.isEmpty()
) {
network = null
unregister()
}
is NetworkMessage.Put -> {
network = message.network
pendingRequests.forEach { it.response.complete(message.network) }
pendingRequests.clear()
listeners.values.forEach { it(network) }
}
is NetworkMessage.Update -> if (network == message.network) listeners.values.forEach {
it(
network
)
}
is NetworkMessage.Lost -> if (network == message.network) {
network = null
listeners.values.forEach { it(null) }
}
}
}
suspend fun start(key: Any, listener: (Network?) -> Unit) =
networkActor.send(NetworkMessage.Start(key, listener))
suspend fun get() = if (fallback) @TargetApi(23) {
SagerNet.connectivity.activeNetwork
?: throw UnknownHostException() // failed to listen, return current if available
} else NetworkMessage.Get().run {
networkActor.send(this)
response.await()
}
suspend fun stop(key: Any) = networkActor.send(NetworkMessage.Stop(key))
// NB: this runs in ConnectivityThread, and this behavior cannot be changed until API 26
private object Callback : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) =
runBlocking { networkActor.send(NetworkMessage.Put(network)) }
override fun onCapabilitiesChanged(
network: Network, networkCapabilities: NetworkCapabilities
) { // it's a good idea to refresh capabilities
runBlocking { networkActor.send(NetworkMessage.Update(network)) }
}
override fun onLost(network: Network) =
runBlocking { networkActor.send(NetworkMessage.Lost(network)) }
}
private var fallback = false
private val request = NetworkRequest.Builder().apply {
addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
if (Build.VERSION.SDK_INT == 23) { // workarounds for OEM bugs
removeCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
removeCapability(NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL)
}
}.build()
private val mainHandler = Handler(Looper.getMainLooper())
/**
* Unfortunately registerDefaultNetworkCallback is going to return VPN interface since Android P DP1:
* https://android.googlesource.com/platform/frameworks/base/+/dda156ab0c5d66ad82bdcf76cda07cbc0a9c8a2e
*
* This makes doing a requestNetwork with REQUEST necessary so that we don't get ALL possible networks that
* satisfies default network capabilities but only THE default network. Unfortunately, we need to have
* android.permission.CHANGE_NETWORK_STATE to be able to call requestNetwork.
*
* Source: https://android.googlesource.com/platform/frameworks/base/+/2df4c7d/services/core/java/com/android/server/ConnectivityService.java#887
*/
private fun register() {
try {
fallback = false
when (Build.VERSION.SDK_INT) {
in 31..Int.MAX_VALUE -> @TargetApi(31) {
SagerNet.connectivity.registerBestMatchingNetworkCallback(
request, Callback, mainHandler
)
}
in 28 until 31 -> @TargetApi(28) { // we want REQUEST here instead of LISTEN
SagerNet.connectivity.requestNetwork(request, Callback, mainHandler)
}
in 26 until 28 -> @TargetApi(26) {
SagerNet.connectivity.registerDefaultNetworkCallback(Callback, mainHandler)
}
in 24 until 26 -> @TargetApi(24) {
SagerNet.connectivity.registerDefaultNetworkCallback(Callback)
}
else -> {
SagerNet.connectivity.requestNetwork(request, Callback)
// known bug on API 23: https://stackoverflow.com/a/33509180/2245107
}
}
} catch (e: Exception) {
Logs.w(e)
fallback = true
}
}
private fun unregister() = SagerNet.connectivity.unregisterNetworkCallback(Callback)
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/utils/DefaultNetworkListener.kt | 2857278193 |
package io.nekohasekai.sagernet.utils.cf
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import com.wireguard.crypto.Key
import java.text.SimpleDateFormat
import java.util.*
data class RegisterRequest(
@SerializedName("fcm_token") var fcmToken: String = "",
@SerializedName("install_id") var installedId: String = "",
var key: String = "",
var locale: String = "",
var model: String = "",
var tos: String = "",
var type: String = ""
) {
companion object {
fun newRequest(publicKey: Key): String {
val request = RegisterRequest()
request.fcmToken = ""
request.installedId = ""
request.key = publicKey.toBase64()
request.locale = "en_US"
request.model = "PC"
val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'000000'+08:00", Locale.US)
request.tos = format.format(Date())
request.type = "Android"
return Gson().toJson(request)
}
}
} | nacs/app/src/main/java/io/nekohasekai/sagernet/utils/cf/RegisterRequest.kt | 1471201697 |
package io.nekohasekai.sagernet.utils.cf
import com.google.gson.Gson
data class UpdateDeviceRequest(
var name: String, var active: Boolean
) {
companion object {
fun newRequest(name: String = "SagerNet Client", active: Boolean = true) =
Gson().toJson(UpdateDeviceRequest(name, active))
}
} | nacs/app/src/main/java/io/nekohasekai/sagernet/utils/cf/UpdateDeviceRequest.kt | 1219765438 |
package io.nekohasekai.sagernet.utils.cf
import com.google.gson.annotations.SerializedName
data class DeviceResponse(
@SerializedName("created")
var created: String = "",
@SerializedName("type")
var type: String = "",
@SerializedName("locale")
var locale: String = "",
@SerializedName("enabled")
var enabled: Boolean = false,
@SerializedName("token")
var token: String = "",
@SerializedName("waitlist_enabled")
var waitlistEnabled: Boolean = false,
@SerializedName("install_id")
var installId: String = "",
@SerializedName("warp_enabled")
var warpEnabled: Boolean = false,
@SerializedName("name")
var name: String = "",
@SerializedName("fcm_token")
var fcmToken: String = "",
@SerializedName("tos")
var tos: String = "",
@SerializedName("model")
var model: String = "",
@SerializedName("id")
var id: String = "",
@SerializedName("place")
var place: Int = 0,
@SerializedName("config")
var config: Config = Config(),
@SerializedName("updated")
var updated: String = "",
@SerializedName("key")
var key: String = "",
@SerializedName("account")
var account: Account = Account()
) {
data class Config(
@SerializedName("peers")
var peers: List<Peer> = listOf(),
@SerializedName("services")
var services: Services = Services(),
@SerializedName("interface")
var interfaceX: Interface = Interface(),
@SerializedName("client_id")
var clientId: String = ""
) {
data class Peer(
@SerializedName("public_key")
var publicKey: String = "",
@SerializedName("endpoint")
var endpoint: Endpoint = Endpoint()
) {
data class Endpoint(
@SerializedName("v6")
var v6: String = "",
@SerializedName("host")
var host: String = "",
@SerializedName("v4")
var v4: String = ""
)
}
data class Services(
@SerializedName("http_proxy")
var httpProxy: String = ""
)
data class Interface(
@SerializedName("addresses")
var addresses: Addresses = Addresses()
) {
data class Addresses(
@SerializedName("v6")
var v6: String = "",
@SerializedName("v4")
var v4: String = ""
)
}
}
data class Account(
@SerializedName("account_type")
var accountType: String = "",
@SerializedName("role")
var role: String = "",
@SerializedName("referral_renewal_countdown")
var referralRenewalCountdown: Int = 0,
@SerializedName("created")
var created: String = "",
@SerializedName("usage")
var usage: Int = 0,
@SerializedName("warp_plus")
var warpPlus: Boolean = false,
@SerializedName("referral_count")
var referralCount: Int = 0,
@SerializedName("license")
var license: String = "",
@SerializedName("quota")
var quota: Int = 0,
@SerializedName("premium_data")
var premiumData: Int = 0,
@SerializedName("id")
var id: String = "",
@SerializedName("updated")
var updated: String = ""
)
} | nacs/app/src/main/java/io/nekohasekai/sagernet/utils/cf/DeviceResponse.kt | 3183051982 |
package io.nekohasekai.sagernet.utils
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.util.Log
import com.jakewharton.processphoenix.ProcessPhoenix
import io.nekohasekai.sagernet.BuildConfig
import io.nekohasekai.sagernet.database.preference.PublicDatabase
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ui.BlankActivity
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Pattern
object CrashHandler : Thread.UncaughtExceptionHandler {
@Suppress("UNNECESSARY_SAFE_CALL")
override fun uncaughtException(thread: Thread, throwable: Throwable) {
// note: libc / go panic is in android log
try {
Log.e(thread.toString(), throwable.stackTraceToString())
} catch (e: Exception) {
}
try {
Logs.e(thread.toString())
Logs.e(throwable.stackTraceToString())
} catch (e: Exception) {
}
ProcessPhoenix.triggerRebirth(app, Intent(app, BlankActivity::class.java).apply {
putExtra("sendLog", "husi Crash")
})
}
fun formatThrowable(throwable: Throwable): String {
var format = throwable.javaClass.name
val message = throwable.message
if (!message.isNullOrBlank()) {
format += ": $message"
}
format += "\n"
format += throwable.stackTrace.joinToString("\n") {
" at ${it.className}.${it.methodName}(${it.fileName}:${if (it.isNativeMethod) "native" else it.lineNumber})"
}
val cause = throwable.cause
if (cause != null) {
format += "\n\nCaused by: " + formatThrowable(cause)
}
return format
}
fun buildReportHeader(): String {
var report = ""
report += "husi ${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE}) ${BuildConfig.FLAVOR.uppercase()}\n"
report += "Date: ${getCurrentMilliSecondUTCTimeStamp()}\n\n"
report += "OS_VERSION: ${getSystemPropertyWithAndroidAPI("os.version")}\n"
report += "SDK_INT: ${Build.VERSION.SDK_INT}\n"
report += if ("REL" == Build.VERSION.CODENAME) {
"RELEASE: ${Build.VERSION.RELEASE}"
} else {
"CODENAME: ${Build.VERSION.CODENAME}"
} + "\n"
report += "ID: ${Build.ID}\n"
report += "DISPLAY: ${Build.DISPLAY}\n"
report += "INCREMENTAL: ${Build.VERSION.INCREMENTAL}\n"
val systemProperties = getSystemProperties()
report += "SECURITY_PATCH: ${systemProperties.getProperty("ro.build.version.security_patch")}\n"
report += "IS_DEBUGGABLE: ${systemProperties.getProperty("ro.debuggable")}\n"
report += "IS_EMULATOR: ${systemProperties.getProperty("ro.boot.qemu")}\n"
report += "IS_TREBLE_ENABLED: ${systemProperties.getProperty("ro.treble.enabled")}\n"
report += "TYPE: ${Build.TYPE}\n"
report += "TAGS: ${Build.TAGS}\n\n"
report += "MANUFACTURER: ${Build.MANUFACTURER}\n"
report += "BRAND: ${Build.BRAND}\n"
report += "MODEL: ${Build.MODEL}\n"
report += "PRODUCT: ${Build.PRODUCT}\n"
report += "BOARD: ${Build.BOARD}\n"
report += "HARDWARE: ${Build.HARDWARE}\n"
report += "DEVICE: ${Build.DEVICE}\n"
report += "SUPPORTED_ABIS: ${
Build.SUPPORTED_ABIS.filter { it.isNotBlank() }.joinToString(", ")
}\n\n"
try {
report += "Settings: \n"
for (pair in PublicDatabase.kvPairDao.all()) {
report += "\n"
report += pair.key + ": " + pair.toString()
}
} catch (e: Exception) {
report += "Export settings failed: " + formatThrowable(e)
}
report += "\n\n"
return report
}
private fun getSystemProperties(): Properties {
val systemProperties = Properties()
// getprop commands returns values in the format `[key]: [value]`
// Regex matches string starting with a literal `[`,
// followed by one or more characters that do not match a closing square bracket as the key,
// followed by a literal `]: [`,
// followed by one or more characters as the value,
// followed by string ending with literal `]`
// multiline values will be ignored
val propertiesPattern = Pattern.compile("^\\[([^]]+)]: \\[(.+)]$")
try {
val process = ProcessBuilder().command("/system/bin/getprop")
.redirectErrorStream(true)
.start()
val inputStream = process.inputStream
val bufferedReader = BufferedReader(InputStreamReader(inputStream))
var line: String?
var key: String
var value: String
while (bufferedReader.readLine().also { line = it } != null) {
val matcher = propertiesPattern.matcher(line)
if (matcher.matches()) {
key = matcher.group(1)
value = matcher.group(2)
if (key != null && value != null && !key.isEmpty() && !value.isEmpty()) systemProperties[key] =
value
}
}
bufferedReader.close()
process.destroy()
} catch (e: IOException) {
Logs.e(
"Failed to get run \"/system/bin/getprop\" to get system properties.", e
)
}
//for (String key : systemProperties.stringPropertyNames()) {
// Logger.logVerbose(key + ": " + systemProperties.get(key));
//}
return systemProperties
}
private fun getSystemPropertyWithAndroidAPI(property: String): String? {
return try {
System.getProperty(property)
} catch (e: Exception) {
Logs.e("Failed to get system property \"" + property + "\":" + e.message)
null
}
}
@SuppressLint("SimpleDateFormat")
private fun getCurrentMilliSecondUTCTimeStamp(): String {
val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z")
df.timeZone = TimeZone.getTimeZone("UTC")
return df.format(Date())
}
} | nacs/app/src/main/java/io/nekohasekai/sagernet/utils/CrashHandler.kt | 2876288223 |
package io.nekohasekai.sagernet.utils
import android.content.Context
import android.content.res.Configuration
import androidx.appcompat.app.AppCompatDelegate
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ktx.app
object Theme {
const val RED = 1
const val PINK_SSR = 2
const val PINK = 3
const val PURPLE = 4
const val DEEP_PURPLE = 5
const val INDIGO = 6
const val BLUE = 7
const val LIGHT_BLUE = 8
const val CYAN = 9
const val TEAL = 10
const val GREEN = 11
const val LIGHT_GREEN = 12
const val LIME = 13
const val YELLOW = 14
const val AMBER = 15
const val ORANGE = 16
const val DEEP_ORANGE = 17
const val BROWN = 18
const val GREY = 19
const val BLUE_GREY = 20
const val BLACK = 21
private fun defaultTheme() = PINK_SSR
fun apply(context: Context) {
context.setTheme(getTheme())
}
fun applyDialog(context: Context) {
context.setTheme(getDialogTheme())
}
fun getTheme(): Int {
return getTheme(DataStore.appTheme)
}
fun getDialogTheme(): Int {
return getDialogTheme(DataStore.appTheme)
}
fun getTheme(theme: Int): Int {
return when (theme) {
RED -> R.style.Theme_SagerNet_Red
PINK -> R.style.Theme_SagerNet
PINK_SSR -> R.style.Theme_SagerNet_Pink_SSR
PURPLE -> R.style.Theme_SagerNet_Purple
DEEP_PURPLE -> R.style.Theme_SagerNet_DeepPurple
INDIGO -> R.style.Theme_SagerNet_Indigo
BLUE -> R.style.Theme_SagerNet_Blue
LIGHT_BLUE -> R.style.Theme_SagerNet_LightBlue
CYAN -> R.style.Theme_SagerNet_Cyan
TEAL -> R.style.Theme_SagerNet_Teal
GREEN -> R.style.Theme_SagerNet_Green
LIGHT_GREEN -> R.style.Theme_SagerNet_LightGreen
LIME -> R.style.Theme_SagerNet_Lime
YELLOW -> R.style.Theme_SagerNet_Yellow
AMBER -> R.style.Theme_SagerNet_Amber
ORANGE -> R.style.Theme_SagerNet_Orange
DEEP_ORANGE -> R.style.Theme_SagerNet_DeepOrange
BROWN -> R.style.Theme_SagerNet_Brown
GREY -> R.style.Theme_SagerNet_Grey
BLUE_GREY -> R.style.Theme_SagerNet_BlueGrey
BLACK -> R.style.Theme_SagerNet_Black
else -> getTheme(defaultTheme())
}
}
fun getDialogTheme(theme: Int): Int {
return when (theme) {
RED -> R.style.Theme_SagerNet_Dialog_Red
PINK -> R.style.Theme_SagerNet_Dialog
PINK_SSR -> R.style.Theme_SagerNet_Dialog_Pink_SSR
PURPLE -> R.style.Theme_SagerNet_Dialog_Purple
DEEP_PURPLE -> R.style.Theme_SagerNet_Dialog_DeepPurple
INDIGO -> R.style.Theme_SagerNet_Dialog_Indigo
BLUE -> R.style.Theme_SagerNet_Dialog_Blue
LIGHT_BLUE -> R.style.Theme_SagerNet_Dialog_LightBlue
CYAN -> R.style.Theme_SagerNet_Dialog_Cyan
TEAL -> R.style.Theme_SagerNet_Dialog_Teal
GREEN -> R.style.Theme_SagerNet_Dialog_Green
LIGHT_GREEN -> R.style.Theme_SagerNet_Dialog_LightGreen
LIME -> R.style.Theme_SagerNet_Dialog_Lime
YELLOW -> R.style.Theme_SagerNet_Dialog_Yellow
AMBER -> R.style.Theme_SagerNet_Dialog_Amber
ORANGE -> R.style.Theme_SagerNet_Dialog_Orange
DEEP_ORANGE -> R.style.Theme_SagerNet_Dialog_DeepOrange
BROWN -> R.style.Theme_SagerNet_Dialog_Brown
GREY -> R.style.Theme_SagerNet_Dialog_Grey
BLUE_GREY -> R.style.Theme_SagerNet_Dialog_BlueGrey
BLACK -> R.style.Theme_SagerNet_Dialog_Black
else -> getDialogTheme(defaultTheme())
}
}
var currentNightMode = -1
fun getNightMode(): Int {
if (currentNightMode == -1) {
currentNightMode = DataStore.nightTheme
}
return getNightMode(currentNightMode)
}
fun getNightMode(mode: Int): Int {
return when (mode) {
0 -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
1 -> AppCompatDelegate.MODE_NIGHT_YES
2 -> AppCompatDelegate.MODE_NIGHT_NO
else -> AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY
}
}
fun usingNightMode(): Boolean {
return when (DataStore.nightTheme) {
1 -> true
2 -> false
else -> (app.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
}
}
fun applyNightTheme() {
AppCompatDelegate.setDefaultNightMode(getNightMode())
}
} | nacs/app/src/main/java/io/nekohasekai/sagernet/utils/Theme.kt | 176227511 |
package io.nekohasekai.sagernet.utils
import io.nekohasekai.sagernet.ktx.parseNumericAddress
import java.net.InetAddress
import java.util.*
class Subnet(val address: InetAddress, val prefixSize: Int) : Comparable<Subnet> {
companion object {
fun fromString(value: String, lengthCheck: Int = -1): Subnet? {
val parts = value.split('/', limit = 2)
val addr = parts[0].parseNumericAddress() ?: return null
check(lengthCheck < 0 || addr.address.size == lengthCheck)
return if (parts.size == 2) try {
val prefixSize = parts[1].toInt()
if (prefixSize < 0 || prefixSize > addr.address.size shl 3) null else Subnet(
addr,
prefixSize
)
} catch (_: NumberFormatException) {
null
} else Subnet(addr, addr.address.size shl 3)
}
}
private val addressLength get() = address.address.size shl 3
init {
require(prefixSize in 0..addressLength) { "prefixSize $prefixSize not in 0..$addressLength" }
}
class Immutable(private val a: ByteArray, private val prefixSize: Int = 0) {
companion object : Comparator<Immutable> {
override fun compare(a: Immutable, b: Immutable): Int {
check(a.a.size == b.a.size)
for (i in a.a.indices) {
val result = a.a[i].compareTo(b.a[i])
if (result != 0) return result
}
return 0
}
}
fun matches(b: Immutable) = matches(b.a)
fun matches(b: ByteArray): Boolean {
if (a.size != b.size) return false
var i = 0
while (i * 8 < prefixSize && i * 8 + 8 <= prefixSize) {
if (a[i] != b[i]) return false
++i
}
return i * 8 == prefixSize || a[i] == (b[i].toInt() and -(1 shl i * 8 + 8 - prefixSize)).toByte()
}
}
fun toImmutable() = Immutable(address.address.also {
var i = prefixSize / 8
if (prefixSize % 8 > 0) {
it[i] = (it[i].toInt() and -(1 shl i * 8 + 8 - prefixSize)).toByte()
++i
}
while (i < it.size) it[i++] = 0
}, prefixSize)
override fun toString(): String =
if (prefixSize == addressLength) address.hostAddress else address.hostAddress + '/' + prefixSize
private fun Byte.unsigned() = toInt() and 0xFF
override fun compareTo(other: Subnet): Int {
val addrThis = address.address
val addrThat = other.address.address
var result =
addrThis.size.compareTo(addrThat.size) // IPv4 address goes first
if (result != 0) return result
for (i in addrThis.indices) {
result = addrThis[i].unsigned()
.compareTo(addrThat[i].unsigned()) // undo sign extension of signed byte
if (result != 0) return result
}
return prefixSize.compareTo(other.prefixSize)
}
override fun equals(other: Any?): Boolean {
val that = other as? Subnet
return address == that?.address && prefixSize == that.prefixSize
}
override fun hashCode(): Int = Objects.hash(address, prefixSize)
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/utils/Subnet.kt | 3127769274 |
package io.nekohasekai.sagernet.utils
import com.wireguard.crypto.KeyPair
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.fmt.wireguard.WireGuardBean
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.utils.cf.DeviceResponse
import io.nekohasekai.sagernet.utils.cf.RegisterRequest
import io.nekohasekai.sagernet.utils.cf.UpdateDeviceRequest
import libcore.Libcore
import moe.matsuri.nb4a.utils.JavaUtil.gson
// kang from wgcf
object Cloudflare {
private const val API_URL = "https://api.cloudflareclient.com"
private const val API_VERSION = "v0a1922"
private const val CLIENT_VERSION_KEY = "CF-Client-Version"
private const val CLIENT_VERSION = "a-6.3-1922"
fun makeWireGuardConfiguration(): WireGuardBean {
val keyPair = KeyPair()
val client = Libcore.newHttpClient().apply {
pinnedTLS12()
trySocks5(DataStore.mixedPort)
useCazilla(DataStore.enabledCazilla)
}
try {
val response = client.newRequest().apply {
setMethod("POST")
setURL("$API_URL/$API_VERSION/reg")
setHeader(CLIENT_VERSION_KEY, CLIENT_VERSION)
setHeader("Accept", "application/json")
setHeader("Content-Type", "application/json")
setContentString(RegisterRequest.newRequest(keyPair.publicKey))
setUserAgent("okhttp/3.12.1")
}.execute()
Logs.d(response.contentString)
val device = gson.fromJson(response.contentString, DeviceResponse::class.java)
val accessToken = device.token
client.newRequest().apply {
setMethod("PATCH")
setURL(API_URL + "/" + API_VERSION + "/reg/" + device.id + "/account/reg/" + device.id)
setHeader("Accept", "application/json")
setHeader("Content-Type", "application/json")
setHeader("Authorization", "Bearer $accessToken")
setHeader(CLIENT_VERSION_KEY, CLIENT_VERSION)
setContentString(UpdateDeviceRequest.newRequest())
setUserAgent("okhttp/3.12.1")
}.execute()
val peer = device.config.peers[0]
val localAddresses = device.config.interfaceX.addresses
return WireGuardBean().apply {
name = "CloudFlare Warp ${device.account.id}"
privateKey = keyPair.privateKey.toBase64()
peerPublicKey = peer.publicKey
serverAddress = peer.endpoint.host.substringBeforeLast(":")
serverPort = peer.endpoint.host.substringAfterLast(":").toInt()
localAddress = localAddresses.v4 + "/32" + "\n" + localAddresses.v6 + "/128"
mtu = 1280
reserved = device.config.clientId
}
} finally {
client.close()
}
}
} | nacs/app/src/main/java/io/nekohasekai/sagernet/utils/Cloudflare.kt | 581237558 |
package io.nekohasekai.sagernet.utils
import java.util.*
/**
* Commandline objects help handling command lines specifying processes to
* execute.
*
* The class can be used to define a command line as nested elements or as a
* helper to define a command line by an application.
*
*
* `
* <someelement><br></br>
* <acommandline executable="/executable/to/run"><br></br>
* <argument value="argument 1" /><br></br>
* <argument line="argument_1 argument_2 argument_3" /><br></br>
* <argument value="argument 4" /><br></br>
* </acommandline><br></br>
* </someelement><br></br>
` *
*
* Based on: https://github.com/apache/ant/blob/588ce1f/src/main/org/apache/tools/ant/types/Commandline.java
*
* Adds support for escape character '\'.
*/
object Commandline {
/**
* Quote the parts of the given array in way that makes them
* usable as command line arguments.
* @param args the list of arguments to quote.
* @return empty string for null or no command, else every argument split
* by spaces and quoted by quoting rules.
*/
fun toString(args: Iterable<String>?): String {
// empty path return empty string
args ?: return ""
// path containing one or more elements
val result = StringBuilder()
for (arg in args) {
if (result.isNotEmpty()) result.append(' ')
arg.indices.map { arg[it] }.forEach {
when (it) {
' ', '\\', '"', '\'' -> {
result.append('\\') // intentionally no break
result.append(it)
}
else -> result.append(it)
}
}
}
return result.toString()
}
/**
* Quote the parts of the given array in way that makes them
* usable as command line arguments.
* @param args the list of arguments to quote.
* @return empty string for null or no command, else every argument split
* by spaces and quoted by quoting rules.
*/
fun toString(args: Array<String>) =
toString(args.asIterable()) // thanks to Java, arrays aren't iterable
/**
* Crack a command line.
* @param toProcess the command line to process.
* @return the command line broken into strings.
* An empty or null toProcess parameter results in a zero sized array.
*/
fun translateCommandline(toProcess: String?): Array<String> {
if (toProcess == null || toProcess.isEmpty()) {
//no command? no string
return arrayOf()
}
// parse with a simple finite state machine
val normal = 0
val inQuote = 1
val inDoubleQuote = 2
var state = normal
val tok = StringTokenizer(toProcess, "\\\"\' ", true)
val result = ArrayList<String>()
val current = StringBuilder()
var lastTokenHasBeenQuoted = false
var lastTokenIsSlash = false
while (tok.hasMoreTokens()) {
val nextTok = tok.nextToken()
when (state) {
inQuote -> if ("\'" == nextTok) {
lastTokenHasBeenQuoted = true
state = normal
} else current.append(nextTok)
inDoubleQuote -> when (nextTok) {
"\"" -> if (lastTokenIsSlash) {
current.append(nextTok)
lastTokenIsSlash = false
} else {
lastTokenHasBeenQuoted = true
state = normal
}
"\\" -> lastTokenIsSlash = if (lastTokenIsSlash) {
current.append(nextTok)
false
} else true
else -> {
if (lastTokenIsSlash) {
current.append("\\") // unescaped
lastTokenIsSlash = false
}
current.append(nextTok)
}
}
else -> {
when {
lastTokenIsSlash -> {
current.append(nextTok)
lastTokenIsSlash = false
}
"\\" == nextTok -> lastTokenIsSlash = true
"\'" == nextTok -> state = inQuote
"\"" == nextTok -> state = inDoubleQuote
" " == nextTok -> if (lastTokenHasBeenQuoted || current.isNotEmpty()) {
result.add(current.toString())
current.setLength(0)
}
else -> current.append(nextTok)
}
lastTokenHasBeenQuoted = false
}
}
}
if (lastTokenHasBeenQuoted || current.isNotEmpty()) result.add(current.toString())
require(state != inQuote && state != inDoubleQuote) { "unbalanced quotes in $toProcess" }
require(!lastTokenIsSlash) { "escape character following nothing in $toProcess" }
return result.toTypedArray()
}
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/utils/Commandline.kt | 1071655378 |
package io.nekohasekai.sagernet.utils
import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ktx.listenForPackageChanges
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import moe.matsuri.nb4a.plugin.Plugins
import java.util.concurrent.atomic.AtomicBoolean
object PackageCache {
lateinit var installedPackages: Map<String, PackageInfo>
lateinit var installedPluginPackages: Map<String, PackageInfo>
lateinit var installedApps: Map<String, ApplicationInfo>
lateinit var packageMap: Map<String, Int>
val uidMap = HashMap<Int, HashSet<String>>()
val loaded = Mutex(true)
var registerd = AtomicBoolean(false)
// called from init (suspend)
fun register() {
if (registerd.getAndSet(true)) return
reload()
app.listenForPackageChanges(false) {
reload()
labelMap.clear()
}
loaded.unlock()
}
@SuppressLint("InlinedApi")
fun reload() {
val rawPackageInfo = app.packageManager.getInstalledPackages(
PackageManager.MATCH_UNINSTALLED_PACKAGES
or PackageManager.GET_PERMISSIONS
or PackageManager.GET_PROVIDERS
or PackageManager.GET_META_DATA
)
installedPackages = rawPackageInfo.filter {
when (it.packageName) {
"android" -> true
else -> it.requestedPermissions?.contains(Manifest.permission.INTERNET) == true
}
}.associateBy { it.packageName }
installedPluginPackages = rawPackageInfo.filter {
Plugins.isExeOrPlugin(it)
}.associateBy { it.packageName }
val installed = app.packageManager.getInstalledApplications(PackageManager.GET_META_DATA)
installedApps = installed.associateBy { it.packageName }
packageMap = installed.associate { it.packageName to it.uid }
uidMap.clear()
for (info in installed) {
val uid = info.uid
uidMap.getOrPut(uid) { HashSet() }.add(info.packageName)
}
}
operator fun get(uid: Int) = uidMap[uid]
operator fun get(packageName: String) = packageMap[packageName]
suspend fun awaitLoad() {
if (::packageMap.isInitialized) {
return
}
loaded.withLock {
// just await
}
}
fun awaitLoadSync() {
if (::packageMap.isInitialized) {
return
}
if (!registerd.get()) {
register()
return
}
runBlocking {
loaded.withLock {
// just await
}
}
}
private val labelMap = mutableMapOf<String, String>()
fun loadLabel(packageName: String): String {
var label = labelMap[packageName]
if (label != null) return label
val info = installedApps[packageName] ?: return packageName
label = info.loadLabel(app.packageManager).toString()
labelMap[packageName] = label
return label
}
} | nacs/app/src/main/java/io/nekohasekai/sagernet/utils/PackageCache.kt | 2330990160 |
package io.nekohasekai.sagernet
import android.annotation.SuppressLint
import android.app.*
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.net.ConnectivityManager
import android.net.Network
import android.net.wifi.WifiManager
import android.os.Build
import android.os.PowerManager
import android.os.StrictMode
import android.os.UserManager
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import go.Seq
import io.nekohasekai.sagernet.bg.SagerConnection
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.ktx.runOnDefaultDispatcher
import io.nekohasekai.sagernet.ui.MainActivity
import io.nekohasekai.sagernet.utils.CrashHandler
import io.nekohasekai.sagernet.utils.DefaultNetworkListener
import io.nekohasekai.sagernet.utils.PackageCache
import io.nekohasekai.sagernet.utils.Theme
import kotlinx.coroutines.DEBUG_PROPERTY_NAME
import kotlinx.coroutines.DEBUG_PROPERTY_VALUE_ON
import libcore.Libcore
import moe.matsuri.nb4a.NativeInterface
import moe.matsuri.nb4a.utils.JavaUtil
import moe.matsuri.nb4a.utils.cleanWebview
import androidx.work.Configuration as WorkConfiguration
class SagerNet : Application(),
WorkConfiguration.Provider {
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
application = this
}
val nativeInterface = NativeInterface()
val externalAssets by lazy { getExternalFilesDir(null) ?: filesDir }
val process = JavaUtil.getProcessName()
val isMainProcess = process == BuildConfig.APPLICATION_ID
val isBgProcess = process.endsWith(":bg")
override fun onCreate() {
super.onCreate()
System.setProperty(DEBUG_PROPERTY_NAME, DEBUG_PROPERTY_VALUE_ON)
Thread.setDefaultUncaughtExceptionHandler(CrashHandler)
if (isMainProcess || isBgProcess) {
// fix multi process issue in Android 9+
JavaUtil.handleWebviewDir(this)
runOnDefaultDispatcher {
PackageCache.register()
cleanWebview()
}
}
Seq.setContext(this)
updateNotificationChannels()
// nb4a: init core
externalAssets.mkdirs()
Libcore.initCore(
process,
cacheDir.absolutePath + "/",
filesDir.absolutePath + "/",
externalAssets.absolutePath + "/",
DataStore.logBufSize,
DataStore.logLevel > 0,
nativeInterface, nativeInterface
)
if (isMainProcess) {
Theme.apply(this)
Theme.applyNightTheme()
runOnDefaultDispatcher {
DefaultNetworkListener.start(this) {
underlyingNetwork = it
}
}
}
if (BuildConfig.DEBUG) StrictMode.setVmPolicy(
StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.detectLeakedRegistrationObjects()
.penaltyLog()
.build()
)
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
updateNotificationChannels()
}
override val workManagerConfiguration: androidx.work.Configuration
get() {
return WorkConfiguration.Builder()
.setDefaultProcessName("${BuildConfig.APPLICATION_ID}:bg")
.build()
}
override fun onTrimMemory(level: Int) {
super.onTrimMemory(level)
Libcore.forceGc()
}
@SuppressLint("InlinedApi")
companion object {
lateinit var application: SagerNet
val isTv by lazy {
uiMode.currentModeType == Configuration.UI_MODE_TYPE_TELEVISION
}
val configureIntent: (Context) -> PendingIntent by lazy {
{
PendingIntent.getActivity(
it,
0,
Intent(
application, MainActivity::class.java
).setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0
)
}
}
val activity by lazy { application.getSystemService<ActivityManager>()!! }
val clipboard by lazy { application.getSystemService<ClipboardManager>()!! }
val connectivity by lazy { application.getSystemService<ConnectivityManager>()!! }
val notification by lazy { application.getSystemService<NotificationManager>()!! }
val user by lazy { application.getSystemService<UserManager>()!! }
val uiMode by lazy { application.getSystemService<UiModeManager>()!! }
val power by lazy { application.getSystemService<PowerManager>()!! }
val wifiManager by lazy { application.getSystemService<WifiManager>()!! }
fun getClipboardText(): String {
return clipboard.primaryClip?.takeIf { it.itemCount > 0 }
?.getItemAt(0)?.text?.toString() ?: ""
}
fun trySetPrimaryClip(clip: String) = try {
clipboard.setPrimaryClip(ClipData.newPlainText(null, clip))
true
} catch (e: RuntimeException) {
Logs.w(e)
false
}
fun updateNotificationChannels() {
if (Build.VERSION.SDK_INT >= 26) @RequiresApi(26) {
notification.createNotificationChannels(
listOf(
NotificationChannel(
"service-vpn",
application.getText(R.string.service_vpn),
if (Build.VERSION.SDK_INT >= 28) NotificationManager.IMPORTANCE_MIN
else NotificationManager.IMPORTANCE_LOW
), // #1355
NotificationChannel(
"service-proxy",
application.getText(R.string.service_proxy),
NotificationManager.IMPORTANCE_LOW
), NotificationChannel(
"service-subscription",
application.getText(R.string.service_subscription),
NotificationManager.IMPORTANCE_DEFAULT
)
)
)
}
}
fun startService() = ContextCompat.startForegroundService(
application, Intent(application, SagerConnection.serviceClass)
)
fun reloadService() =
application.sendBroadcast(Intent(Action.RELOAD).setPackage(application.packageName))
fun stopService() =
application.sendBroadcast(Intent(Action.CLOSE).setPackage(application.packageName))
var underlyingNetwork: Network? = null
}
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/SagerNet.kt | 3990248803 |
/*******************************************************************************
* *
* Copyright (C) 2017 by Max Lv <[email protected]> *
* Copyright (C) 2017 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
package io.nekohasekai.sagernet
import android.app.Activity
import android.content.Intent
import android.content.pm.ShortcutManager
import android.os.Build
import android.os.Bundle
import androidx.core.content.getSystemService
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat
import io.nekohasekai.sagernet.aidl.ISagerNetService
import io.nekohasekai.sagernet.bg.BaseService
import io.nekohasekai.sagernet.bg.SagerConnection
import io.nekohasekai.sagernet.database.DataStore
@Suppress("DEPRECATION")
class QuickToggleShortcut : Activity(), SagerConnection.Callback {
private val connection = SagerConnection(SagerConnection.CONNECTION_ID_SHORTCUT)
private var profileId = -1L
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (intent.action == Intent.ACTION_CREATE_SHORTCUT) {
setResult(
RESULT_OK, ShortcutManagerCompat.createShortcutResultIntent(
this,
ShortcutInfoCompat.Builder(this, "toggle")
.setIntent(
Intent(
this,
QuickToggleShortcut::class.java
).setAction(Intent.ACTION_MAIN)
)
.setIcon(
IconCompat.createWithResource(
this,
R.drawable.ic_qu_shadowsocks_launcher
)
)
.setShortLabel(getString(R.string.quick_toggle))
.build()
)
)
finish()
} else {
profileId = intent.getLongExtra("profile", -1L)
connection.connect(this, this)
if (Build.VERSION.SDK_INT >= 25) {
getSystemService<ShortcutManager>()!!.reportShortcutUsed(if (profileId >= 0) "shortcut-profile-$profileId" else "toggle")
}
}
}
override fun onServiceConnected(service: ISagerNetService) {
val state = BaseService.State.values()[service.state]
when {
state.canStop -> {
if (profileId == DataStore.selectedProxy || profileId == -1L) {
SagerNet.stopService()
} else {
DataStore.selectedProxy = profileId
SagerNet.reloadService()
}
}
state == BaseService.State.Stopped -> {
if (profileId >= 0L) DataStore.selectedProxy = profileId
SagerNet.startService()
}
}
finish()
}
override fun stateChanged(state: BaseService.State, profileName: String?, msg: String?) {}
override fun onDestroy() {
connection.disconnect(this)
super.onDestroy()
}
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/QuickToggleShortcut.kt | 3360289519 |
package io.nekohasekai.sagernet.bg
import android.Manifest
import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.content.pm.PackageManager
import android.net.ProxyInfo
import android.os.Build
import android.os.ParcelFileDescriptor
import android.os.PowerManager
import io.nekohasekai.sagernet.IPv6Mode
import io.nekohasekai.sagernet.Key
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.fmt.LOCALHOST
import io.nekohasekai.sagernet.fmt.hysteria.HysteriaBean
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.ui.VpnRequestActivity
import io.nekohasekai.sagernet.utils.Subnet
import moe.matsuri.nb4a.proxy.neko.needBypassRootUid
import android.net.VpnService as BaseVpnService
class VpnService : BaseVpnService(),
BaseService.Interface {
companion object {
const val PRIVATE_VLAN4_CLIENT = "172.19.0.1"
const val PRIVATE_VLAN4_ROUTER = "172.19.0.2"
const val FAKEDNS_VLAN4_CLIENT = "198.18.0.0"
const val PRIVATE_VLAN6_CLIENT = "fdfe:dcba:9876::1"
const val PRIVATE_VLAN6_ROUTER = "fdfe:dcba:9876::2"
}
var conn: ParcelFileDescriptor? = null
private var metered = false
override var upstreamInterfaceName: String? = null
override suspend fun startProcesses() {
DataStore.vpnService = this
super.startProcesses() // launch proxy instance
}
override var wakeLock: PowerManager.WakeLock? = null
@SuppressLint("WakelockTimeout")
override fun acquireWakeLock() {
wakeLock = SagerNet.power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "sagernet:vpn")
.apply { acquire() }
}
@Suppress("EXPERIMENTAL_API_USAGE")
override fun killProcesses() {
conn?.close()
conn = null
super.killProcesses()
}
override fun onBind(intent: Intent) = when (intent.action) {
SERVICE_INTERFACE -> super<BaseVpnService>.onBind(intent)
else -> super<BaseService.Interface>.onBind(intent)
}
override val data = BaseService.Data(this)
override val tag = "SagerNetVpnService"
override fun createNotification(profileName: String) =
ServiceNotification(this, profileName, "service-vpn")
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (DataStore.serviceMode == Key.MODE_VPN) {
if (prepare(this) != null) {
startActivity(
Intent(
this, VpnRequestActivity::class.java
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
} else return super<BaseService.Interface>.onStartCommand(intent, flags, startId)
}
stopRunner()
return Service.START_NOT_STICKY
}
inner class NullConnectionException : NullPointerException(),
BaseService.ExpectedException {
override fun getLocalizedMessage() = getString(R.string.reboot_required)
}
fun startVpn(tunOptionsJson: String, tunPlatformOptionsJson: String): Int {
// Logs.d(tunOptionsJson)
// Logs.d(tunPlatformOptionsJson)
// val tunOptions = JSONObject(tunOptionsJson)
// address & route & MTU ...... use NB4A GUI config
val builder = Builder().setConfigureIntent(SagerNet.configureIntent(this))
.setSession(getString(R.string.app_name))
.setMtu(DataStore.mtu)
val ipv6Mode = DataStore.ipv6Mode
// address
builder.addAddress(PRIVATE_VLAN4_CLIENT, 30)
if (ipv6Mode != IPv6Mode.DISABLE) {
builder.addAddress(PRIVATE_VLAN6_CLIENT, 126)
}
builder.addDnsServer(PRIVATE_VLAN4_ROUTER)
// route
if (DataStore.bypassLan) {
resources.getStringArray(R.array.bypass_private_route).forEach {
val subnet = Subnet.fromString(it)!!
builder.addRoute(subnet.address.hostAddress!!, subnet.prefixSize)
}
builder.addRoute(PRIVATE_VLAN4_ROUTER, 32)
builder.addRoute(FAKEDNS_VLAN4_CLIENT, 15)
// https://issuetracker.google.com/issues/149636790
if (ipv6Mode != IPv6Mode.DISABLE) {
builder.addRoute("2000::", 3)
}
} else {
builder.addRoute("0.0.0.0", 0)
if (ipv6Mode != IPv6Mode.DISABLE) {
builder.addRoute("::", 0)
}
}
updateUnderlyingNetwork(builder)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) builder.setMetered(metered)
// app route
val packageName = packageName
val proxyApps = DataStore.proxyApps
var bypass = DataStore.bypass
val workaroundSYSTEM = false /* DataStore.tunImplementation == TunImplementation.SYSTEM */
val needBypassRootUid = workaroundSYSTEM || data.proxy!!.config.trafficMap.values.any {
it[0].nekoBean?.needBypassRootUid() == true || it[0].hysteriaBean?.protocol == HysteriaBean.PROTOCOL_FAKETCP
}
if (proxyApps || needBypassRootUid) {
val individual = mutableSetOf<String>()
val allApps by lazy {
packageManager.getInstalledPackages(PackageManager.GET_PERMISSIONS).filter {
when (it.packageName) {
packageName -> false
"android" -> true
else -> it.requestedPermissions?.contains(Manifest.permission.INTERNET) == true
}
}.map {
it.packageName
}
}
if (proxyApps) {
individual.addAll(DataStore.individual.split('\n').filter { it.isNotBlank() })
if (bypass && needBypassRootUid) {
val individualNew = allApps.toMutableList()
individualNew.removeAll(individual)
individual.clear()
individual.addAll(individualNew)
bypass = false
}
} else {
individual.addAll(allApps)
bypass = false
}
val added = mutableListOf<String>()
individual.apply {
// Allow Matsuri itself using VPN.
remove(packageName)
if (!bypass) add(packageName)
}.forEach {
try {
if (bypass) {
builder.addDisallowedApplication(it)
} else {
builder.addAllowedApplication(it)
}
added.add(it)
} catch (ex: PackageManager.NameNotFoundException) {
Logs.w(ex)
}
}
if (bypass) {
Logs.d("Add bypass: ${added.joinToString(", ")}")
} else {
Logs.d("Add allow: ${added.joinToString(", ")}")
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && DataStore.appendHttpProxy &&
DataStore.inboundUsername.isNullOrEmpty() && DataStore.inboundPassword.isNullOrEmpty()
) {
builder.setHttpProxy(ProxyInfo.buildDirectProxy(LOCALHOST, DataStore.mixedPort))
}
metered = DataStore.meteredNetwork
if (Build.VERSION.SDK_INT >= 29) builder.setMetered(metered)
conn = builder.establish() ?: throw NullConnectionException()
return conn!!.fd
}
fun updateUnderlyingNetwork(builder: Builder? = null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
SagerNet.underlyingNetwork?.let {
builder?.setUnderlyingNetworks(arrayOf(SagerNet.underlyingNetwork))
?: setUnderlyingNetworks(arrayOf(SagerNet.underlyingNetwork))
}
}
}
override fun onRevoke() = stopRunner()
override fun onDestroy() {
DataStore.vpnService = null
super.onDestroy()
data.binder.close()
}
} | nacs/app/src/main/java/io/nekohasekai/sagernet/bg/VpnService.kt | 1639686622 |
package io.nekohasekai.sagernet.bg
import android.system.ErrnoException
import android.system.Os
import android.system.OsConstants
import android.text.TextUtils
import io.nekohasekai.sagernet.ktx.Logs
import java.io.File
import java.io.IOException
object Executable {
private val EXECUTABLES = setOf(
"libtrojan.so",
"libtrojan-go.so",
"libnaive.so",
"libtuic.so",
"libhysteria.so"
)
fun killAll(alsoKillBg: Boolean = false) {
for (process in File("/proc").listFiles { _, name -> TextUtils.isDigitsOnly(name) }
?: return) {
val exe = File(try {
File(process, "cmdline").inputStream().bufferedReader().use {
it.readText()
}
} catch (_: IOException) {
continue
}.split(Character.MIN_VALUE, limit = 2).first())
if (EXECUTABLES.contains(exe.name) || (alsoKillBg && exe.name.endsWith(":bg"))) try {
Os.kill(process.name.toInt(), OsConstants.SIGKILL)
Logs.w("SIGKILL ${exe.name} (${process.name}) succeed")
} catch (e: ErrnoException) {
if (e.errno != OsConstants.ESRCH) {
Logs.w("SIGKILL ${exe.absolutePath} (${process.name}) failed")
Logs.w(e)
}
}
}
}
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/bg/Executable.kt | 783851016 |
package io.nekohasekai.sagernet.bg
import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.os.PowerManager
import io.nekohasekai.sagernet.SagerNet
class ProxyService : Service(), BaseService.Interface {
override val data = BaseService.Data(this)
override val tag: String get() = "SagerNetProxyService"
override fun createNotification(profileName: String): ServiceNotification =
ServiceNotification(this, profileName, "service-proxy", true)
override var wakeLock: PowerManager.WakeLock? = null
override var upstreamInterfaceName: String? = null
@SuppressLint("WakelockTimeout")
override fun acquireWakeLock() {
wakeLock = SagerNet.power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "sagernet:proxy")
.apply { acquire() }
}
override fun onBind(intent: Intent) = super.onBind(intent)
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int =
super<BaseService.Interface>.onStartCommand(intent, flags, startId)
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/bg/ProxyService.kt | 1797744901 |
package io.nekohasekai.sagernet.bg.proto
import io.nekohasekai.sagernet.BuildConfig
import io.nekohasekai.sagernet.bg.BaseService
import io.nekohasekai.sagernet.bg.ServiceNotification
import io.nekohasekai.sagernet.database.ProxyEntity
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.ktx.runOnDefaultDispatcher
import kotlinx.coroutines.runBlocking
import libcore.Libcore
import moe.matsuri.nb4a.net.LocalResolverImpl
import moe.matsuri.nb4a.utils.JavaUtil
class ProxyInstance(profile: ProxyEntity, var service: BaseService.Interface? = null) :
BoxInstance(profile) {
var notTmp = true
var lastSelectorGroupId = -1L
var displayProfileName = ServiceNotification.genTitle(profile)
// for TrafficLooper
var looper: TrafficLooper? = null
override fun buildConfig() {
super.buildConfig()
lastSelectorGroupId = super.config.selectorGroupId
//
if (notTmp) Logs.d(config.config)
if (notTmp && BuildConfig.DEBUG) Logs.d(JavaUtil.gson.toJson(config.trafficMap))
}
// only use this in temporary instance
fun buildConfigTmp() {
notTmp = false
buildConfig()
}
override suspend fun init() {
super.init()
pluginConfigs.forEach { (_, plugin) ->
val (_, content) = plugin
Logs.d(content)
}
}
override suspend fun loadConfig() {
Libcore.registerLocalDNSTransport(LocalResolverImpl)
super.loadConfig()
}
override fun launch() {
box.setAsMain()
super.launch() // start box
runOnDefaultDispatcher {
looper = service?.let { TrafficLooper(it.data, this) }
looper?.start()
}
}
override fun close() {
Libcore.registerLocalDNSTransport(null)
super.close()
runBlocking {
looper?.stop()
looper = null
}
}
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/bg/proto/ProxyInstance.kt | 2253333696 |
package io.nekohasekai.sagernet.bg.proto
import android.os.SystemClock
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.bg.AbstractInstance
import io.nekohasekai.sagernet.bg.GuardedProcessPool
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.ProxyEntity
import io.nekohasekai.sagernet.fmt.ConfigBuildResult
import io.nekohasekai.sagernet.fmt.buildConfig
import io.nekohasekai.sagernet.fmt.hysteria.HysteriaBean
import io.nekohasekai.sagernet.fmt.hysteria.buildHysteria1Config
import io.nekohasekai.sagernet.fmt.mieru.MieruBean
import io.nekohasekai.sagernet.fmt.mieru.buildMieruConfig
import io.nekohasekai.sagernet.fmt.naive.NaiveBean
import io.nekohasekai.sagernet.fmt.naive.buildNaiveConfig
import io.nekohasekai.sagernet.fmt.trojan_go.TrojanGoBean
import io.nekohasekai.sagernet.fmt.trojan_go.buildTrojanGoConfig
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ktx.forEach
import io.nekohasekai.sagernet.plugin.PluginManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.plus
import libcore.BoxInstance
import libcore.Libcore
import moe.matsuri.nb4a.plugin.NekoPluginManager
import moe.matsuri.nb4a.proxy.neko.NekoBean
import moe.matsuri.nb4a.proxy.neko.NekoJSInterface
import moe.matsuri.nb4a.proxy.neko.updateAllConfig
import org.json.JSONObject
import java.io.File
abstract class BoxInstance(
val profile: ProxyEntity
) : AbstractInstance {
lateinit var config: ConfigBuildResult
lateinit var box: BoxInstance
val pluginPath = hashMapOf<String, PluginManager.InitResult>()
val pluginConfigs = hashMapOf<Int, Pair<Int, String>>()
val externalInstances = hashMapOf<Int, AbstractInstance>()
open lateinit var processes: GuardedProcessPool
private var cacheFiles = ArrayList<File>()
fun isInitialized(): Boolean {
return ::config.isInitialized && ::box.isInitialized
}
protected fun initPlugin(name: String): PluginManager.InitResult {
return pluginPath.getOrPut(name) { PluginManager.init(name)!! }
}
protected open fun buildConfig() {
config = buildConfig(profile)
}
protected open suspend fun loadConfig() {
NekoJSInterface.Default.destroyAllJsi()
box = Libcore.newSingBoxInstance(config.config)
}
open suspend fun init() {
buildConfig()
for ((chain) in config.externalIndex) {
chain.entries.forEachIndexed { index, (port, profile) ->
when (val bean = profile.requireBean()) {
is TrojanGoBean -> {
initPlugin("trojan-go-plugin")
pluginConfigs[port] = profile.type to bean.buildTrojanGoConfig(port)
}
is MieruBean -> {
initPlugin("mieru-plugin")
pluginConfigs[port] = profile.type to bean.buildMieruConfig(port)
}
is NaiveBean -> {
initPlugin("naive-plugin")
pluginConfigs[port] = profile.type to bean.buildNaiveConfig(port)
}
is HysteriaBean -> {
initPlugin("hysteria-plugin")
pluginConfigs[port] = profile.type to bean.buildHysteria1Config(port) {
File(
app.cacheDir, "hysteria_" + SystemClock.elapsedRealtime() + ".ca"
).apply {
parentFile?.mkdirs()
cacheFiles.add(this)
}
}
}
is NekoBean -> {
// check if plugin binary can be loaded
initPlugin(bean.plgId)
// build config and check if succeed
bean.updateAllConfig(port)
if (bean.allConfig == null) {
throw NekoPluginManager.PluginInternalException(bean.protocolId)
}
}
}
}
}
loadConfig()
}
override fun launch() {
// TODO move, this is not box
val cacheDir = File(SagerNet.application.cacheDir, "tmpcfg")
cacheDir.mkdirs()
for ((chain) in config.externalIndex) {
chain.entries.forEachIndexed { index, (port, profile) ->
val bean = profile.requireBean()
val needChain = index != chain.size - 1
val (profileType, config) = pluginConfigs[port] ?: (0 to "")
when {
externalInstances.containsKey(port) -> {
externalInstances[port]!!.launch()
}
bean is TrojanGoBean -> {
val configFile = File(
cacheDir, "trojan_go_" + SystemClock.elapsedRealtime() + ".json"
)
configFile.parentFile?.mkdirs()
configFile.writeText(config)
cacheFiles.add(configFile)
val commands = mutableListOf(
initPlugin("trojan-go-plugin").path, "-config", configFile.absolutePath
)
processes.start(commands)
}
bean is MieruBean -> {
val configFile = File(
cacheDir, "mieru_" + SystemClock.elapsedRealtime() + ".json"
)
configFile.parentFile?.mkdirs()
configFile.writeText(config)
cacheFiles.add(configFile)
val envMap = mutableMapOf<String, String>()
envMap["MIERU_CONFIG_JSON_FILE"] = configFile.absolutePath
val commands = mutableListOf(
initPlugin("mieru-plugin").path, "run",
)
processes.start(commands, envMap)
}
bean is NaiveBean -> {
val configFile = File(
cacheDir, "naive_" + SystemClock.elapsedRealtime() + ".json"
)
configFile.parentFile?.mkdirs()
configFile.writeText(config)
cacheFiles.add(configFile)
val envMap = mutableMapOf<String, String>()
val commands = mutableListOf(
initPlugin("naive-plugin").path, configFile.absolutePath
)
processes.start(commands, envMap)
}
bean is HysteriaBean -> {
val configFile = File(
cacheDir, "hysteria_" + SystemClock.elapsedRealtime() + ".json"
)
configFile.parentFile?.mkdirs()
configFile.writeText(config)
cacheFiles.add(configFile)
val commands = mutableListOf(
initPlugin("hysteria-plugin").path,
"--no-check",
"--config",
configFile.absolutePath,
"--log-level",
if (DataStore.logLevel > 0) "trace" else "warn",
"client"
)
if (bean.protocol == HysteriaBean.PROTOCOL_FAKETCP) {
commands.addAll(0, listOf("su", "-c"))
}
processes.start(commands)
}
bean is NekoBean -> {
// config built from JS
val nekoRunConfigs = bean.allConfig.optJSONArray("nekoRunConfigs")
val configs = mutableMapOf<String, String>()
nekoRunConfigs?.forEach { _, any ->
any as JSONObject
val name = any.getString("name")
val configFile = File(cacheDir, name)
configFile.parentFile?.mkdirs()
val content = any.getString("content")
configFile.writeText(content)
cacheFiles.add(configFile)
configs[name] = configFile.absolutePath
Logs.d(name + "\n\n" + content)
}
val nekoCommands = bean.allConfig.getJSONArray("nekoCommands")
val commands = mutableListOf<String>()
nekoCommands.forEach { _, any ->
if (any is String) {
if (configs.containsKey(any)) {
commands.add(configs[any]!!)
} else if (any == "%exe%") {
commands.add(initPlugin(bean.plgId).path)
} else {
commands.add(any)
}
}
}
processes.start(commands)
}
}
}
}
box.start()
}
@Suppress("EXPERIMENTAL_API_USAGE")
override fun close() {
for (instance in externalInstances.values) {
runCatching {
instance.close()
}
}
cacheFiles.removeAll { it.delete(); true }
if (::processes.isInitialized) processes.close(GlobalScope + Dispatchers.IO)
if (::box.isInitialized) {
box.close()
}
}
} | nacs/app/src/main/java/io/nekohasekai/sagernet/bg/proto/BoxInstance.kt | 4096663092 |
package io.nekohasekai.sagernet.bg.proto
class TrafficUpdater(
private val box: libcore.BoxInstance,
val items: List<TrafficLooperData>, // contain "bypass"
) {
class TrafficLooperData(
// Don't associate proxyEntity
var tag: String,
var tx: Long = 0,
var rx: Long = 0,
var txBase: Long = 0,
var rxBase: Long = 0,
var txRate: Long = 0,
var rxRate: Long = 0,
var lastUpdate: Long = 0,
var ignore: Boolean = false,
)
private fun updateOne(item: TrafficLooperData): TrafficLooperData {
// last update
val now = System.currentTimeMillis()
val interval = now - item.lastUpdate
item.lastUpdate = now
if (interval <= 0) return item.apply {
rxRate = 0
txRate = 0
}
// query
val tx = box.queryStats(item.tag, "uplink")
val rx = box.queryStats(item.tag, "downlink")
// add diff
item.rx += rx
item.tx += tx
item.rxRate = rx * 1000 / interval
item.txRate = tx * 1000 / interval
// return diff
return TrafficLooperData(
tag = item.tag,
rx = rx,
tx = tx,
rxRate = item.rxRate,
txRate = item.txRate,
)
}
suspend fun updateAll() {
val updated = mutableMapOf<String, TrafficLooperData>() // diffs
items.forEach { item ->
if (item.ignore) return@forEach
var diff = updated[item.tag]
// query a tag only once
if (diff == null) {
diff = updateOne(item)
updated[item.tag] = diff
} else {
item.rx += diff.rx
item.tx += diff.tx
item.rxRate = diff.rxRate
item.txRate = diff.txRate
}
}
// Logs.d(JavaUtil.gson.toJson(items))
// Logs.d(JavaUtil.gson.toJson(updated))
}
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/bg/proto/TrafficUpdater.kt | 3726871401 |
package io.nekohasekai.sagernet.bg.proto
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.ProxyEntity
class UrlTest {
val link = DataStore.connectionTestURL
val timeout = 3000
suspend fun doTest(profile: ProxyEntity): Int {
return TestInstance(profile, link, timeout).doTest()
}
} | nacs/app/src/main/java/io/nekohasekai/sagernet/bg/proto/UrlTest.kt | 2643707126 |
package io.nekohasekai.sagernet.bg.proto
import io.nekohasekai.sagernet.BuildConfig
import io.nekohasekai.sagernet.bg.GuardedProcessPool
import io.nekohasekai.sagernet.database.ProxyEntity
import io.nekohasekai.sagernet.fmt.buildConfig
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.ktx.runOnDefaultDispatcher
import io.nekohasekai.sagernet.ktx.tryResume
import io.nekohasekai.sagernet.ktx.tryResumeWithException
import kotlinx.coroutines.delay
import libcore.Libcore
import kotlin.coroutines.suspendCoroutine
class TestInstance(profile: ProxyEntity, val link: String, val timeout: Int) :
BoxInstance(profile) {
suspend fun doTest(): Int {
return suspendCoroutine { c ->
processes = GuardedProcessPool {
Logs.w(it)
c.tryResumeWithException(it)
}
runOnDefaultDispatcher {
use {
try {
init()
launch()
if (processes.processCount > 0) {
// wait for plugin start
delay(500)
}
c.tryResume(Libcore.urlTest(box, link, timeout))
} catch (e: Exception) {
c.tryResumeWithException(e)
}
}
}
}
}
override fun buildConfig() {
config = buildConfig(profile, true)
}
override suspend fun loadConfig() {
// don't call destroyAllJsi here
if (BuildConfig.DEBUG) Logs.d(config.config)
box = Libcore.newSingBoxInstance(config.config)
box.forTest = true
}
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/bg/proto/TestInstance.kt | 3937998860 |
package io.nekohasekai.sagernet.bg.proto
import io.nekohasekai.sagernet.aidl.SpeedDisplayData
import io.nekohasekai.sagernet.aidl.TrafficData
import io.nekohasekai.sagernet.bg.BaseService
import io.nekohasekai.sagernet.bg.SagerConnection
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.ProfileManager
import io.nekohasekai.sagernet.fmt.TAG_BYPASS
import io.nekohasekai.sagernet.fmt.TAG_PROXY
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.ktx.runOnDefaultDispatcher
import kotlinx.coroutines.*
class TrafficLooper
(
val data: BaseService.Data, private val sc: CoroutineScope
) {
private var job: Job? = null
private val idMap = mutableMapOf<Long, TrafficUpdater.TrafficLooperData>() // id to 1 data
private val tagMap = mutableMapOf<String, TrafficUpdater.TrafficLooperData>() // tag to 1 data
suspend fun stop() {
job?.cancel()
// finally traffic post
if (!DataStore.profileTrafficStatistics) return
val traffic = mutableMapOf<Long, TrafficData>()
data.proxy?.config?.trafficMap?.forEach { (_, ents) ->
for (ent in ents) {
val item = idMap[ent.id] ?: return@forEach
ent.rx = item.rx
ent.tx = item.tx
ProfileManager.updateProfile(ent) // update DB
traffic[ent.id] = TrafficData(
id = ent.id,
rx = ent.rx,
tx = ent.tx,
)
}
}
data.binder.broadcast { b ->
for (t in traffic) {
b.cbTrafficUpdate(t.value)
}
}
Logs.d("finally traffic post done")
}
fun start() {
job = sc.launch { loop() }
}
var selectorNowId = -114514L
var selectorNowFakeTag = ""
fun selectMain(id: Long) {
Logs.d("select traffic count $TAG_PROXY to $id, old id is $selectorNowId")
val oldData = idMap[selectorNowId]
val newData = idMap[id] ?: return
oldData?.apply {
tag = selectorNowFakeTag
ignore = true
// post traffic when switch
if (DataStore.profileTrafficStatistics) {
data.proxy?.config?.trafficMap?.get(tag)?.firstOrNull()?.let {
it.rx = rx
it.tx = tx
runOnDefaultDispatcher {
ProfileManager.updateProfile(it) // update DB
}
}
}
}
selectorNowFakeTag = newData.tag
selectorNowId = id
newData.apply {
tag = TAG_PROXY
ignore = false
}
}
private suspend fun loop() {
val delayMs = DataStore.speedInterval.toLong()
val showDirectSpeed = DataStore.showDirectSpeed
val profileTrafficStatistics = DataStore.profileTrafficStatistics
if (delayMs == 0L) return
var trafficUpdater: TrafficUpdater? = null
var proxy: ProxyInstance?
// for display
val itemBypass = TrafficUpdater.TrafficLooperData(tag = TAG_BYPASS)
while (sc.isActive) {
proxy = data.proxy
if (proxy == null) {
delay(delayMs)
continue
}
if (trafficUpdater == null) {
if (!proxy.isInitialized()) continue
idMap.clear()
idMap[-1] = itemBypass
//
val tags = hashSetOf(TAG_PROXY, TAG_BYPASS)
proxy.config.trafficMap.forEach { (tag, ents) ->
tags.add(tag)
for (ent in ents) {
val item = TrafficUpdater.TrafficLooperData(
tag = tag,
rx = ent.rx,
tx = ent.tx,
rxBase = ent.rx,
txBase = ent.tx,
ignore = proxy.config.selectorGroupId >= 0L,
)
idMap[ent.id] = item
tagMap[tag] = item
Logs.d("traffic count $tag to ${ent.id}")
}
}
if (proxy.config.selectorGroupId >= 0L) {
selectMain(proxy.config.mainEntId)
}
//
trafficUpdater = TrafficUpdater(
box = proxy.box, items = idMap.values.toList()
)
proxy.box.setV2rayStats(tags.joinToString("\n"))
}
trafficUpdater.updateAll()
if (!sc.isActive) return
// add all non-bypass to "main"
var mainTxRate = 0L
var mainRxRate = 0L
var mainTx = 0L
var mainRx = 0L
tagMap.forEach { (_, it) ->
if (!it.ignore) {
mainTxRate += it.txRate
mainRxRate += it.rxRate
}
mainTx += it.tx - it.txBase
mainRx += it.rx - it.rxBase
}
// speed
val speed = SpeedDisplayData(
mainTxRate,
mainRxRate,
if (showDirectSpeed) itemBypass.txRate else 0L,
if (showDirectSpeed) itemBypass.rxRate else 0L,
mainTx,
mainRx
)
// broadcast (MainActivity)
if (data.state == BaseService.State.Connected
&& data.binder.callbackIdMap.containsValue(SagerConnection.CONNECTION_ID_MAIN_ACTIVITY_FOREGROUND)
) {
data.binder.broadcast { b ->
if (data.binder.callbackIdMap[b] == SagerConnection.CONNECTION_ID_MAIN_ACTIVITY_FOREGROUND) {
b.cbSpeedUpdate(speed)
if (profileTrafficStatistics) {
idMap.forEach { (id, item) ->
b.cbTrafficUpdate(
TrafficData(id = id, rx = item.rx, tx = item.tx) // display
)
}
}
}
}
}
// ServiceNotification
data.notification?.apply {
if (listenPostSpeed) postNotificationSpeedUpdate(speed)
}
delay(delayMs)
}
}
} | nacs/app/src/main/java/io/nekohasekai/sagernet/bg/proto/TrafficLooper.kt | 3143062312 |
package io.nekohasekai.sagernet.bg
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.*
import android.widget.Toast
import io.nekohasekai.sagernet.Action
import io.nekohasekai.sagernet.BootReceiver
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.aidl.ISagerNetService
import io.nekohasekai.sagernet.aidl.ISagerNetServiceCallback
import io.nekohasekai.sagernet.bg.proto.ProxyInstance
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.SagerDatabase
import io.nekohasekai.sagernet.ktx.*
import io.nekohasekai.sagernet.plugin.PluginManager
import io.nekohasekai.sagernet.utils.DefaultNetworkListener
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import libcore.Libcore
import moe.matsuri.nb4a.Protocols
import moe.matsuri.nb4a.utils.LibcoreUtil
import moe.matsuri.nb4a.utils.Util
import java.net.UnknownHostException
class BaseService {
enum class State(
val canStop: Boolean = false,
val started: Boolean = false,
val connected: Boolean = false,
) {
/**
* Idle state is only used by UI and will never be returned by BaseService.
*/
Idle, Connecting(true, true, false), Connected(true, true, true), Stopping, Stopped,
}
interface ExpectedException
class Data internal constructor(private val service: Interface) {
var state = State.Stopped
var proxy: ProxyInstance? = null
var notification: ServiceNotification? = null
val receiver = broadcastReceiver { ctx, intent ->
when (intent.action) {
Intent.ACTION_SHUTDOWN -> service.persistStats()
Action.RELOAD -> service.reload()
// Action.SWITCH_WAKE_LOCK -> runOnDefaultDispatcher { service.switchWakeLock() }
PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (SagerNet.power.isDeviceIdleMode) {
proxy?.box?.sleep()
} else {
proxy?.box?.wake()
}
}
}
Action.RESET_UPSTREAM_CONNECTIONS -> runOnDefaultDispatcher {
LibcoreUtil.resetAllConnections(true)
runOnMainDispatcher {
Util.collapseStatusBar(ctx)
Toast.makeText(ctx, "Reset upstream connections done", Toast.LENGTH_SHORT)
.show()
}
}
else -> service.stopRunner()
}
}
var closeReceiverRegistered = false
val binder = Binder(this)
var connectingJob: Job? = null
fun changeState(s: State, msg: String? = null) {
if (state == s && msg == null) return
state = s
DataStore.serviceState = s
binder.stateChanged(s, msg)
}
}
class Binder(private var data: Data? = null) : ISagerNetService.Stub(), CoroutineScope,
AutoCloseable {
private val callbacks = object : RemoteCallbackList<ISagerNetServiceCallback>() {
override fun onCallbackDied(callback: ISagerNetServiceCallback?, cookie: Any?) {
super.onCallbackDied(callback, cookie)
}
}
val callbackIdMap = mutableMapOf<ISagerNetServiceCallback, Int>()
override val coroutineContext = Dispatchers.Main.immediate + Job()
override fun getState(): Int = (data?.state ?: State.Idle).ordinal
override fun getProfileName(): String = data?.proxy?.displayProfileName ?: "Idle"
override fun registerCallback(cb: ISagerNetServiceCallback, id: Int) {
if (!callbackIdMap.contains(cb)) {
callbacks.register(cb)
}
callbackIdMap[cb] = id
}
private val broadcastMutex = Mutex()
suspend fun broadcast(work: (ISagerNetServiceCallback) -> Unit) {
broadcastMutex.withLock {
val count = callbacks.beginBroadcast()
try {
repeat(count) {
try {
work(callbacks.getBroadcastItem(it))
} catch (_: RemoteException) {
} catch (_: Exception) {
}
}
} finally {
callbacks.finishBroadcast()
}
}
}
override fun unregisterCallback(cb: ISagerNetServiceCallback) {
callbackIdMap.remove(cb)
callbacks.unregister(cb)
}
override fun urlTest(): Int {
if (data?.proxy?.box == null) {
error("core not started")
}
try {
return Libcore.urlTest(
data!!.proxy!!.box, DataStore.connectionTestURL, 3000
)
} catch (e: Exception) {
error(Protocols.genFriendlyMsg(e.readableMessage))
}
}
fun stateChanged(s: State, msg: String?) = launch {
val profileName = profileName
broadcast { it.stateChanged(s.ordinal, profileName, msg) }
}
fun missingPlugin(pluginName: String) = launch {
val profileName = profileName
broadcast { it.missingPlugin(profileName, pluginName) }
}
override fun close() {
callbacks.kill()
cancel()
data = null
}
}
interface Interface {
val data: Data
val tag: String
fun createNotification(profileName: String): ServiceNotification
fun onBind(intent: Intent): IBinder? =
if (intent.action == Action.SERVICE) data.binder else null
fun reload() {
if (DataStore.selectedProxy == 0L) {
stopRunner(false, (this as Context).getString(R.string.profile_empty))
}
if (canReloadSelector()) {
val ent = SagerDatabase.proxyDao.getById(DataStore.selectedProxy)
val tag = data.proxy!!.config.profileTagMap[ent?.id] ?: ""
if (tag.isNotBlank() && ent != null) {
// select from GUI
data.proxy!!.box.selectOutbound(tag)
// or select from webui
// => selector_OnProxySelected
}
return
}
val s = data.state
when {
s == State.Stopped -> startRunner()
s.canStop -> stopRunner(true)
else -> Logs.w("Illegal state $s when invoking use")
}
}
fun canReloadSelector(): Boolean {
if ((data.proxy?.config?.selectorGroupId ?: -1L) < 0) return false
val ent = SagerDatabase.proxyDao.getById(DataStore.selectedProxy) ?: return false
val tmpBox = ProxyInstance(ent)
tmpBox.buildConfigTmp()
if (tmpBox.lastSelectorGroupId == data.proxy?.lastSelectorGroupId) {
return true
}
return false
}
suspend fun startProcesses() {
data.proxy!!.launch()
}
fun startRunner() {
this as Context
if (Build.VERSION.SDK_INT >= 26) startForegroundService(Intent(this, javaClass))
else startService(Intent(this, javaClass))
}
fun killProcesses() {
data.proxy?.close()
wakeLock?.apply {
release()
wakeLock = null
}
runOnDefaultDispatcher {
DefaultNetworkListener.stop(this)
}
}
fun stopRunner(restart: Boolean = false, msg: String? = null) {
DataStore.baseService = null
DataStore.vpnService = null
if (data.state == State.Stopping) return
data.notification?.destroy()
data.notification = null
this as Service
data.changeState(State.Stopping)
runOnMainDispatcher {
data.connectingJob?.cancelAndJoin() // ensure stop connecting first
// we use a coroutineScope here to allow clean-up in parallel
coroutineScope {
killProcesses()
val data = data
if (data.closeReceiverRegistered) {
unregisterReceiver(data.receiver)
data.closeReceiverRegistered = false
}
data.proxy = null
}
// change the state
data.changeState(State.Stopped, msg)
// stop the service if nothing has bound to it
if (restart) startRunner() else {
stopSelf()
}
}
}
open fun persistStats() {
// TODO NEW save app stats?
}
// networks
var upstreamInterfaceName: String?
suspend fun preInit() {
DefaultNetworkListener.start(this) {
SagerNet.connectivity.getLinkProperties(it)?.also { link ->
SagerNet.underlyingNetwork = it
DataStore.vpnService?.updateUnderlyingNetwork()
//
val oldName = upstreamInterfaceName
if (oldName != link.interfaceName) {
upstreamInterfaceName = link.interfaceName
}
if (oldName != null && upstreamInterfaceName != null && oldName != upstreamInterfaceName) {
Logs.d("Network changed: $oldName -> $upstreamInterfaceName")
LibcoreUtil.resetAllConnections(true)
}
}
}
}
var wakeLock: PowerManager.WakeLock?
fun acquireWakeLock()
suspend fun switchWakeLock() {
wakeLock?.apply {
release()
wakeLock = null
data.notification?.postNotificationWakeLockStatus(false)
} ?: apply {
acquireWakeLock()
data.notification?.postNotificationWakeLockStatus(true)
}
}
suspend fun lateInit() {
wakeLock?.apply {
release()
wakeLock = null
}
if (DataStore.acquireWakeLock) {
acquireWakeLock()
data.notification?.postNotificationWakeLockStatus(true)
} else {
data.notification?.postNotificationWakeLockStatus(false)
}
}
fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
DataStore.baseService = this
val data = data
if (data.state != State.Stopped) return Service.START_NOT_STICKY
val profile = SagerDatabase.proxyDao.getById(DataStore.selectedProxy)
this as Context
if (profile == null) { // gracefully shutdown: https://stackoverflow.com/q/47337857/2245107
data.notification = createNotification("")
stopRunner(false, getString(R.string.profile_empty))
return Service.START_NOT_STICKY
}
val proxy = ProxyInstance(profile, this)
data.proxy = proxy
BootReceiver.enabled = DataStore.persistAcrossReboot
if (!data.closeReceiverRegistered) {
registerReceiver(data.receiver, IntentFilter().apply {
addAction(Action.RELOAD)
addAction(Intent.ACTION_SHUTDOWN)
addAction(Action.CLOSE)
// addAction(Action.SWITCH_WAKE_LOCK)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED)
}
addAction(Action.RESET_UPSTREAM_CONNECTIONS)
}, "$packageName.SERVICE", null)
data.closeReceiverRegistered = true
}
data.changeState(State.Connecting)
runOnMainDispatcher {
try {
data.notification = createNotification(ServiceNotification.genTitle(profile))
Executable.killAll() // clean up old processes
preInit()
proxy.init()
DataStore.currentProfile = profile.id
proxy.processes = GuardedProcessPool {
Logs.w(it)
stopRunner(false, it.readableMessage)
}
startProcesses()
data.changeState(State.Connected)
lateInit()
} catch (_: CancellationException) { // if the job was cancelled, it is canceller's responsibility to call stopRunner
} catch (_: UnknownHostException) {
stopRunner(false, getString(R.string.invalid_server))
} catch (e: PluginManager.PluginNotFoundException) {
Toast.makeText(this@Interface, e.readableMessage, Toast.LENGTH_SHORT).show()
Logs.w(e)
data.binder.missingPlugin(e.plugin)
stopRunner(false, null)
} catch (exc: Throwable) {
if (exc.javaClass.name.endsWith("proxyerror")) {
// error from golang
Logs.w(exc.readableMessage)
} else {
Logs.w(exc)
}
stopRunner(
false, "${getString(R.string.service_failed)}: ${exc.readableMessage}"
)
} finally {
data.connectingJob = null
}
}
return Service.START_NOT_STICKY
}
}
} | nacs/app/src/main/java/io/nekohasekai/sagernet/bg/BaseService.kt | 3865345289 |
package io.nekohasekai.sagernet.bg
import android.content.Context
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.work.CoroutineWorker
import androidx.work.ExistingPeriodicWorkPolicy.UPDATE
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkerParameters
import androidx.work.multiprocess.RemoteWorkManager
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.SagerDatabase
import io.nekohasekai.sagernet.group.GroupUpdater
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.ktx.app
import java.util.concurrent.TimeUnit
object SubscriptionUpdater {
private const val WORK_NAME = "SubscriptionUpdater"
suspend fun reconfigureUpdater() {
RemoteWorkManager.getInstance(app).cancelUniqueWork(WORK_NAME)
val subscriptions = SagerDatabase.groupDao.subscriptions()
.filter { it.subscription!!.autoUpdate }
if (subscriptions.isEmpty()) return
// PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS
var minDelay =
subscriptions.minByOrNull { it.subscription!!.autoUpdateDelay }!!.subscription!!.autoUpdateDelay.toLong()
val now = System.currentTimeMillis() / 1000L
var minInitDelay =
subscriptions.minOf { now - it.subscription!!.lastUpdated - (minDelay * 60) }
if (minDelay < 15) minDelay = 15
if (minInitDelay > 60) minInitDelay = 60
// main process
RemoteWorkManager.getInstance(app).enqueueUniquePeriodicWork(
WORK_NAME,
UPDATE,
PeriodicWorkRequest.Builder(UpdateTask::class.java, minDelay, TimeUnit.MINUTES)
.apply {
if (minInitDelay > 0) setInitialDelay(minInitDelay, TimeUnit.SECONDS)
}
.build()
)
}
class UpdateTask(
appContext: Context, params: WorkerParameters
) : CoroutineWorker(appContext, params) {
val nm = NotificationManagerCompat.from(applicationContext)
val notification = NotificationCompat.Builder(applicationContext, "service-subscription")
.setWhen(0)
.setTicker(applicationContext.getString(R.string.forward_success))
.setContentTitle(applicationContext.getString(R.string.subscription_update))
.setSmallIcon(R.drawable.ic_service_active)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
override suspend fun doWork(): Result {
var subscriptions =
SagerDatabase.groupDao.subscriptions().filter { it.subscription!!.autoUpdate }
if (!DataStore.serviceState.connected) {
Logs.d("work: not connected")
subscriptions = subscriptions.filter { !it.subscription!!.updateWhenConnectedOnly }
}
if (subscriptions.isNotEmpty()) for (profile in subscriptions) {
val subscription = profile.subscription!!
if (((System.currentTimeMillis() / 1000).toInt() - subscription.lastUpdated) < subscription.autoUpdateDelay * 60) {
Logs.d("work: not updating " + profile.displayName())
continue
}
Logs.d("work: updating " + profile.displayName())
notification.setContentText(
applicationContext.getString(
R.string.subscription_update_message, profile.displayName()
)
)
nm.notify(2, notification.build())
GroupUpdater.executeUpdate(profile, false)
}
nm.cancel(2)
return Result.success()
}
}
} | nacs/app/src/main/java/io/nekohasekai/sagernet/bg/SubscriptionUpdater.kt | 675422013 |
package io.nekohasekai.sagernet.bg
import android.os.Build
import android.os.SystemClock
import android.system.ErrnoException
import android.system.Os
import android.system.OsConstants
import androidx.annotation.MainThread
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.utils.Commandline
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import libcore.Libcore
import java.io.File
import java.io.IOException
import java.io.InputStream
import kotlin.concurrent.thread
class GuardedProcessPool(private val onFatal: suspend (IOException) -> Unit) : CoroutineScope {
companion object {
private val pid by lazy {
Class.forName("java.lang.ProcessManager\$ProcessImpl").getDeclaredField("pid")
.apply { isAccessible = true }
}
}
private inner class Guard(
private val cmd: List<String>,
private val env: Map<String, String> = mapOf()
) {
private lateinit var process: Process
private fun streamLogger(input: InputStream, logger: (String) -> Unit) = try {
input.bufferedReader().forEachLine(logger)
} catch (_: IOException) {
} // ignore
fun start() {
process = ProcessBuilder(cmd).directory(SagerNet.application.noBackupFilesDir).apply {
environment().putAll(env)
}.start()
}
@DelicateCoroutinesApi
suspend fun looper(onRestartCallback: (suspend () -> Unit)?) {
var running = true
val cmdName = File(cmd.first()).nameWithoutExtension
val exitChannel = Channel<Int>()
try {
while (true) {
thread(name = "stderr-$cmdName") {
streamLogger(process.errorStream) { Libcore.nekoLogPrintln("[$cmdName] $it") }
}
thread(name = "stdout-$cmdName") {
streamLogger(process.inputStream) { Libcore.nekoLogPrintln("[$cmdName] $it") }
// this thread also acts as a daemon thread for waitFor
runBlocking { exitChannel.send(process.waitFor()) }
}
val startTime = SystemClock.elapsedRealtime()
val exitCode = exitChannel.receive()
running = false
when {
SystemClock.elapsedRealtime() - startTime < 1000 -> throw IOException(
"$cmdName exits too fast (exit code: $exitCode)"
)
exitCode == 128 + OsConstants.SIGKILL -> Logs.w("$cmdName was killed")
else -> Logs.w(IOException("$cmdName unexpectedly exits with code $exitCode"))
}
Logs.i("restart process: ${Commandline.toString(cmd)} (last exit code: $exitCode)")
start()
running = true
onRestartCallback?.invoke()
}
} catch (e: IOException) {
Logs.w("error occurred. stop guard: ${Commandline.toString(cmd)}")
GlobalScope.launch(Dispatchers.Main) { onFatal(e) }
} finally {
if (running) withContext(NonCancellable) { // clean-up cannot be cancelled
if (Build.VERSION.SDK_INT < 24) {
try {
Os.kill(pid.get(process) as Int, OsConstants.SIGTERM)
} catch (e: ErrnoException) {
if (e.errno != OsConstants.ESRCH) Logs.w(e)
} catch (e: ReflectiveOperationException) {
Logs.w(e)
}
if (withTimeoutOrNull(500) { exitChannel.receive() } != null) return@withContext
}
process.destroy() // kill the process
if (Build.VERSION.SDK_INT >= 26) {
if (withTimeoutOrNull(1000) { exitChannel.receive() } != null) return@withContext
process.destroyForcibly() // Force to kill the process if it's still alive
}
exitChannel.receive()
} // otherwise process already exited, nothing to be done
}
}
}
override val coroutineContext = Dispatchers.Main.immediate + Job()
var processCount = 0
@MainThread
fun start(
cmd: List<String>,
env: MutableMap<String, String> = mutableMapOf(),
onRestartCallback: (suspend () -> Unit)? = null
) {
Logs.i("start process: ${Commandline.toString(cmd)}")
Guard(cmd, env).apply {
start() // if start fails, IOException will be thrown directly
launch { looper(onRestartCallback) }
}
processCount += 1
}
@MainThread
fun close(scope: CoroutineScope) {
cancel()
coroutineContext[Job]!!.also { job -> scope.launch { job.cancelAndJoin() } }
}
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/bg/GuardedProcessPool.kt | 2888837645 |
package io.nekohasekai.sagernet.bg
import android.app.PendingIntent
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.text.format.Formatter
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import io.nekohasekai.sagernet.Action
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.aidl.SpeedDisplayData
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.ProxyEntity
import io.nekohasekai.sagernet.database.SagerDatabase
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ktx.getColorAttr
import io.nekohasekai.sagernet.ktx.runOnMainDispatcher
import io.nekohasekai.sagernet.ui.SwitchActivity
import io.nekohasekai.sagernet.utils.Theme
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
/**
* User can customize visibility of notification since Android 8.
* The default visibility:
*
* Android 8.x: always visible due to system limitations
* VPN: always invisible because of VPN notification/icon
* Other: always visible
*
* See also: https://github.com/aosp-mirror/platform_frameworks_base/commit/070d142993403cc2c42eca808ff3fafcee220ac4
*/
class ServiceNotification(
private val service: BaseService.Interface, title: String,
channel: String, visible: Boolean = false,
) : BroadcastReceiver() {
companion object {
const val notificationId = 1
val flags =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0
fun genTitle(ent: ProxyEntity): String {
val gn = if (DataStore.showGroupInNotification)
SagerDatabase.groupDao.getById(ent.groupId)?.displayName() else null
return if (gn == null) ent.displayName() else "[$gn] ${ent.displayName()}"
}
}
var listenPostSpeed = true
suspend fun postNotificationSpeedUpdate(stats: SpeedDisplayData) {
useBuilder {
if (showDirectSpeed) {
val speedDetail = (service as Context).getString(
R.string.speed_detail, service.getString(
R.string.speed, Formatter.formatFileSize(service, stats.txRateProxy)
), service.getString(
R.string.speed, Formatter.formatFileSize(service, stats.rxRateProxy)
), service.getString(
R.string.speed,
Formatter.formatFileSize(service, stats.txRateDirect)
), service.getString(
R.string.speed,
Formatter.formatFileSize(service, stats.rxRateDirect)
)
)
it.setStyle(NotificationCompat.BigTextStyle().bigText(speedDetail))
it.setContentText(speedDetail)
} else {
val speedSimple = (service as Context).getString(
R.string.traffic, service.getString(
R.string.speed, Formatter.formatFileSize(service, stats.txRateProxy)
), service.getString(
R.string.speed, Formatter.formatFileSize(service, stats.rxRateProxy)
)
)
it.setContentText(speedSimple)
}
it.setSubText(
service.getString(
R.string.traffic,
Formatter.formatFileSize(service, stats.txTotal),
Formatter.formatFileSize(service, stats.rxTotal)
)
)
}
update()
}
suspend fun postNotificationTitle(newTitle: String) {
useBuilder {
it.setContentTitle(newTitle)
}
update()
}
suspend fun postNotificationWakeLockStatus(acquired: Boolean) {
updateActions()
useBuilder {
it.priority =
if (acquired) NotificationCompat.PRIORITY_HIGH else NotificationCompat.PRIORITY_LOW
}
update()
}
private val showDirectSpeed = DataStore.showDirectSpeed
private val builder = NotificationCompat.Builder(service as Context, channel)
.setWhen(0)
.setTicker(service.getString(R.string.forward_success))
.setContentTitle(title)
.setOnlyAlertOnce(true)
.setContentIntent(SagerNet.configureIntent(service))
.setSmallIcon(R.drawable.ic_service_active)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setPriority(if (visible) NotificationCompat.PRIORITY_LOW else NotificationCompat.PRIORITY_MIN)
private val buildLock = Mutex()
private suspend fun useBuilder(f: (NotificationCompat.Builder) -> Unit) {
buildLock.withLock {
f(builder)
}
}
init {
service as Context
Theme.apply(app)
Theme.apply(service)
builder.color = service.getColorAttr(R.attr.colorPrimary)
service.registerReceiver(this, IntentFilter().apply {
addAction(Intent.ACTION_SCREEN_ON)
addAction(Intent.ACTION_SCREEN_OFF)
})
runOnMainDispatcher {
updateActions()
show()
}
}
private suspend fun updateActions() {
service as Context
useBuilder {
it.clearActions()
val closeAction = NotificationCompat.Action.Builder(
0, service.getText(R.string.stop), PendingIntent.getBroadcast(
service, 0, Intent(Action.CLOSE).setPackage(service.packageName), flags
)
).setShowsUserInterface(false).build()
it.addAction(closeAction)
val switchAction = NotificationCompat.Action.Builder(
0, service.getString(R.string.action_switch), PendingIntent.getActivity(
service, 0, Intent(service, SwitchActivity::class.java), flags
)
).setShowsUserInterface(false).build()
it.addAction(switchAction)
val resetUpstreamAction = NotificationCompat.Action.Builder(
0, service.getString(R.string.reset_connections),
PendingIntent.getBroadcast(
service, 0, Intent(Action.RESET_UPSTREAM_CONNECTIONS), flags
)
).setShowsUserInterface(false).build()
it.addAction(resetUpstreamAction)
}
}
override fun onReceive(context: Context, intent: Intent) {
if (service.data.state == BaseService.State.Connected) {
listenPostSpeed = intent.action == Intent.ACTION_SCREEN_ON
}
}
private suspend fun show() =
useBuilder { (service as Service).startForeground(notificationId, it.build()) }
private suspend fun update() = useBuilder {
NotificationManagerCompat.from(service as Service).notify(notificationId, it.build())
}
fun destroy() {
listenPostSpeed = false
(service as Service).stopForeground(true)
service.unregisterReceiver(this)
}
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/bg/ServiceNotification.kt | 1132822435 |
package io.nekohasekai.sagernet.bg
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.os.RemoteException
import io.nekohasekai.sagernet.Action
import io.nekohasekai.sagernet.Key
import io.nekohasekai.sagernet.aidl.ISagerNetService
import io.nekohasekai.sagernet.aidl.ISagerNetServiceCallback
import io.nekohasekai.sagernet.aidl.SpeedDisplayData
import io.nekohasekai.sagernet.aidl.TrafficData
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ktx.runOnMainDispatcher
class SagerConnection(
private var connectionId: Int,
private var listenForDeath: Boolean = false
) : ServiceConnection, IBinder.DeathRecipient {
companion object {
val serviceClass
get() = when (DataStore.serviceMode) {
Key.MODE_PROXY -> ProxyService::class
Key.MODE_VPN -> VpnService::class
else -> throw UnknownError()
}.java
const val CONNECTION_ID_SHORTCUT = 0
const val CONNECTION_ID_TILE = 1
const val CONNECTION_ID_MAIN_ACTIVITY_FOREGROUND = 2
const val CONNECTION_ID_MAIN_ACTIVITY_BACKGROUND = 3
}
interface Callback {
// smaller ISagerNetServiceCallback
fun cbSpeedUpdate(stats: SpeedDisplayData) {}
fun cbTrafficUpdate(data: TrafficData) {}
fun cbSelectorUpdate(id: Long) {}
fun stateChanged(state: BaseService.State, profileName: String?, msg: String?)
fun missingPlugin(profileName: String, pluginName: String) {}
fun onServiceConnected(service: ISagerNetService)
/**
* Different from Android framework, this method will be called even when you call `detachService`.
*/
fun onServiceDisconnected() {}
fun onBinderDied() {}
}
private var connectionActive = false
private var callbackRegistered = false
private var callback: Callback? = null
private val serviceCallback = object : ISagerNetServiceCallback.Stub() {
override fun stateChanged(state: Int, profileName: String?, msg: String?) {
if (state < 0) return // skip private
val s = BaseService.State.values()[state]
DataStore.serviceState = s
val callback = callback ?: return
runOnMainDispatcher {
callback.stateChanged(s, profileName, msg)
}
}
override fun cbSpeedUpdate(stats: SpeedDisplayData) {
val callback = callback ?: return
runOnMainDispatcher {
callback.cbSpeedUpdate(stats)
}
}
override fun cbTrafficUpdate(stats: TrafficData) {
val callback = callback ?: return
runOnMainDispatcher {
callback.cbTrafficUpdate(stats)
}
}
override fun cbSelectorUpdate(id: Long) {
val callback = callback ?: return
runOnMainDispatcher {
callback.cbSelectorUpdate(id)
}
}
override fun missingPlugin(profileName: String, pluginName: String) {
val callback = callback ?: return
runOnMainDispatcher {
callback.missingPlugin(profileName, pluginName)
}
}
}
private var binder: IBinder? = null
var service: ISagerNetService? = null
fun updateConnectionId(id: Int) {
connectionId = id
try {
service?.registerCallback(serviceCallback, id)
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onServiceConnected(name: ComponentName?, binder: IBinder) {
this.binder = binder
val service = ISagerNetService.Stub.asInterface(binder)!!
this.service = service
try {
if (listenForDeath) binder.linkToDeath(this, 0)
check(!callbackRegistered)
service.registerCallback(serviceCallback, connectionId)
callbackRegistered = true
} catch (e: RemoteException) {
e.printStackTrace()
}
callback!!.onServiceConnected(service)
}
override fun onServiceDisconnected(name: ComponentName?) {
unregisterCallback()
callback?.onServiceDisconnected()
service = null
binder = null
}
override fun binderDied() {
service = null
callbackRegistered = false
callback?.also { runOnMainDispatcher { it.onBinderDied() } }
}
private fun unregisterCallback() {
val service = service
if (service != null && callbackRegistered) try {
service.unregisterCallback(serviceCallback)
} catch (_: RemoteException) {
}
callbackRegistered = false
}
fun connect(context: Context, callback: Callback) {
if (connectionActive) return
connectionActive = true
check(this.callback == null)
this.callback = callback
val intent = Intent(context, serviceClass).setAction(Action.SERVICE)
context.bindService(intent, this, Context.BIND_AUTO_CREATE)
}
fun disconnect(context: Context) {
unregisterCallback()
if (connectionActive) try {
context.unbindService(this)
} catch (_: IllegalArgumentException) {
} // ignore
connectionActive = false
if (listenForDeath) try {
binder?.unlinkToDeath(this, 0)
} catch (_: NoSuchElementException) {
}
binder = null
service = null
callback = null
}
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/bg/SagerConnection.kt | 2064665227 |
package io.nekohasekai.sagernet.bg
import java.io.Closeable
interface AbstractInstance : Closeable {
fun launch()
} | nacs/app/src/main/java/io/nekohasekai/sagernet/bg/AbstractInstance.kt | 2363142510 |
package io.nekohasekai.sagernet.bg
import android.graphics.drawable.Icon
import android.service.quicksettings.Tile
import androidx.annotation.RequiresApi
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.aidl.ISagerNetService
import io.nekohasekai.sagernet.database.SagerDatabase
import android.service.quicksettings.TileService as BaseTileService
@RequiresApi(24)
class TileService : BaseTileService(), SagerConnection.Callback {
private val iconIdle by lazy { Icon.createWithResource(this, R.drawable.ic_service_idle) }
private val iconBusy by lazy { Icon.createWithResource(this, R.drawable.ic_service_busy) }
private val iconConnected by lazy {
Icon.createWithResource(this, R.drawable.ic_service_active)
}
private var tapPending = false
private val connection = SagerConnection(SagerConnection.CONNECTION_ID_TILE)
override fun stateChanged(state: BaseService.State, profileName: String?, msg: String?) =
updateTile(state, profileName)
override fun onServiceConnected(service: ISagerNetService) {
updateTile(BaseService.State.values()[service.state], service.profileName)
if (tapPending) {
tapPending = false
onClick()
}
}
override fun cbSelectorUpdate(id: Long) {
val profile = SagerDatabase.proxyDao.getById(id) ?: return
updateTile(BaseService.State.Connected, profile.displayName())
}
override fun onStartListening() {
super.onStartListening()
connection.connect(this, this)
}
override fun onStopListening() {
connection.disconnect(this)
super.onStopListening()
}
override fun onClick() {
if (isLocked) unlockAndRun(this::toggle) else toggle()
}
private fun updateTile(serviceState: BaseService.State, profileName: String?) {
qsTile?.apply {
label = null
when (serviceState) {
BaseService.State.Idle -> error("serviceState")
BaseService.State.Connecting -> {
icon = iconBusy
state = Tile.STATE_ACTIVE
}
BaseService.State.Connected -> {
icon = iconConnected
label = profileName
state = Tile.STATE_ACTIVE
}
BaseService.State.Stopping -> {
icon = iconBusy
state = Tile.STATE_UNAVAILABLE
}
BaseService.State.Stopped -> {
icon = iconIdle
state = Tile.STATE_INACTIVE
}
}
label = label ?: getString(R.string.app_name)
updateTile()
}
}
private fun toggle() {
val service = connection.service
if (service == null) tapPending =
true else BaseService.State.values()[service.state].let { state ->
when {
state.canStop -> SagerNet.stopService()
state == BaseService.State.Stopped -> SagerNet.startService()
}
}
}
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/bg/TileService.kt | 4195187675 |
package io.nekohasekai.sagernet
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import io.nekohasekai.sagernet.bg.SubscriptionUpdater
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ktx.runOnDefaultDispatcher
class BootReceiver : BroadcastReceiver() {
companion object {
private val componentName by lazy { ComponentName(app, BootReceiver::class.java) }
var enabled: Boolean
get() = app.packageManager.getComponentEnabledSetting(componentName) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
set(value) = app.packageManager.setComponentEnabledSetting(
componentName, if (value) PackageManager.COMPONENT_ENABLED_STATE_ENABLED
else PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP
)
}
override fun onReceive(context: Context, intent: Intent) {
runOnDefaultDispatcher {
SubscriptionUpdater.reconfigureUpdater()
}
if (!DataStore.persistAcrossReboot) { // sanity check
enabled = false
return
}
val doStart = when (intent.action) {
Intent.ACTION_LOCKED_BOOT_COMPLETED -> false // DataStore.directBootAware
else -> Build.VERSION.SDK_INT < 24 || SagerNet.user.isUserUnlocked
} && DataStore.selectedProxy > 0
if (doStart) SagerNet.startService()
}
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/BootReceiver.kt | 1811220347 |
package io.nekohasekai.sagernet
const val CONNECTION_TEST_URL = "http://cp.cloudflare.com/"
object Key {
const val DB_PUBLIC = "configuration.db"
const val DB_PROFILE = "sager_net.db"
const val PERSIST_ACROSS_REBOOT = "isAutoConnect"
const val APP_EXPERT = "isExpert"
const val APP_THEME = "appTheme"
const val NIGHT_THEME = "nightTheme"
const val SERVICE_MODE = "serviceMode"
const val MODE_VPN = "vpn"
const val MODE_PROXY = "proxy"
const val REMOTE_DNS = "remoteDns"
const val DIRECT_DNS = "directDns"
const val UNDERLYING_DNS = "underlyingDns"
const val ENABLE_DNS_ROUTING = "enableDnsRouting"
const val ENABLE_FAKEDNS = "enableFakeDns"
const val IPV6_MODE = "ipv6Mode"
const val PROXY_APPS = "proxyApps"
const val BYPASS_MODE = "bypassMode"
const val INDIVIDUAL = "individual"
const val METERED_NETWORK = "meteredNetwork"
const val TRAFFIC_SNIFFING = "trafficSniffing"
const val RESOLVE_DESTINATION = "resolveDestination"
const val BYPASS_LAN = "bypassLan"
const val BYPASS_LAN_IN_CORE = "bypassLanInCore"
const val INBOUND_USERNAME = "inboundUsername"
const val INBOUND_PASSWORD = "inboundPassword"
const val MIXED_PORT = "mixedPort"
const val ALLOW_ACCESS = "allowAccess"
const val SPEED_INTERVAL = "speedInterval"
const val SHOW_DIRECT_SPEED = "showDirectSpeed"
const val LOCAL_DNS_PORT = "portLocalDns"
const val APPEND_HTTP_PROXY = "appendHttpProxy"
const val CONNECTION_TEST_URL = "connectionTestURL"
const val TCP_KEEP_ALIVE_INTERVAL = "tcpKeepAliveInterval"
const val RULES_PROVIDER = "rulesProvider"
const val LOG_LEVEL = "logLevel"
const val LOG_BUF_SIZE = "logBufSize"
const val MTU = "mtu"
const val ALWAYS_SHOW_ADDRESS = "alwaysShowAddress"
// Protocol Settings
const val MUX_TYPE = "muxType"
const val MUX_PROTOCOLS = "mux"
const val MUX_CONCURRENCY = "muxConcurrency"
const val GLOBAL_ALLOW_INSECURE = "globalAllowInsecure"
const val ACQUIRE_WAKE_LOCK = "acquireWakeLock"
const val SHOW_BOTTOM_BAR = "showBottomBar"
const val ALLOW_INSECURE_ON_REQUEST = "allowInsecureOnRequest"
const val TUN_IMPLEMENTATION = "tunImplementation"
const val PROFILE_TRAFFIC_STATISTICS = "profileTrafficStatistics"
const val PROFILE_DIRTY = "profileDirty"
const val PROFILE_ID = "profileId"
const val PROFILE_NAME = "profileName"
const val PROFILE_GROUP = "profileGroup"
const val PROFILE_CURRENT = "profileCurrent"
const val SERVER_ADDRESS = "serverAddress"
const val SERVER_PORT = "serverPort"
const val SERVER_USERNAME = "serverUsername"
const val SERVER_PASSWORD = "serverPassword"
const val SERVER_METHOD = "serverMethod"
const val SERVER_PASSWORD1 = "serverPassword1"
const val PROTOCOL_VERSION = "protocolVersion"
const val SERVER_PROTOCOL = "serverProtocol"
const val SERVER_OBFS = "serverObfs"
const val SERVER_NETWORK = "serverNetwork"
const val SERVER_HOST = "serverHost"
const val SERVER_PATH = "serverPath"
const val SERVER_SNI = "serverSNI"
const val SERVER_ENCRYPTION = "serverEncryption"
const val SERVER_ALPN = "serverALPN"
const val SERVER_CERTIFICATES = "serverCertificates"
const val SERVER_CONFIG = "serverConfig"
const val SERVER_CUSTOM = "serverCustom"
const val SERVER_CUSTOM_OUTBOUND = "serverCustomOutbound"
const val SERVER_SECURITY_CATEGORY = "serverSecurityCategory"
const val SERVER_TLS_CAMOUFLAGE_CATEGORY = "serverTlsCamouflageCategory"
const val SERVER_ECH_CATEGORY = "serverEchCategory"
const val SERVER_WS_CATEGORY = "serverWsCategory"
const val SERVER_SS_CATEGORY = "serverSsCategory"
const val SERVER_HEADERS = "serverHeaders"
const val SERVER_ALLOW_INSECURE = "serverAllowInsecure"
const val ECH = "ech"
const val ECH_CFG = "echCfg"
const val SERVER_AUTH_TYPE = "serverAuthType"
const val SERVER_UPLOAD_SPEED = "serverUploadSpeed"
const val SERVER_DOWNLOAD_SPEED = "serverDownloadSpeed"
const val SERVER_STREAM_RECEIVE_WINDOW = "serverStreamReceiveWindow"
const val SERVER_CONNECTION_RECEIVE_WINDOW = "serverConnectionReceiveWindow"
const val SERVER_DISABLE_MTU_DISCOVERY = "serverDisableMtuDiscovery"
const val SERVER_HOP_INTERVAL = "hopInterval"
const val SERVER_PRIVATE_KEY = "serverPrivateKey"
const val SERVER_INSECURE_CONCURRENCY = "serverInsecureConcurrency"
const val SERVER_UDP_RELAY_MODE = "serverUDPRelayMode"
const val SERVER_CONGESTION_CONTROLLER = "serverCongestionController"
const val SERVER_DISABLE_SNI = "serverDisableSNI"
const val SERVER_REDUCE_RTT = "serverReduceRTT"
const val ROUTE_NAME = "routeName"
const val ROUTE_DOMAIN = "routeDomain"
const val ROUTE_IP = "routeIP"
const val ROUTE_PORT = "routePort"
const val ROUTE_SOURCE_PORT = "routeSourcePort"
const val ROUTE_NETWORK = "routeNetwork"
const val ROUTE_SOURCE = "routeSource"
const val ROUTE_PROTOCOL = "routeProtocol"
const val ROUTE_OUTBOUND = "routeOutbound"
const val ROUTE_PACKAGES = "routePackages"
const val ROUTE_SSID = "routeSSID"
const val ROUTE_BSSID = "routeBSSID"
const val GROUP_NAME = "groupName"
const val GROUP_TYPE = "groupType"
const val GROUP_ORDER = "groupOrder"
const val GROUP_IS_SELECTOR = "groupIsSelector"
const val GROUP_FRONT_PROXY = "groupFrontProxy"
const val GROUP_LANDING_PROXY = "groupLandingProxy"
const val GROUP_SUBSCRIPTION = "groupSubscription"
const val SUBSCRIPTION_LINK = "subscriptionLink"
const val SUBSCRIPTION_FORCE_RESOLVE = "subscriptionForceResolve"
const val SUBSCRIPTION_DEDUPLICATION = "subscriptionDeduplication"
const val SUBSCRIPTION_UPDATE = "subscriptionUpdate"
const val SUBSCRIPTION_UPDATE_WHEN_CONNECTED_ONLY = "subscriptionUpdateWhenConnectedOnly"
const val SUBSCRIPTION_USER_AGENT = "subscriptionUserAgent"
const val SUBSCRIPTION_AUTO_UPDATE = "subscriptionAutoUpdate"
const val SUBSCRIPTION_AUTO_UPDATE_DELAY = "subscriptionAutoUpdateDelay"
//
const val NEKO_PLUGIN_MANAGED = "nekoPlugins"
const val APP_TLS_VERSION = "appTLSVersion"
const val CLASH_API_LISTEN = "clashAPIListen"
const val ENABLED_CAZILLA = "enabledCazilla"
}
object TunImplementation {
const val GVISOR = 0
const val SYSTEM = 1
const val MIXED = 2
}
object IPv6Mode {
const val DISABLE = 0
const val ENABLE = 1
const val PREFER = 2
const val ONLY = 3
}
object GroupType {
const val BASIC = 0
const val SUBSCRIPTION = 1
}
object GroupOrder {
const val ORIGIN = 0
const val BY_NAME = 1
const val BY_DELAY = 2
}
object Action {
const val SERVICE = "io.nekohasekai.sagernet.SERVICE"
const val CLOSE = "io.nekohasekai.sagernet.CLOSE"
const val RELOAD = "io.nekohasekai.sagernet.RELOAD"
// const val SWITCH_WAKE_LOCK = "io.nekohasekai.sagernet.SWITCH_WAKELOCK"
const val RESET_UPSTREAM_CONNECTIONS = "moe.nb4a.RESET_UPSTREAM_CONNECTIONS"
}
| nacs/app/src/main/java/io/nekohasekai/sagernet/Constants.kt | 2597751379 |
package moe.matsuri.nb4a.ui
import android.content.Context
import android.content.Intent
import android.util.AttributeSet
import androidx.preference.Preference
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ui.profile.ConfigEditActivity
class EditConfigPreference : Preference {
constructor(
context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int
) : super(context, attrs, defStyleAttr, defStyleRes)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context, attrs, defStyleAttr
)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context) : super(context)
init {
intent = Intent(context, ConfigEditActivity::class.java)
}
override fun getSummary(): CharSequence {
val config = DataStore.serverConfig
return if (DataStore.serverConfig.isBlank()) {
return app.resources.getString(androidx.preference.R.string.not_set)
} else {
app.resources.getString(R.string.lines, config.split('\n').size)
}
}
public override fun notifyChanged() {
super.notifyChanged()
}
}
| nacs/app/src/main/java/moe/matsuri/nb4a/ui/EditConfigPreference.kt | 4017526230 |
package moe.matsuri.nb4a.ui
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.preference.PreferenceViewHolder
import io.nekohasekai.sagernet.R
class LongClickMenuPreference
@JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyle: Int = R.attr.dropdownPreferenceStyle
) : SimpleMenuPreference(context, attrs, defStyle, 0) {
private var mLongClickListener: View.OnLongClickListener? = null
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
val itemView: View = holder.itemView
itemView.setOnLongClickListener {
mLongClickListener?.onLongClick(it) ?: true
}
}
fun setOnLongClickListener(longClickListener: View.OnLongClickListener) {
this.mLongClickListener = longClickListener
}
}
| nacs/app/src/main/java/moe/matsuri/nb4a/ui/LongClickMenuPreference.kt | 2736707621 |
package moe.matsuri.nb4a.ui
import android.content.Context
import android.util.AttributeSet
import android.widget.EditText
import android.widget.LinearLayout
import androidx.core.content.res.TypedArrayUtils
import androidx.core.view.isVisible
import androidx.preference.EditTextPreference
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.database.DataStore
class UrlTestPreference
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = TypedArrayUtils.getAttr(
context, R.attr.editTextPreferenceStyle,
android.R.attr.editTextPreferenceStyle
),
defStyleRes: Int = 0
) : EditTextPreference(context, attrs, defStyleAttr, defStyleRes) {
var concurrent: EditText? = null
init {
dialogLayoutResource = R.layout.layout_urltest_preference_dialog
setOnBindEditTextListener {
concurrent = it.rootView.findViewById(R.id.edit_concurrent)
concurrent?.apply {
setText(DataStore.connectionTestConcurrent.toString())
}
it.rootView.findViewById<LinearLayout>(R.id.concurrent_layout)?.isVisible = true
}
setOnPreferenceChangeListener { _, _ ->
concurrent?.apply {
var newConcurrent = text?.toString()?.toIntOrNull()
if (newConcurrent == null || newConcurrent <= 0) {
newConcurrent = 5
}
DataStore.connectionTestConcurrent = newConcurrent
}
true
}
}
} | nacs/app/src/main/java/moe/matsuri/nb4a/ui/UrlTestPreference.kt | 2777987035 |
package moe.matsuri.nb4a.ui
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.preference.ListPreference
import androidx.preference.PreferenceViewHolder
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import io.nekohasekai.sagernet.R
class MTUPreference
@JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyle: Int = R.attr.dropdownPreferenceStyle
) : ListPreference(context, attrs, defStyle, 0) {
init {
setSummaryProvider {
value.toString()
}
dialogLayoutResource = R.layout.layout_mtu_help
}
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
val itemView: View = holder.itemView
itemView.setOnLongClickListener {
val view = EditText(context).apply {
inputType = EditorInfo.TYPE_CLASS_NUMBER
setText(preferenceDataStore?.getString(key, "") ?: "")
}
MaterialAlertDialogBuilder(context).setTitle("MTU")
.setView(view)
.setPositiveButton(android.R.string.ok) { _, _ ->
val mtu = view.text.toString().toInt()
if (mtu <= 1000 || mtu > 65535) return@setPositiveButton
value = mtu.toString()
}
.setNegativeButton(android.R.string.cancel, null)
.show()
true
}
}
}
| nacs/app/src/main/java/moe/matsuri/nb4a/ui/MTUPreference.kt | 1023081701 |
package moe.matsuri.nb4a.ui
import android.content.Context
import android.widget.TextView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.ktx.readableMessage
import io.nekohasekai.sagernet.ktx.runOnMainDispatcher
object Dialogs {
fun logExceptionAndShow(context: Context, e: Exception, callback: Runnable) {
Logs.e(e)
runOnMainDispatcher {
MaterialAlertDialogBuilder(context)
.setTitle(R.string.error_title)
.setMessage(e.readableMessage)
.setCancelable(false)
.setPositiveButton(android.R.string.ok) { _, _ ->
callback.run()
}
.show()
}
}
fun message(context: Context, title: String, message: String) {
runOnMainDispatcher {
val dialog = MaterialAlertDialogBuilder(context)
.setTitle(title)
.setMessage(message)
.setCancelable(true)
.show()
dialog.findViewById<TextView>(android.R.id.message)?.apply {
setTextIsSelectable(true)
}
}
}
} | nacs/app/src/main/java/moe/matsuri/nb4a/ui/Dialogs.kt | 3968676665 |
package moe.matsuri.nb4a.ui
import android.content.Context
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.GridLayout
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.appcompat.app.AlertDialog
import androidx.core.content.res.ResourcesCompat
import androidx.core.content.res.TypedArrayUtils
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.view.setPadding
import androidx.preference.Preference
import androidx.preference.PreferenceViewHolder
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.ktx.getColorAttr
import io.nekohasekai.sagernet.ktx.isExpertFlavor
import kotlin.math.roundToInt
class ColorPickerPreference
@JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyle: Int = TypedArrayUtils.getAttr(
context,
androidx.preference.R.attr.editTextPreferenceStyle,
android.R.attr.editTextPreferenceStyle
)
) : Preference(
context, attrs, defStyle
) {
var inited = false
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
val widgetFrame = holder.findViewById(android.R.id.widget_frame) as LinearLayout
if (!inited) {
inited = true
widgetFrame.addView(
getNekoImageViewAtColor(
context.getColorAttr(R.attr.colorPrimary),
48,
0
)
)
widgetFrame.visibility = View.VISIBLE
}
}
fun getNekoImageViewAtColor(color: Int, sizeDp: Int, paddingDp: Int): ImageView {
// dp to pixel
val factor = context.resources.displayMetrics.density
val size = (sizeDp * factor).roundToInt()
val paddingSize = (paddingDp * factor).roundToInt()
return ImageView(context).apply {
layoutParams = ViewGroup.LayoutParams(size, size)
setPadding(paddingSize)
setImageDrawable(getNekoAtColor(resources, color))
}
}
fun getNekoAtColor(res: Resources, color: Int): Drawable {
val neko = ResourcesCompat.getDrawable(
res,
R.drawable.ic_baseline_fiber_manual_record_24,
null
)!!
DrawableCompat.setTint(neko.mutate(), color)
return neko
}
override fun onClick() {
super.onClick()
lateinit var dialog: AlertDialog
val grid = GridLayout(context).apply {
columnCount = 4
val colors = context.resources.getIntArray(R.array.material_colors)
var i = 0
for (color in colors) {
i++ //Theme.kt
if (!isExpertFlavor && i in listOf(21)) continue
val themeId = i
val view = getNekoImageViewAtColor(color, 64, 0).apply {
setOnClickListener {
persistInt(themeId)
dialog.dismiss()
callChangeListener(themeId)
}
}
addView(view)
}
}
dialog = MaterialAlertDialogBuilder(context).setTitle(title)
.setView(LinearLayout(context).apply {
gravity = Gravity.CENTER
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
)
addView(grid)
})
.setNegativeButton(android.R.string.cancel, null)
.show()
}
} | nacs/app/src/main/java/moe/matsuri/nb4a/ui/ColorPickerPreference.kt | 162445628 |
package moe.matsuri.nb4a.ui
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.core.content.res.TypedArrayUtils
import androidx.preference.PreferenceViewHolder
import androidx.preference.R
import androidx.preference.SwitchPreference
class LongClickSwitchPreference
@JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = TypedArrayUtils.getAttr(
context, R.attr.switchPreferenceStyle, android.R.attr.switchPreferenceStyle
), defStyleRes: Int = 0
) : SwitchPreference(
context, attrs, defStyleAttr, defStyleRes
) {
private var mLongClickListener: View.OnLongClickListener? = null
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
val itemView: View = holder.itemView
itemView.setOnLongClickListener {
mLongClickListener?.onLongClick(it) ?: true
}
}
fun setOnLongClickListener(longClickListener: View.OnLongClickListener) {
this.mLongClickListener = longClickListener
}
}
| nacs/app/src/main/java/moe/matsuri/nb4a/ui/LongClickSwitchPreference.kt | 142227840 |
package moe.matsuri.nb4a.ui
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.preference.ListPreference
import androidx.preference.PreferenceViewHolder
import io.nekohasekai.sagernet.R
class LongClickListPreference
@JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyle: Int = R.attr.dropdownPreferenceStyle
) : ListPreference(context, attrs, defStyle, 0) {
private var mLongClickListener: View.OnLongClickListener? = null
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
val itemView: View = holder.itemView
itemView.setOnLongClickListener {
mLongClickListener?.onLongClick(it) ?: true
}
}
fun setOnLongClickListener(longClickListener: View.OnLongClickListener) {
this.mLongClickListener = longClickListener
}
}
| nacs/app/src/main/java/moe/matsuri/nb4a/ui/LongClickListPreference.kt | 1785859482 |
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package moe.matsuri.nb4a.ui
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Spinner
import androidx.core.content.ContextCompat
import androidx.preference.DropDownPreference
import androidx.preference.PreferenceViewHolder
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.ktx.getColorAttr
/**
* Bend [DropDownPreference] to support
* [Simple Menus](https://material.google.com/components/menus.html#menus-behavior).
*/
open class SimpleMenuPreference
@JvmOverloads constructor(
context: Context?,
attrs: AttributeSet? = null,
defStyleAttr: Int = androidx.preference.R.attr.dropdownPreferenceStyle,
defStyleRes: Int = 0
) : DropDownPreference(context!!, attrs, defStyleAttr, defStyleRes) {
private lateinit var mAdapter: SimpleMenuAdapter
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
val mSpinner = holder.itemView.findViewById<Spinner>(R.id.spinner)
mSpinner.layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT
}
override fun createAdapter(): ArrayAdapter<CharSequence?> {
mAdapter = SimpleMenuAdapter(getContext(), R.layout.simple_menu_dropdown_item)
return mAdapter
}
override fun setValue(value: String?) {
super.setValue(value)
if (::mAdapter.isInitialized) {
mAdapter.currentPosition = entryValues.indexOf(value)
mAdapter.notifyDataSetChanged()
}
}
private class SimpleMenuAdapter(context: Context, resource: Int) :
ArrayAdapter<CharSequence?>(context, resource) {
var currentPosition = -1
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
val view: View = super.getDropDownView(position, convertView, parent)
if (position == currentPosition) {
view.setBackgroundColor(context.getColorAttr(R.attr.colorMaterial100))
} else {
view.setBackgroundColor(
ContextCompat.getColor(
context,
R.color.preference_simple_menu_background
)
)
}
return view
}
}
} | nacs/app/src/main/java/moe/matsuri/nb4a/ui/SimpleMenuPreference.kt | 613549670 |
/*
* Copyright 2021 Squircle IDE contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package moe.matsuri.nb4a.ui
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import io.nekohasekai.sagernet.databinding.ItemKeyboardKeyBinding
class ExtendedKeyboard @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : RecyclerView(context, attrs, defStyleAttr) {
private lateinit var keyAdapter: KeyAdapter
fun setKeyListener(keyListener: OnKeyListener) {
keyAdapter = KeyAdapter(keyListener)
adapter = keyAdapter
}
fun submitList(keys: List<String>) {
keyAdapter.submitList(keys)
}
private class KeyAdapter(
private val keyListener: OnKeyListener
) : ListAdapter<String, KeyAdapter.KeyViewHolder>(diffCallback) {
companion object {
private val diffCallback = object : DiffUtil.ItemCallback<String>() {
override fun areItemsTheSame(oldItem: String, newItem: String): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: String, newItem: String): Boolean {
return oldItem == newItem
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): KeyViewHolder {
return KeyViewHolder.create(parent, keyListener)
}
override fun onBindViewHolder(holder: KeyViewHolder, position: Int) {
holder.bind(getItem(position))
}
private class KeyViewHolder(
private val binding: ItemKeyboardKeyBinding,
private val keyListener: OnKeyListener
) : ViewHolder(binding.root) {
companion object {
fun create(parent: ViewGroup, keyListener: OnKeyListener): KeyViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ItemKeyboardKeyBinding.inflate(inflater, parent, false)
return KeyViewHolder(binding, keyListener)
}
}
private lateinit var char: String
init {
itemView.setOnClickListener {
keyListener.onKey(char)
}
}
fun bind(item: String) {
char = item
binding.itemTitle.text = char
binding.itemTitle.setTextColor(Color.WHITE)
}
}
}
fun interface OnKeyListener {
fun onKey(char: String)
}
} | nacs/app/src/main/java/moe/matsuri/nb4a/ui/ExtendedKeyboard.kt | 2406679057 |
package moe.matsuri.nb4a.net
import android.net.DnsResolver
import android.os.Build
import android.os.CancellationSignal
import android.system.ErrnoException
import androidx.annotation.RequiresApi
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.ktx.tryResumeWithException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asExecutor
import kotlinx.coroutines.runBlocking
import libcore.ExchangeContext
import libcore.LocalDNSTransport
import java.net.InetAddress
import java.net.UnknownHostException
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
object LocalResolverImpl : LocalDNSTransport {
// new local
private const val RCODE_NXDOMAIN = 3
override fun raw(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun exchange(ctx: ExchangeContext, message: ByteArray) {
return runBlocking {
suspendCoroutine { continuation ->
val signal = CancellationSignal()
ctx.onCancel(signal::cancel)
val callback = object : DnsResolver.Callback<ByteArray> {
override fun onAnswer(answer: ByteArray, rcode: Int) {
// exchange don't generate rcode error
ctx.rawSuccess(answer)
continuation.resume(Unit)
}
override fun onError(error: DnsResolver.DnsException) {
when (val cause = error.cause) {
is ErrnoException -> {
ctx.errnoCode(cause.errno)
continuation.resume(Unit)
return
}
}
continuation.tryResumeWithException(error)
}
}
DnsResolver.getInstance().rawQuery(
SagerNet.underlyingNetwork,
message,
DnsResolver.FLAG_NO_RETRY,
Dispatchers.IO.asExecutor(),
signal,
callback
)
}
}
}
override fun lookup(ctx: ExchangeContext, network: String, domain: String) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
return runBlocking {
suspendCoroutine { continuation ->
val signal = CancellationSignal()
ctx.onCancel(signal::cancel)
val callback = object : DnsResolver.Callback<Collection<InetAddress>> {
override fun onAnswer(answer: Collection<InetAddress>, rcode: Int) {
if (rcode == 0) {
ctx.success((answer as Collection<InetAddress?>).mapNotNull { it?.hostAddress }
.joinToString("\n"))
} else {
ctx.errorCode(rcode)
}
continuation.resume(Unit)
}
override fun onError(error: DnsResolver.DnsException) {
when (val cause = error.cause) {
is ErrnoException -> {
ctx.errnoCode(cause.errno)
continuation.resume(Unit)
return
}
}
continuation.tryResumeWithException(error)
}
}
val type = when {
network.endsWith("4") -> DnsResolver.TYPE_A
network.endsWith("6") -> DnsResolver.TYPE_AAAA
else -> null
}
if (type != null) {
DnsResolver.getInstance().query(
SagerNet.underlyingNetwork,
domain,
type,
DnsResolver.FLAG_NO_RETRY,
Dispatchers.IO.asExecutor(),
signal,
callback
)
} else {
DnsResolver.getInstance().query(
SagerNet.underlyingNetwork,
domain,
DnsResolver.FLAG_NO_RETRY,
Dispatchers.IO.asExecutor(),
signal,
callback
)
}
}
}
} else {
val answer = try {
val u = SagerNet.underlyingNetwork
if (u != null) {
u.getAllByName(domain)
} else {
InetAddress.getAllByName(domain)
}
} catch (e: UnknownHostException) {
ctx.errorCode(RCODE_NXDOMAIN)
return
}
ctx.success(answer.mapNotNull { it.hostAddress }.joinToString("\n"))
}
}
} | nacs/app/src/main/java/moe/matsuri/nb4a/net/LocalResolverImpl.kt | 3109287133 |
package moe.matsuri.nb4a.proxy.shadowtls
import io.nekohasekai.sagernet.fmt.v2ray.buildSingBoxOutboundTLS
import moe.matsuri.nb4a.SingBoxOptions
fun buildSingBoxOutboundShadowTLSBean(bean: ShadowTLSBean): SingBoxOptions.Outbound_ShadowTLSOptions {
return SingBoxOptions.Outbound_ShadowTLSOptions().apply {
type = "shadowtls"
server = bean.serverAddress
server_port = bean.serverPort
version = bean.version
password = bean.password
tls = buildSingBoxOutboundTLS(bean)
}
}
| nacs/app/src/main/java/moe/matsuri/nb4a/proxy/shadowtls/ShadowTLSFmt.kt | 285420641 |
package moe.matsuri.nb4a.proxy.shadowtls
import android.os.Bundle
import androidx.preference.EditTextPreference
import androidx.preference.PreferenceFragmentCompat
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.database.preference.EditTextPreferenceModifiers
import io.nekohasekai.sagernet.ui.profile.ProfileSettingsActivity
import moe.matsuri.nb4a.proxy.PreferenceBinding
import moe.matsuri.nb4a.proxy.PreferenceBindingManager
import moe.matsuri.nb4a.proxy.Type
class ShadowTLSSettingsActivity : ProfileSettingsActivity<ShadowTLSBean>() {
override fun createEntity() = ShadowTLSBean()
private val pbm = PreferenceBindingManager()
private val name = pbm.add(PreferenceBinding(Type.Text, "name"))
private val serverAddress = pbm.add(PreferenceBinding(Type.Text, "serverAddress"))
private val serverPort = pbm.add(PreferenceBinding(Type.TextToInt, "serverPort"))
private val password = pbm.add(PreferenceBinding(Type.Text, "password"))
private val version = pbm.add(PreferenceBinding(Type.TextToInt, "version"))
private val sni = pbm.add(PreferenceBinding(Type.Text, "sni"))
private val alpn = pbm.add(PreferenceBinding(Type.Text, "alpn"))
private val certificates = pbm.add(PreferenceBinding(Type.Text, "certificates"))
private val allowInsecure = pbm.add(PreferenceBinding(Type.Bool, "allowInsecure"))
private val utlsFingerprint = pbm.add(PreferenceBinding(Type.Text, "utlsFingerprint"))
override fun ShadowTLSBean.init() {
pbm.writeToCacheAll(this)
}
override fun ShadowTLSBean.serialize() {
pbm.fromCacheAll(this)
}
override fun PreferenceFragmentCompat.createPreferences(
savedInstanceState: Bundle?,
rootKey: String?,
) {
addPreferencesFromResource(R.xml.shadowtls_preferences)
pbm.setPreferenceFragment(this)
serverPort.preference.apply {
this as EditTextPreference
setOnBindEditTextListener(EditTextPreferenceModifiers.Port)
}
password.preference.apply {
this as EditTextPreference
summaryProvider = PasswordSummaryProvider
}
}
}
| nacs/app/src/main/java/moe/matsuri/nb4a/proxy/shadowtls/ShadowTLSSettingsActivity.kt | 287225921 |
package moe.matsuri.nb4a.proxy
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.ktx.readableMessage
object Type {
const val Text = 0
const val TextToInt = 1
const val Int = 2
const val Bool = 3
}
class PreferenceBinding(
val type: Int = Type.Text,
var fieldName: String,
var bean: Any? = null,
var pf: PreferenceFragmentCompat? = null
) {
var cacheName = fieldName
var disable = false
fun readStringFromCache(): String {
return DataStore.profileCacheStore.getString(cacheName) ?: ""
}
fun readBoolFromCache(): Boolean {
return DataStore.profileCacheStore.getBoolean(cacheName, false)
}
fun readIntFromCache(): Int {
return DataStore.profileCacheStore.getInt(cacheName, 0)
}
fun readStringToIntFromCache(): Int {
val value = DataStore.profileCacheStore.getString(cacheName)?.toIntOrNull() ?: 0
// Logs.d("readStringToIntFromCache $value $cacheName -> $fieldName")
return value
}
fun fromCache() {
if (disable) return
val f = try {
bean!!.javaClass.getField(fieldName)
} catch (e: Exception) {
Logs.d("binding no field: ${e.readableMessage}")
return
}
when (type) {
Type.Text -> f.set(bean, readStringFromCache())
Type.TextToInt -> f.set(bean, readStringToIntFromCache())
Type.Int -> f.set(bean, readIntFromCache())
Type.Bool -> f.set(bean, readBoolFromCache())
}
}
fun writeToCache() {
if (disable) return
val f = try {
bean!!.javaClass.getField(fieldName) ?: return
} catch (e: Exception) {
Logs.d("binding no field: ${e.readableMessage}")
return
}
val value = f.get(bean)
when (type) {
Type.Text -> {
if (value is String) {
// Logs.d("writeToCache TEXT $value $cacheName -> $fieldName")
DataStore.profileCacheStore.putString(cacheName, value)
}
}
Type.TextToInt -> {
if (value is Int) {
// Logs.d("writeToCache TEXT2INT $value $cacheName -> $fieldName")
DataStore.profileCacheStore.putString(cacheName, value.toString())
}
}
Type.Int -> {
if (value is Int) {
DataStore.profileCacheStore.putInt(cacheName, value)
}
}
Type.Bool -> {
if (value is Boolean) {
DataStore.profileCacheStore.putBoolean(cacheName, value)
}
}
}
}
val preference by lazy {
pf!!.findPreference<Preference>(cacheName)!!
}
}
| nacs/app/src/main/java/moe/matsuri/nb4a/proxy/PreferenceBinding.kt | 592572899 |
package moe.matsuri.nb4a.proxy.config
import android.os.Bundle
import androidx.preference.PreferenceDataStore
import androidx.preference.PreferenceFragmentCompat
import io.nekohasekai.sagernet.Key
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.preference.OnPreferenceDataStoreChangeListener
import io.nekohasekai.sagernet.ui.profile.ProfileSettingsActivity
import moe.matsuri.nb4a.ui.EditConfigPreference
class ConfigSettingActivity :
ProfileSettingsActivity<ConfigBean>(),
OnPreferenceDataStoreChangeListener {
private val isOutboundOnlyKey = "isOutboundOnly"
override fun createEntity() = ConfigBean()
override fun ConfigBean.init() {
// CustomBean to input
DataStore.profileCacheStore.putBoolean(isOutboundOnlyKey, type == 1)
DataStore.profileName = name
DataStore.serverConfig = config
}
override fun ConfigBean.serialize() {
// CustomBean from input
type = if (DataStore.profileCacheStore.getBoolean(isOutboundOnlyKey, false)) 1 else 0
name = DataStore.profileName
config = DataStore.serverConfig
}
override fun onPreferenceDataStoreChanged(store: PreferenceDataStore, key: String) {
if (key != Key.PROFILE_DIRTY) {
DataStore.dirty = true
}
}
private lateinit var editConfigPreference: EditConfigPreference
override fun PreferenceFragmentCompat.createPreferences(
savedInstanceState: Bundle?,
rootKey: String?,
) {
addPreferencesFromResource(R.xml.config_preferences)
editConfigPreference = findPreference(Key.SERVER_CONFIG)!!
}
override fun onResume() {
super.onResume()
if (::editConfigPreference.isInitialized) {
editConfigPreference.notifyChanged()
}
}
} | nacs/app/src/main/java/moe/matsuri/nb4a/proxy/config/ConfigSettingActivity.kt | 2063728829 |
package moe.matsuri.nb4a.proxy
import androidx.preference.PreferenceFragmentCompat
class PreferenceBindingManager {
val items = mutableListOf<PreferenceBinding>()
fun add(b: PreferenceBinding): PreferenceBinding {
items.add(b)
return b
}
fun fromCacheAll(bean: Any) {
items.forEach {
it.bean = bean
it.fromCache()
}
}
fun writeToCacheAll(bean: Any) {
items.forEach {
it.bean = bean
it.writeToCache()
}
}
fun setPreferenceFragment(pf: PreferenceFragmentCompat) {
items.forEach {
it.pf = pf
}
}
}
| nacs/app/src/main/java/moe/matsuri/nb4a/proxy/PreferenceBindingManager.kt | 2299101693 |
package moe.matsuri.nb4a.proxy.neko
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.preference.PreferenceDataStore
import androidx.preference.PreferenceFragmentCompat
import io.nekohasekai.sagernet.Key
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ktx.runOnIoDispatcher
import io.nekohasekai.sagernet.ui.profile.ProfileSettingsActivity
import moe.matsuri.nb4a.ui.Dialogs
import org.json.JSONArray
class NekoSettingActivity : ProfileSettingsActivity<NekoBean>() {
lateinit var jsi: NekoJSInterface
lateinit var jsip: NekoJSInterface.NekoProtocol
lateinit var plgId: String
lateinit var protocolId: String
var loaded = false
override fun createEntity() = NekoBean()
override fun NekoBean.init() {
if (!this@NekoSettingActivity::plgId.isInitialized) [email protected] = plgId
if (!this@NekoSettingActivity::protocolId.isInitialized) [email protected] =
protocolId
DataStore.profileCacheStore.putString("name", name)
DataStore.sharedStorage = sharedStorage.toString()
}
override fun NekoBean.serialize() {
// NekoBean from input
plgId = [email protected]
protocolId = [email protected]
sharedStorage = NekoBean.tryParseJSON(DataStore.sharedStorage)
onSharedStorageSet()
}
override fun onCreate(savedInstanceState: Bundle?) {
intent?.getStringExtra("plgId")?.apply { plgId = this }
intent?.getStringExtra("protocolId")?.apply { protocolId = this }
super.onCreate(savedInstanceState)
}
override fun PreferenceFragmentCompat.viewCreated(view: View, savedInstanceState: Bundle?) {
listView.isVisible = false
}
override fun onPreferenceDataStoreChanged(store: PreferenceDataStore, key: String) {
if (loaded && key != Key.PROFILE_DIRTY) {
DataStore.dirty = true
}
}
override fun PreferenceFragmentCompat.createPreferences(
savedInstanceState: Bundle?,
rootKey: String?,
) {
addPreferencesFromResource(R.xml.neko_preferences)
// Create a jsi
jsi = NekoJSInterface(plgId)
runOnIoDispatcher {
try {
jsi.init()
jsip = jsi.switchProtocol(protocolId)
jsi.jsObject.preferenceScreen = preferenceScreen
// Because of the Preference problem, first require the KV and then inflate the UI
jsip.setSharedStorage(DataStore.sharedStorage)
jsip.requireSetProfileCache()
val config = jsip.requirePreferenceScreenConfig()
val pref = JSONArray(config)
NekoPreferenceInflater.inflate(pref, preferenceScreen)
jsip.onPreferenceCreated()
runOnUiThread {
loaded = true
listView.isVisible = true
}
} catch (e: Exception) {
Dialogs.logExceptionAndShow(this@NekoSettingActivity, e) { finish() }
}
}
}
override suspend fun saveAndExit() {
DataStore.sharedStorage = jsip.sharedStorageFromProfileCache()
super.saveAndExit() // serialize & finish
}
override fun onDestroy() {
jsi.destroy()
super.onDestroy()
}
} | nacs/app/src/main/java/moe/matsuri/nb4a/proxy/neko/NekoSettingActivity.kt | 926812835 |
package moe.matsuri.nb4a.proxy.neko
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.ktx.getStr
import io.nekohasekai.sagernet.ktx.runOnIoDispatcher
import libcore.Libcore
import moe.matsuri.nb4a.Protocols
import moe.matsuri.nb4a.plugin.NekoPluginManager
import org.json.JSONObject
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
suspend fun parseShareLink(plgId: String, protocolId: String, link: String): NekoBean =
suspendCoroutine {
runOnIoDispatcher {
val jsi = NekoJSInterface.Default.requireJsi(plgId)
jsi.lock()
try {
jsi.init()
val jsip = jsi.switchProtocol(protocolId)
val sharedStorage = jsip.parseShareLink(link)
// NekoBean from link
val bean = NekoBean()
bean.plgId = plgId
bean.protocolId = protocolId
bean.sharedStorage = NekoBean.tryParseJSON(sharedStorage)
bean.onSharedStorageSet()
it.resume(bean)
} catch (e: Exception) {
Logs.e(e)
it.resume(NekoBean().apply {
this.plgId = plgId
this.protocolId = protocolId
})
}
jsi.unlock()
// destroy when all link parsed
}
}
fun NekoBean.shareLink(): String {
return sharedStorage.optString("shareLink")
}
// Only run in bg process
// seems no concurrent
suspend fun NekoBean.updateAllConfig(port: Int) = suspendCoroutine<Unit> {
allConfig = null
runOnIoDispatcher {
val jsi = NekoJSInterface.Default.requireJsi(plgId)
jsi.lock()
try {
jsi.init()
val jsip = jsi.switchProtocol(protocolId)
// runtime arguments
val otherArgs = mutableMapOf<String, Any>()
otherArgs["finalAddress"] = finalAddress
otherArgs["finalPort"] = finalPort
otherArgs["muxEnabled"] = Protocols.shouldEnableMux(protocolId)
otherArgs["muxConcurrency"] = DataStore.muxConcurrency
val ret = jsip.buildAllConfig(port, this@updateAllConfig, otherArgs)
// result
allConfig = JSONObject(ret)
} catch (e: Exception) {
Logs.e(e)
}
jsi.unlock()
it.resume(Unit)
// destroy when config generated / all tests finished
}
}
fun NekoBean.cacheGet(id: String): String? {
return DataStore.profileCacheStore.getString("neko_${hash()}_$id")
}
fun NekoBean.cacheSet(id: String, value: String) {
DataStore.profileCacheStore.putString("neko_${hash()}_$id", value)
}
fun NekoBean.hash(): String {
var a = plgId
a += protocolId
a += sharedStorage.toString()
return Libcore.sha256Hex(a.toByteArray())
}
// must call it to update something like serverAddress
fun NekoBean.onSharedStorageSet() {
serverAddress = sharedStorage.getStr("serverAddress")
serverPort = sharedStorage.getStr("serverPort")?.toInt() ?: 1080
if (serverAddress == null || serverAddress.isBlank()) {
serverAddress = "127.0.0.1"
}
name = sharedStorage.optString("name")
}
fun NekoBean.needBypassRootUid(): Boolean {
val p = NekoPluginManager.findProtocol(protocolId) ?: return false
return p.protocolConfig.optBoolean("needBypassRootUid")
}
fun NekoBean.haveStandardLink(): Boolean {
val p = NekoPluginManager.findProtocol(protocolId) ?: return false
return p.protocolConfig.optBoolean("haveStandardLink")
}
fun NekoBean.canShare(): Boolean {
val p = NekoPluginManager.findProtocol(protocolId) ?: return false
return p.protocolConfig.optBoolean("canShare")
}
| nacs/app/src/main/java/moe/matsuri/nb4a/proxy/neko/NekoFmt.kt | 1131599399 |
package moe.matsuri.nb4a.proxy.neko
import android.annotation.SuppressLint
import android.webkit.*
import android.widget.Toast
import androidx.preference.Preference
import androidx.preference.PreferenceScreen
import io.nekohasekai.sagernet.BuildConfig
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ktx.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.withContext
import moe.matsuri.nb4a.plugin.NekoPluginManager
import moe.matsuri.nb4a.ui.SimpleMenuPreference
import moe.matsuri.nb4a.utils.JavaUtil
import moe.matsuri.nb4a.utils.Util
import moe.matsuri.nb4a.utils.WebViewUtil
import org.json.JSONObject
import java.io.File
import java.io.FileInputStream
import java.util.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
class NekoJSInterface(val plgId: String) {
private val mutex = Mutex()
private var webView: WebView? = null
val jsObject = JsObject()
var plgConfig: JSONObject? = null
var plgConfigException: Exception? = null
val protocols = mutableMapOf<String, NekoProtocol>()
val loaded = AtomicBoolean()
suspend fun lock() {
mutex.lock(null)
}
fun unlock() {
mutex.unlock(null)
}
// load webview and js
// Return immediately when already loaded
// Return plgConfig or throw exception
suspend fun init() = withContext(Dispatchers.Main) {
initInternal()
}
@SuppressLint("SetJavaScriptEnabled")
private suspend fun initInternal() = suspendCoroutine<JSONObject> {
if (loaded.get()) {
plgConfig?.apply {
it.resume(this)
return@suspendCoroutine
}
plgConfigException?.apply {
it.resumeWithException(this)
return@suspendCoroutine
}
it.resumeWithException(Exception("wtf"))
return@suspendCoroutine
}
WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG)
NekoPluginManager.extractPlugin(plgId, false)
webView = WebView(SagerNet.application.applicationContext)
webView!!.settings.javaScriptEnabled = true
webView!!.addJavascriptInterface(jsObject, "neko")
webView!!.webViewClient = object : WebViewClient() {
// provide files
override fun shouldInterceptRequest(
view: WebView?, request: WebResourceRequest?
): WebResourceResponse {
return WebViewUtil.interceptRequest(
{ res ->
val f = File(NekoPluginManager.htmlPath(plgId), res)
if (f.exists()) {
FileInputStream(f)
} else {
null
}
},
view,
request
)
}
override fun onReceivedError(
view: WebView?, request: WebResourceRequest?, error: WebResourceError?
) {
WebViewUtil.onReceivedError(view, request, error)
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
if (loaded.getAndSet(true)) return
runOnIoDispatcher {
// Process nekoInit
var ret = ""
try {
ret = nekoInit()
val obj = JSONObject(ret)
if (!obj.getBoolean("ok")) {
throw Exception("plugin refuse to run: ${obj.optString("reason")}")
}
val min = obj.getInt("minVersion")
if (min > NekoPluginManager.managerVersion) {
throw Exception("manager version ${NekoPluginManager.managerVersion} too old, this plugin requires >= $min")
}
plgConfig = obj
NekoPluginManager.updatePlgConfig(plgId, obj)
it.resume(obj)
} catch (e: Exception) {
val e2 = Exception("nekoInit: " + e.readableMessage + "\n\n" + ret)
plgConfigException = e2
it.resumeWithException(e2)
}
}
}
}
webView!!.loadUrl("http://$plgId/plugin.html")
}
// Android call JS
private suspend fun callJS(script: String): String = suspendCoroutine {
val jsLatch = CountDownLatch(1)
var jsReceivedValue = ""
runOnMainDispatcher {
if (webView != null) {
webView!!.evaluateJavascript(script) { value ->
jsReceivedValue = value
jsLatch.countDown()
}
} else {
jsReceivedValue = "webView is null"
jsLatch.countDown()
}
}
jsLatch.await(5, TimeUnit.SECONDS)
// evaluateJavascript escapes Javascript's String
jsReceivedValue = JavaUtil.unescapeString(jsReceivedValue.removeSurrounding("\""))
if (BuildConfig.DEBUG) Logs.d("$script: $jsReceivedValue")
it.resume(jsReceivedValue)
}
// call once
private suspend fun nekoInit(): String {
val sendData = JSONObject()
sendData.put("lang", Locale.getDefault().toLanguageTag())
sendData.put("plgId", plgId)
sendData.put("managerVersion", NekoPluginManager.managerVersion)
return callJS(
"nekoInit(\"${
Util.b64EncodeUrlSafe(
sendData.toString().toByteArray()
)
}\")"
)
}
fun switchProtocol(id: String): NekoProtocol {
lateinit var p: NekoProtocol
if (protocols.containsKey(id)) {
p = protocols[id]!!
} else {
p = NekoProtocol(id) { callJS(it) }
protocols[id] = p
}
jsObject.protocol = p
return p
}
suspend fun getAbout(): String {
return callJS("nekoAbout()")
}
inner class NekoProtocol(val protocolId: String, val callJS: suspend (String) -> String) {
private suspend fun callProtocol(method: String, b64Str: String?): String {
var arg = ""
if (b64Str != null) {
arg = "\"" + b64Str + "\""
}
return callJS("nekoProtocol(\"$protocolId\").$method($arg)")
}
suspend fun buildAllConfig(
port: Int, bean: NekoBean, otherArgs: Map<String, Any>?
): String {
val sendData = JSONObject()
sendData.put("port", port)
sendData.put(
"sharedStorage",
Util.b64EncodeUrlSafe(bean.sharedStorage.toString().toByteArray())
)
otherArgs?.forEach { (t, u) -> sendData.put(t, u) }
return callProtocol(
"buildAllConfig", Util.b64EncodeUrlSafe(sendData.toString().toByteArray())
)
}
suspend fun parseShareLink(shareLink: String): String {
val sendData = JSONObject()
sendData.put("shareLink", shareLink)
return callProtocol(
"parseShareLink", Util.b64EncodeUrlSafe(sendData.toString().toByteArray())
)
}
// UI Interface
suspend fun setSharedStorage(sharedStorage: String) {
callProtocol(
"setSharedStorage",
Util.b64EncodeUrlSafe(sharedStorage.toByteArray())
)
}
suspend fun requireSetProfileCache() {
callProtocol("requireSetProfileCache", null)
}
suspend fun requirePreferenceScreenConfig(): String {
return callProtocol("requirePreferenceScreenConfig", null)
}
suspend fun sharedStorageFromProfileCache(): String {
return callProtocol("sharedStorageFromProfileCache", null)
}
suspend fun onPreferenceCreated() {
callProtocol("onPreferenceCreated", null)
}
suspend fun onPreferenceChanged(key: String, v: Any) {
val sendData = JSONObject()
sendData.put("key", key)
sendData.put("newValue", v)
callProtocol(
"onPreferenceChanged",
Util.b64EncodeUrlSafe(sendData.toString().toByteArray())
)
}
}
inner class JsObject {
var preferenceScreen: PreferenceScreen? = null
var protocol: NekoProtocol? = null
// JS call Android
@JavascriptInterface
fun toast(s: String) {
Toast.makeText(SagerNet.application.applicationContext, s, Toast.LENGTH_SHORT).show()
}
@JavascriptInterface
fun logError(s: String) {
Logs.e("logError: $s")
}
@JavascriptInterface
fun setPreferenceVisibility(key: String, isVisible: Boolean) {
runBlockingOnMainDispatcher {
preferenceScreen?.findPreference<Preference>(key)?.isVisible = isVisible
}
}
@JavascriptInterface
fun setPreferenceTitle(key: String, title: String) {
runBlockingOnMainDispatcher {
preferenceScreen?.findPreference<Preference>(key)?.title = title
}
}
@JavascriptInterface
fun setMenu(key: String, entries: String) {
runBlockingOnMainDispatcher {
preferenceScreen?.findPreference<SimpleMenuPreference>(key)?.apply {
NekoPreferenceInflater.setMenu(this, JSONObject(entries))
}
}
}
@JavascriptInterface
fun listenOnPreferenceChanged(key: String) {
preferenceScreen?.findPreference<Preference>(key)
?.setOnPreferenceChangeListener { preference, newValue ->
runOnIoDispatcher {
protocol?.onPreferenceChanged(preference.key, newValue)
}
true
}
}
@JavascriptInterface
fun setKV(type: Int, key: String, jsonStr: String) {
try {
val v = JSONObject(jsonStr)
when (type) {
0 -> DataStore.profileCacheStore.putBoolean(key, v.getBoolean("v"))
1 -> DataStore.profileCacheStore.putFloat(key, v.getDouble("v").toFloat())
2 -> DataStore.profileCacheStore.putInt(key, v.getInt("v"))
3 -> DataStore.profileCacheStore.putLong(key, v.getLong("v"))
4 -> DataStore.profileCacheStore.putString(key, v.getString("v"))
}
} catch (e: Exception) {
Logs.e("setKV: $e")
}
}
@JavascriptInterface
fun getKV(type: Int, key: String): String {
val v = JSONObject()
try {
when (type) {
0 -> v.put("v", DataStore.profileCacheStore.getBoolean(key))
1 -> v.put("v", DataStore.profileCacheStore.getFloat(key))
2 -> v.put("v", DataStore.profileCacheStore.getInt(key))
3 -> v.put("v", DataStore.profileCacheStore.getLong(key))
4 -> v.put("v", DataStore.profileCacheStore.getString(key))
}
} catch (e: Exception) {
Logs.e("getKV: $e")
}
return v.toString()
}
}
fun destroy() {
webView?.onPause()
webView?.removeAllViews()
webView?.destroy()
webView = null
}
suspend fun destorySuspend() = withContext(Dispatchers.Main) {
destroy()
}
object Default {
val map = mutableMapOf<String, NekoJSInterface>()
suspend fun destroyJsi(plgId: String) = withContext(Dispatchers.Main) {
if (map.containsKey(plgId)) {
map[plgId]!!.destroy()
map.remove(plgId)
}
}
// now it's manually managed
suspend fun destroyAllJsi() = withContext(Dispatchers.Main) {
map.forEach { (t, u) ->
u.destroy()
map.remove(t)
}
}
suspend fun requireJsi(plgId: String): NekoJSInterface = withContext(Dispatchers.Main) {
lateinit var jsi: NekoJSInterface
if (map.containsKey(plgId)) {
jsi = map[plgId]!!
} else {
jsi = NekoJSInterface(plgId)
map[plgId] = jsi
}
return@withContext jsi
}
}
}
| nacs/app/src/main/java/moe/matsuri/nb4a/proxy/neko/NekoJSInterface.kt | 835217538 |
package moe.matsuri.nb4a.proxy.neko
import androidx.preference.*
import io.nekohasekai.sagernet.database.preference.EditTextPreferenceModifiers
import io.nekohasekai.sagernet.ktx.forEach
import io.nekohasekai.sagernet.ktx.getStr
import io.nekohasekai.sagernet.ui.profile.ProfileSettingsActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import moe.matsuri.nb4a.ui.SimpleMenuPreference
import moe.matsuri.nb4a.utils.getDrawableByName
import org.json.JSONArray
import org.json.JSONObject
object NekoPreferenceInflater {
suspend fun inflate(pref: JSONArray, preferenceScreen: PreferenceScreen) =
withContext(Dispatchers.Main) {
val context = preferenceScreen.context
pref.forEach { _, category ->
category as JSONObject
val preferenceCategory = PreferenceCategory(context)
preferenceScreen.addPreference(preferenceCategory)
category.getStr("key")?.apply { preferenceCategory.key = this }
category.getStr("title")?.apply { preferenceCategory.title = this }
category.optJSONArray("preferences")?.forEach { _, any ->
if (any is JSONObject) {
lateinit var p: Preference
// Create Preference
when (any.getStr("type")) {
"EditTextPreference" -> {
p = EditTextPreference(context).apply {
when (any.getStr("summaryProvider")) {
null -> summaryProvider =
EditTextPreference.SimpleSummaryProvider.getInstance()
"PasswordSummaryProvider" -> summaryProvider =
ProfileSettingsActivity.PasswordSummaryProvider
}
when (any.getStr("EditTextPreferenceModifiers")) {
"Monospace" -> setOnBindEditTextListener(
EditTextPreferenceModifiers.Monospace
)
"Hosts" -> setOnBindEditTextListener(
EditTextPreferenceModifiers.Hosts
)
"Port" -> setOnBindEditTextListener(
EditTextPreferenceModifiers.Port
)
"Number" -> setOnBindEditTextListener(
EditTextPreferenceModifiers.Number
)
}
}
}
"SwitchPreference" -> {
p = SwitchPreference(context)
}
"SimpleMenuPreference" -> {
p = SimpleMenuPreference(context).apply {
val entries = any.optJSONObject("entries")
if (entries != null) setMenu(this, entries)
}
}
}
// Set key & title
p.key = any.getString("key")
any.getStr("title")?.apply { p.title = this }
// Set icon
any.getStr("icon")?.apply {
p.icon = context.getDrawableByName(this)
}
// Set summary
any.getStr("summary")?.apply {
p.summary = this
}
// Add to category
preferenceCategory.addPreference(p)
}
}
}
}
fun setMenu(p: SimpleMenuPreference, entries: JSONObject) {
val menuEntries = mutableListOf<String>()
val menuEntryValues = mutableListOf<String>()
entries.forEach { s, b ->
menuEntryValues.add(s)
menuEntries.add(b as String)
}
entries.apply {
p.entries = menuEntries.toTypedArray()
p.entryValues = menuEntryValues.toTypedArray()
}
}
} | nacs/app/src/main/java/moe/matsuri/nb4a/proxy/neko/NekoPreferenceInflater.kt | 241916416 |
package moe.matsuri.nb4a.plugin
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.pm.ProviderInfo
import android.net.Uri
import android.os.Build
import android.widget.Toast
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.plugin.PluginManager.loadString
import io.nekohasekai.sagernet.utils.PackageCache
object Plugins {
const val AUTHORITIES_PREFIX_SEKAI_EXE = "io.nekohasekai.sagernet.plugin."
const val AUTHORITIES_PREFIX_NEKO_EXE = "moe.matsuri.exe."
const val AUTHORITIES_PREFIX_NEKO_PLUGIN = "moe.matsuri.plugin."
const val ACTION_NATIVE_PLUGIN = "io.nekohasekai.sagernet.plugin.ACTION_NATIVE_PLUGIN"
const val METADATA_KEY_ID = "io.nekohasekai.sagernet.plugin.id"
const val METADATA_KEY_EXECUTABLE_PATH = "io.nekohasekai.sagernet.plugin.executable_path"
fun isExeOrPlugin(pkg: PackageInfo): Boolean {
if (pkg.providers == null || pkg.providers.isEmpty()) return false
val provider = pkg.providers[0] ?: return false
val auth = provider.authority ?: return false
return auth.startsWith(AUTHORITIES_PREFIX_SEKAI_EXE)
|| auth.startsWith(AUTHORITIES_PREFIX_NEKO_EXE)
|| auth.startsWith(AUTHORITIES_PREFIX_NEKO_PLUGIN)
}
fun preferExePrefix(): String {
return AUTHORITIES_PREFIX_NEKO_EXE
}
fun isUsingMatsuriExe(pluginId: String): Boolean {
getPlugin(pluginId)?.apply {
if (authority.startsWith(AUTHORITIES_PREFIX_NEKO_EXE)) {
return true
}
}
return false;
}
fun displayExeProvider(pkgName: String): String {
return if (pkgName.startsWith(AUTHORITIES_PREFIX_SEKAI_EXE)) {
"SagerNet"
} else if (pkgName.startsWith(AUTHORITIES_PREFIX_NEKO_EXE)) {
"Matsuri"
} else {
"Unknown"
}
}
fun getPlugin(pluginId: String): ProviderInfo? {
if (pluginId.isBlank()) return null
getPluginExternal(pluginId)?.let { return it }
// internal so
return ProviderInfo().apply { authority = AUTHORITIES_PREFIX_NEKO_EXE }
}
fun getPluginExternal(pluginId: String): ProviderInfo? {
if (pluginId.isBlank()) return null
// try queryIntentContentProviders
var providers = getExtPluginOld(pluginId)
// try PackageCache
if (providers.isEmpty()) providers = getExtPluginNew(pluginId)
// not found
if (providers.isEmpty()) return null
if (providers.size > 1) {
val prefer = providers.filter {
it.authority.startsWith(preferExePrefix())
}
if (prefer.size == 1) providers = prefer
}
if (providers.size > 1) {
val message =
"Conflicting plugins found from: ${providers.joinToString { it.packageName }}"
Toast.makeText(SagerNet.application, message, Toast.LENGTH_LONG).show()
}
return providers[0]
}
private fun getExtPluginNew(pluginId: String): List<ProviderInfo> {
PackageCache.awaitLoadSync()
val pkgs = PackageCache.installedPluginPackages
.map { it.value }
.filter { it.providers[0].loadString(METADATA_KEY_ID) == pluginId }
return pkgs.map { it.providers[0] }
}
private fun buildUri(id: String, auth: String) = Uri.Builder()
.scheme("plugin")
.authority(auth)
.path("/$id")
.build()
private fun getExtPluginOld(pluginId: String): List<ProviderInfo> {
var flags = PackageManager.GET_META_DATA
if (Build.VERSION.SDK_INT >= 24) {
flags =
flags or PackageManager.MATCH_DIRECT_BOOT_UNAWARE or PackageManager.MATCH_DIRECT_BOOT_AWARE
}
val list1 = SagerNet.application.packageManager.queryIntentContentProviders(
Intent(ACTION_NATIVE_PLUGIN, buildUri(pluginId, "io.nekohasekai.sagernet")), flags
)
val list2 = SagerNet.application.packageManager.queryIntentContentProviders(
Intent(ACTION_NATIVE_PLUGIN, buildUri(pluginId, "moe.matsuri.lite")), flags
)
return (list1 + list2).mapNotNull {
it.providerInfo
}.filter { it.exported }
}
}
| nacs/app/src/main/java/moe/matsuri/nb4a/plugin/Plugins.kt | 672862035 |
package moe.matsuri.nb4a.plugin
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.bg.BaseService
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ktx.forEach
import io.nekohasekai.sagernet.utils.PackageCache
import moe.matsuri.nb4a.proxy.neko.NekoJSInterface
import okhttp3.internal.closeQuietly
import org.json.JSONObject
import java.io.File
import java.util.zip.CRC32
import java.util.zip.ZipFile
object NekoPluginManager {
const val managerVersion = 2
val plugins get() = DataStore.nekoPlugins.split("\n").filter { it.isNotBlank() }
// plgID to plgConfig object
fun getManagedPlugins(): Map<String, JSONObject> {
val ret = mutableMapOf<String, JSONObject>()
plugins.forEach {
tryGetPlgConfig(it)?.apply {
ret[it] = this
}
}
return ret
}
class Protocol(
val protocolId: String, val plgId: String, val protocolConfig: JSONObject
)
fun getProtocols(): List<Protocol> {
val ret = mutableListOf<Protocol>()
getManagedPlugins().forEach { (t, u) ->
u.optJSONArray("protocols")?.forEach { _, any ->
if (any is JSONObject) {
val name = any.optString("protocolId")
ret.add(Protocol(name, t, any))
}
}
}
return ret
}
fun findProtocol(protocolId: String): Protocol? {
getManagedPlugins().forEach { (t, u) ->
u.optJSONArray("protocols")?.forEach { _, any ->
if (any is JSONObject) {
if (protocolId == any.optString("protocolId")) {
return Protocol(protocolId, t, any)
}
}
}
}
return null
}
fun removeManagedPlugin(plgId: String) {
DataStore.configurationStore.remove(plgId)
val dir = File(SagerNet.application.filesDir.absolutePath + "/plugins/" + plgId)
if (dir.exists()) {
dir.deleteRecursively()
}
}
fun extractPlugin(plgId: String, install: Boolean) {
val app = PackageCache.installedApps[plgId] ?: return
val apk = File(app.publicSourceDir)
if (!apk.exists()) {
return
}
if (!install && !plugins.contains(plgId)) {
return
}
val zipFile = ZipFile(apk)
val unzipDir = File(SagerNet.application.filesDir.absolutePath + "/plugins/" + plgId)
unzipDir.mkdirs()
for (entry in zipFile.entries()) {
if (entry.name.startsWith("assets/")) {
val relativePath = entry.name.removePrefix("assets/")
val outFile = File(unzipDir, relativePath)
if (entry.isDirectory) {
outFile.mkdirs()
continue
}
if (outFile.isDirectory) {
outFile.delete()
} else if (outFile.exists()) {
val checksum = CRC32()
checksum.update(outFile.readBytes())
if (checksum.value == entry.crc) {
continue
}
}
val input = zipFile.getInputStream(entry)
outFile.outputStream().use {
input.copyTo(it)
}
}
}
zipFile.closeQuietly()
}
suspend fun installPlugin(plgId: String) {
if (plgId == "moe.matsuri.plugin.singbox" || plgId == "moe.matsuri.plugin.xray") {
throw Exception("This plugin is deprecated")
}
extractPlugin(plgId, true)
NekoJSInterface.Default.destroyJsi(plgId)
NekoJSInterface.Default.requireJsi(plgId).init()
NekoJSInterface.Default.destroyJsi(plgId)
}
const val PLUGIN_APP_VERSION = "_v_vc"
const val PLUGIN_APP_VERSION_NAME = "_v_vn"
// Return null if not managed
fun tryGetPlgConfig(plgId: String): JSONObject? {
return try {
JSONObject(DataStore.configurationStore.getString(plgId)!!)
} catch (e: Exception) {
null
}
}
fun updatePlgConfig(plgId: String, plgConfig: JSONObject) {
PackageCache.installedPluginPackages[plgId]?.apply {
// longVersionCode requires API 28
// plgConfig.put(PLUGIN_APP_VERSION, versionCode)
plgConfig.put(PLUGIN_APP_VERSION_NAME, versionName)
}
DataStore.configurationStore.putString(plgId, plgConfig.toString())
}
fun htmlPath(plgId: String): String {
val htmlFile = File(SagerNet.application.filesDir.absolutePath + "/plugins/" + plgId)
return htmlFile.absolutePath
}
class PluginInternalException(val protocolId: String) : Exception(),
BaseService.ExpectedException {
override fun getLocalizedMessage() =
SagerNet.application.getString(R.string.neko_plugin_internal_error, protocolId)
}
} | nacs/app/src/main/java/moe/matsuri/nb4a/plugin/NekoPluginManager.kt | 1399361963 |
package moe.matsuri.nb4a.utils
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.Editable
import android.util.Base64
import io.nekohasekai.sagernet.ktx.Logs
import java.net.URLDecoder
import java.net.URLEncoder
import java.util.*
// Copy form v2rayNG to parse their stupid format
object NGUtil {
/**
* convert string to editalbe for kotlin
*
* @param text
* @return
*/
fun getEditable(text: String): Editable {
return Editable.Factory.getInstance().newEditable(text)
}
/**
* find value in array position
*/
fun arrayFind(array: Array<out String>, value: String): Int {
for (i in array.indices) {
if (array[i] == value) {
return i
}
}
return -1
}
/**
* parseInt
*/
fun parseInt(str: String): Int {
return try {
Integer.parseInt(str)
} catch (e: Exception) {
e.printStackTrace()
0
}
}
/**
* get text from clipboard
*/
fun getClipboard(context: Context): String {
return try {
val cmb = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
cmb.primaryClip?.getItemAt(0)?.text.toString()
} catch (e: Exception) {
e.printStackTrace()
""
}
}
/**
* set text to clipboard
*/
fun setClipboard(context: Context, content: String) {
try {
val cmb = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clipData = ClipData.newPlainText(null, content)
cmb.setPrimaryClip(clipData)
} catch (e: Exception) {
e.printStackTrace()
}
}
/**
* base64 decode
*/
fun decode(text: String): String {
tryDecodeBase64(text)?.let { return it }
if (text.endsWith('=')) {
// try again for some loosely formatted base64
tryDecodeBase64(text.trimEnd('='))?.let { return it }
}
return ""
}
fun tryDecodeBase64(text: String): String? {
try {
return Base64.decode(text, Base64.NO_WRAP).toString(charset("UTF-8"))
} catch (e: Exception) {
Logs.i("Parse base64 standard failed $e")
}
try {
return Base64.decode(text, Base64.NO_WRAP.or(Base64.URL_SAFE))
.toString(charset("UTF-8"))
} catch (e: Exception) {
Logs.i("Parse base64 url safe failed $e")
}
return null
}
/**
* base64 encode
*/
fun encode(text: String): String {
return try {
Base64.encodeToString(text.toByteArray(charset("UTF-8")), Base64.NO_WRAP)
} catch (e: Exception) {
e.printStackTrace()
""
}
}
/**
* is ip address
*/
fun isIpAddress(value: String): Boolean {
try {
var addr = value
if (addr.isEmpty() || addr.isBlank()) {
return false
}
//CIDR
if (addr.indexOf("/") > 0) {
val arr = addr.split("/")
if (arr.count() == 2 && Integer.parseInt(arr[1]) > 0) {
addr = arr[0]
}
}
// "::ffff:192.168.173.22"
// "[::ffff:192.168.173.22]:80"
if (addr.startsWith("::ffff:") && '.' in addr) {
addr = addr.drop(7)
} else if (addr.startsWith("[::ffff:") && '.' in addr) {
addr = addr.drop(8).replace("]", "")
}
// addr = addr.toLowerCase()
val octets = addr.split('.').toTypedArray()
if (octets.size == 4) {
if (octets[3].indexOf(":") > 0) {
addr = addr.substring(0, addr.indexOf(":"))
}
return isIpv4Address(addr)
}
// Ipv6addr [2001:abc::123]:8080
return isIpv6Address(addr)
} catch (e: Exception) {
e.printStackTrace()
return false
}
}
fun isPureIpAddress(value: String): Boolean {
return (isIpv4Address(value) || isIpv6Address(value))
}
fun isIpv4Address(value: String): Boolean {
val regV4 =
Regex("^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$")
return regV4.matches(value)
}
fun isIpv6Address(value: String): Boolean {
var addr = value
if (addr.indexOf("[") == 0 && addr.lastIndexOf("]") > 0) {
addr = addr.drop(1)
addr = addr.dropLast(addr.count() - addr.lastIndexOf("]"))
}
val regV6 =
Regex("^((?:[0-9A-Fa-f]{1,4}))?((?::[0-9A-Fa-f]{1,4}))*::((?:[0-9A-Fa-f]{1,4}))?((?::[0-9A-Fa-f]{1,4}))*|((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4})){7}$")
return regV6.matches(addr)
}
private fun isCoreDNSAddress(s: String): Boolean {
return s.startsWith("https") || s.startsWith("tcp") || s.startsWith("quic")
}
fun openUri(context: Context, uriString: String) {
val uri = Uri.parse(uriString)
context.startActivity(Intent(Intent.ACTION_VIEW, uri))
}
/**
* uuid
*/
fun getUuid(): String {
return try {
UUID.randomUUID().toString().replace("-", "")
} catch (e: Exception) {
e.printStackTrace()
""
}
}
fun urlDecode(url: String): String {
return try {
URLDecoder.decode(url, "UTF-8")
} catch (e: Exception) {
url
}
}
fun urlEncode(url: String): String {
return try {
URLEncoder.encode(url, "UTF-8")
} catch (e: Exception) {
e.printStackTrace()
url
}
}
/**
* package path
*/
fun packagePath(context: Context): String {
var path = context.filesDir.toString()
path = path.replace("files", "")
//path += "tun2socks"
return path
}
/**
* readTextFromAssets
*/
fun readTextFromAssets(context: Context, fileName: String): String {
val content = context.assets.open(fileName).bufferedReader().use {
it.readText()
}
return content
}
} | nacs/app/src/main/java/moe/matsuri/nb4a/utils/NGUtil.kt | 2746865047 |
package moe.matsuri.nb4a.utils
import android.os.Build
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import io.nekohasekai.sagernet.ktx.Logs
import java.io.ByteArrayInputStream
import java.io.InputStream
object WebViewUtil {
fun onReceivedError(
view: WebView?, request: WebResourceRequest?, error: WebResourceError?
) {
if (Build.VERSION.SDK_INT >= 23 && error != null) {
Logs.e("WebView error description: ${error.description}")
}
Logs.e("WebView error: ${error.toString()}")
}
fun interceptRequest(
res: (String) -> InputStream?, view: WebView?, request: WebResourceRequest?
): WebResourceResponse {
val path = request?.url?.path ?: "404"
val input = res(path)
var mime = "text/plain"
if (path.endsWith(".js")) mime = "application/javascript"
if (path.endsWith(".html")) mime = "text/html"
return if (input != null) {
WebResourceResponse(mime, "UTF-8", input)
} else {
WebResourceResponse(
"text/plain", "UTF-8", ByteArrayInputStream("".toByteArray())
)
}
}
}
| nacs/app/src/main/java/moe/matsuri/nb4a/utils/WebViewUtil.kt | 80724283 |
package moe.matsuri.nb4a.utils
import android.content.Context
import android.content.Intent
import androidx.core.content.FileProvider
import io.nekohasekai.sagernet.BuildConfig
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ktx.use
import io.nekohasekai.sagernet.utils.CrashHandler
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
object SendLog {
// Create full log and send
fun sendLog(context: Context, title: String) {
val logFile = File.createTempFile(
"$title ",
".log",
File(app.cacheDir, "log").also { it.mkdirs() })
var report = CrashHandler.buildReportHeader()
report += "Logcat: \n\n"
logFile.writeText(report)
try {
Runtime.getRuntime().exec(arrayOf("logcat", "-d")).inputStream.use(
FileOutputStream(
logFile, true
)
)
logFile.appendText("\n")
} catch (e: IOException) {
Logs.w(e)
logFile.appendText("Export logcat error: " + CrashHandler.formatThrowable(e))
}
logFile.appendText("\n")
logFile.appendBytes(getNekoLog(0))
context.startActivity(
Intent.createChooser(
Intent(Intent.ACTION_SEND).setType("text/x-log")
.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
.putExtra(
Intent.EXTRA_STREAM, FileProvider.getUriForFile(
context, BuildConfig.APPLICATION_ID + ".cache", logFile
)
), context.getString(R.string.abc_shareactionprovider_share_with)
)
)
}
// Get log bytes from neko.log
fun getNekoLog(max: Long): ByteArray {
return try {
val file = File(
SagerNet.application.cacheDir,
"neko.log"
)
val len = file.length()
val stream = FileInputStream(file)
if (max in 1 until len) {
stream.skip(len - max) // TODO string?
}
stream.use { it.readBytes() }
} catch (e: Exception) {
e.stackTraceToString().toByteArray()
}
}
}
| nacs/app/src/main/java/moe/matsuri/nb4a/utils/SendLog.kt | 2388125883 |
package moe.matsuri.nb4a.utils
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.ProxyEntity
import io.nekohasekai.sagernet.database.SagerDatabase
import libcore.Libcore
object LibcoreUtil {
fun resetAllConnections(system: Boolean) {
if (DataStore.serviceState.started) {
val proxy = SagerDatabase.proxyDao.getById(DataStore.currentProfile)
if (proxy?.type == ProxyEntity.TYPE_TUIC) {
return
}
}
Libcore.resetAllConnections(system)
}
}
| nacs/app/src/main/java/moe/matsuri/nb4a/utils/LibcoreUtil.kt | 2745970463 |
package moe.matsuri.nb4a.utils
import android.annotation.SuppressLint
import android.content.Context
import android.util.Base64
import java.io.ByteArrayOutputStream
import java.text.SimpleDateFormat
import java.util.*
import java.util.zip.Deflater
import java.util.zip.Inflater
object Util {
/**
* 取两个文本之间的文本值
*
* @param text 源文本 比如:欲取全文本为 12345
* @param left 文本前面
* @param right 后面文本
* @return 返回 String
*/
fun getSubString(text: String, left: String?, right: String?): String {
var zLen: Int
if (left.isNullOrEmpty()) {
zLen = 0
} else {
zLen = text.indexOf(left)
if (zLen > -1) {
zLen += left.length
} else {
zLen = 0
}
}
var yLen = if (right == null) -1 else text.indexOf(right, zLen)
if (yLen < 0 || right.isNullOrEmpty()) {
yLen = text.length
}
return text.substring(zLen, yLen)
}
// Base64 for all
fun b64EncodeUrlSafe(s: String): String {
return b64EncodeUrlSafe(s.toByteArray())
}
fun b64EncodeUrlSafe(b: ByteArray): String {
return String(Base64.encode(b, Base64.NO_PADDING or Base64.NO_WRAP or Base64.URL_SAFE))
}
// v2rayN Style
fun b64EncodeOneLine(b: ByteArray): String {
return String(Base64.encode(b, Base64.NO_WRAP))
}
fun b64EncodeDefault(b: ByteArray): String {
return String(Base64.encode(b, Base64.DEFAULT))
}
fun b64Decode(b: String): ByteArray {
var ret: ByteArray? = null
// padding 自动处理,不用理
// URLSafe 需要替换这两个,不要用 URL_SAFE 否则处理非 Safe 的时候会乱码
val str = b.replace("-", "+").replace("_", "/")
val flags = listOf(
Base64.DEFAULT, // 多行
Base64.NO_WRAP, // 单行
)
for (flag in flags) {
try {
ret = Base64.decode(str, flag)
} catch (_: Exception) {
}
if (ret != null) return ret
}
throw IllegalStateException("Cannot decode base64")
}
fun zlibCompress(input: ByteArray, level: Int): ByteArray {
// Compress the bytes
// 1 to 4 bytes/char for UTF-8
val output = ByteArray(input.size * 4)
val compressor = Deflater(level).apply {
setInput(input)
finish()
}
val compressedDataLength: Int = compressor.deflate(output)
compressor.end()
return output.copyOfRange(0, compressedDataLength)
}
fun zlibDecompress(input: ByteArray): ByteArray {
val inflater = Inflater()
val outputStream = ByteArrayOutputStream()
return outputStream.use {
val buffer = ByteArray(1024)
inflater.setInput(input)
var count = -1
while (count != 0) {
count = inflater.inflate(buffer)
outputStream.write(buffer, 0, count)
}
inflater.end()
outputStream.toByteArray()
}
}
fun mergeJSON(j: String, to: MutableMap<String, Any>) {
if (j.isBlank()) return
val m = JavaUtil.gson.fromJson(j, to.javaClass)
m.forEach { (k, v) ->
if (v is Map<*, *> && to[k] is Map<*, *>) {
val currentMap = (to[k] as Map<*, *>).toMutableMap()
currentMap += v
to[k] = currentMap
} else {
to[k] = v
}
}
}
// Format Time
@SuppressLint("SimpleDateFormat")
val sdf1 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
fun timeStamp2Text(t: Long): String {
return sdf1.format(Date(t))
}
fun tryToSetField(o: Any, name: String, value: Any) {
try {
o.javaClass.getField(name).set(o, value)
} catch (_: Exception) {
}
}
@SuppressLint("WrongConstant")
fun collapseStatusBar(context: Context) {
try {
val statusBarManager = context.getSystemService("statusbar")
val collapse = statusBarManager.javaClass.getMethod("collapsePanels")
collapse.invoke(statusBarManager)
} catch (_: Exception) {
}
}
}
| nacs/app/src/main/java/moe/matsuri/nb4a/utils/Util.kt | 3584710514 |
package moe.matsuri.nb4a.utils
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import androidx.appcompat.content.res.AppCompatResources
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.ktx.Logs
import java.io.File
// SagerNet Class
const val KB = 1024L
const val MB = KB * 1024
const val GB = MB * 1024
fun SagerNet.cleanWebview() {
var pathToClean = "app_webview"
if (isBgProcess) pathToClean += "_$process"
try {
val dataDir = filesDir.parentFile!!
File(dataDir, "$pathToClean/BrowserMetrics").recreate(true)
File(dataDir, "$pathToClean/BrowserMetrics-spare.pma").recreate(false)
} catch (e: Exception) {
Logs.e(e)
}
}
fun File.recreate(dir: Boolean) {
if (parentFile?.isDirectory != true) return
if (dir && !isFile) {
if (exists()) deleteRecursively()
createNewFile()
} else if (!dir && !isDirectory) {
if (exists()) delete()
mkdir()
}
}
// Context utils
@SuppressLint("DiscouragedApi")
fun Context.getDrawableByName(name: String?): Drawable? {
val resourceId: Int = resources.getIdentifier(name, "drawable", packageName)
return AppCompatResources.getDrawable(this, resourceId)
}
// Traffic display
fun Long.toBytesString(): String {
val size = this.toDouble()
return when {
this >= GB -> String.format("%.2f GiB", size / GB)
this >= MB -> String.format("%.2f MiB", size / MB)
this >= KB -> String.format("%.2f KiB", size / KB)
else -> "$this Bytes"
}
}
// List
fun String.listByLineOrComma(): List<String> {
return this.split(",", "\n").map { it.trim() }.filter { it.isNotEmpty() }
}
| nacs/app/src/main/java/moe/matsuri/nb4a/utils/KotlinUtil.kt | 415048454 |
package moe.matsuri.nb4a
import android.content.Context
import android.os.Build
import androidx.annotation.RequiresApi
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.bg.ServiceNotification
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.SagerDatabase
import io.nekohasekai.sagernet.ktx.Logs
import io.nekohasekai.sagernet.ktx.runOnDefaultDispatcher
import io.nekohasekai.sagernet.utils.PackageCache
import libcore.BoxPlatformInterface
import libcore.NB4AInterface
import libcore.WIFIState
import moe.matsuri.nb4a.utils.LibcoreUtil
import java.net.InetSocketAddress
class NativeInterface : BoxPlatformInterface, NB4AInterface {
// libbox interface
override fun autoDetectInterfaceControl(fd: Int) {
DataStore.vpnService?.protect(fd)
}
override fun openTun(singTunOptionsJson: String, tunPlatformOptionsJson: String): Long {
if (DataStore.vpnService == null) {
throw Exception("no VpnService")
}
return DataStore.vpnService!!.startVpn(singTunOptionsJson, tunPlatformOptionsJson).toLong()
}
override fun useProcFS(): Boolean {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun findConnectionOwner(
ipProto: Int, srcIp: String, srcPort: Int, destIp: String, destPort: Int
): Int {
return SagerNet.connectivity.getConnectionOwnerUid(
ipProto, InetSocketAddress(srcIp, srcPort), InetSocketAddress(destIp, destPort)
)
}
override fun packageNameByUid(uid: Int): String {
PackageCache.awaitLoadSync()
if (uid <= 1000L) {
return "android"
}
val packageNames = PackageCache.uidMap[uid]
if (!packageNames.isNullOrEmpty()) for (packageName in packageNames) {
return packageName
}
error("unknown uid $uid")
}
override fun uidByPackageName(packageName: String): Int {
PackageCache.awaitLoadSync()
return PackageCache[packageName] ?: 0
}
// nb4a interface
override fun useOfficialAssets(): Boolean {
return DataStore.rulesProvider == 0
}
override fun selector_OnProxySelected(selectorTag: String, tag: String) {
if (selectorTag != "proxy") {
Logs.d("other selector: $selectorTag")
return
}
LibcoreUtil.resetAllConnections(true)
DataStore.baseService?.apply {
runOnDefaultDispatcher {
val id = data.proxy!!.config.profileTagMap
.filterValues { it == tag }.keys.firstOrNull() ?: -1
val ent = SagerDatabase.proxyDao.getById(id) ?: return@runOnDefaultDispatcher
// traffic & title
data.proxy?.apply {
looper?.selectMain(id)
displayProfileName = ServiceNotification.genTitle(ent)
data.notification?.postNotificationTitle(displayProfileName)
}
// post binder
data.binder.broadcast { b ->
b.cbSelectorUpdate(id)
}
}
}
}
// TODO new API
override fun readWIFIState(): WIFIState? {
val wifiInfo = SagerNet.wifiManager.connectionInfo ?: return null
var ssid = wifiInfo.ssid
if (ssid.startsWith("\"") && ssid.endsWith("\"")) {
ssid = ssid.substring(1, ssid.length - 1)
}
return WIFIState(ssid, wifiInfo.bssid)
}
}
| nacs/app/src/main/java/moe/matsuri/nb4a/NativeInterface.kt | 1750850692 |
package moe.matsuri.nb4a
import io.nekohasekai.sagernet.database.DataStore
import android.content.Context
import java.io.File
object SingBoxOptionsUtil {
fun domainStrategy(tag: String): String {
fun auto2AsIs(key: String): String {
return (DataStore.configurationStore.getString(key) ?: "").replace("auto", "")
}
return when (tag) {
"dns-remote" -> {
auto2AsIs("domain_strategy_for_remote")
}
"dns-direct" -> {
auto2AsIs("domain_strategy_for_direct")
}
// server
else -> {
auto2AsIs("domain_strategy_for_server")
}
}
}
}
fun SingBoxOptions.DNSRule_DefaultOptions.makeSingBoxRule(list: List<String>) {
geosite = mutableListOf<String>()
domain = mutableListOf<String>()
domain_suffix = mutableListOf<String>()
domain_regex = mutableListOf<String>()
domain_keyword = mutableListOf<String>()
rule_set = mutableListOf<String>()
wifi_ssid = mutableListOf<String>()
wifi_bssid = mutableListOf<String>()
list.forEach {
if (it.startsWith("geosite:")) {
// geosite.plusAssign(it.removePrefix("geosite:"))
rule_set.plusAssign("geosite-" + it.removePrefix("geosite:"))
} else if (it.startsWith("full:")) {
domain.plusAssign(it.removePrefix("full:").lowercase())
} else if (it.startsWith("domain:")) {
domain_suffix.plusAssign(it.removePrefix("domain:").lowercase())
} else if (it.startsWith("regexp:")) {
domain_regex.plusAssign(it.removePrefix("regexp:").lowercase())
} else if (it.startsWith("keyword:")) {
domain_keyword.plusAssign(it.removePrefix("keyword:").lowercase())
} else {
// https://github.com/SagerNet/sing-box/commit/5d41e328d4a9f7549dd27f11b4ccc43710a73664
domain.plusAssign(it.lowercase())
}
}
geosite?.removeIf { it.isNullOrBlank() }
rule_set?.removeIf { it.isNullOrBlank() }
domain?.removeIf { it.isNullOrBlank() }
domain_suffix?.removeIf { it.isNullOrBlank() }
domain_regex?.removeIf { it.isNullOrBlank() }
domain_keyword?.removeIf { it.isNullOrBlank() }
wifi_ssid?.removeIf() { it.isNullOrBlank() }
wifi_bssid?.removeIf() { it.isNullOrBlank() }
if (geosite?.isEmpty() == true) geosite = null
if (rule_set?.isEmpty() == true) rule_set = null
if (domain?.isEmpty() == true) domain = null
if (domain_suffix?.isEmpty() == true) domain_suffix = null
if (domain_regex?.isEmpty() == true) domain_regex = null
if (domain_keyword?.isEmpty() == true) domain_keyword = null
if (wifi_ssid?.isEmpty() == true) wifi_ssid = null
if (wifi_bssid?.isEmpty() == true) wifi_bssid = null
}
fun SingBoxOptions.DNSRule_DefaultOptions.checkEmpty(): Boolean {
if (geosite?.isNotEmpty() == true) return false
if (rule_set?.isNotEmpty() == true) return false
if (domain?.isNotEmpty() == true) return false
if (domain_suffix?.isNotEmpty() == true) return false
if (domain_regex?.isNotEmpty() == true) return false
if (domain_keyword?.isNotEmpty() == true) return false
if (user_id?.isNotEmpty() == true) return false
if (wifi_ssid?.isEmpty() == true) return false
if (wifi_bssid?.isEmpty() == true) return false
return true
}
fun SingBoxOptions.Rule_DefaultOptions.makeSingBoxRule(list: List<String>, isIP: Boolean) {
if (isIP) {
ip_cidr = mutableListOf<String>()
geoip = mutableListOf<String>()
} else {
geosite = mutableListOf<String>()
domain = mutableListOf<String>()
domain_suffix = mutableListOf<String>()
domain_regex = mutableListOf<String>()
domain_keyword = mutableListOf<String>()
wifi_ssid = mutableListOf<String>()
wifi_bssid = mutableListOf<String>()
}
rule_set = mutableListOf<String>()
list.forEach {
if (isIP) {
if (it.startsWith("geoip:")) {
// geoip.plusAssign(it.removePrefix("geoip:"))
rule_set.plusAssign("geoip-" + it.removePrefix("geoip:"))
} else {
ip_cidr.plusAssign(it)
}
return@forEach
}
if (it.startsWith("geosite:")) {
// geosite.plusAssign(it.removePrefix("geosite:"))
rule_set.plusAssign("geosite-" + it.removePrefix("geosite:"))
} else if (it.startsWith("full:")) {
domain.plusAssign(it.removePrefix("full:").lowercase())
} else if (it.startsWith("domain:")) {
domain_suffix.plusAssign(it.removePrefix("domain:").lowercase())
} else if (it.startsWith("regexp:")) {
domain_regex.plusAssign(it.removePrefix("regexp:").lowercase())
} else if (it.startsWith("keyword:")) {
domain_keyword.plusAssign(it.removePrefix("keyword:").lowercase())
} else {
// https://github.com/SagerNet/sing-box/commit/5d41e328d4a9f7549dd27f11b4ccc43710a73664
domain.plusAssign(it.lowercase())
}
}
ip_cidr?.removeIf { it.isNullOrBlank() }
geoip?.removeIf { it.isNullOrBlank() }
geosite?.removeIf { it.isNullOrBlank() }
rule_set?.removeIf { it.isNullOrBlank() }
domain?.removeIf { it.isNullOrBlank() }
domain_suffix?.removeIf { it.isNullOrBlank() }
domain_regex?.removeIf { it.isNullOrBlank() }
domain_keyword?.removeIf { it.isNullOrBlank() }
wifi_ssid?.removeIf() { it.isNullOrBlank() }
wifi_bssid?.removeIf() { it.isNullOrBlank() }
if (ip_cidr?.isEmpty() == true) ip_cidr = null
if (geoip?.isEmpty() == true) geoip = null
if (geosite?.isEmpty() == true) geosite = null
if (rule_set?.isEmpty() == true) rule_set = null
if (domain?.isEmpty() == true) domain = null
if (domain_suffix?.isEmpty() == true) domain_suffix = null
if (domain_regex?.isEmpty() == true) domain_regex = null
if (domain_keyword?.isEmpty() == true) domain_keyword = null
if (wifi_ssid?.isEmpty() == true) wifi_ssid = null
if (wifi_bssid?.isEmpty() == true) wifi_bssid = null
}
fun SingBoxOptions.Rule_DefaultOptions.checkEmpty(): Boolean {
if (ip_cidr?.isNotEmpty() == true) return false
if (geoip?.isNotEmpty() == true) return false
if (geosite?.isNotEmpty() == true) return false
if (rule_set?.isNotEmpty() == true) return false
if (domain?.isNotEmpty() == true) return false
if (domain_suffix?.isNotEmpty() == true) return false
if (domain_regex?.isNotEmpty() == true) return false
if (domain_keyword?.isNotEmpty() == true) return false
if (user_id?.isNotEmpty() == true) return false
//
if (port?.isNotEmpty() == true) return false
if (port_range?.isNotEmpty() == true) return false
if (source_ip_cidr?.isNotEmpty() == true) return false
if (wifi_ssid?.isEmpty() == true) return false
if (wifi_bssid?.isEmpty() == true) return false
return true
}
fun makeSingBoxRuleSet(rule: String, geoPath: String): SingBoxOptions.Rule_SetOptions {
val newRuleSetOption = SingBoxOptions.Rule_SetOptions()
val ruleSetType = if (rule.startsWith("geoip:")) {
"geoip"
} else if (rule.startsWith("geosite:")) {
"geosite"
} else {
return newRuleSetOption
}
val withoutPrefix = when (ruleSetType) {
"geoip" -> rule.removePrefix("geoip:")
"geosite" -> rule.removePrefix("geosite:")
else -> rule
}
newRuleSetOption.tag = "$ruleSetType-$withoutPrefix"
newRuleSetOption.type = "local"
newRuleSetOption.format = "binary"
newRuleSetOption.path = "$geoPath/$ruleSetType-$withoutPrefix.srs"
return newRuleSetOption
}
fun List<SingBoxOptions.Rule_SetOptions>.distinctByTag(): List<SingBoxOptions.Rule_SetOptions> {
return this.distinctBy { it.tag }
}
fun SingBoxOptions.Rule_SetOptions.checkEmpty(): Boolean {
// ???
if (tag?.isNotEmpty() == true) return false
if (type?.isNotEmpty() == true) return false
if (format?.isNotEmpty() == true) return false
return true
}
| nacs/app/src/main/java/moe/matsuri/nb4a/SingBoxOptionsUtil.kt | 72370208 |
package moe.matsuri.nb4a
import android.content.Context
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.ProxyEntity.Companion.TYPE_NEKO
import io.nekohasekai.sagernet.fmt.AbstractBean
import io.nekohasekai.sagernet.fmt.v2ray.StandardV2RayBean
import io.nekohasekai.sagernet.fmt.v2ray.isTLS
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ktx.getColorAttr
import moe.matsuri.nb4a.plugin.NekoPluginManager
// Settings for all protocols, built-in or plugin
object Protocols {
// Mux
fun isProfileNeedMux(bean: StandardV2RayBean): Boolean {
return when (bean.type) {
"tcp", "ws" -> true
"http" -> !bean.isTLS()
else -> false
}
}
fun shouldEnableMux(protocol: String): Boolean {
return DataStore.muxProtocols.contains(protocol)
}
fun getCanMuxList(): List<String> {
// built-in and support mux
val list = mutableListOf("vmess", "trojan", "trojan-go", "shadowsocks", "vless", "padding")
NekoPluginManager.getProtocols().forEach {
if (it.protocolConfig.optBoolean("canMux")) {
list.add(it.protocolId)
}
}
return list
}
// Deduplication
class Deduplication(
val bean: AbstractBean, val type: String
) {
fun hash(): String {
return bean.serverAddress + bean.serverPort + type
}
override fun hashCode(): Int {
return hash().toByteArray().contentHashCode()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Deduplication
return hash() == other.hash()
}
}
// Display
fun Context.getProtocolColor(type: Int): Int {
return when (type) {
TYPE_NEKO -> getColorAttr(android.R.attr.textColorPrimary)
else -> getColorAttr(R.attr.accentOrTextSecondary)
}
}
// Test
fun genFriendlyMsg(msg: String): String {
val msgL = msg.lowercase()
return when {
msgL.contains("timeout") || msgL.contains("deadline") -> {
app.getString(R.string.connection_test_timeout)
}
msgL.contains("refused") || msgL.contains("closed pipe") -> {
app.getString(R.string.connection_test_refused)
}
else -> msg
}
}
} | nacs/app/src/main/java/moe/matsuri/nb4a/Protocols.kt | 1387787124 |
package moe.matsuri.nb4a
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.database.preference.KeyValuePair
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
@Database(entities = [KeyValuePair::class], version = 1)
abstract class TempDatabase : RoomDatabase() {
companion object {
@Suppress("EXPERIMENTAL_API_USAGE")
private val instance by lazy {
Room.inMemoryDatabaseBuilder(SagerNet.application, TempDatabase::class.java)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.setQueryExecutor { GlobalScope.launch { it.run() } }
.build()
}
val profileCacheDao get() = instance.profileCacheDao()
}
abstract fun profileCacheDao(): KeyValuePair.Dao
} | nacs/app/src/main/java/moe/matsuri/nb4a/TempDatabase.kt | 4206425251 |
@file:JvmName("Utils")
package com.github.shadowsocks.plugin
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
class Empty : Parcelable | nacs/app/src/main/java/com/github/shadowsocks/plugin/Utils.kt | 341295831 |
package com.github.shadowsocks.plugin.fragment
import android.app.Activity
import android.content.DialogInterface
import android.os.Bundle
import android.os.Parcelable
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.setFragmentResultListener
import com.google.android.material.dialog.MaterialAlertDialogBuilder
/**
* Based on: https://android.googlesource.com/platform/
packages/apps/ExactCalculator/+/8c43f06/src/com/android/calculator2/AlertDialogFragment.java
*/
abstract class AlertDialogFragment<Arg : Parcelable, Ret : Parcelable?> :
AppCompatDialogFragment(), DialogInterface.OnClickListener {
companion object {
private const val KEY_RESULT = "result"
private const val KEY_ARG = "arg"
private const val KEY_RET = "ret"
private const val KEY_WHICH = "which"
fun <Ret : Parcelable> setResultListener(
fragment: Fragment, requestKey: String,
listener: (Int, Ret?) -> Unit
) {
fragment.setFragmentResultListener(requestKey) { _, bundle ->
listener(
bundle.getInt(KEY_WHICH, Activity.RESULT_CANCELED),
bundle.getParcelable(KEY_RET)
)
}
}
inline fun <reified T : AlertDialogFragment<*, Ret>, Ret : Parcelable?> setResultListener(
fragment: Fragment, noinline listener: (Int, Ret?) -> Unit
) =
setResultListener(fragment, T::class.java.name, listener)
}
protected abstract fun AlertDialog.Builder.prepare(listener: DialogInterface.OnClickListener)
private val resultKey get() = requireArguments().getString(KEY_RESULT)
protected val arg by lazy { requireArguments().getParcelable<Arg>(KEY_ARG)!! }
protected open fun ret(which: Int): Ret? = null
private fun args() = arguments ?: Bundle().also { arguments = it }
fun arg(arg: Arg) = args().putParcelable(KEY_ARG, arg)
fun key(resultKey: String = javaClass.name) = args().putString(KEY_RESULT, resultKey)
override fun onCreateDialog(savedInstanceState: Bundle?): AlertDialog =
MaterialAlertDialogBuilder(requireContext()).also { it.prepare(this) }.create()
override fun onClick(dialog: DialogInterface?, which: Int) {
setFragmentResult(resultKey ?: return, Bundle().apply {
putInt(KEY_WHICH, which)
putParcelable(KEY_RET, ret(which) ?: return@apply)
})
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
onClick(null, Activity.RESULT_CANCELED)
}
}
| nacs/app/src/main/java/com/github/shadowsocks/plugin/fragment/AlertDialogFragment.kt | 682131542 |
import com.android.build.api.dsl.ApplicationExtension
import com.android.build.gradle.AbstractAppExtension
import com.android.build.gradle.internal.api.BaseVariantOutputImpl
import org.gradle.api.JavaVersion
import org.gradle.api.Project
import org.gradle.api.plugins.ExtensionAware
import org.gradle.kotlin.dsl.getByName
import org.jetbrains.kotlin.gradle.dsl.KotlinJvmOptions
import java.security.MessageDigest
import java.util.*
import kotlin.system.exitProcess
fun sha256Hex(bytes: ByteArray): String {
val md = MessageDigest.getInstance("SHA-256")
val digest = md.digest(bytes)
return digest.fold("") { str, it -> str + "%02x".format(it) }
}
private val Project.android get() = extensions.getByName<ApplicationExtension>("android")
private lateinit var metadata: Properties
private lateinit var localProperties: Properties
private lateinit var flavor: String
fun Project.requireFlavor(): String {
if (::flavor.isInitialized) return flavor
if (gradle.startParameter.taskNames.isNotEmpty()) {
val taskName = gradle.startParameter.taskNames[0]
when {
taskName.contains("assemble") -> {
flavor = taskName.substringAfter("assemble")
return flavor
}
taskName.contains("install") -> {
flavor = taskName.substringAfter("install")
return flavor
}
taskName.contains("bundle") -> {
flavor = taskName.substringAfter("bundle")
return flavor
}
}
}
flavor = ""
return flavor
}
fun Project.requireMetadata(): Properties {
if (!::metadata.isInitialized) {
metadata = Properties().apply {
load(rootProject.file("husi.properties").inputStream())
}
}
return metadata
}
fun Project.requireLocalProperties(): Properties {
if (!::localProperties.isInitialized) {
localProperties = Properties()
val base64 = System.getenv("LOCAL_PROPERTIES")
if (!base64.isNullOrBlank()) {
localProperties.load(Base64.getDecoder().decode(base64).inputStream())
} else if (project.rootProject.file("local.properties").exists()) {
localProperties.load(rootProject.file("local.properties").inputStream())
}
}
return localProperties
}
fun Project.requireTargetAbi(): String {
var targetAbi = ""
if (gradle.startParameter.taskNames.isNotEmpty()) {
if (gradle.startParameter.taskNames.size == 1) {
val targetTask = gradle.startParameter.taskNames[0].lowercase(Locale.ROOT).trim()
when {
targetTask.contains("arm64") -> targetAbi = "arm64-v8a"
targetTask.contains("arm") -> targetAbi = "armeabi-v7a"
targetTask.contains("x64") -> targetAbi = "x86_64"
targetTask.contains("x86") -> targetAbi = "x86"
}
}
}
return targetAbi
}
fun Project.setupCommon() {
android.apply {
buildToolsVersion = "34.0.0"
compileSdk = 34
defaultConfig {
minSdk = 21
targetSdk = 34
}
buildTypes {
getByName("release") {
isMinifyEnabled = true
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
(android as ExtensionAware).extensions.getByName<KotlinJvmOptions>("kotlinOptions").apply {
jvmTarget = JavaVersion.VERSION_17.toString()
}
lint {
showAll = true
checkAllWarnings = true
checkReleaseBuilds = true
warningsAsErrors = true
textOutput = project.file("build/lint.txt")
htmlOutput = project.file("build/lint.html")
}
packaging {
resources.excludes.addAll(
listOf(
"**/*.kotlin_*",
"/META-INF/*.version",
"/META-INF/native/**",
"/META-INF/native-image/**",
"/META-INF/INDEX.LIST",
"DebugProbesKt.bin",
"com/**",
"org/**",
"**/*.java",
"**/*.proto",
"okhttp3/**"
)
)
jniLibs.useLegacyPackaging = true
}
(this as? AbstractAppExtension)?.apply {
buildTypes {
getByName("release") {
isShrinkResources = true
if (System.getenv("nkmr_minify") == "0") {
isShrinkResources = false
isMinifyEnabled = false
}
}
getByName("debug") {
applicationIdSuffix = "debug"
debuggable(true)
jniDebuggable(true)
}
}
applicationVariants.forEach { variant ->
variant.outputs.forEach {
it as BaseVariantOutputImpl
it.outputFileName = it.outputFileName.replace(
"app", "${project.name}-" + variant.versionName
).replace("-release", "").replace("-oss", "")
}
}
}
}
}
fun Project.setupAppCommon() {
setupCommon()
val lp = requireLocalProperties()
val keystorePwd = lp.getProperty("KEYSTORE_PASS") ?: System.getenv("KEYSTORE_PASS")
val alias = lp.getProperty("ALIAS_NAME") ?: System.getenv("ALIAS_NAME")
val pwd = lp.getProperty("ALIAS_PASS") ?: System.getenv("ALIAS_PASS")
android.apply {
if (keystorePwd != null) {
signingConfigs {
create("release") {
storeFile = rootProject.file("release.keystore")
storePassword = keystorePwd
keyAlias = alias
keyPassword = pwd
}
}
} else if (requireFlavor().contains("(Oss|Expert|Play)Release".toRegex())) {
exitProcess(0)
}
buildTypes {
val key = signingConfigs.findByName("release")
if (key != null) {
if (requireTargetAbi().isBlank()) {
getByName("release").signingConfig = key
}
getByName("debug").signingConfig = key
}
}
}
}
fun Project.setupApp() {
val pkgName = requireMetadata().getProperty("PACKAGE_NAME")
val verName = requireMetadata().getProperty("VERSION_NAME")
val verCode = (requireMetadata().getProperty("VERSION_CODE").toInt()) * 5
android.apply {
defaultConfig {
applicationId = pkgName
versionCode = verCode
versionName = verName
}
}
setupAppCommon()
val targetAbi = requireTargetAbi()
android.apply {
this as AbstractAppExtension
buildTypes {
getByName("release") {
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
file("proguard-rules.pro")
)
}
}
splits.abi {
isEnable = true
isUniversalApk = false
if (targetAbi.isNotBlank()) {
reset()
include(targetAbi)
}
}
flavorDimensions += "vendor"
productFlavors {
create("oss")
create("fdroid")
create("play")
}
applicationVariants.all {
outputs.all {
this as BaseVariantOutputImpl
outputFileName = outputFileName.replace(project.name, "husi-$versionName")
.replace("-release", "")
.replace("-oss", "")
}
}
for (abi in listOf("Arm64", "Arm", "X64", "X86")) {
tasks.create("assemble" + abi + "FdroidRelease") {
dependsOn("assembleFdroidRelease")
}
}
sourceSets.getByName("main").apply {
jniLibs.srcDir("executableSo")
}
}
}
| nacs/buildSrc/src/main/kotlin/Helpers.kt | 1502344929 |
package com.example.crudfirebase3
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* 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 useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.crudfirebase3", appContext.packageName)
}
} | CRUDFirebase3/app/src/androidTest/java/com/example/crudfirebase3/ExampleInstrumentedTest.kt | 349104989 |
package com.example.crudfirebase3
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | CRUDFirebase3/app/src/test/java/com/example/crudfirebase3/ExampleUnitTest.kt | 1540593567 |
package com.example.crudfirebase3
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.Toast
import com.example.crudfirebase3.databinding.ActivityMainBinding
import com.firebase.ui.auth.AuthUI
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
class MainActivity : AppCompatActivity(), View.OnClickListener {
private var auth: FirebaseAuth? = null
private val RC_SIGN_IN = 1
private lateinit var binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
//Inisialisasi ID (Button)
binding.logout.setOnClickListener(this)
binding.save.setOnClickListener(this)
binding.showdata.setOnClickListener(this)
//Mendapatkan Instance Firebase Autentifikasi
auth = FirebaseAuth.getInstance()
}
private fun isEmpty(s: String): Boolean {
return TextUtils.isEmpty(s)
}
override fun onClick(p0: View?) {
when (p0?.getId()) {
R.id.save -> {
// Statement program untuk simpan data
//Mendapatkan UserID dari pengguna yang Terautentikasi
val getUserID = auth!!.currentUser!!.uid
//Mendapatkan Instance dari Database
val database = FirebaseDatabase.getInstance()
//Menyimpan Data yang diinputkan User kedalam Variable
val getNIM: String = binding.nim.getText().toString()
val getNama: String = binding.nama.getText().toString()
val getJurusan: String = binding.jurusan.getText().toString()
// Mendapatkan Referensi dari Database
val getReference: DatabaseReference
getReference = database.reference
// Mengecek apakah ada data yang kosong
if (isEmpty(getNIM) || isEmpty(getNama) || isEmpty(getJurusan)) {
//Jika Ada, maka akan menampilkan pesan singkan seperti berikut ini.
Toast.makeText(
this@MainActivity, "Data tidak boleh ada yang kosong",
Toast.LENGTH_SHORT
).show()
} else {
/* Jika Tidak, maka data dapat diproses dan meyimpannya pada Database
Menyimpan data referensi pada Database berdasarkan User ID dari masing-masing
Akun
*/
getReference.child("Admin").child(getUserID).child("Mahasiswa").push()
.setValue(data_mahasiswa(getNIM, getNama, getJurusan))
.addOnCompleteListener(this) {
//Peristiwa ini terjadi saat user berhasil menyimpan datanya kedalam Database
binding.nim.setText("")
binding.nama.setText("")
binding.jurusan.setText("")
Toast.makeText(
this@MainActivity, "Data Tersimpan",
Toast.LENGTH_SHORT
).show()
}
}
}
R.id.logout ->
// Statement program untuk logout/keluar
AuthUI.getInstance()
.signOut(this)
.addOnCompleteListener(object :
OnCompleteListener<Void> {
override fun onComplete(p0: Task<Void>) {
Toast.makeText(this@MainActivity, "Logout Berhasil", Toast.LENGTH_SHORT)
.show()
intent = Intent(
applicationContext,
LoginActivity::class.java
)
startActivity(intent)
finish()
}
})
R.id.showdata -> {
startActivity(Intent(this@MainActivity, MyListData::class.java))
}
}
}
}
| CRUDFirebase3/app/src/main/java/com/example/crudfirebase3/MainActivity.kt | 4284253878 |
package com.example.crudfirebase3
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class MyListData : AppCompatActivity() {
//Deklarasi Variable untuk RecyclerView
private var recyclerView: RecyclerView? = null
private var adapter: RecyclerView.Adapter<*>? = null
private var layoutManager: RecyclerView.LayoutManager? = null
//Deklarasi Variable Database Reference & ArrayList dengan Parameter Class Model kita.
val database = FirebaseDatabase.getInstance()
private var dataMahasiswa = ArrayList<data_mahasiswa>()
private var auth: FirebaseAuth? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my_list_data)
recyclerView = findViewById(R.id.datalist)
supportActionBar?.title = "Data Mahasiswa"
auth = FirebaseAuth.getInstance()
MyRecyclerView()
GetData()
}
//Baris kode untuk mengambil data dari Database & menampilkan kedalam Adapter
private fun GetData() {
Toast.makeText(applicationContext, "Mohon Tunggu Sebentar...",
Toast.LENGTH_LONG).show()
val getUserID: String = auth?.getCurrentUser()?.getUid().toString()
val getReference = database.getReference()
getReference.child("Admin").child(getUserID).child("Mahasiswa")
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (dataSnapshot.exists()) {
for (snapshot in dataSnapshot.children) {
//Mapping data pada DataSnapshot ke dalam objek mahasiswa
val mahasiswa =
snapshot.getValue(data_mahasiswa::class.java)
//Mengambil Primary Key, digunakan untuk proses Update/Delete
mahasiswa?.key = snapshot.key
dataMahasiswa.add(mahasiswa!!)
}
//Inisialisasi Adapter dan data Mahasiswa dalam bentuk Array
adapter = RecyclerViewAdapter(dataMahasiswa, this@MyListData)
//Memasang Adapter pada RecyclerView
recyclerView?.adapter = adapter
(adapter as RecyclerViewAdapter).notifyDataSetChanged()
Toast.makeText(applicationContext,"Data Berhasil Dimuat",
Toast.LENGTH_LONG).show()
}
}
override fun onCancelled(databaseError: DatabaseError) {
// Kode ini akan dijalankan ketika ada error, simpan ke LogCat
Toast.makeText(applicationContext, "Data Gagal Dimuat",
Toast.LENGTH_LONG).show()
Log.e("MyListActivity", databaseError.details + " " +
databaseError.message)
}
})
}
//Methode yang berisi kumpulan baris kode untuk mengatur RecyclerView
private fun MyRecyclerView() {
//Menggunakan Layout Manager, Dan Membuat List Secara Vertical
layoutManager = LinearLayoutManager(this)
recyclerView?.layoutManager = layoutManager
recyclerView?.setHasFixedSize(true)
//Membuat Underline pada Setiap Item Didalam List
val itemDecoration = DividerItemDecoration(applicationContext,
DividerItemDecoration.VERTICAL)
itemDecoration.setDrawable(
ContextCompat.getDrawable(applicationContext,
R.drawable.line)!!)
recyclerView?.addItemDecoration(itemDecoration)
}
} | CRUDFirebase3/app/src/main/java/com/example/crudfirebase3/MyListData.kt | 4291468437 |
package com.example.crudfirebase3
import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class RecyclerViewAdapter( private val listMahasiswa: ArrayList<data_mahasiswa>, context: Context) :
RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>() {
private val context: Context
//ViewHolder Digunakan Untuk Menyimpan Referensi Dari View-View
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val NIM: TextView
val Nama: TextView
val Jurusan: TextView
val ListItem: LinearLayout
init {//Menginisialisasi View yang terpasang pada layout RecyclerView kita
NIM = itemView.findViewById(R.id.nimx)
Nama = itemView.findViewById(R.id.namax)
Jurusan = itemView.findViewById(R.id.jurusanx)
ListItem = itemView.findViewById(R.id.list_item)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
//Membuat View untuk Menyiapkan & Memasang Layout yang digunakan pada RecyclerView
val V: View = LayoutInflater.from(parent.getContext()).inflate(
R.layout.view_design, parent, false)
return ViewHolder(V)
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
//Mengambil Nilai/Value pada RecyclerView berdasarkan Posisi Tertentu
val NIM: String? = listMahasiswa.get(position).nim
val Nama: String? = listMahasiswa.get(position).nama
val Jurusan: String? = listMahasiswa.get(position).jurusan
//Memasukan Nilai/Value kedalam View (TextView: NIM, Nama, Jurusan)
holder.NIM.text = "NIM: $NIM"
holder.Nama.text = "Nama: $Nama"
holder.Jurusan.text = "Jurusan: $Jurusan"
holder.ListItem.setOnLongClickListener(object : View.OnLongClickListener {
override fun onLongClick(v: View?): Boolean {
//Kodingan untuk fungsi Edit dan Delete, yang dibahas pada Tutorial Berikutnya.
return true
}
})
}
override fun getItemCount(): Int {
//Menghitung Ukuran/Jumlah Data Yang Akan Ditampilkan Pada RecyclerView
return listMahasiswa.size
}
//Membuat Konstruktor, untuk menerima input dari Database
init {
this.context = context
}
} | CRUDFirebase3/app/src/main/java/com/example/crudfirebase3/RecyclerViewAdapter.kt | 172361286 |
package com.example.crudfirebase3
class data_mahasiswa {
//Deklarasi Variable
var nim: String? = null
var nama: String? = null
var jurusan: String? = null
var key: String? = null
//Membuat Konstuktor kosong untuk membaca data snapshot
constructor() {}
//Konstruktor dengan beberapa parameter, untuk mendapatkan Input Data dari User
constructor(nim: String?, nama: String?, jurusan: String?) {
this.nim = nim
this.nama = nama
this.jurusan = jurusan
}
} | CRUDFirebase3/app/src/main/java/com/example/crudfirebase3/data_mahasiswa.kt | 3347711614 |
package com.example.crudfirebase3
import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.example.crudfirebase3.databinding.ActivityLoginBinding
import com.firebase.ui.auth.AuthUI
import com.firebase.ui.auth.IdpResponse
import com.google.firebase.auth.FirebaseAuth
class LoginActivity : AppCompatActivity(), View.OnClickListener {
private var auth: FirebaseAuth? = null
private val RC_SIGN_IN = 1
private lateinit var binding : ActivityLoginBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.progress.visibility = View.GONE
binding.login.setOnClickListener(this)
auth = FirebaseAuth.getInstance()
if(auth!!.currentUser == null){
} else {
intent = Intent(applicationContext,
MainActivity::class.java)
startActivity(intent)
finish()
}
}
override fun onClick(p0: View?) {
// Choose authentication providers
val providers = arrayListOf(
AuthUI.IdpConfig.GoogleBuilder().build())
// Create and launch sign-in intent
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.build(),
RC_SIGN_IN)
}
override fun onActivityResult(requestCode: Int, resultCode: Int,
data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val response = IdpResponse.fromResultIntent(data)
if (resultCode == Activity.RESULT_OK) {
val user = FirebaseAuth.getInstance().currentUser
Toast.makeText(this, "Login Berhasil",
Toast.LENGTH_SHORT).show()
intent = Intent(applicationContext,
MainActivity::class.java)
startActivity(intent)
finish()
} else {
Toast.makeText(this, "Login Dibatalkan",
Toast.LENGTH_SHORT).show()
}
}
}
}
| CRUDFirebase3/app/src/main/java/com/example/crudfirebase3/LoginActivity.kt | 3296338731 |
package com.kys2024.tpkysadministration
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* 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 useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.kys2024.tpkysadministration", appContext.packageName)
}
} | TPkysAdministration/app/src/androidTest/java/com/kys2024/tpkysadministration/ExampleInstrumentedTest.kt | 1745530454 |
package com.kys2024.tpkysadministration
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | TPkysAdministration/app/src/test/java/com/kys2024/tpkysadministration/ExampleUnitTest.kt | 455259922 |
package com.kys2024.tpkysadministration.activities.activity
import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.kys2024.tpkysadministration.R
import com.kys2024.tpkysadministration.databinding.ActivitySigninMembershipBinding
class Signin_MembershipActivity : AppCompatActivity() {
private val binding by lazy { ActivitySigninMembershipBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
//툴바 뒤로가기 버튼눌렀을때 뒤로가지는 기능
binding.toolbar.setNavigationOnClickListener { finish() }
binding.tvLogin.setOnClickListener { startActivity(Intent(this,MembershipActivity::class.java)) }
binding.layoutEmailLogin.setOnClickListener { startActivity(Intent(this,EmailSignInActivity::class.java)) }
binding.layoutKakaoLogin.setOnClickListener { clickKakao() }
binding.layoutGoogleLogin.setOnClickListener { clickGoogle() }
binding.layoutNaverLogin.setOnClickListener { clickNaver() }
}
private fun clickKakao(){
Toast.makeText(this, "카카오로그인", Toast.LENGTH_SHORT).show()
}
private fun clickGoogle(){
Toast.makeText(this, "구글로그인", Toast.LENGTH_SHORT).show()
}
private fun clickNaver(){
Toast.makeText(this, "네이버로그인", Toast.LENGTH_SHORT).show()
}
} | TPkysAdministration/app/src/main/java/com/kys2024/tpkysadministration/activities/activity/Signin_MembershipActivity.kt | 3007706653 |
package com.kys2024.tpkysadministration.activities.activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.kys2024.tpkysadministration.R
import com.kys2024.tpkysadministration.databinding.ActivityBoardBinding
import com.kys2024.tpkysadministration.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.bottomNavigation.setOnItemSelectedListener {
when(it.itemId){
R.id.menu_bnv_person->startActivity(Intent(this,Signin_MembershipActivity::class.java))
}
true
}//bottomNavigation
binding.cardViewBoard.setOnClickListener { clcikBoard() }
binding.cardViewArea.setOnClickListener { clickArea() }
binding.cardViewBehavior.setOnClickListener { clickBehanior() }
}
private fun clcikBoard(){
startActivity(Intent(this,BoardActivity::class.java))
}
private fun clickArea(){
}
private fun clickBehanior(){
}
} | TPkysAdministration/app/src/main/java/com/kys2024/tpkysadministration/activities/activity/MainActivity.kt | 2836806968 |
package com.kys2024.tpkysadministration.activities.activity
import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.kys2024.tpkysadministration.R
import com.kys2024.tpkysadministration.databinding.ActivityEmailSignInBinding
class EmailSignInActivity : AppCompatActivity() {
private val binding by lazy { ActivityEmailSignInBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_email_sign_in)
binding.toolbar.setNavigationOnClickListener { finish() }
}
} | TPkysAdministration/app/src/main/java/com/kys2024/tpkysadministration/activities/activity/EmailSignInActivity.kt | 775129840 |
package com.kys2024.tpkysadministration.activities.activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import com.kys2024.tpkysadministration.R
class IntroActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_intro)
Handler(Looper.getMainLooper()).postDelayed({
startActivity(Intent(this, MainActivity::class.java ))
finish()
},1500)
}
} | TPkysAdministration/app/src/main/java/com/kys2024/tpkysadministration/activities/activity/IntroActivity.kt | 2233450330 |
package com.kys2024.tpkysadministration.activities.activity
import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.kys2024.tpkysadministration.R
import com.kys2024.tpkysadministration.databinding.ActivityMembershipBinding
class MembershipActivity : AppCompatActivity() {
private val binding by lazy { ActivityMembershipBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.toolbar.setNavigationOnClickListener { finish() }
}
} | TPkysAdministration/app/src/main/java/com/kys2024/tpkysadministration/activities/activity/MembershipActivity.kt | 145914808 |
package com.kys2024.tpkysadministration.activities.activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.kys2024.tpkysadministration.R
import com.kys2024.tpkysadministration.databinding.ActivityBoardBinding
class BoardActivity : AppCompatActivity() {
private val binding by lazy { ActivityBoardBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.toolbar.setNavigationOnClickListener { finish() }
binding.bnt.setOnClickListener { clickBtnSave() }
}
private fun clickBtnSave(){
}
} | TPkysAdministration/app/src/main/java/com/kys2024/tpkysadministration/activities/activity/BoardActivity.kt | 3319952750 |
package com.kys2024.tpkysadministration.activities.activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.kys2024.tpkysadministration.R
class MyPageActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my_page)
}
} | TPkysAdministration/app/src/main/java/com/kys2024/tpkysadministration/activities/activity/MyPageActivity.kt | 2356829320 |
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import data.UserRepositoryImpl
import presentation.MainScreen
@Composable
@Preview
fun App() {
MaterialTheme {
MainScreen(
repository = UserRepositoryImpl(),
modifier = Modifier.padding(vertical = 12.dp)
)
}
}
fun main() = application {
Window(onCloseRequest = ::exitApplication) {
App()
}
}
| Users-Project-/src/jvmMain/kotlin/Main.kt | 744309056 |
package data
import domain.models.User
import domain.repository.UserRepository
import kotlinx.serialization.json.Json
import java.net.URL
class UserRepositoryImpl: UserRepository {
override fun getUsers(): List<User> {
val url = "https://jsonplaceholder.typicode.com/users"
val response = URL(url).readText()
val json = Json { ignoreUnknownKeys = true }
return json.decodeFromString<List<User>>(response)
}
} | Users-Project-/src/jvmMain/kotlin/data/UserRepositoryImpl.kt | 2921892580 |
package domain.repository
import domain.models.User
interface UserRepository {
fun getUsers(): List<User>
} | Users-Project-/src/jvmMain/kotlin/domain/repository/UserRepository.kt | 330358474 |
package domain.models
import kotlinx.serialization.Serializable
import java.util.*
@Serializable
data class User(
val id: Long = Random().nextLong(),
val name: String,
val username: String,
val email: String
) | Users-Project-/src/jvmMain/kotlin/domain/models/User.kt | 493739071 |
package presentation.components
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.sp
@Composable
fun CommonTextButton(
title: String,
color: Color,
onClick: () -> Unit
) {
TextButton(
onClick = { onClick() }
) {
Text(
text = title,
fontSize = 18.sp,
color = color
)
}
} | Users-Project-/src/jvmMain/kotlin/presentation/components/CommonTextButton.kt | 1322283603 |
package presentation.components
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Composable
fun CommonTextField(
value: String,
onValueChange: (String) -> Unit,
label: String,
isError: Boolean,
modifier: Modifier = Modifier
) = TextField(
value = value,
onValueChange = onValueChange,
singleLine = true,
label = {
Text(text = label)
},
shape = RoundedCornerShape(12.dp),
colors = TextFieldDefaults.textFieldColors(backgroundColor = Color.Transparent),
isError = isError,
modifier = modifier
) | Users-Project-/src/jvmMain/kotlin/presentation/components/CommonTextField.kt | 1116085417 |
package presentation.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
@Composable
fun CommonDialog(
title: String,
onDismissRequest: () -> Unit,
content: @Composable ColumnScope.() -> Unit
) {
Dialog(onDismissRequest = onDismissRequest) {
Column (
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier
.clip(RoundedCornerShape(12.dp))
.background(Color.White)
.padding(24.dp)
) {
Text(
text = title,
fontSize = 18.sp,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(bottom = 8.dp)
)
content()
}
}
} | Users-Project-/src/jvmMain/kotlin/presentation/components/CommonDialog.kt | 2263580969 |
package presentation
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.rounded.Delete
import androidx.compose.material.icons.rounded.Edit
import androidx.compose.material.icons.rounded.Face
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import domain.models.User
import domain.repository.UserRepository
import io.kamel.core.config.KamelConfig
import io.kamel.core.config.takeFrom
import io.kamel.core.utils.URL
import io.kamel.image.KamelImage
import io.kamel.image.asyncPainterResource
import io.kamel.image.config.Default
import io.kamel.image.config.LocalKamelConfig
import io.kamel.image.config.batikSvgDecoder
import io.kamel.image.config.resourcesFetcher
import presentation.components.CommonDialog
import presentation.components.CommonTextButton
import presentation.components.CommonTextField
@Composable
fun MainScreen(
repository: UserRepository,
modifier: Modifier = Modifier
) {
var users by remember { mutableStateOf(repository.getUsers()) }
var isDialogVisible by remember { mutableStateOf(false) }
var dialogTitle by remember { mutableStateOf("") }
var userId by remember { mutableStateOf<Long?>(null) }
var nameToEdit by remember { mutableStateOf("") }
var usernameToEdit by remember { mutableStateOf("") }
var emailToEdit by remember { mutableStateOf("") }
Scaffold(
floatingActionButton = {
FloatingActionButton(onClick = {
userId = null
nameToEdit = ""
usernameToEdit = ""
emailToEdit = ""
dialogTitle = "Add user"
isDialogVisible = true
}) {
Icon(imageVector = Icons.Default.Add, contentDescription = "Add user")
}
}
) { paddingValues ->
Column(
modifier = modifier
.fillMaxSize()
.padding(paddingValues = paddingValues)
) {
Text(
text = "Users",
style = MaterialTheme.typography.h3,
modifier = Modifier.padding(horizontal = 20.dp)
)
Divider(Modifier.padding(vertical = 12.dp))
val desktopConfig = KamelConfig {
takeFrom(KamelConfig.Default)
resourcesFetcher()
batikSvgDecoder()
}
CompositionLocalProvider(LocalKamelConfig provides desktopConfig) {
KamelImage(
resource = asyncPainterResource("drawables/image.png"),
contentDescription = "Welcome image",
contentAlignment = Alignment.Center,
contentScale = ContentScale.Fit,
modifier = Modifier.height(100.dp)
)
}
LazyColumn(
modifier = Modifier.padding(horizontal = 20.dp)
) {
items(users) { user ->
UserItem(
model = user,
onEditClick = {
userId = user.id
nameToEdit = user.name
usernameToEdit = user.username
emailToEdit = user.email
dialogTitle = "Edit user"
isDialogVisible = true
},
onDeleteClick = {
users = users.filter { it.id != user.id }
}
)
}
}
}
}
if (isDialogVisible) {
UserInfoDialog(
title = dialogTitle,
initialName = nameToEdit,
initialUsername = usernameToEdit,
initialEmail = emailToEdit,
onDismissRequest = {
dialogTitle = ""
isDialogVisible = false
},
onSaveClick = { name, username, email ->
if (userId == null) {
val newUser = User(name = name, username = username, email = email)
users = users + newUser
} else {
users = users.map {
if (it.id == userId) {
User(id = it.id, name = name, username = username, email = email)
} else {
it
}
}
}
}
)
}
}
@Composable
private fun UserItem(
model: User,
onEditClick: () -> Unit,
onDeleteClick: () -> Unit,
modifier: Modifier = Modifier
) = Row(
modifier = modifier.padding(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Image(
imageVector = Icons.Rounded.Face,
contentDescription = "avatar",
modifier = Modifier.size(48.dp),
alignment = Alignment.Center
)
Spacer(Modifier.width(4.dp))
Column(
modifier = Modifier
) {
Text(
text = model.name,
style = MaterialTheme.typography.h6
)
Text(
text = "Username:@" + model.username,
style = MaterialTheme.typography.caption
)
Text(
text = "Email: " + model.email,
style = MaterialTheme.typography.caption
)
}
Spacer(Modifier.weight(1f))
Icon(
imageVector = Icons.Rounded.Edit,
contentDescription = "Edit",
tint = Color.DarkGray,
modifier = Modifier
.size(36.dp)
.clickable { onEditClick() }
.padding(8.dp)
)
Icon(
imageVector = Icons.Rounded.Delete,
contentDescription = "Delete",
tint = Color.Red,
modifier = Modifier
.size(36.dp)
.clickable { onDeleteClick() }
.padding(8.dp)
)
}
@Composable
private fun UserInfoDialog(
title: String,
initialName: String,
initialUsername: String,
initialEmail: String,
onDismissRequest: () -> Unit,
onSaveClick: (name: String, username: String, email: String) -> Unit
) = CommonDialog(
title = title,
onDismissRequest = onDismissRequest
) {
var name by remember { mutableStateOf(initialName) }
var username by remember { mutableStateOf(initialUsername) }
var email by remember { mutableStateOf(initialEmail) }
var isNameError by remember { mutableStateOf(false) }
var isUsernameError by remember { mutableStateOf(false) }
var isEmailError by remember { mutableStateOf(false) }
CommonTextField(
value = name,
onValueChange = {
name = it
isNameError = false
},
label = "Name",
isError = isNameError,
modifier = Modifier.fillMaxWidth()
)
CommonTextField(
value = username,
onValueChange = {
username = it
isUsernameError = false
},
label = "Username",
isError = isUsernameError,
modifier = Modifier.fillMaxWidth()
)
CommonTextField(
value = email,
onValueChange = {
email = it
isEmailError = false
},
label = "Email",
isError = isEmailError,
modifier = Modifier.fillMaxWidth()
)
Row {
CommonTextButton(title = "Cancel", color = Color.Black) { onDismissRequest() }
CommonTextButton(title = "Save", color = Color.Black) {
if (name.isBlank()) isNameError = true
if (username.isBlank()) isUsernameError = true
if (email.isBlank()) isEmailError = true
if (isNameError || isUsernameError || isEmailError) return@CommonTextButton
onSaveClick(name, username, email)
onDismissRequest()
}
}
} | Users-Project-/src/jvmMain/kotlin/presentation/MainScreen.kt | 1314892944 |
package com.example.journalapp
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* 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 useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.journalapp", appContext.packageName)
}
} | Journal_App/app/src/androidTest/java/com/example/journalapp/ExampleInstrumentedTest.kt | 3695134700 |
package com.example.journalapp
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | Journal_App/app/src/test/java/com/example/journalapp/ExampleUnitTest.kt | 185086944 |
package com.example.journalapp
import android.graphics.BitmapFactory
import android.util.Base64
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class JournalRecyclerAdapter( private val itmlst: List<Journal>)
: RecyclerView.Adapter<JournalRecyclerAdapter.MyViewHolder>()
{
public class MyViewHolder(itemView : View) :
RecyclerView.ViewHolder(itemView){
val username: TextView = itemView.findViewById(R.id.journal_row_username)
val imageview : ImageView = itemView.findViewById(R.id.journal_image_list)
val journaltitle : TextView = itemView.findViewById(R.id.journal_title_list)
val journalThoughts : TextView = itemView.findViewById(R.id.journal_thought_list)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.journal_row,parent,false)
return MyViewHolder(itemView,)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentitem = itmlst[position]
// Glide.with(context).load(Journal_list[position].imageUri).into(holder.imageview)
holder.username.text = currentitem.userName.toString()
holder.journaltitle.text = currentitem.title.toString()
holder.journalThoughts.text = currentitem.thoughts.toString()
/* val bytes = android.util.Base64.decode(currentitem.imageUri,
Base64.DEFAULT)
val bitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.size)
holder.imageview.setImageBitmap(bitmap)*/
}
override fun getItemCount(): Int {
return itmlst.size
}
}
// lateinit var binding: JournalRowBinding
| Journal_App/app/src/main/java/com/example/journalapp/JournalRecyclerAdapter.kt | 447561432 |
package com.example.journalapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import com.example.journalapp.databinding.ActivityMainBinding
import com.google.firebase.Firebase
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.auth
class MainActivity : AppCompatActivity() {
lateinit var binding : ActivityMainBinding
//Firebase Auth
private lateinit var auth : FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this,R.layout.activity_main)
binding.registerbtn.setOnClickListener(){
val intent = Intent(this,SigninActivity::class.java)
startActivity(intent)
}
binding.loginbtn.setOnClickListener {
loginwithEmailandPassword(
binding.email.text.toString().trim(),
binding.password.text.toString().trim(),
)
}
//Auth ref
auth = Firebase.auth
}
private fun loginwithEmailandPassword(email: String, password: String) {
auth.signInWithEmailAndPassword(email,password)
.addOnCompleteListener(this){
task ->
if(task.isSuccessful){
//signinsuccess
var journal: JournalUser= JournalUser.instance!!
journal.userId = auth.currentUser?.uid
journal.username=auth.currentUser?.displayName
gotojournallist()
}
else{
Toast.makeText(
this,
"Authentication is Failed",
Toast.LENGTH_LONG
).show()
}
}
}
override fun onStart() {
super.onStart()
val currentUser = auth.currentUser
if(currentUser != null){
gotojournallist()
}
}
private fun gotojournallist() {
var intent = Intent(this,Journal_list::class.java)
startActivity(intent)
}
} | Journal_App/app/src/main/java/com/example/journalapp/MainActivity.kt | 3269460428 |
package com.example.journalapp
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.annotation.RequiresApi
import androidx.databinding.DataBindingUtil
import com.example.journalapp.databinding.ActivityAddJournalBinding
import com.google.firebase.Timestamp
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.ktx.auth
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import java.util.Date
class AddJournalActivity : AppCompatActivity() {
lateinit var binding:ActivityAddJournalBinding
//Credentials
var currentsUserId:String = " "
var currentUserName: String = " "
//firebase
lateinit var auth:FirebaseAuth
lateinit var user:FirebaseUser
//Firebase firestore
var db : FirebaseFirestore= FirebaseFirestore.getInstance()
lateinit var storageReference: StorageReference
var collectionRefresher: CollectionReference = db.collection("Journal")
lateinit var imageUri: Uri
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_add_journal)
storageReference = FirebaseStorage.getInstance().getReference()
auth = Firebase.auth
binding.apply {
postProgressBar.visibility = View.INVISIBLE
if (JournalUser.instance != null) {
// currentsUserId = JournalUser.instance!!.userId.toString()
currentsUserId = auth.currentUser?.uid.toString()
currentUserName = auth.currentUser?.displayName.toString()
postUsernameTextView.text = currentUserName
}
//Getting Image from the gallery
postCameraButton.setOnClickListener(){
var i : Intent=Intent(Intent.ACTION_GET_CONTENT)
i.setType("image/*")
startActivityForResult(i,1)
}
postSaveJournalButton.setOnClickListener() {
saveJournal()
}
}
}
@RequiresApi(Build.VERSION_CODES.O)
private fun saveJournal() {
val title: String = binding.postTitleEt.text.toString().trim()
val thoughts: String = binding.postDescriptionEt.text.toString().trim()
binding.postProgressBar.visibility = View.VISIBLE
if (title.isNotEmpty() && thoughts.isNotEmpty() && imageUri != null) {
val filepath: StorageReference = storageReference.child("journal_images")
.child("my_image_${System.currentTimeMillis() / 1000}")
filepath.putFile(imageUri!!).addOnSuccessListener {
filepath.downloadUrl.addOnSuccessListener { uri ->
val imageUri = uri.toString()
val timestamp = Timestamp(Date())
val journal = Journal(title, thoughts, imageUri, currentsUserId, timestamp, currentUserName)
val databaseRef = FirebaseDatabase.getInstance().getReference("Journals")
val journalId = databaseRef.push().key
journalId?.let {
databaseRef.child(it).setValue(journal)
.addOnSuccessListener {
binding.postProgressBar.visibility = View.INVISIBLE
startActivity(Intent(this, MainActivity::class.java))
finish()
}
.addOnFailureListener { e ->
binding.postProgressBar.visibility = View.INVISIBLE
Log.e("FirebaseError", "Failed to write data", e)
}
} ?: Log.e("FirebaseError", "Failed to generate a unique key for the journal entry")
}.addOnFailureListener { e ->
binding.postProgressBar.visibility = View.INVISIBLE
Log.e("FirebaseError", "Failed to upload image", e)
}
}
} else {
binding.postProgressBar.visibility = View.INVISIBLE
// Handle empty fields
}
}
@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == 1 && resultCode == RESULT_OK){
if(data != null){
imageUri = data.data!!
binding.postImageView.setImageURI(imageUri)//showig the image
}
}
}
override fun onStart() {
super.onStart()
user = auth.currentUser!!
}
override fun onStop() {
super.onStop()
if(auth != null){
}
}
}
| Journal_App/app/src/main/java/com/example/journalapp/AddJournalActivity.kt | 3816570758 |
package com.example.journalapp
class Journal{
var imageUri: String? = null
var thoughts: String? = null
var timestamp: com.google.firebase.Timestamp? = null
var title: String? = null
var userId: String? = null
var userName: String? = null
// No-argument constructor
//constructor()
// All-arguments constructor (if needed)
constructor(title: String?, thoughts: String?, imageUri: String?, userId: String?, timestamp: com.google.firebase.Timestamp?, userName: String?) {
this.title = title
this.thoughts = thoughts
this.imageUri = imageUri
this.userId = userId
this.timestamp = timestamp
this.userName = userName
}
constructor(){
}
}
| Journal_App/app/src/main/java/com/example/journalapp/Journal.kt | 1754180514 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.