first commit

This commit is contained in:
ganfra
2018-10-03 17:56:33 +02:00
commit b406e8301a
94 changed files with 1825 additions and 0 deletions

1
matrix-sdk-core/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build

View File

@ -0,0 +1,25 @@
apply plugin: 'java-library'
apply plugin: "kotlin"
apply plugin: 'kotlin-kapt'
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation fileTree(dir: 'libs', include: ['*.jar'])
// Network
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-moshi:2.4.0'
implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.okio:okio:1.15.0'
implementation 'com.squareup.moshi:moshi-kotlin:1.7.0'
kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.7.0'
// DI
implementation "org.koin:koin-core:$koin_version"
implementation "org.koin:koin-core-ext:$koin_version"
testImplementation 'junit:junit:4.12'
}

View File

@ -0,0 +1,21 @@
package im.vector.matrix.core.api
import im.vector.matrix.core.api.login.data.HomeServerConnectionConfig
import im.vector.matrix.core.internal.DefaultSession
import im.vector.matrix.core.internal.MatrixModule
import im.vector.matrix.core.internal.network.NetworkModule
import org.koin.standalone.StandAloneContext.loadKoinModules
class Matrix(matrixOptions: MatrixOptions) {
init {
val matrixModule = MatrixModule(matrixOptions)
val networkModule = NetworkModule()
loadKoinModules(listOf(matrixModule, networkModule))
}
fun createSession(homeServerConnectionConfig: HomeServerConnectionConfig): Session {
return DefaultSession(homeServerConnectionConfig)
}
}

View File

@ -0,0 +1,11 @@
package im.vector.matrix.core.api
import im.vector.matrix.core.api.failure.Failure
interface MatrixCallback<in T> {
fun onSuccess(data: T?)
fun onFailure(failure: Failure)
}

View File

@ -0,0 +1,5 @@
package im.vector.matrix.core.api
import java.util.concurrent.Executor
data class MatrixOptions(val mainExecutor: Executor)

View File

@ -0,0 +1,11 @@
package im.vector.matrix.core.api
import im.vector.matrix.core.api.login.Authenticator
interface Session {
fun authenticator(): Authenticator
fun close()
}

View File

@ -0,0 +1,4 @@
package im.vector.matrix.core.api.events
data class Event(val sender: String,
val eventType: EventType)

View File

@ -0,0 +1,41 @@
package im.vector.matrix.core.api.events
sealed class EventType(val str: String) {
object Presence : EventType("m.presence")
object Message : EventType("m.room.message")
object Sticker : EventType("m.sticker")
object Encrypted : EventType("m.room.encrypted")
object Encryption : EventType("m.room.encryption")
object Feedback : EventType("m.room.message.feedback")
object Typing : EventType("m.typing")
object Redaction : EventType("m.room.redaction")
object Receipt : EventType("m.receipt")
object Tag : EventType("m.tag")
object RoomKey : EventType("m.room_key")
object FullyRead : EventType("m.fully_read")
object Plumbing : EventType("m.room.plumbing")
object BotOptions : EventType("m.room.bot.options")
object KeyRequest : EventType("m.room_key_request")
object ForwardedRoomKey : EventType("m.forwarded_room_key")
object PreviewUrls : EventType("org.matrix.room.preview_urls")
class StateEvents {
object RoomName : EventType("m.room.name")
object Topic : EventType("m.room.topic")
object Avatar : EventType("m.room.avatar")
object Member : EventType("m.room.member")
object ThirdPartyInvite : EventType("m.room.third_party_invite")
object Create : EventType("m.room.userIdentifier")
object JoinRules : EventType("m.room.join_rules")
object GuestAccess : EventType("m.room.guest_access")
object PowerLevels : EventType("m.room.power_levels")
object Aliases : EventType("m.room.aliases")
object Tombstone : EventType("m.room.tombstone")
object CanonicalAlias : EventType("m.room.canonical_alias")
object HistoryVisibility : EventType("m.room.history_visibility")
object RelatedGroups : EventType("m.room.related_groups")
}
}

