Make the sdk targeting android to win time

This commit is contained in:
ganfra
2018-10-04 15:19:03 +02:00
parent 54fb54a695
commit c4316d5055
80 changed files with 380 additions and 261 deletions

View File

@ -0,0 +1,21 @@
package im.vector.matrix.android.api
import im.vector.matrix.android.api.login.data.HomeServerConnectionConfig
import im.vector.matrix.android.internal.DefaultSession
import im.vector.matrix.android.internal.di.MatrixModule
import im.vector.matrix.android.internal.di.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.android.api
import im.vector.matrix.android.api.failure.Failure
interface MatrixCallback<in T> {
fun onSuccess(data: T?)
fun onFailure(failure: Failure)
}

View File

@ -0,0 +1,8 @@
package im.vector.matrix.android.api
import android.content.Context
import im.vector.matrix.android.api.thread.MainThreadExecutor
import java.util.concurrent.Executor
data class MatrixOptions(val context: Context,
val mainExecutor: Executor = MainThreadExecutor())

View File

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

View File

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

View File

@ -0,0 +1,41 @@
package im.vector.matrix.android.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.android.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.android.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.android.api.login
import im.vector.matrix.android.api.MatrixCallback
import im.vector.matrix.android.api.util.Cancelable
import im.vector.matrix.android.api.login.data.Credentials
interface Authenticator {
fun authenticate(login: String, password: String, callback: MatrixCallback<Credentials>): Cancelable
}

View File

@ -0,0 +1,11 @@
package im.vector.matrix.android.api.login
import im.vector.matrix.android.api.login.data.Credentials
interface CredentialsStore {
fun get(): Credentials?
fun save(credentials: Credentials)
}

View File

@ -0,0 +1,15 @@
package im.vector.matrix.android.api.login.data
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
@Entity
@JsonClass(generateAdapter = true)
data class Credentials(@Id var id: Long = 0,
@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.android.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,15 @@
package im.vector.matrix.android.api.persitence
import android.arch.paging.PagedList
interface Persister<DATA, KEY> {
fun put(data: DATA)
fun remove(data: DATA)
fun get(id: KEY): DATA?
fun getAll(): PagedList<DATA>
}

View File

@ -0,0 +1,11 @@
package im.vector.matrix.android.api.persitence
import im.vector.matrix.android.api.util.Cancelable
interface Query<DATA> {
fun find(): DATA
fun subscribe(observer: QueryDataObserver<DATA>): Cancelable
}

View File

@ -0,0 +1,7 @@
package im.vector.matrix.android.api.persitence
interface QueryBuilder<DATA, QUERY : Query<DATA>> {
fun build(): QUERY
}

View File

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

View File

@ -1,4 +1,4 @@
package im.vector.matrix.android.thread;
package im.vector.matrix.android.api.thread;
import android.os.Handler;
import android.os.Looper;

View File

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

View File

@ -0,0 +1,57 @@
package im.vector.matrix.android.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.android.internal
import im.vector.matrix.android.api.Session
import im.vector.matrix.android.api.login.Authenticator
import im.vector.matrix.android.api.login.data.HomeServerConnectionConfig
import im.vector.matrix.android.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.android.internal
import kotlinx.coroutines.CoroutineDispatcher
data class MatrixCoroutineDispatchers(
val io: CoroutineDispatcher,
val computation: CoroutineDispatcher,
val main: CoroutineDispatcher
)

View File

@ -0,0 +1,41 @@
package im.vector.matrix.android.internal.di
import im.vector.matrix.android.api.MatrixOptions
import im.vector.matrix.android.api.login.CredentialsStore
import im.vector.matrix.android.api.login.data.Credentials
import im.vector.matrix.android.api.login.data.MyObjectBox
import im.vector.matrix.android.internal.MatrixCoroutineDispatchers
import im.vector.matrix.android.internal.login.db.ObjectBoxCredentialsStore
import io.objectbox.Box
import io.objectbox.BoxStore
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 {
MyObjectBox.builder().androidContext(options.context).build()
}
single {
val boxStore = get() as BoxStore
boxStore.boxFor(Credentials::class.java) as Box<Credentials>
}
single {
ObjectBoxCredentialsStore(get()) as CredentialsStore
}
}.invoke()
}

View File

