Migrate mobile module to coroutines

This commit is contained in:
Mikołaj Pich 2020-06-14 19:05:55 +02:00
parent 0165e05aae
commit 08ec425b6a
19 changed files with 176 additions and 260 deletions

View file

@ -22,7 +22,6 @@ import io.github.wulkanowy.sdk.mobile.repository.RepositoryManager
import io.github.wulkanowy.sdk.mobile.school.Teacher import io.github.wulkanowy.sdk.mobile.school.Teacher
import io.github.wulkanowy.sdk.mobile.timetable.Lesson import io.github.wulkanowy.sdk.mobile.timetable.Lesson
import io.github.wulkanowy.signer.getPrivateKeyFromCert import io.github.wulkanowy.signer.getPrivateKeyFromCert
import io.reactivex.Single
import okhttp3.Interceptor import okhttp3.Interceptor
import okhttp3.logging.HttpLoggingInterceptor import okhttp3.logging.HttpLoggingInterceptor
import org.threeten.bp.LocalDate import org.threeten.bp.LocalDate
@ -83,21 +82,19 @@ class Mobile {
private lateinit var dictionaries: Dictionaries private lateinit var dictionaries: Dictionaries
fun getDictionaries(): Single<Dictionaries> { suspend fun getDictionaries(): Dictionaries {
if (::dictionaries.isInitialized) return Single.just(dictionaries) if (::dictionaries.isInitialized) return dictionaries
return mobile.getDictionaries(0, 0, classId).map { return mobile.getDictionaries(0, 0, classId)
it.apply { dictionaries = this } .apply { dictionaries = this }
}
} }
fun getCertificate(token: String, pin: String, symbol: String, deviceName: String, androidVer: String, firebaseToken: String): Single<CertificateResponse> { suspend fun getCertificate(token: String, pin: String, symbol: String, deviceName: String, androidVer: String, firebaseToken: String): CertificateResponse {
return routes.getRouteByToken(token).flatMap { baseUrl -> val baseUrl = routes.getRouteByToken(token)
serviceManager.getRegisterRepository(baseUrl, symbol).getCertificate(token, pin, deviceName, androidVer, firebaseToken) return serviceManager.getRegisterRepository(baseUrl, symbol).getCertificate(token, pin, deviceName, androidVer, firebaseToken)
}
} }
fun getStudents(certRes: CertificateResponse, apiKey: String = ""): Single<List<Student>> { suspend fun getStudents(certRes: CertificateResponse, apiKey: String = ""): List<Student> {
if (certRes.isError) when { if (certRes.isError) when {
certRes.message == "TokenDead" -> throw TokenDeadException(certRes.message) certRes.message == "TokenDead" -> throw TokenDeadException(certRes.message)
certRes.message == "TokenNotFound" -> throw TokenNotFoundException(certRes.message) certRes.message == "TokenNotFound" -> throw TokenNotFoundException(certRes.message)
@ -117,82 +114,73 @@ class Mobile {
.removeSurrounding("(", ")") .removeSurrounding("(", ")")
}, cert.certificatePfx) }, cert.certificatePfx)
return serviceManager.getRegisterRepository(cert.baseUrl).getStudents().map { students -> return serviceManager.getRegisterRepository(cert.baseUrl).getStudents().map {
students.map { it.copy().apply {
it.copy().apply { certificateKey = this@Mobile.certKey
certificateKey = this@Mobile.certKey privateKey = this@Mobile.privateKey
privateKey = this@Mobile.privateKey mobileBaseUrl = this@Mobile.baseUrl
mobileBaseUrl = this@Mobile.baseUrl
}
} }
} }
} }
fun getStudents(): Single<List<Student>> { suspend fun getStudents(): List<Student> {
return serviceManager.getRegisterRepository(baseUrl).getStudents() return serviceManager.getRegisterRepository(baseUrl).getStudents()
} }
fun getAttendance(start: LocalDate, end: LocalDate, classificationPeriodId: Int): Single<List<Attendance>> { suspend fun getAttendance(start: LocalDate, end: LocalDate, classificationPeriodId: Int): List<Attendance> {
return mobile.getAttendance(start, end, classId, classificationPeriodId, studentId) return mobile.getAttendance(start, end, classId, classificationPeriodId, studentId)
} }
fun getExams(start: LocalDate, end: LocalDate, classificationPeriodId: Int): Single<List<Exam>> { suspend fun getExams(start: LocalDate, end: LocalDate, classificationPeriodId: Int): List<Exam> {
return mobile.getExams(start, end, classId, classificationPeriodId, studentId) return mobile.getExams(start, end, classId, classificationPeriodId, studentId)
} }
fun getGrades(classificationPeriodId: Int): Single<Pair<List<Grade>, GradesSummaryResponse>> { suspend fun getGrades(classificationPeriodId: Int): Pair<List<Grade>, GradesSummaryResponse> {
return getGradesDetails(classificationPeriodId).flatMap { details -> return getGradesDetails(classificationPeriodId) to getGradesSummary(classificationPeriodId)
getGradesSummary(classificationPeriodId).map { summary ->
details to summary
}
}
} }
fun getGradesDetails(classificationPeriodId: Int): Single<List<Grade>> { suspend fun getGradesDetails(classificationPeriodId: Int): List<Grade> {
return mobile.getGradesDetails(classId, classificationPeriodId, studentId) return mobile.getGradesDetails(classId, classificationPeriodId, studentId)
} }
fun getGradesSummary(classificationPeriodId: Int): Single<GradesSummaryResponse> { suspend fun getGradesSummary(classificationPeriodId: Int): GradesSummaryResponse {
return mobile.getGradesSummary(classId, classificationPeriodId, studentId) return mobile.getGradesSummary(classId, classificationPeriodId, studentId)
} }
fun getHomework(start: LocalDate, end: LocalDate, classificationPeriodId: Int): Single<List<Homework>> { suspend fun getHomework(start: LocalDate, end: LocalDate, classificationPeriodId: Int): List<Homework> {
return mobile.getHomework(start, end, classId, classificationPeriodId, studentId) return mobile.getHomework(start, end, classId, classificationPeriodId, studentId)
} }
fun getNotes(classificationPeriodId: Int): Single<List<Note>> { suspend fun getNotes(classificationPeriodId: Int): List<Note> {
return mobile.getNotes(classificationPeriodId, studentId) return mobile.getNotes(classificationPeriodId, studentId)
} }
fun getTeachers(studentId: Int, semesterId: Int): Single<List<Teacher>> { suspend fun getTeachers(studentId: Int, semesterId: Int): List<Teacher> {
return mobile.getTeachers(studentId, semesterId) return mobile.getTeachers(studentId, semesterId)
} }
fun getMessages(start: LocalDateTime, end: LocalDateTime): Single<List<Message>> { suspend fun getMessages(start: LocalDateTime, end: LocalDateTime): List<Message> {
return mobile.getMessages(start, end, loginId, studentId) return mobile.getMessages(start, end, loginId, studentId)
} }
fun getMessagesSent(start: LocalDateTime, end: LocalDateTime): Single<List<Message>> { suspend fun getMessagesSent(start: LocalDateTime, end: LocalDateTime): List<Message> {
return mobile.getMessagesSent(start, end, loginId, studentId) return mobile.getMessagesSent(start, end, loginId, studentId)
} }
fun getMessagesDeleted(start: LocalDateTime, end: LocalDateTime): Single<List<Message>> { suspend fun getMessagesDeleted(start: LocalDateTime, end: LocalDateTime): List<Message> {
return mobile.getMessagesDeleted(start, end, loginId, studentId) return mobile.getMessagesDeleted(start, end, loginId, studentId)
} }
fun changeMessageStatus(messageId: Int, folder: String, status: String): Single<String> { suspend fun changeMessageStatus(messageId: Int, folder: String, status: String): String {
return mobile.changeMessageStatus(messageId, folder, status, loginId, studentId) return mobile.changeMessageStatus(messageId, folder, status, loginId, studentId)
} }
fun sendMessage(subject: String, content: String, recipients: List<Recipient>): Single<Message> { suspend fun sendMessage(subject: String, content: String, recipients: List<Recipient>): Message {
return getStudents().map { students -> val sender = getStudents().singleOrNull { it.loginId == loginId }?.name.orEmpty()
students.singleOrNull { it.loginId == loginId }?.name.orEmpty() return mobile.sendMessage(sender, subject, content, recipients, loginId, studentId)
}.flatMap { sender ->
mobile.sendMessage(sender, subject, content, recipients, loginId, studentId)
}
} }
fun getTimetable(start: LocalDate, end: LocalDate, classificationPeriodId: Int): Single<List<Lesson>> { suspend fun getTimetable(start: LocalDate, end: LocalDate, classificationPeriodId: Int): List<Lesson> {
return mobile.getTimetable(start, end, classId, classificationPeriodId, studentId) return mobile.getTimetable(start, end, classId, classificationPeriodId, studentId)
} }
} }