View File

@ -0,0 +1,11 @@
package im.vector.matrix.core.api.failure
sealed class Failure {
data class Unknown(val exception: Exception? = null) : Failure()
object NetworkConnection : Failure()
data class ServerError(val error: MatrixError) : Failure()
abstract class FeatureFailure : Failure()
}

View File

@ -0,0 +1,33 @@
package im.vector.matrix.core.api.failure
import com.squareup.moshi.Json
data class MatrixError(@Json(name = "errcode") val code: String,
@Json(name = "error") val message: String) {
companion object {
const val FORBIDDEN = "M_FORBIDDEN"
const val UNKNOWN = "M_UNKNOWN"
const val UNKNOWN_TOKEN = "M_UNKNOWN_TOKEN"
const val BAD_JSON = "M_BAD_JSON"
const val NOT_JSON = "M_NOT_JSON"
const val NOT_FOUND = "M_NOT_FOUND"
const val LIMIT_EXCEEDED = "M_LIMIT_EXCEEDED"
const val USER_IN_USE = "M_USER_IN_USE"
const val ROOM_IN_USE = "M_ROOM_IN_USE"
const val BAD_PAGINATION = "M_BAD_PAGINATION"
const val UNAUTHORIZED = "M_UNAUTHORIZED"
const val OLD_VERSION = "M_OLD_VERSION"
const val UNRECOGNIZED = "M_UNRECOGNIZED"
const val LOGIN_EMAIL_URL_NOT_YET = "M_LOGIN_EMAIL_URL_NOT_YET"
const val THREEPID_AUTH_FAILED = "M_THREEPID_AUTH_FAILED"
// Error code returned by the server when no account matches the given 3pid
const val THREEPID_NOT_FOUND = "M_THREEPID_NOT_FOUND"
const val THREEPID_IN_USE = "M_THREEPID_IN_USE"
const val SERVER_NOT_TRUSTED = "M_SERVER_NOT_TRUSTED"
const val TOO_LARGE = "M_TOO_LARGE"
const val M_CONSENT_NOT_GIVEN = "M_CONSENT_NOT_GIVEN"
const val RESOURCE_LIMIT_EXCEEDED = "M_RESOURCE_LIMIT_EXCEEDED"
}
}

View File

@ -0,0 +1,11 @@
package im.vector.matrix.core.api.login
import im.vector.matrix.core.api.MatrixCallback
import im.vector.matrix.core.api.util.Cancelable
import im.vector.matrix.core.api.login.data.Credentials
interface Authenticator {
fun authenticate(login: String, password: String, callback: MatrixCallback<Credentials>): Cancelable
}

View File

@ -0,0 +1,6 @@
package im.vector.matrix.core.api.login
import im.vector.matrix.core.api.login.data.Credentials
import im.vector.matrix.core.api.storage.MxStore
interface CredentialsStore : MxStore<Credentials, String>

View File

@ -0,0 +1,11 @@
package im.vector.matrix.core.api.login.data
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class Credentials(@Json(name = "user_id") val userId: String,
@Json(name = "home_server") val homeServer: String,
@Json(name = "access_token") val accessToken: String,
@Json(name = "refresh_token") val refreshToken: String?,
@Json(name = "device_id") val deviceId: String?)

View File

@ -0,0 +1,9 @@
package im.vector.matrix.core.api.login.data
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class HomeServerConnectionConfig(
// the home server URI
val hsUri: String
)

View File

@ -0,0 +1,11 @@
package im.vector.matrix.core.api.storage
import im.vector.matrix.core.api.util.Cancelable
interface MxQuery<DATA> {
fun find(): DATA?
fun subscribe(observer: MxQueryDataObserver<DATA>): Cancelable
}

View File

@ -0,0 +1,7 @@
package im.vector.matrix.core.api.storage
interface MxQueryBuilder<DATA, QUERY : MxQuery<DATA>> {
fun build(): QUERY
}