@ -0,0 +1,47 @@
package im.vector.matrix.android.internal.di
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import im.vector.matrix.android.internal.network.AccessTokenInterceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
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 {
AccessTokenInterceptor(get())
}
single {
HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }
}
single {
OkHttpClient.Builder()
.addInterceptor(get() as AccessTokenInterceptor)
.addInterceptor(get() as HttpLoggingInterceptor)
.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,37 @@
package im.vector.matrix.android.internal.login
import com.squareup.moshi.Moshi
import im.vector.matrix.android.api.MatrixCallback
import im.vector.matrix.android.api.login.Authenticator
import im.vector.matrix.android.api.login.CredentialsStore
import im.vector.matrix.android.api.login.data.Credentials
import im.vector.matrix.android.api.util.Cancelable
import im.vector.matrix.android.internal.MatrixCoroutineDispatchers
import im.vector.matrix.android.internal.util.map
import im.vector.matrix.android.internal.login.data.PasswordLoginParams
import im.vector.matrix.android.internal.network.executeRequest
import im.vector.matrix.android.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.save(it) }
}
loginResult.either({ callback.onFailure(it) }, { callback.onSuccess(it) })
}
return CancelableCoroutine(job)
}
}

View File

@ -0,0 +1,24 @@
package im.vector.matrix.android.internal.login
import im.vector.matrix.android.api.login.data.Credentials
import im.vector.matrix.android.internal.login.data.PasswordLoginParams
import im.vector.matrix.android.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.android.internal.login
import im.vector.matrix.android.api.login.Authenticator
import im.vector.matrix.android.api.login.data.HomeServerConnectionConfig
import im.vector.matrix.android.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.android.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.android.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.android.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.android.internal.login.data
interface LoginParams {
val type: String
}

View File

@ -0,0 +1,47 @@
package im.vector.matrix.android.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,18 @@
package im.vector.matrix.android.internal.login.db
import im.vector.matrix.android.api.login.CredentialsStore
import im.vector.matrix.android.api.login.data.Credentials
class InMemoryCredentialsStore : CredentialsStore {
var credentials: Credentials? = null
override fun get(): Credentials? {
return credentials
}
override fun save(credentials: Credentials) {
this.credentials = credentials.copy()
}
}

View File

@ -0,0 +1,17 @@
package im.vector.matrix.android.internal.login.db
import im.vector.matrix.android.api.login.CredentialsStore
import im.vector.matrix.android.api.login.data.Credentials
import io.objectbox.Box
class ObjectBoxCredentialsStore(private val box: Box<Credentials>) : CredentialsStore {
override fun save(credentials: Credentials) {
box.put(credentials)
}
override fun get(): Credentials? {
return box.all.firstOrNull()
}
}

View File

@ -0,0 +1,22 @@
package im.vector.matrix.android.internal.network
import im.vector.matrix.android.api.login.CredentialsStore
import okhttp3.Interceptor
import okhttp3.Response
class AccessTokenInterceptor(private val credentialsStore: CredentialsStore) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
val newRequestBuilder = request.newBuilder()
// Add the access token to all requests if it is set
val credentials = credentialsStore.get()
credentials?.let {
newRequestBuilder.addHeader("Authorization", "Bearer " + it.accessToken)
}
request = newRequestBuilder.build()
return chain.proceed(request)
}
}

View File

@ -0,0 +1,8 @@
package im.vector.matrix.android.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,56 @@
package im.vector.matrix.android.internal.network
import com.squareup.moshi.Moshi
import im.vector.matrix.android.api.failure.Failure
import im.vector.matrix.android.api.failure.MatrixError
import im.vector.matrix.android.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,15 @@
package im.vector.matrix.android.internal.sync
import im.vector.matrix.android.internal.network.NetworkConstants
import im.vector.matrix.android.internal.sync.data.SyncResponse
import kotlinx.coroutines.Deferred
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.QueryMap
interface SyncAPI {
@GET(NetworkConstants.URI_API_PREFIX_PATH_R0 + "sync")
fun sync(@QueryMap params: Map<String, Any>): Deferred<Response<SyncResponse>>
}

View File

@ -0,0 +1,53 @@
/*
* Copyright 2014 OpenMarket Ltd
* Copyright 2017 Vector Creations Ltd
* Copyright 2018 New Vector Ltd
*
* 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
*
* http://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 im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
/**
* This class describes the device information
*/
@JsonClass(generateAdapter = true)
data class DeviceInfo(
/**
* The owner user id
*/
var user_id: String? = null,
/**
* The device id
*/
var device_id: String? = null,
/**
* The device display name
*/
var display_name: String? = null,
/**
* The last time this device has been seen.
*/
var last_seen_ts: Long = 0,
/**
* The last ip address
*/
var last_seen_ip: String? = null
)

