Using AI to improve function documentation

This commit is contained in:
2dust
2025-03-19 14:12:30 +08:00
parent d0e8937f03
commit 12ab2954b0
9 changed files with 215 additions and 13 deletions
@@ -39,7 +39,10 @@ object NotificationService {
private var speedNotificationJob: Job? = null
private var mNotificationManager: NotificationManager? = null
/**
* Starts the speed notification.
* @param currentConfig The current profile configuration.
*/
fun startSpeedNotification(currentConfig: ProfileItem?) {
if (MmkvManager.decodeSettingsBool(AppConfig.PREF_SPEED_ENABLED) != true) return
if (speedNotificationJob != null || V2RayServiceManager.isRunning() == false) return
@@ -83,6 +86,10 @@ object NotificationService {
}
}
/**
* Shows the notification.
* @param currentConfig The current profile configuration.
*/
fun showNotification(currentConfig: ProfileItem?) {
val service = getService() ?: return
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
@@ -131,13 +138,15 @@ object NotificationService {
service.getString(R.string.title_service_restart),
restartV2RayPendingIntent
)
//.build()
//mBuilder?.setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE) //取消震动,铃声其他都不好使
//mBuilder?.setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
service.startForeground(NOTIFICATION_ID, mBuilder?.build())
}
/**
* Cancels the notification.
*/
fun cancelNotification() {
val service = getService() ?: return
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
@@ -151,6 +160,10 @@ object NotificationService {
speedNotificationJob = null
}
/**
* Stops the speed notification.
* @param currentConfig The current profile configuration.
*/
fun stopSpeedNotification(currentConfig: ProfileItem?) {
speedNotificationJob?.let {
it.cancel()
@@ -159,6 +172,10 @@ object NotificationService {
}
}
/**
* Creates a notification channel for Android O and above.
* @return The channel ID.
*/
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(): String {
val channelId = AppConfig.RAY_NG_CHANNEL_ID
@@ -174,6 +191,12 @@ object NotificationService {
return channelId
}
/**
* Updates the notification with the given content text and traffic data.
* @param contentText The content text.
* @param proxyTraffic The proxy traffic.
* @param directTraffic The direct traffic.
*/
private fun updateNotification(contentText: String?, proxyTraffic: Long, directTraffic: Long) {
if (mBuilder != null) {
if (proxyTraffic < NOTIFICATION_ICON_THRESHOLD && directTraffic < NOTIFICATION_ICON_THRESHOLD) {
@@ -184,11 +207,15 @@ object NotificationService {
mBuilder?.setSmallIcon(R.drawable.ic_stat_direct)
}
mBuilder?.setStyle(NotificationCompat.BigTextStyle().bigText(contentText))
mBuilder?.setContentText(contentText) // Emui4.1 need content text even if style is set as BigTextStyle
mBuilder?.setContentText(contentText)
getNotificationManager()?.notify(NOTIFICATION_ID, mBuilder?.build())
}
}
/**
* Gets the notification manager.
* @return The notification manager.
*/
private fun getNotificationManager(): NotificationManager? {
if (mNotificationManager == null) {
val service = getService() ?: return null
@@ -197,6 +224,13 @@ object NotificationService {
return mNotificationManager
}
/**
* Appends the speed string to the given text.
* @param text The text to append to.
* @param name The name of the tag.
* @param up The uplink speed.
* @param down The downlink speed.
*/
private fun appendSpeedString(text: StringBuilder, name: String?, up: Double, down: Double) {
var n = name ?: "no tag"
n = n.substring(0, min(n.length, 6))
@@ -207,8 +241,11 @@ object NotificationService {
text.append("${up.toLong().toSpeedString()}${down.toLong().toSpeedString()}\n")
}
/**
* Gets the service instance.
* @return The service instance.
*/
private fun getService(): Service? {
return V2RayServiceManager.serviceControl?.get()?.getService()
}
}
@@ -10,6 +10,11 @@ import kotlinx.coroutines.launch
class ProcessService {
private var process: Process? = null
/**
* Runs a process with the given command.
* @param context The context.
* @param cmd The command to run.
*/
fun runProcess(context: Context, cmd: MutableList<String>) {
Log.d(ANG_PACKAGE, cmd.toString())
@@ -33,6 +38,9 @@ class ProcessService {
}
}
/**
* Stops the running process.
*/
fun stopProcess() {
try {
Log.d(ANG_PACKAGE, "runProcess destroy")
@@ -19,6 +19,10 @@ import java.lang.ref.SoftReference
@TargetApi(Build.VERSION_CODES.N)
class QSTileService : TileService() {
/**
* Sets the state of the tile.
* @param state The state to set.
*/
fun setState(state: Int) {
if (state == Tile.STATE_INACTIVE) {
qsTile?.state = Tile.STATE_INACTIVE
@@ -37,7 +41,6 @@ class QSTileService : TileService() {
* Refer to the official documentation for [registerReceiver](https://developer.android.com/reference/androidx/core/content/ContextCompat#registerReceiver(android.content.Context,android.content.BroadcastReceiver,android.content.IntentFilter,int):
* `registerReceiver(Context, BroadcastReceiver, IntentFilter, int)`.
*/
override fun onStartListening() {
super.onStartListening()
@@ -48,6 +51,9 @@ class QSTileService : TileService() {
MessageUtil.sendMsg2Service(this, AppConfig.MSG_REGISTER_CLIENT, "")
}
/**
* Called when the tile stops listening.
*/
override fun onStopListening() {
super.onStopListening()
@@ -60,6 +66,9 @@ class QSTileService : TileService() {
}
/**
* Called when the tile is clicked.
*/
override fun onClick() {
super.onClick()
when (qsTile.state) {
@@ -3,11 +3,26 @@ package com.v2ray.ang.service
import android.app.Service
interface ServiceControl {
/**
* Gets the service instance.
* @return The service instance.
*/
fun getService(): Service
/**
* Starts the service.
*/
fun startService()
/**
* Stops the service.
*/
fun stopService()
/**
* Protects the VPN socket.
* @param socket The socket to protect.
* @return True if the socket is protected, false otherwise.
*/
fun vpnProtect(socket: Int): Boolean
}
@@ -19,7 +19,6 @@ import com.v2ray.ang.handler.MmkvManager
object SubscriptionUpdater {
class UpdateTask(context: Context, params: WorkerParameters) :
CoroutineWorker(context, params) {
@@ -33,6 +32,10 @@ object SubscriptionUpdater {
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
/**
* Performs the subscription update work.
* @return The result of the work.
*/
@SuppressLint("MissingPermission")
override suspend fun doWork(): Result {
Log.d(AppConfig.ANG_PACKAGE, "subscription automatic update starting")
@@ -11,41 +11,78 @@ import com.v2ray.ang.util.MyContextWrapper
import java.lang.ref.SoftReference
class V2RayProxyOnlyService : Service(), ServiceControl {
/**
* Initializes the service.
*/
override fun onCreate() {
super.onCreate()
V2RayServiceManager.serviceControl = SoftReference(this)
}
/**
* Handles the start command for the service.
* @param intent The intent.
* @param flags The flags.
* @param startId The start ID.
* @return The start mode.
*/
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
V2RayServiceManager.startV2rayPoint()
return START_STICKY
}
/**
* Destroys the service.
*/
override fun onDestroy() {
super.onDestroy()
V2RayServiceManager.stopV2rayPoint()
}
/**
* Gets the service instance.
* @return The service instance.
*/
override fun getService(): Service {
return this
}
/**
* Starts the service.
*/
override fun startService() {
// do nothing
}
/**
* Stops the service.
*/
override fun stopService() {
stopSelf()
}
/**
* Protects the VPN socket.
* @param socket The socket to protect.
* @return True if the socket is protected, false otherwise.
*/
override fun vpnProtect(socket: Int): Boolean {
return true
}
/**
* Binds the service.
* @param intent The intent.
* @return The binder.
*/
override fun onBind(intent: Intent?): IBinder? {
return null
}
/**
* Attaches the base context to the service.
* @param newBase The new base context.
*/
@RequiresApi(Build.VERSION_CODES.N)
override fun attachBaseContext(newBase: Context?) {
val context = newBase?.let {
@@ -42,6 +42,11 @@ object V2RayServiceManager {
Libv2ray.initV2Env(Utils.userAssetPath(value?.get()?.getService()), Utils.getDeviceIdForXUDPBaseKey())
}
/**
* Starts the V2Ray service from a toggle action.
* @param context The context from which the service is started.
* @return True if the service was started successfully, false otherwise.
*/
fun startVServiceFromToggle(context: Context): Boolean {
if (MmkvManager.getSelectServer().isNullOrEmpty()) {
context.toast(R.string.app_tile_first_use)
@@ -51,6 +56,11 @@ object V2RayServiceManager {
return true
}
/**
* Starts the V2Ray service.
* @param context The context from which the service is started.
* @param guid The GUID of the server configuration to use (optional).
*/
fun startVService(context: Context, guid: String? = null) {
if (guid != null) {
MmkvManager.setSelectServer(guid)
@@ -58,15 +68,31 @@ object V2RayServiceManager {
startContextService(context)
}
/**
* Stops the V2Ray service.
* @param context The context from which the service is stopped.
*/
fun stopVService(context: Context) {
context.toast(R.string.toast_services_stop)
MessageUtil.sendMsg2Service(context, AppConfig.MSG_STATE_STOP, "")
}
/**
* Checks if the V2Ray service is running.
* @return True if the service is running, false otherwise.
*/
fun isRunning() = v2rayPoint.isRunning
/**
* Gets the name of the currently running server.
* @return The name of the running server.
*/
fun getRunningServerName() = currentConfig?.remarks.orEmpty()
/**
* Starts the context service for V2Ray.
* @param context The context from which the service is started.
*/
private fun startContextService(context: Context) {
if (v2rayPoint.isRunning) return
val guid = MmkvManager.getSelectServer() ?: return
@@ -98,8 +124,8 @@ object V2RayServiceManager {
/**
* Refer to the official documentation for [registerReceiver](https://developer.android.com/reference/androidx/core/content/ContextCompat#registerReceiver(android.content.Context,android.content.BroadcastReceiver,android.content.IntentFilter,int):
* `registerReceiver(Context, BroadcastReceiver, IntentFilter, int)`.
* Starts the V2Ray point.
*/
fun startV2rayPoint() {
val service = getService() ?: return
val guid = MmkvManager.getSelectServer() ?: return
@@ -142,6 +168,9 @@ object V2RayServiceManager {
}
}
/**
* Stops the V2Ray point.
*/
fun stopV2rayPoint() {
val service = getService() ?: return
@@ -166,10 +195,19 @@ object V2RayServiceManager {
PluginUtil.stopPlugin()
}
/**
* Queries the statistics for a given tag and link.
* @param tag The tag to query.
* @param link The link to query.
* @return The statistics value.
*/
fun queryStats(tag: String, link: String): Long {
return v2rayPoint.queryStats(tag, link)
}
/**
* Measures the delay for V2Ray.
*/
private fun measureV2rayDelay() {
CoroutineScope(Dispatchers.IO).launch {
val service = getService() ?: return@launch
@@ -201,6 +239,10 @@ object V2RayServiceManager {
}
}
/**
* Gets the current service instance.
* @return The current service instance, or null if not available.
*/
private fun getService(): Service? {
return serviceControl?.get()?.getService()
}
@@ -227,10 +269,21 @@ object V2RayServiceManager {
return serviceControl.vpnProtect(l.toInt())
}
/**
* Called by Go to emit status.
* @param l The status code.
* @param s The status message.
* @return The status code.
*/
override fun onEmitStatus(l: Long, s: String?): Long {
return 0
}
/**
* Called by Go to set up the service.
* @param s The setup string.
* @return The status code.
*/
override fun setup(s: String): Long {
val serviceControl = serviceControl?.get() ?: return -1
return try {
@@ -245,6 +298,11 @@ object V2RayServiceManager {
}
private class ReceiveMessageHandler : BroadcastReceiver() {
/**
* Handles received broadcast messages.
* @param ctx The context in which the receiver is running.
* @param intent The intent being received.
*/
override fun onReceive(ctx: Context?, intent: Intent?) {
val serviceControl = serviceControl?.get() ?: return
when (intent?.getIntExtra("key", 0)) {
@@ -26,12 +26,22 @@ import java.util.concurrent.Executors
class V2RayTestService : Service() {
private val realTestScope by lazy { CoroutineScope(Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()).asCoroutineDispatcher()) }
/**
* Initializes the V2Ray environment.
*/
override fun onCreate() {
super.onCreate()
Seq.setContext(this)
Libv2ray.initV2Env(Utils.userAssetPath(this), Utils.getDeviceIdForXUDPBaseKey())
}
/**
* Handles the start command for the service.
* @param intent The intent.
* @param flags The flags.
* @param startId The start ID.
* @return The start mode.
*/
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.getIntExtra("key", 0)) {
MSG_MEASURE_CONFIG -> {
@@ -49,10 +59,20 @@ class V2RayTestService : Service() {
return super.onStartCommand(intent, flags, startId)
}
/**
* Binds the service.
* @param intent The intent.
* @return The binder.
*/
override fun onBind(intent: Intent?): IBinder? {
return null
}
/**
* Starts the real ping test.
* @param guid The GUID of the configuration.
* @return The ping result.
*/
private fun startRealPing(guid: String): Long {
val retFailure = -1L
@@ -42,11 +42,8 @@ class V2RayVpnService : VpnService(), ServiceControl {
private const val TUN2SOCKS = "libtun2socks.so"
}
private lateinit var mInterface: ParcelFileDescriptor
private var isRunning = false
//val fd: Int get() = mInterface.fd
private lateinit var process: Process
/**destroy
@@ -88,7 +85,6 @@ class V2RayVpnService : VpnService(), ServiceControl {
override fun onCreate() {
super.onCreate()
val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
V2RayServiceManager.serviceControl = SoftReference(this)
@@ -138,6 +134,10 @@ class V2RayVpnService : VpnService(), ServiceControl {
super.attachBaseContext(context)
}
/**
* Sets up the VPN service.
* Prepares the VPN and configures it if preparation is successful.
*/
private fun setup() {
val prepare = prepare(this)
if (prepare != null) {
@@ -151,6 +151,10 @@ class V2RayVpnService : VpnService(), ServiceControl {
runTun2socks()
}
/**
* Configures the VPN service.
* @return True if the VPN service was configured successfully, false otherwise.
*/
private fun setupVpnService(): Boolean {
// If the old interface has exactly the same parameters, use it!
// Configure a builder while parsing the parameters.
@@ -247,6 +251,10 @@ class V2RayVpnService : VpnService(), ServiceControl {
return false
}
/**
* Runs the tun2socks process.
* Starts the tun2socks process with the appropriate parameters.
*/
private fun runTun2socks() {
val socksPort = SettingsManager.getSocksPort()
val cmd = arrayListOf(
@@ -294,6 +302,10 @@ class V2RayVpnService : VpnService(), ServiceControl {
}
}
/**
* Sends the file descriptor to the tun2socks process.
* Attempts to send the file descriptor multiple times if necessary.
*/
private fun sendFd() {
val fd = mInterface.fileDescriptor
val path = File(applicationContext.filesDir, "sock_path").absolutePath
@@ -318,6 +330,10 @@ class V2RayVpnService : VpnService(), ServiceControl {
}
}
/**
* Stops the V2Ray service.
* @param isForced Whether to force stop the service.
*/
private fun stopV2Ray(isForced: Boolean = true) {
// val configName = defaultDPreference.getPrefString(PREF_CURR_CONFIG_GUID, "")
// val emptyInfo = VpnNetworkInfo()
@@ -356,5 +372,4 @@ class V2RayVpnService : VpnService(), ServiceControl {
}
}
}
}