View File

@ -0,0 +1,5 @@
package im.vector.matrix.core.api.storage;
public interface MxQueryDataObserver<DATA> {
void onData(DATA data);
}

View File

@ -0,0 +1,13 @@
package im.vector.matrix.core.api.storage
interface MxStore<DATA, KEY> {
fun put(data: DATA)
fun remove(data: DATA)
fun get(id: KEY): DATA?
fun getAll(): List<DATA>
}

View File

@ -0,0 +1,5 @@
package im.vector.matrix.core.api.util
interface Cancelable {
fun cancel()
}

View File

@ -0,0 +1,57 @@
package im.vector.matrix.core.api.util
interface Logger {
/** Log a verbose message with optional format args. */
fun v(message: String, vararg args: Any)
/** Log a verbose exception and a message with optional format args. */
fun v(t: Throwable, message: String, vararg args: Any)
/** Log a verbose exception. */
fun v(t: Throwable)
/** Log a debug message with optional format args. */
fun d(message: String, vararg args: Any)
/** Log a debug exception and a message with optional format args. */
fun d(t: Throwable, message: String, vararg args: Any)
/** Log a debug exception. */
fun d(t: Throwable)
/** Log an info message with optional format args. */
fun i(message: String, vararg args: Any)
/** Log an info exception and a message with optional format args. */
fun i(t: Throwable, message: String, vararg args: Any)
/** Log an info exception. */
fun i(t: Throwable)
/** Log a warning message with optional format args. */
fun w(message: String, vararg args: Any)
/** Log a warning exception and a message with optional format args. */
fun w(t: Throwable, message: String, vararg args: Any)
/** Log a warning exception. */
fun w(t: Throwable)
/** Log an error message with optional format args. */
fun e(message: String, vararg args: Any)
/** Log an error exception and a message with optional format args. */
fun e(t: Throwable, message: String, vararg args: Any)
/** Log an error exception. */
fun e(t: Throwable)
/** Log an assert message with optional format args. */
fun wtf(message: String, vararg args: Any)
/** Log an assert exception and a message with optional format args. */
fun wtf(t: Throwable, message: String, vararg args: Any)
/** Log an assert exception. */
fun wtf(t: Throwable)
}

View File

@ -0,0 +1,37 @@
package im.vector.matrix.core.internal
import im.vector.matrix.core.api.Session
import im.vector.matrix.core.api.login.Authenticator
import im.vector.matrix.core.api.login.data.HomeServerConnectionConfig
import im.vector.matrix.core.internal.login.LoginModule
import org.koin.core.scope.Scope
import org.koin.standalone.KoinComponent
import org.koin.standalone.StandAloneContext
import org.koin.standalone.getKoin
import org.koin.standalone.inject
class DefaultSession(val homeServerConnectionConfig: HomeServerConnectionConfig) : Session, KoinComponent {
private val authenticator by inject<Authenticator>()
private val scope: Scope
init {
val loginModule = LoginModule(homeServerConnectionConfig)
StandAloneContext.loadKoinModules(listOf(loginModule))
scope = getKoin().createScope(SCOPE)
}
override fun authenticator(): Authenticator {
return authenticator
}
override fun close() {
scope.close()
}
companion object {
const val SCOPE: String = "session"
}
}

View File

@ -0,0 +1,9 @@
package im.vector.matrix.core.internal
import kotlinx.coroutines.CoroutineDispatcher
data class MatrixCoroutineDispatchers(
val io: CoroutineDispatcher,
val computation: CoroutineDispatcher,
val main: CoroutineDispatcher
)

View File

