Add support for multiple SnP sites (#140)

This commit is contained in:
Mikołaj Pich 2018-07-14 16:52:09 +02:00 committed by Rafał Borcz
parent 5a4b8b22f3
commit 378aba9716
26 changed files with 630 additions and 219 deletions

View File

@ -8,9 +8,11 @@ import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import io.github.wulkanowy.api.generic.School;
import io.github.wulkanowy.api.login.Login; import io.github.wulkanowy.api.login.Login;
public class Client { public class Client {
@ -25,16 +27,21 @@ public class Client {
private String symbol; private String symbol;
private String schoolId;
private List<School> schools;
private Date lastSuccessRequest; private Date lastSuccessRequest;
private Cookies cookies = new Cookies(); private Cookies cookies = new Cookies();
private static final Logger logger = LoggerFactory.getLogger(Client.class); 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.email = email;
this.password = password; this.password = password;
this.symbol = symbol; this.symbol = symbol;
this.schoolId = schoolId;
setFullEndpointInfo(email); setFullEndpointInfo(email);
} }
@ -62,14 +69,18 @@ public class Client {
return; return;
} }
logger.info("Not logged. Login...");
clearCookies(); 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()); logger.info("Login successful on {} at {}", getHost(), new Date());
} }
private boolean isLoggedIn() { private boolean isLoggedIn() {
logger.debug("Last success request: {}", lastSuccessRequest); logger.trace("Last success request: {}", lastSuccessRequest);
logger.debug("Cookies: {}", getCookies().size()); logger.trace("Cookies: {}", getCookies().size());
return getCookies().size() > 0 && lastSuccessRequest != null && return getCookies().size() > 0 && lastSuccessRequest != null &&
5 > TimeUnit.MILLISECONDS.toMinutes(new Date().getTime() - lastSuccessRequest.getTime()); 5 > TimeUnit.MILLISECONDS.toMinutes(new Date().getTime() - lastSuccessRequest.getTime());
@ -92,15 +103,30 @@ public class Client {
cookies = new Cookies(); cookies = new Cookies();
} }
String getHost() { public String getHost() {
return host; return host;
} }
public void setSchools(List<School> schools) {
this.schools = schools;
this.schoolId = schools.get(0).getId();
}
public List<School> 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) { String getFilledUrl(String url) {
return url return url
.replace("{schema}", protocol) .replace("{schema}", protocol)
.replace("{host}", host.replace(":", "%253A")) .replace("{host}", host)
.replace("{symbol}", symbol); .replace("{symbol}", symbol)
.replace("{ID}", schoolId != null ? schoolId : "");
} }
public Document getPageByUrl(String url) throws IOException, VulcanException { public Document getPageByUrl(String url) throws IOException, VulcanException {

View File

@ -13,8 +13,6 @@ import io.github.wulkanowy.api.generic.Student;
public interface SnP { public interface SnP {
String getSchoolID();
void setDiaryID(String id); void setDiaryID(String id);
String getStudentID(); String getStudentID();

View File

@ -20,32 +20,27 @@ import io.github.wulkanowy.api.generic.Student;
public class StudentAndParent implements SnP { 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 BASE_URL = "{schema}://uonetplus-opiekun.{host}/{symbol}/{ID}/";
private static final String GRADES_PAGE_URL = "Oceny/Wszystkie"; private static final String GRADES_PAGE_URL = "Oceny/Wszystkie";
private Client client; private Client client;
private String schoolID;
private String studentID; private String studentID;
private String diaryID; private String diaryID;
private static final Logger logger = LoggerFactory.getLogger(StudentAndParent.class); 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.client = client;
this.schoolID = schoolID;
this.studentID = studentID; this.studentID = studentID;
this.diaryID = diaryID; this.diaryID = diaryID;
} }
public StudentAndParent setUp() throws IOException, VulcanException { public StudentAndParent setUp() throws IOException, VulcanException {
if (null == getStudentID() || "".equals(getStudentID())) { if (null == getStudentID() || "".equals(getStudentID())) {
Document doc = client.getPageByUrl(getSnpHomePageUrl()); Document doc = client.getPageByUrl(BASE_URL);
if (doc.select("#idSection").isEmpty()) { if (doc.select("#idSection").isEmpty()) {
logger.error("Expected SnP page, got page with title: {} {}", doc.title(), doc.selectFirst("body")); 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; return this;
} }
public String getSchoolID() {
return schoolID;
}
public String getStudentID() { public String getStudentID() {
return studentID; 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) { public String getRowDataChildValue(Element e, int index) {
return e.select(".daneWiersz .wartosc").get(index - 1).text(); return e.select(".daneWiersz .wartosc").get(index - 1).text();
} }
@ -120,7 +74,7 @@ public class StudentAndParent implements SnP {
cookies.put("idBiezacyDziennik", diaryID); cookies.put("idBiezacyDziennik", diaryID);
cookies.put("idBiezacyUczen", studentID); 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")) { if (!doc.title().startsWith("Witryna ucznia i rodzica")) {
logger.error("Expected SnP page, got page with title: {} {}", doc.title(), doc.selectFirst("body")); 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<Diary> getDiaries() throws IOException, VulcanException { public List<Diary> getDiaries() throws IOException, VulcanException {
return getDiaries(client.getPageByUrl(getBaseUrl())); return getDiaries(client.getPageByUrl(BASE_URL));
} }
private List<Diary> getDiaries(Document doc) throws IOException, VulcanException { private List<Diary> getDiaries(Document doc) throws IOException, VulcanException {
@ -143,7 +97,7 @@ public class StudentAndParent implements SnP {
} }
public List<Student> getStudents() throws IOException, VulcanException { public List<Student> getStudents() throws IOException, VulcanException {
return getStudents(client.getPageByUrl(getBaseUrl())); return getStudents(client.getPageByUrl(BASE_URL));
} }
private List<Student> getStudents(Document doc) throws IOException, VulcanException { private List<Student> getStudents(Document doc) throws IOException, VulcanException {

View File

@ -4,10 +4,12 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.util.List;
import io.github.wulkanowy.api.attendance.AttendanceStatistics; import io.github.wulkanowy.api.attendance.AttendanceStatistics;
import io.github.wulkanowy.api.attendance.AttendanceTable; import io.github.wulkanowy.api.attendance.AttendanceTable;
import io.github.wulkanowy.api.exams.ExamsWeek; 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.GradesList;
import io.github.wulkanowy.api.grades.SubjectsList; import io.github.wulkanowy.api.grades.SubjectsList;
import io.github.wulkanowy.api.messages.Messages; import io.github.wulkanowy.api.messages.Messages;
@ -27,8 +29,6 @@ public class Vulcan {
private Client client; private Client client;
private String schoolId;
private String studentId; private String studentId;
private String diaryId; private String diaryId;
@ -36,11 +36,10 @@ public class Vulcan {
private static final Logger logger = LoggerFactory.getLogger(Vulcan.class); private static final Logger logger = LoggerFactory.getLogger(Vulcan.class);
public void setCredentials(String email, String password, String symbol, String schoolId, String studentId, String diaryId) { public void setCredentials(String email, String password, String symbol, String schoolId, String studentId, String diaryId) {
this.schoolId = schoolId;
this.studentId = studentId; this.studentId = studentId;
this.diaryId = diaryId; this.diaryId = diaryId;
client = new Client(email, password, symbol); client = new Client(email, password, symbol, schoolId);
logger.debug("Client created with symbol " + symbol); logger.debug("Client created with symbol " + symbol);
} }
@ -55,7 +54,10 @@ public class Vulcan {
public String getSymbol() throws NotLoggedInErrorException { public String getSymbol() throws NotLoggedInErrorException {
return getClient().getSymbol(); return getClient().getSymbol();
}
public List<School> getSchools() throws VulcanException, IOException {
return getClient().getSchools();
} }
public SnP getStudentAndParent() throws VulcanException, IOException { public SnP getStudentAndParent() throws VulcanException, IOException {
@ -63,7 +65,7 @@ public class Vulcan {
return this.snp; return this.snp;
} }
this.snp = new StudentAndParent(getClient(), schoolId, studentId, diaryId) this.snp = new StudentAndParent(getClient(), studentId, diaryId)
.setUp(); .setUp();
return this.snp; return this.snp;

View File

@ -0,0 +1,7 @@
package io.github.wulkanowy.api.generic
data class School(
val name: String,
val id: String,
val current: Boolean
)

View File

@ -16,8 +16,9 @@ import io.github.wulkanowy.api.VulcanException;
public class Login { public class Login {
static final String LOGIN_PAGE_URL = "{schema}://cufs.{host}/{symbol}/Account/LogOn" + protected static final String LOGIN_PAGE_URL = "{schema}://cufs.{host}/{symbol}/Account/LogOn";
"?ReturnUrl=%2F{symbol}%2FFS%2FLS%3Fwa%3Dwsignin1.0%26wtrealm%3D" +
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%26wctx%3D" +
"{schema}%253a%252f%252fuonetplus.{host}%252f{symbol}%252fLoginEndpoint.aspx"; "{schema}%253a%252f%252fuonetplus.{host}%252f{symbol}%252fLoginEndpoint.aspx";
@ -29,7 +30,7 @@ public class Login {
this.client = client; 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); Document certDoc = sendCredentials(email, password);
if ("Błąd".equals(certDoc.title())) { if ("Błąd".equals(certDoc.title())) {
@ -37,7 +38,7 @@ public class Login {
throw new NotLoggedInErrorException(certDoc.body().text()); throw new NotLoggedInErrorException(certDoc.body().text());
} }
return sendCertificate(certDoc, symbol); sendCertificate(certDoc, symbol);
} }
Document sendCredentials(String email, String password) throws IOException, VulcanException { Document sendCredentials(String email, String password) throws IOException, VulcanException {
@ -46,7 +47,7 @@ public class Login {
{"Password", password} {"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"); Element errorMessage = nextDoc.selectFirst(".ErrorMessage, #ErrorTextLabel");
if (null != errorMessage) { 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())); client.setSymbol(findSymbol(defaultSymbol, doc.select("input[name=wresult]").val()));
Document targetDoc = sendCertData(doc); Document targetDoc = sendCertData(doc);
@ -106,7 +107,7 @@ public class Login {
throw new LoginErrorException("Expected page title `UONET+`, got " + title); 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 { private Document sendCertData(Document doc) throws IOException, VulcanException {

View File

@ -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<School> {
val schoolList = mutableListOf<School>()
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]
}
}

View File

@ -12,16 +12,24 @@ public class ClientTest {
} }
@Test @Test
public void setFullEndpointInfoTest() throws Exception { public void setFullEndpointInfoTest() {
Client client = new Client("http://fakelog.net\\\\admin", "pass", "Default"); 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()); 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 @Test
public void checkForNoErrorsTest() throws Exception { public void checkForNoErrorsTest() throws Exception {
Client client = new Client("", "", ""); Client client = new Client("", "", "", "123");
Document doc = Jsoup.parse(getFixtureAsString("login/Logowanie-success.html")); Document doc = Jsoup.parse(getFixtureAsString("login/Logowanie-success.html"));
@ -30,7 +38,7 @@ public class ClientTest {
@Test(expected = VulcanOfflineException.class) @Test(expected = VulcanOfflineException.class)
public void checkForErrorsOffline() throws Exception { public void checkForErrorsOffline() throws Exception {
Client client = new Client("", "", ""); Client client = new Client("", "", "", "123");
Document doc = Jsoup.parse(getFixtureAsString("login/PrzerwaTechniczna.html")); Document doc = Jsoup.parse(getFixtureAsString("login/PrzerwaTechniczna.html"));
@ -39,7 +47,7 @@ public class ClientTest {
@Test(expected = NotLoggedInErrorException.class) @Test(expected = NotLoggedInErrorException.class)
public void checkForErrors() throws Exception { public void checkForErrors() throws Exception {
Client client = new Client("", "", ""); Client client = new Client("", "", "", "123");
Document doc = Jsoup.parse(getFixtureAsString("login/Logowanie-notLoggedIn.html")); Document doc = Jsoup.parse(getFixtureAsString("login/Logowanie-notLoggedIn.html"));
@ -48,16 +56,23 @@ public class ClientTest {
@Test @Test
public void getFilledUrlTest() throws Exception { 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", Assert.assertEquals("http://uonetplus-opiekun.fakelog.cf/symbol123/321/Oceny/Wszystkie",
client.getFilledUrl("{schema}://uonetplus.{host}/{symbol}/LoginEndpoint.aspx")); client.getFilledUrl("{schema}://uonetplus-opiekun.{host}/{symbol}/{ID}/Oceny/Wszystkie"));
} }
@Test @Test
public void getSymbolTest() throws Exception { public void getSymbolTest() {
Client client = new Client("", "", "symbol4321"); Client client = new Client("", "", "symbol4321", "123");
Assert.assertEquals("symbol4321", client.getSymbol()); Assert.assertEquals("symbol4321", client.getSymbol());
} }
@Test
public void getSchoolIdTest() throws Exception {
Client client = new Client("", "", "1", "123456");
Assert.assertEquals("123456", client.getSchoolId());
}
} }

View File

@ -32,68 +32,13 @@ public class StudentAndParentTest {
@Test @Test
public void snpTest() { public void snpTest() {
StudentAndParent snp = new StudentAndParent(client, "id123", null, null); StudentAndParent snp = new StudentAndParent(client, "1234", null);
Assert.assertEquals("id123", snp.getSchoolID()); Assert.assertEquals("1234", snp.getStudentID());
}
@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/"));
} }
@Test @Test
public void getSemestersTest() throws Exception { public void getSemestersTest() throws Exception {
SnP snp = new StudentAndParent(client, "123456", null, null); SnP snp = new StudentAndParent(client, null, null);
List<Semester> semesters = snp.getSemesters(); List<Semester> semesters = snp.getSemesters();
Assert.assertEquals(2, semesters.size()); 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("1500100900").setId("1").setCurrent(false));
semesters.add(new Semester().setName("1500100901").setId("2").setCurrent(true)); 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); Semester semester = snp.getCurrent(semesters);
Assert.assertTrue(semester.isCurrent()); Assert.assertTrue(semester.isCurrent());
@ -123,7 +68,7 @@ public class StudentAndParentTest {
@Test @Test
public void getCurrentSemesterFromEmptyTest() { public void getCurrentSemesterFromEmptyTest() {
SnP snp = new StudentAndParent(client, "", null, null); SnP snp = new StudentAndParent(client, null, null);
List<Semester> semesters = new ArrayList<>(); List<Semester> semesters = new ArrayList<>();
Assert.assertNull(snp.getCurrent(semesters)); Assert.assertNull(snp.getCurrent(semesters));
@ -136,7 +81,7 @@ public class StudentAndParentTest {
client = Mockito.mock(Client.class); client = Mockito.mock(Client.class);
Mockito.when(client.getPageByUrl(Mockito.anyString())).thenReturn(snpHome); Mockito.when(client.getPageByUrl(Mockito.anyString())).thenReturn(snpHome);
SnP snp = new StudentAndParent(client, "", null, null); SnP snp = new StudentAndParent(client, null, null);
snp.setUp(); snp.setUp();

View File

@ -38,9 +38,11 @@ public class LoginTest {
.thenReturn(getFixtureAsDocument("Logowanie-certyfikat.html")); .thenReturn(getFixtureAsDocument("Logowanie-certyfikat.html"));
Mockito.doCallRealMethod().when(client).setSymbol(Mockito.anyString()); Mockito.doCallRealMethod().when(client).setSymbol(Mockito.anyString());
Mockito.when(client.getSymbol()).thenCallRealMethod(); Mockito.when(client.getSymbol()).thenCallRealMethod();
Mockito.when(client.getHost()).thenReturn("fakelog.cf");
Login login = new Login(client); 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) @Test(expected = BadCredentialsException.class)
@ -74,10 +76,12 @@ public class LoginTest {
Client client = getClient("Logowanie-success.html"); Client client = getClient("Logowanie-success.html");
Mockito.doCallRealMethod().when(client).setSymbol(Mockito.anyString()); Mockito.doCallRealMethod().when(client).setSymbol(Mockito.anyString());
Mockito.when(client.getSymbol()).thenCallRealMethod(); Mockito.when(client.getSymbol()).thenCallRealMethod();
Mockito.when(client.getHost()).thenReturn("fakelog.cf");
Login login = new Login(client); Login login = new Login(client);
Assert.assertEquals("wulkanowyschool321", login.sendCertificate( login.sendCertificate(getFixtureAsDocument("Logowanie-certyfikat.html"), "wulkanowyschool321");
getFixtureAsDocument("Logowanie-certyfikat.html"), "wulkanowyschool321"));
Assert.assertEquals("wulkanowyschool321", client.getSymbol());
} }
@Test @Test
@ -85,10 +89,12 @@ public class LoginTest {
Client client = getClient("Logowanie-success.html"); Client client = getClient("Logowanie-success.html");
Mockito.doCallRealMethod().when(client).setSymbol(Mockito.anyString()); Mockito.doCallRealMethod().when(client).setSymbol(Mockito.anyString());
Mockito.when(client.getSymbol()).thenCallRealMethod(); Mockito.when(client.getSymbol()).thenCallRealMethod();
Mockito.when(client.getHost()).thenReturn("fakelog.cf");
Login login = new Login(client); 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) @Test(expected = AccountPermissionException.class)

View File

@ -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/"))
}
}

View File

@ -0,0 +1,27 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Uonet+</title>
</head>
<body>
<div class="startScreen">
<div class="holder">
<div class="content">
<div class="panel linkownia pracownik klient">
<div id="idAppUczen" class="subDiv">
<a href="https://uonetplus-opiekun.fakelog.cf/symbol/123456/Start/Index/">
<span class="header directLink">GIMBB</span>
</a>
<br>
<a href="https://uonetplus-opiekun.fakelog.cf/symbol/123457/Start/Index/">
<span class="header directLink">SPBB</span>
</a>
<br>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

View File

@ -9,7 +9,7 @@
<div class="holder"> <div class="holder">
<div class="content"> <div class="content">
<div class="panel linkownia pracownik klient"> <div class="panel linkownia pracownik klient">
<a href="https://uonetplus-opiekun.vulcan.net.pl/symbol/534213/Start/Index/"> <a href="https://uonetplus-opiekun.fakelog.cf/symbol/534213/Start/Index/">
<div class="imagedHeader directLink"> <div class="imagedHeader directLink">
<div id="idEmptyAppUczeń"> <div id="idEmptyAppUczeń">
<div class="name">Uczeń</div> <div class="name">Uczeń</div>

View File

@ -11,6 +11,19 @@
<span class="userdata">example@wulkanowy.io (<a href="/demo123/LoginEndpoint.aspx?logout=true">wyloguj</a>)</span> <span class="userdata">example@wulkanowy.io (<a href="/demo123/LoginEndpoint.aspx?logout=true">wyloguj</a>)</span>
</div> </div>
</div> </div>
<div class="holder">
<div class="content">
<div class="panel linkownia pracownik klient">
<a href="https://uonetplus-opiekun.fakelog.cf/symbol/534213/Start/Index/">
<div class="imagedHeader directLink">
<div id="idEmptyAppUczeń">
<div class="name">Uczeń</div>
</div>
</div>
</a>
</div>
</div>
</div>
</div> </div>
</body> </body>
</html> </html>

View File

@ -93,7 +93,7 @@ play {
} }
greendao { greendao {
schemaVersion 28 schemaVersion 29
generateTests = true generateTests = true
} }

View File

@ -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<SchoolDao, School> {
public SchoolTest() {
super(SchoolDao.class);
}
@Override
protected School createEntity(Long key) {
School entity = new School();
entity.setId(key);
entity.setCurrent(false);
return entity;
}
}

View File

@ -17,6 +17,8 @@ public interface DbContract {
List<Grade> getNewGrades(int semesterName); List<Grade> getNewGrades(int semesterName);
long getCurrentSchoolId();
long getCurrentStudentId(); long getCurrentStudentId();
long getCurrentSymbolId(); long getCurrentSymbolId();

View File

@ -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.Migration26;
import io.github.wulkanowy.data.db.dao.migrations.Migration27; 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.Migration28;
import io.github.wulkanowy.data.db.dao.migrations.Migration29;
import io.github.wulkanowy.data.db.shared.SharedPrefContract; import io.github.wulkanowy.data.db.shared.SharedPrefContract;
import timber.log.Timber; import timber.log.Timber;
@ -79,6 +80,7 @@ public class DbHelper extends DaoMaster.OpenHelper {
migrations.add(new Migration26()); migrations.add(new Migration26());
migrations.add(new Migration27()); migrations.add(new Migration27());
migrations.add(new Migration28()); migrations.add(new Migration28());
migrations.add(new Migration29());
// Sorting just to be safe, in case other people add migrations in the wrong order. // Sorting just to be safe, in case other people add migrations in the wrong order.
Comparator<Migration> migrationComparator = new Comparator<Migration>() { Comparator<Migration> migrationComparator = new Comparator<Migration>() {

View File

@ -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.DiaryDao;
import io.github.wulkanowy.data.db.dao.entities.Grade; 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.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.Semester;
import io.github.wulkanowy.data.db.dao.entities.SemesterDao; import io.github.wulkanowy.data.db.dao.entities.SemesterDao;
import io.github.wulkanowy.data.db.dao.entities.StudentDao; import io.github.wulkanowy.data.db.dao.entities.StudentDao;
@ -72,10 +73,18 @@ public class DbRepository implements DbContract {
return getCurrentSymbol().getId(); 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 @Override
public long getCurrentStudentId() { public long getCurrentStudentId() {
return daoSession.getStudentDao().queryBuilder().where( return daoSession.getStudentDao().queryBuilder().where(
StudentDao.Properties.SymbolId.eq(getCurrentSymbolId()), StudentDao.Properties.SchoolId.eq(getCurrentSchoolId()),
StudentDao.Properties.Current.eq(true) StudentDao.Properties.Current.eq(true)
).unique().getId(); ).unique().getId();
} }

View File

@ -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<Student> 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<Student> 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<Student> 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;
}
}

View File

@ -18,8 +18,8 @@ public class Student {
@Id(autoincrement = true) @Id(autoincrement = true)
private Long id; private Long id;
@Property(nameInDb = "symbol_id") @Property(nameInDb = "school_id")
private Long symbolId; private Long schoolId;
@Property(nameInDb = "current") @Property(nameInDb = "current")
private boolean current; private boolean current;
@ -45,10 +45,10 @@ public class Student {
@Generated(hash = 1943931642) @Generated(hash = 1943931642)
private transient StudentDao myDao; private transient StudentDao myDao;
@Generated(hash = 1334215952) @Generated(hash = 470181623)
public Student(Long id, Long symbolId, boolean current, String realId, String name) { public Student(Long id, Long schoolId, boolean current, String realId, String name) {
this.id = id; this.id = id;
this.symbolId = symbolId; this.schoolId = schoolId;
this.current = current; this.current = current;
this.realId = realId; this.realId = realId;
this.name = name; this.name = name;
@ -66,12 +66,12 @@ public class Student {
this.id = id; this.id = id;
} }
public Long getSymbolId() { public Long getSchoolId() {
return this.symbolId; return this.schoolId;
} }
public Student setSymbolId(Long symbolId) { public Student setSchoolId(Long schoolId) {
this.symbolId = symbolId; this.schoolId = schoolId;
return this; return this;
} }

View File

@ -24,9 +24,6 @@ public class Symbol {
@Property(nameInDb = "host") @Property(nameInDb = "host")
private String host; private String host;
@Property(nameInDb = "school_id")
private String schoolId;
@Property(nameInDb = "symbol") @Property(nameInDb = "symbol")
private String symbol; private String symbol;
@ -34,7 +31,7 @@ public class Symbol {
private String type; private String type;
@ToMany(referencedJoinProperty = "symbolId") @ToMany(referencedJoinProperty = "symbolId")
private List<Student> studentList; private List<School> schoolList;
/** /**
* Used to resolve relations * Used to resolve relations
@ -48,13 +45,11 @@ public class Symbol {
@Generated(hash = 684907977) @Generated(hash = 684907977)
private transient SymbolDao myDao; private transient SymbolDao myDao;
@Generated(hash = 242774339) @Generated(hash = 1034469460)
public Symbol(Long id, Long userId, String host, String schoolId, String symbol, public Symbol(Long id, Long userId, String host, String symbol, String type) {
String type) {
this.id = id; this.id = id;
this.userId = userId; this.userId = userId;
this.host = host; this.host = host;
this.schoolId = schoolId;
this.symbol = symbol; this.symbol = symbol;
this.type = type; this.type = type;
} }
@ -89,15 +84,6 @@ public class Symbol {
return this; return this;
} }
public String getSchoolId() {
return this.schoolId;
}
public Symbol setSchoolId(String schoolId) {
this.schoolId = schoolId;
return this;
}
public String getSymbol() { public String getSymbol() {
return this.symbol; return this.symbol;
} }
@ -120,30 +106,28 @@ public class Symbol {
* To-many relationship, resolved on first access (and after reset). * To-many relationship, resolved on first access (and after reset).
* Changes to to-many relations are not persisted, make changes to the target entity. * Changes to to-many relations are not persisted, make changes to the target entity.
*/ */
@Generated(hash = 604366458) @Generated(hash = 1733082867)
public List<Student> getStudentList() { public List<School> getSchoolList() {
if (studentList == null) { if (schoolList == null) {
final DaoSession daoSession = this.daoSession; final DaoSession daoSession = this.daoSession;
if (daoSession == null) { if (daoSession == null) {
throw new DaoException("Entity is detached from DAO context"); throw new DaoException("Entity is detached from DAO context");
} }
StudentDao targetDao = daoSession.getStudentDao(); SchoolDao targetDao = daoSession.getSchoolDao();
List<Student> studentListNew = targetDao._querySymbol_StudentList(id); List<School> schoolListNew = targetDao._querySymbol_SchoolList(id);
synchronized (this) { synchronized (this) {
if (studentList == null) { if (schoolList == null) {
studentList = studentListNew; schoolList = schoolListNew;
} }
} }
} }
return studentList; return schoolList;
} }
/** /** Resets a to-many relationship, making the next get call to query for a fresh result. */
* Resets a to-many relationship, making the next get call to query for a fresh result. @Generated(hash = 1757777300)
*/ public synchronized void resetSchoolList() {
@Generated(hash = 1628625923) schoolList = null;
public synchronized void resetStudentList() {
studentList = null;
} }
/** /**

View File

@ -15,7 +15,7 @@ public class Migration27 implements DbHelper.Migration {
} }
@Override @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.dropTable(db, true);
ExamDao.createTable(db, true); ExamDao.createTable(db, true);

View File

@ -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ń\"" +
")")
}
}

View File

@ -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.DaoSession;
import io.github.wulkanowy.data.db.dao.entities.Diary; 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.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.Semester;
import io.github.wulkanowy.data.db.dao.entities.Student; import io.github.wulkanowy.data.db.dao.entities.Student;
import io.github.wulkanowy.data.db.dao.entities.StudentDao; import io.github.wulkanowy.data.db.dao.entities.StudentDao;
@ -57,12 +59,15 @@ public class AccountSync {
daoSession.getDatabase().beginTransaction(); daoSession.getDatabase().beginTransaction();
Timber.i("Register start");
try { try {
Account account = insertAccount(email, password); Account account = insertAccount(email, password);
Symbol symbolEntity = insertSymbol(account); Symbol symbolEntity = insertSymbol(account);
insertStudents(symbolEntity); School schoolEntity = insertSchools(symbolEntity);
insertDiaries(symbolEntity); Student student = insertStudents(schoolEntity);
insertSemesters(); Diary diary = insertDiaries(student);
insertSemesters(diary);
sharedPref.setCurrentUserId(account.getId()); sharedPref.setCurrentUserId(account.getId());
@ -70,6 +75,8 @@ public class AccountSync {
} finally { } finally {
daoSession.getDatabase().endTransaction(); daoSession.getDatabase().endTransaction();
} }
Timber.i("Register end");
} }
private Account insertAccount(String email, String password) throws CryptoException { private Account insertAccount(String email, String password) throws CryptoException {
@ -82,44 +89,64 @@ public class AccountSync {
} }
private Symbol insertSymbol(Account account) throws VulcanException, IOException { private Symbol insertSymbol(Account account) throws VulcanException, IOException {
String schoolId = vulcan.getStudentAndParent().getSchoolID(); vulcan.getSchools();
Timber.d("Register symbol %s", vulcan.getSymbol()); Timber.d("Register symbol (%s)", vulcan.getSymbol());
Symbol symbol = new Symbol() Symbol symbol = new Symbol()
.setUserId(account.getId()) .setUserId(account.getId())
.setSchoolId(schoolId)
.setSymbol(vulcan.getSymbol()); .setSymbol(vulcan.getSymbol());
daoSession.getSymbolDao().insert(symbol); daoSession.getSymbolDao().insert(symbol);
return symbol; return symbol;
} }
private void insertStudents(Symbol symbol) throws VulcanException, IOException { private School insertSchools(Symbol symbol) throws VulcanException, IOException {
List<Student> studentList = DataObjectConverter.studentsToStudentEntities( List<School> schoolList = DataObjectConverter.schoolsToSchoolsEntities(
vulcan.getStudentAndParent().getStudents(), vulcan.getSchools(),
symbol.getId() symbol.getId()
); );
Timber.d("Register students %s", studentList.size()); Timber.d("Register schools (%s)", schoolList.size());
daoSession.getStudentDao().insertInTx(studentList); 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<Student> 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<Diary> diaryList = DataObjectConverter.diariesToDiaryEntities( List<Diary> diaryList = DataObjectConverter.diariesToDiaryEntities(
vulcan.getStudentAndParent().getDiaries(), vulcan.getStudentAndParent().getDiaries(),
daoSession.getStudentDao().queryBuilder().where( student.getId()
StudentDao.Properties.SymbolId.eq(symbolEntity.getId()), );
StudentDao.Properties.Current.eq(true) Timber.d("Register diaries (%s)", diaryList.size());
).unique().getId());
Timber.d("Register diaries %s", diaryList.size());
daoSession.getDiaryDao().insertInTx(diaryList); 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<Semester> semesterList = DataObjectConverter.semestersToSemesterEntities( List<Semester> semesterList = DataObjectConverter.semestersToSemesterEntities(
vulcan.getStudentAndParent().getSemesters(), vulcan.getStudentAndParent().getSemesters(),
daoSession.getDiaryDao().queryBuilder().where( diary.getId()
DiaryDao.Properties.Current.eq(true) );
).unique().getId()); Timber.d("Register semesters (%s)", semesterList.size());
Timber.d("Register semesters %s", semesterList.size());
daoSession.getSemesterDao().insertInTx(semesterList); daoSession.getSemesterDao().insertInTx(semesterList);
} }
@ -138,8 +165,11 @@ public class AccountSync {
Symbol symbol = daoSession.getSymbolDao().queryBuilder().where( Symbol symbol = daoSession.getSymbolDao().queryBuilder().where(
SymbolDao.Properties.UserId.eq(account.getId())).unique(); 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( Student student = daoSession.getStudentDao().queryBuilder().where(
StudentDao.Properties.SymbolId.eq(symbol.getId()), StudentDao.Properties.SchoolId.eq(school.getId()),
StudentDao.Properties.Current.eq(true) StudentDao.Properties.Current.eq(true)
).unique(); ).unique();
@ -152,7 +182,7 @@ public class AccountSync {
account.getEmail(), account.getEmail(),
Scrambler.decrypt(account.getEmail(), account.getPassword()), Scrambler.decrypt(account.getEmail(), account.getPassword()),
symbol.getSymbol(), symbol.getSymbol(),
symbol.getSchoolId(), school.getRealId(),
student.getRealId(), student.getRealId(),
diary.getValue() diary.getValue()
); );

View File

@ -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.Diary;
import io.github.wulkanowy.data.db.dao.entities.Exam; 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.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.Semester;
import io.github.wulkanowy.data.db.dao.entities.Student; import io.github.wulkanowy.data.db.dao.entities.Student;
import io.github.wulkanowy.data.db.dao.entities.Subject; import io.github.wulkanowy.data.db.dao.entities.Subject;
@ -21,7 +22,22 @@ public final class DataObjectConverter {
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
public static List<Student> studentsToStudentEntities(List<io.github.wulkanowy.api.generic.Student> students, Long symbolId) { public static List<School> schoolsToSchoolsEntities(List<io.github.wulkanowy.api.generic.School> schools, Long symbolId) {
List<School> 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<Student> studentsToStudentEntities(List<io.github.wulkanowy.api.generic.Student> students, Long schoolId) {
List<Student> studentList = new ArrayList<>(); List<Student> studentList = new ArrayList<>();
for (io.github.wulkanowy.api.generic.Student student : students) { for (io.github.wulkanowy.api.generic.Student student : students) {
@ -29,7 +45,7 @@ public final class DataObjectConverter {
.setName(student.getName()) .setName(student.getName())
.setCurrent(student.isCurrent()) .setCurrent(student.isCurrent())
.setRealId(student.getId()) .setRealId(student.getId())
.setSymbolId(symbolId) .setSchoolId(schoolId)
); );
} }