View File

@ -0,0 +1,29 @@
/*
* Copyright 2017 Vector Creations Ltd
*
* 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
*
* http://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 im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
/**
* This class describes the device list response from a sync request
*/
@JsonClass(generateAdapter = true)
data class DeviceListResponse(
// user ids list which have new crypto devices
val changed: List<String>? = null,
// List of user ids who are no more tracked.
val left: List<String>? = null)

View File

@ -0,0 +1,9 @@
package im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class DeviceOneTimeKeysCountSyncResponse(
var signed_curve25519: Int? = null
)

View File

@ -0,0 +1,26 @@
/*
* Copyright 2014 OpenMarket Ltd
*
* 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
*
* http://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 im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
/**
* This class describes the
*/
@JsonClass(generateAdapter = true)
data class DevicesListResponse(
var devices: List<DeviceInfo>? = null
)

View File

@ -0,0 +1,32 @@
/*
* Copyright 2016 OpenMarket Ltd
*
* 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
*
* http://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 im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
// InvitedRoomSync represents a room invitation during server sync v2.
@JsonClass(generateAdapter = true)
data class InvitedRoomSync(
/**
* The state of a room that the user has been invited to. These state events may only have the 'sender', 'type', 'state_key'
* and 'content' keys present. These events do not replace any state that the client already has for the room, for example if
* the client has archived the room. Instead the client should keep two separate copies of the state: the one from the 'invite_state'
* and one from the archived 'state'. If the client joins the room then the current state will be given as a delta against the
* archived 'state' not the 'invite_state'.
*/
var inviteState: RoomInviteState? = null
)

View File

@ -0,0 +1,14 @@
package im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
import im.vector.matrix.android.api.events.Event
// PresenceSyncResponse represents the updates to the presence status of other users during server sync v2.
@JsonClass(generateAdapter = true)
data class PresenceSyncResponse(
/**
* List of presence events (array of Event with type m.presence).
*/
var events: List<Event>? = null
)

View File

@ -0,0 +1,30 @@
/*
* Copyright 2016 OpenMarket Ltd
*
* 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
*
* http://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 im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
import im.vector.matrix.android.api.events.Event
// RoomInviteState represents the state of a room that the user has been invited to.
@JsonClass(generateAdapter = true)
data class RoomInviteState(
/**
* List of state events (array of MXEvent).
*/
var events: List<Event>? = null
)

View File

@ -0,0 +1,41 @@
package im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
import im.vector.matrix.android.api.events.Event
/**
* Class representing a room from a JSON response from room or global initial sync.
*/
@JsonClass(generateAdapter = true)
data class RoomResponse(
// The room identifier.
var roomId: String? = null,
// The last recent messages of the room.
var messages: TokensChunkResponse<Event>? = null,
// The state events.
var state: List<Event>? = null,
// The private data that this user has attached to this room.
var accountData: List<Event>? = null,
// The current user membership in this room.
var membership: String? = null,
// The room visibility (public/private).
var visibility: String? = null,
// The matrix id of the inviter in case of pending invitation.
var inviter: String? = null,
// The invite event if membership is invite.
var invite: Event? = null,
// The presence status of other users (Provided in case of room initial sync @see http://matrix.org/docs/api/client-server/#!/-rooms/get_room_sync_data)).
var presence: List<Event>? = null,
// The read receipts (Provided in case of room initial sync).
var receipts: List<Event>? = null
)

View File

@ -0,0 +1,48 @@
/*
* Copyright 2016 OpenMarket Ltd
*
* 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
*
* http://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 im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
// RoomSync represents the response for a room during server sync v2.
@JsonClass(generateAdapter = true)
data class RoomSync(
/**
* The state updates for the room.
*/
var state: RoomSyncState? = null,
/**
* The timeline of messages and state changes in the room.
*/
var timeline: RoomSyncTimeline? = null,
/**
* The ephemeral events in the room that aren't recorded in the timeline or state of the room (e.g. typing, receipts).
*/
var ephemeral: RoomSyncEphemeral? = null,
/**
* The account data events for the room (e.g. tags).
*/
var accountData: RoomSyncAccountData? = null,
/**
* The notification counts for the room.
*/
var unreadNotifications: RoomSyncUnreadNotifications? = null
)

View File