@ -0,0 +1,27 @@
package im.vector.matrix.core.internal
import im.vector.matrix.core.api.MatrixOptions
import im.vector.matrix.core.api.login.CredentialsStore
import im.vector.matrix.core.internal.login.db.InMemoryCredentialsStore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.asCoroutineDispatcher
import org.koin.dsl.context.ModuleDefinition
import org.koin.dsl.module.Module
import org.koin.dsl.module.module
class MatrixModule(private val options: MatrixOptions) : Module {
override fun invoke(): ModuleDefinition = module {
single {
MatrixCoroutineDispatchers(io = Dispatchers.IO, computation = Dispatchers.IO, main = options.mainExecutor.asCoroutineDispatcher())
}
single {
InMemoryCredentialsStore() as CredentialsStore
}
}.invoke()
}

View File

@ -0,0 +1,37 @@
package im.vector.matrix.core.internal.login
import com.squareup.moshi.Moshi
import im.vector.matrix.core.api.MatrixCallback
import im.vector.matrix.core.api.login.Authenticator
import im.vector.matrix.core.api.login.CredentialsStore
import im.vector.matrix.core.api.login.data.Credentials
import im.vector.matrix.core.api.util.Cancelable
import im.vector.matrix.core.internal.MatrixCoroutineDispatchers
import im.vector.matrix.core.internal.util.map
import im.vector.matrix.core.internal.login.data.PasswordLoginParams
import im.vector.matrix.core.internal.network.executeRequest
import im.vector.matrix.core.internal.util.CancelableCoroutine
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class DefaultAuthenticator(private val loginApi: LoginApi,
private val jsonMapper: Moshi,
private val coroutineDispatchers: MatrixCoroutineDispatchers,
private val credentialsStore: CredentialsStore) : Authenticator {
override fun authenticate(login: String, password: String, callback: MatrixCallback<Credentials>): Cancelable {
val job = GlobalScope.launch(coroutineDispatchers.main) {
val loginParams = PasswordLoginParams.userIdentifier(login, password, "Mobile")
val loginResult = executeRequest<Credentials> {
apiCall = loginApi.login(loginParams)
moshi = jsonMapper
dispatcher = coroutineDispatchers.io
}.map {
it?.apply { credentialsStore.put(it) }
}
loginResult.either({ callback.onFailure(it) }, { callback.onSuccess(it) })
}
return CancelableCoroutine(job)
}
}

View File

@ -0,0 +1,24 @@
package im.vector.matrix.core.internal.login
import im.vector.matrix.core.api.login.data.Credentials
import im.vector.matrix.core.internal.login.data.PasswordLoginParams
import im.vector.matrix.core.internal.network.NetworkConstants
import kotlinx.coroutines.Deferred
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.POST
/**
* The login REST API.
*/
interface LoginApi {
/**
* Pass params to the server for the current login phase.
*
* @param loginParams the login parameters
*/
@POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "login")
fun login(@Body loginParams: PasswordLoginParams): Deferred<Response<Credentials>>
}

View File

@ -0,0 +1,33 @@
package im.vector.matrix.core.internal.login
import im.vector.matrix.core.api.login.Authenticator
import im.vector.matrix.core.api.login.data.HomeServerConnectionConfig
import im.vector.matrix.core.internal.DefaultSession
import org.koin.dsl.context.ModuleDefinition
import org.koin.dsl.module.Module
import org.koin.dsl.module.module
import retrofit2.Retrofit
class LoginModule(private val connectionConfig: HomeServerConnectionConfig) : Module {
override fun invoke(): ModuleDefinition = module {
scope(DefaultSession.SCOPE) {
Retrofit.Builder()
.client(get())
.baseUrl(connectionConfig.hsUri)
.addConverterFactory(get())
.addCallAdapterFactory(get())
.build()
}
scope(DefaultSession.SCOPE) {
val retrofit: Retrofit = get()
retrofit.create(LoginApi::class.java)
}
scope(DefaultSession.SCOPE) {
DefaultAuthenticator(get(), get(), get(), get()) as Authenticator
}
}.invoke()
}

View File

@ -0,0 +1,7 @@
package im.vector.matrix.core.internal.login.data
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class LoginFlow(val type: String,
val stages: List<String>)

View File

