List all configuration files in Utils val BARESIP_FILES

Use BARESIP_FILES in mainscreen and utils functions
Utils code styling
This commit is contained in:
Juha Heinanen
2026-07-24 16:01:33 +03:00
parent f9872e891d
commit e328bb43e6
2 changed files with 46 additions and 60 deletions

View File

@ -2791,8 +2791,7 @@ private fun acceptTransfer(ctx: Context, viewModel: ViewModel, ua: UserAgent, ca
} }
private fun backup(ctx: Context, password: String) { private fun backup(ctx: Context, password: String) {
val files = arrayListOf("accounts", "config", "contacts", "call_history", val files = ArrayList(Utils.BARESIP_FILES)
"messages", "uuid", "gzrtp.zid", "cert.pem", "ca_cert", "ca_certs.crt", "blocked.json")
File(BaresipService.filesPath).walk().forEach { File(BaresipService.filesPath).walk().forEach {
if (it.name.endsWith(".png")) if (it.name.endsWith(".png"))
files.add(it.name) files.add(it.name)

View File

@ -98,6 +98,9 @@ import javax.net.ssl.X509TrustManager
object Utils { object Utils {
val BARESIP_FILES = listOf("accounts", "call_history", "config", "contacts", "messages", "uuid",
"gzrtp.zid", "cert.pem", "ca_certs.crt", "blocked.json")
fun getNameValue(string: String, name: String): ArrayList<String> { fun getNameValue(string: String, name: String): ArrayList<String> {
val lines = string.split("\n") val lines = string.split("\n")
val result = ArrayList<String>() val result = ArrayList<String>()
@ -115,13 +118,13 @@ object Utils {
} }
fun uriHostPart(uri: String): String { fun uriHostPart(uri: String): String {
return if (uri.contains("@")) { return if (uri.contains("@"))
uri.substringAfter("@") uri.substringAfter("@")
.substringBefore(":") .substringBefore(":")
.substringBefore(";") .substringBefore(";")
.substringBefore("?") .substringBefore("?")
.substringBefore(">") .substringBefore(">")
} else { else {
val parts = uri.split(":") val parts = uri.split(":")
when (parts.size) { when (parts.size) {
2 -> parts[1].substringBefore(";") 2 -> parts[1].substringBefore(";")
@ -203,7 +206,7 @@ object Utils {
fun e164Uri(uri: String, countryCode: String): String { fun e164Uri(uri: String, countryCode: String): String {
val scheme = uri.take(4) val scheme = uri.take(4)
val userPart = uriUserPart(uri) val userPart = uriUserPart(uri)
return if (userPart.isNotEmpty() && userPart.isDigitsOnly()) { return if (userPart.isNotEmpty() && userPart.isDigitsOnly())
when { when {
userPart.startsWith("00") -> uri.replace("$scheme$userPart", userPart.startsWith("00") -> uri.replace("$scheme$userPart",
scheme + "+" + userPart.substring(2)) scheme + "+" + userPart.substring(2))
@ -212,7 +215,7 @@ object Utils {
"$scheme$countryCode") "$scheme$countryCode")
else -> uri.replace(scheme, "$scheme$countryCode") else -> uri.replace(scheme, "$scheme$countryCode")
} }
} else else
uri uri
} }
@ -241,21 +244,18 @@ object Utils {
if (!checkSipUri(aor)) return false if (!checkSipUri(aor)) return false
val params = uriParams(aor) val params = uriParams(aor)
return params.isEmpty() || return params.isEmpty() ||
((params.size == 1) && ((params.size == 1) && params[0] in arrayOf("transport=udp", "transport=tcp", "transport=tls"))
params[0] in arrayOf("transport=udp", "transport=tcp", "transport=tls"))
} }
private fun checkTransport(transport: String, transports: Set<String>): Boolean { private fun checkTransport(transport: String, transports: Set<String>): Boolean {
return transport.split("=")[0] == "transport" && return transport.split("=")[0] == "transport" && transport.split("=")[1].lowercase() in transports
transport.split("=")[1].lowercase() in transports
} }
fun checkStunUri(uri: String): Boolean { fun checkStunUri(uri: String): Boolean {
if (uri.substringBefore(":").lowercase() !in setOf("stun", "stuns", "turn", "turns")) if (uri.substringBefore(":").lowercase() !in setOf("stun", "stuns", "turn", "turns"))
return false return false
return checkHostPort(uri.substringAfter(":").substringBefore("?")) && return checkHostPort(uri.substringAfter(":").substringBefore("?")) &&
(uri.indexOf("?") == -1 || (uri.indexOf("?") == -1 || checkTransport(uri.substringAfter("?"), setOf("udp", "tcp")))
checkTransport(uri.substringAfter("?"), setOf("udp", "tcp")))
} }
fun checkIpV4(ip: String): Boolean { fun checkIpV4(ip: String): Boolean {
@ -280,11 +280,10 @@ object Utils {
fun checkDomain(domain: String): Boolean { fun checkDomain(domain: String): Boolean {
val parts = domain.split(".") val parts = domain.split(".")
for (p in parts) { for (p in parts)
if (p.endsWith("-") || p.startsWith("-") || if (p.endsWith("-") || p.startsWith("-") ||
!Regex("^[-a-zA-Z0-9]+$").matches(p)) !Regex("^[-a-zA-Z0-9]+$").matches(p))
return false return false
}
return true return true
} }
@ -370,9 +369,9 @@ object Utils {
checkUriUser(userRest[0]) && checkHostPortParams(userRest[1]) checkUriUser(userRest[0]) && checkHostPortParams(userRest[1])
else -> false else -> false
} }
} else {
false
} }
else
false
} }
fun isTelNumber(no: String): Boolean { fun isTelNumber(no: String): Boolean {
@ -454,12 +453,8 @@ object Utils {
fun implode(list: List<String>, sep: String): String { fun implode(list: List<String>, sep: String): String {
var res = "" var res = ""
for (s in list) { for (s in list)
res = if (res == "") res = if (res == "") s else res + sep + s
s
else
res + sep + s
}
return res return res
} }
@ -472,9 +467,9 @@ object Utils {
val normalizedName = unaccent(name) val normalizedName = unaccent(name)
val normalizedQuery = unaccent(query) val normalizedQuery = unaccent(query)
val startIndex = normalizedName.indexOf(normalizedQuery, ignoreCase = true) val startIndex = normalizedName.indexOf(normalizedQuery, ignoreCase = true)
return if (startIndex == -1) { return if (startIndex == -1)
buildAnnotatedString { append(name) } buildAnnotatedString { append(name) }
} else { else
buildAnnotatedString { buildAnnotatedString {
append(name.take(startIndex)) append(name.take(startIndex))
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) { withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
@ -482,7 +477,6 @@ object Utils {
} }
append(name.drop(startIndex + normalizedQuery.length)) append(name.drop(startIndex + normalizedQuery.length))
} }
}
} }
fun isVisible(): Boolean { fun isVisible(): Boolean {
@ -526,14 +520,13 @@ object Utils {
} }
fun checkPermissions(ctx: Context, permissions: Array<String>) : Boolean { fun checkPermissions(ctx: Context, permissions: Array<String>) : Boolean {
for (p in permissions) { for (p in permissions)
if (ContextCompat.checkSelfPermission(ctx, p) != PackageManager.PERMISSION_GRANTED) { if (ContextCompat.checkSelfPermission(ctx, p) != PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Permission $p is denied") Log.d(TAG, "Permission $p is denied")
return false return false
} else {
Log.d(TAG, "Permission $p is granted")
} }
} else
Log.d(TAG, "Permission $p is granted")
return true return true
} }
@ -563,13 +556,12 @@ object Utils {
} }
fun deleteFile(file: File) { fun deleteFile(file: File) {
if (file.exists()) { if (file.exists())
try { try {
file.delete() file.delete()
} catch (e: IOException) { } catch (e: IOException) {
Log.e(TAG, "Could not delete file ${file.absolutePath}: $e") Log.e(TAG, "Could not delete file ${file.absolutePath}: $e")
} }
}
} }
fun deleteFile(ctx: Context, uri: Uri): Boolean { fun deleteFile(ctx: Context, uri: Uri): Boolean {
@ -583,7 +575,8 @@ object Utils {
Log.d(TAG, "File not found or could not be deleted: $uri") Log.d(TAG, "File not found or could not be deleted: $uri")
return false return false
} }
} else { }
else {
Log.d(TAG, "Uri is not a document uri: $uri") Log.d(TAG, "Uri is not a document uri: $uri")
return false return false
} }
@ -621,9 +614,7 @@ object Utils {
fun File.copyInputStreamToFile(inputStream: InputStream): Boolean { fun File.copyInputStreamToFile(inputStream: InputStream): Boolean {
try { try {
this.outputStream().use { fileOut -> this.outputStream().use { fileOut -> inputStream.copyTo(fileOut) }
inputStream.copyTo(fileOut)
}
return true return true
} }
catch (e: IOException) { catch (e: IOException) {
@ -760,9 +751,7 @@ object Utils {
try { try {
val stream = ctx.contentResolver.openOutputStream(uri) val stream = ctx.contentResolver.openOutputStream(uri)
if (stream != null) if (stream != null)
ObjectOutputStream(stream).use { ObjectOutputStream(stream).use { it.writeObject(obj) }
it.writeObject(obj)
}
else { else {
Log.w(TAG, "encryptToUri: could not open output stream") Log.w(TAG, "encryptToUri: could not open output stream")
return false return false
@ -812,7 +801,7 @@ object Utils {
val data = ByteArray(1024) val data = ByteArray(1024)
for (fileName in fileNames) { for (fileName in fileNames) {
val filePath = BaresipService.filesPath + "/" + fileName val filePath = BaresipService.filesPath + "/" + fileName
if (File(filePath).exists()) { if (File(filePath).exists())
FileInputStream(filePath).use { fi -> FileInputStream(filePath).use { fi ->
BufferedInputStream(fi).use { origin -> BufferedInputStream(fi).use { origin ->
val entry = ZipEntry(fileName) val entry = ZipEntry(fileName)
@ -824,7 +813,6 @@ object Utils {
} }
} }
} }
}
} }
} }
} catch (e: IOException) { } catch (e: IOException) {
@ -835,8 +823,6 @@ object Utils {
} }
fun unZip(zipFilePath: String): Boolean { fun unZip(zipFilePath: String): Boolean {
val allFiles = listOf("accounts", "call_history", "config", "contacts", "messages", "uuid",
"gzrtp.zid", "cert.pem", "ca_cert", "ca_certs.crt")
val zipFiles = mutableListOf<String>() val zipFiles = mutableListOf<String>()
try { try {
ZipFile(File(zipFilePath)).use { zip -> ZipFile(File(zipFilePath)).use { zip ->
@ -857,7 +843,7 @@ object Utils {
Log.e(TAG, "Failed to unzip file '$zipFilePath': $e") Log.e(TAG, "Failed to unzip file '$zipFilePath': $e")
return false return false
} }
(allFiles - zipFiles.toSet()).iterator().forEach { (BARESIP_FILES - zipFiles.toSet()).iterator().forEach {
deleteFile(File(BaresipService.filesPath, it)) deleteFile(File(BaresipService.filesPath, it))
} }
return true return true
@ -911,7 +897,7 @@ object Utils {
try { try {
val getCallsMethod = TelecomManager::class.java.getMethod("getCalls") val getCallsMethod = TelecomManager::class.java.getMethod("getCalls")
val calls = getCallsMethod.invoke(tm) as? List<*> val calls = getCallsMethod.invoke(tm) as? List<*>
if (calls != null) { if (calls != null)
for (c in calls) { for (c in calls) {
if (c == null) continue if (c == null) continue
val state = c.javaClass.getMethod("getState").invoke(c) as Int val state = c.javaClass.getMethod("getState").invoke(c) as Int
@ -924,7 +910,6 @@ object Utils {
} }
} }
} }
}
} catch (e: Exception) { } catch (e: Exception) {
Log.e(TAG, "isPSTNCallActive reflection error: $e") Log.e(TAG, "isPSTNCallActive reflection error: $e")
} }
@ -940,7 +925,8 @@ object Utils {
return if (DateUtils.isToday(time.timeInMillis)) { return if (DateUtils.isToday(time.timeInMillis)) {
val fmt = DateFormat.getTimeInstance(DateFormat.SHORT) val fmt = DateFormat.getTimeInstance(DateFormat.SHORT)
ctx.getString(R.string.today) + "\n" + fmt.format(time.time) ctx.getString(R.string.today) + "\n" + fmt.format(time.time)
} else { }
else {
val month = time.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault())!! val month = time.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault())!!
.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() } .replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }
val day = time.get(Calendar.DAY_OF_MONTH) val day = time.get(Calendar.DAY_OF_MONTH)
@ -948,9 +934,9 @@ object Utils {
if (time.get(Calendar.YEAR) == currentYear) { if (time.get(Calendar.YEAR) == currentYear) {
val fmt = DateFormat.getTimeInstance(DateFormat.SHORT) val fmt = DateFormat.getTimeInstance(DateFormat.SHORT)
"$month $day" + "\n" + fmt.format(time.time) "$month $day" + "\n" + fmt.format(time.time)
} else {
"$month $day" + "\n" + time.get(Calendar.YEAR)
} }
else
"$month $day" + "\n" + time.get(Calendar.YEAR)
} }
} }
@ -983,7 +969,8 @@ object Utils {
Log.d(TAG, "Setting com device to ${speakerDevice.type} in MODE_NORMAL") Log.d(TAG, "Setting com device to ${speakerDevice.type} in MODE_NORMAL")
if (!am.setCommunicationDevice(speakerDevice)) if (!am.setCommunicationDevice(speakerDevice))
Log.e(TAG, "Could not set com device") Log.e(TAG, "Could not set com device")
} else { }
else {
val normalListener = object : AudioManager.OnModeChangedListener { val normalListener = object : AudioManager.OnModeChangedListener {
override fun onModeChanged(mode: Int) { override fun onModeChanged(mode: Int) {
if (mode == AudioManager.MODE_NORMAL) { if (mode == AudioManager.MODE_NORMAL) {
@ -1004,7 +991,8 @@ object Utils {
Log.d(TAG, "New com device/mode is " + Log.d(TAG, "New com device/mode is " +
"${am.communicationDevice?.type ?: AudioDeviceInfo.TYPE_UNKNOWN}/${am.mode}") "${am.communicationDevice?.type ?: AudioDeviceInfo.TYPE_UNKNOWN}/${am.mode}")
} }
} else { }
else {
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
am.isSpeakerphoneOn = enable am.isSpeakerphoneOn = enable
Log.d(TAG, "Speakerphone is $enable") Log.d(TAG, "Speakerphone is $enable")
@ -1027,10 +1015,9 @@ object Utils {
fun clearCommunicationDevice(am: AudioManager) { fun clearCommunicationDevice(am: AudioManager) {
if (Build.VERSION.SDK_INT >= 31) if (Build.VERSION.SDK_INT >= 31)
am.clearCommunicationDevice() am.clearCommunicationDevice()
else { else
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
am.isSpeakerphoneOn = false am.isSpeakerphoneOn = false
}
} }
@Suppress("unused") @Suppress("unused")
@ -1080,9 +1067,9 @@ object Utils {
BaresipService.aecAvailable = true BaresipService.aecAvailable = true
aec.release() aec.release()
Log.i(TAG, "Creation of hardware AEC for $sessionId succeeded") Log.i(TAG, "Creation of hardware AEC for $sessionId succeeded")
} else {
Log.w(TAG, "Creation of hardware AEC for $sessionId failed")
} }
else
Log.w(TAG, "Creation of hardware AEC for $sessionId failed")
} }
else else
Log.i(TAG, "Hardware AEC is NOT available") Log.i(TAG, "Hardware AEC is NOT available")
@ -1093,9 +1080,9 @@ object Utils {
BaresipService.agcAvailable = true BaresipService.agcAvailable = true
agc.release() agc.release()
Log.d(TAG, "Creation of hardware AGC for $sessionId succeeded") Log.d(TAG, "Creation of hardware AGC for $sessionId succeeded")
} else {
Log.w(TAG, "Creation of hardware AGC for $sessionId failed")
} }
else
Log.w(TAG, "Creation of hardware AGC for $sessionId failed")
} }
else else
Log.i(TAG, "Hardware AGC is NOT available") Log.i(TAG, "Hardware AGC is NOT available")
@ -1106,9 +1093,9 @@ object Utils {
BaresipService.nsAvailable = true BaresipService.nsAvailable = true
ns.release() ns.release()
Log.d(TAG, "Creation of hardware NS for $sessionId succeeded") Log.d(TAG, "Creation of hardware NS for $sessionId succeeded")
} else {
Log.w(TAG, "Creation of hardware NS for $sessionId failed")
} }
else
Log.w(TAG, "Creation of hardware NS for $sessionId failed")
} }
else else
Log.i(TAG, "Hardware NS is NOT available") Log.i(TAG, "Hardware NS is NOT available")
@ -1532,10 +1519,10 @@ object Utils {
return if (Build.VERSION.SDK_INT >= 29) { return if (Build.VERSION.SDK_INT >= 29) {
val roleManager = ctx.getSystemService(ROLE_SERVICE) as RoleManager val roleManager = ctx.getSystemService(ROLE_SERVICE) as RoleManager
roleManager.isRoleHeld(RoleManager.ROLE_SMS) roleManager.isRoleHeld(RoleManager.ROLE_SMS)
} else { }
else
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
android.provider.Telephony.Sms.getDefaultSmsPackage(ctx) == ctx.packageName android.provider.Telephony.Sms.getDefaultSmsPackage(ctx) == ctx.packageName
}
} }
@Suppress("unused") @Suppress("unused")