@ -0,0 +1,12 @@
package im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
import im.vector.matrix.android.api.events.Event
@JsonClass(generateAdapter = true)
data class RoomSyncAccountData(
/**
* List of account data events (array of Event).
*/
var events: List<Event>? = null
)

View File

@ -0,0 +1,14 @@
package im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
import im.vector.matrix.android.api.events.Event
// RoomSyncEphemeral represents the ephemeral events in the room that aren't recorded in the timeline or state of the room (e.g. typing).
@JsonClass(generateAdapter = true)
data class RoomSyncEphemeral(
/**
* List of ephemeral events (array of Event).
*/
var events: List<Event>? = null
)

View File

@ -0,0 +1,29 @@
/*
* Copyright 2016 OpenMarket Ltd
*
* 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
*
* http://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 im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
import im.vector.matrix.android.api.events.Event
// RoomSyncState represents the state updates for a room during server sync v2.
@JsonClass(generateAdapter = true)
data class RoomSyncState(
/**
* List of state events (array of Event). The resulting state corresponds to the *start* of the timeline.
*/
val events: List<Event>? = null)

View File

@ -0,0 +1,25 @@
package im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
import im.vector.matrix.android.api.events.Event
// RoomSyncTimeline represents the timeline of messages and state changes for a room during server sync v2.
@JsonClass(generateAdapter = true)
data class RoomSyncTimeline(
/**
* List of events (array of Event).
*/
var events: List<Event>? = null,
/**
* Boolean which tells whether there are more events on the server
*/
var limited: Boolean = false,
/**
* If the batch was limited then this is a token that can be supplied to the server to retrieve more events
*/
var prevBatch: String? = null
)

View File

@ -0,0 +1,25 @@
package im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
import im.vector.matrix.android.api.events.Event
/**
* `MXRoomSyncUnreadNotifications` represents the unread counts for a room.
*/
@JsonClass(generateAdapter = true)
data class RoomSyncUnreadNotifications(
/**
* List of account data events (array of Event).
*/
val events: List<Event>? = null,
/**
* The number of unread messages that match the push notification rules.
*/
val notificationCount: Int? = null,
/**
* The number of highlighted unread messages (subset of notifications).
*/
val highlightCount: Int? = null)

View File

@ -0,0 +1,36 @@
/*
* Copyright 2016 OpenMarket Ltd
*
* 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
*
* http://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 im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
// RoomsSyncResponse represents the rooms list in server sync v2 response.
@JsonClass(generateAdapter = true)
data class RoomsSyncResponse(
/**
* Joined rooms: keys are rooms ids.
*/
var join: Map<String, RoomSync>? = null,
/**
* Invitations. The rooms that the user has been invited to: keys are rooms ids.
*/
var invite: Map<String, InvitedRoomSync>? = null,
/**
* Left rooms. The rooms that the user has left or been banned from: keys are rooms ids.
*/
var leave: Map<String, RoomSync>? = null)

View File

@ -0,0 +1,44 @@
package im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
// SyncResponse represents the request response for server sync v2.
@JsonClass(generateAdapter = true)
data class SyncResponse(
/**
* The user private data.
*/
var accountData: Map<String, Any>? = null,
/**
* The opaque token for the end.
*/
var nextBatch: String? = null,
/**
* The updates to the presence status of other users.
*/
var presence: PresenceSyncResponse? = null,
/*
* Data directly sent to one of user's devices.
*/
var toDevice: ToDeviceSyncResponse? = null,
/**
* List of rooms.
*/
var rooms: RoomsSyncResponse? = null,
/**
* Devices list update
*/
var deviceLists: DeviceListResponse? = null,
/**
* One time keys management
*/
var deviceOneTimeKeysCount: DeviceOneTimeKeysCountSyncResponse? = null
)

View File

@ -0,0 +1,15 @@
package im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
import im.vector.matrix.android.api.events.Event
// ToDeviceSyncResponse represents the data directly sent to one of user's devices.
@JsonClass(generateAdapter = true)
data class ToDeviceSyncResponse(
/**
* List of direct-to-device events.
*/
var events: List<Event>? = null
)

View File

@ -0,0 +1,9 @@
package im.vector.matrix.android.internal.sync.data
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class TokensChunkResponse<T>(
var start: String? = null,
var end: String? = null,
var chunk: List<T>? = null)

View File

@ -0,0 +1,12 @@
package im.vector.matrix.android.internal.util
import im.vector.matrix.android.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.android.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))