@ -0,0 +1,6 @@
package im.vector.matrix.core.internal.login.data
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class LoginFlowResponse(val flows: List<LoginFlow>)

View File

@ -0,0 +1,12 @@
package im.vector.matrix.core.internal.login.data
object LoginFlowTypes {
const val PASSWORD = "m.login.password"
const val OAUTH2 = "m.login.oauth2"
const val EMAIL_CODE = "m.login.email.code"
const val EMAIL_URL = "m.login.email.url"
const val EMAIL_IDENTITY = "m.login.email.identity"
const val MSISDN = "m.login.msisdn"
const val RECAPTCHA = "m.login.recaptcha"
const val DUMMY = "m.login.dummy"
}

View File

@ -0,0 +1,5 @@
package im.vector.matrix.core.internal.login.data
interface LoginParams {
val type: String
}

View File

@ -0,0 +1,47 @@
package im.vector.matrix.core.internal.login.data
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class PasswordLoginParams(@Json(name = "identifier") val identifier: Map<String, String>,
@Json(name = "password") val password: String,
@Json(name = "type") override val type: String,
@Json(name = "initial_device_display_name") val deviceDisplayName: String?,
@Json(name = "device_id") val deviceId: String?) : LoginParams {
companion object {
val IDENTIFIER_KEY_TYPE_USER = "m.id.user"
val IDENTIFIER_KEY_TYPE_THIRD_PARTY = "m.id.thirdparty"
val IDENTIFIER_KEY_TYPE_PHONE = "m.id.phone"
val IDENTIFIER_KEY_TYPE = "type"
val IDENTIFIER_KEY_MEDIUM = "medium"
val IDENTIFIER_KEY_ADDRESS = "address"
val IDENTIFIER_KEY_USER = "user"
val IDENTIFIER_KEY_COUNTRY = "country"
val IDENTIFIER_KEY_NUMBER = "number"
fun userIdentifier(user: String, password: String, deviceDisplayName: String? = null, deviceId: String? = null): PasswordLoginParams {
val identifier = HashMap<String, String>()
identifier[IDENTIFIER_KEY_TYPE] = IDENTIFIER_KEY_TYPE_USER
identifier[IDENTIFIER_KEY_USER] = user
return PasswordLoginParams(identifier, password, LoginFlowTypes.PASSWORD, deviceDisplayName, deviceId)
}
fun thirdPartyIdentifier(medium: String, address: String, password: String, deviceDisplayName: String? = null, deviceId: String? = null): PasswordLoginParams {
val identifier = HashMap<String, String>()
identifier[IDENTIFIER_KEY_TYPE] = IDENTIFIER_KEY_TYPE_THIRD_PARTY
identifier[IDENTIFIER_KEY_MEDIUM] = medium
identifier[IDENTIFIER_KEY_ADDRESS] = address
return PasswordLoginParams(identifier, password, LoginFlowTypes.PASSWORD, deviceDisplayName, deviceId)
}
}
}

View File

@ -0,0 +1,26 @@
package im.vector.matrix.core.internal.login.db
import im.vector.matrix.core.api.login.CredentialsStore
import im.vector.matrix.core.api.login.data.Credentials
class InMemoryCredentialsStore : CredentialsStore {
var credentials: Credentials? = null
override fun put(data: Credentials) = synchronized(this) {
credentials = data.copy()
}
override fun remove(data: Credentials) = synchronized(this) {
credentials = null
}
override fun get(id: String): Credentials? = synchronized(this) {
return credentials
}
override fun getAll(): List<Credentials> = synchronized(this) {
return credentials?.let { listOf(it) } ?: emptyList()
}
}

View File

@ -0,0 +1,8 @@
package im.vector.matrix.core.internal.network
object NetworkConstants {
const val URI_API_PREFIX_PATH = "_matrix/client/"
const val URI_API_PREFIX_PATH_R0 = "_matrix/client/r0/"
}

View File