View file

@ -17,5 +17,5 @@ data class AttendanceResponse(
val dateEndText: String, val dateEndText: String,
@SerializedName("Frekwencje") @SerializedName("Frekwencje")
val data: List<Attendance> val items: List<Attendance>
) )

View file

@ -26,69 +26,68 @@ import io.github.wulkanowy.sdk.mobile.service.MobileService
import io.github.wulkanowy.sdk.mobile.timetable.Lesson import io.github.wulkanowy.sdk.mobile.timetable.Lesson
import io.github.wulkanowy.sdk.mobile.timetable.TimetableRequest import io.github.wulkanowy.sdk.mobile.timetable.TimetableRequest
import io.github.wulkanowy.sdk.mobile.toFormat import io.github.wulkanowy.sdk.mobile.toFormat
import io.reactivex.Single
import org.threeten.bp.LocalDate import org.threeten.bp.LocalDate
import org.threeten.bp.LocalDateTime import org.threeten.bp.LocalDateTime
class MobileRepository(private val api: MobileService) { class MobileRepository(private val api: MobileService) {
fun logStart(): Single<ApiResponse<String>> = api.logAppStart(object : ApiRequest() {}) suspend fun logStart(): ApiResponse<String> = api.logAppStart(object : ApiRequest() {})
fun getDictionaries(userId: Int, classificationPeriodId: Int, classId: Int): Single<Dictionaries> { suspend fun getDictionaries(userId: Int, classificationPeriodId: Int, classId: Int): Dictionaries {
return api.getDictionaries(DictionariesRequest(userId, classificationPeriodId, classId)).map { requireNotNull(it.data) } return api.getDictionaries(DictionariesRequest(userId, classificationPeriodId, classId)).data!!
} }
fun getTeachers(studentId: Int, semesterId: Int): Single<List<Teacher>> { suspend fun getTeachers(studentId: Int, semesterId: Int): List<Teacher> {
return api.getTeachers(TeachersRequest(studentId, semesterId)).map { requireNotNull(it.data) }.map { return api.getTeachers(TeachersRequest(studentId, semesterId)).data.let {
it.schoolTeachers.union(it.teachersSubjects).toList() it?.schoolTeachers.orEmpty().union(it?.teachersSubjects.orEmpty()).toList()
} }
} }
fun getTimetable(start: LocalDate, end: LocalDate, classId: Int, classificationPeriodId: Int, studentId: Int): Single<List<Lesson>> { suspend fun getTimetable(start: LocalDate, end: LocalDate, classId: Int, classificationPeriodId: Int, studentId: Int): List<Lesson> {
return api.getTimetable(TimetableRequest(start.toFormat(), end.toFormat(), classId, classificationPeriodId, studentId)).map { requireNotNull(it.data) } return api.getTimetable(TimetableRequest(start.toFormat(), end.toFormat(), classId, classificationPeriodId, studentId)).data!!
} }
fun getGradesDetails(classId: Int, classificationPeriodId: Int, studentId: Int): Single<List<Grade>> { suspend fun getGradesDetails(classId: Int, classificationPeriodId: Int, studentId: Int): List<Grade> {
return api.getGrades(GradesRequest(classId, classificationPeriodId, studentId)).map { requireNotNull(it.data) } return api.getGrades(GradesRequest(classId, classificationPeriodId, studentId)).data!!
} }
fun getGradesSummary(classId: Int, classificationPeriodId: Int, studentId: Int): Single<GradesSummaryResponse> { suspend fun getGradesSummary(classId: Int, classificationPeriodId: Int, studentId: Int): GradesSummaryResponse {
return api.getGradesSummary(GradesRequest(classId, classificationPeriodId, studentId)).map { requireNotNull(it.data) } return api.getGradesSummary(GradesRequest(classId, classificationPeriodId, studentId)).data!!
} }
fun getExams(start: LocalDate, end: LocalDate, classId: Int, classificationPeriodId: Int, studentId: Int): Single<List<Exam>> { suspend fun getExams(start: LocalDate, end: LocalDate, classId: Int, classificationPeriodId: Int, studentId: Int): List<Exam> {
return api.getExams(ExamsRequest(start.toFormat(), end.toFormat(), classId, classificationPeriodId, studentId)).map { requireNotNull(it.data) } return api.getExams(ExamsRequest(start.toFormat(), end.toFormat(), classId, classificationPeriodId, studentId)).data!!
} }
fun getNotes(classificationPeriodId: Int, studentId: Int): Single<List<Note>> { suspend fun getNotes(classificationPeriodId: Int, studentId: Int): List<Note> {
return api.getNotes(NotesRequest(classificationPeriodId, studentId)).map { requireNotNull(it.data) } return api.getNotes(NotesRequest(classificationPeriodId, studentId)).data!!
} }
fun getAttendance(start: LocalDate, end: LocalDate, classId: Int, classificationPeriodId: Int, studentId: Int): Single<List<Attendance>> { suspend fun getAttendance(start: LocalDate, end: LocalDate, classId: Int, classificationPeriodId: Int, studentId: Int): List<Attendance> {
return api.getAttendance(AttendanceRequest(start.toFormat(), end.toFormat(), classId, classificationPeriodId, studentId)).map { requireNotNull(it.data?.data) } return api.getAttendance(AttendanceRequest(start.toFormat(), end.toFormat(), classId, classificationPeriodId, studentId)).data!!.items
} }
fun getHomework(start: LocalDate, end: LocalDate, classId: Int, classificationPeriodId: Int, studentId: Int): Single<List<Homework>> { suspend fun getHomework(start: LocalDate, end: LocalDate, classId: Int, classificationPeriodId: Int, studentId: Int): List<Homework> {
return api.getHomework(HomeworkRequest(start.toFormat(), end.toFormat(), classId, classificationPeriodId, studentId)).map { requireNotNull(it.data) } return api.getHomework(HomeworkRequest(start.toFormat(), end.toFormat(), classId, classificationPeriodId, studentId)).data!!
} }
fun getMessages(start: LocalDateTime, end: LocalDateTime, loginId: Int, studentId: Int): Single<List<Message>> { suspend fun getMessages(start: LocalDateTime, end: LocalDateTime, loginId: Int, studentId: Int): List<Message> {
return api.getMessages(MessagesRequest(start.toFormat(), end.toFormat(), loginId, studentId)).map { requireNotNull(it.data) } return api.getMessages(MessagesRequest(start.toFormat(), end.toFormat(), loginId, studentId)).data!!
} }
fun getMessagesDeleted(start: LocalDateTime, end: LocalDateTime, loginId: Int, studentId: Int): Single<List<Message>> { suspend fun getMessagesDeleted(start: LocalDateTime, end: LocalDateTime, loginId: Int, studentId: Int): List<Message> {
return api.getMessagesDeleted(MessagesRequest(start.toFormat(), end.toFormat(), loginId, studentId)).map { requireNotNull(it.data) } return api.getMessagesDeleted(MessagesRequest(start.toFormat(), end.toFormat(), loginId, studentId)).data!!
} }
fun getMessagesSent(start: LocalDateTime, end: LocalDateTime, loginId: Int, studentId: Int): Single<List<Message>> { suspend fun getMessagesSent(start: LocalDateTime, end: LocalDateTime, loginId: Int, studentId: Int): List<Message> {
return api.getMessagesSent(MessagesRequest(start.toFormat(), end.toFormat(), loginId, studentId)).map { requireNotNull(it.data) } return api.getMessagesSent(MessagesRequest(start.toFormat(), end.toFormat(), loginId, studentId)).data!!
} }
fun changeMessageStatus(messageId: Int, folder: String, status: String, loginId: Int, studentId: Int): Single<String> { suspend fun changeMessageStatus(messageId: Int, folder: String, status: String, loginId: Int, studentId: Int): String {
return api.changeMessageStatus(MessageStatusChangeRequest(messageId, folder, status, loginId, studentId)).map { requireNotNull(it.data) } return api.changeMessageStatus(MessageStatusChangeRequest(messageId, folder, status, loginId, studentId)).data!!
} }
fun sendMessage(sender: String, subject: String, content: String, recipients: List<Recipient>, loginId: Int, studentId: Int): Single<Message> { suspend fun sendMessage(sender: String, subject: String, content: String, recipients: List<Recipient>, loginId: Int, studentId: Int): Message {
return api.sendMessage(SendMessageRequest( return api.sendMessage(SendMessageRequest(
sender = sender, sender = sender,
subject = subject, subject = subject,

View file

@ -5,11 +5,10 @@ import io.github.wulkanowy.sdk.mobile.register.CertificateRequest
import io.github.wulkanowy.sdk.mobile.register.CertificateResponse import io.github.wulkanowy.sdk.mobile.register.CertificateResponse
import io.github.wulkanowy.sdk.mobile.register.Student import io.github.wulkanowy.sdk.mobile.register.Student
import io.github.wulkanowy.sdk.mobile.service.RegisterService import io.github.wulkanowy.sdk.mobile.service.RegisterService
import io.reactivex.Single
class RegisterRepository(private val api: RegisterService) { class RegisterRepository(private val api: RegisterService) {
fun getCertificate(token: String, pin: String, deviceName: String, android: String, firebaseToken: String): Single<CertificateResponse> { suspend fun getCertificate(token: String, pin: String, deviceName: String, android: String, firebaseToken: String): CertificateResponse {
return api.getCertificate(CertificateRequest( return api.getCertificate(CertificateRequest(
tokenKey = token, tokenKey = token,
pin = pin, pin = pin,
@ -19,5 +18,5 @@ class RegisterRepository(private val api: RegisterService) {
)) ))
} }
fun getStudents(): Single<List<Student>> = api.getPupils(object : ApiRequest() {}).map { requireNotNull(it.data) } suspend fun getStudents(): List<Student> = api.getPupils(object : ApiRequest() {}).data.orEmpty()
} }

View file

@ -6,7 +6,6 @@ import okhttp3.Interceptor
import okhttp3.OkHttpClient import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory import retrofit2.converter.scalars.ScalarsConverterFactory
import retrofit2.create import retrofit2.create
@ -36,7 +35,6 @@ class RepositoryManager(
private fun getRetrofitBuilder(interceptors: MutableList<Pair<Interceptor, Boolean>>): Retrofit.Builder { private fun getRetrofitBuilder(interceptors: MutableList<Pair<Interceptor, Boolean>>): Retrofit.Builder {
return Retrofit.Builder() return Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create())
.client(OkHttpClient().newBuilder() .client(OkHttpClient().newBuilder()

View file

@ -3,22 +3,19 @@ package io.github.wulkanowy.sdk.mobile.repository
import io.github.wulkanowy.sdk.mobile.exception.InvalidTokenException import io.github.wulkanowy.sdk.mobile.exception.InvalidTokenException
import io.github.wulkanowy.sdk.mobile.exception.UnknownTokenException import io.github.wulkanowy.sdk.mobile.exception.UnknownTokenException
import io.github.wulkanowy.sdk.mobile.service.RoutingRulesService import io.github.wulkanowy.sdk.mobile.service.RoutingRulesService
import io.reactivex.Single
class RoutingRulesRepository(private val api: RoutingRulesService) { class RoutingRulesRepository(private val api: RoutingRulesService) {
fun getRouteByToken(token: String): Single<String> { suspend fun getRouteByToken(token: String): String {
if (token.length < 4) return Single.error<String>(InvalidTokenException("Token '$token' is too short")) if (token.length < 4) throw InvalidTokenException("Token '$token' is too short")
val tokenSymbol = token.substring(0..2) val tokenSymbol = token.substring(0..2)
if ("FK1" == tokenSymbol) return Single.just("https://api.fakelog.tk") if ("FK1" == tokenSymbol) return "https://api.fakelog.tk"
return api.getRoutingRules().map { routes -> return api.getRoutingRules().split("\r?\n".toRegex())
routes.split("\r?\n".toRegex()) .singleOrNull { tokenSymbol == it.substringBefore(",") }
.singleOrNull { tokenSymbol == it.substringBefore(",") } ?.substringAfter(",")
?.substringAfter(",") ?: throw UnknownTokenException("This token: '$token' is unsupported")
?: throw UnknownTokenException("This token: '$token' is unsupported")
}
} }
} }

View file

@ -23,54 +23,53 @@ import io.github.wulkanowy.sdk.mobile.school.TeachersRequest
import io.github.wulkanowy.sdk.mobile.school.TeachersResponse import io.github.wulkanowy.sdk.mobile.school.TeachersResponse
import io.github.wulkanowy.sdk.mobile.timetable.Lesson import io.github.wulkanowy.sdk.mobile.timetable.Lesson
import io.github.wulkanowy.sdk.mobile.timetable.TimetableRequest import io.github.wulkanowy.sdk.mobile.timetable.TimetableRequest
import io.reactivex.Single
import retrofit2.http.Body import retrofit2.http.Body
import retrofit2.http.POST import retrofit2.http.POST
interface MobileService { interface MobileService {
@POST("LogAppStart") @POST("LogAppStart")
fun logAppStart(@Body logAppStartRequest: ApiRequest): Single<ApiResponse<String>> suspend fun logAppStart(@Body logAppStartRequest: ApiRequest): ApiResponse<String>
@POST("Slowniki") @POST("Slowniki")
fun getDictionaries(@Body dictionariesRequest: DictionariesRequest): Single<ApiResponse<Dictionaries>> suspend fun getDictionaries(@Body dictionariesRequest: DictionariesRequest): ApiResponse<Dictionaries>
@POST("Nauczyciele") @POST("Nauczyciele")
fun getTeachers(@Body teachersRequest: TeachersRequest): Single<ApiResponse<TeachersResponse>> suspend fun getTeachers(@Body teachersRequest: TeachersRequest): ApiResponse<TeachersResponse>
@POST("PlanLekcjiZeZmianami") @POST("PlanLekcjiZeZmianami")
fun getTimetable(@Body timetableRequest: TimetableRequest): Single<ApiResponse<List<Lesson>>> suspend fun getTimetable(@Body timetableRequest: TimetableRequest): ApiResponse<List<Lesson>>
@POST("Oceny") @POST("Oceny")
fun getGrades(@Body gradesRequest: GradesRequest): Single<ApiResponse<List<Grade>>> suspend fun getGrades(@Body gradesRequest: GradesRequest): ApiResponse<List<Grade>>
@POST("OcenyPodsumowanie") @POST("OcenyPodsumowanie")
fun getGradesSummary(@Body gradesRequest: GradesRequest): Single<ApiResponse<GradesSummaryResponse>> suspend fun getGradesSummary(@Body gradesRequest: GradesRequest): ApiResponse<GradesSummaryResponse>
@POST("Sprawdziany") @POST("Sprawdziany")
fun getExams(@Body examsRequest: ExamsRequest): Single<ApiResponse<List<Exam>>> suspend fun getExams(@Body examsRequest: ExamsRequest): ApiResponse<List<Exam>>
@POST("UwagiUcznia") @POST("UwagiUcznia")
fun getNotes(@Body notesRequest: NotesRequest): Single<ApiResponse<List<Note>>> suspend fun getNotes(@Body notesRequest: NotesRequest): ApiResponse<List<Note>>
@POST("Frekwencje") @POST("Frekwencje")
fun getAttendance(@Body attendanceRequest: AttendanceRequest): Single<ApiResponse<AttendanceResponse>> suspend fun getAttendance(@Body attendanceRequest: AttendanceRequest): ApiResponse<AttendanceResponse>
@POST("ZadaniaDomowe") @POST("ZadaniaDomowe")
fun getHomework(@Body homeworkRequest: HomeworkRequest): Single<ApiResponse<List<Homework>>> suspend fun getHomework(@Body homeworkRequest: HomeworkRequest): ApiResponse<List<Homework>>
@POST("WiadomosciOdebrane") @POST("WiadomosciOdebrane")
fun getMessages(@Body messagesRequest: MessagesRequest): Single<ApiResponse<List<Message>>> suspend fun getMessages(@Body messagesRequest: MessagesRequest): ApiResponse<List<Message>>
@POST("WiadomosciWyslane") @POST("WiadomosciWyslane")
fun getMessagesSent(@Body messagesRequest: MessagesRequest): Single<ApiResponse<List<Message>>> suspend fun getMessagesSent(@Body messagesRequest: MessagesRequest): ApiResponse<List<Message>>
@POST("WiadomosciUsuniete") @POST("WiadomosciUsuniete")
fun getMessagesDeleted(@Body messagesRequest: MessagesRequest): Single<ApiResponse<List<Message>>> suspend fun getMessagesDeleted(@Body messagesRequest: MessagesRequest): ApiResponse<List<Message>>
@POST("ZmienStatusWiadomosci") @POST("ZmienStatusWiadomosci")
fun changeMessageStatus(@Body messageStatusChangeRequest: MessageStatusChangeRequest): Single<ApiResponse<String>> suspend fun changeMessageStatus(@Body messageStatusChangeRequest: MessageStatusChangeRequest): ApiResponse<String>
@POST("DodajWiadomosc") @POST("DodajWiadomosc")
fun sendMessage(@Body sendMessageRequest: SendMessageRequest): Single<Message> suspend fun sendMessage(@Body sendMessageRequest: SendMessageRequest): Message
} }

View file

@ -5,7 +5,6 @@ import io.github.wulkanowy.sdk.mobile.ApiResponse
import io.github.wulkanowy.sdk.mobile.register.CertificateRequest import io.github.wulkanowy.sdk.mobile.register.CertificateRequest
import io.github.wulkanowy.sdk.mobile.register.CertificateResponse import io.github.wulkanowy.sdk.mobile.register.CertificateResponse
import io.github.wulkanowy.sdk.mobile.register.Student import io.github.wulkanowy.sdk.mobile.register.Student
import io.reactivex.Single
import retrofit2.http.Body import retrofit2.http.Body
import retrofit2.http.Headers import retrofit2.http.Headers
import retrofit2.http.POST import retrofit2.http.POST
@ -14,8 +13,8 @@ interface RegisterService {
@POST("Certyfikat") @POST("Certyfikat")
@Headers("RequestMobileType: RegisterDevice") @Headers("RequestMobileType: RegisterDevice")
fun getCertificate(@Body certificateRequest: CertificateRequest): Single<CertificateResponse> suspend fun getCertificate(@Body certificateRequest: CertificateRequest): CertificateResponse
@POST("ListaUczniow") @POST("ListaUczniow")
fun getPupils(@Body pupilsListRequest: ApiRequest): Single<ApiResponse<List<Student>>> suspend fun getPupils(@Body pupilsListRequest: ApiRequest): ApiResponse<List<Student>>
} }

View file

@ -1,10 +1,9 @@
package io.github.wulkanowy.sdk.mobile.service package io.github.wulkanowy.sdk.mobile.service
import io.reactivex.Single
import retrofit2.http.GET import retrofit2.http.GET
interface RoutingRulesService { interface RoutingRulesService {
@GET("/UonetPlusMobile/RoutingRules.txt") @GET("/UonetPlusMobile/RoutingRules.txt")
fun getRoutingRules(): Single<String> suspend fun getRoutingRules(): String
} }

View file

@ -7,7 +7,6 @@ import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer import okhttp3.mockwebserver.MockWebServer
import org.junit.After import org.junit.After
import retrofit2.Retrofit import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory import retrofit2.converter.scalars.ScalarsConverterFactory
@ -32,7 +31,6 @@ open class BaseLocalTest {
fun getRetrofit(baseUrl: String = server.url("/").toString()): Retrofit = getRetrofitBuilder().baseUrl(baseUrl).build() fun getRetrofit(baseUrl: String = server.url("/").toString()): Retrofit = getRetrofitBuilder().baseUrl(baseUrl).build()
fun getRetrofitBuilder(): Retrofit.Builder = Retrofit.Builder() fun getRetrofitBuilder(): Retrofit.Builder = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create())
.client(OkHttpClient().newBuilder() .client(OkHttpClient().newBuilder()

View file

@ -1,20 +1,12 @@
package io.github.wulkanowy.sdk.mobile package io.github.wulkanowy.sdk.mobile
import io.github.wulkanowy.sdk.mobile.attendance.Attendance
import io.github.wulkanowy.sdk.mobile.dictionaries.Dictionaries
import io.github.wulkanowy.sdk.mobile.exams.Exam
import io.github.wulkanowy.sdk.mobile.grades.Grade
import io.github.wulkanowy.sdk.mobile.homework.Homework
import io.github.wulkanowy.sdk.mobile.interceptor.SignInterceptor import io.github.wulkanowy.sdk.mobile.interceptor.SignInterceptor
import io.github.wulkanowy.sdk.mobile.notes.Note
import io.github.wulkanowy.sdk.mobile.register.CertificateResponse
import io.github.wulkanowy.sdk.mobile.register.Student import io.github.wulkanowy.sdk.mobile.register.Student
import io.github.wulkanowy.sdk.mobile.repository.MobileRepository import io.github.wulkanowy.sdk.mobile.repository.MobileRepository
import io.github.wulkanowy.sdk.mobile.repository.RegisterRepository import io.github.wulkanowy.sdk.mobile.repository.RegisterRepository
import io.github.wulkanowy.sdk.mobile.timetable.Lesson
import io.github.wulkanowy.signer.getPrivateKeyFromCert import io.github.wulkanowy.signer.getPrivateKeyFromCert
import io.reactivex.observers.TestObserver
import junit.framework.TestCase.assertEquals import junit.framework.TestCase.assertEquals
import kotlinx.coroutines.runBlocking
import okhttp3.OkHttpClient import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor import okhttp3.logging.HttpLoggingInterceptor
import org.junit.BeforeClass import org.junit.BeforeClass
@ -22,7 +14,6 @@ import org.junit.Ignore
import org.junit.Test import org.junit.Test
import org.threeten.bp.LocalDate.of import org.threeten.bp.LocalDate.of
import retrofit2.Retrofit import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory import retrofit2.converter.scalars.ScalarsConverterFactory
import retrofit2.create import retrofit2.create
@ -45,7 +36,6 @@ class UonetTest {
private fun getRetrofitBuilder(privateKey: String, certKey: String): Retrofit.Builder { private fun getRetrofitBuilder(privateKey: String, certKey: String): Retrofit.Builder {
return Retrofit.Builder() return Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create())
.client(OkHttpClient().newBuilder() .client(OkHttpClient().newBuilder()
@ -64,29 +54,21 @@ class UonetTest {
.build().create() .build().create()
) )
val certificate = register.getCertificate(TOKEN, PIN, DEVICE_NAME, "8.1.0", "") val certificate = runBlocking { register.getCertificate(TOKEN, PIN, DEVICE_NAME, "8.1.0", "") }
val certSubscriber = TestObserver<CertificateResponse>()
certificate.subscribe(certSubscriber)
certSubscriber.assertComplete()
certSubscriber.assertNoErrors()
assertEquals(false, certSubscriber.values()[0].isError) assertEquals(false, certificate.isError)
val tokenCrt = certSubscriber.values()[0].tokenCert val tokenCrt = certificate.tokenCert
val certKey = tokenCrt!!.certificateKey val certKey = tokenCrt!!.certificateKey
val cert = tokenCrt.certificatePfx val cert = tokenCrt.certificatePfx
val privateKey = getPrivateKeyFromCert(PASSWORD, cert) val privateKey = getPrivateKeyFromCert(PASSWORD, cert)
val pupils = register.getStudents() val pupils = runBlocking { register.getStudents() }
val pupilSubscriber = TestObserver<List<Student>>() assertEquals(2, pupils.size)
pupils.subscribe(pupilSubscriber)
pupilSubscriber.assertComplete()
pupilSubscriber.assertNoErrors()
assertEquals(2, pupilSubscriber.values()[0].size)
student = pupilSubscriber.values()[0][0] student = pupils[0]
// MobileRepository // MobileRepository
mobile = MobileRepository(getRetrofitBuilder(privateKey, certKey) mobile = MobileRepository(getRetrofitBuilder(privateKey, certKey)
@ -98,74 +80,42 @@ class UonetTest {
@Test @Test
fun logStartTest() { fun logStartTest() {
val start = mobile.logStart() val start = runBlocking { mobile.logStart() }
val startSubscriber = TestObserver<ApiResponse<String>>() assertEquals("Ok", start.status)
start.subscribe(startSubscriber)
startSubscriber.assertComplete()
startSubscriber.assertNoErrors()
assertEquals("Ok", startSubscriber.values()[0].status)
} }
@Test @Test
fun dictionariesTest() { fun dictionariesTest() {
val dictionaries = mobile.getDictionaries(student.userLoginId, student.classificationPeriodId, student.classId) runBlocking { mobile.getDictionaries(student.userLoginId, student.classificationPeriodId, student.classId) }
val dictionariesSubscriber = TestObserver<Dictionaries>()
dictionaries.subscribe(dictionariesSubscriber)
dictionariesSubscriber.assertComplete()
dictionariesSubscriber.assertNoErrors()
} }
@Test @Test
fun timetableTest() { fun timetableTest() {
val lessons = mobile.getTimetable(of(2018, 4, 23), of(2018, 4, 24), student.classId, student.classificationPeriodId, student.id) runBlocking { mobile.getTimetable(of(2018, 4, 23), of(2018, 4, 24), student.classId, student.classificationPeriodId, student.id) }
val lessonsSubscriber = TestObserver<List<Lesson>>()
lessons.subscribe(lessonsSubscriber)
lessonsSubscriber.assertComplete()
lessonsSubscriber.assertNoErrors()
} }
@Test @Test
fun gradesTest() { fun gradesTest() {
val grades = mobile.getGradesDetails(student.classId, student.classificationPeriodId, student.id) runBlocking { mobile.getGradesDetails(student.classId, student.classificationPeriodId, student.id) }
val gradesSubscriber = TestObserver<List<Grade>>()
grades.subscribe(gradesSubscriber)
gradesSubscriber.assertComplete()
gradesSubscriber.assertNoErrors()
} }
@Test @Test
fun examsTest() { fun examsTest() {
val exams = mobile.getExams(of(2018, 5, 28), of(2018, 6, 3), student.classId, student.classificationPeriodId, student.id) runBlocking { mobile.getExams(of(2018, 5, 28), of(2018, 6, 3), student.classId, student.classificationPeriodId, student.id) }
val examsSubscriber = TestObserver<List<Exam>>()
exams.subscribe(examsSubscriber)
examsSubscriber.assertComplete()
examsSubscriber.assertNoErrors()
} }
@Test @Test
fun notesTest() { fun notesTest() {
val notes = mobile.getNotes(student.classificationPeriodId, student.id) runBlocking { mobile.getNotes(student.classificationPeriodId, student.id) }
val notesSubscriber = TestObserver<List<Note>>()
notes.subscribe(notesSubscriber)
notesSubscriber.assertComplete()
notesSubscriber.assertNoErrors()
} }
@Test @Test
fun attendanceTest() { fun attendanceTest() {
val attendance = mobile.getAttendance(of(2018, 4, 23), of(2018, 4, 24), student.classId, student.classificationPeriodId, student.id) runBlocking { mobile.getAttendance(of(2018, 4, 23), of(2018, 4, 24), student.classId, student.classificationPeriodId, student.id) }
val attendanceSubscriber = TestObserver<List<Attendance>>()
attendance.subscribe(attendanceSubscriber)
attendanceSubscriber.assertComplete()
attendanceSubscriber.assertNoErrors()
} }
@Test @Test
fun homeworkTest() { fun homeworkTest() {
val homework = mobile.getHomework(of(2017, 10, 23), of(2017, 10, 27), student.classId, student.classificationPeriodId, student.id) runBlocking { mobile.getHomework(of(2017, 10, 23), of(2017, 10, 27), student.classId, student.classificationPeriodId, student.id) }
val homeworkSubscriber = TestObserver<List<Homework>>()
homework.subscribe(homeworkSubscriber)
homeworkSubscriber.assertComplete()
homeworkSubscriber.assertNoErrors()
} }
} }

View file

@ -2,6 +2,7 @@ package io.github.wulkanowy.sdk.mobile.exams
import io.github.wulkanowy.sdk.mobile.BaseLocalTest import io.github.wulkanowy.sdk.mobile.BaseLocalTest
import io.github.wulkanowy.sdk.mobile.repository.MobileRepository import io.github.wulkanowy.sdk.mobile.repository.MobileRepository
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
import org.threeten.bp.LocalDate.of import org.threeten.bp.LocalDate.of
@ -15,7 +16,7 @@ class ExamsTest : BaseLocalTest() {
fun getExams() { fun getExams() {
server.enqueueAndStart("Sprawdziany.json") server.enqueueAndStart("Sprawdziany.json")
val items = exams.getExams(of(2020, 1, 16), of(2020, 1, 17), 1, 2, 3).blockingGet() val items = runBlocking { exams.getExams(of(2020, 1, 16), of(2020, 1, 17), 1, 2, 3) }
assertEquals(3, items.size) assertEquals(3, items.size)
} }

View file

@ -2,6 +2,7 @@ package io.github.wulkanowy.sdk.mobile.grades
import io.github.wulkanowy.sdk.mobile.BaseLocalTest import io.github.wulkanowy.sdk.mobile.BaseLocalTest
import io.github.wulkanowy.sdk.mobile.repository.MobileRepository import io.github.wulkanowy.sdk.mobile.repository.MobileRepository
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
import retrofit2.create import retrofit2.create
@ -14,7 +15,7 @@ class GradesTest : BaseLocalTest() {
fun getGrades() { fun getGrades() {
server.enqueueAndStart("Oceny.json") server.enqueueAndStart("Oceny.json")
val items = grades.getGradesDetails(0, 0, 0).blockingGet() val items = runBlocking { grades.getGradesDetails(0, 0, 0) }
assertEquals(2, items.size) assertEquals(2, items.size)
} }

View file

@ -2,9 +2,9 @@ package io.github.wulkanowy.sdk.mobile.interceptor
import io.github.wulkanowy.sdk.mobile.BaseLocalTest import io.github.wulkanowy.sdk.mobile.BaseLocalTest
import io.github.wulkanowy.sdk.mobile.exception.InvalidSymbolException import io.github.wulkanowy.sdk.mobile.exception.InvalidSymbolException
import io.github.wulkanowy.sdk.mobile.register.Student
import io.github.wulkanowy.sdk.mobile.repository.RegisterRepository import io.github.wulkanowy.sdk.mobile.repository.RegisterRepository
import io.reactivex.observers.TestObserver import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertTrue
import org.junit.Test import org.junit.Test
import retrofit2.create import retrofit2.create
import java.io.IOException import java.io.IOException
@ -16,11 +16,12 @@ class ErrorInterceptorTest : BaseLocalTest() {
server.enqueueAndStart("bad-request.txt") server.enqueueAndStart("bad-request.txt")
val repo = RegisterRepository(getRetrofitBuilder().baseUrl("http://localhost:3030/").build().create()) val repo = RegisterRepository(getRetrofitBuilder().baseUrl("http://localhost:3030/").build().create())
val students = repo.getStudents()
val studentsObserver = TestObserver<List<Student>>() try {
students.subscribe(studentsObserver) runBlocking { repo.getStudents() }
studentsObserver.assertNotComplete() } catch (e: Throwable) {
studentsObserver.assertError(IOException::class.java) assertTrue(e is IOException)
}
} }
@Test @Test
@ -28,10 +29,11 @@ class ErrorInterceptorTest : BaseLocalTest() {
server.enqueueAndStart("invalid-symbol.html") server.enqueueAndStart("invalid-symbol.html")
val repo = RegisterRepository(getRetrofitBuilder().baseUrl("http://localhost:3030/").build().create()) val repo = RegisterRepository(getRetrofitBuilder().baseUrl("http://localhost:3030/").build().create())
val students = repo.getStudents()
val studentsObserver = TestObserver<List<Student>>() try {
students.subscribe(studentsObserver) runBlocking { repo.getStudents() }
studentsObserver.assertNotComplete() } catch (e: Throwable) {
studentsObserver.assertError(InvalidSymbolException::class.java) assertTrue(e is InvalidSymbolException)
}
} }
} }

View file

@ -2,6 +2,7 @@ package io.github.wulkanowy.sdk.mobile.register
import io.github.wulkanowy.sdk.mobile.BaseLocalTest import io.github.wulkanowy.sdk.mobile.BaseLocalTest
import io.github.wulkanowy.sdk.mobile.repository.RegisterRepository import io.github.wulkanowy.sdk.mobile.repository.RegisterRepository
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
import retrofit2.create import retrofit2.create
@ -14,7 +15,7 @@ class RegisterTest : BaseLocalTest() {
fun getStudents() { fun getStudents() {
server.enqueueAndStart("ListaUczniow.json") server.enqueueAndStart("ListaUczniow.json")
val students = repo.getStudents().blockingGet() val students = runBlocking { repo.getStudents() }
assertEquals(2, students.size) assertEquals(2, students.size)
} }
} }

View file

@ -2,8 +2,9 @@ package io.github.wulkanowy.sdk.mobile.repository
import io.github.wulkanowy.sdk.mobile.BaseLocalTest import io.github.wulkanowy.sdk.mobile.BaseLocalTest
import io.github.wulkanowy.sdk.mobile.exception.InvalidTokenException import io.github.wulkanowy.sdk.mobile.exception.InvalidTokenException
import io.reactivex.observers.TestObserver import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test import org.junit.Test
import retrofit2.create import retrofit2.create
@ -14,7 +15,7 @@ class RoutingRulesRepositoryTest : BaseLocalTest() {
server.enqueueAndStart("RoutingRules.txt") server.enqueueAndStart("RoutingRules.txt")
val repo = RoutingRulesRepository(getRetrofit().create()) val repo = RoutingRulesRepository(getRetrofit().create())
val route = repo.getRouteByToken("KA2000").blockingGet() val route = runBlocking { repo.getRouteByToken("KA2000") }
assertEquals("https://uonetplus-komunikacja-test.mcuw.katowice.eu", route) assertEquals("https://uonetplus-komunikacja-test.mcuw.katowice.eu", route)
} }
@ -24,11 +25,12 @@ class RoutingRulesRepositoryTest : BaseLocalTest() {
server.enqueueAndStart("RoutingRules.txt") server.enqueueAndStart("RoutingRules.txt")
val repo = RoutingRulesRepository(getRetrofit().create()) val repo = RoutingRulesRepository(getRetrofit().create())
val route = repo.getRouteByToken("ERR00000")
val routeObserver = TestObserver<String>() try {
route.subscribe(routeObserver) runBlocking { repo.getRouteByToken("ERR00000") }
routeObserver.assertNotComplete() } catch (e: Throwable) {
routeObserver.assertError(InvalidTokenException::class.java) assertTrue(e is InvalidTokenException)
}
} }
@Test @Test
@ -36,10 +38,12 @@ class RoutingRulesRepositoryTest : BaseLocalTest() {
server.enqueueAndStart("RoutingRules.txt") server.enqueueAndStart("RoutingRules.txt")
val repo = RoutingRulesRepository(getRetrofit().create()) val repo = RoutingRulesRepository(getRetrofit().create())
val route = repo.getRouteByToken("ER")
val routeObserver = TestObserver<String>() // TODO: fix assert to run event if no exception thrown
route.subscribe(routeObserver) try {
routeObserver.assertNotComplete() runBlocking { repo.getRouteByToken("ER") }
routeObserver.assertError(InvalidTokenException::class.java) } catch (e: Throwable) {
assertTrue(e is InvalidTokenException)
}
} }
} }

View file

@ -2,6 +2,7 @@ package io.github.wulkanowy.sdk.mobile.timetable
import io.github.wulkanowy.sdk.mobile.BaseLocalTest import io.github.wulkanowy.sdk.mobile.BaseLocalTest
import io.github.wulkanowy.sdk.mobile.repository.MobileRepository import io.github.wulkanowy.sdk.mobile.repository.MobileRepository
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
import org.threeten.bp.LocalDate.of import org.threeten.bp.LocalDate.of
@ -15,7 +16,7 @@ class TimetableTest : BaseLocalTest() {
fun getTimetable() { fun getTimetable() {
server.enqueueAndStart("PlanLekcji.json") server.enqueueAndStart("PlanLekcji.json")
val items = timetable.getTimetable(of(2020, 1, 10), of(2020, 2, 11), 1, 2, 3).blockingGet() val items = runBlocking { timetable.getTimetable(of(2020, 1, 10), of(2020, 2, 11), 1, 2, 3) }
assertEquals(5, items.size) assertEquals(5, items.size)
} }

View file

@ -181,8 +181,8 @@ class Sdk {
} }
fun getStudentsFromMobileApi(token: String, pin: String, symbol: String, firebaseToken: String, apiKey: String = ""): Single<List<Student>> { fun getStudentsFromMobileApi(token: String, pin: String, symbol: String, firebaseToken: String, apiKey: String = ""): Single<List<Student>> {
return mobile.getCertificate(token, pin, symbol, buildTag, androidVersion, firebaseToken) return rxSingle { mobile.getCertificate(token, pin, symbol, buildTag, androidVersion, firebaseToken) }
.flatMap { mobile.getStudents(it, apiKey) } .flatMap { rxSingle { mobile.getStudents(it, apiKey) } }
.map { it.mapStudents(symbol) } .map { it.mapStudents(symbol) }
} }
@ -227,16 +227,14 @@ class Sdk {
fun getSemesters(now: LocalDate = LocalDate.now()): Single<List<Semester>> { fun getSemesters(now: LocalDate = LocalDate.now()): Single<List<Semester>> {
return when (mode) { return when (mode) {
Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.getSemesters() }.compose(ScrapperExceptionTransformer()).map { it.mapSemesters() } Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.getSemesters() }.compose(ScrapperExceptionTransformer()).map { it.mapSemesters() }
Mode.API -> mobile.getStudents().map { it.mapSemesters(studentId, now) } Mode.API -> rxSingle { mobile.getStudents().mapSemesters(studentId, now) }
} }
} }
fun getAttendance(startDate: LocalDate, endDate: LocalDate, semesterId: Int): Single<List<Attendance>> { fun getAttendance(startDate: LocalDate, endDate: LocalDate, semesterId: Int): Single<List<Attendance>> {
return when (mode) { return when (mode) {
Mode.SCRAPPER -> rxSingle { scrapper.getAttendance(startDate, endDate) }.compose(ScrapperExceptionTransformer()).map { it.mapAttendance() } Mode.SCRAPPER -> rxSingle { scrapper.getAttendance(startDate, endDate) }.compose(ScrapperExceptionTransformer()).map { it.mapAttendance() }
Mode.HYBRID, Mode.API -> mobile.getDictionaries().flatMap { dict -> Mode.HYBRID, Mode.API -> rxSingle { mobile.getAttendance(startDate, endDate, semesterId).mapAttendance(mobile.getDictionaries()) }
mobile.getAttendance(startDate, endDate, semesterId).map { it.mapAttendance(dict) }
}
} }
} }
@ -257,43 +255,35 @@ class Sdk {
fun getSubjects(): Single<List<Subject>> { fun getSubjects(): Single<List<Subject>> {
return when (mode) { return when (mode) {
Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.getSubjects() }.compose(ScrapperExceptionTransformer()).map { it.mapSubjects() } Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.getSubjects() }.compose(ScrapperExceptionTransformer()).map { it.mapSubjects() }
Mode.API -> mobile.getDictionaries().map { it.subjects }.map { it.mapSubjects() } Mode.API -> rxSingle { mobile.getDictionaries().subjects.mapSubjects() }
} }
} }
fun getExams(start: LocalDate, end: LocalDate, semesterId: Int): Single<List<Exam>> { fun getExams(start: LocalDate, end: LocalDate, semesterId: Int): Single<List<Exam>> {
return when (mode) { return when (mode) {
Mode.SCRAPPER -> rxSingle { scrapper.getExams(start, end) }.compose(ScrapperExceptionTransformer()).map { it.mapExams() } Mode.SCRAPPER -> rxSingle { scrapper.getExams(start, end) }.compose(ScrapperExceptionTransformer()).map { it.mapExams() }
Mode.HYBRID, Mode.API -> mobile.getDictionaries().flatMap { dict -> Mode.HYBRID, Mode.API -> rxSingle { mobile.getExams(start, end, semesterId).mapExams(mobile.getDictionaries()) }
mobile.getExams(start, end, semesterId).map { it.mapExams(dict) }
}
} }
} }
fun getGrades(semesterId: Int): Single<Pair<List<Grade>, List<GradeSummary>>> { fun getGrades(semesterId: Int): Single<Pair<List<Grade>, List<GradeSummary>>> {
return when (mode) { return when (mode) {
Mode.SCRAPPER -> rxSingle { scrapper.getGrades(semesterId) }.compose(ScrapperExceptionTransformer()).map { grades -> grades.mapGrades() } Mode.SCRAPPER -> rxSingle { scrapper.getGrades(semesterId) }.compose(ScrapperExceptionTransformer()).map { grades -> grades.mapGrades() }
Mode.HYBRID, Mode.API -> mobile.getDictionaries().flatMap { dict -> Mode.HYBRID, Mode.API -> rxSingle { mobile.getGrades(semesterId).mapGrades(mobile.getDictionaries()) }
mobile.getGrades(semesterId).map { grades -> grades.mapGrades(dict) }
}
} }
} }
fun getGradesDetails(semesterId: Int): Single<List<Grade>> { fun getGradesDetails(semesterId: Int): Single<List<Grade>> {
return when (mode) { return when (mode) {
Mode.SCRAPPER -> rxSingle { scrapper.getGradesDetails(semesterId) }.compose(ScrapperExceptionTransformer()).map { grades -> grades.mapGradesDetails() } Mode.SCRAPPER -> rxSingle { scrapper.getGradesDetails(semesterId) }.compose(ScrapperExceptionTransformer()).map { grades -> grades.mapGradesDetails() }
Mode.HYBRID, Mode.API -> mobile.getDictionaries().flatMap { dict -> Mode.HYBRID, Mode.API -> rxSingle { mobile.getGradesDetails(semesterId).mapGradesDetails(mobile.getDictionaries()) }
mobile.getGradesDetails(semesterId).map { it.mapGradesDetails(dict) }
}
} }
} }
fun getGradesSummary(semesterId: Int): Single<List<GradeSummary>> { fun getGradesSummary(semesterId: Int): Single<List<GradeSummary>> {
return when (mode) { return when (mode) {
Mode.SCRAPPER -> rxSingle { scrapper.getGradesSummary(semesterId) }.compose(ScrapperExceptionTransformer()).map { it.mapGradesSummary() } Mode.SCRAPPER -> rxSingle { scrapper.getGradesSummary(semesterId) }.compose(ScrapperExceptionTransformer()).map { it.mapGradesSummary() }
Mode.HYBRID, Mode.API -> mobile.getDictionaries().flatMap { dict -> Mode.HYBRID, Mode.API -> rxSingle { mobile.getGradesSummary(semesterId).mapGradesSummary(mobile.getDictionaries()) }
mobile.getGradesSummary(semesterId).map { it.mapGradesSummary(dict) }
}
} }
} }
@ -321,18 +311,14 @@ class Sdk {
fun getHomework(start: LocalDate, end: LocalDate, semesterId: Int = 0): Single<List<Homework>> { fun getHomework(start: LocalDate, end: LocalDate, semesterId: Int = 0): Single<List<Homework>> {
return when (mode) { return when (mode) {
Mode.SCRAPPER -> rxSingle { scrapper.getHomework(start, end) }.compose(ScrapperExceptionTransformer()).map { it.mapHomework() } Mode.SCRAPPER -> rxSingle { scrapper.getHomework(start, end) }.compose(ScrapperExceptionTransformer()).map { it.mapHomework() }
Mode.HYBRID, Mode.API -> mobile.getDictionaries().flatMap { dict -> Mode.HYBRID, Mode.API -> rxSingle { mobile.getHomework(start, end, semesterId).mapHomework(mobile.getDictionaries()) }
mobile.getHomework(start, end, semesterId).map { it.mapHomework(dict) }
}
} }
} }
fun getNotes(semesterId: Int): Single<List<Note>> { fun getNotes(semesterId: Int): Single<List<Note>> {
return when (mode) { return when (mode) {
Mode.SCRAPPER -> rxSingle { scrapper.getNotes() }.compose(ScrapperExceptionTransformer()).map { it.mapNotes() } Mode.SCRAPPER -> rxSingle { scrapper.getNotes() }.compose(ScrapperExceptionTransformer()).map { it.mapNotes() }
Mode.HYBRID, Mode.API -> mobile.getDictionaries().flatMap { dict -> Mode.HYBRID, Mode.API -> rxSingle { mobile.getNotes(semesterId).mapNotes(mobile.getDictionaries()) }
mobile.getNotes(semesterId).map { it.mapNotes(dict) }
}
} }
} }
@ -360,9 +346,7 @@ class Sdk {
fun getTeachers(semesterId: Int): Single<List<Teacher>> { fun getTeachers(semesterId: Int): Single<List<Teacher>> {
return when (mode) { return when (mode) {
Mode.SCRAPPER -> rxSingle { scrapper.getTeachers() }.compose(ScrapperExceptionTransformer()).map { it.mapTeachers() } Mode.SCRAPPER -> rxSingle { scrapper.getTeachers() }.compose(ScrapperExceptionTransformer()).map { it.mapTeachers() }
Mode.HYBRID, Mode.API -> mobile.getDictionaries().flatMap { dict -> Mode.HYBRID, Mode.API -> rxSingle { mobile.getTeachers(studentId, semesterId).mapTeachers(mobile.getDictionaries()) }
mobile.getTeachers(studentId, semesterId).map { it.mapTeachers(dict) }
}
} }
} }
@ -383,14 +367,14 @@ class Sdk {
fun getReportingUnits(): Single<List<ReportingUnit>> { fun getReportingUnits(): Single<List<ReportingUnit>> {
return when (mode) { return when (mode) {
Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.getReportingUnits() }.compose(ScrapperExceptionTransformer()).map { it.mapReportingUnits() } Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.getReportingUnits() }.compose(ScrapperExceptionTransformer()).map { it.mapReportingUnits() }
Mode.API -> mobile.getStudents().map { it.mapReportingUnits(studentId) } Mode.API -> rxSingle { mobile.getStudents().mapReportingUnits(studentId) }
} }
} }
fun getRecipients(unitId: Int, role: Int = 2): Single<List<Recipient>> { fun getRecipients(unitId: Int, role: Int = 2): Single<List<Recipient>> {
return when (mode) { return when (mode) {
Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.getRecipients(unitId, role) }.compose(ScrapperExceptionTransformer()).map { it.mapRecipients() } Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.getRecipients(unitId, role) }.compose(ScrapperExceptionTransformer()).map { it.mapRecipients() }
Mode.API -> mobile.getDictionaries().map { it.teachers }.map { it.mapRecipients(unitId) } Mode.API -> rxSingle { mobile.getDictionaries().teachers.mapRecipients(unitId) }
} }
} }
@ -405,27 +389,21 @@ class Sdk {
fun getReceivedMessages(start: LocalDateTime, end: LocalDateTime): Single<List<Message>> { fun getReceivedMessages(start: LocalDateTime, end: LocalDateTime): Single<List<Message>> {
return when (mode) { return when (mode) {
Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.getReceivedMessages() }.compose(ScrapperExceptionTransformer()).map { it.mapMessages() } // TODO Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.getReceivedMessages() }.compose(ScrapperExceptionTransformer()).map { it.mapMessages() } // TODO
Mode.API -> mobile.getDictionaries().flatMap { dict -> Mode.API -> rxSingle { mobile.getMessages(start, end).mapMessages(mobile.getDictionaries()) }
mobile.getMessages(start, end).map { it.mapMessages(dict) }
}
} }
} }
fun getSentMessages(start: LocalDateTime, end: LocalDateTime): Single<List<Message>> { fun getSentMessages(start: LocalDateTime, end: LocalDateTime): Single<List<Message>> {
return when (mode) { return when (mode) {
Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.getSentMessages() }.compose(ScrapperExceptionTransformer()).map { it.mapMessages() } Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.getSentMessages() }.compose(ScrapperExceptionTransformer()).map { it.mapMessages() }
Mode.API -> mobile.getDictionaries().flatMap { dict -> Mode.API -> rxSingle { mobile.getMessagesSent(start, end).mapMessages(mobile.getDictionaries()) }
mobile.getMessagesSent(start, end).map { it.mapMessages(dict) }
}
} }
} }
fun getDeletedMessages(start: LocalDateTime, end: LocalDateTime): Single<List<Message>> { fun getDeletedMessages(start: LocalDateTime, end: LocalDateTime): Single<List<Message>> {
return when (mode) { return when (mode) {
Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.getDeletedMessages() }.compose(ScrapperExceptionTransformer()).map { it.mapMessages() } Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.getDeletedMessages() }.compose(ScrapperExceptionTransformer()).map { it.mapMessages() }
Mode.API -> mobile.getDictionaries().flatMap { dict -> Mode.API -> rxSingle { mobile.getMessagesDeleted(start, end).mapMessages(mobile.getDictionaries()) }
mobile.getMessagesDeleted(start, end).map { it.mapMessages(dict) }
}
} }
} }
@ -439,11 +417,13 @@ class Sdk {
fun getMessageDetails(messageId: Int, folderId: Int, read: Boolean = false, id: Int? = null): Single<MessageDetails> { fun getMessageDetails(messageId: Int, folderId: Int, read: Boolean = false, id: Int? = null): Single<MessageDetails> {
return when (mode) { return when (mode) {
Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.getMessageDetails(messageId, folderId, read, id) }.compose(ScrapperExceptionTransformer()).map { it.mapScrapperMessage() } Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.getMessageDetails(messageId, folderId, read, id) }.compose(ScrapperExceptionTransformer()).map { it.mapScrapperMessage() }
Mode.API -> mobile.changeMessageStatus(messageId, when (folderId) { Mode.API -> rxSingle {
1 -> "Odebrane" mobile.changeMessageStatus(messageId, when (folderId) {
2 -> "Wysłane" 1 -> "Odebrane"
else -> "Usunięte" 2 -> "Wysłane"
}, "Widoczna").map { MessageDetails("", emptyList()) } else -> "Usunięte"
}, "Widoczna").let { MessageDetails("", emptyList()) }
}
} }
} }
@ -452,7 +432,7 @@ class Sdk {
Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.sendMessage(subject, content, recipients.mapFromRecipientsToScraper()) } Mode.HYBRID, Mode.SCRAPPER -> rxSingle { scrapper.sendMessage(subject, content, recipients.mapFromRecipientsToScraper()) }
.compose(ScrapperExceptionTransformer()) .compose(ScrapperExceptionTransformer())
.map { it.mapSentMessage() } .map { it.mapSentMessage() }
Mode.API -> mobile.sendMessage(subject, content, recipients.mapFromRecipientsToMobile()).map { it.mapSentMessage(loginId) } Mode.API -> rxSingle { mobile.sendMessage(subject, content, recipients.mapFromRecipientsToMobile()).mapSentMessage(loginId) }
} }
} }
@ -460,11 +440,13 @@ class Sdk {
return when (mode) { return when (mode) {
Mode.SCRAPPER -> rxSingle { scrapper.deleteMessages(messages) }.compose(ScrapperExceptionTransformer()) Mode.SCRAPPER -> rxSingle { scrapper.deleteMessages(messages) }.compose(ScrapperExceptionTransformer())
Mode.HYBRID, Mode.API -> Completable.mergeDelayError(messages.map { (messageId, folderId) -> Mode.HYBRID, Mode.API -> Completable.mergeDelayError(messages.map { (messageId, folderId) ->
mobile.changeMessageStatus(messageId, when (folderId) { rxSingle {
1 -> "Odebrane" mobile.changeMessageStatus(messageId, when (folderId) {
2 -> "Wysłane" 1 -> "Odebrane"
else -> "Usunięte" 2 -> "Wysłane"
}, "Usunieta").ignoreElement() else -> "Usunięte"
}, "Usunieta")
}.ignoreElement()
}).toSingleDefault(true) }).toSingleDefault(true)
} }
} }
@ -472,9 +454,7 @@ class Sdk {
fun getTimetable(start: LocalDate, end: LocalDate): Single<List<Timetable>> { fun getTimetable(start: LocalDate, end: LocalDate): Single<List<Timetable>> {
return when (mode) { return when (mode) {
Mode.SCRAPPER -> rxSingle { scrapper.getTimetable(start, end) }.compose(ScrapperExceptionTransformer()).map { it.mapTimetable() } Mode.SCRAPPER -> rxSingle { scrapper.getTimetable(start, end) }.compose(ScrapperExceptionTransformer()).map { it.mapTimetable() }
Mode.HYBRID, Mode.API -> mobile.getDictionaries().flatMap { dict -> Mode.HYBRID, Mode.API -> rxSingle { mobile.getTimetable(start, end, 0).mapTimetable(mobile.getDictionaries()) }
mobile.getTimetable(start, end, 0).map { it.mapTimetable(dict) }
}
} }
} }

View file

@ -9,7 +9,7 @@ import org.threeten.bp.format.DateTimeFormatter.ofPattern
import java.sql.Timestamp import java.sql.Timestamp
import java.util.Date import java.util.Date
fun String.toLocalDateTime(format: String) = LocalDateTime.parse(this, ofPattern(format)) fun String.toLocalDateTime(format: String): LocalDateTime = LocalDateTime.parse(this, ofPattern(format))
fun Long.toLocalDate(): LocalDate = Instant fun Long.toLocalDate(): LocalDate = Instant
.ofEpochMilli(this * 1000L) .ofEpochMilli(this * 1000L)