Bump org.jlleitschuh.gradle.ktlint from 9.2.1 to 10.1.0 (#90)

This commit is contained in:
dependabot[bot] 2021-08-22 10:24:37 +00:00 committed by GitHub
parent f15cc8223a
commit b991d0c5b6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
27 changed files with 389 additions and 228 deletions

View file

@ -31,3 +31,24 @@ jobs:
./gradlew test --stacktrace
./gradlew jacocoTestReport --stacktrace
- uses: codecov/codecov-action@v1
link:
name: Lint check
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: fkirc/skip-duplicate-actions@master
- uses: actions/checkout@v2
- uses: actions/setup-java@v1
with:
java-version: 11
- uses: actions/cache@v2
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*') }}
- name: Lint
run: |
./gradlew ktlintCheck --stacktrace
- uses: codecov/codecov-action@v1

View file

@ -1,6 +1,6 @@
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.5.21' apply false
id "org.jlleitschuh.gradle.ktlint" version "9.2.1"
id "org.jlleitschuh.gradle.ktlint" version "10.1.0"
id "io.github.gradle-nexus.publish-plugin" version "1.1.0"
}

View file

@ -106,13 +106,14 @@ class Mobile {
}
val cert = certRes.tokenCert!!
certKey = cert.certificateKey
baseUrl = cert.baseUrl.removeSuffix("/")
privateKey = getPrivateKeyFromCert(apiKey.ifEmpty {
val privateKeyValue = apiKey.ifEmpty {
Base64.decode(if (cert.baseUrl.contains("fakelog")) "KDAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ1Njc4OUFCKQ==" else "KENFNzVFQTU5OEM3NzQzQUQ5QjBCNzMyOERFRDg1QjA2KQ==")
.toString(Charset.defaultCharset())
.removeSurrounding("(", ")")
}, cert.certificatePfx)
}
certKey = cert.certificateKey
baseUrl = cert.baseUrl.removeSuffix("/")
privateKey = getPrivateKeyFromCert(privateKeyValue, cert.certificatePfx)
return serviceManager.getRegisterRepository(cert.baseUrl).getStudents().map {
it.copy().apply {

View file

@ -88,13 +88,14 @@ class MobileRepository(private val api: MobileService) {
}
suspend fun sendMessage(sender: String, subject: String, content: String, recipients: List<Recipient>, loginId: Int, studentId: Int): Message {
return api.sendMessage(SendMessageRequest(
val request = SendMessageRequest(
sender = sender,
subject = subject,
content = content,
recipients = recipients,
loginId = loginId,
studentId = studentId
))
)
return api.sendMessage(request)
}
}

View file

@ -9,13 +9,14 @@ import io.github.wulkanowy.sdk.mobile.service.RegisterService
class RegisterRepository(private val api: RegisterService) {
suspend fun getCertificate(token: String, pin: String, deviceName: String, android: String, firebaseToken: String): CertificateResponse {
return api.getCertificate(CertificateRequest(
val request = CertificateRequest(
tokenKey = token,
pin = pin,
deviceName = "$deviceName (Wulkanowy)",
deviceSystemVersion = android,
firebaseToken = firebaseToken
))
)
return api.getCertificate(request)
}
suspend fun getStudents(): List<Student> = api.getPupils(object : ApiRequest() {}).data.orEmpty()

View file

@ -37,17 +37,18 @@ class RepositoryManager(
return Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(MoshiConverterFactory.create())
.client(OkHttpClient().newBuilder()
.addInterceptor(HttpLoggingInterceptor().setLevel(logLevel))
.addInterceptor(ErrorInterceptor())
.addInterceptor(SignInterceptor(privateKey, certKey))
.apply {
interceptors.forEach {
if (it.second) addNetworkInterceptor(it.first)
else addInterceptor(it.first)
.client(
OkHttpClient().newBuilder()
.addInterceptor(HttpLoggingInterceptor().setLevel(logLevel))
.addInterceptor(ErrorInterceptor())
.addInterceptor(SignInterceptor(privateKey, certKey))
.apply {
interceptors.forEach {
if (it.second) addNetworkInterceptor(it.first)
else addInterceptor(it.first)
}
}
}
.build()
.build()
)
}
}

View file

@ -33,9 +33,10 @@ open class BaseLocalTest {
fun getRetrofitBuilder(): Retrofit.Builder = Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(MoshiConverterFactory.create())
.client(OkHttpClient().newBuilder()
.addInterceptor(ErrorInterceptor())
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
.build()
.client(
OkHttpClient().newBuilder()
.addInterceptor(ErrorInterceptor())
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
.build()
)
}

View file

@ -38,10 +38,11 @@ class UonetTest {
return Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(MoshiConverterFactory.create())
.client(OkHttpClient().newBuilder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
.addInterceptor(SignInterceptor(privateKey, certKey))
.build()
.client(
OkHttpClient().newBuilder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
.addInterceptor(SignInterceptor(privateKey, certKey))
.build()
)
}
@ -49,9 +50,10 @@ class UonetTest {
@BeforeClass
fun setUp() {
// RegisterRepository
val register = RegisterRepository(getRetrofitBuilder("", "")
.baseUrl("$HOST/$SYMBOL/mobile-api/Uczen.v3.UczenStart/")
.build().create()
val register = RegisterRepository(
api = getRetrofitBuilder("", "")
.baseUrl("$HOST/$SYMBOL/mobile-api/Uczen.v3.UczenStart/")
.build().create()
)
val certificate = runBlocking { register.getCertificate(TOKEN, PIN, DEVICE_NAME, "8.1.0", "") }
@ -71,9 +73,10 @@ class UonetTest {
student = pupils[0]
// MobileRepository
mobile = MobileRepository(getRetrofitBuilder(privateKey, certKey)
.baseUrl("$HOST/powiatwulkanowy/${student.reportingUnitSymbol}/mobile-api/Uczen.v3.Uczen/")
.build().create()
mobile = MobileRepository(
api = getRetrofitBuilder(privateKey, certKey)
.baseUrl("$HOST/powiatwulkanowy/${student.reportingUnitSymbol}/mobile-api/Uczen.v3.Uczen/")
.build().create()
)
}
}

View file

@ -78,9 +78,11 @@ fun List<GradesStatisticsPartial>.mapGradesStatisticsPartial() = map {
}
private fun GradeStatisticsPartialSeries.addGradeValue(): GradeStatisticsPartialSeries {
return copy(items = items.orEmpty().reversed().mapIndexed { i, item ->
item.copy().apply {
grade = i + 1
}
}.reversed())
return copy(
items = items.orEmpty().reversed().mapIndexed { i, item ->
item.copy().apply {
grade = i + 1
}
}.reversed()
)
}

View file

@ -103,14 +103,14 @@ class AutoLoginInterceptor(
}
}
if (when (loginType) {
STANDARD -> doc.select(SELECTOR_STANDARD)
ADFS -> doc.select(SELECTOR_ADFS)
ADFSLight, ADFSLightCufs, ADFSLightScoped -> doc.select(SELECTOR_ADFS_LIGHT)
ADFSCards -> doc.select(SELECTOR_ADFS_CARDS)
else -> Elements()
}.isNotEmpty()
) {
val loginSelectors = when (loginType) {
STANDARD -> doc.select(SELECTOR_STANDARD)
ADFS -> doc.select(SELECTOR_ADFS)
ADFSLight, ADFSLightCufs, ADFSLightScoped -> doc.select(SELECTOR_ADFS_LIGHT)
ADFSCards -> doc.select(SELECTOR_ADFS_CARDS)
else -> Elements()
}
if (loginSelectors.isNotEmpty()) {
throw NotLoggedInException("User not logged in")
}
@ -128,10 +128,12 @@ class AutoLoginInterceptor(
.message(message())
.request(request)
.protocol(Protocol.HTTP_1_1)
.body(response()?.errorBody() ?: object : ResponseBody() {
override fun contentLength() = 0L
override fun contentType(): MediaType? = null
override fun source(): BufferedSource = Buffer()
})
.body(
body = response()?.errorBody() ?: object : ResponseBody() {
override fun contentLength() = 0L
override fun contentType(): MediaType? = null
override fun source(): BufferedSource = Buffer()
}
)
.build()
}

View file

@ -15,13 +15,14 @@ class UserAgentInterceptor(
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
return chain.proceed(chain.request().newBuilder()
.addHeader("User-Agent",
return chain.proceed(
chain.request().newBuilder().addHeader(
"User-Agent",
"Mozilla/5.0 (Linux; Android $androidVersion; $buildTag) " +
"AppleWebKit/$webKitRev (KHTML, like Gecko) " +
"Chrome/$chromeRev Mobile " +
"Safari/$webKitRev")
.build()
"Safari/$webKitRev"
).build()
)
}
}

View file

@ -91,111 +91,158 @@ class LoginHelper(
suspend fun sendCertificate(cert: CertificateResponse, email: String, url: String = cert.action): SendCertificateResponse {
cookies.cookieStore.removeAll()
val res = api.sendCertificate(url, mapOf(
"wa" to cert.wa,
"wresult" to cert.wresult,
"wctx" to cert.wctx
))
val res = api.sendCertificate(
url = url,
certificate = mapOf(
"wa" to cert.wa,
"wresult" to cert.wresult,
"wctx" to cert.wctx
)
)
if (email.contains("||")) api.switchLogin("$url?rebuild=${email.substringAfter("||", "")}")
if (email.contains("||")) {
api.switchLogin("$url?rebuild=${email.substringAfter("||", "")}")
}
return res
}
private suspend fun sendStandard(email: String, password: String): CertificateResponse {
return certificateAdapter.fromHtml(api.sendCredentials(firstStepReturnUrl, mapOf(
"LoginName" to email,
"Password" to password
)))
return certificateAdapter.fromHtml(
api.sendCredentials(
returnUrl = firstStepReturnUrl,
credentials = mapOf(
"LoginName" to email,
"Password" to password
)
)
)
}
private suspend fun sendADFSLightGeneric(email: String, password: String, type: Scrapper.LoginType): CertificateResponse {
val res = certificateAdapter.fromHtml(api.sendADFSForm(
getADFSUrl(type), mapOf(
"Username" to email,
"Password" to password,
"x" to "0",
"y" to "0"
val res = certificateAdapter.fromHtml(
api.sendADFSForm(
url = getADFSUrl(type),
values = mapOf(
"Username" to email,
"Password" to password,
"x" to "0",
"y" to "0"
)
)
))
)
logger.debug("Page title after credentials sent: ${res.title}, action: ${res.action} wresult: ${res.wresult.length}, wctx: ${res.wctx}")
return certificateAdapter.fromHtml(api.sendADFSForm(
res.action, mapOf(
"wa" to res.wa,
"wresult" to res.wresult,
"wctx" to res.wctx
return certificateAdapter.fromHtml(
api.sendADFSForm(
url = res.action,
values = mapOf(
"wa" to res.wa,
"wresult" to res.wresult,
"wctx" to res.wctx
)
)
))
)
}
private suspend fun sendADFS(email: String, password: String): CertificateResponse {
val res = api.getForm(getADFSUrl(ADFS))
if (res.formAction.isBlank()) throw VulcanException("Invalid ADFS login page: '${res.title}'. Try again")
val form = certificateAdapter.fromHtml(api.sendADFSForm("$schema://adfs.$host/${res.formAction.removePrefix("/")}", mapOf(
"__db" to res.db,
"__VIEWSTATE" to res.viewstate,
"__VIEWSTATEGENERATOR" to res.viewStateGenerator,
"__EVENTVALIDATION" to res.eventValidation,
"UsernameTextBox" to email,
"PasswordTextBox" to password,
"SubmitButton.x" to "0",
"SubmitButton.y" to "0"
)))
val form = certificateAdapter.fromHtml(
api.sendADFSForm(
url = "$schema://adfs.$host/${res.formAction.removePrefix("/")}",
values = mapOf(
"__db" to res.db,
"__VIEWSTATE" to res.viewstate,
"__VIEWSTATEGENERATOR" to res.viewStateGenerator,
"__EVENTVALIDATION" to res.eventValidation,
"UsernameTextBox" to email,
"PasswordTextBox" to password,
"SubmitButton.x" to "0",
"SubmitButton.y" to "0"
)
)
)
return certificateAdapter.fromHtml(api.sendADFSForm(form.action, mapOf(
"wa" to form.wa,
"wresult" to form.wresult,
"wctx" to form.wctx
)))
return certificateAdapter.fromHtml(
api.sendADFSForm(
url = form.action,
values = mapOf(
"wa" to form.wa,
"wresult" to form.wresult,
"wctx" to form.wctx
)
)
)
}
private suspend fun sendADFSMS(email: String, password: String): CertificateResponse {
val res = api.sendADFSMSForm(getADFSUrl(ADFS), mapOf(
"UserName" to email,
"Password" to password,
"AuthMethod" to "FormsAuthentication"
))
val res = api.sendADFSMSForm(
url = getADFSUrl(ADFS),
values = mapOf(
"UserName" to email,
"Password" to password,
"AuthMethod" to "FormsAuthentication"
)
)
val form = certificateAdapter.fromHtml(res)
return certificateAdapter.fromHtml(api.sendADFSForm(form.action, mapOf(
"wa" to form.wa,
"wresult" to form.wresult,
"wctx" to form.wctx
)))
return certificateAdapter.fromHtml(
api.sendADFSForm(
url = form.action,
values = mapOf(
"wa" to form.wa,
"wresult" to form.wresult,
"wctx" to form.wctx
)
)
)
}
private suspend fun sendADFSCards(email: String, password: String): CertificateResponse {
val form = api.getForm(getADFSUrl(ADFSCards))
val form2 = api.sendADFSFormStandardChoice("$schema://adfs.$host/${form.formAction.removePrefix("/")}", mapOf(
"__db" to form.db,
"__VIEWSTATE" to form.viewstate,
"__VIEWSTATEGENERATOR" to form.viewStateGenerator,
"__EVENTVALIDATION" to form.eventValidation,
"PassiveSignInButton.x" to "0",
"PassiveSignInButton.y" to "0"
))
val form2 = api.sendADFSFormStandardChoice(
url = "$schema://adfs.$host/${form.formAction.removePrefix("/")}",
formState = mapOf(
"__db" to form.db,
"__VIEWSTATE" to form.viewstate,
"__VIEWSTATEGENERATOR" to form.viewStateGenerator,
"__EVENTVALIDATION" to form.eventValidation,
"PassiveSignInButton.x" to "0",
"PassiveSignInButton.y" to "0"
)
)
val form3 = certificateAdapter.fromHtml(api.sendADFSForm("$schema://adfs.$host/${form2.formAction.removePrefix("/")}", mapOf(
"__db" to form2.db,
"__VIEWSTATE" to form2.viewstate,
"__VIEWSTATEGENERATOR" to form2.viewStateGenerator,
"__EVENTVALIDATION" to form2.eventValidation,
"SubmitButton.x" to "0",
"SubmitButton.y" to "0",
"UsernameTextBox" to email,
"PasswordTextBox" to password
)))
val form3 = certificateAdapter.fromHtml(
api.sendADFSForm(
url = "$schema://adfs.$host/${form2.formAction.removePrefix("/")}",
values = mapOf(
"__db" to form2.db,
"__VIEWSTATE" to form2.viewstate,
"__VIEWSTATEGENERATOR" to form2.viewStateGenerator,
"__EVENTVALIDATION" to form2.eventValidation,
"SubmitButton.x" to "0",
"SubmitButton.y" to "0",
"UsernameTextBox" to email,
"PasswordTextBox" to password
)
)
)
return certificateAdapter.fromHtml(api.sendADFSForm(form3.action, mapOf(
"wa" to form3.wa,
"wresult" to form3.wresult,
"wctx" to form3.wctx
)))
return certificateAdapter.fromHtml(
api.sendADFSForm(
url = form3.action,
values = mapOf(
"wa" to form3.wa,
"wresult" to form3.wresult,
"wctx" to form3.wctx
)
)
)
}
private fun getADFSUrl(type: Scrapper.LoginType): String {

View file

@ -41,9 +41,15 @@ class AccountRepository(private val account: AccountService) {
ADFSLight, ADFSLightScoped, ADFSLightCufs -> account.sendPasswordResetRequestADFSLight(url, email, captchaCode)
ADFS, ADFSCards -> {
val page = account.getPasswordResetPageADFS(url)
account.sendPasswordResetRequestADFS(url, email, captchaCode, (page.html.select("[type=hidden]").map { input ->
val formFields = page.html.select("[type=hidden]").map { input ->
input.attr("name") to input.attr("value")
}).toMap().plus("btSend.x" to "5").plus("btSend.y" to "6"))
}.toMap()
account.sendPasswordResetRequestADFS(
url = url,
username = email,
captchaCode = captchaCode,
viewStateParams = formFields.plus("btSend.x" to "5").plus("btSend.y" to "6")
)
}
else -> throw ScrapperException("Never happen")
}

View file

@ -28,10 +28,14 @@ class MessagesRepository(private val api: MessagesService) {
}
suspend fun getRecipients(unitId: Int, role: Int = 2): List<Recipient> {
return api.getRecipients(RecipientsRequest(RecipientsRequest.ParamsVo(
unitId = unitId,
role = role
))).handleErrors().data.orEmpty().map {
return api.getRecipients(
recipientsRequest = RecipientsRequest(
paramsVo = RecipientsRequest.ParamsVo(
unitId = unitId,
role = role
)
)
).handleErrors().data.orEmpty().map {
it.copy(shortName = it.name.normalizeRecipient())
}
}
@ -59,8 +63,11 @@ class MessagesRepository(private val api: MessagesService) {
}
suspend fun getMessageRecipients(messageId: Int, loginId: Int): List<Recipient> {
return (if (0 == loginId) api.getMessageRecipients(messageId).handleErrors()
else api.getMessageSender(loginId, messageId)).handleErrors().data.orEmpty().map { recipient ->
val recipients = when (loginId) {
0 -> api.getMessageRecipients(messageId).handleErrors()
else -> api.getMessageSender(loginId, messageId)
}
return recipients.handleErrors().data.orEmpty().map { recipient ->
recipient.copy(shortName = recipient.name.normalizeRecipient())
}
}

View file

@ -99,12 +99,15 @@ class ServiceManager(
}
fun getAccountService(): AccountService {
return getRetrofit(getClientBuilder(errIntercept = false, loginIntercept = false, separateJar = true),
urlGenerator.generate(UrlGenerator.Site.LOGIN), false).create()
return getRetrofit(
getClientBuilder(errIntercept = false, loginIntercept = false, separateJar = true),
urlGenerator.generate(UrlGenerator.Site.LOGIN), false
).create()
}
fun getRegisterService(): RegisterService {
return getRetrofit(getClientBuilder(errIntercept = false, loginIntercept = false, separateJar = true),
return getRetrofit(
getClientBuilder(errIntercept = false, loginIntercept = false, separateJar = true),
urlGenerator.generate(UrlGenerator.Site.LOGIN),
false
).create()
@ -125,10 +128,19 @@ class ServiceManager(
if (studentInterceptor) {
if (0 == diaryId || 0 == studentId) throw ScrapperException("Student or/and diaryId id are not set")
client.addInterceptor(StudentCookieInterceptor(cookies, schema, host, diaryId, studentId, when (schoolYear) {
0 -> if (LocalDate.now().monthValue < 9) LocalDate.now().year - 1 else LocalDate.now().year // fallback
else -> schoolYear
}))
client.addInterceptor(
StudentCookieInterceptor(
cookies = cookies,
schema = schema,
host = host,
diaryId = diaryId,
studentId = studentId,
schoolYear = when (schoolYear) {
0 -> if (LocalDate.now().monthValue < 9) LocalDate.now().year - 1 else LocalDate.now().year // fallback
else -> schoolYear
}
)
)
}
return client
}
@ -145,11 +157,14 @@ class ServiceManager(
.baseUrl(baseUrl)
.client(client.build())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(if (gson) MoshiConverterFactory.create(Moshi.Builder()
.add(CustomDateAdapter())
.add(GradeDateDeserializer())
.build()
) else JspoonConverterFactory.create())
.addConverterFactory(
if (gson) MoshiConverterFactory.create(
Moshi.Builder()
.add(CustomDateAdapter())
.add(GradeDateDeserializer())
.build()
) else JspoonConverterFactory.create()
)
.build()
private fun getClientBuilder(

View file

@ -52,11 +52,14 @@ abstract class BaseLocalTest : BaseTest() {
): T = Retrofit.Builder()
.client(okHttp)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(if (!html) MoshiConverterFactory.create(Moshi.Builder()
.add(CustomDateAdapter())
.add(GradeDateDeserializer())
.build()
) else JspoonConverterFactory.create())
.addConverterFactory(
if (!html) MoshiConverterFactory.create(
Moshi.Builder()
.add(CustomDateAdapter())
.add(GradeDateDeserializer())
.build()
) else JspoonConverterFactory.create()
)
.baseUrl(url)
.build()
.create(service)

View file

@ -33,10 +33,13 @@ class ScrapperRemoteTest : BaseTest() {
classId = 1
androidVersion = "9.0"
buildTag = "Wulkanowy"
addInterceptor({
println("Request event ${it.request().url.host}")
it.proceed(it.request())
}, true)
addInterceptor(
interceptor = {
println("Request event ${it.request().url.host}")
it.proceed(it.request())
},
network = true
)
}
}
@ -51,10 +54,12 @@ class ScrapperRemoteTest : BaseTest() {
@Test
fun sendPasswordResetRequest() {
val res = runBlocking {
api.sendPasswordResetRequest("https://fakelog.cf",
"Default",
"jan@fakelog.cf",
"03AOLTBLQRPyr0pWvWLRAgD4hRLfxktoqD2IVweeMuXwbkpR_8S9YQtcS3cAXqUOyEw3NxfvwzV0lTjgFWyl8j3UXGQpsc2nvQcqIofj1N8DYfxvtZO-h24W_S0Z9-fDnfXErd7vERS-Ny4d5IU1FupBAEKvT8rrf3OA3GYYbMM7TwB8b_o9Tt192TqYnSxkyIYE4UdaZnLBA0KIXxlBAoqM6QGlPEsSPK9gmCGx-0hn68w-UBQkv_ghRruf4kpv2Shw5emcP-qHBlv3YjAagsb_358K0v8uGJeyLrx4dXN9Ky02TXFMKYWNHz29fjhfunxT73u_PrsLj56f-MjOXrqO894NkUlJ7RkTTclwIsqXtJ794LEBH--mtsqZBND0miR5-odmZszqiNB3V5UsS5ObsqF_fWMl2TCWyNTTvF4elOGwOEeKiumVpjB6e740COxvxN3vbkNWxP9eeghpd5nPN5l2wUV3VL2R5s44TbqHqkrkNpUOd3h7efs3cQtCfGc-tCXoqLC26LxT7aztvKpjXMuqGEf-7wbQ")
api.sendPasswordResetRequest(
registerBaseUrl = "https://fakelog.cf",
symbol = "Default",
email = "jan@fakelog.cf",
captchaCode = "03AOLTBLQRPyr0pWvWLRAgD4hRLfxktoqD2IVweeMuXwbkpR_8S9YQtcS3cAXqUOyEw3NxfvwzV0lTjgFWyl8j3UXGQpsc2nvQcqIofj1N8DYfxvtZO-h24W_S0Z9-fDnfXErd7vERS-Ny4d5IU1FupBAEKvT8rrf3OA3GYYbMM7TwB8b_o9Tt192TqYnSxkyIYE4UdaZnLBA0KIXxlBAoqM6QGlPEsSPK9gmCGx-0hn68w-UBQkv_ghRruf4kpv2Shw5emcP-qHBlv3YjAagsb_358K0v8uGJeyLrx4dXN9Ky02TXFMKYWNHz29fjhfunxT73u_PrsLj56f-MjOXrqO894NkUlJ7RkTTclwIsqXtJ794LEBH--mtsqZBND0miR5-odmZszqiNB3V5UsS5ObsqF_fWMl2TCWyNTTvF4elOGwOEeKiumVpjB6e740COxvxN3vbkNWxP9eeghpd5nPN5l2wUV3VL2R5s44TbqHqkrkNpUOd3h7efs3cQtCfGc-tCXoqLC26LxT7aztvKpjXMuqGEf-7wbQ"
)
}
assertTrue(res.startsWith("Wysłano wiadomość na zapisany w systemie adres e-mail"))
@ -342,8 +347,10 @@ class ScrapperRemoteTest : BaseTest() {
@Test
fun sendMessage() {
runBlocking {
api.sendMessage("Temat wiadomości", "Treść",
listOf(Recipient("0", "Kowalski Jan", 0, 0, 2, "hash"))
api.sendMessage(
subject = "Temat wiadomości",
content = "Treść",
recipients = listOf(Recipient("0", "Kowalski Jan", 0, 0, 2, "hash")),
)
}
}

View file

@ -16,11 +16,12 @@ import java.time.LocalDateTime
class AttendanceTest : BaseLocalTest() {
private val student by lazy {
runBlocking { getStudentRepo {
val repo = getStudentRepo {
it.enqueue("Frekwencja.json", AttendanceTest::class.java)
it.enqueue("WitrynaUcznia.html", RegisterTest::class.java)
it.enqueue("UczenCache.json", RegisterTest::class.java)
}.getAttendance(getLocalDate(2018, 10, 1), null) }
}
runBlocking { repo.getAttendance(getLocalDate(2018, 10, 1), null) }
}
@Test
@ -143,11 +144,12 @@ class AttendanceTest : BaseLocalTest() {
@Test
fun getAttendance_requestDateFormat() {
runBlocking { getStudentRepo {
val repo = getStudentRepo {
it.enqueue("Frekwencja.json", AttendanceTest::class.java)
it.enqueue("WitrynaUcznia.html", RegisterTest::class.java)
it.enqueue("UczenCache.json", RegisterTest::class.java)
}.getAttendance(getLocalDate(2018, 10, 1), null) }
}
runBlocking { repo.getAttendance(getLocalDate(2018, 10, 1), null) }
val request = server.takeRequest()
val adapter = AttendanceRequestJsonAdapter(Moshi.Builder().add(CustomDateAdapter()).build())

View file

@ -81,13 +81,12 @@ class HomepageTest : BaseLocalTest() {
server.start(3000)
val res = runBlocking { repo.getLastGrades() }
assertEquals(
listOf(
"j. angielski: 1, 6",
"j. polski: 6, 1",
"matematyka: 4+, -"
), res
val expected = listOf(
"j. angielski: 1, 6",
"j. polski: 6, 1",
"matematyka: 4+, -"
)
assertEquals(expected, res)
}
@Test
@ -97,12 +96,11 @@ class HomepageTest : BaseLocalTest() {
server.start(3000)
val res = runBlocking { repo.getFreeDays() }
assertEquals(
listOf(
"Czwartek (20.06.2019) - Sobota (31.08.2019) - Ferie letnie",
"Czwartek (15.08.2019) - Wniebowzięcie Najświętszej Maryi Panny"
), res
val expected = listOf(
"Czwartek (20.06.2019) - Sobota (31.08.2019) - Ferie letnie",
"Czwartek (15.08.2019) - Wniebowzięcie Najświętszej Maryi Panny"
)
assertEquals(expected, res)
}
@Test
@ -148,10 +146,11 @@ class HomepageTest : BaseLocalTest() {
server.start(3000)
val numbers = runBlocking { repo.getKidsLuckyNumbers() }
assertEquals(listOf(
val expected = listOf(
LuckyNumber("002547", "T", 37),
LuckyNumber("010472", "ZSP Warcie", 12)
), numbers)
)
assertEquals(expected, numbers)
server.takeRequest()
with(server.takeRequest().body.readUtf8()) {

View file

@ -83,7 +83,7 @@ class AutoLoginInterceptorTest : BaseLocalTest() {
val a = awaitAll(notes1, notes2, notes3)
assertEquals(1 + 1 + 1, a.size)
assertEquals((1 + 1 + 1), a.size)
}
// @Test

View file

@ -20,16 +20,23 @@ import java.net.CookieManager
class RegisterTest : BaseLocalTest() {
private val login by lazy {
LoginHelper(Scrapper.LoginType.STANDARD, "http", "fakelog.localhost:3000", "default", CookieManager(),
getService(LoginService::class.java, "http://fakelog.localhost:3000/", true, getOkHttp(true, false, Scrapper.LoginType.STANDARD)))
LoginHelper(
loginType = Scrapper.LoginType.STANDARD,
schema = "http",
host = "fakelog.localhost:3000",
symbol = "default",
cookies = CookieManager(),
api = getService(LoginService::class.java, "http://fakelog.localhost:3000/", true, getOkHttp(true, false, Scrapper.LoginType.STANDARD))
)
}
private val registerStudent by lazy {
RegisterRepository("default", "jan@fakelog.localhost", "jan123", login,
getService(RegisterService::class.java, "http://fakelog.localhost:3000/Default/", true, getOkHttp(false, false)),
getService(MessagesService::class.java, "http://fakelog.localhost:3000", false),
getService(StudentService::class.java, "http://fakelog.localhost:3000", false),
ServiceManager.UrlGenerator("http", "fakelog.localhost:3000", "default", "123")
RegisterRepository(
startSymbol = "default", email = "jan@fakelog.localhost", password = "jan123", loginHelper = login,
register = getService(RegisterService::class.java, "http://fakelog.localhost:3000/Default/", true, getOkHttp(false, false)),
messages = getService(MessagesService::class.java, "http://fakelog.localhost:3000", false),
student = getService(StudentService::class.java, "http://fakelog.localhost:3000", false),
url = ServiceManager.UrlGenerator("http", "fakelog.localhost:3000", "default", "123")
)
}

View file

@ -202,8 +202,8 @@ class RegisterRepositoryTest : BaseLocalTest() {
runBlocking { getRegisterRepository("Default").getStudents() }
} catch (e: Throwable) {
assertTrue(e is VulcanException)
assertEquals("Wystąpił nieoczekiwany błąd. Wystąpił błąd aplikacji. Prosimy zalogować się ponownie. Jeśli problem będzie się powtarzał, prosimy o kontakt z serwisem.",
e.message)
val expected = "Wystąpił nieoczekiwany błąd. Wystąpił błąd aplikacji. Prosimy zalogować się ponownie. Jeśli problem będzie się powtarzał, prosimy o kontakt z serwisem."
assertEquals(expected, e.message)
}
assertEquals("/Default/Account/LogOn", server.takeRequest().path)
@ -222,8 +222,8 @@ class RegisterRepositoryTest : BaseLocalTest() {
runBlocking { getRegisterRepository(" Rzeszów + ").getStudents() }
} catch (e: Throwable) {
assertTrue(e is VulcanException)
assertEquals("Wystąpił nieoczekiwany błąd. Wystąpił błąd aplikacji. Prosimy zalogować się ponownie. Jeśli problem będzie się powtarzał, prosimy o kontakt z serwisem.",
e.message)
val expected = "Wystąpił nieoczekiwany błąd. Wystąpił błąd aplikacji. Prosimy zalogować się ponownie. Jeśli problem będzie się powtarzał, prosimy o kontakt z serwisem."
assertEquals(expected, e.message)
}
assertEquals("/rzeszow/Account/LogOn", server.takeRequest().path)
@ -242,8 +242,8 @@ class RegisterRepositoryTest : BaseLocalTest() {
runBlocking { getRegisterRepository(" Niepoprawny symbol no ale + ").getStudents() }
} catch (e: Throwable) {
assertTrue(e is VulcanException)
assertEquals("Wystąpił nieoczekiwany błąd. Wystąpił błąd aplikacji. Prosimy zalogować się ponownie. Jeśli problem będzie się powtarzał, prosimy o kontakt z serwisem.",
e.message)
val expected = "Wystąpił nieoczekiwany błąd. Wystąpił błąd aplikacji. Prosimy zalogować się ponownie. Jeśli problem będzie się powtarzał, prosimy o kontakt z serwisem."
assertEquals(expected, e.message)
}
assertEquals("/niepoprawnysymbolnoale/Account/LogOn", server.takeRequest().path)
@ -262,8 +262,8 @@ class RegisterRepositoryTest : BaseLocalTest() {
runBlocking { getRegisterRepository(" + ").getStudents() }
} catch (e: Throwable) {
assertTrue(e is VulcanException)
assertEquals("Wystąpił nieoczekiwany błąd. Wystąpił błąd aplikacji. Prosimy zalogować się ponownie. Jeśli problem będzie się powtarzał, prosimy o kontakt z serwisem.",
e.message)
val expected = "Wystąpił nieoczekiwany błąd. Wystąpił błąd aplikacji. Prosimy zalogować się ponownie. Jeśli problem będzie się powtarzał, prosimy o kontakt z serwisem."
assertEquals(expected, e.message)
}
assertEquals("/Default/Account/LogOn", server.takeRequest().path)
@ -282,8 +282,8 @@ class RegisterRepositoryTest : BaseLocalTest() {
runBlocking { getRegisterRepository("Default").getStudents() }
} catch (e: Throwable) {
assertTrue(e is VulcanException)
assertEquals("Wystąpił nieoczekiwany błąd. Wystąpił błąd aplikacji. Prosimy zalogować się ponownie. Jeśli problem będzie się powtarzał, prosimy o kontakt z serwisem.",
e.message)
val expected = "Wystąpił nieoczekiwany błąd. Wystąpił błąd aplikacji. Prosimy zalogować się ponownie. Jeśli problem będzie się powtarzał, prosimy o kontakt z serwisem."
assertEquals(expected, e.message)
}
assertEquals("/Default/Account/LogOn", server.takeRequest().path)

View file

@ -20,13 +20,24 @@ class ServiceManagerTest : BaseLocalTest() {
@Test
fun interceptorTest() {
val manager = ServiceManager(OkHttpClientBuilderFactory(), HttpLoggingInterceptor.Level.NONE,
Scrapper.LoginType.STANDARD, "http", "fakelog.localhost:3000", "default", "email", "password",
"schoolSymbol", 123, 101, 2019, false, "", ""
val manager = ServiceManager(
okHttpClientBuilderFactory = OkHttpClientBuilderFactory(),
logLevel = HttpLoggingInterceptor.Level.NONE,
loginType = Scrapper.LoginType.STANDARD,
schema = "http",
host = "fakelog.localhost:3000",
symbol = "default",
email = "email",
password = "password",
schoolSymbol = "schoolSymbol",
studentId = 123,
diaryId = 101,
schoolYear = 2019,
emptyCookieJarIntercept = false,
androidVersion = "",
buildTag = ""
)
manager.setInterceptor({
throw ScrapperException("Test")
})
manager.setInterceptor({ throw ScrapperException("Test") })
try {
runBlocking { manager.getStudentService().getNotes() }
@ -39,17 +50,28 @@ class ServiceManagerTest : BaseLocalTest() {
fun interceptorTest_prepend() {
server.enqueue(MockResponse().setBody(NotesTest::class.java.getResource("UwagiIOsiagniecia.json").readText()))
server.start(3000)
val manager = ServiceManager(OkHttpClientBuilderFactory(), HttpLoggingInterceptor.Level.NONE,
Scrapper.LoginType.STANDARD, "http", "fakelog.localhost:3000", "default", "email", "password",
"schoolSymbol", 123, 101, 2019, false, "", ""
val manager = ServiceManager(
okHttpClientBuilderFactory = OkHttpClientBuilderFactory(),
logLevel = HttpLoggingInterceptor.Level.NONE,
loginType = Scrapper.LoginType.STANDARD,
schema = "http",
host = "fakelog.localhost:3000",
symbol = "default",
email = "email",
password = "password",
schoolSymbol = "schoolSymbol",
studentId = 123,
diaryId = 101,
schoolYear = 2019,
emptyCookieJarIntercept = false,
androidVersion = "",
buildTag = ""
)
manager.setInterceptor({
// throw IOException("Test")
it.proceed(it.request())
})
manager.setInterceptor({
throw ScrapperException("Test")
}, false)
manager.setInterceptor({ throw ScrapperException("Test") }, false)
try {
runBlocking { manager.getStudentService().getNotes() }
@ -94,7 +116,8 @@ class ServiceManagerTest : BaseLocalTest() {
fun autoLoginInterceptor() {
server.enqueue(MockResponse().setResponseCode(503))
server.start(3000)
val manager = ServiceManager(OkHttpClientBuilderFactory(), HttpLoggingInterceptor.Level.NONE,
val manager = ServiceManager(
OkHttpClientBuilderFactory(), HttpLoggingInterceptor.Level.NONE,
Scrapper.LoginType.STANDARD, "http", "fakelog.localhost:3000", "default", "email", "password",
"schoolSymbol", 123, 101, 2019, true, "", ""
)

View file

@ -196,9 +196,10 @@ class Sdk {
fun setSimpleHttpLogger(logger: (String) -> Unit) {
logLevel = HttpLoggingInterceptor.Level.NONE
addInterceptor(HttpLoggingInterceptor(HttpLoggingInterceptor.Logger {
val interceptor = HttpLoggingInterceptor {
logger(it)
}).setLevel(HttpLoggingInterceptor.Level.BASIC))
}.setLevel(HttpLoggingInterceptor.Level.BASIC)
addInterceptor(interceptor)
}
fun addInterceptor(interceptor: Interceptor, network: Boolean = false) {
@ -466,11 +467,15 @@ class Sdk {
suspend fun getMessageDetails(messageId: Int, folderId: Int, read: Boolean = false, id: Int? = null) = withContext(Dispatchers.IO) {
when (mode) {
Mode.HYBRID, Mode.SCRAPPER -> scrapper.getMessageDetails(messageId, folderId, read, id).mapScrapperMessage()
Mode.API -> mobile.changeMessageStatus(messageId, when (folderId) {
1 -> "Odebrane"
2 -> "Wysłane"
else -> "Usunięte"
}, "Widoczna").let { MessageDetails("", emptyList()) }
Mode.API -> {
val folder = when (folderId) {
1 -> "Odebrane"
2 -> "Wysłane"
else -> "Usunięte"
}
mobile.changeMessageStatus(messageId, folder, "Widoczna")
MessageDetails("", emptyList())
}
}
}
@ -485,11 +490,12 @@ class Sdk {
when (mode) {
Mode.SCRAPPER -> scrapper.deleteMessages(messages, folderId)
Mode.HYBRID, Mode.API -> messages.map { messageId ->
mobile.changeMessageStatus(messageId, when (folderId) {
val folder = when (folderId) {
1 -> "Odebrane"
2 -> "Wysłane"
else -> "Usunięte"
}, "Usunieta")
}
mobile.changeMessageStatus(messageId, folder, "Usunieta")
}.isNotEmpty()
}
}

View file

@ -40,10 +40,11 @@ fun List<Student>.mapSemesters(studentId: Int) = filter { it.id == studentId }.m
private fun List<Semester>.mockSecondSemester(): List<Semester> {
if (size != 1) throw VulcanException("Expected semester list size 1, get $size")
val semester = single()
return (this + semester.copy(
val secondSemester = semester.copy(
semesterNumber = if (semester.semesterNumber == 1) 2 else 1,
semesterId = if (semester.semesterNumber == 1) semester.semesterId + 1 else semester.semesterId - 1,
start = if (semester.semesterNumber == 1) semester.end.plusDays(1) else of(semester.schoolYear, 9, 1),
end = if (semester.semesterNumber == 1) of(semester.schoolYear + 1, 8, 31) else semester.start.minusDays(1)
))
)
return (this + secondSemester)
}

View file

@ -46,11 +46,12 @@ fun List<ApiTimetable>.mapTimetable(dictionaries: Dictionaries) = map {
}.groupBy { Triple(it.date, it.number, it.studentPlan) }.map { (_, lessons) ->
if (lessons.size > 1 && lessons.any { !it.canceled } && lessons.any { it.canceled }) {
val canceled = lessons.first { it.canceled }
listOf(lessons.first { !it.canceled }.copy(
val lesson = lessons.first { !it.canceled }.copy(
subjectOld = canceled.subject,
teacherOld = canceled.teacher,
roomOld = canceled.room
))
)
listOf(lesson)
} else lessons
}.flatten()

View file

@ -106,10 +106,13 @@ class AttendanceMapperTest : BaseLocalTest() {
}
}
private fun createAttendance(cat: AttendanceCategory) = listOf(Attendance(1, Date(), "").apply {
number = 0
category = cat
excusable = false
excuseStatus = null
})
private fun createAttendance(cat: AttendanceCategory): List<Attendance> {
val item = Attendance(1, Date(), "").apply {
number = 0
category = cat
excusable = false
excuseStatus = null
}
return listOf(item)
}
}