From 378aba971692d334aa671933fb8bde500acddd57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miko=C5=82aj=20Pich?= Date: Sat, 14 Jul 2018 16:52:09 +0200 Subject: [PATCH] Add support for multiple SnP sites (#140) --- .../java/io/github/wulkanowy/api/Client.java | 40 +++- .../java/io/github/wulkanowy/api/SnP.java | 2 - .../wulkanowy/api/StudentAndParent.java | 56 +----- .../java/io/github/wulkanowy/api/Vulcan.java | 12 +- .../io/github/wulkanowy/api/generic/School.kt | 7 + .../io/github/wulkanowy/api/login/Login.java | 15 +- .../github/wulkanowy/api/login/StartPage.kt | 45 +++++ .../io/github/wulkanowy/api/ClientTest.java | 37 ++-- .../wulkanowy/api/StudentAndParentTest.java | 67 +------ .../github/wulkanowy/api/login/LoginTest.java | 16 +- .../wulkanowy/api/login/StartPageTest.kt | 68 +++++++ .../io/github/wulkanowy/api/Start-multi.html | 27 +++ .../api/{Start.html => Start-std.html} | 2 +- .../api/login/Logowanie-success.html | 13 ++ app/build.gradle | 2 +- .../data/db/dao/entities/SchoolTest.java | 22 +++ .../wulkanowy/data/db/dao/DbContract.java | 2 + .../wulkanowy/data/db/dao/DbHelper.java | 2 + .../wulkanowy/data/db/dao/DbRepository.java | 11 +- .../data/db/dao/entities/School.java | 179 ++++++++++++++++++ .../data/db/dao/entities/Student.java | 18 +- .../data/db/dao/entities/Symbol.java | 46 ++--- .../data/db/dao/migrations/Migration27.java | 2 +- .../data/db/dao/migrations/Migration29.kt | 60 ++++++ .../wulkanowy/data/sync/AccountSync.java | 78 +++++--- .../wulkanowy/utils/DataObjectConverter.java | 20 +- 26 files changed, 630 insertions(+), 219 deletions(-) create mode 100644 api/src/main/java/io/github/wulkanowy/api/generic/School.kt create mode 100644 api/src/main/java/io/github/wulkanowy/api/login/StartPage.kt create mode 100644 api/src/test/java/io/github/wulkanowy/api/login/StartPageTest.kt create mode 100644 api/src/test/resources/io/github/wulkanowy/api/Start-multi.html rename api/src/test/resources/io/github/wulkanowy/api/{Start.html => Start-std.html} (85%) create mode 100644 app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SchoolTest.java create mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/entities/School.java create mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration29.kt diff --git a/api/src/main/java/io/github/wulkanowy/api/Client.java b/api/src/main/java/io/github/wulkanowy/api/Client.java index 8bbae7ca..c6360d04 100644 --- a/api/src/main/java/io/github/wulkanowy/api/Client.java +++ b/api/src/main/java/io/github/wulkanowy/api/Client.java @@ -8,9 +8,11 @@ import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Date; +import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; +import io.github.wulkanowy.api.generic.School; import io.github.wulkanowy.api.login.Login; public class Client { @@ -25,16 +27,21 @@ public class Client { private String symbol; + private String schoolId; + + private List schools; + private Date lastSuccessRequest; private Cookies cookies = new Cookies(); private static final Logger logger = LoggerFactory.getLogger(Client.class); - Client(String email, String password, String symbol) { + Client(String email, String password, String symbol, String schoolId) { this.email = email; this.password = password; this.symbol = symbol; + this.schoolId = schoolId; setFullEndpointInfo(email); } @@ -62,14 +69,18 @@ public class Client { return; } + logger.info("Not logged. Login..."); + clearCookies(); - this.symbol = new Login(this).login(email, password, symbol); + new Login(this).login(email, password, symbol); + lastSuccessRequest = new Date(); + logger.info("Login successful on {} at {}", getHost(), new Date()); } private boolean isLoggedIn() { - logger.debug("Last success request: {}", lastSuccessRequest); - logger.debug("Cookies: {}", getCookies().size()); + logger.trace("Last success request: {}", lastSuccessRequest); + logger.trace("Cookies: {}", getCookies().size()); return getCookies().size() > 0 && lastSuccessRequest != null && 5 > TimeUnit.MILLISECONDS.toMinutes(new Date().getTime() - lastSuccessRequest.getTime()); @@ -92,15 +103,30 @@ public class Client { cookies = new Cookies(); } - String getHost() { + public String getHost() { return host; } + public void setSchools(List schools) { + this.schools = schools; + this.schoolId = schools.get(0).getId(); + } + + public List getSchools() throws IOException, VulcanException { + login(); + return schools; + } + + public String getSchoolId() throws IOException, VulcanException { + return schoolId != null ? schoolId : getSchools().get(0).getId(); + } + String getFilledUrl(String url) { return url .replace("{schema}", protocol) - .replace("{host}", host.replace(":", "%253A")) - .replace("{symbol}", symbol); + .replace("{host}", host) + .replace("{symbol}", symbol) + .replace("{ID}", schoolId != null ? schoolId : ""); } public Document getPageByUrl(String url) throws IOException, VulcanException { diff --git a/api/src/main/java/io/github/wulkanowy/api/SnP.java b/api/src/main/java/io/github/wulkanowy/api/SnP.java index 6747faf0..84ec1aed 100644 --- a/api/src/main/java/io/github/wulkanowy/api/SnP.java +++ b/api/src/main/java/io/github/wulkanowy/api/SnP.java @@ -13,8 +13,6 @@ import io.github.wulkanowy.api.generic.Student; public interface SnP { - String getSchoolID(); - void setDiaryID(String id); String getStudentID(); diff --git a/api/src/main/java/io/github/wulkanowy/api/StudentAndParent.java b/api/src/main/java/io/github/wulkanowy/api/StudentAndParent.java index 03a7b0e5..ba527f6a 100644 --- a/api/src/main/java/io/github/wulkanowy/api/StudentAndParent.java +++ b/api/src/main/java/io/github/wulkanowy/api/StudentAndParent.java @@ -20,32 +20,27 @@ import io.github.wulkanowy.api.generic.Student; public class StudentAndParent implements SnP { - private static final String START_PAGE_URL = "{schema}://uonetplus.{host}/{symbol}/Start.mvc/Index"; - private static final String BASE_URL = "{schema}://uonetplus-opiekun.{host}/{symbol}/{ID}/"; private static final String GRADES_PAGE_URL = "Oceny/Wszystkie"; private Client client; - private String schoolID; - private String studentID; private String diaryID; private static final Logger logger = LoggerFactory.getLogger(StudentAndParent.class); - StudentAndParent(Client client, String schoolID, String studentID, String diaryID) { + StudentAndParent(Client client, String studentID, String diaryID) { this.client = client; - this.schoolID = schoolID; this.studentID = studentID; this.diaryID = diaryID; } public StudentAndParent setUp() throws IOException, VulcanException { if (null == getStudentID() || "".equals(getStudentID())) { - Document doc = client.getPageByUrl(getSnpHomePageUrl()); + Document doc = client.getPageByUrl(BASE_URL); if (doc.select("#idSection").isEmpty()) { logger.error("Expected SnP page, got page with title: {} {}", doc.title(), doc.selectFirst("body")); @@ -62,51 +57,10 @@ public class StudentAndParent implements SnP { return this; } - public String getSchoolID() { - return schoolID; - } - public String getStudentID() { return studentID; } - private String getBaseUrl() { - return BASE_URL.replace("{ID}", getSchoolID()); - } - - String getSnpHomePageUrl() throws IOException, VulcanException { - if (null != getSchoolID()) { - return getBaseUrl(); - } - - // get url to uonetplus-opiekun.fakelog.cf - Document startPage = client.getPageByUrl(START_PAGE_URL); - Elements studentTileLink = startPage.select(".panel.linkownia.pracownik.klient > a"); - - logger.debug("studentTileLink: {}", studentTileLink.size()); - - if (studentTileLink.isEmpty()) { - throw new VulcanException("Na pewno używasz konta z dostępem do Witryny ucznia i rodzica?"); - } - - String snpPageUrl = studentTileLink.last().attr("href"); - - this.schoolID = getExtractedIdFromUrl(snpPageUrl); - - return snpPageUrl; - } - - String getExtractedIdFromUrl(String snpPageUrl) throws VulcanException { - String[] path = snpPageUrl.split(client.getHost())[1].split("/"); - - if (5 != path.length) { - logger.error("Expected snp url, got {}", snpPageUrl); - throw new VulcanException("Na pewno używasz konta z dostępem do Witryny ucznia i rodzica?"); - } - - return path[2]; - } - public String getRowDataChildValue(Element e, int index) { return e.select(".daneWiersz .wartosc").get(index - 1).text(); } @@ -120,7 +74,7 @@ public class StudentAndParent implements SnP { cookies.put("idBiezacyDziennik", diaryID); cookies.put("idBiezacyUczen", studentID); - Document doc = client.getPageByUrl(getBaseUrl() + url, true, cookies); + Document doc = client.getPageByUrl(BASE_URL + url, true, cookies); if (!doc.title().startsWith("Witryna ucznia i rodzica")) { logger.error("Expected SnP page, got page with title: {} {}", doc.title(), doc.selectFirst("body")); @@ -135,7 +89,7 @@ public class StudentAndParent implements SnP { } public List getDiaries() throws IOException, VulcanException { - return getDiaries(client.getPageByUrl(getBaseUrl())); + return getDiaries(client.getPageByUrl(BASE_URL)); } private List getDiaries(Document doc) throws IOException, VulcanException { @@ -143,7 +97,7 @@ public class StudentAndParent implements SnP { } public List getStudents() throws IOException, VulcanException { - return getStudents(client.getPageByUrl(getBaseUrl())); + return getStudents(client.getPageByUrl(BASE_URL)); } private List getStudents(Document doc) throws IOException, VulcanException { diff --git a/api/src/main/java/io/github/wulkanowy/api/Vulcan.java b/api/src/main/java/io/github/wulkanowy/api/Vulcan.java index 2b4d1205..bf482969 100644 --- a/api/src/main/java/io/github/wulkanowy/api/Vulcan.java +++ b/api/src/main/java/io/github/wulkanowy/api/Vulcan.java @@ -4,10 +4,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; +import java.util.List; import io.github.wulkanowy.api.attendance.AttendanceStatistics; import io.github.wulkanowy.api.attendance.AttendanceTable; import io.github.wulkanowy.api.exams.ExamsWeek; +import io.github.wulkanowy.api.generic.School; import io.github.wulkanowy.api.grades.GradesList; import io.github.wulkanowy.api.grades.SubjectsList; import io.github.wulkanowy.api.messages.Messages; @@ -27,8 +29,6 @@ public class Vulcan { private Client client; - private String schoolId; - private String studentId; private String diaryId; @@ -36,11 +36,10 @@ public class Vulcan { private static final Logger logger = LoggerFactory.getLogger(Vulcan.class); public void setCredentials(String email, String password, String symbol, String schoolId, String studentId, String diaryId) { - this.schoolId = schoolId; this.studentId = studentId; this.diaryId = diaryId; - client = new Client(email, password, symbol); + client = new Client(email, password, symbol, schoolId); logger.debug("Client created with symbol " + symbol); } @@ -55,7 +54,10 @@ public class Vulcan { public String getSymbol() throws NotLoggedInErrorException { return getClient().getSymbol(); + } + public List getSchools() throws VulcanException, IOException { + return getClient().getSchools(); } public SnP getStudentAndParent() throws VulcanException, IOException { @@ -63,7 +65,7 @@ public class Vulcan { return this.snp; } - this.snp = new StudentAndParent(getClient(), schoolId, studentId, diaryId) + this.snp = new StudentAndParent(getClient(), studentId, diaryId) .setUp(); return this.snp; diff --git a/api/src/main/java/io/github/wulkanowy/api/generic/School.kt b/api/src/main/java/io/github/wulkanowy/api/generic/School.kt new file mode 100644 index 00000000..c14fc5d2 --- /dev/null +++ b/api/src/main/java/io/github/wulkanowy/api/generic/School.kt @@ -0,0 +1,7 @@ +package io.github.wulkanowy.api.generic + +data class School( + val name: String, + val id: String, + val current: Boolean +) diff --git a/api/src/main/java/io/github/wulkanowy/api/login/Login.java b/api/src/main/java/io/github/wulkanowy/api/login/Login.java index f6d4cd11..443a9387 100644 --- a/api/src/main/java/io/github/wulkanowy/api/login/Login.java +++ b/api/src/main/java/io/github/wulkanowy/api/login/Login.java @@ -16,8 +16,9 @@ import io.github.wulkanowy.api.VulcanException; public class Login { - static final String LOGIN_PAGE_URL = "{schema}://cufs.{host}/{symbol}/Account/LogOn" + - "?ReturnUrl=%2F{symbol}%2FFS%2FLS%3Fwa%3Dwsignin1.0%26wtrealm%3D" + + protected static final String LOGIN_PAGE_URL = "{schema}://cufs.{host}/{symbol}/Account/LogOn"; + + private static final String LOGIN_PAGE_URL_QUERY = "?ReturnUrl=%2F{symbol}%2FFS%2FLS%3Fwa%3Dwsignin1.0%26wtrealm%3D" + "{schema}%253a%252f%252fuonetplus.{host}%252f{symbol}%252fLoginEndpoint.aspx%26wctx%3D" + "{schema}%253a%252f%252fuonetplus.{host}%252f{symbol}%252fLoginEndpoint.aspx"; @@ -29,7 +30,7 @@ public class Login { this.client = client; } - public String login(String email, String password, String symbol) throws VulcanException, IOException { + public void login(String email, String password, String symbol) throws VulcanException, IOException { Document certDoc = sendCredentials(email, password); if ("Błąd".equals(certDoc.title())) { @@ -37,7 +38,7 @@ public class Login { throw new NotLoggedInErrorException(certDoc.body().text()); } - return sendCertificate(certDoc, symbol); + sendCertificate(certDoc, symbol); } Document sendCredentials(String email, String password) throws IOException, VulcanException { @@ -46,7 +47,7 @@ public class Login { {"Password", password} }; - Document nextDoc = sendCredentialsData(credentials, LOGIN_PAGE_URL); + Document nextDoc = sendCredentialsData(credentials, LOGIN_PAGE_URL + LOGIN_PAGE_URL_QUERY.replace(":", "%253A")); Element errorMessage = nextDoc.selectFirst(".ErrorMessage, #ErrorTextLabel"); if (null != errorMessage) { @@ -86,7 +87,7 @@ public class Login { }; } - String sendCertificate(Document doc, String defaultSymbol) throws IOException, VulcanException { + void sendCertificate(Document doc, String defaultSymbol) throws IOException, VulcanException { client.setSymbol(findSymbol(defaultSymbol, doc.select("input[name=wresult]").val())); Document targetDoc = sendCertData(doc); @@ -106,7 +107,7 @@ public class Login { throw new LoginErrorException("Expected page title `UONET+`, got " + title); } - return client.getSymbol(); + client.setSchools(new StartPage(client).getSchools(targetDoc)); } private Document sendCertData(Document doc) throws IOException, VulcanException { diff --git a/api/src/main/java/io/github/wulkanowy/api/login/StartPage.kt b/api/src/main/java/io/github/wulkanowy/api/login/StartPage.kt new file mode 100644 index 00000000..6f6b1490 --- /dev/null +++ b/api/src/main/java/io/github/wulkanowy/api/login/StartPage.kt @@ -0,0 +1,45 @@ +package io.github.wulkanowy.api.login + +import io.github.wulkanowy.api.Client +import io.github.wulkanowy.api.VulcanException +import io.github.wulkanowy.api.generic.School +import org.jsoup.nodes.Document +import org.slf4j.LoggerFactory + +class StartPage(val client: Client) { + + private val logger = LoggerFactory.getLogger(StartPage::class.java) + + fun getSchools(startPage: Document): MutableList { + val schoolList = mutableListOf() + + val snpLinks = startPage.select(".panel.linkownia.pracownik.klient a") + + logger.debug("SnP links: {}", snpLinks.size) + + if (snpLinks.isEmpty()) { + throw VulcanException("Na pewno używasz konta z dostępem do Witryny ucznia i rodzica?") + } + + snpLinks.map { + schoolList.add(School( + it.text(), + getExtractedIdFromUrl(it.attr("href")), + it == snpLinks.first() + )) + } + + return schoolList + } + + internal fun getExtractedIdFromUrl(snpPageUrl: String): String { + val path = snpPageUrl.split(client.host).getOrNull(1)?.split("/") + + if (6 != path?.size) { + logger.error("Expected snp url, got {}", snpPageUrl) + throw VulcanException("Na pewno używasz konta z dostępem do Witryny ucznia i rodzica?") + } + + return path[2] + } +} diff --git a/api/src/test/java/io/github/wulkanowy/api/ClientTest.java b/api/src/test/java/io/github/wulkanowy/api/ClientTest.java index 50724875..298affac 100644 --- a/api/src/test/java/io/github/wulkanowy/api/ClientTest.java +++ b/api/src/test/java/io/github/wulkanowy/api/ClientTest.java @@ -12,16 +12,24 @@ public class ClientTest { } @Test - public void setFullEndpointInfoTest() throws Exception { - Client client = new Client("http://fakelog.net\\\\admin", "pass", "Default"); + public void setFullEndpointInfoTest() { + Client client = new Client("http://fakelog.cf\\\\admin", "pass", "Default", "123"); - Assert.assertEquals("fakelog.net", client.getHost()); + Assert.assertEquals("fakelog.cf", client.getHost()); Assert.assertEquals("Default", client.getSymbol()); } + @Test + public void setFullEndpointInfoWithSymbolTest() { + Client client = new Client("http://fakelog.cf/notdefault\\\\admin", "pass", "Default", "123"); + + Assert.assertEquals("fakelog.cf", client.getHost()); + Assert.assertEquals("notdefault", client.getSymbol()); // + } + @Test public void checkForNoErrorsTest() throws Exception { - Client client = new Client("", "", ""); + Client client = new Client("", "", "", "123"); Document doc = Jsoup.parse(getFixtureAsString("login/Logowanie-success.html")); @@ -30,7 +38,7 @@ public class ClientTest { @Test(expected = VulcanOfflineException.class) public void checkForErrorsOffline() throws Exception { - Client client = new Client("", "", ""); + Client client = new Client("", "", "", "123"); Document doc = Jsoup.parse(getFixtureAsString("login/PrzerwaTechniczna.html")); @@ -39,7 +47,7 @@ public class ClientTest { @Test(expected = NotLoggedInErrorException.class) public void checkForErrors() throws Exception { - Client client = new Client("", "", ""); + Client client = new Client("", "", "", "123"); Document doc = Jsoup.parse(getFixtureAsString("login/Logowanie-notLoggedIn.html")); @@ -48,16 +56,23 @@ public class ClientTest { @Test public void getFilledUrlTest() throws Exception { - Client client = new Client("http://fakelog.cf\\\\admin", "", "symbol123"); + Client client = new Client("http://fakelog.cf\\\\admin", "", "symbol123", "321"); - Assert.assertEquals("http://uonetplus.fakelog.cf/symbol123/LoginEndpoint.aspx", - client.getFilledUrl("{schema}://uonetplus.{host}/{symbol}/LoginEndpoint.aspx")); + Assert.assertEquals("http://uonetplus-opiekun.fakelog.cf/symbol123/321/Oceny/Wszystkie", + client.getFilledUrl("{schema}://uonetplus-opiekun.{host}/{symbol}/{ID}/Oceny/Wszystkie")); } @Test - public void getSymbolTest() throws Exception { - Client client = new Client("", "", "symbol4321"); + public void getSymbolTest() { + Client client = new Client("", "", "symbol4321", "123"); Assert.assertEquals("symbol4321", client.getSymbol()); } + + @Test + public void getSchoolIdTest() throws Exception { + Client client = new Client("", "", "1", "123456"); + + Assert.assertEquals("123456", client.getSchoolId()); + } } diff --git a/api/src/test/java/io/github/wulkanowy/api/StudentAndParentTest.java b/api/src/test/java/io/github/wulkanowy/api/StudentAndParentTest.java index ba0c8f7f..4c6443b1 100644 --- a/api/src/test/java/io/github/wulkanowy/api/StudentAndParentTest.java +++ b/api/src/test/java/io/github/wulkanowy/api/StudentAndParentTest.java @@ -32,68 +32,13 @@ public class StudentAndParentTest { @Test public void snpTest() { - StudentAndParent snp = new StudentAndParent(client, "id123", null, null); - Assert.assertEquals("id123", snp.getSchoolID()); - } - - @Test - public void getSnpPageUrlWithIdTest() throws Exception { - Assert.assertEquals("{schema}://uonetplus-opiekun.{host}/{symbol}/123456/", - (new StudentAndParent(client, "123456", null, null)).getSnpHomePageUrl()); - } - - @Test - public void getSnpPageUrlWithoutIdTest() throws Exception { - String input = FixtureHelper.getAsString(getClass().getResourceAsStream("Start.html")); - Document startPageDocument = Jsoup.parse(input); - - Mockito.when(client.getHost()).thenReturn("vulcan.net.pl"); - Mockito.when(client.getPageByUrl(Mockito.anyString())).thenReturn(startPageDocument); - StudentAndParent snp = new StudentAndParent(client, null, null, null); - - Assert.assertEquals("https://uonetplus-opiekun.vulcan.net.pl/symbol/534213/Start/Index/", - snp.getSnpHomePageUrl()); - } - - @Test(expected = VulcanException.class) - public void getSnpPageUrlWithWrongPage() throws Exception { - Document wrongPageDocument = Jsoup.parse( - FixtureHelper.getAsString(getClass().getResourceAsStream("OcenyWszystkie-semester.html")) - ); - - Mockito.when(client.getPageByUrl(Mockito.anyString())).thenReturn(wrongPageDocument); - StudentAndParent snp = new StudentAndParent(client, null, null, null); - - snp.getSnpHomePageUrl(); - } - - @Test - public void getExtractedIDStandardTest() throws Exception { - Mockito.when(client.getHost()).thenReturn("vulcan.net.pl"); - StudentAndParent snp = new StudentAndParent(client, "symbol", null, null); - Assert.assertEquals("123456", snp.getExtractedIdFromUrl("https://uonetplus-opiekun" - + ".vulcan.net.pl/powiat/123456/Start/Index/")); - } - - @Test - public void getExtractedIDDemoTest() throws Exception { - Mockito.when(client.getHost()).thenReturn("vulcan.net.pl"); - StudentAndParent snp = new StudentAndParent(client, "symbol", null, null); - Assert.assertEquals("demo12345", - snp.getExtractedIdFromUrl("https://uonetplus-opiekun.vulcan.net.pl/demoupowiat/demo12345/Start/Index/")); - } - - @Test(expected = VulcanException.class) - public void getExtractedIDNotLoggedTest() throws Exception { - Mockito.when(client.getHost()).thenReturn("vulcan.net.pl"); - StudentAndParent snp = new StudentAndParent(client, "symbol", null, null); - Assert.assertEquals("123", - snp.getExtractedIdFromUrl("https://uonetplus.vulcan.net.pl/powiat/")); + StudentAndParent snp = new StudentAndParent(client, "1234", null); + Assert.assertEquals("1234", snp.getStudentID()); } @Test public void getSemestersTest() throws Exception { - SnP snp = new StudentAndParent(client, "123456", null, null); + SnP snp = new StudentAndParent(client, null, null); List semesters = snp.getSemesters(); Assert.assertEquals(2, semesters.size()); @@ -113,7 +58,7 @@ public class StudentAndParentTest { semesters.add(new Semester().setName("1500100900").setId("1").setCurrent(false)); semesters.add(new Semester().setName("1500100901").setId("2").setCurrent(true)); - SnP snp = new StudentAndParent(client, "", null, null); + SnP snp = new StudentAndParent(client, null, null); Semester semester = snp.getCurrent(semesters); Assert.assertTrue(semester.isCurrent()); @@ -123,7 +68,7 @@ public class StudentAndParentTest { @Test public void getCurrentSemesterFromEmptyTest() { - SnP snp = new StudentAndParent(client, "", null, null); + SnP snp = new StudentAndParent(client, null, null); List semesters = new ArrayList<>(); Assert.assertNull(snp.getCurrent(semesters)); @@ -136,7 +81,7 @@ public class StudentAndParentTest { client = Mockito.mock(Client.class); Mockito.when(client.getPageByUrl(Mockito.anyString())).thenReturn(snpHome); - SnP snp = new StudentAndParent(client, "", null, null); + SnP snp = new StudentAndParent(client, null, null); snp.setUp(); diff --git a/api/src/test/java/io/github/wulkanowy/api/login/LoginTest.java b/api/src/test/java/io/github/wulkanowy/api/login/LoginTest.java index 4a4f8915..86a3ef40 100644 --- a/api/src/test/java/io/github/wulkanowy/api/login/LoginTest.java +++ b/api/src/test/java/io/github/wulkanowy/api/login/LoginTest.java @@ -38,9 +38,11 @@ public class LoginTest { .thenReturn(getFixtureAsDocument("Logowanie-certyfikat.html")); Mockito.doCallRealMethod().when(client).setSymbol(Mockito.anyString()); Mockito.when(client.getSymbol()).thenCallRealMethod(); + Mockito.when(client.getHost()).thenReturn("fakelog.cf"); Login login = new Login(client); + login.login("a@a", "pswd", "d123"); - Assert.assertEquals("d123", login.login("a@a", "pswd", "d123")); + Assert.assertEquals("d123", client.getSymbol()); } @Test(expected = BadCredentialsException.class) @@ -74,10 +76,12 @@ public class LoginTest { Client client = getClient("Logowanie-success.html"); Mockito.doCallRealMethod().when(client).setSymbol(Mockito.anyString()); Mockito.when(client.getSymbol()).thenCallRealMethod(); + Mockito.when(client.getHost()).thenReturn("fakelog.cf"); Login login = new Login(client); - Assert.assertEquals("wulkanowyschool321", login.sendCertificate( - getFixtureAsDocument("Logowanie-certyfikat.html"), "wulkanowyschool321")); + login.sendCertificate(getFixtureAsDocument("Logowanie-certyfikat.html"), "wulkanowyschool321"); + + Assert.assertEquals("wulkanowyschool321", client.getSymbol()); } @Test @@ -85,10 +89,12 @@ public class LoginTest { Client client = getClient("Logowanie-success.html"); Mockito.doCallRealMethod().when(client).setSymbol(Mockito.anyString()); Mockito.when(client.getSymbol()).thenCallRealMethod(); + Mockito.when(client.getHost()).thenReturn("fakelog.cf"); Login login = new Login(client); - Assert.assertEquals("demo12345", - login.sendCertificate(getFixtureAsDocument("Logowanie-certyfikat.html"), "Default")); + login.sendCertificate(getFixtureAsDocument("Logowanie-certyfikat.html"), "Default"); + + Assert.assertEquals("demo12345", client.getSymbol()); } @Test(expected = AccountPermissionException.class) diff --git a/api/src/test/java/io/github/wulkanowy/api/login/StartPageTest.kt b/api/src/test/java/io/github/wulkanowy/api/login/StartPageTest.kt new file mode 100644 index 00000000..271b3bb0 --- /dev/null +++ b/api/src/test/java/io/github/wulkanowy/api/login/StartPageTest.kt @@ -0,0 +1,68 @@ +package io.github.wulkanowy.api.login + +import io.github.wulkanowy.api.Client +import io.github.wulkanowy.api.FixtureHelper +import io.github.wulkanowy.api.VulcanException +import org.jsoup.Jsoup +import org.jsoup.nodes.Document +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.mockito.Mockito +import org.mockito.Mockito.mock + +class StartPageTest { + + private val client: Client = mock(Client::class.java) + + @Before fun setUp() { + Mockito.`when`(client.host).thenReturn("fakelog.cf") + } + + private fun getDoc(name: String): Document = Jsoup.parse(FixtureHelper.getAsString(javaClass.getResourceAsStream(name))) + + @Test fun getSchoolTest() { + assertEquals("534213", StartPage(client).getSchools(getDoc("../Start-std.html"))[0].id) + } + + @Test fun getMultiSchoolTest() { + val schools = StartPage(client).getSchools(getDoc("../Start-multi.html")) + + assertEquals("123456", schools[0].id) + assertEquals("123457", schools[1].id) + } + + @Test fun getSchoolNameTest() { + assertEquals("Uczeń", StartPage(client).getSchools(getDoc("../Start-std.html"))[0].name) + } + + @Test fun getMultiSchoolNameTest() { + val schools = StartPage(client).getSchools(getDoc("../Start-multi.html")) + + assertEquals("GIMBB", schools[0].name) + assertEquals("SPBB", schools[1].name) + } + + @Test(expected = VulcanException::class) + fun getSnpPageUrlWithWrongPage() { + StartPage(client).getSchools(getDoc("../OcenyWszystkie-semester.html")) + } + + @Test + fun getExtractedIDStandardTest() { + assertEquals("123456", StartPage(client) + .getExtractedIdFromUrl("https://uonetplus-opiekun.fakelog.cf/powiat/123456/Start/Index/")) + } + + @Test + fun getExtractedIDDemoTest() { + assertEquals("demo12345", StartPage(client) + .getExtractedIdFromUrl("https://uonetplus-opiekun.fakelog.cf/demoupowiat/demo12345/Start/Index/")) + } + + @Test(expected = VulcanException::class) + fun getExtractedIDNotLoggedTest() { + assertEquals("123", StartPage(client) + .getExtractedIdFromUrl("https://uonetplus.NOTfakelog.cf/powiat/")) + } +} diff --git a/api/src/test/resources/io/github/wulkanowy/api/Start-multi.html b/api/src/test/resources/io/github/wulkanowy/api/Start-multi.html new file mode 100644 index 00000000..98d385ee --- /dev/null +++ b/api/src/test/resources/io/github/wulkanowy/api/Start-multi.html @@ -0,0 +1,27 @@ + + + + + Uonet+ + + +
+
+
+ +
+
+
+ + diff --git a/api/src/test/resources/io/github/wulkanowy/api/Start.html b/api/src/test/resources/io/github/wulkanowy/api/Start-std.html similarity index 85% rename from api/src/test/resources/io/github/wulkanowy/api/Start.html rename to api/src/test/resources/io/github/wulkanowy/api/Start-std.html index 40e69161..574bd9b9 100644 --- a/api/src/test/resources/io/github/wulkanowy/api/Start.html +++ b/api/src/test/resources/io/github/wulkanowy/api/Start-std.html @@ -9,7 +9,7 @@
diff --git a/app/build.gradle b/app/build.gradle index e8a9ab48..df08a23e 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -93,7 +93,7 @@ play { } greendao { - schemaVersion 28 + schemaVersion 29 generateTests = true } diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SchoolTest.java b/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SchoolTest.java new file mode 100644 index 00000000..13f63e0d --- /dev/null +++ b/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SchoolTest.java @@ -0,0 +1,22 @@ +package io.github.wulkanowy.data.db.dao.entities; + +import org.greenrobot.greendao.test.AbstractDaoTestLongPk; + +import io.github.wulkanowy.data.db.dao.entities.School; +import io.github.wulkanowy.data.db.dao.entities.SchoolDao; + +public class SchoolTest extends AbstractDaoTestLongPk { + + public SchoolTest() { + super(SchoolDao.class); + } + + @Override + protected School createEntity(Long key) { + School entity = new School(); + entity.setId(key); + entity.setCurrent(false); + return entity; + } + +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/DbContract.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/DbContract.java index f32884f5..22eaa944 100644 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/DbContract.java +++ b/app/src/main/java/io/github/wulkanowy/data/db/dao/DbContract.java @@ -17,6 +17,8 @@ public interface DbContract { List getNewGrades(int semesterName); + long getCurrentSchoolId(); + long getCurrentStudentId(); long getCurrentSymbolId(); diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/DbHelper.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/DbHelper.java index 904fa343..33b19311 100644 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/DbHelper.java +++ b/app/src/main/java/io/github/wulkanowy/data/db/dao/DbHelper.java @@ -21,6 +21,7 @@ import io.github.wulkanowy.data.db.dao.migrations.Migration23; import io.github.wulkanowy.data.db.dao.migrations.Migration26; import io.github.wulkanowy.data.db.dao.migrations.Migration27; import io.github.wulkanowy.data.db.dao.migrations.Migration28; +import io.github.wulkanowy.data.db.dao.migrations.Migration29; import io.github.wulkanowy.data.db.shared.SharedPrefContract; import timber.log.Timber; @@ -79,6 +80,7 @@ public class DbHelper extends DaoMaster.OpenHelper { migrations.add(new Migration26()); migrations.add(new Migration27()); migrations.add(new Migration28()); + migrations.add(new Migration29()); // Sorting just to be safe, in case other people add migrations in the wrong order. Comparator migrationComparator = new Comparator() { diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/DbRepository.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/DbRepository.java index 2c92c55d..d869bfe9 100644 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/DbRepository.java +++ b/app/src/main/java/io/github/wulkanowy/data/db/dao/DbRepository.java @@ -11,6 +11,7 @@ import io.github.wulkanowy.data.db.dao.entities.DaoSession; import io.github.wulkanowy.data.db.dao.entities.DiaryDao; import io.github.wulkanowy.data.db.dao.entities.Grade; import io.github.wulkanowy.data.db.dao.entities.GradeDao; +import io.github.wulkanowy.data.db.dao.entities.SchoolDao; import io.github.wulkanowy.data.db.dao.entities.Semester; import io.github.wulkanowy.data.db.dao.entities.SemesterDao; import io.github.wulkanowy.data.db.dao.entities.StudentDao; @@ -72,10 +73,18 @@ public class DbRepository implements DbContract { return getCurrentSymbol().getId(); } + @Override + public long getCurrentSchoolId() { + return daoSession.getSchoolDao().queryBuilder().where( + SchoolDao.Properties.SymbolId.eq(getCurrentSymbolId()), + SchoolDao.Properties.Current.eq(true) + ).unique().getId(); + } + @Override public long getCurrentStudentId() { return daoSession.getStudentDao().queryBuilder().where( - StudentDao.Properties.SymbolId.eq(getCurrentSymbolId()), + StudentDao.Properties.SchoolId.eq(getCurrentSchoolId()), StudentDao.Properties.Current.eq(true) ).unique().getId(); } diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/School.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/School.java new file mode 100644 index 00000000..59860e9e --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/School.java @@ -0,0 +1,179 @@ +package io.github.wulkanowy.data.db.dao.entities; + +import org.greenrobot.greendao.DaoException; +import org.greenrobot.greendao.annotation.Entity; +import org.greenrobot.greendao.annotation.Generated; +import org.greenrobot.greendao.annotation.Id; +import org.greenrobot.greendao.annotation.Property; +import org.greenrobot.greendao.annotation.ToMany; + +import java.util.List; + +@Entity( + nameInDb = "Schools", + active = true +) +public class School { + + @Id(autoincrement = true) + private Long id; + + @Property(nameInDb = "symbol_id") + private Long symbolId; + + @Property(nameInDb = "current") + private boolean current; + + @Property(nameInDb = "real_id") + private String realId; + + @Property(nameInDb = "name") + private String name; + + @ToMany(referencedJoinProperty = "schoolId") + private List studentList; + + /** + * Used to resolve relations + */ + @Generated(hash = 2040040024) + private transient DaoSession daoSession; + + /** + * Used for active entity operations. + */ + @Generated(hash = 1796006707) + private transient SchoolDao myDao; + + @Generated(hash = 975562398) + public School(Long id, Long symbolId, boolean current, String realId, + String name) { + this.id = id; + this.symbolId = symbolId; + this.current = current; + this.realId = realId; + this.name = name; + } + + @Generated(hash = 1579966795) + public School() { + } + + public Long getId() { + return this.id; + } + + public School setId(Long id) { + this.id = id; + return this; + } + + public Long getSymbolId() { + return this.symbolId; + } + + public School setSymbolId(Long symbolId) { + this.symbolId = symbolId; + return this; + } + + public boolean getCurrent() { + return this.current; + } + + public School setCurrent(boolean current) { + this.current = current; + return this; + } + + public String getRealId() { + return this.realId; + } + + public School setRealId(String realId) { + this.realId = realId; + return this; + } + + public String getName() { + return this.name; + } + + public School setName(String name) { + this.name = name; + return this; + } + + /** + * To-many relationship, resolved on first access (and after reset). + * Changes to to-many relations are not persisted, make changes to the target entity. + */ + @Generated(hash = 180118651) + public List getStudentList() { + if (studentList == null) { + final DaoSession daoSession = this.daoSession; + if (daoSession == null) { + throw new DaoException("Entity is detached from DAO context"); + } + StudentDao targetDao = daoSession.getStudentDao(); + List studentListNew = targetDao._querySchool_StudentList(id); + synchronized (this) { + if (studentList == null) { + studentList = studentListNew; + } + } + } + return studentList; + } + + /** + * Resets a to-many relationship, making the next get call to query for a fresh result. + */ + @Generated(hash = 1628625923) + public synchronized void resetStudentList() { + studentList = null; + } + + /** + * Convenient call for {@link org.greenrobot.greendao.AbstractDao#delete(Object)}. + * Entity must attached to an entity context. + */ + @Generated(hash = 128553479) + public void delete() { + if (myDao == null) { + throw new DaoException("Entity is detached from DAO context"); + } + myDao.delete(this); + } + + /** + * Convenient call for {@link org.greenrobot.greendao.AbstractDao#refresh(Object)}. + * Entity must attached to an entity context. + */ + @Generated(hash = 1942392019) + public void refresh() { + if (myDao == null) { + throw new DaoException("Entity is detached from DAO context"); + } + myDao.refresh(this); + } + + /** + * Convenient call for {@link org.greenrobot.greendao.AbstractDao#update(Object)}. + * Entity must attached to an entity context. + */ + @Generated(hash = 713229351) + public void update() { + if (myDao == null) { + throw new DaoException("Entity is detached from DAO context"); + } + myDao.update(this); + } + + /** called by internal mechanisms, do not call yourself. */ + @Generated(hash = 234091322) + public void __setDaoSession(DaoSession daoSession) { + this.daoSession = daoSession; + myDao = daoSession != null ? daoSession.getSchoolDao() : null; + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Student.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Student.java index f8ae0e31..1d545473 100644 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Student.java +++ b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Student.java @@ -18,8 +18,8 @@ public class Student { @Id(autoincrement = true) private Long id; - @Property(nameInDb = "symbol_id") - private Long symbolId; + @Property(nameInDb = "school_id") + private Long schoolId; @Property(nameInDb = "current") private boolean current; @@ -45,10 +45,10 @@ public class Student { @Generated(hash = 1943931642) private transient StudentDao myDao; - @Generated(hash = 1334215952) - public Student(Long id, Long symbolId, boolean current, String realId, String name) { + @Generated(hash = 470181623) + public Student(Long id, Long schoolId, boolean current, String realId, String name) { this.id = id; - this.symbolId = symbolId; + this.schoolId = schoolId; this.current = current; this.realId = realId; this.name = name; @@ -66,12 +66,12 @@ public class Student { this.id = id; } - public Long getSymbolId() { - return this.symbolId; + public Long getSchoolId() { + return this.schoolId; } - public Student setSymbolId(Long symbolId) { - this.symbolId = symbolId; + public Student setSchoolId(Long schoolId) { + this.schoolId = schoolId; return this; } diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Symbol.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Symbol.java index 2b5984b5..7cc46111 100644 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Symbol.java +++ b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Symbol.java @@ -24,9 +24,6 @@ public class Symbol { @Property(nameInDb = "host") private String host; - @Property(nameInDb = "school_id") - private String schoolId; - @Property(nameInDb = "symbol") private String symbol; @@ -34,7 +31,7 @@ public class Symbol { private String type; @ToMany(referencedJoinProperty = "symbolId") - private List studentList; + private List schoolList; /** * Used to resolve relations @@ -48,13 +45,11 @@ public class Symbol { @Generated(hash = 684907977) private transient SymbolDao myDao; - @Generated(hash = 242774339) - public Symbol(Long id, Long userId, String host, String schoolId, String symbol, - String type) { + @Generated(hash = 1034469460) + public Symbol(Long id, Long userId, String host, String symbol, String type) { this.id = id; this.userId = userId; this.host = host; - this.schoolId = schoolId; this.symbol = symbol; this.type = type; } @@ -89,15 +84,6 @@ public class Symbol { return this; } - public String getSchoolId() { - return this.schoolId; - } - - public Symbol setSchoolId(String schoolId) { - this.schoolId = schoolId; - return this; - } - public String getSymbol() { return this.symbol; } @@ -120,30 +106,28 @@ public class Symbol { * To-many relationship, resolved on first access (and after reset). * Changes to to-many relations are not persisted, make changes to the target entity. */ - @Generated(hash = 604366458) - public List getStudentList() { - if (studentList == null) { + @Generated(hash = 1733082867) + public List getSchoolList() { + if (schoolList == null) { final DaoSession daoSession = this.daoSession; if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } - StudentDao targetDao = daoSession.getStudentDao(); - List studentListNew = targetDao._querySymbol_StudentList(id); + SchoolDao targetDao = daoSession.getSchoolDao(); + List schoolListNew = targetDao._querySymbol_SchoolList(id); synchronized (this) { - if (studentList == null) { - studentList = studentListNew; + if (schoolList == null) { + schoolList = schoolListNew; } } } - return studentList; + return schoolList; } - /** - * Resets a to-many relationship, making the next get call to query for a fresh result. - */ - @Generated(hash = 1628625923) - public synchronized void resetStudentList() { - studentList = null; + /** Resets a to-many relationship, making the next get call to query for a fresh result. */ + @Generated(hash = 1757777300) + public synchronized void resetSchoolList() { + schoolList = null; } /** diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration27.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration27.java index 5c8c82f1..922079f4 100644 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration27.java +++ b/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration27.java @@ -15,7 +15,7 @@ public class Migration27 implements DbHelper.Migration { } @Override - public void runMigration(Database db, SharedPrefContract sharedPref, Vulcan vulcan) throws Exception { + public void runMigration(Database db, SharedPrefContract sharedPref, Vulcan vulcan) { ExamDao.dropTable(db, true); ExamDao.createTable(db, true); diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration29.kt b/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration29.kt new file mode 100644 index 00000000..cb2fccb1 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration29.kt @@ -0,0 +1,60 @@ +package io.github.wulkanowy.data.db.dao.migrations + +import android.database.Cursor + +import org.greenrobot.greendao.database.Database + +import io.github.wulkanowy.api.Vulcan +import io.github.wulkanowy.data.db.dao.DbHelper +import io.github.wulkanowy.data.db.shared.SharedPrefContract + +class Migration29 : DbHelper.Migration { + + override fun getVersion(): Int? { + return 29 + } + + override fun runMigration(db: Database, sharedPref: SharedPrefContract, vulcan: Vulcan) { + createSchoolsTable(db) + modifyStudents(db) + insertSchool(db, getRealSchoolId(db)) + } + + private fun createSchoolsTable(db: Database) { + db.execSQL("DROP TABLE IF EXISTS \"Schools\";") + db.execSQL("CREATE TABLE IF NOT EXISTS \"Schools\" (" + // + "\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id + "\"symbol_id\" INTEGER," + // 1: symbolId + "\"current\" INTEGER NOT NULL ," + // 2: current + "\"real_id\" TEXT," + // 3: realId + "\"name\" TEXT);") // 4: name + } + + private fun modifyStudents(db: Database) { + db.execSQL("ALTER TABLE Students ADD COLUMN school_id INTEGER") + db.execSQL("UPDATE Students SET (school_id) = ('1')") + } + + private fun getRealSchoolId(db: Database): String { + var cursor: Cursor? = null + try { + cursor = db.rawQuery("SELECT school_id FROM Symbols WHERE _id=?", arrayOf("1")) + + return if (cursor!!.count > 0) { + cursor.moveToFirst() + cursor.getString(cursor.getColumnIndex("school_id")) + } else "" + } finally { + cursor!!.close() + } + } + + private fun insertSchool(db: Database, realId: String) { + db.execSQL("INSERT INTO Schools(symbol_id, current, real_id, name) VALUES(" + + "\"1\"," + + "\"1\"," + + "\"" + realId + "\"," + + "\"Uczeń\"" + + ")") + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/sync/AccountSync.java b/app/src/main/java/io/github/wulkanowy/data/sync/AccountSync.java index b9f72cb2..45f8c1f5 100644 --- a/app/src/main/java/io/github/wulkanowy/data/sync/AccountSync.java +++ b/app/src/main/java/io/github/wulkanowy/data/sync/AccountSync.java @@ -17,6 +17,8 @@ import io.github.wulkanowy.data.db.dao.entities.DaoMaster; import io.github.wulkanowy.data.db.dao.entities.DaoSession; import io.github.wulkanowy.data.db.dao.entities.Diary; import io.github.wulkanowy.data.db.dao.entities.DiaryDao; +import io.github.wulkanowy.data.db.dao.entities.School; +import io.github.wulkanowy.data.db.dao.entities.SchoolDao; import io.github.wulkanowy.data.db.dao.entities.Semester; import io.github.wulkanowy.data.db.dao.entities.Student; import io.github.wulkanowy.data.db.dao.entities.StudentDao; @@ -57,12 +59,15 @@ public class AccountSync { daoSession.getDatabase().beginTransaction(); + Timber.i("Register start"); + try { Account account = insertAccount(email, password); Symbol symbolEntity = insertSymbol(account); - insertStudents(symbolEntity); - insertDiaries(symbolEntity); - insertSemesters(); + School schoolEntity = insertSchools(symbolEntity); + Student student = insertStudents(schoolEntity); + Diary diary = insertDiaries(student); + insertSemesters(diary); sharedPref.setCurrentUserId(account.getId()); @@ -70,6 +75,8 @@ public class AccountSync { } finally { daoSession.getDatabase().endTransaction(); } + + Timber.i("Register end"); } private Account insertAccount(String email, String password) throws CryptoException { @@ -82,44 +89,64 @@ public class AccountSync { } private Symbol insertSymbol(Account account) throws VulcanException, IOException { - String schoolId = vulcan.getStudentAndParent().getSchoolID(); - Timber.d("Register symbol %s", vulcan.getSymbol()); + vulcan.getSchools(); + Timber.d("Register symbol (%s)", vulcan.getSymbol()); Symbol symbol = new Symbol() .setUserId(account.getId()) - .setSchoolId(schoolId) .setSymbol(vulcan.getSymbol()); daoSession.getSymbolDao().insert(symbol); return symbol; } - private void insertStudents(Symbol symbol) throws VulcanException, IOException { - List studentList = DataObjectConverter.studentsToStudentEntities( - vulcan.getStudentAndParent().getStudents(), + private School insertSchools(Symbol symbol) throws VulcanException, IOException { + List schoolList = DataObjectConverter.schoolsToSchoolsEntities( + vulcan.getSchools(), symbol.getId() ); - Timber.d("Register students %s", studentList.size()); - daoSession.getStudentDao().insertInTx(studentList); + Timber.d("Register schools (%s)", schoolList.size()); + daoSession.getSchoolDao().insertInTx(schoolList); + + return daoSession.getSchoolDao().queryBuilder().where( + SchoolDao.Properties.SymbolId.eq(symbol.getId()), + SchoolDao.Properties.Current.eq(true) + ).unique(); } - private void insertDiaries(Symbol symbolEntity) throws VulcanException, IOException { + private Student insertStudents(School school) throws VulcanException, IOException { + List studentList = DataObjectConverter.studentsToStudentEntities( + vulcan.getStudentAndParent().getStudents(), + school.getId() + ); + Timber.d("Register students (%s)", studentList.size()); + daoSession.getStudentDao().insertInTx(studentList); + + return daoSession.getStudentDao().queryBuilder().where( + StudentDao.Properties.SchoolId.eq(school.getId()), + StudentDao.Properties.Current.eq(true) + ).unique(); + } + + private Diary insertDiaries(Student student) throws VulcanException, IOException { List diaryList = DataObjectConverter.diariesToDiaryEntities( vulcan.getStudentAndParent().getDiaries(), - daoSession.getStudentDao().queryBuilder().where( - StudentDao.Properties.SymbolId.eq(symbolEntity.getId()), - StudentDao.Properties.Current.eq(true) - ).unique().getId()); - Timber.d("Register diaries %s", diaryList.size()); + student.getId() + ); + Timber.d("Register diaries (%s)", diaryList.size()); daoSession.getDiaryDao().insertInTx(diaryList); + + return daoSession.getDiaryDao().queryBuilder().where( + DiaryDao.Properties.StudentId.eq(student.getId()), + DiaryDao.Properties.Current.eq(true) + ).unique(); } - private void insertSemesters() throws VulcanException, IOException { + private void insertSemesters(Diary diary) throws VulcanException, IOException { List semesterList = DataObjectConverter.semestersToSemesterEntities( vulcan.getStudentAndParent().getSemesters(), - daoSession.getDiaryDao().queryBuilder().where( - DiaryDao.Properties.Current.eq(true) - ).unique().getId()); - Timber.d("Register semesters %s", semesterList.size()); + diary.getId() + ); + Timber.d("Register semesters (%s)", semesterList.size()); daoSession.getSemesterDao().insertInTx(semesterList); } @@ -138,8 +165,11 @@ public class AccountSync { Symbol symbol = daoSession.getSymbolDao().queryBuilder().where( SymbolDao.Properties.UserId.eq(account.getId())).unique(); + School school = daoSession.getSchoolDao().queryBuilder().where( + SchoolDao.Properties.SymbolId.eq(symbol.getId())).unique(); + Student student = daoSession.getStudentDao().queryBuilder().where( - StudentDao.Properties.SymbolId.eq(symbol.getId()), + StudentDao.Properties.SchoolId.eq(school.getId()), StudentDao.Properties.Current.eq(true) ).unique(); @@ -152,7 +182,7 @@ public class AccountSync { account.getEmail(), Scrambler.decrypt(account.getEmail(), account.getPassword()), symbol.getSymbol(), - symbol.getSchoolId(), + school.getRealId(), student.getRealId(), diary.getValue() ); diff --git a/app/src/main/java/io/github/wulkanowy/utils/DataObjectConverter.java b/app/src/main/java/io/github/wulkanowy/utils/DataObjectConverter.java index 1747fc26..cd4490d6 100644 --- a/app/src/main/java/io/github/wulkanowy/utils/DataObjectConverter.java +++ b/app/src/main/java/io/github/wulkanowy/utils/DataObjectConverter.java @@ -9,6 +9,7 @@ import io.github.wulkanowy.data.db.dao.entities.Day; import io.github.wulkanowy.data.db.dao.entities.Diary; import io.github.wulkanowy.data.db.dao.entities.Exam; import io.github.wulkanowy.data.db.dao.entities.Grade; +import io.github.wulkanowy.data.db.dao.entities.School; import io.github.wulkanowy.data.db.dao.entities.Semester; import io.github.wulkanowy.data.db.dao.entities.Student; import io.github.wulkanowy.data.db.dao.entities.Subject; @@ -21,7 +22,22 @@ public final class DataObjectConverter { throw new IllegalStateException("Utility class"); } - public static List studentsToStudentEntities(List students, Long symbolId) { + public static List schoolsToSchoolsEntities(List schools, Long symbolId) { + List studentList = new ArrayList<>(); + + for (io.github.wulkanowy.api.generic.School school : schools) { + studentList.add(new School() + .setName(school.getName()) + .setCurrent(school.getCurrent()) + .setRealId(school.getId()) + .setSymbolId(symbolId) + ); + } + + return studentList; + } + + public static List studentsToStudentEntities(List students, Long schoolId) { List studentList = new ArrayList<>(); for (io.github.wulkanowy.api.generic.Student student : students) { @@ -29,7 +45,7 @@ public final class DataObjectConverter { .setName(student.getName()) .setCurrent(student.isCurrent()) .setRealId(student.getId()) - .setSymbolId(symbolId) + .setSchoolId(schoolId) ); }