@ -0,0 +1,30 @@
package im.vector.matrix.core.internal.network
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.OkHttpClient
import org.koin.dsl.context.ModuleDefinition
import org.koin.dsl.module.Module
import org.koin.dsl.module.module
import retrofit2.CallAdapter
import retrofit2.Converter
import retrofit2.converter.moshi.MoshiConverterFactory
class NetworkModule() : Module {
override fun invoke(): ModuleDefinition = module {
single { OkHttpClient.Builder().build() }
single { Moshi.Builder().add(KotlinJsonAdapterFactory()).build() }
single {
MoshiConverterFactory.create(get()) as Converter.Factory
}
single {
CoroutineCallAdapterFactory() as CallAdapter.Factory
}
}.invoke()
}

View File

@ -0,0 +1,56 @@
package im.vector.matrix.core.internal.network
import com.squareup.moshi.Moshi
import im.vector.matrix.core.api.failure.Failure
import im.vector.matrix.core.api.failure.MatrixError
import im.vector.matrix.core.internal.util.Either
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.withContext
import okhttp3.ResponseBody
import retrofit2.Response
import java.io.IOException
suspend inline fun <DATA> executeRequest(block: Request<DATA>.() -> Unit) = Request<DATA>().apply(block).execute()
class Request<DATA> {
lateinit var apiCall: Deferred<Response<DATA>>
lateinit var moshi: Moshi
lateinit var dispatcher: CoroutineDispatcher
suspend fun execute(): Either<Failure, DATA?> = withContext(dispatcher) {
return@withContext try {
val response = apiCall.await()
if (response.isSuccessful) {
val result = response.body()
Either.Right(result)
} else {
val failure = manageFailure(response.errorBody())
Either.Left(failure)
}
} catch (e: Exception) {
when (e) {
is IOException -> Either.Left(Failure.NetworkConnection)
else -> Either.Left(Failure.Unknown(e))
}
}
}
private fun manageFailure(errorBody: ResponseBody?): Failure {
return try {
val matrixError = errorBody?.let {
val matrixErrorAdapter = moshi.adapter(MatrixError::class.java)
matrixErrorAdapter.fromJson(errorBody.source())
} ?: throw RuntimeException("Matrix error should not be null")
Failure.ServerError(matrixError)
} catch (e: Exception) {
Failure.Unknown(e)
}
}
}

View File

@ -0,0 +1,12 @@
package im.vector.matrix.core.internal.util
import im.vector.matrix.core.api.util.Cancelable
import kotlinx.coroutines.Job
class CancelableCoroutine(private val job: Job) : Cancelable {
override fun cancel() {
job.cancel()
}
}

View File

@ -0,0 +1,35 @@
package im.vector.matrix.core.internal.util
sealed class Either<out L, out R> {
/** * Represents the left side of [Either] class which by convention is a "Failure". */
data class Left<out L>(val a: L) : Either<L, Nothing>()
/** * Represents the right side of [Either] class which by convention is a "Success". */
data class Right<out R>(val b: R) : Either<Nothing, R>()
val isRight get() = this is Right<R>
val isLeft get() = this is Left<L>
fun <L> left(a: L) = Left(a)
fun <R> right(b: R) = Right(b)
fun either(fnL: (L) -> Any, fnR: (R) -> Any): Any =
when (this) {
is Left -> fnL(a)
is Right -> fnR(b)
}
}
// Credits to Alex Hart -> https://proandroiddev.com/kotlins-nothing-type-946de7d464fb
// Composes 2 functions
fun <A, B, C> ((A) -> B).c(f: (B) -> C): (A) -> C = {
f(this(it))
}
fun <T, L, R> Either<L, R>.flatMap(fn: (R) -> Either<L, T>): Either<L, T> =
when (this) {
is Either.Left -> Either.Left(a)
is Either.Right -> fn(b)
}
fun <T, L, R> Either<L, R>.map(fn: (R) -> (T)): Either<L, T> = this.flatMap(fn.c(::right))