content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package moe.matsuri.nya.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 == null || left.isEmpty()) {
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 == null || right.isEmpty()) {
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()
}
}
// Format Time
@SuppressLint("SimpleDateFormat")
val sdf1 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
fun timeStamp2Text(t: Long): String {
return sdf1.format(Date(t))
}
@SuppressLint("WrongConstant")
fun collapseStatusBar(context: Context) {
try {
val statusBarManager = context.getSystemService("statusbar")
val collapse = statusBarManager.javaClass.getMethod("collapsePanels")
collapse.invoke(statusBarManager)
} catch (_: Exception) {
}
}
}
| Ving-Vpn/app/src/main/java/moe/matsuri/nya/utils/Util.kt | 479632806 |
package moe.matsuri.nya.utils
import android.content.Context
import android.graphics.drawable.Drawable
import androidx.appcompat.content.res.AppCompatResources
import com.narcis.application.presentation.connection.Logs
import io.nekohasekai.sagernet.SagerNet
import java.io.File
// SagerNet Class
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
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 {
return when {
this > 1024 * 1024 * 1024 -> String.format(
"%.2f GiB", (this.toDouble() / 1024 / 1024 / 1024)
)
this > 1024 * 1024 -> String.format("%.2f MiB", (this.toDouble() / 1024 / 1024))
this > 1024 -> String.format("%.2f KiB", (this.toDouble() / 1024))
else -> "$this Bytes"
}
}
| Ving-Vpn/app/src/main/java/moe/matsuri/nya/utils/KotlinUtil.kt | 3959598290 |
package moe.matsuri.nya
import io.nekohasekai.sagernet.ftm.v2ray.V2RayConfig.DnsObject.ServerObject
import io.nekohasekai.sagernet.database.DataStore
object DNS {
fun ServerObject.applyDNSNetworkSettings(isDirect: Boolean) {
if (isDirect) {
if (DataStore.dnsNetwork.contains("NoDirectIPv4")) this.queryStrategy = "UseIPv6"
if (DataStore.dnsNetwork.contains("NoDirectIPv6")) this.queryStrategy = "UseIPv4"
} else {
if (DataStore.dnsNetwork.contains("NoRemoteIPv4")) this.queryStrategy = "UseIPv6"
if (DataStore.dnsNetwork.contains("NoRemoteIPv6")) this.queryStrategy = "UseIPv4"
}
}
}
| Ving-Vpn/app/src/main/java/moe/matsuri/nya/DNS.kt | 600051379 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[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 moe.matsuri.nya.neko
import moe.matsuri.nya.Protocols
import io.nekohasekai.sagernet.database.DataStore
import com.narcis.application.presentation.connection.Logs
import com.narcis.application.presentation.connection.getStr
import com.narcis.application.presentation.connection.runOnIoDispatcher
import libcore.Libcore
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")
}
| Ving-Vpn/app/src/main/java/moe/matsuri/nya/neko/NekoFmt.kt | 2578238087 |
package moe.matsuri.nya.neko
import android.annotation.SuppressLint
import android.os.Build
import android.webkit.*
import android.widget.Toast
import androidx.preference.Preference
import androidx.preference.PreferenceScreen
import io.nekohasekai.sagernet.BuildConfig
import moe.matsuri.nya.utils.Util
import moe.matsuri.nya.utils.JavaUtil
import com.narcis.application.presentation.connection.Logs
import com.narcis.application.presentation.connection.runBlockingOnMainDispatcher
import com.narcis.application.presentation.connection.runOnIoDispatcher
import com.narcis.application.presentation.connection.runOnMainDispatcher
import com.takisoft.preferencex.SimpleMenuPreference
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.ktx.readableMessage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.io.ByteArrayInputStream
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 {
val path = request?.url?.path ?: "404"
val file = File(NekoPluginManager.htmlPath(plgId), path)
var mime = "text/plain"
if (path.endsWith(".js")) mime = "application/javascript"
if (path.endsWith(".html")) mime = "text/html"
if (file.exists()) {
return WebResourceResponse(
mime, "UTF-8", FileInputStream(file)
)
} else {
return WebResourceResponse(
"text/plain", "UTF-8", ByteArrayInputStream("".toByteArray())
)
}
}
override fun onReceivedError(
view: WebView?, request: WebResourceRequest?, error: WebResourceError?
) {
super.onReceivedError(view, request, error)
if (Build.VERSION.SDK_INT >= 23 && error != null) {
Logs.e("WebView error description: ${error.description}")
}
Logs.e("WebView error: ${error.toString()}")
}
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
}
}
}
| Ving-Vpn/app/src/main/java/moe/matsuri/nya/neko/NekoJSInterface.kt | 1863053125 |
package moe.matsuri.nya.neko
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 com.github.shadowsocks.plugin.PluginManager.loadString
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.database.DataStore
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 {
var prefix = AUTHORITIES_PREFIX_NEKO_EXE
if (DataStore.exePreferProvider == 1) prefix = AUTHORITIES_PREFIX_SEKAI_EXE
return prefix
}
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
// try queryIntentContentProviders
var providers = getPluginOld(pluginId)
// try PackageCache
if (providers.isEmpty()) providers = getPluginNew(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]
}
fun getPluginNew(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 getPluginOld(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 }
}
}
| Ving-Vpn/app/src/main/java/moe/matsuri/nya/neko/Plugins.kt | 4146816538 |
package moe.matsuri.nya.neko
import androidx.preference.Preference
import androidx.preference.PreferenceScreen
import androidx.preference.SwitchPreference
import com.narcis.application.presentation.connection.forEach
import moe.matsuri.nya.utils.getDrawableByName
import com.narcis.application.presentation.connection.getStr
import com.takisoft.preferencex.EditTextPreference
import com.takisoft.preferencex.PreferenceCategory
import com.takisoft.preferencex.SimpleMenuPreference
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
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 = androidx.preference.EditTextPreference.SimpleSummaryProvider.getInstance()
// "PasswordSummaryProvider" -> summaryProvider = ProfileSettingsActivity.PasswordSummaryProvider
// }
// when (any.getStr("EditTextPreferenceModifiers")) {
// "Monospace" -> onBindEditTextListener = EditTextPreferenceModifiers.Monospace
// "Hosts" -> onBindEditTextListener = EditTextPreferenceModifiers.Hosts
// "Port" -> onBindEditTextListener = EditTextPreferenceModifiers.Port
// "Number" -> onBindEditTextListener = EditTextPreferenceModifiers.Number
// }
}
}
"SwitchPreference" -> {
p = SwitchPreference(context)
}
"SimpleMenuPreference" -> {
p = SimpleMenuPreference(context).apply {
summaryProvider = androidx.preference.ListPreference.SimpleSummaryProvider.getInstance()
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.setEntries(menuEntries.toTypedArray())
p.setEntryValues(menuEntryValues.toTypedArray())
}
}
} | Ving-Vpn/app/src/main/java/moe/matsuri/nya/neko/NekoPreferenceInflater.kt | 109943624 |
package moe.matsuri.nya.neko
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.bg.BaseService
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.utils.PackageCache
import io.nekohasekai.sagernet.SagerNet
import com.narcis.application.presentation.connection.forEach
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) {
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)
}
} | Ving-Vpn/app/src/main/java/moe/matsuri/nya/neko/NekoPluginManager.kt | 1808232879 |
package moe.matsuri.nya
import android.content.Context
import io.nekohasekai.sagernet.R
import moe.matsuri.nya.neko.NekoPluginManager
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.ProxyEntity.Companion.TYPE_NEKO
import io.nekohasekai.sagernet.ktx.app
import io.nekohasekai.sagernet.ktx.getColorAttr
// Settings for all protocols, built-in or plugin
object Protocols {
// Mux
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")
NekoPluginManager.getProtocols().forEach {
if (it.protocolConfig.optBoolean("canMux")) {
list.add(it.protocolId)
}
}
return list
}
// Deduplication
class Deduplication(
val bean: io.nekohasekai.sagernet.ftm.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
}
}
} | Ving-Vpn/app/src/main/java/moe/matsuri/nya/Protocols.kt | 678889445 |
package moe.matsuri.nya
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
}
| Ving-Vpn/app/src/main/java/moe/matsuri/nya/TempDatabase.kt | 2398002728 |
package moe.matsuri.nb4a.ui
import android.annotation.SuppressLint
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,
@SuppressLint("RestrictedApi") defStyleAttr: Int = TypedArrayUtils.getAttr(
context, R.attr.colorMaterial300,
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
}
}
} | Ving-Vpn/app/src/main/java/moe/matsuri/nb4a/ui/UrlTestPreference.kt | 2976122140 |
package com.narcis.application.di
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Qualifier
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class WallClock
@Suppress("TooManyFunctions")
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@WallClock
fun provideWallClock(): () -> Long = System::currentTimeMillis
} | Ving-Vpn/app/src/main/java/com/narcis/application/di/AppModule.kt | 3029524990 |
package com.narcis.application.presentation.viewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.narcis.application.presentation.utiles.validateSignInRequest
import com.narcis.application.presentation.viewModel.event.SendCodeEvent
import com.narcis.application.presentation.viewModel.state.SendCodeState
import com.narcis.domain.auth.CheckMailCodeUseCase
import com.narcis.domain.common.Result
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class AuthenticationViewModel @Inject constructor(
private val checkMailUseCase: CheckMailCodeUseCase
) : ViewModel() {
private val _state = MutableStateFlow(SendCodeState())
val state: StateFlow<SendCodeState> = _state
fun onEvent(event: SendCodeEvent) {
when (event) {
is SendCodeEvent.EmailQuery -> {
_state.value = SendCodeState(isLoading = true)
val isValid = validateSignInRequest(event.email)
_state.value = SendCodeState(
isValid = isValid.isValid,
message = isValid.message,
isLoading = true
)
if (isValid.isValid) {
_state.value = SendCodeState(
email = event.email,
message = isValid.message,
isLoading = true
)
sendVerificationCode()
}
}
SendCodeEvent.ClearEvent -> {
_state.value = SendCodeState(isLoading = false, isAlreadyRegistered = false)
}
}
}
private fun sendVerificationCode() {
viewModelScope.launch {
when (val result = checkMailUseCase(_state.value.email)) {
is Result.Error -> {
_state.value =
SendCodeState(
isLoading = false,
isValid = false,
isAlreadyRegistered = false,
message = "send email task failed"
)
}
Result.Loading -> {
_state.value = SendCodeState(isLoading = true, message = "email was sent")
}
is Result.Success -> {
when (result.data) {
409 -> {
_state.value = SendCodeState(
isLoading = false,
isValid = true,
isAlreadyRegistered = true,
message = "server error, check your network"
)
}
400 -> {
_state.value = SendCodeState(
isLoading = false,
isValid = true,
isAlreadyRegistered = false,
message = "server error, check your network"
)
}
200 -> {
_state.value = SendCodeState(
isLoading = false,
isValid = true,
isAlreadyRegistered = false,
message = "email accepted"
)
}
0 -> {
_state.value = SendCodeState(
isLoading = false,
isValid = false,
isAlreadyRegistered = false,
message = "Unknown Server Error"
)
}
else -> {
_state.value = SendCodeState(
isLoading = false,
isValid = false,
isAlreadyRegistered = false,
message = "task failed"
)
}
}
}
}
}
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/viewModel/AuthenticationViewModel.kt | 270003466 |
package com.narcis.application.presentation.viewModel.state
import com.narcis.domain.model.VerificationObject
data class VerificationCodeState(
val isLoading: Boolean = false,
val isSuccessful: Boolean = false,
val error: String = "",
val verificationObject: VerificationObject?= null,
val password: String = "",
val email: String = "",
val code: String = ""
)
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/viewModel/state/VerificationCodeState.kt | 1164321233 |
package com.narcis.application.presentation.viewModel.state
import com.narcis.application.presentation.viewModel.model.DefaultConfig
data class DefaultConfigState(
val isLoading: Boolean = false,
val configs: List<DefaultConfig>? = emptyList(),
val error: String = "",
val isRefreshing: Boolean = false,
)
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/viewModel/state/DefaultConfigState.kt | 634967215 |
package com.narcis.application.presentation.viewModel.state
import com.narcis.application.presentation.viewModel.state.model.SignInObj
data class SignInState(
val isLoading: Boolean = false,
val signIn: SignInObj?= null,
val isSuccessful: Boolean = false,
val isRequestSend: Boolean = true,
val error: String = ""
)
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/viewModel/state/SignInState.kt | 3293260225 |
package com.narcis.application.presentation.viewModel.state.model
data class SignUpObj (
val password: String, val email: String, val code: String
) | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/viewModel/state/model/SignUpObj.kt | 1537498947 |
package com.narcis.application.presentation.viewModel.state.model
data class SignInObj(
val email: String,
val password: String
) | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/viewModel/state/model/SignInObj.kt | 2289885129 |
package com.narcis.application.presentation.viewModel.state
data class SendCodeState(
val isLoading: Boolean = false,
val email: String = "",
val isValid: Boolean = false,
val isAlreadyRegistered: Boolean = false,
val message: String = ""
) | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/viewModel/state/SendCodeState.kt | 1797798886 |
package com.narcis.application.presentation.viewModel.model
data class DefaultConfig(
val id: Long? = 0L,
val address: String? = "",
val alpn: String? = "",
val country: String? = "",
val fingerprint: String? = "",
val flag: String? = "",
val password: String? = "",
val port: Int? = 0,
val protocol: String? = "",
val security: String? = "",
val sni: String? = "",
val type: String? = "",
val url: String? = "",
)
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/viewModel/model/DefaultConfig.kt | 1795671625 |
package com.narcis.application.presentation.viewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.narcis.application.presentation.mapper.mapToDomain
import com.narcis.application.presentation.viewModel.event.SignInEvent
import com.narcis.application.presentation.viewModel.state.SignInState
import com.narcis.application.presentation.viewModel.state.model.SignInObj
import com.narcis.domain.auth.SignInPasswordUseCase
import com.narcis.domain.common.Result
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class SignInViewModel @Inject constructor(
private val signInPasswordUseCase: SignInPasswordUseCase
) : ViewModel() {
// var state by mutableStateOf(SignInState())
private val _state = MutableStateFlow(SignInState())
val state: StateFlow<SignInState> = _state
fun onEvent(event: SignInEvent) {
when (event) {
is SignInEvent.SignInQuery -> {
_state.value = SignInState(signIn = SignInObj(event.email, event.password), isRequestSend = true)
requestSignIn()
}
SignInEvent.ClearEvent -> {
}
}
}
private fun requestSignIn() {
viewModelScope.launch {
signInPasswordUseCase(_state.value.signIn!!.mapToDomain()).collect { result ->
when (result) {
is Result.Error -> {
_state.value = SignInState(isLoading = false, error = result.exception.toString(), isSuccessful = false)
}
Result.Loading -> {
_state.value = SignInState(isLoading = true)
}
is Result.Success -> {
_state.value = SignInState(isLoading = false, isSuccessful = true)
}
}
}
}
}
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/viewModel/SignInViewModel.kt | 2440804812 |
package com.narcis.application.presentation.viewModel
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class PasswordViewModel @Inject constructor(
savedStateHandle: SavedStateHandle
): ViewModel(){
private val _email = mutableStateOf("")
val email: State<String> = _email
init {
savedStateHandle.get<String>("email")?.let {email ->
_email.value = email
}
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/viewModel/PasswordViewModel.kt | 3516821118 |
package com.narcis.application.presentation.viewModel
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.narcis.application.presentation.viewModel.event.SendVerificationEvent
import com.narcis.application.presentation.viewModel.state.SendCodeState
import com.narcis.application.presentation.viewModel.state.VerificationCodeState
import com.narcis.domain.auth.SendVerificationCodeUseCase
import com.narcis.domain.auth.SignUpVerificationCodeUseCase
import com.narcis.domain.common.Result
import com.narcis.domain.model.VerificationObject
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class VerificationCodeViewModel @Inject constructor(
private val signUpWithVerificationCodeUseCase: SignUpVerificationCodeUseCase,
private val sendCodeVerificationUseCase: SendVerificationCodeUseCase,
savedStateHandle: SavedStateHandle
) : ViewModel() {
var state by mutableStateOf(VerificationCodeState())
private val _resendState = MutableStateFlow(SendCodeState())
val resendState: StateFlow<SendCodeState> = _resendState
var email = ""
private var password = ""
init {
savedStateHandle.get<String>("email")?.let {eml ->
email = eml
}
savedStateHandle.get<String>("password")?.let {psw ->
password = psw
}
resendVerificationCode(email)
}
fun onEvent(event: SendVerificationEvent) {
when (event) {
is SendVerificationEvent.SignInQuery -> {
sendCodeForVerification(VerificationObject(password = password, email = email, code = event.code))
}
is SendVerificationEvent.EmailQuery -> {
resendVerificationCode(email)
}
}
}
private fun sendCodeForVerification(verificationObject: VerificationObject) {
viewModelScope.launch {
signUpWithVerificationCodeUseCase(verificationObject).collect { result ->
when (result) {
is Result.Error -> {
state = state.copy(
isLoading = false,
isSuccessful = false,
error = result.exception.toString()
)
}
Result.Loading -> {
state = state.copy(isLoading = true)
}
is Result.Success -> {
state = state.copy(isLoading = false, isSuccessful = true)
}
}
}
}
}
private fun resendVerificationCode(email: String) {
viewModelScope.launch {
when (val result = sendCodeVerificationUseCase(email)) {
is Result.Error -> {
_resendState.value =
SendCodeState(isLoading = false, isValid = false, isAlreadyRegistered = false, message = "send email task failed")
}
Result.Loading -> {
_resendState.value = SendCodeState(isLoading = true, message = "email was sent")
}
is Result.Success -> {
when (result.data) {
400 -> {
_resendState.value = SendCodeState(
isLoading = false,
isValid = true,
isAlreadyRegistered = true,
message = "server error, check your network"
)
}
200 -> {
_resendState.value = SendCodeState(
isLoading = false,
isValid = true,
isAlreadyRegistered = false,
message = "email accepted"
)
}
0 -> {
_resendState.value = SendCodeState(
isLoading = false,
isValid = false,
isAlreadyRegistered = false,
message = "Unknown Server Error"
)
}
else -> {
_resendState.value = SendCodeState(
isLoading = false,
isValid = false,
isAlreadyRegistered = false,
message = "task failed"
)
}
}
}
}
}
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/viewModel/VerificationCodeViewModel.kt | 3989583054 |
package com.narcis.application.presentation.viewModel.event
sealed class SendCodeEvent{
data class EmailQuery(val email: String): SendCodeEvent()
object ClearEvent: SendCodeEvent()
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/viewModel/event/SendCodeEvent.kt | 231107860 |
package com.narcis.application.presentation.viewModel.event
sealed class SendVerificationEvent {
data class SignInQuery(val email: String, val password: String, val code: String) :
SendVerificationEvent()
object EmailQuery: SendVerificationEvent()
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/viewModel/event/SendVerificationEvent.kt | 1555572680 |
package com.narcis.application.presentation.viewModel.event
sealed class SignInEvent {
data class SignInQuery(val email: String, val password: String): SignInEvent()
object ClearEvent: SignInEvent()
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/viewModel/event/SignInEvent.kt | 300270367 |
package com.narcis.application.presentation.viewModel.event
import android.content.Context
import com.narcis.application.presentation.viewModel.model.DefaultConfig
sealed class ProxyEvent {
data class ConfigEvent(val defaultConfig: DefaultConfig, val current: Context) : ProxyEvent()
object triggerRefresh: ProxyEvent()
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/viewModel/event/ProxyEvent.kt | 2479317814 |
package com.narcis.application.presentation.viewModel
import android.content.Context
import android.net.Uri
import androidx.activity.result.ActivityResultLauncher
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.narcis.application.presentation.connection.SubscriptionFoundException
import com.narcis.application.presentation.connection.onMainDispatcher
import com.narcis.application.presentation.connection.runOnDefaultDispatcher
import com.narcis.application.presentation.utiles.isInternetConnected
import com.narcis.application.presentation.viewModel.event.ProxyEvent
import com.narcis.application.presentation.viewModel.model.DefaultConfig
import com.narcis.application.presentation.viewModel.state.DefaultConfigState
import com.narcis.domain.common.Result
import com.narcis.domain.connection.GetDefaultConfigUseCase
import com.github.shadowsocks.plugin.ProfileManager
import dagger.hilt.android.lifecycle.HiltViewModel
import io.nekohasekai.sagernet.GroupType
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.SubscriptionType
import io.nekohasekai.sagernet.bg.BaseService
import io.nekohasekai.sagernet.bg.SagerConnection
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.GroupManager
import io.nekohasekai.sagernet.database.ProxyEntity
import io.nekohasekai.sagernet.database.ProxyGroup
import io.nekohasekai.sagernet.database.SagerDatabase
import io.nekohasekai.sagernet.database.SubscriptionBean
import io.nekohasekai.sagernet.ftm.AbstractBean
import io.nekohasekai.sagernet.ftm.KryoConverters
import io.nekohasekai.sagernet.group.GroupUpdater
import io.nekohasekai.sagernet.group.RawUpdater
import io.nekohasekai.sagernet.ktx.readableMessage
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import moe.matsuri.nya.utils.Util
import timber.log.Timber
import javax.inject.Inject
@HiltViewModel
class DefaultConfigViewModel @Inject constructor(
private val getDefaultConfigUseCase: GetDefaultConfigUseCase,
) : ViewModel() {
private var _configState = MutableStateFlow(DefaultConfigState())
val configState: StateFlow<DefaultConfigState> = _configState
private var _selectedProxy = MutableStateFlow(DefaultConfig())
val selectedProxy: StateFlow<DefaultConfig?> = _selectedProxy
val connection = SagerConnection(true)
var selected = false
var configurationIdList: MutableList<Long> = mutableListOf()
val configurationList = HashMap<Long, ProxyEntity>()
val select: Boolean = false
init {
getAllConfigs()
}
fun onEvent(event: ProxyEvent) {
var selectedProfileIndex = -1
when (event) {
is ProxyEvent.ConfigEvent -> {
val profileAccess = Mutex()
val selectedProxy = event.defaultConfig.id ?: DataStore.selectedProxy
val proxyEntity by lazy { SagerDatabase.proxyDao.getById(selectedProxy) }
_selectedProxy.value = event.defaultConfig
var update: Boolean
var lastSelected: Long
// (ConfigurationFragment.SelectCallback).returnProfile(selectedItem?.id ?: 1L)
runOnDefaultDispatcher {
profileAccess.withLock {
update = DataStore.selectedProxy != event.defaultConfig.id
lastSelected = DataStore.selectedProxy
Timber.i("^^", "timber workes")
DataStore.selectedProxy = event.defaultConfig.id ?: 1L
// onMainDispatcher {
// selectedView.visibility = View.VISIBLE
// }
}
}
}
ProxyEvent.triggerRefresh -> {
_configState.value = DefaultConfigState(isLoading = true, isRefreshing = true)
getAllConfigs()
}
}
}
private fun getAllConfigs() {
viewModelScope.launch {
var tryTimes = 0
getDefaultConfigUseCase(Unit).collect { result ->
when (result) {
is Result.Error -> {
_configState.value = DefaultConfigState(
error = result.exception.message ?: "An unexpected error occured",
isRefreshing = false
)
if (tryTimes < 5) {
getAllConfigs()
tryTimes++
}
}
Result.Loading -> {
_configState.value =
DefaultConfigState(isLoading = true, isRefreshing = false)
}
is Result.Success -> {
var id = 1
SagerDatabase.proxyDao.reset()
SagerDatabase.proxyDao.deleteAllProxyEntities()
SagerDatabase.proxyDao.clearPrimaryKey()
if (result.data.isEmpty() && tryTimes < 5) {
getAllConfigs()
tryTimes++
}
result.data.forEach { config ->
try {
var url = ""
if (config.protocol == "SSH") {
val stringBuilder = StringBuilder()
stringBuilder.append("ssh://")
stringBuilder.append("&address=").append(config.address)
stringBuilder.append("&port=").append(config.port)
stringBuilder.append("&username=").append(config.username)
stringBuilder.append("&password=").append(config.password)
url = stringBuilder.toString()
} else {
url = config.url
}
val proxies = RawUpdater.parseRaw(url)
if (proxies.isNullOrEmpty()) {
onMainDispatcher {
Timber.e("Error", "Proxy Not Found")
}
} else {
import(proxies)
}
} catch (e: SubscriptionFoundException) {
importSubscription(Uri.parse(e.link))
}
// reloadProfiles()
}
_configState.value = DefaultConfigState(
configs = result.data.map { it ->
DefaultConfig(
(id++).toLong(),
it.address,
it.alpn,
it.country,
it.fingerprint,
it.flag,
it.password,
it.port,
it.protocol,
it.security,
it.sni,
it.type,
it.url
)
}, isRefreshing = false)
_configState.value.let {
_selectedProxy.value = _configState.value.configs?.get(0)!!
}
}
}
}
}
}
suspend fun import(proxies: List<AbstractBean>) {
val targetId = DataStore.selectedGroupForImport()
for (proxy in proxies) {
ProfileManager.createProfile(targetId, proxy)
}
onMainDispatcher {
DataStore.editingGroup = targetId
Timber.i("proxies", proxies.size)
// snackbar(
// [email protected](
// R.plurals.added, proxies.size, proxies.size
// )
// ).show()
}
}
private fun getItem(profileId: Long): ProxyEntity {
var profile = configurationList[profileId]
if (profile == null) {
profile = ProfileManager.getProfile(profileId)
if (profile != null) {
configurationList[profileId] = profile
}
}
return profile!!
}
private fun getItemAt(index: Int) = getItem(configurationIdList[index])
suspend fun importSubscription(uri: Uri) {
val group: ProxyGroup
val url = uri.getQueryParameter("url")
if (!url.isNullOrBlank()) {
group = ProxyGroup(type = GroupType.SUBSCRIPTION)
val subscription =
SubscriptionBean()
group.subscription = subscription
// cleartext format
subscription.link = url
group.name = uri.getQueryParameter("name")
val type = uri.getQueryParameter("type")
when (type?.lowercase()) {
"sip008" -> {
subscription.type = SubscriptionType.SIP008
}
}
} else {
val data = uri.encodedQuery.takeIf { !it.isNullOrBlank() } ?: return
try {
group = KryoConverters.deserialize(
ProxyGroup().apply { export = true },
Util.zlibDecompress(Util.b64Decode(data))
).apply {
export = false
}
} catch (e: Exception) {
onMainDispatcher {
// alert(e.readableMessage).show()
Timber.i("vpns", e.readableMessage)
}
return
}
}
val name = group.name.takeIf { !it.isNullOrBlank() } ?: group.subscription?.link
?: group.subscription?.token
if (name.isNullOrBlank()) return
group.name = group.name.takeIf { !it.isNullOrBlank() }
?: ("Subscription #" + System.currentTimeMillis())
onMainDispatcher {
// displayFragmentWithId(R.id.nav_group)
finishImportSubscription(group)
}
}
private suspend fun finishImportSubscription(subscription: ProxyGroup) {
GroupManager.createGroup(subscription)
GroupUpdater.startUpdate(subscription, true)
}
private fun changeState(
state: BaseService.State,
msg: String? = null,
animate: Boolean = false,
) {
DataStore.serviceState = state
if (!DataStore.serviceState.connected) {
}
when (state) {
BaseService.State.Stopped -> {
runOnDefaultDispatcher {
// refresh view
ProfileManager.postUpdate(DataStore.currentProfile)
}
}
else -> {}
}
}
fun onClickConnect(connect: ActivityResultLauncher<Void?>, context: Context) {
// val connect = activityContext.registerForActivityResult(StartService()) {}
val isInternetConnected = isInternetConnected(context)
if (isInternetConnected) {
if (DataStore.serviceState.canStop) SagerNet.stopService() else connect.launch(
null
)
}
// connect.launch(null)
}
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/viewModel/DefaultConfigViewModel.kt | 1402483483 |
/*
* Copyright 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
*
* https://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 com.narcis.application.presentation.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(percent = 50),
medium = RoundedCornerShape(20.dp),
large = RoundedCornerShape(0.dp)
)
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/ui/theme/Shape.kt | 332690809 |
package com.narcis.application.presentation.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
val Shadow12 = Color(0xFF037FC9)
val Shadow11 = Color(0xff001787)
val Shadow10 = Color(0xff00119e)
val Shadow9 = Color(0xff0009b3)
val Shadow8 = Color(0xff0200c7)
val Shadow7 = Color(0xff0e00d7)
val Shadow6 = Color(0xff2a13e4)
val Shadow5 = Color(0xff4b30ed)
val Shadow4 = Color(0xff7057f5)
val Shadow3 = Color(0xff9b86fa)
val Shadow2 = Color(0xffc8bbfd)
val Shadow1 = Color(0xffded6fe)
val Shadow0 = Color(0xfff4f2ff)
val Ocean13 = Color(0xFF005673)
val Ocean12 = Color(0xFF0988D7)
val Ocean11 = Color(0xff005687)
val Ocean10 = Color(0xff006d9e)
val Ocean9 = Color(0xff0087b3)
val Ocean8 = Color(0xff00a1c7)
val Ocean7 = Color(0xff00b9d7)
val Ocean6 = Color(0xff13d0e4)
val Ocean5 = Color(0xff30e2ed)
val Ocean4 = Color(0xff57eff5)
val Ocean3 = Color(0xff86f7fa)
val Ocean2 = Color(0xffbbfdfd)
val Ocean1 = Color(0xffd6fefe)
val Ocean0 = Color(0xfff2ffff)
val Sky0 = Color(0xFFB6E4FF)
val Sky1 = Color(0xFF8CC8FF)
val Lavender11 = Color(0xff170085)
val Lavender10 = Color(0xff23009e)
val Lavender9 = Color(0xff3300b3)
val Lavender8 = Color(0xff4400c7)
val Lavender7 = Color(0xff5500d7)
val Lavender6 = Color(0xff6f13e4)
val Lavender5 = Color(0xff8a30ed)
val Lavender4 = Color(0xffa557f5)
val Lavender3 = Color(0xffc186fa)
val Lavender2 = Color(0xffdebbfd)
val Lavender1 = Color(0xffebd6fe)
val Lavender0 = Color(0xfff9f2ff)
val Violate0 = Color(0xFF94A3B8)
val Blue1 = Color(0xFF005696)
val Blue0 = Color(0xFF11A8FD)
val FunctionalRed = Color(0xffd00036)
val FunctionalRedDark = Color(0xffea6d7e)
val Neutral8 = Color(0xff121212)
val Neutral7 = Color(0xde000000)
val Neutral6 = Color(0x99000000)
val Neutral5 = Color(0x61000000)
val Neutral4 = Color(0x1f000000)
val Neutral3 = Color(0x1fffffff)
val Neutral2 = Color(0xFF818A99)
val Neutral1 = Color(0xbdffffff)
val Neutral0 = Color(0xffffffff)
val FunctionalDarkGrey = Color(0xff2e2e2e)
const val AlphaNearOpaque = 0.95f
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/ui/theme/Color.kt | 1496505079 |
package com.narcis.application.presentation.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.Colors
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.graphics.Color
import com.google.accompanist.systemuicontroller.rememberSystemUiController
private val DarkColorPalette = ApplicationColors(
gradiantBackground = listOf(Shadow11, Shadow7, Shadow4, Lavender7),
uiBackground = FunctionalDarkGrey,
textPrimary = Neutral0,
textSecondry = Neutral1,
textHelp = Neutral6,
iconGradiant = listOf(Ocean9, Shadow11),
welcomeGradiant = listOf(Shadow12, Ocean12),
neturalBackGround = listOf(Neutral1,Violate0,Neutral0),
error = FunctionalRedDark,
navigationPrimary = Neutral3,
iconInteractiveInactive = Neutral6,
isDark = true
)
private val LightColorPalette = ApplicationColors(
gradiantBackground = listOf(Shadow11, Shadow7, Shadow4, Lavender7),
uiBackground = Neutral0,
textPrimary = Neutral7,
textSecondry = Neutral2,
textHelp = Neutral1,
iconGradiant = listOf(Ocean9, Shadow11),
welcomeGradiant = listOf(Shadow12, Ocean12),
neturalBackGround = listOf(Neutral1,Violate0,Neutral0),
error = FunctionalRed,
navigationPrimary = Lavender2,
iconInteractiveInactive = Neutral1,
isDark = false
)
@Composable
fun narcisApplicationTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colorPalette = if (darkTheme) DarkColorPalette else LightColorPalette
val sysController = rememberSystemUiController()
SideEffect {
sysController.setSystemBarsColor(
color = colorPalette.uiBackground.copy(AlphaNearOpaque)
)
}
ProvideApplicationColors(colors = colorPalette) {
MaterialTheme(
colors = debugColors(darkTheme),
typography = Typography,
shapes = Shapes,
content = content
)
}
}
private val LocalApplicationColor = staticCompositionLocalOf<ApplicationColors> {
error("no palette provided")
}
object ApplicationTheme {
val colors: ApplicationColors
@Composable
get() = LocalApplicationColor.current
}
@Composable
fun ProvideApplicationColors(
colors: ApplicationColors,
content: @Composable () -> Unit
) {
val colorPalette = remember {
colors.copy()
}
colorPalette.update(colors)
CompositionLocalProvider(LocalApplicationColor provides colorPalette, content = content)
}
@Stable
class ApplicationColors(
gradiantBackground: List<Color>,
uiBackground: Color,
textPrimary: Color,
textSecondry: Color,
textHelp: Color,
iconGradiant: List<Color>,
welcomeGradiant: List<Color>,
neturalBackGround: List<Color>,
error: Color,
navigationPrimary: Color,
iconInteractiveInactive: Color,
isDark: Boolean
) {
var gradiantBackground by mutableStateOf(gradiantBackground)
private set
var uiBackground by mutableStateOf(uiBackground)
private set
var textPrimary by mutableStateOf(textPrimary)
private set
var textSecondry by mutableStateOf(textSecondry)
private set
var textHelp by mutableStateOf(textHelp)
private set
var iconGradiant by mutableStateOf(iconGradiant)
private set
var welcomeGradiant by mutableStateOf(welcomeGradiant)
private set
var neturalBackGround by mutableStateOf(neturalBackGround)
var error by mutableStateOf(error)
private set
var isDark by mutableStateOf(isDark)
private set
var navigationPrimary by mutableStateOf(navigationPrimary)
private set
var iconInteractiveInactive by mutableStateOf(iconInteractiveInactive)
private set
fun update(other: ApplicationColors) {
gradiantBackground = other.gradiantBackground
uiBackground = other.uiBackground
textPrimary = other.textPrimary
textSecondry = other.textSecondry
textHelp = other.textHelp
iconGradiant = other.iconGradiant
welcomeGradiant = other.welcomeGradiant
neturalBackGround = other.neturalBackGround
error = other.error
navigationPrimary = other.navigationPrimary
iconInteractiveInactive = other.iconInteractiveInactive
isDark = other.isDark
}
fun copy(): ApplicationColors = ApplicationColors(
gradiantBackground = gradiantBackground,
uiBackground = uiBackground,
textPrimary = textPrimary,
textSecondry = textSecondry,
textHelp = textHelp,
iconGradiant = iconGradiant,
welcomeGradiant = welcomeGradiant,
neturalBackGround = neturalBackGround,
error = error,
navigationPrimary = navigationPrimary,
iconInteractiveInactive= iconInteractiveInactive,
isDark = isDark,
)
}
fun debugColors(
darkTheme: Boolean,
debugColor: Color = Color.Magenta
) = Colors(
primary = debugColor,
primaryVariant = debugColor,
secondary = debugColor,
secondaryVariant = debugColor,
background = debugColor,
surface = debugColor,
error = debugColor,
onPrimary = debugColor,
onSecondary = debugColor,
onBackground = debugColor,
onSurface = debugColor,
onError = debugColor,
isLight = !darkTheme
) | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/ui/theme/Theme.kt | 3177540741 |
package com.narcis.application.presentation.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import io.nekohasekai.sagernet.R
private val Montserrat = FontFamily(
Font(R.font.montserrat_light, FontWeight.Light),
Font(R.font.montserrat_regular, FontWeight.Normal),
Font(R.font.montserrat_medium, FontWeight.Medium),
Font(R.font.montserrat_semibold, FontWeight.SemiBold)
)
private val Karla = FontFamily(
Font(R.font.karla_regular, FontWeight.Normal),
Font(R.font.karla_bold, FontWeight.Bold)
)
val Typography = Typography(
h1 = TextStyle(
fontFamily = Montserrat,
fontSize = 96.sp,
fontWeight = FontWeight.Light,
lineHeight = 117.sp,
letterSpacing = (-1.5).sp
),
h2 = TextStyle(
fontFamily = Montserrat,
fontSize = 60.sp,
fontWeight = FontWeight.Light,
lineHeight = 73.sp,
letterSpacing = (-0.5).sp
),
h3 = TextStyle(
fontFamily = Montserrat,
fontSize = 48.sp,
fontWeight = FontWeight.Normal,
lineHeight = 59.sp
),
h4 = TextStyle(
fontFamily = Montserrat,
fontSize = 30.sp,
fontWeight = FontWeight.SemiBold,
lineHeight = 37.sp
),
h5 = TextStyle(
fontFamily = Montserrat,
fontSize = 24.sp,
fontWeight = FontWeight.SemiBold,
lineHeight = 29.sp
),
h6 = TextStyle(
fontFamily = Montserrat,
fontSize = 20.sp,
fontWeight = FontWeight.SemiBold,
lineHeight = 24.sp
),
subtitle1 = TextStyle(
fontFamily = Montserrat,
fontSize = 16.sp,
fontWeight = FontWeight.SemiBold,
lineHeight = 24.sp,
letterSpacing = 0.15.sp
),
subtitle2 = TextStyle(
fontFamily = Karla,
fontSize = 14.sp,
fontWeight = FontWeight.Bold,
lineHeight = 24.sp,
letterSpacing = 0.1.sp
),
body1 = TextStyle(
fontFamily = Karla,
fontSize = 16.sp,
fontWeight = FontWeight.Normal,
lineHeight = 28.sp,
letterSpacing = 0.15.sp
),
body2 = TextStyle(
fontFamily = Montserrat,
fontSize = 14.sp,
fontWeight = FontWeight.Medium,
lineHeight = 20.sp,
letterSpacing = 0.25.sp
),
button = TextStyle(
fontFamily = Montserrat,
fontSize = 14.sp,
fontWeight = FontWeight.SemiBold,
lineHeight = 16.sp,
letterSpacing = 1.25.sp
),
caption = TextStyle(
fontFamily = Karla,
fontSize = 12.sp,
fontWeight = FontWeight.Bold,
lineHeight = 16.sp,
letterSpacing = 0.4.sp
),
overline = TextStyle(
fontFamily = Montserrat,
fontSize = 12.sp,
fontWeight = FontWeight.SemiBold,
lineHeight = 16.sp,
letterSpacing = 1.sp
)
) | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/ui/theme/Type.kt | 3856192694 |
package com.narcis.application.presentation.ui
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.unit.dp
object UiConstants {
val TextIconSpacing = 2.dp
val BottomNavLabelTransformOrigin = TransformOrigin(0f, 0.5f)
val BottomNavHeight = 60.dp
val BottomNavIndicatorShape = RoundedCornerShape(percent = 50)
val BottomNavigationItemPadding = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/ui/UiConstants.kt | 1850519741 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[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 com.narcis.application.presentation.uiActivity
import libcore.Libcore
import java.io.InputStream
import java.io.OutputStream
object Logs {
private fun mkTag(): String {
val stackTrace = Thread.currentThread().stackTrace
return stackTrace[4].className.substringAfterLast(".")
}
// level int use logrus.go
fun v(message: String) {
Libcore.nekoLogWrite(6, mkTag(), message)
}
fun v(message: String, exception: Throwable) {
Libcore.nekoLogWrite(6, mkTag(), message + "\n" + exception.stackTraceToString())
}
fun d(message: String) {
Libcore.nekoLogWrite(5, mkTag(), message)
}
fun d(message: String, exception: Throwable) {
Libcore.nekoLogWrite(5, mkTag(), message + "\n" + exception.stackTraceToString())
}
fun i(message: String) {
Libcore.nekoLogWrite(4, mkTag(), message)
}
fun i(message: String, exception: Throwable) {
Libcore.nekoLogWrite(4, mkTag(), message + "\n" + exception.stackTraceToString())
}
fun w(message: String) {
Libcore.nekoLogWrite(3, mkTag(), message)
}
fun w(message: String, exception: Throwable) {
Libcore.nekoLogWrite(3, mkTag(), message + "\n" + exception.stackTraceToString())
}
fun w(exception: Throwable) {
Libcore.nekoLogWrite(3, mkTag(), exception.stackTraceToString())
}
fun e(message: String) {
Libcore.nekoLogWrite(2, mkTag(), message)
}
fun e(message: String, exception: Throwable) {
Libcore.nekoLogWrite(2, mkTag(), message + "\n" + exception.stackTraceToString())
}
fun e(exception: Throwable) {
Libcore.nekoLogWrite(2, mkTag(), exception.stackTraceToString())
}
}
fun InputStream.use(out: OutputStream) {
use { input ->
out.use { output ->
input.copyTo(output)
}
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/uiActivity/Logs.kt | 3220580477 |
package com.narcis.application.presentation
import android.content.Intent
import android.os.Bundle
import android.os.RemoteException
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.ActivityResultLauncher
import androidx.annotation.StringRes
import androidx.compose.animation.AnimatedContentTransitionScope
import androidx.compose.animation.core.tween
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.view.WindowCompat
import androidx.lifecycle.lifecycleScope
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.preference.PreferenceDataStore
import com.narcis.application.presentation.bottomNavigation.RootScreen
import com.narcis.application.presentation.connection.VpnRequestActivity
import com.narcis.application.presentation.connection.runOnDefaultDispatcher
import com.narcis.application.presentation.mainConnection.MainConnectionScreen
import com.narcis.application.presentation.navigation.Navigation
import com.narcis.application.presentation.screens.landing.Landing
import com.narcis.application.presentation.screens.landing.Welcome
import com.narcis.application.presentation.screens.purchase.PurchaseScreen
import com.narcis.application.presentation.screens.signUp.EmailSignIn
import com.narcis.application.presentation.screens.signUp.EmailSignUpScreen
import com.narcis.application.presentation.screens.signUp.PasswordSignUp
import com.narcis.application.presentation.screens.signUp.VerificationSignUp
import com.narcis.application.presentation.ui.theme.narcisApplicationTheme
import com.narcis.application.presentation.utiles.setupCachePolicy
import com.narcis.domain.auth.CheckSignedInUseCase
import com.narcis.domain.common.Result
import com.github.shadowsocks.plugin.ProfileManager
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
import io.nekohasekai.sagernet.Key
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.aidl.AppStats
import io.nekohasekai.sagernet.aidl.ISagerNetService
import io.nekohasekai.sagernet.aidl.TrafficStats
import io.nekohasekai.sagernet.bg.BaseService
import io.nekohasekai.sagernet.bg.SagerConnection
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.GroupManager
import io.nekohasekai.sagernet.database.ProxyGroup
import io.nekohasekai.sagernet.database.preference.OnPreferenceDataStoreChangeListener
import io.nekohasekai.sagernet.ftm.PluginEntry
import io.nekohasekai.sagernet.group.GroupInterfaceAdapter
import io.nekohasekai.sagernet.group.GroupUpdater
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity :
ComponentActivity(),
SagerConnection.Callback,
OnPreferenceDataStoreChangeListener {
@Inject
lateinit var checkSignedInUseCase: CheckSignedInUseCase
private val connectionState = mutableStateOf(BaseService.State.Idle)
private val trafficState = mutableStateOf(TrafficStats())
val connection = SagerConnection(true)
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
super.onCreate(savedInstanceState)
createDatFile()
setupCachePolicy(this)
WindowCompat.setDecorFitsSystemWindows(window, false)
val connect = registerForActivityResult(VpnRequestActivity.StartService()) {
if (it) Toast.makeText(this, R.string.vpn_permission_denied, Toast.LENGTH_LONG).show()
}
changeState(BaseService.State.Idle)
connection.disconnect(this)
connection.connect(this, this)
DataStore.configurationStore.registerChangeListener(this)
GroupManager.userInterface = GroupInterfaceAdapter(this)
if (intent?.action == Intent.ACTION_VIEW) {
onNewIntent(intent)
}
lifecycleScope.launch(Dispatchers.Main) {
val result = checkSignedInUseCase(Unit)
when (result) {
is Result.Error -> {
Log.i("show", "shwo error")
}
Result.Loading -> {
Log.i("show", "show Loading")
}
is Result.Success -> {
setContent {
narcisApplicationTheme {
RootScreen(
defaultRoute = if (result.data) {Navigation.MainConnectionScreen.route} else {Navigation.LandingScreen.route},
connect = connect,
connectionState = connectionState,
trafficState = trafficState
)
}
}
}
}
}
}
@Composable
fun LoginApplication(
defaultRoute: String,
connect: ActivityResultLauncher<Void?>,
connectionState: MutableState<BaseService.State>,
trafficState: MutableState<TrafficStats>
) {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = defaultRoute,
builder = {
composable(
route = Navigation.LandingScreen.route,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(700)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(700)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
content = { Landing(navController = navController) },
)
composable(Navigation.WelcomeScreen.route,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(700)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(700)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
}, content = { Welcome(navController) })
composable(
Navigation.EmailSignUpScreen.route,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(700)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(700)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
content = { EmailSignUpScreen(navController = navController) }
)
composable(
Navigation.PasswordScreen.route + "/{email}",
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(700)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(700)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
content = { PasswordSignUp(navController = navController) }
)
composable(
Navigation.VerificationCodeScreen.route + "/{email}" + "/{password}",
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(700)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(700)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
content = { VerificationSignUp(navController) }
)
composable(
Navigation.MainConnectionScreen.route,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(700)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(700)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
content = {
MainConnectionScreen(
navControle = navController,
connect = connect,
state = connectionState,
trafficState = trafficState
)
}
)
composable(
Navigation.EmailSignInScreen.route,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(700)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(700)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
content = { EmailSignIn(navController = navController) }
)
composable(
Navigation.PurchasePlanScreen.route,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(700)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(700)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
content = { PurchaseScreen(navController = navController) }
)
}
)
}
fun ruleCreated() {
// navigation.menu.findItem(R.id.nav_route).isChecked = true
// supportFragmentManager.beginTransaction()
// .replace(R.id.fragment_holder, RouteFragment())
// .commitAllowingStateLoss()
if (DataStore.serviceState.started) {
snackbar(getString(R.string.restart)).setAction(R.string.apply) {
SagerNet.reloadService()
}.show()
}
}
private fun changeState(
state: BaseService.State,
msg: String? = null,
animate: Boolean = false,
) {
connectionState.value = state
DataStore.serviceState = state
if (!DataStore.serviceState.connected) {
statsUpdated(emptyList())
}
// binding.fab.changeState(state, DataStore.serviceState, animate)
// binding.stats.changeState(state)
if (msg != null) {
// snackbar(getString(R.string.vpn_error, msg)).show()
}
when (state) {
BaseService.State.Stopped -> {
runOnDefaultDispatcher {
// refresh view
ProfileManager.postUpdate(DataStore.currentProfile)
}
}
else -> {}
}
}
override fun stateChanged(state: BaseService.State, profileName: String?, msg: String?) {
changeState(state, msg, true)
}
override fun onServiceConnected(service: ISagerNetService) = changeState(
try {
BaseService.State.values()[service.state]
} catch (_: RemoteException) {
BaseService.State.Idle
}
)
override fun onPreferenceDataStoreChanged(store: PreferenceDataStore, key: String) {
when (key) {
Key.SERVICE_MODE -> onBinderDied()
Key.PROXY_APPS, Key.BYPASS_MODE, Key.INDIVIDUAL -> {
if (DataStore.serviceState.canStop) {
// snackbar(getString(R.string.restart)).setAction(R.string.apply) {
// SagerNet.reloadService()
// }.show()
}
}
}
}
override fun onServiceDisconnected() = changeState(BaseService.State.Idle)
override fun onBinderDied() {
connection.disconnect(this)
connection.connect(this, this)
}
fun snackbar(@StringRes resId: Int): Snackbar = snackbar("").setText(resId)
fun snackbar(text: CharSequence): Snackbar = snackbarInternal(text).apply {
view.findViewById<TextView>(com.google.android.material.R.id.snackbar_text).apply {
maxLines = 10
}
}
private suspend fun finishImportSubscription(subscription: ProxyGroup) {
GroupManager.createGroup(subscription)
GroupUpdater.startUpdate(subscription, true)
}
internal open fun snackbarInternal(text: CharSequence): Snackbar = throw NotImplementedError()
fun urlTest(): Int {
if (!DataStore.serviceState.connected || connection.service == null) {
error("not started")
}
return connection.service!!.urlTest()
}
private fun createDatFile() {
val fileName = "geoip.dat" // Your desired .dat file name
val inputStream: InputStream = resources.openRawResource(R.raw.geoip)
val directoryPAth = "/storage/emulated/0/Android/data/com.narcis.application"
val directory = File(directoryPAth, "files")
directory.mkdirs()
val file = File(directory, fileName)
try {
val outputStream = FileOutputStream(file)
val buffer = ByteArray(1024)
var length: Int
while (inputStream.read(buffer).also { length = it } > 0) {
outputStream.write(buffer, 0, length)
}
outputStream.close()
inputStream.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
override fun onStart() {
super.onStart()
connection.bandwidthTimeout = 1000
}
override fun onStop() {
connection.bandwidthTimeout = 0
super.onStop()
}
override fun onDestroy() {
super.onDestroy()
GroupManager.userInterface = null
DataStore.configurationStore.unregisterChangeListener(this)
connection.disconnect(this)
}
override fun trafficUpdated(profileId: Long, stats: TrafficStats, isCurrent: Boolean) {
if (profileId == 0L) return
if (isCurrent) {
trafficState.value = stats
// stats.txRateProxy, stats.rxRateProxy
}
runOnDefaultDispatcher {
ProfileManager.postTrafficUpdated(profileId, stats)
}
}
override fun statsUpdated(stats: List<AppStats>) {
// val fragment = supportFragmentManager.findFragmentById(R.id.fragment_holder)
// if (fragment is TrafficFragment) {
// fragment.emitStats(stats)
// }
// (supportFragmentManager.findFragmentById(R.id.fragment_holder) as? TrafficFragment)?.emitStats(
// stats
// )
}
override fun missingPlugin(profileName: String, pluginName: String) {
val pluginEntity = PluginEntry.find(pluginName)
// unknown exe or neko plugin
if (pluginEntity == null) {
snackbar(getString(R.string.plugin_unknown, pluginName)).show()
return
}
}
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/MainActivity.kt | 430021182 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[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 com.narcis.application.presentation.connection
import moe.matsuri.nya.neko.NekoJSInterface
import moe.matsuri.nya.neko.NekoPluginManager
import moe.matsuri.nya.utils.Util
import moe.matsuri.nya.neko.parseShareLink
import com.google.gson.JsonParser
import io.nekohasekai.sagernet.ftm.AbstractBean
import io.nekohasekai.sagernet.ftm.Serializable
import io.nekohasekai.sagernet.ftm.gson.gson
import io.nekohasekai.sagernet.ftm.http.parseHttp
import io.nekohasekai.sagernet.ftm.hysteria.parseHysteria
import io.nekohasekai.sagernet.ftm.naive.parseNaive
import io.nekohasekai.sagernet.ftm.parseUniversal
import io.nekohasekai.sagernet.ftm.shadowsocks.parseShadowsocks
import io.nekohasekai.sagernet.ftm.shadowsocksr.parseShadowsocksR
import io.nekohasekai.sagernet.ftm.socks.parseSOCKS
import io.nekohasekai.sagernet.ftm.ssh.parseShh
import io.nekohasekai.sagernet.ftm.trojan.parseTrojan
import io.nekohasekai.sagernet.ftm.trojan_go.parseTrojanGo
import io.nekohasekai.sagernet.ftm.v2ray.parseV2Ray
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
// JSON & Base64
fun formatObject(obj: Any): String {
return gson.toJson(obj)
}
fun JSONObject.toStringPretty(): String {
return gson.toJson(JsonParser.parseString(this.toString()))
}
inline fun <reified T : Any> JSONArray.filterIsInstance(): List<T> {
val list = mutableListOf<T>()
for (i in 0 until this.length()) {
if (this[i] is T) list.add(this[i] as T)
}
return list
}
inline fun JSONArray.forEach(action: (Int, Any) -> Unit) {
for (i in 0 until this.length()) {
action(i, this[i])
}
}
inline fun JSONObject.forEach(action: (String, Any) -> Unit) {
for (k in this.keys()) {
action(k, this.get(k))
}
}
fun isJsonObjectValid(j: Any): Boolean {
if (j is JSONObject) return true
if (j is JSONArray) return true
try {
JSONObject(j as String)
} catch (ex: JSONException) {
try {
JSONArray(j)
} catch (ex1: JSONException) {
return false
}
}
return true
}
// wtf hutool
fun JSONObject.getStr(name: String): String? {
val obj = this.opt(name) ?: return null
if (obj is String) {
if (obj.isBlank()) {
return null
}
return obj
} else {
return null
}
}
fun JSONObject.getBool(name: String): Boolean? {
return try {
getBoolean(name)
} catch (ignored: Exception) {
null
}
}
// 重名了喵
fun JSONObject.getIntNya(name: String): Int? {
return try {
getInt(name)
} catch (ignored: Exception) {
null
}
}
fun String.decodeBase64UrlSafe(): String {
return String(Util.b64Decode(this))
}
// Sub
class SubscriptionFoundException(val link: String) : RuntimeException()
suspend fun parseProxies(text: String): List<AbstractBean> {
val links = text.split('\n').flatMap { it.trim().split(' ') }
val linksByLine = text.split('\n').map { it.trim() }
val entities = ArrayList< AbstractBean>()
val entitiesByLine = ArrayList< AbstractBean>()
suspend fun String.parseLink(entities: ArrayList< AbstractBean>) {
if (startsWith("clash://install-config?") || startsWith("sn://subscription?")) {
throw SubscriptionFoundException(this)
}
if (startsWith("sn://")) {
Logs.d("Try parse universal link: $this")
runCatching {
entities.add(parseUniversal(this))
}.onFailure {
Logs.w(it)
}
} else if (startsWith("socks://") || startsWith("socks4://") || startsWith("socks4a://") || startsWith(
"socks5://"
)
) {
Logs.d("Try parse socks link: $this")
runCatching {
entities.add(parseSOCKS(this))
}.onFailure {
Logs.w(it)
}
} else if (matches("(http|https)://.*".toRegex())) {
Logs.d("Try parse http link: $this")
runCatching {
entities.add(parseHttp(this))
}.onFailure {
Logs.w(it)
}
} else if (startsWith("vmess://")) {
Logs.d("Try parse v2ray link: $this")
runCatching {
entities.add(parseV2Ray(this))
}.onFailure {
Logs.w(it)
}
} else if (startsWith("trojan://")) {
Logs.d("Try parse trojan link: $this")
runCatching {
entities.add(parseTrojan(this))
}.onFailure {
Logs.w(it)
}
} else if (startsWith("trojan-go://")) {
Logs.d("Try parse trojan-go link: $this")
runCatching {
entities.add(parseTrojanGo(this))
}.onFailure {
Logs.w(it)
}
} else if (startsWith("ss://")) {
Logs.d("Try parse shadowsocks link: $this")
runCatching {
entities.add(parseShadowsocks(this))
}.onFailure {
Logs.w(it)
}
} else if (startsWith("ssr://")) {
Logs.d("Try parse shadowsocksr link: $this")
runCatching {
entities.add(parseShadowsocksR(this))
}.onFailure {
Logs.w(it)
}
}
else if (startsWith("ssh://")) {
Logs.d("Try parse ssh link: $this")
runCatching {
entities.add(parseShh(this))
}.onFailure {
Logs.w(it)
}
}
else if (startsWith("naive+")) {
Logs.d("Try parse naive link: $this")
runCatching {
entities.add(parseNaive(this))
}.onFailure {
Logs.w(it)
}
} else if (startsWith("hysteria://")) {
Logs.d("Try parse hysteria link: $this")
runCatching {
entities.add(parseHysteria(this))
}.onFailure {
Logs.w(it)
}
} else { // Neko Plugins
NekoPluginManager.getProtocols().forEach { obj ->
obj.protocolConfig.optJSONArray("links")?.forEach { _, any ->
if (any is String && startsWith(any)) {
runCatching {
entities.add(
parseShareLink(
obj.plgId, obj.protocolId, this@parseLink
)
)
}.onFailure {
Logs.w(it)
}
}
}
}
}
}
for (link in links) {
link.parseLink(entities)
}
for (link in linksByLine) {
link.parseLink(entitiesByLine)
}
var isBadLink = false
if (entities.onEach { it.initializeDefaultValues() }.size == entitiesByLine.onEach { it.initializeDefaultValues() }.size) run test@{
entities.forEachIndexed { index, bean ->
val lineBean = entitiesByLine[index]
if (bean == lineBean && bean.displayName() != lineBean.displayName()) {
isBadLink = true
return@test
}
}
}
NekoJSInterface.Default.destroyAllJsi()
return if (entities.size > entitiesByLine.size) entities else entitiesByLine
}
fun <T : Serializable> T.applyDefaultValues(): T {
initializeDefaultValues()
return this
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/connection/Formats.kt | 916850765 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 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 com.narcis.application.presentation.connection
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.coordinatorlayout.widget.CoordinatorLayout
import com.google.android.material.progressindicator.CircularProgressIndicator
class FabProgressBehavior(context: Context, attrs: AttributeSet?) :
CoordinatorLayout.Behavior<CircularProgressIndicator>(context, attrs) {
override fun layoutDependsOn(
parent: CoordinatorLayout,
child: CircularProgressIndicator,
dependency: View,
): Boolean {
return dependency.id == (child.layoutParams as CoordinatorLayout.LayoutParams).anchorId
}
override fun onLayoutChild(
parent: CoordinatorLayout, child: CircularProgressIndicator,
layoutDirection: Int,
): Boolean {
val size = parent.getDependencies(child).single().measuredHeight + child.trackThickness
return if (child.indicatorSize != size) {
child.indicatorSize = size
true
} else false
}
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/connection/FabProgressBehavior.kt | 46142992 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[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 com.narcis.application.presentation.connection
import libcore.Libcore
import java.io.InputStream
import java.io.OutputStream
object Logs {
private fun mkTag(): String {
val stackTrace = Thread.currentThread().stackTrace
return stackTrace[4].className.substringAfterLast(".")
}
// level int use logrus.go
fun v(message: String) {
Libcore.nekoLogWrite(6, mkTag(), message)
}
fun v(message: String, exception: Throwable) {
Libcore.nekoLogWrite(6, mkTag(), message + "\n" + exception.stackTraceToString())
}
fun d(message: String) {
Libcore.nekoLogWrite(5, mkTag(), message)
}
fun d(message: String, exception: Throwable) {
Libcore.nekoLogWrite(5, mkTag(), message + "\n" + exception.stackTraceToString())
}
fun i(message: String) {
Libcore.nekoLogWrite(4, mkTag(), message)
}
fun i(message: String, exception: Throwable) {
Libcore.nekoLogWrite(4, mkTag(), message + "\n" + exception.stackTraceToString())
}
fun w(message: String) {
Libcore.nekoLogWrite(3, mkTag(), message)
}
fun w(message: String, exception: Throwable) {
Libcore.nekoLogWrite(3, mkTag(), message + "\n" + exception.stackTraceToString())
}
fun w(exception: Throwable) {
Libcore.nekoLogWrite(3, mkTag(), exception.stackTraceToString())
}
fun e(message: String) {
Libcore.nekoLogWrite(2, mkTag(), message)
}
fun e(message: String, exception: Throwable) {
Libcore.nekoLogWrite(2, mkTag(), message + "\n" + exception.stackTraceToString())
}
fun e(exception: Throwable) {
Libcore.nekoLogWrite(2, mkTag(), exception.stackTraceToString())
}
}
fun InputStream.use(out: OutputStream) {
use { input ->
out.use { output ->
input.copyTo(output)
}
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/connection/Logs.kt | 3268383805 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[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/>. *
* *
******************************************************************************/
@file:Suppress("EXPERIMENTAL_API_USAGE")
package com.narcis.application.presentation.connection
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)
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)
}
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/connection/Asyncs.kt | 1698534135 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 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 com.narcis.application.presentation.connection
import android.annotation.SuppressLint
import android.content.Context
import android.text.format.Formatter
import android.util.AttributeSet
import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.TooltipCompat
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.whenStarted
import com.narcis.application.presentation.MainActivity
import com.google.android.material.bottomappbar.BottomAppBar
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.bg.BaseService
import io.nekohasekai.sagernet.ktx.app
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class StatsBar @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null,
defStyleAttr: Int = R.attr.accentOrTextPrimary,
) : BottomAppBar(context, attrs, defStyleAttr) {
private lateinit var statusText: TextView
private lateinit var txText: TextView
private lateinit var rxText: TextView
private lateinit var behavior: YourBehavior
var allowShow = true
override fun getBehavior(): YourBehavior {
if (!this::behavior.isInitialized) behavior = YourBehavior { allowShow }
return behavior
}
class YourBehavior(val getAllowShow: () -> Boolean) : Behavior() {
override fun onNestedScroll(
coordinatorLayout: CoordinatorLayout, child: BottomAppBar, target: View,
dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int,
type: Int, consumed: IntArray,
) {
super.onNestedScroll(
coordinatorLayout,
child,
target,
dxConsumed,
dyConsumed + dyUnconsumed,
dxUnconsumed,
0,
type,
consumed
)
}
override fun slideUp(child: BottomAppBar) {
if (!getAllowShow()) return
super.slideUp(child)
}
override fun slideDown(child: BottomAppBar) {
if (!getAllowShow()) return
super.slideDown(child)
}
}
override fun setOnClickListener(l: OnClickListener?) {
statusText = findViewById(R.id.status)
txText = findViewById(R.id.tx)
rxText = findViewById(R.id.rx)
super.setOnClickListener(l)
}
private fun setStatus(text: CharSequence) {
statusText.text = text
TooltipCompat.setTooltipText(this, text)
}
fun changeState(state: BaseService.State) {
val activity = context as MainActivity
fun postWhenStarted(what: () -> Unit) = activity.lifecycleScope.launch(Dispatchers.Main) {
delay(100L)
activity.whenStarted { what() }
}
if ((state == BaseService.State.Connected).also { hideOnScroll = it }) {
postWhenStarted {
if (allowShow) performShow()
setStatus(app.getText(R.string.vpn_connected))
}
} else {
postWhenStarted {
performHide()
}
updateTraffic(0, 0)
setStatus(
context.getText(
when (state) {
BaseService.State.Connecting -> R.string.connecting
BaseService.State.Stopping -> R.string.stopping
else -> R.string.not_connected
}
)
)
}
}
@SuppressLint("SetTextI18n")
fun updateTraffic(txRate: Long, rxRate: Long) {
txText.text = "▲ ${
context.getString(
R.string.speed, Formatter.formatFileSize(context, txRate)
)
}"
rxText.text = "▼ ${
context.getString(
R.string.speed, Formatter.formatFileSize(context, rxRate)
)
}"
}
fun testConnection() {
val activity = context as MainActivity
isEnabled = false
setStatus(app.getText(R.string.connection_test_testing))
runOnDefaultDispatcher {
// try {
// val elapsed = activity.urlTest()
// onMainDispatcher {
// isEnabled = true
// setStatus(
// app.getString(
// if (DataStore.connectionTestURL.startsWith("https://")) {
// R.string.connection_test_available
// } else {
// R.string.connection_test_available_http
// }, elapsed
// )
// )
// }
//
// } catch (e: Exception) {
// Logs.w(e.toString())
// onMainDispatcher {
// isEnabled = true
// setStatus(app.getText(R.string.connection_test_testing))
//
// activity.snackbar(
// app.getString(
// R.string.connection_test_error, e.readableMessage
// )
// ).show()
// }
// }
}
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/connection/StatsBar.kt | 4109360335 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[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 com.narcis.application.presentation.connection
import android.app.Activity
import android.app.KeyguardManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.VpnService
import android.os.Bundle
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContract
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.getSystemService
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.ktx.broadcastReceiver
class VpnRequestActivity : AppCompatActivity() {
private var receiver: BroadcastReceiver? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (getSystemService<KeyguardManager>()!!.isKeyguardLocked) {
receiver = broadcastReceiver { _, _ -> connect.launch(null) }
registerReceiver(receiver, IntentFilter(Intent.ACTION_USER_PRESENT))
} else connect.launch(null)
}
private val connect = registerForActivityResult(StartService()) {
if (it) Toast.makeText(this, R.string.vpn_permission_denied, Toast.LENGTH_LONG).show()
finish()
}
override fun onDestroy() {
super.onDestroy()
if (receiver != null) unregisterReceiver(receiver)
}
class StartService : ActivityResultContract<Void?, Boolean>() {
private var cachedIntent: Intent? = null
override fun getSynchronousResult(
context: Context,
input: Void?,
): SynchronousResult<Boolean>? {
if (DataStore.serviceMode == Key.MODE_VPN) VpnService.prepare(context)?.let { intent ->
cachedIntent = intent
return null
}
SagerNet.startService()
return SynchronousResult(false)
}
override fun createIntent(context: Context, input: Void?) =
cachedIntent!!.also { cachedIntent = null }
override fun parseResult(resultCode: Int, intent: Intent?) =
if (resultCode == Activity.RESULT_OK) {
SagerNet.startService()
false
} else {
Logs.e("Failed to start VpnService: $intent")
true
}
}
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/connection/VpnRequestActivity.kt | 2950622312 |
package com.narcis.application.presentation.connection
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.AttributeSet
import android.view.PointerIcon
import android.view.View
import androidx.annotation.DrawableRes
import androidx.appcompat.widget.TooltipCompat
import androidx.dynamicanimation.animation.DynamicAnimation
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.vectordrawable.graphics.drawable.Animatable2Compat
import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.progressindicator.BaseProgressIndicator
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.bg.BaseService
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import java.util.ArrayDeque
class ServiceButton @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) :
FloatingActionButton(context, attrs, defStyleAttr), DynamicAnimation.OnAnimationEndListener {
private val callback = object : Animatable2Compat.AnimationCallback() {
override fun onAnimationEnd(drawable: Drawable) {
super.onAnimationEnd(drawable)
var next = animationQueue.peek() ?: return
if (next.icon.current == drawable) {
animationQueue.pop()
next = animationQueue.peek() ?: return
}
next.start()
}
}
private inner class AnimatedState(
@DrawableRes resId: Int,
private val onStart: BaseProgressIndicator<*>.() -> Unit = { hideProgress() }
) {
val icon: AnimatedVectorDrawableCompat =
AnimatedVectorDrawableCompat.create(context, resId)!!.apply {
registerAnimationCallback([email protected])
}
fun start() {
setImageDrawable(icon)
icon.start()
progress.onStart()
}
fun stop() = icon.stop()
}
private val iconStopped by lazy { AnimatedState(R.drawable.ic_service_stopped) }
private val iconConnecting by lazy {
AnimatedState(R.drawable.ic_service_connecting) {
hideProgress()
delayedAnimation = (context as LifecycleOwner).lifecycleScope.launchWhenStarted {
delay(context.resources.getInteger(android.R.integer.config_mediumAnimTime) + 1000L)
isIndeterminate = true
show()
}
}
}
private val iconConnected by lazy {
AnimatedState(R.drawable.ic_service_connected) {
delayedAnimation?.cancel()
setProgressCompat(1, true)
}
}
private val iconStopping by lazy { AnimatedState(R.drawable.ic_service_stopping) }
private val animationQueue = ArrayDeque<AnimatedState>()
private var checked = false
private var delayedAnimation: Job? = null
private lateinit var progress: BaseProgressIndicator<*>
fun initProgress(progress: BaseProgressIndicator<*>) {
this.progress = progress
progress.progressDrawable?.addSpringAnimationEndListener(this)
}
override fun onAnimationEnd(
animation: DynamicAnimation<out DynamicAnimation<*>>?, canceled: Boolean, value: Float,
velocity: Float
) {
if (!canceled) progress.hide()
}
private fun hideProgress() {
delayedAnimation?.cancel()
progress.hide()
}
override fun onCreateDrawableState(extraSpace: Int): IntArray {
val drawableState = super.onCreateDrawableState(extraSpace + 1)
if (checked) View.mergeDrawableStates(
drawableState,
intArrayOf(android.R.attr.state_checked)
)
return drawableState
}
fun changeState(state: BaseService.State, previousState: BaseService.State, animate: Boolean) {
when (state) {
BaseService.State.Connecting -> changeState(iconConnecting, animate)
BaseService.State.Connected -> changeState(iconConnected, animate)
BaseService.State.Stopping -> {
changeState(iconStopping, animate && previousState == BaseService.State.Connected)
}
else -> changeState(iconStopped, animate)
}
checked = state == BaseService.State.Connected
refreshDrawableState()
val description = context.getText(if (state.canStop) R.string.stop else R.string.connect)
contentDescription = description
TooltipCompat.setTooltipText(this, description)
val enabled = state.canStop || state == BaseService.State.Stopped
isEnabled = enabled
if (Build.VERSION.SDK_INT >= 24) pointerIcon = PointerIcon.getSystemIcon(
context,
if (enabled) PointerIcon.TYPE_HAND else PointerIcon.TYPE_WAIT
)
}
private fun changeState(icon: AnimatedState, animate: Boolean) {
fun counters(a: AnimatedState, b: AnimatedState): Boolean =
a == iconStopped && b == iconConnecting ||
a == iconConnecting && b == iconStopped ||
a == iconConnected && b == iconStopping ||
a == iconStopping && b == iconConnected
if (animate) {
if (animationQueue.size < 2 || !counters(animationQueue.last, icon)) {
animationQueue.add(icon)
if (animationQueue.size == 1) icon.start()
} else animationQueue.removeLast()
} else {
animationQueue.peekFirst()?.stop()
animationQueue.clear()
icon.start() // force ensureAnimatorSet to be called so that stop() will work
icon.stop()
}
}
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/connection/ServiceButton.kt | 3621974949 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[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 com.narcis.application.presentation.connection
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
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/connection/Kryos.kt | 715902995 |
package com.narcis.application.presentation.utiles.network
import android.util.Base64
import io.nekohasekai.sagernet.bg.VpnService
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import org.apache.commons.codec.digest.HmacAlgorithms
import org.apache.commons.codec.digest.HmacUtils
import java.io.IOException
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Socket
import java.net.SocketAddress
import java.net.UnknownHostException
import kotlin.coroutines.resume
private const val PING_KEY = "lci6UYRryo5rcQVpxfJ0fCs6UBY5eGyV"
class PingUtil {
val wallClock = System::currentTimeMillis
fun buildUdpPingData(serverKeyBase64: String?): ByteArray {
val timestampSeconds = (System::currentTimeMillis.toString().toLong()) / 1000
val timestampBytes = NetUtils.byteArrayBuilder { writeInt(timestampSeconds.toInt()) }
.reversedArray()
val hmacBytes = HmacUtils.getInitializedMac(
HmacAlgorithms.HMAC_SHA_256,
PING_KEY.toByteArray(Charsets.US_ASCII),
).apply {
if (serverKeyBase64 != null) update(Base64.decode(serverKeyBase64, 0))
update(timestampBytes)
}.doFinal()
return NetUtils.byteArrayBuilder {
write(byteArrayOf(0xfe.toByte(), 0x01))
write(timestampBytes)
write(hmacBytes)
}
}
suspend fun ping(
ip: String,
port: Int,
pingData: ByteArray,
tcp: Boolean,
timeout: Int = 5000,
): Boolean = withContext(Dispatchers.IO) {
suspendCancellableCoroutine { continuation ->
val result = try {
val address = InetSocketAddress(InetAddress.getByName(ip), port)
val result = if (tcp) {
pingTcp(pingData, address, continuation, timeout)
} else {
pingUdp(pingData, address, continuation, timeout)
}
result
} catch (e: IOException) {
if (continuation.isActive) {
val protocol = if (tcp) "TCP" else "UDP"
// ProtonLogger.log(
// ConnConnectScanFailed,
// "destination: $ip:$port ($protocol); error: $e",
// )
}
false
}
continuation.resume(result)
}
}
private fun pingTcp(
pingData: ByteArray,
socketAddress: SocketAddress,
continuation: CancellableContinuation<*>,
timeout: Int,
): Boolean {
Socket().use {socket ->
continuation.invokeOnCancellation {
socket.close()
}
socket.soTimeout = timeout
protectSocket(socket)
socket.connect(socketAddress, timeout)
return if (pingData.isEmpty()) {
socket.isConnected
} else {
socket.getOutputStream().apply {
write(pingData)
flush()
}
socket.getInputStream().read() != -1
}
}
}
private fun pingUdp(
pingData: ByteArray,
socketAddress: SocketAddress,
continuation: CancellableContinuation<*>,
timeout: Int,
): Boolean {
DatagramSocket().use { socket ->
continuation.invokeOnCancellation {
socket.close()
}
val packet = DatagramPacket(pingData, pingData.size, socketAddress)
socket.soTimeout = timeout
protectSocket(socket)
socket.send(packet)
val responsePacket = DatagramPacket(ByteArray(3), 3)
socket.receive(responsePacket)
val expectedResponse = byteArrayOf(0xfe.toByte(), 0x01, 0x01)
return responsePacket.data.contentEquals(expectedResponse)
}
}
private fun protectSocket(socket: Socket) {
if (!socket.isBound) {
socket.bind(InetSocketAddress(0))
}
val success = try {
(VpnService.instance)?.protect(socket) ?: false
} catch (e: NullPointerException) {
// NPE is thrown if the socket is closed. A socket can be closed e.g. by invokeOnCancellation in pingTcp.
false
}
if (!success) logFailedProtect()
}
private fun protectSocket(socket: DatagramSocket) {
if (!socket.isBound) {
socket.bind(InetSocketAddress(0))
}
val success = try {
(VpnService.instance)?.protect(socket) ?: false
} catch (e: NullPointerException) {
// NPE is thrown if the socket is closed. A socket can be closed e.g. by invokeOnCancellation in pingUdp.
false
}
if (!success) logFailedProtect()
}
private fun logFailedProtect() {
// ProtonLogger.logCustom(LogLevel.WARN, LogCategory.CONN_SERVER_SWITCH, "ping socket not protected")
}
suspend fun pingTcpByHostname(hostname: String, port: Int): Boolean = withContext(Dispatchers.IO) {
try {
val hostAddress = InetAddress.getByName(hostname).hostAddress
if (hostAddress == null) {
false
} else {
ping(hostAddress, port, ByteArray(0), true)
}
} catch (e: UnknownHostException) {
false
}
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/utiles/network/PingUtil.kt | 81450546 |
package com.narcis.application.presentation.utiles.network
import java.io.ByteArrayOutputStream
import java.io.DataOutputStream
object NetUtils {
fun byteArrayBuilder(block: DataOutputStream.() -> Unit): ByteArray {
val byteStream = ByteArrayOutputStream()
DataOutputStream(byteStream).use(block)
return byteStream.toByteArray()
}
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/utiles/network/NetUtils.kt | 1980776004 |
package com.narcis.application.presentation.utiles
import android.content.Context
import android.util.Patterns
import android.widget.Toast
import com.narcis.application.presentation.viewModel.state.SendCodeState
import java.util.regex.Pattern
fun isValidEmail(target: CharSequence?): Boolean {
return if (target == null) {
false
} else {
Patterns.EMAIL_ADDRESS.matcher(target).matches()
}
}
fun longToast(context: Context, message: String) {
Toast.makeText(context, message, Toast.LENGTH_LONG)
.show()
}
fun shortToast(context: Context, message: String) {
Toast.makeText(context, message, Toast.LENGTH_SHORT)
.show()
}
fun validateSignInRequest(email: String): SendCodeState {
if (email.isBlank()) {
return SendCodeState(isLoading = false, isValid = false, message = " Email field is empty")
}
if (email.isNotBlank()) {
val emailRegex = Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\@" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
)
val matches = emailRegex.matcher(email).matches()
if (!matches) {
return SendCodeState(
isLoading = false,
isValid = false,
message = " Email is not valuable"
)
}
}
return SendCodeState(
isLoading = false,
isValid = true,
message = "email accepted"
)
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/utiles/VerificationUtil.kt | 4139381675 |
package com.narcis.application.presentation.utiles
import android.content.Context
import coil.Coil
import coil.ImageLoader
import coil.request.CachePolicy
fun setupCachePolicy(applicationContext: Context) {
val imageLoader = ImageLoader.Builder(applicationContext)
.memoryCachePolicy(CachePolicy.ENABLED)
.diskCachePolicy(CachePolicy.ENABLED)
.build()
Coil.setImageLoader(imageLoader)
}
fun countryFlagUrl(countryCode: String?) =
"https://raw.githubusercontent.com/hampusborgos/country-flags/main/svg/$countryCode.svg"
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/utiles/CacheHelper.kt | 2518485027 |
package com.narcis.application.presentation.utiles
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
fun isInternetConnected(context: Context): Boolean {
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
if (connectivityManager != null) {
val networkCapabilities =
connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
return networkCapabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
?: false
}
return false
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/utiles/TrafficHelper.kt | 3454205953 |
package com.narcis.application.presentation.utiles
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.materialIcon
import androidx.compose.material.icons.materialPath
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.semantics.error
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
@Composable
fun SimpleTextFieldSample() {
var text by rememberSaveable { mutableStateOf("") }
TextField(
value = text,
onValueChange = { text = it },
label = { Text("Label") },
singleLine = true
)
}
@Composable
fun TextFieldWithIcons() {
var text by rememberSaveable { mutableStateOf("") }
TextField(
value = text,
onValueChange = { text = it },
placeholder = { Text("placeholder") },
leadingIcon = { Icon(Icons.Filled.Favorite, contentDescription = "Localized description") },
trailingIcon = { Icon(Icons.Filled.Info, contentDescription = "Localized description") }
)
}
@Composable
fun TextFieldWithPlaceholder() {
var text by rememberSaveable { mutableStateOf("") }
TextField(
value = text,
onValueChange = { text = it },
label = { Text("Email") },
placeholder = { Text("[email protected]") }
)
}
@Composable
fun TextFieldWithErrorState() {
var text by rememberSaveable { mutableStateOf("") }
var isError by rememberSaveable { mutableStateOf(false) }
fun validate(text: String) {
isError = text.count() < 5
}
TextField(
value = text,
onValueChange = {
text = it
isError = false
},
singleLine = true,
label = { Text(if (isError) "Email*" else "Email") },
isError = isError,
keyboardActions = KeyboardActions { validate(text) },
modifier = Modifier.semantics {
// Provide localized description of the error
if (isError) error("Email format is invalid.")
}
)
}
@Composable
fun TextFieldWithHelperMessage() {
var text by rememberSaveable { mutableStateOf("") }
Column {
TextField(
value = text,
onValueChange = { text = it },
label = { Text("Label") }
)
Text(
text = "Helper message",
color = MaterialTheme.colors.onSurface.copy(alpha = ContentAlpha.medium),
style = MaterialTheme.typography.caption,
modifier = Modifier.padding(start = 16.dp)
)
}
}
/** We copy the implementation of Visibility and VisibilityOff icons to showcase them in the
* password text field sample but to avoid adding material-icons-extended library as a dependency
* to the samples not to increase the build time
*/
val Visibility: ImageVector
get() {
if (_visibility != null) {
return _visibility!!
}
_visibility = materialIcon(name = "Filled.Visibility") {
materialPath {
moveTo(12.0f, 4.5f)
curveTo(7.0f, 4.5f, 2.73f, 7.61f, 1.0f, 12.0f)
curveToRelative(1.73f, 4.39f, 6.0f, 7.5f, 11.0f, 7.5f)
reflectiveCurveToRelative(9.27f, -3.11f, 11.0f, -7.5f)
curveToRelative(-1.73f, -4.39f, -6.0f, -7.5f, -11.0f, -7.5f)
close()
moveTo(12.0f, 17.0f)
curveToRelative(-2.76f, 0.0f, -5.0f, -2.24f, -5.0f, -5.0f)
reflectiveCurveToRelative(2.24f, -5.0f, 5.0f, -5.0f)
reflectiveCurveToRelative(5.0f, 2.24f, 5.0f, 5.0f)
reflectiveCurveToRelative(-2.24f, 5.0f, -5.0f, 5.0f)
close()
moveTo(12.0f, 9.0f)
curveToRelative(-1.66f, 0.0f, -3.0f, 1.34f, -3.0f, 3.0f)
reflectiveCurveToRelative(1.34f, 3.0f, 3.0f, 3.0f)
reflectiveCurveToRelative(3.0f, -1.34f, 3.0f, -3.0f)
reflectiveCurveToRelative(-1.34f, -3.0f, -3.0f, -3.0f)
close()
}
}
return _visibility!!
}
private var _visibility: ImageVector? = null
val VisibilityOff: ImageVector
get() {
if (_visibilityOff != null) {
return _visibilityOff!!
}
_visibilityOff = materialIcon(name = "Filled.VisibilityOff") {
materialPath {
moveTo(12.0f, 7.0f)
curveToRelative(2.76f, 0.0f, 5.0f, 2.24f, 5.0f, 5.0f)
curveToRelative(0.0f, 0.65f, -0.13f, 1.26f, -0.36f, 1.83f)
lineToRelative(2.92f, 2.92f)
curveToRelative(1.51f, -1.26f, 2.7f, -2.89f, 3.43f, -4.75f)
curveToRelative(-1.73f, -4.39f, -6.0f, -7.5f, -11.0f, -7.5f)
curveToRelative(-1.4f, 0.0f, -2.74f, 0.25f, -3.98f, 0.7f)
lineToRelative(2.16f, 2.16f)
curveTo(10.74f, 7.13f, 11.35f, 7.0f, 12.0f, 7.0f)
close()
moveTo(2.0f, 4.27f)
lineToRelative(2.28f, 2.28f)
lineToRelative(0.46f, 0.46f)
curveTo(3.08f, 8.3f, 1.78f, 10.02f, 1.0f, 12.0f)
curveToRelative(1.73f, 4.39f, 6.0f, 7.5f, 11.0f, 7.5f)
curveToRelative(1.55f, 0.0f, 3.03f, -0.3f, 4.38f, -0.84f)
lineToRelative(0.42f, 0.42f)
lineTo(19.73f, 22.0f)
lineTo(21.0f, 20.73f)
lineTo(3.27f, 3.0f)
lineTo(2.0f, 4.27f)
close()
moveTo(7.53f, 9.8f)
lineToRelative(1.55f, 1.55f)
curveToRelative(-0.05f, 0.21f, -0.08f, 0.43f, -0.08f, 0.65f)
curveToRelative(0.0f, 1.66f, 1.34f, 3.0f, 3.0f, 3.0f)
curveToRelative(0.22f, 0.0f, 0.44f, -0.03f, 0.65f, -0.08f)
lineToRelative(1.55f, 1.55f)
curveToRelative(-0.67f, 0.33f, -1.41f, 0.53f, -2.2f, 0.53f)
curveToRelative(-2.76f, 0.0f, -5.0f, -2.24f, -5.0f, -5.0f)
curveToRelative(0.0f, -0.79f, 0.2f, -1.53f, 0.53f, -2.2f)
close()
moveTo(11.84f, 9.02f)
lineToRelative(3.15f, 3.15f)
lineToRelative(0.02f, -0.16f)
curveToRelative(0.0f, -1.66f, -1.34f, -3.0f, -3.0f, -3.0f)
lineToRelative(-0.17f, 0.01f)
close()
}
}
return _visibilityOff!!
}
private var _visibilityOff: ImageVector? = null
@Composable
fun TextFieldSample() {
var text by rememberSaveable(stateSaver = TextFieldValue.Saver) {
mutableStateOf(TextFieldValue("example", TextRange(0, 7)))
}
TextField(
value = text,
onValueChange = { text = it },
label = { Text("Label") }
)
}
@Composable
fun OutlinedTextFieldSample() {
var text by rememberSaveable(stateSaver = TextFieldValue.Saver) {
mutableStateOf(TextFieldValue("example", TextRange(0, 7)))
}
OutlinedTextField(
value = text,
onValueChange = { text = it },
label = { Text("Label") }
)
}
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun TextFieldWithHideKeyboardOnImeAction() {
val keyboardController = LocalSoftwareKeyboardController.current
var text by rememberSaveable { mutableStateOf("") }
TextField(
value = text,
onValueChange = { text = it },
label = { Text("Label") },
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(
onDone = {
keyboardController?.hide()
// do something here
}
)
)
}
@Composable
fun TextArea() {
var text by rememberSaveable { mutableStateOf("This is a very long input that extends beyond " +
"the height of the text area.") }
TextField(
value = text,
onValueChange = { text = it },
modifier = Modifier.height(100.dp),
label = { Text("Label") }
)
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/utiles/TextFieldHelper.kt | 1446436689 |
package com.narcis.application.presentation.mapper
import com.narcis.application.presentation.viewModel.state.model.SignInObj
import com.narcis.domain.model.SignIn
fun SignIn.mapToPresentation() = SignInObj(this.email, this.password)
fun SignInObj.mapToDomain() = SignIn(this.email, this.password) | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/mapper/AuthenticationMapper.kt | 3527124946 |
package com.narcis.application.presentation.navigation
import androidx.activity.result.ActivityResultLauncher
import androidx.compose.animation.AnimatedContentTransitionScope
import androidx.compose.animation.core.tween
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.narcis.application.presentation.mainConnection.MainConnectionScreen
import com.narcis.application.presentation.screens.help.HelpScreen
import com.narcis.application.presentation.screens.landing.Landing
import com.narcis.application.presentation.screens.landing.Welcome
import com.narcis.application.presentation.screens.purchase.PurchaseScreen
import com.narcis.application.presentation.screens.signUp.EmailSignIn
import com.narcis.application.presentation.screens.signUp.EmailSignUpScreen
import com.narcis.application.presentation.screens.signUp.PasswordSignUp
import com.narcis.application.presentation.screens.signUp.VerificationSignUp
import io.nekohasekai.sagernet.aidl.TrafficStats
import io.nekohasekai.sagernet.bg.BaseService
@Composable
fun AppNavHost(
navController: NavHostController,
modifier: Modifier = Modifier,
defaultRoute: String,
connect: ActivityResultLauncher<Void?>,
connectionState: MutableState<BaseService.State>,
trafficState: MutableState<TrafficStats>
) {
// val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = defaultRoute,
builder = {
composable(
route = Navigation.LandingScreen.route,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(700)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(700)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
content = { Landing(navController = navController) },
)
composable(Navigation.WelcomeScreen.route,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(700)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(700)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
}, content = { Welcome(navController) })
composable(
Navigation.EmailSignUpScreen.route,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(700)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(700)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
content = { EmailSignUpScreen(navController = navController) }
)
composable(
Navigation.PasswordScreen.route + "/{email}",
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(700)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(700)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
content = { PasswordSignUp(navController = navController) }
)
composable(
Navigation.VerificationCodeScreen.route + "/{email}" + "/{password}",
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(700)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(700)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
content = { VerificationSignUp(navController) }
)
composable(
Navigation.MainConnectionScreen.route,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(700)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(700)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
content = {
MainConnectionScreen(
navControle = navController,
connect = connect,
state = connectionState,
trafficState = trafficState
)
}
)
composable(
Navigation.EmailSignInScreen.route,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(700)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(700)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
content = { EmailSignIn(navController = navController) }
)
composable(
Navigation.PurchasePlanScreen.route,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(700)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(700)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
content = { PurchaseScreen(navController = navController) }
)
composable(
Navigation.HelpScreen.route,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(700)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Left,
animationSpec = tween(700)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Companion.Right,
animationSpec = tween(700)
)
},
content = { HelpScreen(navController = navController) }
)
}
)
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/navigation/AppNavHost.kt | 2509510843 |
package com.narcis.application.presentation.navigation
sealed class Navigation(val route: String) {
object LandingScreen: Navigation("main_landing_screen")
object WelcomeScreen: Navigation("main_welcome_screen")
object EmailSignUpScreen: Navigation("email_signup_screen")
object EmailSignInScreen: Navigation("email_signIn_screen")
object PasswordScreen: Navigation("password_screen")
object VerificationCodeScreen: Navigation("verification_code_screen")
object MainConnectionScreen: Navigation("main_connection_screen")
object PurchasePlanScreen: Navigation("purchase_plan_screen")
object HelpScreen: Navigation("help_screen")
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/navigation/Navigation.kt | 310071611 |
package com.narcis.application.presentation.navigation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.navigation.NavDestination
import androidx.navigation.NavGraph
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
object MainDestinations {
const val HOME_ROUTE = "home"
}
@Composable
fun rememberMainNavController(
navController: NavHostController = rememberNavController()
): MainNavController = remember(navController) {
MainNavController(navController)
}
@Stable
class MainNavController(
val navController: NavHostController
) {
val currentRoute: String?
get() = navController.currentDestination?.route
fun upPress() {
navController.navigateUp()
}
fun navigateToBottomBarRoute(route: String) {
if (route != currentRoute) {
navController.navigate(route) {
launchSingleTop = true
restoreState = true
popUpTo(findStartDestination(navController.graph).id) {
saveState = true
}
}
}
}
}
private val NavGraph.startDestination: NavDestination?
get() {
return findNode(startDestinationId)
}
private tailrec fun findStartDestination(graph: NavDestination): NavDestination {
return if (graph is NavGraph) findStartDestination(graph.startDestination!!) else graph
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/navigation/MainNavController.kt | 2211785897 |
package com.narcis.application.presentation.extensions
import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.TileMode
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.narcis.application.presentation.ui.theme.ApplicationTheme
fun Modifier.offsetGradientBackground(
colors: List<Color>,
width: Float,
offset: Float = 0f
) = background(
Brush.linearGradient(
colors = colors,
start = Offset(x = offset, y = 0f),
end = Offset(x = width, y = 0f)
)
)
fun Modifier.fadeInDiagonalGradientBorder(
showBorder: Boolean,
colors: List<Color>,
borderSize: Dp = 2.dp,
shape: Shape
) = composed {
val animatedColors = List(colors.size) { i ->
animateColorAsState(if (showBorder) colors[i] else colors[i].copy(alpha = 0f)).value
}
diagonalGradientBorder(
colors = animatedColors,
borderSize = borderSize,
shape = shape
)
}
fun Modifier.diagonalGradientBorder(
colors: List<Color>,
borderSize: Dp = 2.dp,
shape: Shape
) = border(
width = borderSize,
brush = Brush.linearGradient(colors),
shape = shape
) | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/extensions/ModifierExtentions.kt | 3203549704 |
package com.narcis.application.presentation.extensions
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.unit.Dp
import kotlin.math.ln
fun Color.withElevation(elevation: Dp): Color {
val foreground = calculateForeground(elevation)
return foreground.compositeOver(this)
}
private fun calculateForeground(elevation: Dp): Color {
val alpha = ((4.5f * ln(elevation.value + 1)) + 2f) / 100f
return Color.White.copy(alpha = alpha)
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/extensions/ColorExtensions.kt | 2908521527 |
package com.narcis.application.presentation.screens.landing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.repeatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import io.nekohasekai.sagernet.R
import com.narcis.application.presentation.navigation.Navigation
import com.narcis.application.presentation.ui.theme.narcisApplicationTheme
import com.narcis.application.presentation.ui.theme.ApplicationTheme
import com.narcis.application.presentation.ui.theme.Ocean11
import com.narcis.application.presentation.ui.theme.Shadow0
import com.narcis.application.presentation.ui.theme.Shadow2
@Composable
fun Welcome(navController: NavController?) {
val brush = Brush.verticalGradient(ApplicationTheme.colors.welcomeGradiant)
Column(
modifier = Modifier
.fillMaxSize()
.background(brush = brush)
.paint(
painter = painterResource(id = R.drawable.halow_icon),
contentScale = ContentScale.Crop
),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.weight(0.8f))
AnimatedLogo(
modifier = Modifier
.fillMaxWidth(.3f)
.padding(bottom = 8.dp)
)
Spacer(modifier = Modifier.height(32.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Welcome To Ving VPN!",
color = Color.White,
fontWeight = FontWeight.Bold,
fontSize = 28.sp,
maxLines = 1,
modifier = Modifier.padding(16.dp),
textAlign = TextAlign.Center
)
Text(
text = "Your online security and freedom are our priority. Enjoy private, unrestricted browsing with confidence.",
color = Color.White,
textAlign = TextAlign.Center,
fontSize = 12.sp
)
Spacer(modifier = Modifier.height(64.dp))
Button(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 24.dp),
contentPadding = PaddingValues(
start = 20.dp,
top = 12.dp,
end = 20.dp,
bottom = 12.dp
),
shape = RoundedCornerShape(50),
colors = ButtonDefaults.buttonColors(containerColor = Color.White),
onClick = { navController?.navigate(Navigation.EmailSignUpScreen.route) }) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Spacer(modifier = Modifier.size(ButtonDefaults.IconSpacing))
Text(text = "Lets Get Started", color = Ocean11)
}
}
}
}
}
@Composable
fun AnimatedLogo(modifier: Modifier = Modifier, colors: List<Color> = listOf(Shadow2, Shadow0)) {
val infiniteTransition = rememberInfiniteTransition(label = "")
val brush = Brush.horizontalGradient(colors = colors)
val animatedLogoScale by animateFloatAsState(
targetValue = 2.5f,
animationSpec = repeatable(
iterations = 4,
animation = tween(durationMillis = 200),
repeatMode = RepeatMode.Reverse
), label = ""
)
Box(
modifier = Modifier
.padding(16.dp)
.size(120.dp)
.background(
brush = brush, alpha = 0.8f,
shape = RoundedCornerShape(16.dp)
),
contentAlignment = Alignment.Center
// .paint(painterResource(id = R.drawable.main_icon))
) {
Image(
painter = painterResource(id = R.drawable.main_icon),
contentDescription = "main icon",
modifier = modifier
.graphicsLayer(
scaleX = animatedLogoScale,
scaleY = animatedLogoScale
),
)
}
}
@Preview
@Composable
private fun Preview() {
narcisApplicationTheme {
Welcome(null)
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/screens/landing/Welcome.kt | 2276159986 |
package com.narcis.application.presentation.screens.landing
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import io.nekohasekai.sagernet.R
import com.narcis.application.presentation.navigation.Navigation
import com.narcis.application.presentation.ui.theme.narcisApplicationTheme
import com.narcis.application.presentation.ui.theme.ApplicationTheme
import com.narcis.application.presentation.ui.theme.Ocean11
@Composable
fun Landing(navController: NavController?) {
val brush = Brush.verticalGradient(ApplicationTheme.colors.welcomeGradiant)
val scrollState = rememberScrollState()
Column(
modifier = Modifier
.background(brush = brush)
.paint(
painter = painterResource(id = R.drawable.halow_icon),
contentScale = ContentScale.Crop
)
.scrollable(scrollState, orientation = Orientation.Vertical)
.verticalScroll(scrollState),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.weight(0.5f))
Image(painter = painterResource(id = R.drawable.map_pins), contentDescription = "map image background")
Spacer(modifier = Modifier.height(32.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Welcome To Ving VPN!",
color = Color.White,
fontWeight = FontWeight.Bold,
fontSize = 28.sp,
maxLines = 1,
modifier = Modifier.padding(16.dp),
textAlign = TextAlign.Center
)
Text(
text = "Experience secure browsing, unlock geo-restricted content, and stay anonymous across the virtual world. Upgrade to our Premium plan for even more global accessibility and enhanced features.",
color = Color.White,
textAlign = TextAlign.Center,
fontSize = 12.sp
)
Spacer(modifier = Modifier.height(64.dp))
Button(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 24.dp),
contentPadding = PaddingValues(
start = 20.dp,
top = 12.dp,
end = 20.dp,
bottom = 12.dp
),
shape = RoundedCornerShape(50),
colors = ButtonDefaults.buttonColors(containerColor = Color.White),
onClick = { navController?.navigate(Navigation.WelcomeScreen.route) }
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Spacer(modifier = Modifier.size(ButtonDefaults.IconSpacing))
Text(
text = "Connect Now",
color = Ocean11,
fontWeight = FontWeight.Bold
)
}
}
}
}
}
@Preview
@Composable
private fun Preview() {
narcisApplicationTheme {
Landing(null)
}
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/screens/landing/Landing.kt | 585529937 |
package com.narcis.application.presentation.screens.signUp
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Icon
import androidx.compose.material.OutlinedButton
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import io.nekohasekai.sagernet.R
import com.narcis.application.presentation.components.ButtonGradient
import com.narcis.application.presentation.navigation.Navigation
import com.narcis.application.presentation.screens.landing.AnimatedLogo
import com.narcis.application.presentation.ui.theme.narcisApplicationTheme
import com.narcis.application.presentation.ui.theme.ApplicationTheme
import com.narcis.application.presentation.ui.theme.Blue0
import com.narcis.application.presentation.ui.theme.Blue1
import com.narcis.application.presentation.ui.theme.Neutral2
import com.narcis.application.presentation.ui.theme.Neutral3
import com.narcis.application.presentation.ui.theme.Purple40
import com.narcis.application.presentation.ui.theme.Sky0
import com.narcis.application.presentation.ui.theme.Sky1
import com.narcis.application.presentation.viewModel.AuthenticationViewModel
import com.narcis.application.presentation.viewModel.event.SendCodeEvent
import kotlinx.coroutines.launch
@OptIn(ExperimentalComposeUiApi::class, ExperimentalMaterial3Api::class)
@Composable
fun EmailSignUpScreen(
navController: NavController?,
viewModel: AuthenticationViewModel = hiltViewModel()
) {
var text by rememberSaveable {
mutableStateOf("")
}
val scope = rememberCoroutineScope()
var loadingVisibility by remember { mutableStateOf(false) }
val state by viewModel.state.collectAsState()
val snackBarHostState = remember {
SnackbarHostState()
}
LaunchedEffect(key1 = state) {
if (state.isValid) {
loadingVisibility = false
if (loadingVisibility) {
} else {
if (state.isAlreadyRegistered) {
navController?.navigate(Navigation.EmailSignInScreen.route)
viewModel.onEvent(SendCodeEvent.ClearEvent)
} else {
navController?.navigate(Navigation.PasswordScreen.route + "/${text}")
viewModel.onEvent(SendCodeEvent.ClearEvent)
}
}
} else {
loadingVisibility = false
scope.launch {
if (state.message.isNotBlank()) {
snackBarHostState.showSnackbar(state.message)
navController?.navigate(Navigation.EmailSignInScreen.route) // add this to navigate without server!
}
}
}
}
val keyboardController = LocalSoftwareKeyboardController.current
Scaffold(
modifier = Modifier.fillMaxSize(),
containerColor = ApplicationTheme.colors.uiBackground,
snackbarHost = {
SnackbarHost(hostState = snackBarHostState)
}) {
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
// .background(color = ApplicationTheme.colors.uiBackground)
.padding(it),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.height(32.dp))
AnimatedLogo(
modifier = Modifier
.fillMaxWidth(.3f)
.padding(bottom = 8.dp),
colors = listOf(Sky1, Sky0)
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = "Create Your Account",
color = ApplicationTheme.colors.textPrimary,
fontWeight = FontWeight.Bold,
fontSize = 28.sp,
maxLines = 1,
modifier = Modifier.padding(16.dp),
textAlign = TextAlign.Center
)
Text(
text = "create your free account now and experience the true potential of VPN",
color = ApplicationTheme.colors.textSecondry,
modifier = Modifier.padding(8.dp),
textAlign = TextAlign.Center,
fontSize = 16.sp
)
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.height(32.dp))
OutlinedTextField(
value = text,
onValueChange = {
text = it
},
shape = RoundedCornerShape(30.dp),
leadingIcon = {
Icon(
painter = painterResource(id = R.drawable.mail_icon),
contentDescription = "mail icon",
tint = Neutral2
)
},
singleLine = true,
label = {
Text(
text = "Email",
color = ApplicationTheme.colors.textSecondry,
style = MaterialTheme.typography.labelMedium
)
},
placeholder = { Text(text = "Enter your email address") },
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Next,
keyboardType = KeyboardType.Email
),
colors = TextFieldDefaults.outlinedTextFieldColors(
textColor = ApplicationTheme.colors.textPrimary,
unfocusedLabelColor = Neutral3,
placeholderColor = Color.White,
focusedBorderColor = Neutral2,
unfocusedBorderColor = Neutral2
),
modifier = Modifier.fillMaxWidth(0.9f),
keyboardActions = KeyboardActions(
onDone = { keyboardController?.hide() },
onNext = { keyboardController?.hide()
loadingVisibility = true
viewModel.onEvent(SendCodeEvent.EmailQuery(text.trim()))
}
)
)
Spacer(modifier = Modifier.padding(10.dp))
ButtonGradient(
gradientColors = listOf(Blue0, Blue1),
cornerRadius = 30.dp,
nameButton = "Next",
roundedCornerShape = RoundedCornerShape(30.dp)
) {
loadingVisibility = true
viewModel.onEvent(SendCodeEvent.EmailQuery(text.trim()))
}
if (loadingVisibility) {
CircularProgressIndicator(color = Purple40)
}
Spacer(modifier = Modifier.padding(10.dp))
Text(text = "OR", letterSpacing = 1.sp, style = MaterialTheme.typography.labelLarge)
Spacer(modifier = Modifier.padding(10.dp))
OutlinedButton(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
onClick = {
},
contentPadding = PaddingValues(
start = 20.dp,
top = 12.dp,
end = 20.dp,
bottom = 12.dp
),
border = BorderStroke(2.dp, Color.LightGray),
shape = RoundedCornerShape(50),
colors = ButtonDefaults.outlinedButtonColors(backgroundColor = ApplicationTheme.colors.uiBackground)
) {
Box(Modifier.fillMaxWidth()) {
Image(
modifier = Modifier
.align(Alignment.CenterStart)
.clip(CircleShape),
painter = painterResource(id = R.drawable.google_icon),
contentDescription = null
)
Text(
modifier = Modifier.align(Alignment.Center),
textAlign = TextAlign.Center,
text = "Continue with Google",
color = ApplicationTheme.colors.textSecondry
)
}
}
}
}
}
}
@Composable
@Preview
private fun Preview() {
narcisApplicationTheme {
EmailSignUpScreen(null)
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/screens/signUp/EmailSignUp.kt | 200702268 |
package com.narcis.application.presentation.screens.signUp
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.narcis.application.presentation.components.ButtonGradient
import com.narcis.application.presentation.components.SmsCodeView
import com.narcis.application.presentation.navigation.Navigation
import com.narcis.application.presentation.screens.landing.AnimatedLogo
import com.narcis.application.presentation.ui.theme.narcisApplicationTheme
import com.narcis.application.presentation.ui.theme.ApplicationTheme
import com.narcis.application.presentation.ui.theme.Blue0
import com.narcis.application.presentation.ui.theme.Blue1
import com.narcis.application.presentation.ui.theme.Neutral3
import com.narcis.application.presentation.ui.theme.Neutral7
import com.narcis.application.presentation.ui.theme.Sky0
import com.narcis.application.presentation.ui.theme.Sky1
import com.narcis.application.presentation.utiles.longToast
import com.narcis.application.presentation.viewModel.VerificationCodeViewModel
import com.narcis.application.presentation.viewModel.event.SendVerificationEvent
import kotlinx.coroutines.delay
@Composable
fun VerificationSignUp(
navController: NavController?,
verificationCodeViewModel: VerificationCodeViewModel? = hiltViewModel()
) {
val context = LocalContext.current
val otpValue = remember { mutableStateOf("") }
var resend by remember {
mutableStateOf(false)
}
var timer by remember { mutableStateOf(120) }
LaunchedEffect(key1 = timer) {
if (timer > 0) {
delay(1_000)
timer -= 1
resend = false
} else {
resend = true
}
}
var smsCodeNumber by remember {
mutableStateOf("")
}
var isNextBtnStatus by remember {
mutableStateOf(false)
}
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.background(color = ApplicationTheme.colors.uiBackground),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Spacer(modifier = Modifier.height(32.dp))
AnimatedLogo(
modifier = Modifier
.fillMaxWidth(.3f)
.padding(bottom = 8.dp),
colors = listOf(Sky1, Sky0)
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = "Verification Code",
color = ApplicationTheme.colors.textPrimary,
fontWeight = FontWeight.Bold,
fontSize = 28.sp,
maxLines = 1,
modifier = Modifier.padding(16.dp),
textAlign = TextAlign.Center
)
Text(
text = "Enter the verification code sent to ${verificationCodeViewModel?.email ?: "email" } to ensure secure account access.",
color = ApplicationTheme.colors.textSecondry,
modifier = Modifier.padding(8.dp),
textAlign = TextAlign.Center,
fontSize = 16.sp
)
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally
) {
// val otpValue = remember { mutableStateOf("") }
Spacer(modifier = Modifier.height(32.dp))
SmsCodeView(
smsCodeLength = 6,
textFieldColors = TextFieldDefaults.outlinedTextFieldColors(
textColor = Neutral7,
unfocusedLabelColor = Neutral3,
placeholderColor = Color.White,
focusedBorderColor = Blue0,
unfocusedBorderColor = Blue0,
backgroundColor = Sky0
),
textStyle = MaterialTheme.typography.h6,
smsFulled = {
smsCodeNumber = it
isNextBtnStatus = it.length == 4
}
)
// PinInput(
// cellModifier = Modifier.border(
// BorderStroke(2.dp, Neutral2),
// shape = RoundedCornerShape(10.dp)
// ),
// value = otpValue.value,
// obscureText = null,
// length = 6,
// disableKeypad = false // Optional
// ) {
// otpValue.value = it
// }
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "Code is 6 digits without space",
color = ApplicationTheme.colors.textSecondry,
modifier = Modifier.padding(start = 32.dp),
textAlign = TextAlign.Right,
fontSize = 16.sp
)
Spacer(modifier = Modifier.padding(10.dp))
ButtonGradient(
gradientColors = listOf(Blue0, Blue1),
cornerRadius = 30.dp,
nameButton = "Verify",
roundedCornerShape = RoundedCornerShape(30.dp)
) {
if (smsCodeNumber.length == 6) {
verificationCodeViewModel!!.onEvent(
SendVerificationEvent.SignInQuery(
email = verificationCodeViewModel.state.email,
password = verificationCodeViewModel.state.password,
code = smsCodeNumber
)
)
if (verificationCodeViewModel.state.isSuccessful) {
// val intent = Intent(context, ConnActivity::class.java)
// context.startActivity(intent)
navController?.navigate(Navigation.MainConnectionScreen.route)
} else {
if (verificationCodeViewModel.state.error.isNotBlank()) {
longToast(
context,
verificationCodeViewModel.state.error
)
} else {
longToast(
context,
"Oops! Try again.."
)
}
}
}
}
Spacer(modifier = Modifier.padding(10.dp))
Text(
text = "Resend Code in ${timer / 60} : ${timer % 60}",
color = Blue1,
modifier = Modifier
.padding(start = 32.dp)
.clickable {
if (resend) {
verificationCodeViewModel?.onEvent(
SendVerificationEvent.EmailQuery
)
timer = 120
} else {
longToast(
context,
"Wait for the count down"
)
}
},
textAlign = TextAlign.Right,
fontSize = 18.sp
)
}
}
}
@Composable
@Preview
private fun Preview() {
narcisApplicationTheme {
VerificationSignUp(null, null)
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/screens/signUp/VerificationSignUp.kt | 2616732367 |
package com.narcis.application.presentation.screens.signUp
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import io.nekohasekai.sagernet.R
import com.narcis.application.presentation.components.ButtonGradient
import com.narcis.application.presentation.navigation.Navigation
import com.narcis.application.presentation.screens.landing.AnimatedLogo
import com.narcis.application.presentation.ui.theme.ApplicationTheme
import com.narcis.application.presentation.ui.theme.Blue0
import com.narcis.application.presentation.ui.theme.Blue1
import com.narcis.application.presentation.ui.theme.Neutral2
import com.narcis.application.presentation.ui.theme.Neutral3
import com.narcis.application.presentation.ui.theme.Sky0
import com.narcis.application.presentation.ui.theme.Sky1
import com.narcis.application.presentation.utiles.Visibility
import com.narcis.application.presentation.utiles.VisibilityOff
import com.narcis.application.presentation.viewModel.PasswordViewModel
import kotlinx.coroutines.launch
@OptIn(ExperimentalComposeUiApi::class, ExperimentalMaterial3Api::class)
@Composable
fun PasswordSignUp(
navController: NavController?,
passwordViewModel: PasswordViewModel = hiltViewModel()
) {
BackHandler() {
// Handle the back press here
navController?.popBackStack()
}
val keyboardController = LocalSoftwareKeyboardController.current
var passwordOne by rememberSaveable {
mutableStateOf("")
}
var passwordTwo by rememberSaveable {
mutableStateOf("")
}
var passwordHiddenOne by rememberSaveable {
mutableStateOf(true)
}
var passwordHiddenTwo by rememberSaveable {
mutableStateOf(true)
}
val snackBarHostState = remember {
SnackbarHostState()
}
val scope = rememberCoroutineScope()
Scaffold(
modifier = Modifier.fillMaxSize(),
containerColor = ApplicationTheme.colors.uiBackground,
snackbarHost = {
SnackbarHost(hostState = snackBarHostState)
}) {
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.background(color = ApplicationTheme.colors.uiBackground)
.padding(it),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.height(32.dp))
AnimatedLogo(
modifier = Modifier
.fillMaxWidth(.3f)
.padding(bottom = 8.dp),
colors = listOf(Sky1, Sky0)
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = "Enter Password",
color = ApplicationTheme.colors.textPrimary,
fontWeight = FontWeight.Bold,
fontSize = 28.sp,
maxLines = 1,
modifier = Modifier.padding(16.dp),
textAlign = TextAlign.Center
)
Text(
text = "create your free account now and experience the true potential of VPN",
color = ApplicationTheme.colors.textSecondry,
modifier = Modifier.padding(8.dp),
textAlign = TextAlign.Center,
fontSize = 16.sp
)
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.height(32.dp))
OutlinedTextField(
value = passwordOne,
onValueChange = { passwordOne = it },
shape = RoundedCornerShape(30.dp),
label = {
Text(
"Password",
color = MaterialTheme.colorScheme.primary,
style = MaterialTheme.typography.labelMedium,
)
},
visualTransformation =
if (passwordHiddenOne) PasswordVisualTransformation() else VisualTransformation.None,
// keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Done,
keyboardType = KeyboardType.Password
),
colors = TextFieldDefaults.outlinedTextFieldColors(
textColor = ApplicationTheme.colors.textPrimary,
unfocusedLabelColor = Neutral3,
placeholderColor = Color.White,
focusedBorderColor = Neutral2,
unfocusedBorderColor = Neutral2
),
trailingIcon = {
IconButton(onClick = { passwordHiddenOne = !passwordHiddenOne }) {
val visibilityIcon =
if (passwordHiddenOne) Visibility else VisibilityOff
// Please provide localized description for accessibility services
val description =
if (passwordHiddenOne) "Show password" else "Hide password"
Icon(imageVector = visibilityIcon, contentDescription = description)
}
},
leadingIcon = {
Icon(
painter = painterResource(id = R.drawable.key_icon),
contentDescription = "password icon",
tint = Neutral2
)
},
modifier = Modifier.fillMaxWidth(0.92f),
keyboardActions = KeyboardActions(
onDone = {
keyboardController?.hide()
// do something here
}
)
)
Spacer(modifier = Modifier.height(16.dp))
OutlinedTextField(
value = passwordTwo,
onValueChange = { passwordTwo = it },
shape = RoundedCornerShape(30.dp),
label = {
Text(
"Confirm Password",
color = MaterialTheme.colorScheme.primary,
style = MaterialTheme.typography.labelMedium,
)
},
visualTransformation =
if (passwordHiddenTwo) PasswordVisualTransformation() else VisualTransformation.None,
// keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Done,
keyboardType = KeyboardType.Password
),
colors = TextFieldDefaults.outlinedTextFieldColors(
textColor = ApplicationTheme.colors.textPrimary,
unfocusedLabelColor = Neutral3,
placeholderColor = Color.White,
focusedBorderColor = Neutral2,
unfocusedBorderColor = Neutral2
),
trailingIcon = {
IconButton(onClick = { passwordHiddenTwo = !passwordHiddenTwo }) {
val visibilityIcon =
if (passwordHiddenTwo) Visibility else VisibilityOff
// Please provide localized description for accessibility services
val description =
if (passwordHiddenTwo) "Show password" else "Hide password"
Icon(imageVector = visibilityIcon, contentDescription = description)
}
},
leadingIcon = {
Icon(
painter = painterResource(id = R.drawable.key_icon),
contentDescription = "password icon",
tint = Neutral2
)
},
modifier = Modifier.fillMaxWidth(0.92f),
keyboardActions = KeyboardActions(
onDone = {
keyboardController?.hide()
// do something here
}
)
)
Spacer(modifier = Modifier.padding(10.dp))
ButtonGradient(
gradientColors = listOf(Blue0, Blue1),
cornerRadius = 30.dp,
nameButton = "Next",
roundedCornerShape = RoundedCornerShape(30.dp)
) {
if (passwordOne == passwordTwo) {
navController?.navigate(
Navigation.VerificationCodeScreen.route + "/${passwordViewModel.email.value}" + "/${passwordOne.toString()}"
)
} else {
scope.launch {
snackBarHostState.showSnackbar("oops! the passwords don't match!")
}
}
}
}
}
}
}
//@Preview
//@Composable
//private fun Preview() {
// narcisApplicationTheme {
// PasswordSignUp(null, VerificationCodeViewModel(), AuthenticationViewModel())
// }
//} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/screens/signUp/PasswordSignUp.kt | 64892241 |
package com.narcis.application.presentation.screens.signUp
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import io.nekohasekai.sagernet.R
import com.narcis.application.presentation.components.ButtonGradient
import com.narcis.application.presentation.navigation.Navigation
import com.narcis.application.presentation.screens.landing.AnimatedLogo
import com.narcis.application.presentation.ui.theme.narcisApplicationTheme
import com.narcis.application.presentation.ui.theme.ApplicationTheme
import com.narcis.application.presentation.ui.theme.Blue0
import com.narcis.application.presentation.ui.theme.Blue1
import com.narcis.application.presentation.ui.theme.Neutral2
import com.narcis.application.presentation.ui.theme.Neutral3
import com.narcis.application.presentation.ui.theme.Purple40
import com.narcis.application.presentation.ui.theme.Sky0
import com.narcis.application.presentation.ui.theme.Sky1
import com.narcis.application.presentation.utiles.Visibility
import com.narcis.application.presentation.utiles.VisibilityOff
import com.narcis.application.presentation.utiles.longToast
import com.narcis.application.presentation.viewModel.SignInViewModel
import com.narcis.application.presentation.viewModel.event.SignInEvent
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun EmailSignIn(
navController: NavController?,
viewModel: SignInViewModel = hiltViewModel()
) {
var text by rememberSaveable {
mutableStateOf("")
}
val keyboardController = LocalSoftwareKeyboardController.current
var password by rememberSaveable {
mutableStateOf("")
}
var passwordHidden by rememberSaveable {
mutableStateOf(true)
}
val context = LocalContext.current
var loadingVisibility by remember { mutableStateOf(false) }
val state by viewModel.state.collectAsState()
LaunchedEffect(key1 = state) {
if (state.isRequestSend) {
if (state.isLoading) {
loadingVisibility = true
} else if (state.isSuccessful) {
loadingVisibility = false
navController?.navigate(Navigation.MainConnectionScreen.route)
} else if (state.error.isNotEmpty()) {
loadingVisibility = false
longToast(context, "Oops, Try Again!")
navController?.navigate(Navigation.MainConnectionScreen.route) // add this to navigate without server
} else {
loadingVisibility = false
}
}
}
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.background(color = ApplicationTheme.colors.uiBackground),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.height(32.dp))
AnimatedLogo(
modifier = Modifier
.fillMaxWidth(.3f)
.padding(bottom = 8.dp),
colors = listOf(Sky1, Sky0)
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = "Welcome Back",
color = ApplicationTheme.colors.textPrimary,
fontWeight = FontWeight.Bold,
fontSize = 28.sp,
maxLines = 1,
modifier = Modifier.padding(16.dp),
textAlign = TextAlign.Center
)
Text(
text = "Please sign in to access your account",
color = ApplicationTheme.colors.textSecondry,
modifier = Modifier.padding(8.dp),
textAlign = TextAlign.Center,
fontSize = 16.sp
)
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.height(32.dp))
OutlinedTextField(value = text,
onValueChange = {
text = it
},
shape = RoundedCornerShape(30.dp),
leadingIcon = {
Icon(
painter = painterResource(id = R.drawable.mail_icon),
contentDescription = "mail icon",
tint = Neutral2
)
},
singleLine = true,
label = {
Text(
text = "Email",
color = ApplicationTheme.colors.textSecondry,
style = MaterialTheme.typography.labelMedium
)
},
placeholder = { Text(text = "Enter your email address") },
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Next,
keyboardType = KeyboardType.Email
),
colors = TextFieldDefaults.outlinedTextFieldColors(
textColor = ApplicationTheme.colors.textPrimary,
unfocusedLabelColor = Neutral3,
placeholderColor = Color.White,
focusedBorderColor = Neutral2,
unfocusedBorderColor = Neutral2
),
modifier = Modifier.fillMaxWidth(0.9f),
keyboardActions = KeyboardActions(
onDone = { keyboardController?.hide() }
)
)
Spacer(modifier = Modifier.height(16.dp))
OutlinedTextField(
value = password,
onValueChange = { password = it },
shape = RoundedCornerShape(30.dp),
label = {
Text(
"Password",
color = MaterialTheme.colorScheme.primary,
style = MaterialTheme.typography.labelMedium,
)
},
visualTransformation =
if (passwordHidden) PasswordVisualTransformation() else VisualTransformation.None,
// keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Done,
keyboardType = KeyboardType.Password
),
colors = TextFieldDefaults.outlinedTextFieldColors(
textColor = ApplicationTheme.colors.textPrimary,
unfocusedLabelColor = Neutral3,
placeholderColor = Color.White,
focusedBorderColor = Neutral2,
unfocusedBorderColor = Neutral2
),
trailingIcon = {
IconButton(onClick = { passwordHidden = !passwordHidden }) {
val visibilityIcon =
if (passwordHidden) Visibility else VisibilityOff
// Please provide localized description for accessibility services
val description = if (passwordHidden) "Show password" else "Hide password"
Icon(imageVector = visibilityIcon, contentDescription = description)
}
},
leadingIcon = {
Icon(
painter = painterResource(id = R.drawable.key_icon),
contentDescription = "password icon",
tint = Neutral2
)
},
modifier = Modifier.fillMaxWidth(0.92f),
keyboardActions = KeyboardActions(
onDone = {
keyboardController?.hide()
// do something here
}
)
)
Spacer(modifier = Modifier.padding(10.dp))
ButtonGradient(
gradientColors = listOf(Blue0, Blue1),
cornerRadius = 30.dp,
nameButton = "Next",
roundedCornerShape = RoundedCornerShape(30.dp)
) {
loadingVisibility = true
viewModel.onEvent(
SignInEvent.SignInQuery(
email = text,
password = password
)
)
}
if (loadingVisibility) {
CircularProgressIndicator(color = Purple40)
}
}
}
}
@Preview
@Composable
private fun Preview() {
narcisApplicationTheme {
EmailSignIn(null)
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/screens/signUp/SignInScreen.kt | 2949335608 |
package com.narcis.application.presentation.screens
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.narcis.application.presentation.components.CustomSurface
import com.narcis.application.presentation.extensions.fadeInDiagonalGradientBorder
import com.narcis.application.presentation.extensions.offsetGradientBackground
import com.narcis.application.presentation.ui.theme.narcisApplicationTheme
import com.narcis.application.presentation.ui.theme.ApplicationTheme
import io.nekohasekai.sagernet.R
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Landing(
onNavigateToRoute: (String) -> Unit,
modifier: Modifier = Modifier
) {
Landing()
}
@Composable
private fun Landing(
modifier: Modifier = Modifier
) {
val brush = Brush.linearGradient(
colors = ApplicationTheme.colors.iconGradiant,
start = Offset.Zero,
end = Offset(x = 260f, y = 0f)
)
val gradiantBackground = Modifier.offsetGradientBackground(
ApplicationTheme.colors.iconGradiant,
2660f,
0f
)
val shape = Modifier.fadeInDiagonalGradientBorder(
showBorder = false,
colors = ApplicationTheme.colors.iconGradiant,
shape = MaterialTheme.shapes.large
)
CustomSurface(
modifier = modifier.fillMaxSize(),
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Image(
painter = painterResource(R.drawable.main_icon), contentDescription = "main icon",
modifier = Modifier.padding(top = 120.dp),
alignment = Alignment.Center
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "Ving VPN",
style = MaterialTheme.typography.h3,
maxLines = 1,
overflow = TextOverflow.Visible,
color = ApplicationTheme.colors.textPrimary,
modifier = Modifier.padding(horizontal = 16.dp)
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = "We have best server around the world with super high speed connection",
style = MaterialTheme.typography.body1,
color = ApplicationTheme.colors.textHelp,
textAlign = TextAlign.Center,
maxLines = 2,
modifier = Modifier.padding(horizontal = 16.dp)
)
Spacer(modifier = Modifier.height(120.dp))
CustomSurface(
shape = RoundedCornerShape(20.dp),
elevation = 2.dp,
modifier = Modifier.wrapContentSize()
) {
Box(
modifier = Modifier
.width(260.dp)
.height(48.dp)
.then(gradiantBackground)
.align(Alignment.CenterHorizontally)
) {
Text(
text = "Continue",
color = Color.White,
fontSize = 24.sp,
style = MaterialTheme.typography.caption,
modifier = Modifier.padding(
start = 70.dp,
top = 8.dp
),
textAlign = TextAlign.Center
)
}
}
Spacer(modifier = Modifier.padding(8.dp))
Text(
text = "Skip For Now",
color = ApplicationTheme.colors.textSecondry,
style = MaterialTheme.typography.h6,
textAlign = TextAlign.Center
)
}
}
}
@Composable
@Preview
private fun Preview() {
narcisApplicationTheme {
Landing(onNavigateToRoute = {})
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/screens/Home.kt | 4270725388 |
package com.narcis.application.presentation.screens.purchase
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.narcis.application.presentation.ui.theme.narcisApplicationTheme
import com.narcis.application.presentation.ui.theme.ApplicationTheme
import com.narcis.application.presentation.ui.theme.Ocean11
import io.nekohasekai.sagernet.R
@Composable
fun PurchaseScreen(navController: NavController?) {
val brush = Brush.verticalGradient(ApplicationTheme.colors.welcomeGradiant)
Column(
modifier = Modifier
.background(brush = brush)
.paint(
painter = painterResource(id = R.drawable.halow_icon),
contentScale = ContentScale.Crop
),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.height(60.dp))
Text(
text = "Premium Plan",
color = Color.White,
fontWeight = FontWeight.Bold,
fontSize = 28.sp,
maxLines = 1,
modifier = Modifier.padding(16.dp),
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(8.dp))
Row(
modifier = Modifier.padding(12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
FeatureTikText(text = "Secure")
FeatureTikText(text = "High-speed VPN")
FeatureTikText(text = "Customer Support")
}
Spacer(modifier = Modifier.height(16.dp))
Column(modifier = Modifier.padding(end = 15.dp, start = 15.dp, bottom = 10.dp)) {
ShoppingItem(onClick = { /*TODO*/ })
}
Button(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 32.dp),
contentPadding = PaddingValues(
start = 20.dp,
top = 12.dp,
end = 20.dp,
bottom = 12.dp
),
shape = RoundedCornerShape(50),
colors = ButtonDefaults.buttonColors(containerColor = Color.White),
onClick = { }
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Spacer(modifier = Modifier.size(ButtonDefaults.IconSpacing))
Text(
text = "Get A Plane",
color = Ocean11,
fontWeight = FontWeight.Bold
)
}
}
}
}
@Composable
fun FeatureTikText(text: String, modifier: Modifier = Modifier) {
Row(modifier = modifier) {
Image(
painter = painterResource(id = R.drawable.tike_icon),
contentDescription = "feature $text",
modifier = Modifier.padding(4.dp)
)
Text(
text = text,
color = Color.White,
maxLines = 1,
textAlign = TextAlign.Center
)
}
}
@Preview
@Composable
private fun Preview() {
narcisApplicationTheme {
PurchaseScreen(null)
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/screens/purchase/PurchasePlaneScreen.kt | 946052868 |
package com.narcis.application.presentation.screens.purchase
class ShoppingList : ArrayList<ShoppingListItem>() | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/screens/purchase/ShoppingList.kt | 12709479 |
package com.narcis.application.presentation.screens.purchase
data class ShoppingListItem(
val createdDate: String,
val features: List<Feature>,
val hasOptions: Boolean,
val id: Int,
val modifiedDate: String,
val period: Int,
val price: Double,
val priceBeforeDiscount: Double,
val title: String,
val users: Int
) | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/screens/purchase/ShoppingListItem.kt | 3883439202 |
package com.narcis.application.presentation.screens.purchase
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.RadioButton
import androidx.compose.material3.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.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.narcis.application.presentation.ui.theme.narcisApplicationTheme
import com.narcis.application.presentation.ui.theme.ApplicationTheme
import com.narcis.application.presentation.ui.theme.Blue1
import com.narcis.application.presentation.ui.theme.Ocean11
@Composable
fun ShoppingItem(
onClick: () -> Unit,
) {
Row(
modifier = Modifier
.clip(RoundedCornerShape(8))
.fillMaxWidth()
.clickable {
onClick()
}
.background(color = Color.White.copy(alpha = 0.7f)),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Column {
// Text(
// text = "Best Deal",
// color = Color.White,
// modifier = Modifier
// .fillMaxWidth()
// .height(25.dp)
// .background(color = Ocean13),
// textAlign = TextAlign.Center,
//
// )
Row {
Column(modifier = Modifier.padding(12.dp)) {
Row(
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "plan",
fontWeight = FontWeight.Bold,
fontSize = 18.sp,
color = ApplicationTheme.colors.textPrimary,
modifier = Modifier.padding(8.dp)
)
Text(
text = "30% OFF",
color = ApplicationTheme.colors.textSecondry,
fontSize = 8.sp,
modifier = Modifier
.background(color = ApplicationTheme.colors.uiBackground.copy(alpha = 0.8f))
.shadow(elevation = 2.dp)
.clip(RoundedCornerShape(20))
.padding(start = 8.dp, end = 4.dp)
)
}
Row(verticalAlignment = Alignment.Bottom) {
Text(
text = "$",
fontSize = 15.sp,
color = Blue1,
modifier = Modifier.padding(
start = 12.dp, end = 4.dp
)
)
Text(
text = "12.99",
color = Ocean11,
fontWeight = FontWeight.Bold,
fontSize = 25.sp,
)
Text(text = " /month", fontSize = 8.sp, color = Blue1)
}
}
Spacer(modifier = Modifier.width(130.dp))
Column(
modifier = Modifier.padding(12.dp)
) {
RadioButton(
selected = false, onClick = { /*TODO*/ },
// colors = RadioButtonDefaults.colors()
)
Text(text = "save 20$", maxLines = 1, overflow = TextOverflow.Visible)
}
}
}
}
}
@Preview
@Composable
private fun preview() {
narcisApplicationTheme {
ShoppingItem(
onClick = {},
)
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/screens/purchase/ShoppingCardItem.kt | 3133467710 |
package com.narcis.application.presentation.screens.purchase
data class Feature(
val createdDate: String,
val id: Int,
val modifiedDate: String,
val status: Boolean,
val title: String
) | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/screens/purchase/Feature.kt | 394214272 |
package com.narcis.application.presentation.screens.purchase
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.selection.selectable
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material3.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.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.narcis.application.presentation.ui.theme.ApplicationTheme
import com.narcis.application.presentation.ui.theme.Ocean13
import com.narcis.application.presentation.ui.theme.Ocean9
@Composable
fun RadioButtonWithImageRow(
duration: String,
selected: Boolean,
onOptionSelected: () -> Unit,
discount: String,
isBestDeal: Boolean? = false,
save: String,
pricePerMonth: String,
modifier: Modifier = Modifier,
) {
Surface(
shape = MaterialTheme.shapes.small,
color = if (selected) {
Ocean9.copy(alpha = 0.4f)
} else {
Color.White.copy(alpha = 0.4f)
},
modifier = modifier
.clip(MaterialTheme.shapes.small)
.selectable(
selected,
onClick = onOptionSelected,
role = Role.RadioButton
)
.wrapContentSize()
) {
Row(
modifier = Modifier
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Column(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
) {
Text(
text = "Best Deal",
color = Color.White,
modifier = Modifier
.fillMaxWidth()
.height(25.dp)
.background(color = Ocean13),
textAlign = TextAlign.Center,
)
Text(
text = "plan",
fontWeight = FontWeight.Bold,
fontSize = 18.sp,
color = ApplicationTheme.colors.textPrimary,
modifier = Modifier.padding(8.dp)
)
Row {
Column(modifier = Modifier.padding(12.dp)) {
Text(
text = "plan",
fontWeight = FontWeight.Bold,
fontSize = 18.sp,
color = ApplicationTheme.colors.textPrimary,
modifier = Modifier.padding(8.dp)
)
}
}
}
}
}
}
@Preview
@Composable
private fun PreviewRadio() {
RadioButtonWithImageRow(
duration = "1 month",
selected = false,
onOptionSelected = {},
discount = "30%",
isBestDeal = false,
save = "$4",
pricePerMonth = "12.99",
)
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/screens/purchase/RadioButtonWithImageRow.kt | 281106903 |
package com.narcis.application.presentation.screens.help
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
@Composable
fun HelpScreen(navController: NavController) {
Column {
Spacer(modifier = Modifier.height(60.dp))
Text(text = "Help Screen", fontSize = 20.sp)
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/screens/help/HelpScreen.kt | 1949549572 |
package com.narcis.application.presentation.components
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.narcis.application.presentation.ui.theme.narcisApplicationTheme
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sin
@Composable
fun PizzaSliceView() {
var sliceColor by remember { mutableStateOf(Color.Red) }
Canvas(
modifier = Modifier.fillMaxSize()
) {
val center = Offset(size.width / 2f, size.height / 2f)
val radius = size.minDimension / 2f
val sliceAngle = (2 * PI) / 8 // Calculate the angle for each slice
val sliceGap = 0f // Adjust the gap between slices
val path = Path()
// Draw the slices
for (i in 0 until 8) { // You can adjust the number of slices
val startAngle = sliceAngle * i.toFloat()
val endAngle = sliceAngle * (i + 1).toFloat()
val startX = center.x + radius * cos(startAngle)
val startY = center.y + radius * sin(startAngle)
val endX = center.x + radius * cos(endAngle)
val endY = center.y + radius * sin(endAngle)
path.moveTo(center.x, center.y)
path.lineTo(startX.toFloat(), startY.toFloat())
path.lineTo(endX.toFloat(), endY.toFloat())
path.close()
}
// Draw the center circle
drawCircle(
color = sliceColor,
center = center,
radius = 30.dp.toPx()
)
// Create space between slices (Draw a smaller circle over the slices)
drawCircle(
color = Color.White, // Background color to create the gap
center = center,
radius = radius/2f - 4f,
)
// Draw the path (slices)
drawPath(path, color = sliceColor)
}
}
@Preview
@Composable
private fun preview() {
narcisApplicationTheme {
PizzaSliceView()
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/components/SliceView.kt | 1370668395 |
package com.narcis.application.presentation.components
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.lazy.layout.getDefaultLazyLayoutKey
import androidx.compose.material.LocalContentColor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import com.narcis.application.presentation.extensions.withElevation
import com.narcis.application.presentation.ui.theme.ApplicationTheme
@Composable
fun CustomSurface(
modifier: Modifier = Modifier,
shape: Shape = RectangleShape,
color: Color = ApplicationTheme.colors.uiBackground,
contentColor: Color = ApplicationTheme.colors.textPrimary,
border: BorderStroke ?= null,
elevation: Dp = 0.dp,
content: @Composable () -> Unit
) {
Box(
modifier = modifier
.shadow(elevation = elevation, shape = shape, clip = false)
.zIndex(elevation.value)
.then(if (border != null) Modifier.border(border, shape) else Modifier)
.background(
color = GetBackgroundWithElevation(color = color, elevation = elevation),
shape = shape
)
.clip(shape)
) {
CompositionLocalProvider(LocalContentColor provides contentColor, content = content)
}
}
@Composable
private fun GetBackgroundWithElevation(color: Color, elevation: Dp): Color {
return if (elevation > 0.dp) {
color.withElevation(elevation)
} else {
color
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/components/CustomSurface.kt | 4183449264 |
package com.narcis.application.presentation.components
import android.text.format.Formatter
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateIntAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.SubcomposeAsyncImage
import coil.decode.SvgDecoder
import coil.request.ImageRequest
import com.narcis.application.presentation.ui.theme.Neutral0
import com.narcis.application.presentation.ui.theme.Sky0
import com.narcis.application.presentation.utiles.countryFlagUrl
import com.narcis.application.presentation.utiles.isInternetConnected
import com.narcis.application.presentation.utiles.longToast
import com.narcis.application.presentation.viewModel.DefaultConfigViewModel
import com.google.android.material.progressindicator.BaseProgressIndicator
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.aidl.TrafficStats
import io.nekohasekai.sagernet.bg.BaseService
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
// private val iconStopping by lazy { AnimatedState(R.drawable.ic_service_stopping) }
private var checked = false
private var delayedAnimation: Job? = null
private lateinit var progress: BaseProgressIndicator<*>
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun VpnConnectButton(
outStrokeWidth: Float = 8f,
thumbStrokeWidth: Float = 6f,
onClick: () -> Unit,
state: MutableState<BaseService.State>,
trafficState: MutableState<TrafficStats>,
configViewModel: DefaultConfigViewModel = hiltViewModel(),
isConfigEmpty: Boolean,
) {
var connected by remember {
mutableStateOf(false)
}
var text by remember {
mutableStateOf("Tap To Connect ")
}
var progress by remember {
mutableStateOf(0)
}
var color by remember {
mutableStateOf(Color(0xFF008B48))
}
val connectionStatus by remember {
state
}
val context = LocalContext.current
val animateProgress by animateIntAsState(
targetValue = getProgressForConnectionStatus(connectionStatus),
animationSpec = tween(1200)
)
val animateColor by animateColorAsState(
targetValue = color,
animationSpec = tween(1500)
)
val configValue by configViewModel.selectedProxy.collectAsState()
val scope = rememberCoroutineScope()
LaunchedEffect(key1 = true) {
progress = 360
delay(1300)
progress = 0
}
Column(
Modifier
.padding(10.dp)
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Spacer(modifier = Modifier.height(12.dp))
Text(
text = if (connectionStatus == BaseService.State.Connected)
"You're Connected" else "You're not Connected",
color = Neutral0,
fontSize = 20.sp
)
Spacer(modifier = Modifier.height(24.dp))
Surface(
shape = CircleShape,
color = Color.White,
elevation = 3.dp,
onClick = {
val isInternetConnected = isInternetConnected(context)
if (isInternetConnected && !isConfigEmpty) {
onClick()
// changeState(state, DataStore.serviceState, context)
scope.launch {
if (!connected) {
connected = true
color = Color(0xFF008B48)
text = connectionStatus.toString()
progress = getProgressForConnectionStatus(connectionStatus)
// text = "Connected"
color = Color(0xFF008B48)
// titleText = "You are connected"
if (text == BaseService.State.Connected.toString()) {
delay(200)
text = trafficState.value.rxRateProxy.toString()
}
} else {
text = "Tap To Connect"
color = Color(0xFF008B48)
progress = 0
connected = false
}
}
} else {
longToast(
context,
"no internet connection"
)
}
}
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.background(Color.White),
) {
Canvas(
Modifier
.size(50.dp)
.padding(10.dp)
) {
drawThumb(
color = animateColor,
thumbStrokeWidth = thumbStrokeWidth
)
}
Canvas(
Modifier
.size(150.dp)
.padding(10.dp)
) {
drawCircleProgressBar(
color = animateColor,
progressStrokeWidth = outStrokeWidth,
sweepAngle = animateProgress.toFloat()
)
}
}
}
Spacer(modifier = Modifier.height(15.dp))
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.wrapContentSize()
) {
if (connectionStatus != BaseService.State.Connected) {
Image(
painter = painterResource(id = R.drawable.tap_icon),
contentDescription = "connection description text",
modifier = Modifier.padding(12.dp)
)
}
Text(
text = if (connectionStatus != BaseService.State.Connected) {
if (connectionStatus == BaseService.State.Stopped) {
"Tap To Connect"
} else {
connectionStatus.toString()
}
} else {
"▲ ${
Formatter.formatFileSize(
LocalContext.current,
trafficState.value.txRateProxy
)
} ▼ ${
Formatter.formatFileSize(
LocalContext.current,
trafficState.value.rxRateProxy
)
}"
},
color = Neutral0,
fontSize = 16.sp,
)
}
if (connectionStatus.connected && configValue?.flag != "") {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.wrapContentSize()
) {
val parts = configValue?.flag?.split('/')
val countryCode = parts?.get(2)
val svgImageUrl = countryFlagUrl(countryCode)
SubcomposeAsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(svgImageUrl)
.decoderFactory(SvgDecoder.Factory())
.build(),
contentDescription = "flag icon image",
modifier = Modifier
.clip(CircleShape)
.size(24.dp)
.aspectRatio(1f),
contentScale = ContentScale.Crop,
loading = {
CircularProgressIndicator()
}
)
Text(
text = configValue?.address.toString(),
color = Neutral0,
fontSize = 16.sp,
modifier = Modifier.padding(8.dp)
)
}
}
}
}
fun DrawScope.drawThumb(
thumbStrokeWidth: Float,
color: Color = Color(0xFF008B48),
) {
drawArc(
color = color,
startAngle = -60f,
sweepAngle = 300f,
useCenter = false,
topLeft = Offset.Zero,
style = Stroke(
width = thumbStrokeWidth,
cap = StrokeCap.Round,
)
)
drawLine(
color = color,
start = center,
end = Offset(
x = center.x,
y = Offset.Zero.y - 5 // because of padding
),
cap = StrokeCap.Round,
strokeWidth = thumbStrokeWidth
)
}
fun DrawScope.drawCircleProgressBar(
color: Color = Color.DarkGray,
progressStrokeWidth: Float,
sweepAngle: Float,
) {
drawArc(
color = Sky0,
startAngle = -90f,
sweepAngle = 360f,
useCenter = false,
topLeft = Offset.Zero,
style = Stroke(
width = progressStrokeWidth * 7,
cap = StrokeCap.Round,
)
)
drawArc(
color = color,
startAngle = -90f,
sweepAngle = sweepAngle,
useCenter = false,
topLeft = Offset.Zero,
style = Stroke(
width = progressStrokeWidth * 6,
cap = StrokeCap.Round,
)
)
}
// @Preview
// @Composable
// private fun Preview() {
// VpnConnectButton(onClick = {}, context = LocalContext.current, state = BaseService.State)
// }
fun getProgressForConnectionStatus(status: BaseService.State): Int {
return when (status) {
BaseService.State.Idle -> 0
BaseService.State.Connecting -> 180
BaseService.State.Connected -> 360
BaseService.State.Stopping -> 180
BaseService.State.Stopped -> 0
}
}
private fun hideProgress() {
delayedAnimation?.cancel()
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/components/VpnCircleButton.kt | 2886720591 |
package com.narcis.application.presentation.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.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.geometry.CornerRadius
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun ButtonGradient(
gradientColors: List<Color>,
cornerRadius: Dp,
nameButton: String,
roundedCornerShape: RoundedCornerShape,
onClick: () -> Unit
) {
Button(
onClick = onClick,
modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp, end = 8.dp)
.background(color = Color.Transparent),
colors = ButtonDefaults.buttonColors(
contentColor = Color.Transparent
),
shape = RoundedCornerShape(cornerRadius),
contentPadding = PaddingValues()
) {
Box(
modifier = Modifier
.fillMaxWidth()
.background(
brush = Brush.horizontalGradient(colors = gradientColors),
shape = roundedCornerShape
)
.clip(roundedCornerShape)
.padding(horizontal = 16.dp, vertical = 8.dp),
contentAlignment = Alignment.Center
) {
Text(
text = nameButton,
fontSize = 20.sp,
color = Color.White
)
}
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/components/ButtonGradient.kt | 2366730451 |
package com.narcis.application.presentation.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.TextFieldColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusOrder
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEvent
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.core.text.isDigitsOnly
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun SmsCodeView(
smsCodeLength: Int,
textFieldColors: TextFieldColors,
textStyle: TextStyle,
smsFulled: (String) -> Unit
) {
val focusRequesters: List<FocusRequester> = remember {
(0 until smsCodeLength).map { FocusRequester() }
}
val enteredNumbers = remember {
mutableStateListOf(
*((0 until smsCodeLength).map { "" }.toTypedArray())
)
}
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
for (index in 0 until smsCodeLength) {
OutlinedTextField(
modifier = Modifier
.width(50.dp)
.height(60.dp)
.clip(RectangleShape)
.focusRequester(focusRequesters[index])
.focusOrder(focusRequester = focusRequesters[index])
.onKeyEvent { keyEvent: KeyEvent ->
val currentValue = enteredNumbers.getOrNull(index) ?: ""
if (keyEvent.key == Key.Backspace) {
if (currentValue.isNotEmpty()) {
enteredNumbers[index] = ""
smsFulled.invoke(enteredNumbers.joinToString(separator = ""))
} else {
focusRequesters
.getOrNull(index.minus(1))
?.requestFocus()
}
}
false
},
shape = RoundedCornerShape(20),
textStyle = textStyle,
singleLine = true,
value = enteredNumbers.getOrNull(index)?.trim() ?: "",
maxLines = 1,
colors = textFieldColors,
onValueChange = { value: String ->
when {
value.isDigitsOnly() -> {
if (focusRequesters[index].freeFocus()) {
when (value.length) {
1 -> {
enteredNumbers[index] = value.trim()
smsFulled.invoke(enteredNumbers.joinToString(separator = ""))
focusRequesters.getOrNull(index + 1)?.requestFocus()
}
2 -> {
focusRequesters.getOrNull(index + 1)?.requestFocus()
}
else -> {
return@OutlinedTextField
}
}
}
}
}
},
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Number,
)
)
val fulled = enteredNumbers.joinToString(separator = "")
if (fulled.length == smsCodeLength) {
smsFulled.invoke(fulled)
}
Spacer(modifier = Modifier.width(8.dp))
}
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/components/OtpView.kt | 2617529654 |
package com.narcis.application.presentation.components
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.center
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
@Composable
fun CircularProgress(
modifier: Modifier = Modifier,
progress: Float = 0f,
progressMAx: Float = 100f,
progressBarColor: Color = Color.Black,
progressBarWidth: Dp = 7.dp,
backgroundProgressBarColor: Color = Color.Gray,
backgroundProgressBarWidth: Dp = 3.dp,
roundBorder:Boolean = false,
startAngle: Float = 0f
) {
Canvas(modifier = modifier.fillMaxWidth()) {
val canvasSize = size.minDimension
val radius = canvasSize / 2 - maxOf(backgroundProgressBarWidth - progressBarWidth).toPx() /2
drawCircle(
color = backgroundProgressBarColor,
radius = radius,
center = size.center,
style = Stroke(width = backgroundProgressBarWidth.toPx())
)
drawArc(
color = progressBarColor,
startAngle = 270f + startAngle,
sweepAngle = (progress / progressMAx) * 360f,
useCenter = false,
topLeft = size.center - Offset(radius, radius),
size = Size(radius*2, radius*2),
style = Stroke(
width = progressBarWidth.toPx(),
cap = if (roundBorder) StrokeCap.Round else StrokeCap.Butt
)
)
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/components/CircularProgress.kt | 836672001 |
package com.narcis.application.presentation.components
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun GradiantButton(modifier: Modifier = Modifier) {
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/components/GradiantButton.kt | 640349922 |
package com.narcis.application.presentation.bottomNavigation
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavDestination
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.narcis.application.presentation.ui.theme.narcisApplicationTheme
import com.google.accompanist.navigation.material.BottomSheetNavigator
import com.google.accompanist.navigation.material.ExperimentalMaterialNavigationApi
@Composable
fun BottomBar(
navController: NavHostController,
currentDestination: NavDestination?,
isDarkTheme: Boolean
) {
NavigationBar(
modifier = Modifier
.height(52.dp)
.shadow(elevation = 16.dp)
.padding(top = 2.dp)
) {
BottomBarDestination.values().asList().forEach {
BottomItem(it, navController, currentDestination, isDarkTheme)
}
}
}
@Composable
fun RowScope.BottomItem(
screen: BottomBarDestination,
navController: NavHostController,
currentDestination: NavDestination?,
isDarkTheme: Boolean
) {
val isCurrentBottomItemSelected = currentDestination?.hierarchy?.any {
it.route == screen.route.route
} ?: false
val (iconSize, offsetY) = Pair(22.dp, 0.dp)
// if (screen == BottomBarDestination.Home) Pair(42.dp, (-8).dp)
// else Pair(22.dp, 0.dp)
var icon: Int = screen.unFilledIcon
screen.apply {
// if (this == BottomBarDestination.Home) {
// if (isDarkTheme) darkModeIcon?.let { icon = it }
// } else {
if (isCurrentBottomItemSelected) {
filledIcon?.let { icon = it }
}
// }
}
NavigationBarItem(
modifier = Modifier.offset(y = -BottomBarItemVerticalOffset),
label = {
screen.title?.let {
Text(
modifier = Modifier.offset(y = BottomBarItemVerticalOffset.times(1.85f)),
text = stringResource(id = screen.title),
style = MaterialTheme.typography.labelSmall,
softWrap = false,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = if (isCurrentBottomItemSelected) 1f else 0.7f)
)
}
},
icon = {
Icon(
painter = painterResource(id = icon),
contentDescription = null,
Modifier
.padding(bottom = 9.dp)
.size(iconSize)
.offset(y = offsetY),
tint = Color.Unspecified,
)
},
colors = NavigationBarItemDefaults.colors(
indicatorColor = MaterialTheme.colorScheme.background,
selectedIconColor = MaterialTheme.colorScheme.secondary,
selectedTextColor = MaterialTheme.colorScheme.secondary
),
selected = isCurrentBottomItemSelected,
onClick = {
screen.route.let {
navController.navigate(it.route) {
launchSingleTop = true
}
}
}
)
}
private val BottomBarItemVerticalOffset = 10.dp
@OptIn(ExperimentalMaterialNavigationApi::class, ExperimentalMaterialApi::class)
@Preview
@Composable
fun DemoBottom() {
narcisApplicationTheme{
val modalSheetState = rememberModalBottomSheetState(
initialValue = ModalBottomSheetValue.Hidden,
skipHalfExpanded = false,
)
val bottomSheetNavigator = remember(modalSheetState) {
BottomSheetNavigator(modalSheetState)
} //rememberBottomSheetNavigator()
val navController = rememberNavController(bottomSheetNavigator)
val currentBackStackEntryAsState by navController.currentBackStackEntryAsState()
val currentDestination = currentBackStackEntryAsState?.destination
BottomBar(navController, currentDestination, isDarkTheme = true)
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/bottomNavigation/BottomBar.kt | 2923678811 |
package com.narcis.application.presentation.bottomNavigation
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import com.narcis.application.presentation.navigation.Navigation
import io.nekohasekai.sagernet.R
enum class BottomBarDestination(
val route: Navigation,
@DrawableRes val unFilledIcon: Int,
@DrawableRes val filledIcon: Int? = null,
@StringRes val title: Int,
@DrawableRes val darkModeIcon: Int? = null
) {
Home(
route = Navigation.MainConnectionScreen,
unFilledIcon = R.drawable.home_icon,
filledIcon = R.drawable.home_icon_filled,
title = R.string.home,
darkModeIcon = R.drawable.home_icon
),
Help(
route = Navigation.HelpScreen,
unFilledIcon = R.drawable.help_icon,
filledIcon = R.drawable.help_icon_filled,
title = R.string.help
),
Profile(
route = Navigation.PurchasePlanScreen,
unFilledIcon = R.drawable.profile_icon,
filledIcon = R.drawable.profile_icon_filled,
title = R.string.profile
)
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/bottomNavigation/BottomNavigationEnums.kt | 4189107764 |
package com.narcis.application.presentation.bottomNavigation
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import io.nekohasekai.sagernet.R
enum class HomeSection(
@StringRes val title: Int,
@DrawableRes val icon: Int,
@DrawableRes val iconSelected: Int,
val route: String,
) {
LANDING(
R.string.home,
icon = R.drawable.home_icon,
iconSelected = R.drawable.home_icon_selected,
route = "home/landing",
),
CONFIG_CUSTOM(
R.string.custom_config,
R.drawable.config_icon,
R.drawable.config_icon_selected,
route = "home/configCustom"
),
PROFILE(
R.string.profile,
R.drawable.profile_icon,
R.drawable.profile_icon_selected,
route = "home/profile"
)
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/bottomNavigation/HomeSection.kt | 3660074149 |
package com.narcis.application.presentation.bottomNavigation
import android.app.Activity
import androidx.activity.compose.BackHandler
import androidx.activity.result.ActivityResultLauncher
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.narcis.application.presentation.navigation.AppNavHost
import com.narcis.application.presentation.navigation.Navigation
import com.narcis.application.presentation.ui.theme.ApplicationTheme
import com.narcis.application.presentation.ui.theme.Blue1
import com.narcis.application.presentation.ui.theme.Violate0
import com.google.accompanist.navigation.material.BottomSheetNavigator
import com.google.accompanist.navigation.material.ExperimentalMaterialNavigationApi
import com.google.accompanist.systemuicontroller.SystemUiController
import io.nekohasekai.sagernet.aidl.TrafficStats
import io.nekohasekai.sagernet.bg.BaseService
@OptIn(
ExperimentalMaterial3Api::class, ExperimentalMaterialNavigationApi::class,
ExperimentalAnimationApi::class, ExperimentalMaterialApi::class
)
@Composable
fun RootScreen(
defaultRoute: String,
connect: ActivityResultLauncher<Void?>,
connectionState: MutableState<BaseService.State>,
trafficState: MutableState<TrafficStats>
) {
val modalSheetState = rememberModalBottomSheetState(
initialValue = ModalBottomSheetValue.Hidden,
skipHalfExpanded = false,
)
val bottomSheetNavigator = remember(modalSheetState) {
BottomSheetNavigator(modalSheetState)
} //rememberBottomSheetNavigator()
val navController = rememberNavController(bottomSheetNavigator)
val currentBackStackEntryAsState by navController.currentBackStackEntryAsState()
val currentDestination = currentBackStackEntryAsState?.destination
val context = LocalContext.current
val isShowBottomBar = true
// when (currentDestination?.route) {
// Navigation.MainConnectionScreen.route, Navigation.PurchasePlanScreen.route, null -> true
// else -> false
// }
val darkMode = isSystemInDarkTheme()
if (currentDestination?.route == Navigation.MainConnectionScreen.route) {
BackHandler {
(context as? Activity)?.finish()
}
}
// SetupSystemUi(rememberSystemUiController(), MaterialTheme.colorScheme.background)
println("the default color is : ${MaterialTheme.colorScheme.background}")
Scaffold(
modifier = Modifier.fillMaxSize(),
topBar = {
},
bottomBar = {
if (defaultRoute != Navigation.LandingScreen.route) {
NavigationBar(
containerColor = ApplicationTheme.colors.uiBackground
) {
BottomBarDestination.values().forEach { item ->
NavigationBarItem(
icon = {
Icon(
painterResource(id = item.unFilledIcon),
contentDescription = stringResource(id = item.title)
)
},
label = { androidx.compose.material3.Text(stringResource(id = item.title)) },
selected = item.route == currentDestination,
colors = NavigationBarItemDefaults.colors(
selectedIconColor = Blue1,
indicatorColor = Violate0
),
onClick = {
if (item.route != currentDestination) {
println(" the rout is ${item.route.route}")
// navController.popAll()
navController.navigate(item.route.route)
}
}
)
}
}
}
}
) {
Surface(modifier = Modifier.padding(it)) {
// Text(text = "hey hey")
AppNavHost(
defaultRoute = defaultRoute,
connect = connect,
connectionState = connectionState,
trafficState = trafficState,
navController = navController
)
}
}
}
@Composable
fun SetupSystemUi(
systemUiController: SystemUiController,
systemBarColor: Color
) {
SideEffect {
systemUiController.setSystemBarsColor(color = systemBarColor)
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/bottomNavigation/RootScreen.kt | 144473594 |
package com.narcis.application.presentation.mainConnection
import androidx.activity.result.ActivityResultLauncher
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.narcis.application.presentation.mainConnection.components.ConnectionItem
import com.narcis.application.presentation.ui.theme.narcisApplicationTheme
import com.narcis.application.presentation.ui.theme.Purple40
import com.narcis.application.presentation.viewModel.DefaultConfigViewModel
import com.narcis.application.presentation.viewModel.event.ProxyEvent
import com.narcis.application.presentation.viewModel.model.DefaultConfig
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import io.nekohasekai.sagernet.aidl.TrafficStats
import io.nekohasekai.sagernet.bg.BaseService
private var checked = false
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainConnectionScreen(
navControle: NavController?,
configViewModel: DefaultConfigViewModel = hiltViewModel(),
connect: ActivityResultLauncher<Void?>,
state: MutableState<BaseService.State>,
trafficState: MutableState<TrafficStats>
) {
val localConnect = connect
val configState by configViewModel.configState.collectAsState()
val currentProxy = remember {
mutableStateOf(DefaultConfig())
}
val context = LocalContext.current
val swipeRefreshState = rememberSwipeRefreshState(
isRefreshing = configState.isRefreshing
)
var loadingVisibility by remember { mutableStateOf(false) }
var isConfigFetched by remember { mutableStateOf(false) }
var configs by remember { mutableStateOf(listOf(DefaultConfig())) }
LaunchedEffect(key1 = configState) {
if (configState.isLoading) {
loadingVisibility = true
} else if (configState.configs!!.isNotEmpty()) {
loadingVisibility = false
configs = configState.configs!!
isConfigFetched = true
}
}
Column {
Backdrop(
modifier = Modifier,
onClick = {
configViewModel.onClickConnect(localConnect, context = context)
},
context = context,
state = state,
currentProxy,
trafficState = trafficState,
isConfigEmpty = configs.first().address == ""
)
Spacer(modifier = Modifier.height(16.dp))
if (loadingVisibility) {
CircularProgressIndicator(color = Purple40)
}
if (isConfigFetched) {
SwipeRefresh(
state = swipeRefreshState,
onRefresh = {
configViewModel.onEvent(ProxyEvent.triggerRefresh)
},
) {
LazyColumn {
if (!loadingVisibility) {
items(configs.size) { i ->
val config = configs[i]
ConnectionItem(
config, onClick = {
currentProxy.value = config
configViewModel.onEvent(
ProxyEvent.ConfigEvent(
defaultConfig = currentProxy.value,
context
)
)
//auto connect and disconnet
configViewModel.onClickConnect(localConnect, context)
},
totalSize = configs.size
)
}
}
}
}
}
}
}
@Preview
@Composable
private fun Preview() {
narcisApplicationTheme {
// MainConnectionScreen(null)
}
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/mainConnection/MainConnectionScreen.kt | 2513584021 |
package com.narcis.application.presentation.mainConnection.components
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.EaseOut
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import io.nekohasekai.sagernet.R
import com.narcis.application.presentation.ui.theme.Neutral1
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
@Composable
fun DownloadButton(
onClick: () -> Unit,
strokeColor: Color,
strokeSize: Dp,
progress: Float,
modifier: Modifier = Modifier
) {
val colorScheme = MaterialTheme.colorScheme
val scope = rememberCoroutineScope()
var isAnimating by remember { mutableStateOf(false) }
val tapAnimation = remember { Animatable(1f) }
Box(
contentAlignment = Alignment.Center,
modifier = modifier
.fillMaxWidth()
.aspectRatio(1f)
.pointerInput(isAnimating) {
detectTapGestures(
onPress = {
scope.launch {
tapAnimation.animateTo(0.8f)
}
tryAwaitRelease()
scope.launch {
tapAnimation.animateTo(1f)
}
},
onTap = {
isAnimating = !isAnimating
onClick()
},
)
}
.graphicsLayer {
alpha = tapAnimation.value
scaleX = tapAnimation.value
scaleY = tapAnimation.value
},
) {
RoundCircularProgressIndicator(
progress = 1f,
strokeWidth = strokeSize * 8,
color = Color.Transparent,
modifier = Modifier.fillMaxSize()
)
RoundCircularProgressIndicator(
progress = progress,
strokeWidth = strokeSize * 6,
color = strokeColor,
modifier = Modifier.fillMaxSize()
)
val animationOneProgress = remember { Animatable(0f) }
val animationTwoProgress = remember { Animatable(0f) }
val animationThreeProgress = remember { Animatable(0f) }
val animationFourProgress = remember { Animatable(0f) }
val animationFiveProgress = remember { Animatable(0f) }
val animationSixProgress = remember { Animatable(0f) }
val animationSevenProgress = remember { Animatable(0f) }
val animationDuration = 200
LaunchedEffect(key1 = isAnimating) {
if (!isAnimating) {
animationOneProgress.snapTo(0f)
animationTwoProgress.snapTo(0f)
animationThreeProgress.snapTo(0f)
animationFourProgress.snapTo(0f)
animationFiveProgress.snapTo(0f)
animationSixProgress.snapTo(0f)
animationSevenProgress.snapTo(0f)
return@LaunchedEffect
}
launch {
animationOneProgress.animateTo(
1f,
animationSpec = tween(
durationMillis = animationDuration,
delayMillis = 0,
easing = LinearEasing
)
)
animationTwoProgress.animateTo(
1f,
animationSpec = tween(
durationMillis = animationDuration,
delayMillis = 0,
easing = CubicBezierEasing(0.34f, 1.8f, 0.64f, 1f),
)
)
}
launch {
animationThreeProgress.animateTo(
1f,
animationSpec = tween(
durationMillis = animationDuration,
delayMillis = (animationDuration * 1.5f).roundToInt(),
easing = EaseOut
)
)
animationFourProgress.animateTo(
1f,
animationSpec = tween(
durationMillis = 600,
delayMillis = 0,
easing = LinearEasing
)
)
val spec = infiniteRepeatable<Float>(
tween(
durationMillis = 600,
delayMillis = 0,
easing = LinearEasing
),
RepeatMode.Restart
)
animationFiveProgress.animateTo(
1f,
spec
)
}
}
LaunchedEffect(key1 = progress, key2 = animationFiveProgress.value) {
if (progress != 1f) return@LaunchedEffect
if (animationFiveProgress.value >= 0.9f) {
animationFiveProgress.snapTo(0f)
}
if (animationFiveProgress.value == 0f) {
animationSixProgress.animateTo(
1f,
animationSpec = tween(
durationMillis = 600,
delayMillis = 0,
easing = LinearEasing
)
)
animationSevenProgress.animateTo(
1f,
animationSpec = tween(
durationMillis = 600,
delayMillis = 0,
easing = LinearEasing
)
)
}
}
val downloadPath = remember {
Path()
}
Image(
painter = painterResource(id = R.drawable.onoff_icon),
contentDescription = "connect - disconnect icon"
)
Canvas(modifier = Modifier.fillMaxSize(fraction = 0.5f)) {
drawRect(color = Neutral1.copy(alpha = 0.2f))
downloadPath.reset()
val downloadLineHeight = size.height * (1f - animationOneProgress.value)
val downloadLineY =
(size.height - downloadLineHeight) / 2f * (1f - animationThreeProgress.value) - animationThreeProgress.value * (size.height * 1 / 2f - 4.dp.toPx())
downloadPath.moveTo(size.width / 2f, downloadLineY)
downloadPath.lineTo(size.width / 2f, downloadLineY)
drawPath(
color = strokeColor,
path = downloadPath,
style = Stroke(
width = (strokeSize * 2).toPx(),
cap = StrokeCap.Round,
),
)
}
// Box (
// contentAlignment = Alignment.TopCenter,
// modifier = Modifier.align(Alignment.BottomCenter)
// .fillMaxHeight(
// fraction = 0.2f + (0.1f * animationFourProgress.value) - (0.1f * animationSevenProgress.value)
// )
// ) {
//
// }
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/mainConnection/components/DownloadButton.kt | 79458533 |
package com.narcis.application.presentation.mainConnection.components
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class PingViewModel @Inject constructor(): ViewModel() {
private var _ping = MutableStateFlow(mutableListOf(""))
val ping: StateFlow<MutableList<String>> = _ping
private var firstTime = false
fun startPing(totalSize: Int) {
val tempList = mutableListOf<String>()
if (!firstTime) {
repeat(totalSize + 1) {
tempList.add("ping_four_bars")
}
_ping.value = tempList
firstTime = true
}
viewModelScope.launch(Dispatchers.IO) {
getNewBars(totalSize = totalSize)
}
}
private suspend fun getNewBars(totalSize : Int) {
delay(10_000)
val barsSample = listOf(
"three",
"three",
"three",
"four",
"four",
"four",
"one",
"two",
"three",
"three",
"three",
"four",
"four",
"four"
)
val newPngs = mutableListOf<String>("")
for (i in 0 until totalSize+1) {
newPngs.add("ping_${barsSample.random()}_bars")
}
_ping.value = newPngs
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/mainConnection/components/PingViewModel.kt | 1832266178 |
package com.narcis.application.presentation.mainConnection.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowRight
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.SubcomposeAsyncImage
import coil.decode.SvgDecoder
import coil.request.ImageRequest
import com.narcis.application.presentation.ui.theme.narcisApplicationTheme
import com.narcis.application.presentation.ui.theme.ApplicationTheme
import com.narcis.application.presentation.ui.theme.Ocean4
import com.narcis.application.presentation.utiles.countryFlagUrl
import com.narcis.application.presentation.viewModel.model.DefaultConfig
import io.nekohasekai.sagernet.R
@Composable
fun ConnectionItem(defaultConfig: DefaultConfig? = null,
onClick: () -> Unit,
totalSize: Int,
pingViewModel: PingViewModel = hiltViewModel()) {
val context = LocalContext.current
val ping by pingViewModel.ping.collectAsState()
val pingDrawabl = remember {
mutableIntStateOf(R.drawable.ping_four_bars)
}
val iconResourceMap = mapOf(
"ping_one_bars" to R.drawable.ping_one_bars,
"ping_two_bars" to R.drawable.ping_two_bars,
"ping_three_bars" to R.drawable.ping_three_bars,
"ping_four_bars" to R.drawable.ping_four_bars
// Add mappings for all the icons you have
)
pingViewModel.startPing(totalSize)
LaunchedEffect(key1 = ping) {
pingDrawabl.intValue = iconResourceMap[defaultConfig?.id?.toInt()?.let { ping[it] }]!!
}
Row(
modifier = Modifier
.clip(RoundedCornerShape(50))
.fillMaxWidth()
.clickable {
onClick()
},
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(modifier = Modifier.padding(start = 8.dp)) {
// Image(
// painter = painterResource(id = R.drawable.us_flag),
// contentDescription = "icon flag",
// modifier = Modifier.clip(CircleShape)
// )
val parts = defaultConfig?.flag?.split('/')
val countryCode = parts?.get(2)
val svgImageUrl = countryFlagUrl(countryCode)
SubcomposeAsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(svgImageUrl)
.decoderFactory(SvgDecoder.Factory())
.build(),
contentDescription = "flag icon image",
modifier = Modifier
.clip(CircleShape)
.size(32.dp)
.aspectRatio(1f),
contentScale = ContentScale.Crop,
loading = {
CircularProgressIndicator()
}
)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(start = 12.dp)
) {
Text(
text = defaultConfig?.country ?: "",
color = ApplicationTheme.colors.textPrimary
)
Row {
Image(
painter = painterResource(id = pingDrawabl.intValue),
contentDescription = ""
)
Text(
text = defaultConfig?.protocol ?: "",
modifier = Modifier.padding(start = 32.dp),
color = ApplicationTheme.colors.textSecondry
)
}
}
}
Button(
onClick = { /*TODO*/ },
colors = ButtonDefaults.elevatedButtonColors(
containerColor = ApplicationTheme.colors.iconInteractiveInactive,
contentColor = ApplicationTheme.colors.iconInteractiveInactive
)
) {
Row {
Text(text = "Change", color = Ocean4)
Icon(
imageVector = Icons.Default.KeyboardArrowRight,
contentDescription = "change",
tint = Ocean4
)
}
}
}
}
@Preview
@Composable
private fun Preview() {
narcisApplicationTheme {
val df = DefaultConfig(
address = "172.86.76.146",
port = 443,
password = "3dc90e78b18c5e9c6f382dd3b42891d3",
security = "tls",
fingerprint = "chrome",
alpn = "http/1.1",
sni = "zire.ml",
type = "TROJAN",
country = "Luxembourg",
flag = "proxy/flag/lu",
url = "trojan://[email protected]:443?security=tls&alpn=http/1.1&headerType=none&fp=chrome&type=tcp&sni=zire.ml",
protocol = "Trojan"
)
ConnectionItem(onClick = {}, totalSize = 1)
}
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/mainConnection/components/ConnectionItem.kt | 3803153840 |
package com.narcis.application.presentation.mainConnection.components
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.LayoutDirection
class BottomArcShape(private val arcHeight: Float) : Shape {
override fun createOutline(
size: Size,
layoutDirection: LayoutDirection,
density: Density
): Outline {
val path = Path().apply {
moveTo(size.width, 0f)
lineTo(size.width, size.height)
val arcOffset = arcHeight / 10
val rect = Rect(
left = 0f - arcOffset,
top = size.height - arcHeight,
right = size.width + arcOffset,
bottom = size.height
)
arcTo(rect, 0f, 180f, false)
lineTo(0f, 0f)
close()
}
return Outline.Generic(path)
}
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/mainConnection/components/BottomArcShape.kt | 132774710 |
package com.narcis.application.presentation.mainConnection.components
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.progressSemantics
import androidx.compose.material.ProgressIndicatorDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.narcis.application.presentation.ui.theme.Ocean7
@Composable
fun RoundCircularProgressIndicator(
progress: Float,
modifier: Modifier = Modifier,
color: Color = Ocean7,
strokeWidth: Dp = ProgressIndicatorDefaults.StrokeWidth
) {
val stroke = with(LocalDensity.current) {
Stroke(width = strokeWidth.toPx(), cap = StrokeCap.Round)
}
Canvas(modifier = modifier
.progressSemantics(progress)
.size(30.dp)) {
val startAngle = 270f
val sweep = progress * 360f
}
}
private fun DrawScope.drawCircularIndicator(
startAngle: Float,
sweep: Float,
color: Color,
stroke: Stroke
) {
val diameterOffset = stroke.width / 2
val arcDimen = size.width - 2 * diameterOffset
drawArc(
color = color,
startAngle = startAngle,
sweepAngle = sweep,
useCenter = false,
topLeft = Offset(diameterOffset, diameterOffset),
size = Size(arcDimen, arcDimen),
style = stroke
)
} | Ving-Vpn/app/src/main/java/com/narcis/application/presentation/mainConnection/components/RoundCircularProgressIndicator.kt | 1221749162 |
package com.narcis.application.presentation.mainConnection
import android.content.Context
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.Card
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.narcis.application.presentation.components.VpnConnectButton
import com.narcis.application.presentation.mainConnection.components.BottomArcShape
import com.narcis.application.presentation.ui.theme.narcisApplicationTheme
import com.narcis.application.presentation.ui.theme.ApplicationTheme
import com.narcis.application.presentation.viewModel.model.DefaultConfig
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.aidl.TrafficStats
import io.nekohasekai.sagernet.bg.BaseService
@Composable
fun Backdrop(
modifier: Modifier,
onClick: () -> Unit,
context: Context,
state: MutableState<BaseService.State>,
currentProxy: MutableState<DefaultConfig>,
trafficState: MutableState<TrafficStats>,
isConfigEmpty: Boolean
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Card(
elevation = 16.dp,
shape = BottomArcShape(arcHeight = (120.dp).dpToPx()),
modifier = modifier
.height(480.dp)
.background(
color = Color.Transparent
)
) {
Image(
painter = painterResource(id = R.drawable.map_backdrop),
contentDescription = "backdrop photo of a world map",
// contentScale = ContentScale.Crop,
modifier = modifier
.fillMaxWidth()
.background(brush = Brush.verticalGradient(ApplicationTheme.colors.welcomeGradiant))
)
Box(
modifier = Modifier
.background(color = Color.Transparent)
.wrapContentSize()
.aspectRatio(1f),
contentAlignment = Alignment.Center
) {
VpnConnectButton(onClick = onClick, state = state, trafficState = trafficState, isConfigEmpty = isConfigEmpty)
}
}
}
}
@Composable
fun Dp.dpToPx() = with(LocalDensity.current) { [email protected]() }
@Preview
@Composable
private fun Preview() {
narcisApplicationTheme {
// MainConnectionScreen2()
}
}
| Ving-Vpn/app/src/main/java/com/narcis/application/presentation/mainConnection/Backdrop.kt | 2999709096 |
/*******************************************************************************
* *
* Copyright (C) 2019 by Max Lv <[email protected]> *
* Copyright (C) 2019 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 com.github.shadowsocks.net
import android.net.LocalSocket
import com.narcis.application.presentation.connection.Logs
import kotlinx.coroutines.*
import java.io.File
abstract class ConcurrentLocalSocketListener(name: String, socketFile: File) :
LocalSocketListener(name, socketFile),
CoroutineScope {
override val coroutineContext =
Dispatchers.IO + SupervisorJob() + CoroutineExceptionHandler { _, t -> Logs.w(t) }
override fun accept(socket: LocalSocket) {
launch { super.accept(socket) }
}
override fun shutdown(scope: CoroutineScope) {
running = false
cancel()
super.shutdown(scope)
coroutineContext[Job]!!.also { job -> scope.launch { job.join() } }
}
}
| Ving-Vpn/app/src/main/java/com/github/shadowsocks/net/ConcurrentLocalSocketListener.kt | 749286758 |
/*******************************************************************************
* *
* 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 com.github.shadowsocks.net
import android.annotation.SuppressLint
import android.net.LocalServerSocket
import android.net.LocalSocket
import android.net.LocalSocketAddress
import android.system.ErrnoException
import android.system.Os
import android.system.OsConstants
import com.narcis.application.presentation.connection.Logs
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.onFailure
import kotlinx.coroutines.channels.trySendBlocking
import kotlinx.coroutines.launch
import java.io.File
import java.io.IOException
abstract class LocalSocketListener(name: String, socketFile: File) : Thread(name) {
private val localSocket = LocalSocket().apply {
socketFile.delete() // It's a must-have to close and reuse previous local socket.
bind(LocalSocketAddress(socketFile.absolutePath, LocalSocketAddress.Namespace.FILESYSTEM))
}
private val serverSocket = LocalServerSocket(localSocket.fileDescriptor)
private val closeChannel = Channel<Unit>(1)
@Volatile
protected var running = true
/**
* Inherited class do not need to close input/output streams as they will be closed automatically.
*/
protected open fun accept(socket: LocalSocket) = socket.use { acceptInternal(socket) }
protected abstract fun acceptInternal(socket: LocalSocket)
final override fun run() {
localSocket.use {
while (running) {
try {
accept(serverSocket.accept())
} catch (e: IOException) {
if (running) Logs.w(e)
continue
}
}
}
closeChannel.trySendBlocking(Unit).onFailure { throw it!! }
}
@SuppressLint("NewApi")
open fun shutdown(scope: CoroutineScope) {
running = false
localSocket.fileDescriptor?.apply {
// see also: https://issuetracker.google.com/issues/36945762#comment15
if (valid()) try {
Os.shutdown(this, OsConstants.SHUT_RDWR)
} catch (e: ErrnoException) {
// suppress fd inactive or already closed
if (e.errno != OsConstants.EBADF && e.errno != OsConstants.ENOTCONN) throw e.rethrowAsSocketException()
}
}
scope.launch { closeChannel.receive() }
}
}
| Ving-Vpn/app/src/main/java/com/github/shadowsocks/net/LocalSocketListener.kt | 1902527043 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 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 com.github.shadowsocks.plugin
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.ContentResolver
import android.content.Intent
import android.content.pm.ComponentInfo
import android.content.pm.PackageManager
import android.content.pm.ProviderInfo
import android.content.pm.Signature
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.system.Os
import android.util.Base64
import android.widget.Toast
import androidx.core.os.bundleOf
import io.nekohasekai.sagernet.R
import com.narcis.application.presentation.connection.Logs
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.bg.BaseService
import io.nekohasekai.sagernet.ktx.listenForPackageChanges
import io.nekohasekai.sagernet.ktx.signaturesCompat
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)
}
/**
* Trusted signatures by the app. Third-party fork should add their public key to their fork if the developer wishes
* to publish or has published plugins for this app. You can obtain your public key by executing:
*
* $ keytool -export -alias key-alias -keystore /path/to/keystore.jks -rfc
*
* If you don't plan to publish any plugin but is developing/has developed some, it's not necessary to add your
* public key yet since it will also automatically trust packages signed by the same signatures, e.g. debug keys.
*/
val trustedSignatures by lazy {
SagerNet.packageInfo.signaturesCompat.toSet() +
Signature(
Base64.decode( // @Mygod
"""
|MIIDWzCCAkOgAwIBAgIEUzfv8DANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJD
|TjEOMAwGA1UECBMFTXlnb2QxDjAMBgNVBAcTBU15Z29kMQ4wDAYDVQQKEwVNeWdv
|ZDEOMAwGA1UECxMFTXlnb2QxDjAMBgNVBAMTBU15Z29kMCAXDTE0MDUwMjA5MjQx
|OVoYDzMwMTMwOTAyMDkyNDE5WjBdMQswCQYDVQQGEwJDTjEOMAwGA1UECBMFTXln
|b2QxDjAMBgNVBAcTBU15Z29kMQ4wDAYDVQQKEwVNeWdvZDEOMAwGA1UECxMFTXln
|b2QxDjAMBgNVBAMTBU15Z29kMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
|AQEAjm5ikHoP3w6zavvZU5bRo6Birz41JL/nZidpdww21q/G9APA+IiJMUeeocy0
|L7/QY8MQZABVwNq79LXYWJBcmmFXM9xBPgDqQP4uh9JsvazCI9bvDiMn92mz9HiS
|Sg9V4KGg0AcY0r230KIFo7hz+2QBp1gwAAE97myBfA3pi3IzJM2kWsh4LWkKQMfL
|M6KDhpb4mdDQnHlgi4JWe3SYbLtpB6whnTqjHaOzvyiLspx1tmrb0KVxssry9KoX
|YQzl56scfE/QJX0jJ5qYmNAYRCb4PibMuNSGB2NObDabSOMAdT4JLueOcHZ/x9tw
|agGQ9UdymVZYzf8uqc+29ppKdQIDAQABoyEwHzAdBgNVHQ4EFgQUBK4uJ0cqmnho
|6I72VmOVQMvVCXowDQYJKoZIhvcNAQELBQADggEBABZQ3yNESQdgNJg+NRIcpF9l
|YSKZvrBZ51gyrC7/2ZKMpRIyXruUOIrjuTR5eaONs1E4HI/uA3xG1eeW2pjPxDnO
|zgM4t7EPH6QbzibihoHw1MAB/mzECzY8r11PBhDQlst0a2hp+zUNR8CLbpmPPqTY
|RSo6EooQ7+NBejOXysqIF1q0BJs8Y5s/CaTOmgbL7uPCkzArB6SS/hzXgDk5gw6v
|wkGeOtzcj1DlbUTvt1s5GlnwBTGUmkbLx+YUje+n+IBgMbohLUDYBtUHylRVgMsc
|1WS67kDqeJiiQZvrxvyW6CZZ/MIGI+uAkkj3DqJpaZirkwPgvpcOIrjZy0uFvQM=
""", Base64.DEFAULT)) +
Signature(
Base64.decode( // @madeye
"""
|MIICQzCCAaygAwIBAgIETV9OhjANBgkqhkiG9w0BAQUFADBmMQswCQYDVQQGEwJjbjERMA8GA1UE
|CBMIU2hhbmdoYWkxDzANBgNVBAcTBlB1ZG9uZzEUMBIGA1UEChMLRnVkYW4gVW5pdi4xDDAKBgNV
|BAsTA1BQSTEPMA0GA1UEAxMGTWF4IEx2MB4XDTExMDIxOTA1MDA1NFoXDTM2MDIxMzA1MDA1NFow
|ZjELMAkGA1UEBhMCY24xETAPBgNVBAgTCFNoYW5naGFpMQ8wDQYDVQQHEwZQdWRvbmcxFDASBgNV
|BAoTC0Z1ZGFuIFVuaXYuMQwwCgYDVQQLEwNQUEkxDzANBgNVBAMTBk1heCBMdjCBnzANBgkqhkiG
|9w0BAQEFAAOBjQAwgYkCgYEAq6lA8LqdeEI+es9SDX85aIcx8LoL3cc//iRRi+2mFIWvzvZ+bLKr
|4Wd0rhu/iU7OeMm2GvySFyw/GdMh1bqh5nNPLiRxAlZxpaZxLOdRcxuvh5Nc5yzjM+QBv8ECmuvu
|AOvvT3UDmA0AMQjZqSCmxWIxc/cClZ/0DubreBo2st0CAwEAATANBgkqhkiG9w0BAQUFAAOBgQAQ
|Iqonxpwk2ay+Dm5RhFfZyG9SatM/JNFx2OdErU16WzuK1ItotXGVJaxCZv3u/tTwM5aaMACGED5n
|AvHaDGCWynY74oDAopM4liF/yLe1wmZDu6Zo/7fXrH+T03LBgj2fcIkUfN1AA4dvnBo8XWAm9VrI
|1iNuLIssdhDz3IL9Yg==
""", Base64.DEFAULT))
}
private var receiver: BroadcastReceiver? = null
private var cachedPlugins: PluginList? = null
private var cachedPluginsSkipInternal: PluginList? = null
fun fetchPlugins(skipInternal: Boolean) = synchronized(this) {
if (receiver == null) receiver = SagerNet.application.listenForPackageChanges {
synchronized(this) {
receiver = null
cachedPlugins = null
cachedPluginsSkipInternal = null
}
}
if (skipInternal) {
if (cachedPlugins == null) cachedPlugins = PluginList(skipInternal)
cachedPlugins!!
} else {
if (cachedPluginsSkipInternal == null) cachedPluginsSkipInternal = PluginList(skipInternal)
cachedPluginsSkipInternal!!
}
}
private fun buildUri(id: String) = Uri.Builder()
.scheme(PluginContract.SCHEME)
.authority(PluginContract.AUTHORITY)
.path("/$id")
.build()
fun buildIntent(id: String, action: String): Intent = Intent(action, buildUri(id))
data class InitResult(
val path: String,
val options: PluginOptions,
val isV2: Boolean = false,
)
// the following parts are meant to be used by :bg
@Throws(Throwable::class)
fun init(configuration: PluginConfiguration): InitResult? {
if (configuration.selected.isEmpty()) return null
var throwable: Throwable? = null
try {
val result = initNative(configuration)
if (result != null) return result
} catch (t: Throwable) {
if (throwable == null) throwable = t else Logs.w(t)
}
// add other plugin types here
throw throwable ?: PluginNotFoundException(configuration.selected)
}
private fun initNative(configuration: PluginConfiguration): InitResult? {
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 providers = SagerNet.application.packageManager.queryIntentContentProviders(
Intent(PluginContract.ACTION_NATIVE_PLUGIN, buildUri(configuration.selected)), flags)
.filter { it.providerInfo.exported }
if (providers.isEmpty()) return null
if (providers.size > 1) {
val message = "Conflicting plugins found from: ${providers.joinToString { it.providerInfo.packageName }}"
Toast.makeText(SagerNet.application, message, Toast.LENGTH_LONG).show()
throw IllegalStateException(message)
}
val provider = providers.single().providerInfo
val options = configuration.getOptions { provider.loadString(PluginContract.METADATA_KEY_DEFAULT_CONFIG) }
val isV2 = provider.applicationInfo.metaData?.getString(PluginContract.METADATA_KEY_VERSION)
?.substringBefore('.')?.toIntOrNull() ?: 0 >= 2
var failure: Throwable? = null
try {
initNativeFaster(provider)?.also { return InitResult(it, options, isV2) }
} catch (t: Throwable) {
Logs.w("Initializing native plugin faster mode failed")
failure = t
}
val uri = Uri.Builder().apply {
scheme(ContentResolver.SCHEME_CONTENT)
authority(provider.authority)
}.build()
try {
return initNativeFast(SagerNet.application.contentResolver, options, uri)?.let { InitResult(it, options, isV2) }
} catch (t: Throwable) {
Logs.w("Initializing native plugin fast mode failed")
failure?.also { t.addSuppressed(it) }
failure = t
}
try {
return initNativeSlow(SagerNet.application.contentResolver, options, uri)?.let { InitResult(it, options, isV2) }
} catch (t: Throwable) {
failure?.also { t.addSuppressed(it) }
throw t
}
}
private fun initNativeFaster(provider: ProviderInfo): String? {
return provider.loadString(PluginContract.METADATA_KEY_EXECUTABLE_PATH)?.let { relativePath ->
File(provider.applicationInfo.nativeLibraryDir).resolve(relativePath).apply {
check(canExecute())
}.absolutePath
}
}
private fun initNativeFast(cr: ContentResolver, options: PluginOptions, uri: Uri): String? {
return cr.call(uri, PluginContract.METHOD_GET_EXECUTABLE, null,
bundleOf(PluginContract.EXTRA_OPTIONS to options.id)
)?.getString(PluginContract.EXTRA_ENTRY)?.also {
check(File(it).canExecute())
}
}
@SuppressLint("Recycle")
private fun initNativeSlow(cr: ContentResolver, options: PluginOptions, uri: Uri): String? {
var initialized = false
fun entryNotFound(): Nothing = throw IndexOutOfBoundsException("Plugin entry binary not found")
val pluginDir = File(SagerNet.deviceStorage.noBackupFilesDir, "plugin")
(cr.query(uri, arrayOf(PluginContract.COLUMN_PATH, PluginContract.COLUMN_MODE), null, null, null)
?: return null).use { cursor ->
if (!cursor.moveToFirst()) entryNotFound()
pluginDir.deleteRecursively()
if (!pluginDir.mkdirs()) throw FileNotFoundException("Unable to create plugin directory")
val pluginDirPath = pluginDir.absolutePath + '/'
do {
val path = cursor.getString(0)
val file = File(pluginDir, path)
check(file.absolutePath.startsWith(pluginDirPath))
cr.openInputStream(uri.buildUpon().path(path).build())!!.use { inStream ->
file.outputStream().use { outStream -> inStream.copyTo(outStream) }
}
Os.chmod(file.absolutePath, when (cursor.getType(1)) {
Cursor.FIELD_TYPE_INTEGER -> cursor.getInt(1)
Cursor.FIELD_TYPE_STRING -> cursor.getString(1).toInt(8)
else -> throw IllegalArgumentException("File mode should be of type int")
})
if (path == options.id) initialized = true
} while (cursor.moveToNext())
}
if (!initialized) entryNotFound()
return File(pluginDir, options.id).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}")
}
}
| Ving-Vpn/app/src/main/java/com/github/shadowsocks/plugin/PluginManager.kt | 886454568 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 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 com.github.shadowsocks.plugin
import android.graphics.drawable.Drawable
abstract class Plugin {
abstract val id: String
open val idAliases get() = emptyArray<String>()
abstract val label: CharSequence
open val icon: Drawable? get() = null
open val defaultConfig: String? get() = null
open val packageName: String get() = ""
open val trusted: Boolean get() = true
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
return id == (other as Plugin).id
}
override fun hashCode() = id.hashCode()
}
| Ving-Vpn/app/src/main/java/com/github/shadowsocks/plugin/Plugin.kt | 3539352950 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 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 com.github.shadowsocks.plugin
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.SagerNet
object NoPlugin : Plugin() {
override val id: String get() = ""
override val label: CharSequence get() = SagerNet.application.getText(R.string.plugin_disabled)
}
| Ving-Vpn/app/src/main/java/com/github/shadowsocks/plugin/NoPlugin.kt | 1358626868 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 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/>. *
* *
******************************************************************************/
@file:JvmName("Utils")
package com.github.shadowsocks.plugin
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
class Empty : Parcelable | Ving-Vpn/app/src/main/java/com/github/shadowsocks/plugin/Utils.kt | 1484114510 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 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 com.github.shadowsocks.plugin
import android.content.pm.ComponentInfo
import android.content.pm.ResolveInfo
import android.graphics.drawable.Drawable
import com.github.shadowsocks.plugin.PluginManager.loadString
import io.nekohasekai.sagernet.SagerNet
import io.nekohasekai.sagernet.ktx.signaturesCompat
abstract class ResolvedPlugin(protected val resolveInfo: ResolveInfo) : Plugin() {
protected abstract val componentInfo: ComponentInfo
override val id by lazy { componentInfo.loadString(PluginContract.METADATA_KEY_ID)!! }
override val idAliases: Array<String> by lazy {
when (val value = componentInfo.metaData.get(PluginContract.METADATA_KEY_ID_ALIASES)) {
is String -> arrayOf(value)
is Int -> SagerNet.application.packageManager.getResourcesForApplication(componentInfo.applicationInfo)
.run {
when (getResourceTypeName(value)) {
"string" -> arrayOf(getString(value))
else -> getStringArray(value)
}
}
null -> emptyArray()
else -> error("unknown type for plugin meta-data idAliases")
}
}
override val label: CharSequence get() = resolveInfo.loadLabel(SagerNet.application.packageManager)
override val icon: Drawable get() = resolveInfo.loadIcon(SagerNet.application.packageManager)
override val defaultConfig by lazy { componentInfo.loadString(PluginContract.METADATA_KEY_DEFAULT_CONFIG) }
override val packageName: String get() = componentInfo.packageName
override val trusted by lazy {
SagerNet.application.getPackageInfo(packageName).signaturesCompat.any(PluginManager.trustedSignatures::contains)
}
}
| Ving-Vpn/app/src/main/java/com/github/shadowsocks/plugin/ResolvedPlugin.kt | 1819910211 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 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 com.github.shadowsocks.plugin
import android.content.pm.ResolveInfo
class NativePlugin(resolveInfo: ResolveInfo) : ResolvedPlugin(resolveInfo) {
init {
check(resolveInfo.providerInfo != null)
}
override val componentInfo get() = resolveInfo.providerInfo!!
}
| Ving-Vpn/app/src/main/java/com/github/shadowsocks/plugin/NativePlugin.kt | 207812136 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 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 com.github.shadowsocks.plugin
class InternalPlugin(override val id: String, override val label: CharSequence) : Plugin() {
companion object {
val SIMPLE_OBFS = InternalPlugin("obfs-local", "Simple Obfs (Internal)")
val V2RAY_PLUGIN = InternalPlugin("v2ray-plugin", "V2Ray Plugin (Internal)")
}
} | Ving-Vpn/app/src/main/java/com/github/shadowsocks/plugin/InternalPlugin.kt | 1038365671 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[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 com.github.shadowsocks.plugin
import android.database.sqlite.SQLiteCantOpenDatabaseException
import com.narcis.application.presentation.connection.Logs
import com.narcis.application.presentation.connection.applyDefaultValues
import io.nekohasekai.sagernet.R
import io.nekohasekai.sagernet.aidl.TrafficStats
import io.nekohasekai.sagernet.database.DataStore
import io.nekohasekai.sagernet.database.GroupManager
import io.nekohasekai.sagernet.database.ProxyEntity
import io.nekohasekai.sagernet.database.RuleEntity
import io.nekohasekai.sagernet.database.SagerDatabase
import io.nekohasekai.sagernet.ftm.AbstractBean
import io.nekohasekai.sagernet.ktx.app
import java.io.IOException
import java.sql.SQLException
import java.util.Locale
object ProfileManager {
interface Listener {
suspend fun onAdd(profile: ProxyEntity)
suspend fun onUpdated(profileId: Long, trafficStats: TrafficStats)
suspend fun onUpdated(profile: ProxyEntity)
suspend fun onRemoved(groupId: Long, profileId: Long)
}
interface RuleListener {
suspend fun onAdd(rule: RuleEntity)
suspend fun onUpdated(rule: RuleEntity)
suspend fun onRemoved(ruleId: Long)
suspend fun onCleared()
}
private val listeners = ArrayList<Listener>()
private val ruleListeners = ArrayList<RuleListener>()
suspend fun iterator(what: suspend Listener.() -> Unit) {
synchronized(listeners) {
listeners.toList()
}.forEach { listener ->
what(listener)
}
}
suspend fun ruleIterator(what: suspend RuleListener.() -> Unit) {
val ruleListeners = synchronized(ruleListeners) {
ruleListeners.toList()
}
for (listener in ruleListeners) {
what(listener)
}
}
fun addListener(listener: Listener) {
synchronized(listeners) {
listeners.add(listener)
}
}
fun removeListener(listener: Listener) {
synchronized(listeners) {
listeners.remove(listener)
}
}
fun addListener(listener: RuleListener) {
synchronized(ruleListeners) {
ruleListeners.add(listener)
}
}
fun removeListener(listener: RuleListener) {
synchronized(ruleListeners) {
ruleListeners.remove(listener)
}
}
suspend fun createProfile(groupId: Long, bean: AbstractBean): ProxyEntity {
bean.applyDefaultValues()
val profile = ProxyEntity(groupId = groupId).apply {
id = 0
putBean(bean)
userOrder = SagerDatabase.proxyDao.nextOrder(groupId) ?: 1
}
profile.id = SagerDatabase.proxyDao.addProxy(profile)
iterator { onAdd(profile) }
return profile
}
suspend fun updateProfile(profile: ProxyEntity) {
SagerDatabase.proxyDao.updateProxy(profile)
iterator { onUpdated(profile) }
}
suspend fun updateProfile(profiles: List<ProxyEntity>) {
SagerDatabase.proxyDao.updateProxy(profiles)
profiles.forEach {
iterator { onUpdated(it) }
}
}
suspend fun deleteProfile2(groupId: Long, profileId: Long) {
if (SagerDatabase.proxyDao.deleteById(profileId) == 0) return
if (DataStore.selectedProxy == profileId) {
DataStore.selectedProxy = 0L
}
}
suspend fun deleteProfile(groupId: Long, profileId: Long) {
if (SagerDatabase.proxyDao.deleteById(profileId) == 0) return
if (DataStore.selectedProxy == profileId) {
DataStore.selectedProxy = 0L
}
iterator { onRemoved(groupId, profileId) }
if (SagerDatabase.proxyDao.countByGroup(groupId) > 1) {
GroupManager.rearrange(groupId)
}
}
fun getProfile(profileId: Long): ProxyEntity? {
if (profileId == 0L) return null
return try {
SagerDatabase.proxyDao.getById(profileId)
} catch (ex: SQLiteCantOpenDatabaseException) {
throw IOException(ex)
} catch (ex: SQLException) {
Logs.w(ex)
null
}
}
fun getProfiles(profileIds: List<Long>): List<ProxyEntity> {
if (profileIds.isEmpty()) return listOf()
return try {
SagerDatabase.proxyDao.getEntities(profileIds)
} catch (ex: SQLiteCantOpenDatabaseException) {
throw IOException(ex)
} catch (ex: SQLException) {
Logs.w(ex)
listOf()
}
}
suspend fun postUpdate(profileId: Long, withoutTraffic: Boolean = false) {
postUpdate(getProfile(profileId)?.also {
if (withoutTraffic) it.info = "withoutTraffic"
} ?: return)
}
suspend fun postUpdate(profile: ProxyEntity) {
iterator { onUpdated(profile) }
}
suspend fun postTrafficUpdated(profileId: Long, stats: TrafficStats) {
iterator { onUpdated(profileId, stats) }
}
suspend fun createRule(rule: RuleEntity, post: Boolean = true): RuleEntity {
rule.userOrder = SagerDatabase.rulesDao.nextOrder() ?: 1
rule.id = SagerDatabase.rulesDao.createRule(rule)
if (post) {
ruleIterator { onAdd(rule) }
}
return rule
}
suspend fun updateRule(rule: RuleEntity) {
SagerDatabase.rulesDao.updateRule(rule)
ruleIterator { onUpdated(rule) }
}
suspend fun deleteRule(ruleId: Long) {
SagerDatabase.rulesDao.deleteById(ruleId)
ruleIterator { onRemoved(ruleId) }
}
suspend fun deleteRules(rules: List<RuleEntity>) {
SagerDatabase.rulesDao.deleteRules(rules)
ruleIterator {
rules.forEach {
onRemoved(it.id)
}
}
}
suspend fun getRules(): List<RuleEntity> {
var rules = SagerDatabase.rulesDao.allRules()
if (rules.isEmpty() && !DataStore.rulesFirstCreate) {
DataStore.rulesFirstCreate = true
createRule(
RuleEntity(
name = app.getString(R.string.route_opt_block_quic),
port = "443",
network = "udp",
outbound = -2
)
)
createRule(
RuleEntity(
name = app.getString(R.string.route_opt_block_ads),
domains = "geosite:category-ads-all",
outbound = -2
)
)
createRule(
RuleEntity(
name = app.getString(R.string.route_opt_block_analysis),
domains = app.assets.open("analysis.txt").use {
it.bufferedReader()
.readLines()
.filter { it.isNotBlank() }
.joinToString("\n")
},
outbound = -2,
)
)
var country = Locale.getDefault().country.lowercase()
var displayCountry = Locale.getDefault().displayCountry
if (country in arrayOf(
"ir"
)
) {
createRule(
RuleEntity(
name = app.getString(R.string.route_bypass_domain, displayCountry),
domains = "domain:$country",
outbound = -1
), false
)
} else {
country = Locale.CHINA.country.lowercase()
displayCountry = Locale.CHINA.displayCountry
createRule(
RuleEntity(
name = app.getString(R.string.route_play_store, displayCountry),
domains = "domain:googleapis.cn",
), false
)
createRule(
RuleEntity(
name = app.getString(R.string.route_bypass_domain, displayCountry),
domains = "geosite:$country",
outbound = -1
), false
)
}
createRule(
RuleEntity(
name = app.getString(R.string.route_bypass_ip, displayCountry),
ip = "geoip:$country",
outbound = -1
), false
)
rules = SagerDatabase.rulesDao.allRules()
}
return rules
}
}
| Ving-Vpn/app/src/main/java/com/github/shadowsocks/plugin/ProfileManager.kt | 1165568045 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 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 com.github.shadowsocks.plugin
/**
* The contract between the plugin provider and host. Contains definitions for the supported actions, extras, etc.
*
* This class is written in Java to keep Java interoperability.
*/
object PluginContract {
/**
* ContentProvider Action: Used for NativePluginProvider.
*
* Constant Value: "com.github.shadowsocks.plugin.ACTION_NATIVE_PLUGIN"
*/
const val ACTION_NATIVE_PLUGIN = "com.github.shadowsocks.plugin.ACTION_NATIVE_PLUGIN"
/**
* Activity Action: Used for ConfigurationActivity.
*
* Constant Value: "com.github.shadowsocks.plugin.ACTION_CONFIGURE"
*/
const val ACTION_CONFIGURE = "com.github.shadowsocks.plugin.ACTION_CONFIGURE"
/**
* Activity Action: Used for HelpActivity or HelpCallback.
*
* Constant Value: "com.github.shadowsocks.plugin.ACTION_HELP"
*/
const val ACTION_HELP = "com.github.shadowsocks.plugin.ACTION_HELP"
/**
* The lookup key for a string that provides the plugin entry binary.
*
* Example: "/data/data/com.github.shadowsocks.plugin.obfs_local/lib/libobfs-local.so"
*
* Constant Value: "com.github.shadowsocks.plugin.EXTRA_ENTRY"
*/
const val EXTRA_ENTRY = "com.github.shadowsocks.plugin.EXTRA_ENTRY"
/**
* The lookup key for a string that provides the options as a string.
*
* Example: "obfs=http;obfs-host=www.baidu.com"
*
* Constant Value: "com.github.shadowsocks.plugin.EXTRA_OPTIONS"
*/
const val EXTRA_OPTIONS = "com.github.shadowsocks.plugin.EXTRA_OPTIONS"
/**
* The lookup key for a CharSequence that provides user relevant help message.
*
* Example: "obfs=<http></http>|tls> Enable obfuscating: HTTP or TLS (Experimental).
* obfs-host=<host_name> Hostname for obfuscating (Experimental)."
*
* Constant Value: "com.github.shadowsocks.plugin.EXTRA_HELP_MESSAGE"
</host_name> */
const val EXTRA_HELP_MESSAGE = "com.github.shadowsocks.plugin.EXTRA_HELP_MESSAGE"
/**
* The metadata key to retrieve plugin version. Required for plugin applications.
*
* Constant Value: "com.github.shadowsocks.plugin.version"
*/
const val METADATA_KEY_VERSION = "com.github.shadowsocks.plugin.version"
/**
* The metadata key to retrieve plugin id. Required for plugins.
*
* Constant Value: "com.github.shadowsocks.plugin.id"
*/
const val METADATA_KEY_ID = "com.github.shadowsocks.plugin.id"
/**
* The metadata key to retrieve plugin id aliases.
* Can be a string (representing one alias) or a resource to a string or string array.
*
* Constant Value: "com.github.shadowsocks.plugin.id.aliases"
*/
const val METADATA_KEY_ID_ALIASES = "com.github.shadowsocks.plugin.id.aliases"
/**
* The metadata key to retrieve default configuration. Default value is empty.
*
* Constant Value: "com.github.shadowsocks.plugin.default_config"
*/
const val METADATA_KEY_DEFAULT_CONFIG = "com.github.shadowsocks.plugin.default_config"
/**
* The metadata key to retrieve executable path to your native binary.
* This path should be relative to your application's nativeLibraryDir.
*
* If this is set, the host app will prefer this value and (probably) not launch your app at all (aka faster mode).
* In order for this to work, plugin app is encouraged to have the following in its AndroidManifest.xml:
* - android:installLocation="internalOnly" for <manifest>
* - android:extractNativeLibs="true" for <application>
*
* Do not use this if you plan to do some setup work before giving away your binary path,
* or your native binary is not at a fixed location relative to your application's nativeLibraryDir.
*
* Since plugin lib: 1.3.0
*
* Constant Value: "com.github.shadowsocks.plugin.executable_path"
*/
const val METADATA_KEY_EXECUTABLE_PATH = "com.github.shadowsocks.plugin.executable_path"
const val METHOD_GET_EXECUTABLE = "shadowsocks:getExecutable"
/** ConfigurationActivity result: fallback to manual edit mode. */
const val RESULT_FALLBACK = 1
/**
* Relative to the file to be copied. This column is required.
*
* Example: "kcptun", "doc/help.txt"
*
* Type: String
*/
const val COLUMN_PATH = "path"
/**
* File mode bits. Default value is 644 in octal.
*
* Example: 0b110100100 (for 755 in octal)
*
* Type: Int or String (deprecated)
*/
const val COLUMN_MODE = "mode"
/**
* The scheme for general plugin actions.
*/
const val SCHEME = "plugin"
/**
* The authority for general plugin actions.
*/
const val AUTHORITY = "com.github.shadowsocks"
}
| Ving-Vpn/app/src/main/java/com/github/shadowsocks/plugin/PluginContract.kt | 3147262067 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 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 com.github.shadowsocks.plugin
import com.narcis.application.presentation.connection.Logs
import io.nekohasekai.sagernet.utils.Commandline
import java.util.*
class PluginConfiguration(val pluginsOptions: MutableMap<String, PluginOptions>, var selected: String) {
private constructor(plugins: List<PluginOptions>) : this(
plugins.filter { it.id.isNotEmpty() }.associateBy { it.id }.toMutableMap(),
if (plugins.isEmpty()) "" else plugins[0].id)
constructor(): this(listOf())
constructor(plugin: String) : this(plugin.split('\n').map { line ->
if (line.startsWith("kcptun ")) {
val opt = PluginOptions()
opt.id = "kcptun"
try {
val iterator = Commandline.translateCommandline(line).drop(1).iterator()
while (iterator.hasNext()) {
val option = iterator.next()
when {
option == "--nocomp" -> opt["nocomp"] = null
option.startsWith("--") -> opt[option.substring(2)] = iterator.next()
else -> throw IllegalArgumentException("Unknown kcptun parameter: $option")
}
}
} catch (exc: Exception) {
Logs.w(exc)
}
opt
} else PluginOptions(line)
})
fun getOptions(
id: String = selected,
defaultConfig: () -> String? = { PluginManager.fetchPlugins(true).lookup[id]?.defaultConfig }
) = if (id.isEmpty()) PluginOptions() else pluginsOptions[id] ?: PluginOptions(id, defaultConfig())
override fun toString(): String {
val result = LinkedList<PluginOptions>()
for ((id, opt) in pluginsOptions) if (id == this.selected) result.addFirst(opt) else result.addLast(opt)
if (!pluginsOptions.contains(selected)) result.addFirst(getOptions())
return result.joinToString("\n") { it.toString(false) }
}
}
| Ving-Vpn/app/src/main/java/com/github/shadowsocks/plugin/PluginConfiguration.kt | 397825189 |
/******************************************************************************
* *
* Copyright (C) 2021 by nekohasekai <[email protected]> *
* Copyright (C) 2021 by Max Lv <[email protected]> *
* Copyright (C) 2021 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 com.github.shadowsocks.plugin
import android.content.Intent
import android.content.pm.PackageManager
import io.nekohasekai.sagernet.SagerNet
class PluginList(skipInternal: Boolean) : ArrayList<Plugin>() {
init {
add(NoPlugin)
if (!skipInternal) {
add(InternalPlugin.SIMPLE_OBFS)
add(InternalPlugin.V2RAY_PLUGIN)
}
addAll(
SagerNet.application.packageManager.queryIntentContentProviders(
Intent(PluginContract.ACTION_NATIVE_PLUGIN), PackageManager.GET_META_DATA)
.filter { it.providerInfo.exported }.map { NativePlugin(it) })
}
val lookup = mutableMapOf<String, Plugin>().apply {
for (plugin in [email protected]()) {
fun check(old: Plugin?) {
if (old != null && old != plugin) {
[email protected](old)
}
// skip check
/*if (old != null && old !== plugin) {
val packages = [email protected] { it.id == plugin.id }.joinToString { it.packageName }
val message = "Conflicting plugins found from: $packages"
Toast.makeText(SagerNet.application, message, Toast.LENGTH_LONG).show()
throw IllegalStateException(message)
}*/
}
check(put(plugin.id, plugin))
for (alias in plugin.idAliases) check(put(alias, plugin))
}
}
}
| Ving-Vpn/app/src/main/java/com/github/shadowsocks/plugin/PluginList.kt | 4210288140 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.