session-android/libsession/src/main/java/org/session/libsession/utilities/OpenGroupUrlParser.kt
Harris d6d0c52745
Migrate old official open group locations for polling and adding (#932)
* feat: adding in first part of open group migrations and tests for migration logic / helpers

* feat: test code and migration logic for open groups in the case of no conflicts

* feat: add in extra test cases and refactor code for migrator

* refactor: migrate open group join URLs and references to server in adding new open groups to catch legacy and re-write it

* refactor: joining open groups using OpenGroupUrlParser.kt now

* fix: add in compile issues for renamed OpenGroupApi.kt from OpenGroupV2

* fix: prevent duplicates of http/https for new open group DNS and prevent adding new groups based on public key

* fix: room and server swapped parameters

* fix: replace default server for config messages

* fix: actually using public key to de-dupe didn't work for rooms

* build: bump version code and name
2022-08-22 09:27:35 +10:00

39 lines
1.7 KiB
Kotlin

package org.session.libsession.utilities
import okhttp3.HttpUrl
import org.session.libsession.messaging.open_groups.migrateLegacyServerUrl
object OpenGroupUrlParser {
sealed class Error(val description: String) : Exception(description) {
object MalformedURL : Error("Malformed URL.")
object NoRoom : Error("No room specified in the URL.")
object NoPublicKey : Error("No public key specified in the URL.")
object InvalidPublicKey : Error("Invalid public key provided.")
}
private const val suffix = "/"
private const val queryPrefix = "public_key"
fun parseUrl(string: String): V2OpenGroupInfo {
// URL has to start with 'http://'
val urlWithPrefix = if (!string.startsWith("http")) "http://$string" else string
// If the URL is malformed, throw an exception
val url = HttpUrl.parse(urlWithPrefix) ?: throw Error.MalformedURL
// Parse components
val server = HttpUrl.Builder().scheme(url.scheme()).host(url.host()).port(url.port()).build().toString().removeSuffix(suffix).migrateLegacyServerUrl()
val room = url.pathSegments().firstOrNull { !it.isNullOrEmpty() } ?: throw Error.NoRoom
val publicKey = url.queryParameter(queryPrefix) ?: throw Error.NoPublicKey
if (publicKey.length != 64) throw Error.InvalidPublicKey
// Return
return V2OpenGroupInfo(server,room,publicKey)
}
fun trimQueryParameter(string: String): String {
return string.substringBefore("?$queryPrefix")
}
}
class V2OpenGroupInfo(val server: String, val room: String, val serverPublicKey: String) {
fun joinUrl() = "$server/$room?public_key=$serverPublicKey"
}