Optimize session handling (#63)

* [APP] Change way the Vulcan is configured (#65)
This commit is contained in:
Mikołaj Pich 2018-03-11 19:16:20 +01:00 committed by Rafał Borcz
parent a0313827ce
commit 3aca34340d
57 changed files with 521 additions and 454 deletions

View File

@ -5,44 +5,102 @@ import org.jsoup.Jsoup;
import org.jsoup.nodes.Document; import org.jsoup.nodes.Document;
import java.io.IOException; import java.io.IOException;
import java.util.Date;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit;
import io.github.wulkanowy.api.login.Login;
public class Client { public class Client {
private String protocol; private String protocol = "https";
private String host; private String host = "vulcan.net.pl";
private String symbol; private String email;
private String password;
private String symbol = "Default";
private Login login;
private Date lastSuccessRequest = new Date();
private Cookies cookies = new Cookies(); private Cookies cookies = new Cookies();
Client(String protocol, String host, String symbol) { Client(String email, String password, String symbol) {
this.protocol = protocol; this.email = email;
this.host = host; this.password = password;
this.symbol = symbol; this.symbol = symbol;
setFullEndpointInfo(email);
} }
String getHost() { private void setFullEndpointInfo(String info) {
return host; String[] creds = info.split("\\\\");
email = info;
if (creds.length > 2) {
String[] url = creds[0].split("://");
protocol = url[0];
host = url[1];
email = creds[2];
}
}
private void login() throws IOException, VulcanException {
if (isLoggedIn()) {
return;
}
this.symbol = getLogin().login(email, password, symbol);
}
private boolean isLoggedIn() {
return getCookies().size() > 0 &&
29 > TimeUnit.MILLISECONDS.toMinutes(new Date().getTime() - lastSuccessRequest.getTime());
}
Login getLogin() {
if (null != login) {
return login;
}
login = new Login(this);
return login;
}
public String getSymbol() {
return symbol;
} }
public void setSymbol(String symbol) { public void setSymbol(String symbol) {
this.symbol = symbol; this.symbol = symbol;
} }
Map<String, String> getCookies() { private Map<String, String> getCookies() {
return cookies.getItems(); return cookies.getItems();
} }
private String getFilledUrl(String url) { String getHost() {
return host;
}
String getFilledUrl(String url) {
return url return url
.replace("{schema}", protocol) .replace("{schema}", protocol)
.replace("{host}", host.replace(":", "%253A")) .replace("{host}", host.replace(":", "%253A"))
.replace("{symbol}", symbol == null ? "Default" : symbol); .replace("{symbol}", symbol);
} }
Document getPageByUrl(String url) throws IOException { Document getPageByUrl(String url) throws IOException, VulcanException {
login();
Connection.Response response = Jsoup.connect(getFilledUrl(url)) Connection.Response response = Jsoup.connect(getFilledUrl(url))
.followRedirects(true) .followRedirects(true)
.cookies(getCookies()) .cookies(getCookies())
@ -50,10 +108,10 @@ public class Client {
this.cookies.addItems(response.cookies()); this.cookies.addItems(response.cookies());
return response.parse(); return checkForErrors(response.parse());
} }
public Document postPageByUrl(String url, String[][] params) throws IOException { public Document postPageByUrl(String url, String[][] params) throws IOException, VulcanException {
Connection connection = Jsoup.connect(getFilledUrl(url)); Connection connection = Jsoup.connect(getFilledUrl(url));
for (String[] data : params) { for (String[] data : params) {
@ -68,10 +126,12 @@ public class Client {
this.cookies.addItems(response.cookies()); this.cookies.addItems(response.cookies());
return response.parse(); return checkForErrors(response.parse());
} }
public String getJsonStringByUrl(String url) throws IOException { public String getJsonStringByUrl(String url) throws IOException, VulcanException {
login();
Connection.Response response = Jsoup.connect(getFilledUrl(url)) Connection.Response response = Jsoup.connect(getFilledUrl(url))
.followRedirects(true) .followRedirects(true)
.ignoreContentType(true) .ignoreContentType(true)
@ -83,7 +143,9 @@ public class Client {
return response.body(); return response.body();
} }
public String postJsonStringByUrl(String url, String[][] params) throws IOException { public String postJsonStringByUrl(String url, String[][] params) throws IOException, VulcanException {
login();
Connection connection = Jsoup.connect(getFilledUrl(url)); Connection connection = Jsoup.connect(getFilledUrl(url));
for (String[] data : params) { for (String[] data : params) {
@ -101,4 +163,18 @@ public class Client {
return response.body(); return response.body();
} }
Document checkForErrors(Document doc) throws VulcanException {
if ("Przerwa techniczna".equals(doc.select("title").text())) {
throw new VulcanOfflineException();
}
if ("Zaloguj się".equals(doc.select(".loginButton").text())) {
throw new NotLoggedInErrorException();
}
lastSuccessRequest = new Date();
return doc;
}
} }

View File

@ -3,21 +3,15 @@ package io.github.wulkanowy.api;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class Cookies { class Cookies {
private Map<String, String> jar = new HashMap<>(); private Map<String, String> jar = new HashMap<>();
public Map<String, String> getItems() { Map<String, String> getItems() {
return jar; return jar;
} }
public Cookies setItems(Map<String, String> items) { void addItems(Map<String, String> items) {
this.jar = items; jar.putAll(items);
return this;
}
public Cookies addItems(Map<String, String> items) {
this.jar.putAll(items);
return this;
} }
} }

View File

@ -0,0 +1,4 @@
package io.github.wulkanowy.api;
public class NotLoggedInErrorException extends VulcanException {
}

View File

@ -6,19 +6,17 @@ import org.jsoup.nodes.Element;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import io.github.wulkanowy.api.login.NotLoggedInErrorException;
public interface SnP { public interface SnP {
String getId(); String getId();
void storeContextCookies() throws IOException, NotLoggedInErrorException; StudentAndParent storeContextCookies() throws IOException, VulcanException;
String getRowDataChildValue(Element e, int index); String getRowDataChildValue(Element e, int index);
Document getSnPPageDocument(String url) throws IOException; Document getSnPPageDocument(String url) throws IOException, VulcanException;
List<Semester> getSemesters() throws IOException; List<Semester> getSemesters() throws IOException, VulcanException;
List<Semester> getSemesters(Document gradesPage); List<Semester> getSemesters(Document gradesPage);

View File

@ -8,8 +8,6 @@ import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import io.github.wulkanowy.api.login.NotLoggedInErrorException;
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 START_PAGE_URL = "{schema}://uonetplus.{host}/{symbol}/Start.mvc/Index";
@ -22,12 +20,8 @@ public class StudentAndParent implements SnP {
private String id; private String id;
StudentAndParent(Client client) {
this.client = client;
}
StudentAndParent(Client client, String id) { StudentAndParent(Client client, String id) {
this(client); this.client = client;
this.id = id; this.id = id;
} }
@ -39,11 +33,12 @@ public class StudentAndParent implements SnP {
return id; return id;
} }
public void storeContextCookies() throws IOException, NotLoggedInErrorException { public StudentAndParent storeContextCookies() throws IOException, VulcanException {
client.getPageByUrl(getSnpHomePageUrl()); client.getPageByUrl(getSnpHomePageUrl());
return this;
} }
String getSnpHomePageUrl() throws IOException, NotLoggedInErrorException { String getSnpHomePageUrl() throws IOException, VulcanException {
if (null != getId()) { if (null != getId()) {
return getBaseUrl(); return getBaseUrl();
} }
@ -77,11 +72,11 @@ public class StudentAndParent implements SnP {
return e.select(".daneWiersz .wartosc").get(index - 1).text(); return e.select(".daneWiersz .wartosc").get(index - 1).text();
} }
public Document getSnPPageDocument(String url) throws IOException { public Document getSnPPageDocument(String url) throws IOException, VulcanException {
return client.getPageByUrl(getBaseUrl() + url); return client.getPageByUrl(getBaseUrl() + url);
} }
public List<Semester> getSemesters() throws IOException { public List<Semester> getSemesters() throws IOException, VulcanException {
return getSemesters(getSnPPageDocument(GRADES_PAGE_URL)); return getSemesters(getSnPPageDocument(GRADES_PAGE_URL));
} }

View File

@ -7,12 +7,6 @@ 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.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.login.AccountPermissionException;
import io.github.wulkanowy.api.login.BadCredentialsException;
import io.github.wulkanowy.api.login.Login;
import io.github.wulkanowy.api.login.LoginErrorException;
import io.github.wulkanowy.api.login.NotLoggedInErrorException;
import io.github.wulkanowy.api.login.VulcanOfflineException;
import io.github.wulkanowy.api.messages.Messages; import io.github.wulkanowy.api.messages.Messages;
import io.github.wulkanowy.api.notes.AchievementsList; import io.github.wulkanowy.api.notes.AchievementsList;
import io.github.wulkanowy.api.notes.NotesList; import io.github.wulkanowy.api.notes.NotesList;
@ -26,171 +20,92 @@ public class Vulcan {
private String id; private String id;
private String symbol;
private SnP snp; private SnP snp;
private String protocolSchema = "https";
private String logHost = "vulcan.net.pl";
private String email;
private Client client; private Client client;
private Login login; public void setCredentials(String email, String password, String symbol, String id) {
client = new Client(email, password, symbol);
public void setClient(Client client) {
this.client = client;
}
public void setLogin(Login login) {
this.login = login;
}
public void login(String email, String password, String symbol)
throws BadCredentialsException, AccountPermissionException,
LoginErrorException, IOException, VulcanOfflineException {
setFullEndpointInfo(email);
login = getLogin();
this.symbol = login.login(this.email, password, symbol);
}
public Vulcan login(String email, String password, String symbol, String id)
throws BadCredentialsException, AccountPermissionException,
LoginErrorException, IOException, VulcanOfflineException {
login(email, password, symbol);
this.id = id; this.id = id;
return this;
} }
String getProtocolSchema() { public Client getClient() throws NotLoggedInErrorException {
return protocolSchema; if (null == client) {
} throw new NotLoggedInErrorException();
String getLogHost() {
return logHost;
}
public String getEmail() {
return email;
}
public String getSymbol() {
return symbol;
}
private void setFullEndpointInfo(String email) {
String[] creds = email.split("\\\\");
this.email = email;
if (creds.length >= 2) {
String[] url = creds[0].split("://");
this.protocolSchema = url[0];
this.logHost = url[1];
this.email = creds[2];
} }
}
protected Client getClient() {
if (null != client) {
return client;
}
client = new Client(getProtocolSchema(), getLogHost(), symbol);
return client; return client;
} }
protected Login getLogin() { public String getSymbol() throws NotLoggedInErrorException {
if (null != login) { return getClient().getSymbol();
return login;
}
login = new Login(getClient());
return login;
} }
public SnP getStudentAndParent() throws IOException, NotLoggedInErrorException { public SnP getStudentAndParent() throws IOException, VulcanException {
if (0 == getClient().getCookies().size()) { if (null != this.snp) {
throw new NotLoggedInErrorException(); return this.snp;
} }
if (null != snp) { this.snp = new StudentAndParent(getClient(), id).storeContextCookies();
return snp;
}
snp = createSnp(getClient(), id); return this.snp;
snp.storeContextCookies();
return snp;
} }
SnP createSnp(Client client, String id) { public String getId() throws IOException, VulcanException {
if (null == id) { return getStudentAndParent().getId();
return new StudentAndParent(client);
}
return new StudentAndParent(client, id);
} }
public AttendanceStatistics getAttendanceStatistics() throws IOException, NotLoggedInErrorException { public AttendanceTable getAttendanceTable() throws IOException, VulcanException {
return new AttendanceStatistics(getStudentAndParent());
}
public AttendanceTable getAttendanceTable() throws IOException, NotLoggedInErrorException {
return new AttendanceTable(getStudentAndParent()); return new AttendanceTable(getStudentAndParent());
} }
public ExamsWeek getExamsList() throws IOException, NotLoggedInErrorException { public AttendanceStatistics getAttendanceStatistics() throws IOException, VulcanException {
return new AttendanceStatistics(getStudentAndParent());
}
public ExamsWeek getExamsList() throws IOException, VulcanException {
return new ExamsWeek(getStudentAndParent()); return new ExamsWeek(getStudentAndParent());
} }
public GradesList getGradesList() throws IOException, NotLoggedInErrorException { public GradesList getGradesList() throws IOException, VulcanException {
return new GradesList(getStudentAndParent()); return new GradesList(getStudentAndParent());
} }
public SubjectsList getSubjectsList() throws IOException, NotLoggedInErrorException { public SubjectsList getSubjectsList() throws IOException, VulcanException {
return new SubjectsList(getStudentAndParent()); return new SubjectsList(getStudentAndParent());
} }
public AchievementsList getAchievementsList() throws IOException, NotLoggedInErrorException { public AchievementsList getAchievementsList() throws IOException, VulcanException {
return new AchievementsList(getStudentAndParent()); return new AchievementsList(getStudentAndParent());
} }
public NotesList getNotesList() throws IOException, NotLoggedInErrorException { public NotesList getNotesList() throws IOException, VulcanException {
return new NotesList(getStudentAndParent()); return new NotesList(getStudentAndParent());
} }
public SchoolInfo getSchoolInfo() throws IOException, NotLoggedInErrorException { public SchoolInfo getSchoolInfo() throws IOException, VulcanException {
return new SchoolInfo(getStudentAndParent()); return new SchoolInfo(getStudentAndParent());
} }
public TeachersInfo getTeachersInfo() throws IOException, NotLoggedInErrorException { public TeachersInfo getTeachersInfo() throws IOException, VulcanException {
return new TeachersInfo(getStudentAndParent()); return new TeachersInfo(getStudentAndParent());
} }
public Timetable getTimetable() throws IOException, NotLoggedInErrorException { public Timetable getTimetable() throws IOException, VulcanException {
return new Timetable(getStudentAndParent()); return new Timetable(getStudentAndParent());
} }
public BasicInformation getBasicInformation() throws IOException, NotLoggedInErrorException { public BasicInformation getBasicInformation() throws IOException, VulcanException {
return new BasicInformation(getStudentAndParent()); return new BasicInformation(getStudentAndParent());
} }
public FamilyInformation getFamilyInformation() throws IOException, NotLoggedInErrorException { public FamilyInformation getFamilyInformation() throws IOException, VulcanException {
return new FamilyInformation(getStudentAndParent()); return new FamilyInformation(getStudentAndParent());
} }
public Messages getMessages() { public Messages getMessages() throws VulcanException {
return new Messages(getClient()); return new Messages(getClient());
} }
} }

View File

@ -0,0 +1,4 @@
package io.github.wulkanowy.api;
public abstract class VulcanException extends Exception {
}

View File

@ -0,0 +1,4 @@
package io.github.wulkanowy.api;
public class VulcanOfflineException extends VulcanException {
}

View File

@ -9,6 +9,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import io.github.wulkanowy.api.SnP; import io.github.wulkanowy.api.SnP;
import io.github.wulkanowy.api.VulcanException;
import io.github.wulkanowy.api.generic.Month; import io.github.wulkanowy.api.generic.Month;
import io.github.wulkanowy.api.generic.Subject; import io.github.wulkanowy.api.generic.Subject;
@ -22,15 +23,15 @@ public class AttendanceStatistics {
this.snp = snp; this.snp = snp;
} }
public Types getTypesTable() throws IOException { public Types getTypesTable() throws IOException, VulcanException {
return getTypesTable(""); return getTypesTable("");
} }
public Types getTypesTable(String tick) throws IOException { public Types getTypesTable(String tick) throws IOException, VulcanException {
return getTypesTable(tick, -1); return getTypesTable(tick, -1);
} }
public List<Subject> getSubjectList() throws IOException { public List<Subject> getSubjectList() throws IOException, VulcanException {
Element mainContainer = snp.getSnPPageDocument(attendancePageUrl) Element mainContainer = snp.getSnPPageDocument(attendancePageUrl)
.select(".mainContainer #idPrzedmiot").first(); .select(".mainContainer #idPrzedmiot").first();
@ -46,7 +47,7 @@ public class AttendanceStatistics {
return subjectList; return subjectList;
} }
public Types getTypesTable(String tick, Integer subjectId) throws IOException { public Types getTypesTable(String tick, Integer subjectId) throws IOException, VulcanException {
Element mainContainer = snp.getSnPPageDocument((attendancePageUrl Element mainContainer = snp.getSnPPageDocument((attendancePageUrl
+ "?data={tick}&idPrzedmiot={subject}") + "?data={tick}&idPrzedmiot={subject}")
.replace("{tick}", tick) .replace("{tick}", tick)

View File

@ -12,26 +12,28 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import io.github.wulkanowy.api.SnP; import io.github.wulkanowy.api.SnP;
import io.github.wulkanowy.api.VulcanException;
import io.github.wulkanowy.api.generic.Day; import io.github.wulkanowy.api.generic.Day;
import io.github.wulkanowy.api.generic.Lesson; import io.github.wulkanowy.api.generic.Lesson;
import io.github.wulkanowy.api.generic.Week; import io.github.wulkanowy.api.generic.Week;
public class AttendanceTable { public class AttendanceTable {
private SnP snp;
private final static String ATTENDANCE_PAGE_URL = "Frekwencja.mvc?data="; private final static String ATTENDANCE_PAGE_URL = "Frekwencja.mvc?data=";
private SnP snp;
public AttendanceTable(SnP snp) { public AttendanceTable(SnP snp) {
this.snp = snp; this.snp = snp;
} }
public Week<Day> getWeekTable() throws IOException, ParseException { public Week<Day> getWeekTable() throws IOException, ParseException, VulcanException {
return getWeekTable(""); return getWeekTable("");
} }
public Week<Day> getWeekTable(String tick) throws IOException, ParseException { public Week<Day> getWeekTable(String tick) throws IOException, ParseException, VulcanException {
Element table = snp.getSnPPageDocument(ATTENDANCE_PAGE_URL + tick) Element table = snp.getSnPPageDocument(ATTENDANCE_PAGE_URL + tick)
.select(".mainContainer .presentData").first(); .select(".mainContainer .presentData").first();
Elements headerCells = table.select("thead th"); Elements headerCells = table.select("thead th");

View File

@ -9,6 +9,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import io.github.wulkanowy.api.SnP; import io.github.wulkanowy.api.SnP;
import io.github.wulkanowy.api.VulcanException;
import io.github.wulkanowy.api.generic.Week; import io.github.wulkanowy.api.generic.Week;
public class ExamsWeek { public class ExamsWeek {
@ -21,11 +22,11 @@ public class ExamsWeek {
this.snp = snp; this.snp = snp;
} }
public Week<ExamDay> getCurrent() throws IOException { public Week<ExamDay> getCurrent() throws IOException, VulcanException {
return getWeek("", true); return getWeek("", true);
} }
public Week<ExamDay> getWeek(String tick, final boolean onlyNotEmpty) throws IOException { public Week<ExamDay> getWeek(String tick, final boolean onlyNotEmpty) throws IOException, VulcanException {
Document examsPage = snp.getSnPPageDocument(EXAMS_PAGE_URL + tick); Document examsPage = snp.getSnPPageDocument(EXAMS_PAGE_URL + tick);
Elements examsDays = examsPage.select(".mainContainer > div:not(.navigation)"); Elements examsDays = examsPage.select(".mainContainer > div:not(.navigation)");

View File

@ -16,6 +16,7 @@ import java.util.regex.Pattern;
import io.github.wulkanowy.api.Semester; import io.github.wulkanowy.api.Semester;
import io.github.wulkanowy.api.SnP; import io.github.wulkanowy.api.SnP;
import io.github.wulkanowy.api.VulcanException;
public class GradesList { public class GradesList {
@ -33,11 +34,11 @@ public class GradesList {
return GRADES_PAGE_URL; return GRADES_PAGE_URL;
} }
public List<Grade> getAll() throws IOException, ParseException { public List<Grade> getAll() throws IOException, ParseException, VulcanException {
return getAll(""); return getAll("");
} }
public List<Grade> getAll(String semester) throws IOException, ParseException { public List<Grade> getAll(String semester) throws IOException, ParseException, VulcanException {
Document gradesPage = snp.getSnPPageDocument(getGradesPageUrl() + semester); Document gradesPage = snp.getSnPPageDocument(getGradesPageUrl() + semester);
Elements gradesRows = gradesPage.select(".ocenySzczegoly-table > tbody > tr"); Elements gradesRows = gradesPage.select(".ocenySzczegoly-table > tbody > tr");
Semester currentSemester = snp.getCurrentSemester(snp.getSemesters(gradesPage)); Semester currentSemester = snp.getCurrentSemester(snp.getSemesters(gradesPage));

View File

@ -9,6 +9,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import io.github.wulkanowy.api.SnP; import io.github.wulkanowy.api.SnP;
import io.github.wulkanowy.api.VulcanException;
public class SubjectsList { public class SubjectsList {
@ -20,7 +21,7 @@ public class SubjectsList {
this.snp = snp; this.snp = snp;
} }
public List<Subject> getAll() throws IOException { public List<Subject> getAll() throws IOException, VulcanException {
Document subjectPage = snp.getSnPPageDocument(SUBJECTS_PAGE_URL); Document subjectPage = snp.getSnPPageDocument(SUBJECTS_PAGE_URL);
Elements rows = subjectPage.select(".ocenyZwykle-table > tbody > tr"); Elements rows = subjectPage.select(".ocenyZwykle-table > tbody > tr");

View File

@ -1,4 +1,6 @@
package io.github.wulkanowy.api.login; package io.github.wulkanowy.api.login;
public class AccountPermissionException extends Exception { import io.github.wulkanowy.api.VulcanException;
public class AccountPermissionException extends VulcanException {
} }

View File

@ -1,4 +1,6 @@
package io.github.wulkanowy.api.login; package io.github.wulkanowy.api.login;
public class BadCredentialsException extends Exception { import io.github.wulkanowy.api.VulcanException;
public class BadCredentialsException extends VulcanException {
} }

View File

@ -8,6 +8,7 @@ import org.jsoup.select.Elements;
import java.io.IOException; import java.io.IOException;
import io.github.wulkanowy.api.Client; import io.github.wulkanowy.api.Client;
import io.github.wulkanowy.api.VulcanException;
public class Login { public class Login {
@ -27,16 +28,13 @@ public class Login {
this.client = client; this.client = client;
} }
public String login(String email, String password, String symbol) public String login(String email, String password, String symbol) throws VulcanException, IOException {
throws BadCredentialsException, LoginErrorException,
AccountPermissionException, IOException, VulcanOfflineException {
String certificate = sendCredentials(email, password, symbol); String certificate = sendCredentials(email, password, symbol);
return sendCertificate(certificate, symbol); return sendCertificate(certificate, symbol);
} }
String sendCredentials(String email, String password, String symbol) String sendCredentials(String email, String password, String symbol) throws IOException, VulcanException {
throws IOException, BadCredentialsException {
this.symbol = symbol; this.symbol = symbol;
Document html = client.postPageByUrl(LOGIN_PAGE_URL, new String[][]{ Document html = client.postPageByUrl(LOGIN_PAGE_URL, new String[][]{
@ -51,25 +49,20 @@ public class Login {
return html.select("input[name=wresult]").attr("value"); return html.select("input[name=wresult]").attr("value");
} }
String sendCertificate(String certificate, String defaultSymbol) String sendCertificate(String certificate, String defaultSymbol) throws IOException, VulcanException {
throws IOException, LoginErrorException, AccountPermissionException, VulcanOfflineException {
this.symbol = findSymbol(defaultSymbol, certificate); this.symbol = findSymbol(defaultSymbol, certificate);
client.setSymbol(this.symbol); client.setSymbol(this.symbol);
Document html = client.postPageByUrl(LOGIN_ENDPOINT_PAGE_URL, new String[][]{ String title = client.postPageByUrl(LOGIN_ENDPOINT_PAGE_URL, new String[][]{
{"wa", "wsignin1.0"}, {"wa", "wsignin1.0"},
{"wresult", certificate} {"wresult", certificate}
}); }).select("title").text();
if (html.getElementsByTag("title").text().equals("Logowanie")) { if ("Logowanie".equals(title)) {
throw new AccountPermissionException(); throw new AccountPermissionException();
} }
if (html.getElementsByTag("title").text().equals("Przerwa techniczna")) { if (!"Uonet+".equals(title)) {
throw new VulcanOfflineException();
}
if (!html.select("title").text().equals("Uonet+")) {
throw new LoginErrorException(); throw new LoginErrorException();
} }
@ -85,7 +78,8 @@ public class Login {
} }
String findSymbolInCertificate(String certificate) { String findSymbolInCertificate(String certificate) {
Elements els = Jsoup.parse(certificate.replaceAll(":", ""), "", Parser.xmlParser()) Elements els = Jsoup
.parse(certificate.replaceAll(":", ""), "", Parser.xmlParser())
.select("[AttributeName=\"UserInstance\"] samlAttributeValue"); .select("[AttributeName=\"UserInstance\"] samlAttributeValue");
if (els.isEmpty()) { if (els.isEmpty()) {
@ -94,4 +88,4 @@ public class Login {
return els.get(1).text(); return els.get(1).text();
} }
} }

View File

@ -1,4 +1,6 @@
package io.github.wulkanowy.api.login; package io.github.wulkanowy.api.login;
import io.github.wulkanowy.api.NotLoggedInErrorException;
public class LoginErrorException extends NotLoggedInErrorException { public class LoginErrorException extends NotLoggedInErrorException {
} }

View File

@ -1,4 +0,0 @@
package io.github.wulkanowy.api.login;
public class NotLoggedInErrorException extends Exception {
}

View File

@ -1,4 +0,0 @@
package io.github.wulkanowy.api.login;
public class VulcanOfflineException extends Exception {
}

View File

@ -1,4 +1,6 @@
package io.github.wulkanowy.api.messages; package io.github.wulkanowy.api.messages;
class BadRequestException extends Exception { import io.github.wulkanowy.api.VulcanException;
class BadRequestException extends VulcanException {
} }

View File

@ -7,7 +7,8 @@ import java.io.IOException;
import java.util.List; import java.util.List;
import io.github.wulkanowy.api.Client; import io.github.wulkanowy.api.Client;
import io.github.wulkanowy.api.login.NotLoggedInErrorException; import io.github.wulkanowy.api.NotLoggedInErrorException;
import io.github.wulkanowy.api.VulcanException;
public class Messages { public class Messages {
@ -37,19 +38,19 @@ public class Messages {
this.client = client; this.client = client;
} }
public List<Message> getReceived() throws IOException, NotLoggedInErrorException, BadRequestException { public List<Message> getReceived() throws IOException, VulcanException {
return getMessages(RECEIVED_URL); return getMessages(RECEIVED_URL);
} }
public List<Message> getSent() throws IOException, NotLoggedInErrorException, BadRequestException { public List<Message> getSent() throws IOException, VulcanException {
return getMessages(SENT_URL); return getMessages(SENT_URL);
} }
public List<Message> getDeleted() throws IOException, NotLoggedInErrorException, BadRequestException { public List<Message> getDeleted() throws IOException, VulcanException {
return getMessages(DELETED_URL); return getMessages(DELETED_URL);
} }
private List<Message> getMessages(String url) throws IOException, NotLoggedInErrorException, BadRequestException { private List<Message> getMessages(String url) throws IOException, VulcanException {
String res = client.getJsonStringByUrl(url); String res = client.getJsonStringByUrl(url);
List<Message> messages; List<Message> messages;
@ -67,7 +68,7 @@ public class Messages {
return messages; return messages;
} }
public Message getMessage(int id, int folder) throws IOException, BadRequestException, NotLoggedInErrorException { public Message getMessage(int id, int folder) throws IOException, VulcanException {
String res = client.postJsonStringByUrl(MESSAGE_URL, new String[][]{ String res = client.postJsonStringByUrl(MESSAGE_URL, new String[][]{
{"idWiadomosc", String.valueOf(id)}, {"idWiadomosc", String.valueOf(id)},
{"Folder", String.valueOf(folder)} {"Folder", String.valueOf(folder)}

View File

@ -8,6 +8,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import io.github.wulkanowy.api.SnP; import io.github.wulkanowy.api.SnP;
import io.github.wulkanowy.api.VulcanException;
public class AchievementsList { public class AchievementsList {
@ -21,7 +22,7 @@ public class AchievementsList {
this.snp = snp; this.snp = snp;
} }
public List<String> getAllAchievements() throws IOException { public List<String> getAllAchievements() throws IOException, VulcanException {
Element pageFragment = snp.getSnPPageDocument(NOTES_PAGE_URL) Element pageFragment = snp.getSnPPageDocument(NOTES_PAGE_URL)
.select(".mainContainer > div").get(1); .select(".mainContainer > div").get(1);
Elements items = pageFragment.select("article"); Elements items = pageFragment.select("article");

View File

@ -8,6 +8,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import io.github.wulkanowy.api.SnP; import io.github.wulkanowy.api.SnP;
import io.github.wulkanowy.api.VulcanException;
public class NotesList { public class NotesList {
@ -21,7 +22,7 @@ public class NotesList {
this.snp = snp; this.snp = snp;
} }
public List<Note> getAllNotes() throws IOException { public List<Note> getAllNotes() throws IOException, VulcanException {
Element pageFragment = snp.getSnPPageDocument(NOTES_PAGE_URL) Element pageFragment = snp.getSnPPageDocument(NOTES_PAGE_URL)
.select(".mainContainer > div").get(0); .select(".mainContainer > div").get(0);
Elements items = pageFragment.select("article"); Elements items = pageFragment.select("article");

View File

@ -5,6 +5,7 @@ import org.jsoup.nodes.Element;
import java.io.IOException; import java.io.IOException;
import io.github.wulkanowy.api.SnP; import io.github.wulkanowy.api.SnP;
import io.github.wulkanowy.api.VulcanException;
public class SchoolInfo { public class SchoolInfo {
@ -16,7 +17,7 @@ public class SchoolInfo {
this.snp = snp; this.snp = snp;
} }
public SchoolData getSchoolData() throws IOException { public SchoolData getSchoolData() throws IOException, VulcanException {
Element e = snp.getSnPPageDocument(SCHOOL_PAGE_URL) Element e = snp.getSnPPageDocument(SCHOOL_PAGE_URL)
.select(".mainContainer > article").get(0); .select(".mainContainer > article").get(0);

View File

@ -9,6 +9,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import io.github.wulkanowy.api.SnP; import io.github.wulkanowy.api.SnP;
import io.github.wulkanowy.api.VulcanException;
public class TeachersInfo { public class TeachersInfo {
@ -20,7 +21,7 @@ public class TeachersInfo {
this.snp = snp; this.snp = snp;
} }
public TeachersData getTeachersData() throws IOException { public TeachersData getTeachersData() throws IOException, VulcanException {
Document doc = snp.getSnPPageDocument(SCHOOL_PAGE_URL); Document doc = snp.getSnPPageDocument(SCHOOL_PAGE_URL);
Elements rows = doc.select(".mainContainer > table tbody tr"); Elements rows = doc.select(".mainContainer > table tbody tr");
String description = doc.select(".mainContainer > p").first().text(); String description = doc.select(".mainContainer > p").first().text();

View File

@ -13,6 +13,7 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import io.github.wulkanowy.api.SnP; import io.github.wulkanowy.api.SnP;
import io.github.wulkanowy.api.VulcanException;
import io.github.wulkanowy.api.generic.Day; import io.github.wulkanowy.api.generic.Day;
import io.github.wulkanowy.api.generic.Lesson; import io.github.wulkanowy.api.generic.Lesson;
import io.github.wulkanowy.api.generic.Week; import io.github.wulkanowy.api.generic.Week;
@ -27,11 +28,11 @@ public class Timetable {
this.snp = snp; this.snp = snp;
} }
public Week<Day> getWeekTable() throws IOException, ParseException { public Week<Day> getWeekTable() throws IOException, ParseException, VulcanException {
return getWeekTable(""); return getWeekTable("");
} }
public Week<Day> getWeekTable(final String tick) throws IOException, ParseException { public Week<Day> getWeekTable(final String tick) throws IOException, ParseException, VulcanException {
Element table = snp.getSnPPageDocument(TIMETABLE_PAGE_URL + tick) Element table = snp.getSnPPageDocument(TIMETABLE_PAGE_URL + tick)
.select(".mainContainer .presentData").first(); .select(".mainContainer .presentData").first();

View File

@ -6,6 +6,7 @@ import org.jsoup.nodes.Element;
import java.io.IOException; import java.io.IOException;
import io.github.wulkanowy.api.SnP; import io.github.wulkanowy.api.SnP;
import io.github.wulkanowy.api.VulcanException;
public class BasicInformation { public class BasicInformation {
@ -21,7 +22,7 @@ public class BasicInformation {
this.snp = snp; this.snp = snp;
} }
public Document getStudentDataPageDocument() throws IOException { public Document getStudentDataPageDocument() throws IOException, VulcanException {
if (null == studentDataPageDocument) { if (null == studentDataPageDocument) {
studentDataPageDocument = snp.getSnPPageDocument(STUDENT_DATA_PAGE_URL); studentDataPageDocument = snp.getSnPPageDocument(STUDENT_DATA_PAGE_URL);
} }
@ -29,7 +30,7 @@ public class BasicInformation {
return studentDataPageDocument; return studentDataPageDocument;
} }
public PersonalData getPersonalData() throws IOException { public PersonalData getPersonalData() throws IOException, VulcanException {
Element e = getStudentDataPageDocument().select(CONTENT_QUERY).get(0); Element e = getStudentDataPageDocument().select(CONTENT_QUERY).get(0);
String name = snp.getRowDataChildValue(e, 1); String name = snp.getRowDataChildValue(e, 1);
@ -48,7 +49,7 @@ public class BasicInformation {
.setParentsNames(snp.getRowDataChildValue(e, 7)); .setParentsNames(snp.getRowDataChildValue(e, 7));
} }
public AddressData getAddressData() throws IOException { public AddressData getAddressData() throws IOException, VulcanException {
Element e = getStudentDataPageDocument().select(CONTENT_QUERY).get(1); Element e = getStudentDataPageDocument().select(CONTENT_QUERY).get(1);
return new AddressData() return new AddressData()
@ -58,7 +59,7 @@ public class BasicInformation {
} }
public ContactDetails getContactDetails() throws IOException { public ContactDetails getContactDetails() throws IOException, VulcanException {
Element e = getStudentDataPageDocument().select(CONTENT_QUERY).get(2); Element e = getStudentDataPageDocument().select(CONTENT_QUERY).get(2);
return new ContactDetails() return new ContactDetails()

View File

@ -8,6 +8,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import io.github.wulkanowy.api.SnP; import io.github.wulkanowy.api.SnP;
import io.github.wulkanowy.api.VulcanException;
public class FamilyInformation { public class FamilyInformation {
@ -19,7 +20,7 @@ public class FamilyInformation {
this.snp = snp; this.snp = snp;
} }
public List<FamilyMember> getFamilyMembers() throws IOException { public List<FamilyMember> getFamilyMembers() throws IOException, VulcanException {
Elements membersElements = snp.getSnPPageDocument(STUDENT_DATA_PAGE_URL) Elements membersElements = snp.getSnPPageDocument(STUDENT_DATA_PAGE_URL)
.select(".mainContainer > article:nth-of-type(n+4)"); .select(".mainContainer > article:nth-of-type(n+4)");

View File

@ -0,0 +1,80 @@
package io.github.wulkanowy.api;
import org.hamcrest.CoreMatchers;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.junit.Assert;
import org.junit.Test;
import io.github.wulkanowy.api.login.Login;
public class ClientTest {
private String getFixtureAsString(String fixtureFileName) {
return FixtureHelper.getAsString(getClass().getResourceAsStream(fixtureFileName));
}
@Test
public void setFullEndpointInfoTest() throws Exception {
Client client = new Client("http://fakelog.net\\\\admin", "pass", "Default");
Assert.assertEquals("fakelog.net", client.getHost());
Assert.assertEquals("Default", client.getSymbol());
}
@Test
public void checkForNoErrorsTest() throws Exception {
Client client = new Client("", "", "");
Document doc = Jsoup.parse(getFixtureAsString("login/Logowanie-success.html"));
Assert.assertEquals(doc, client.checkForErrors(doc));
}
@Test(expected = VulcanOfflineException.class)
public void checkForErrorsOffline() throws Exception {
Client client = new Client("", "", "");
Document doc = Jsoup.parse(getFixtureAsString("login/PrzerwaTechniczna.html"));
client.checkForErrors(doc);
}
@Test(expected = NotLoggedInErrorException.class)
public void checkForErrors() throws Exception {
Client client = new Client("", "", "");
Document doc = Jsoup.parse(getFixtureAsString("login/Logowanie-notLoggedIn.html"));
client.checkForErrors(doc);
}
@Test
public void getClientTest() throws Exception {
Client client = new Client("", "", "");
Assert.assertThat(client.getLogin(), CoreMatchers.instanceOf(Login.class));
}
@Test
public void getClientTwiceTest() throws Exception {
Client client = new Client("", "", "");
Assert.assertEquals(client.getLogin(), client.getLogin());
}
@Test
public void getFilledUrlTest() throws Exception {
Client client = new Client("http://fakelog.cf\\\\admin", "", "symbol123");
Assert.assertEquals("http://uonetplus.fakelog.cf/symbol123/LoginEndpoint.aspx",
client.getFilledUrl("{schema}://uonetplus.{host}/{symbol}/LoginEndpoint.aspx"));
}
@Test
public void getSymbolTest() throws Exception {
Client client = new Client("", "", "symbol4321");
Assert.assertEquals("symbol4321", client.getSymbol());
}
}

View File

@ -10,8 +10,6 @@ import org.mockito.Mockito;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import io.github.wulkanowy.api.login.NotLoggedInErrorException;
public class StudentAndParentTest { public class StudentAndParentTest {
private Client client; private Client client;
@ -45,7 +43,7 @@ public class StudentAndParentTest {
Mockito.when(client.getHost()).thenReturn("vulcan.net.pl"); Mockito.when(client.getHost()).thenReturn("vulcan.net.pl");
Mockito.when(client.getPageByUrl(Mockito.anyString())).thenReturn(startPageDocument); Mockito.when(client.getPageByUrl(Mockito.anyString())).thenReturn(startPageDocument);
StudentAndParent snp = new StudentAndParent(client); StudentAndParent snp = new StudentAndParent(client, null);
Assert.assertEquals("https://uonetplus-opiekun.vulcan.net.pl/symbol/534213/Start/Index/", Assert.assertEquals("https://uonetplus-opiekun.vulcan.net.pl/symbol/534213/Start/Index/",
snp.getSnpHomePageUrl()); snp.getSnpHomePageUrl());
@ -58,7 +56,7 @@ public class StudentAndParentTest {
); );
Mockito.when(client.getPageByUrl(Mockito.anyString())).thenReturn(wrongPageDocument); Mockito.when(client.getPageByUrl(Mockito.anyString())).thenReturn(wrongPageDocument);
StudentAndParent snp = new StudentAndParent(client); StudentAndParent snp = new StudentAndParent(client, null);
snp.getSnpHomePageUrl(); snp.getSnpHomePageUrl();
} }

View File

@ -1,86 +1,31 @@
package io.github.wulkanowy.api; package io.github.wulkanowy.api;
import org.hamcrest.CoreMatchers;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.Mockito;
import java.util.HashMap;
import java.util.Map;
import io.github.wulkanowy.api.login.Login;
import io.github.wulkanowy.api.login.NotLoggedInErrorException;
public class VulcanTest { public class VulcanTest {
private Vulcan vulcan; @Test(expected = NotLoggedInErrorException.class)
public void getClientWithoutLoginTest() throws Exception {
Vulcan vulcan = new Vulcan();
@Before vulcan.getClient();
public void setUp() throws Exception {
vulcan = new Vulcan();
vulcan.setClient(Mockito.mock(Client.class));
vulcan.setLogin(Mockito.mock(Login.class));
} }
@Test @Test
public void setFullEndpointInfoTest() throws Exception { public void getClientTest() throws Exception {
vulcan.login("http://fakelog.net\\\\admin", "pass", "Default", "123"); Vulcan vulcan = new Vulcan();
vulcan.setCredentials("email", "password", "symbol", null);
Assert.assertEquals("http", vulcan.getProtocolSchema()); Assert.assertThat(vulcan.getClient(), CoreMatchers.instanceOf(Client.class));
Assert.assertEquals("fakelog.net", vulcan.getLogHost());
Assert.assertEquals("admin", vulcan.getEmail());
} }
@Test @Test
public void getClientTwiceTest() throws Exception { public void getClientTwiceTest() throws Exception {
Vulcan vulcan = new Vulcan(); Vulcan vulcan = new Vulcan();
Assert.assertTrue(vulcan.getClient().equals(vulcan.getClient())); vulcan.setCredentials("email", "password", "symbol", null);
}
@Test Assert.assertEquals(vulcan.getClient(), vulcan.getClient());
public void getLoginTwiceTest() throws Exception {
Vulcan vulcan = new Vulcan();
Assert.assertTrue(vulcan.getLogin().equals(vulcan.getLogin()));
}
@Test(expected = NotLoggedInErrorException.class)
public void getStudentAndParentNotLoggedInTest() throws Exception {
vulcan.getStudentAndParent();
}
@Test
public void getStudentAndParentTwiceTest() throws Exception {
Client client = Mockito.mock(Client.class);
Map<String, String> cookies = new HashMap<>();
cookies.put("test", "test");
Mockito.when(client.getCookies()).thenReturn(cookies);
SnP snp = Mockito.mock(StudentAndParent.class);
Mockito.doNothing().when(snp).storeContextCookies();
Vulcan vulcan = Mockito.mock(Vulcan.class);
Mockito.when(vulcan.getClient()).thenReturn(client);
Mockito.when(vulcan.getStudentAndParent()).thenCallRealMethod();
Mockito.when(vulcan.createSnp(Mockito.any(Client.class), Mockito.any())).thenReturn(snp);
vulcan.getStudentAndParent();
vulcan.getStudentAndParent();
}
@Test
public void createSnPTest() throws Exception {
vulcan.login("wulkanowy@wulkanowy.io", "wulkanowy123", "wulkan");
SnP snp1 = vulcan.createSnp(Mockito.mock(Client.class), null);
Assert.assertEquals(null, snp1.getId());
SnP snp2 = vulcan.createSnp(Mockito.mock(Client.class), "wulkan");
Assert.assertEquals("wulkan", snp2.getId());
}
@Test(expected = NotLoggedInErrorException.class)
public void getAttendanceExceptionText() throws Exception {
vulcan.getAttendanceTable();
} }
} }

View File

@ -1,6 +1,5 @@
package io.github.wulkanowy.api.login; package io.github.wulkanowy.api.login;
import org.jsoup.Jsoup; import org.jsoup.Jsoup;
import org.jsoup.nodes.Document; import org.jsoup.nodes.Document;
import org.junit.Assert; import org.junit.Assert;
@ -79,13 +78,6 @@ public class LoginTest {
login.sendCertificate(getFixtureAsString("cert.xml"), "demo123"); login.sendCertificate(getFixtureAsString("cert.xml"), "demo123");
} }
@Test(expected = VulcanOfflineException.class)
public void sendCertificateVulcanOfflineTest() throws Exception {
Login login = new Login(getClient("PrzerwaTechniczna.html"));
login.sendCertificate(getFixtureAsString("cert.xml"), "demo123");
}
@Test @Test
public void findSymbolInCertificateTest() throws Exception { public void findSymbolInCertificateTest() throws Exception {
Login login = new Login(getClient("Logowanie-certyfikat.html")); Login login = new Login(getClient("Logowanie-certyfikat.html"));

View File

@ -8,7 +8,7 @@ import java.util.List;
import io.github.wulkanowy.api.Client; import io.github.wulkanowy.api.Client;
import io.github.wulkanowy.api.FixtureHelper; import io.github.wulkanowy.api.FixtureHelper;
import io.github.wulkanowy.api.login.NotLoggedInErrorException; import io.github.wulkanowy.api.NotLoggedInErrorException;
public class MessagesTest { public class MessagesTest {

View File

@ -0,0 +1,22 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dziennik UONET+</title>
</head>
<body>
<div id="MainPage_InfoPage">
<div class="startScreen">
<div class="topBar">
<div class="loginBox">
<div>
<a href="/LoginEndpoint.aspx" class="loginButton"></a>
<a href="/LoginEndpoint.aspx" class="loginButton">Zaloguj się</a>
</div>
</div>
</div>
<div class="bottomBar"><span>Uonet+ wersja 17.09.0007.26300</span></div>
</div>
</div>
</body>
</html>

View File

@ -7,10 +7,7 @@ import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import io.github.wulkanowy.api.login.AccountPermissionException; import io.github.wulkanowy.api.VulcanException;
import io.github.wulkanowy.api.login.BadCredentialsException;
import io.github.wulkanowy.api.login.NotLoggedInErrorException;
import io.github.wulkanowy.api.login.VulcanOfflineException;
import io.github.wulkanowy.data.db.dao.entities.Account; import io.github.wulkanowy.data.db.dao.entities.Account;
import io.github.wulkanowy.data.db.dao.entities.AttendanceLesson; import io.github.wulkanowy.data.db.dao.entities.AttendanceLesson;
import io.github.wulkanowy.data.db.dao.entities.DaoSession; import io.github.wulkanowy.data.db.dao.entities.DaoSession;
@ -21,8 +18,8 @@ import io.github.wulkanowy.data.db.dao.entities.WeekDao;
import io.github.wulkanowy.data.db.resources.ResourcesContract; import io.github.wulkanowy.data.db.resources.ResourcesContract;
import io.github.wulkanowy.data.db.shared.SharedPrefContract; import io.github.wulkanowy.data.db.shared.SharedPrefContract;
import io.github.wulkanowy.data.sync.SyncContract; import io.github.wulkanowy.data.sync.SyncContract;
import io.github.wulkanowy.data.sync.account.AccountSyncContract;
import io.github.wulkanowy.data.sync.attendance.AttendanceSyncContract; import io.github.wulkanowy.data.sync.attendance.AttendanceSyncContract;
import io.github.wulkanowy.data.sync.login.LoginSyncContract;
import io.github.wulkanowy.data.sync.timetable.TimetableSyncContract; import io.github.wulkanowy.data.sync.timetable.TimetableSyncContract;
import io.github.wulkanowy.di.annotations.SyncGrades; import io.github.wulkanowy.di.annotations.SyncGrades;
import io.github.wulkanowy.di.annotations.SyncSubjects; import io.github.wulkanowy.di.annotations.SyncSubjects;
@ -37,7 +34,7 @@ public class Repository implements RepositoryContract {
private final DaoSession daoSession; private final DaoSession daoSession;
private final LoginSyncContract loginSync; private final AccountSyncContract accountSync;
private final AttendanceSyncContract attendanceSync; private final AttendanceSyncContract attendanceSync;
@ -51,7 +48,7 @@ public class Repository implements RepositoryContract {
Repository(SharedPrefContract sharedPref, Repository(SharedPrefContract sharedPref,
ResourcesContract resources, ResourcesContract resources,
DaoSession daoSession, DaoSession daoSession,
LoginSyncContract loginSync, AccountSyncContract accountSync,
AttendanceSyncContract attendanceSync, AttendanceSyncContract attendanceSync,
TimetableSyncContract timetableSync, TimetableSyncContract timetableSync,
@SyncGrades SyncContract gradeSync, @SyncGrades SyncContract gradeSync,
@ -59,7 +56,7 @@ public class Repository implements RepositoryContract {
this.sharedPref = sharedPref; this.sharedPref = sharedPref;
this.resources = resources; this.resources = resources;
this.daoSession = daoSession; this.daoSession = daoSession;
this.loginSync = loginSync; this.accountSync = accountSync;
this.attendanceSync = attendanceSync; this.attendanceSync = attendanceSync;
this.timetableSync = timetableSync; this.timetableSync = timetableSync;
this.gradeSync = gradeSync; this.gradeSync = gradeSync;
@ -92,50 +89,48 @@ public class Repository implements RepositoryContract {
} }
@Override @Override
public void loginUser(String email, String password, String symbol) public void registerUser(String email, String password, String symbol) throws VulcanException,
throws NotLoggedInErrorException, AccountPermissionException, IOException, IOException, CryptoException {
CryptoException, VulcanOfflineException, BadCredentialsException { accountSync.registerUser(email, password, symbol);
loginSync.loginUser(email, password, symbol);
} }
@Override @Override
public void loginCurrentUser() throws NotLoggedInErrorException, AccountPermissionException, public void initLastUser() throws VulcanException, IOException, CryptoException {
IOException, CryptoException, VulcanOfflineException, BadCredentialsException { accountSync.initLastUser();
loginSync.loginCurrentUser();
} }
@Override @Override
public void syncGrades() throws NotLoggedInErrorException, IOException, ParseException { public void syncGrades() throws VulcanException, IOException, ParseException {
gradeSync.sync(); gradeSync.sync();
} }
@Override @Override
public void syncSubjects() throws NotLoggedInErrorException, IOException, ParseException { public void syncSubjects() throws VulcanException, IOException, ParseException {
subjectSync.sync(); subjectSync.sync();
} }
@Override @Override
public void syncAttendance() throws NotLoggedInErrorException, ParseException, IOException { public void syncAttendance() throws ParseException, IOException, VulcanException {
attendanceSync.syncAttendance(); attendanceSync.syncAttendance();
} }
@Override @Override
public void syncAttendance(String date) throws NotLoggedInErrorException, ParseException, IOException { public void syncAttendance(String date) throws ParseException, IOException, VulcanException {
attendanceSync.syncAttendance(date); attendanceSync.syncAttendance(date);
} }
@Override @Override
public void syncTimetable() throws NotLoggedInErrorException, IOException, ParseException { public void syncTimetable() throws VulcanException, IOException, ParseException {
timetableSync.syncTimetable(); timetableSync.syncTimetable();
} }
@Override @Override
public void syncTimetable(String date) throws NotLoggedInErrorException, IOException, ParseException { public void syncTimetable(String date) throws VulcanException, IOException, ParseException {
timetableSync.syncTimetable(date); timetableSync.syncTimetable(date);
} }
@Override @Override
public void syncAll() throws NotLoggedInErrorException, IOException, ParseException { public void syncAll() throws VulcanException, IOException, ParseException {
syncSubjects(); syncSubjects();
syncGrades(); syncGrades();
syncAttendance(); syncAttendance();

View File

@ -6,26 +6,26 @@ import java.util.List;
import javax.inject.Singleton; import javax.inject.Singleton;
import io.github.wulkanowy.api.login.NotLoggedInErrorException; import io.github.wulkanowy.api.VulcanException;
import io.github.wulkanowy.data.db.dao.entities.Account; import io.github.wulkanowy.data.db.dao.entities.Account;
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.Week; import io.github.wulkanowy.data.db.dao.entities.Week;
import io.github.wulkanowy.data.db.resources.ResourcesContract; import io.github.wulkanowy.data.db.resources.ResourcesContract;
import io.github.wulkanowy.data.sync.account.AccountSyncContract;
import io.github.wulkanowy.data.sync.attendance.AttendanceSyncContract; import io.github.wulkanowy.data.sync.attendance.AttendanceSyncContract;
import io.github.wulkanowy.data.sync.login.LoginSyncContract;
import io.github.wulkanowy.data.sync.timetable.TimetableSyncContract; import io.github.wulkanowy.data.sync.timetable.TimetableSyncContract;
@Singleton @Singleton
public interface RepositoryContract extends ResourcesContract, LoginSyncContract, public interface RepositoryContract extends ResourcesContract, AccountSyncContract,
AttendanceSyncContract, TimetableSyncContract { AttendanceSyncContract, TimetableSyncContract {
long getCurrentUserId(); long getCurrentUserId();
void syncGrades() throws NotLoggedInErrorException, IOException, ParseException; void syncGrades() throws VulcanException, IOException, ParseException;
void syncSubjects() throws NotLoggedInErrorException, IOException, ParseException; void syncSubjects() throws VulcanException, IOException, ParseException;
void syncAll() throws NotLoggedInErrorException, IOException, ParseException; void syncAll() throws VulcanException, IOException, ParseException;
Account getCurrentUser(); Account getCurrentUser();

View File

@ -11,8 +11,8 @@ import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import io.github.wulkanowy.R; import io.github.wulkanowy.R;
import io.github.wulkanowy.api.login.NotLoggedInErrorException; import io.github.wulkanowy.api.NotLoggedInErrorException;
import io.github.wulkanowy.api.login.VulcanOfflineException; import io.github.wulkanowy.api.VulcanOfflineException;
import io.github.wulkanowy.data.db.dao.entities.AttendanceLesson; import io.github.wulkanowy.data.db.dao.entities.AttendanceLesson;
import io.github.wulkanowy.di.annotations.ApplicationContext; import io.github.wulkanowy.di.annotations.ApplicationContext;
import io.github.wulkanowy.utils.AppConstant; import io.github.wulkanowy.utils.AppConstant;

View File

@ -3,9 +3,9 @@ package io.github.wulkanowy.data.sync;
import java.io.IOException; import java.io.IOException;
import java.text.ParseException; import java.text.ParseException;
import io.github.wulkanowy.api.login.NotLoggedInErrorException; import io.github.wulkanowy.api.VulcanException;
public interface SyncContract { public interface SyncContract {
void sync() throws NotLoggedInErrorException, IOException, ParseException; void sync() throws VulcanException, IOException, ParseException;
} }

View File

@ -1,4 +1,4 @@
package io.github.wulkanowy.data.sync.login; package io.github.wulkanowy.data.sync.account;
import android.content.Context; import android.content.Context;
@ -8,10 +8,7 @@ import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import io.github.wulkanowy.api.Vulcan; import io.github.wulkanowy.api.Vulcan;
import io.github.wulkanowy.api.login.AccountPermissionException; import io.github.wulkanowy.api.VulcanException;
import io.github.wulkanowy.api.login.BadCredentialsException;
import io.github.wulkanowy.api.login.NotLoggedInErrorException;
import io.github.wulkanowy.api.login.VulcanOfflineException;
import io.github.wulkanowy.data.db.dao.entities.Account; import io.github.wulkanowy.data.db.dao.entities.Account;
import io.github.wulkanowy.data.db.dao.entities.DaoSession; import io.github.wulkanowy.data.db.dao.entities.DaoSession;
import io.github.wulkanowy.data.db.shared.SharedPrefContract; import io.github.wulkanowy.data.db.shared.SharedPrefContract;
@ -21,7 +18,7 @@ import io.github.wulkanowy.utils.security.CryptoException;
import io.github.wulkanowy.utils.security.Scrambler; import io.github.wulkanowy.utils.security.Scrambler;
@Singleton @Singleton
public class LoginSync implements LoginSyncContract { public class AccountSync implements AccountSyncContract {
private final DaoSession daoSession; private final DaoSession daoSession;
@ -32,8 +29,8 @@ public class LoginSync implements LoginSyncContract {
private final Context context; private final Context context;
@Inject @Inject
LoginSync(DaoSession daoSession, SharedPrefContract sharedPref, AccountSync(DaoSession daoSession, SharedPrefContract sharedPref,
Vulcan vulcan, @ApplicationContext Context context) { Vulcan vulcan, @ApplicationContext Context context) {
this.daoSession = daoSession; this.daoSession = daoSession;
this.sharedPref = sharedPref; this.sharedPref = sharedPref;
this.vulcan = vulcan; this.vulcan = vulcan;
@ -41,13 +38,12 @@ public class LoginSync implements LoginSyncContract {
} }
@Override @Override
public void loginUser(String email, String password, String symbol) public void registerUser(String email, String password, String symbol)
throws NotLoggedInErrorException, AccountPermissionException, IOException, throws VulcanException, IOException, CryptoException {
CryptoException, VulcanOfflineException, BadCredentialsException {
LogUtils.debug("Login new user email=" + email); LogUtils.debug("Register new user email=" + email);
vulcan.login(email, password, symbol); vulcan.setCredentials(email, password, symbol, null);
Account account = new Account() Account account = new Account()
.setName(vulcan.getBasicInformation().getPersonalData().getFirstAndLastName()) .setName(vulcan.getBasicInformation().getPersonalData().getFirstAndLastName())
@ -56,24 +52,25 @@ public class LoginSync implements LoginSyncContract {
.setSymbol(vulcan.getSymbol()) .setSymbol(vulcan.getSymbol())
.setSnpId(vulcan.getStudentAndParent().getId()); .setSnpId(vulcan.getStudentAndParent().getId());
sharedPref.setCurrentUserId(daoSession.getAccountDao().insert(account)); daoSession.getAccountDao().insert(account);
sharedPref.setCurrentUserId(account.getId());
} }
@Override @Override
public void loginCurrentUser() throws NotLoggedInErrorException, AccountPermissionException, public void initLastUser() throws VulcanException, IOException, CryptoException {
IOException, CryptoException, VulcanOfflineException, BadCredentialsException {
long userId = sharedPref.getCurrentUserId(); long userId = sharedPref.getCurrentUserId();
if (userId == 0) { if (userId == 0) {
throw new IOException("Can't find logged user"); throw new IOException("Can't find saved user");
} }
LogUtils.debug("Login current user id=" + userId); LogUtils.debug("Initialization current user id=" + userId);
Account account = daoSession.getAccountDao().load(userId); Account account = daoSession.getAccountDao().load(userId);
vulcan.login(account.getEmail(), vulcan.setCredentials(account.getEmail(),
Scrambler.decrypt(account.getEmail(), account.getPassword()), Scrambler.decrypt(account.getEmail(), account.getPassword()),
account.getSymbol(), account.getSymbol(),
account.getSnpId()); account.getSnpId());

View File

@ -0,0 +1,16 @@
package io.github.wulkanowy.data.sync.account;
import java.io.IOException;
import io.github.wulkanowy.api.VulcanException;
import io.github.wulkanowy.utils.security.CryptoException;
public interface AccountSyncContract {
void registerUser(String email, String password, String symbol)
throws VulcanException, IOException,
CryptoException;
void initLastUser() throws VulcanException, IOException,
CryptoException;
}

View File

@ -9,8 +9,8 @@ import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import io.github.wulkanowy.api.Vulcan; import io.github.wulkanowy.api.Vulcan;
import io.github.wulkanowy.api.VulcanException;
import io.github.wulkanowy.api.generic.Lesson; import io.github.wulkanowy.api.generic.Lesson;
import io.github.wulkanowy.api.login.NotLoggedInErrorException;
import io.github.wulkanowy.data.db.dao.entities.AttendanceLesson; import io.github.wulkanowy.data.db.dao.entities.AttendanceLesson;
import io.github.wulkanowy.data.db.dao.entities.AttendanceLessonDao; import io.github.wulkanowy.data.db.dao.entities.AttendanceLessonDao;
import io.github.wulkanowy.data.db.dao.entities.DaoSession; import io.github.wulkanowy.data.db.dao.entities.DaoSession;
@ -42,12 +42,12 @@ public class AttendanceSync implements AttendanceSyncContract {
} }
@Override @Override
public void syncAttendance() throws IOException, NotLoggedInErrorException, ParseException { public void syncAttendance() throws IOException, ParseException, VulcanException {
syncAttendance(null); syncAttendance(null);
} }
@Override @Override
public void syncAttendance(String date) throws IOException, NotLoggedInErrorException, ParseException { public void syncAttendance(String date) throws IOException, ParseException, VulcanException {
this.userId = sharedPref.getCurrentUserId(); this.userId = sharedPref.getCurrentUserId();
io.github.wulkanowy.api.generic.Week<io.github.wulkanowy.api.generic.Day> weekApi = getWeekFromApi(getNormalizedDate(date)); io.github.wulkanowy.api.generic.Week<io.github.wulkanowy.api.generic.Day> weekApi = getWeekFromApi(getNormalizedDate(date));
@ -59,7 +59,7 @@ public class AttendanceSync implements AttendanceSyncContract {
daoSession.getAttendanceLessonDao().saveInTx(lessonList); daoSession.getAttendanceLessonDao().saveInTx(lessonList);
LogUtils.debug("Synchronization lessons (amount = " + lessonList.size() + ")"); LogUtils.debug("Synchronization attendance lessons (amount = " + lessonList.size() + ")");
} }
private String getNormalizedDate(String date) throws ParseException { private String getNormalizedDate(String date) throws ParseException {
@ -67,7 +67,7 @@ public class AttendanceSync implements AttendanceSyncContract {
} }
private io.github.wulkanowy.api.generic.Week<io.github.wulkanowy.api.generic.Day> getWeekFromApi(String date) private io.github.wulkanowy.api.generic.Week<io.github.wulkanowy.api.generic.Day> getWeekFromApi(String date)
throws IOException, NotLoggedInErrorException, ParseException { throws IOException, ParseException, VulcanException {
return vulcan.getAttendanceTable().getWeekTable(date); return vulcan.getAttendanceTable().getWeekTable(date);
} }

View File

@ -3,11 +3,11 @@ package io.github.wulkanowy.data.sync.attendance;
import java.io.IOException; import java.io.IOException;
import java.text.ParseException; import java.text.ParseException;
import io.github.wulkanowy.api.login.NotLoggedInErrorException; import io.github.wulkanowy.api.VulcanException;
public interface AttendanceSyncContract { public interface AttendanceSyncContract {
void syncAttendance(String date) throws NotLoggedInErrorException, IOException, ParseException; void syncAttendance(String date) throws IOException, ParseException, VulcanException;
void syncAttendance() throws NotLoggedInErrorException, IOException, ParseException; void syncAttendance() throws IOException, ParseException, VulcanException;
} }

View File

@ -9,7 +9,7 @@ import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import io.github.wulkanowy.api.Vulcan; import io.github.wulkanowy.api.Vulcan;
import io.github.wulkanowy.api.login.NotLoggedInErrorException; import io.github.wulkanowy.api.VulcanException;
import io.github.wulkanowy.data.db.dao.entities.Account; import io.github.wulkanowy.data.db.dao.entities.Account;
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.Grade; import io.github.wulkanowy.data.db.dao.entities.Grade;
@ -29,6 +29,8 @@ public class GradeSync implements SyncContract {
private final SharedPrefContract sharedPref; private final SharedPrefContract sharedPref;
private Long userId;
@Inject @Inject
GradeSync(DaoSession daoSession, SharedPrefContract sharedPref, Vulcan vulcan) { GradeSync(DaoSession daoSession, SharedPrefContract sharedPref, Vulcan vulcan) {
this.daoSession = daoSession; this.daoSession = daoSession;
@ -37,36 +39,53 @@ public class GradeSync implements SyncContract {
} }
@Override @Override
public void sync() throws IOException, NotLoggedInErrorException, ParseException { public void sync() throws IOException, VulcanException, ParseException {
long userId = sharedPref.getCurrentUserId(); userId = sharedPref.getCurrentUserId();
Account account = daoSession.getAccountDao().load(userId); Account account = daoSession.getAccountDao().load(userId);
account.resetGradeList(); resetAccountRelations(account);
account.resetSubjectList();
List<Grade> gradesFromNet = DataObjectConverter List<Grade> lastList = getUpdatedList(getComparedList(account));
.gradesToGradeEntities(vulcan.getGradesList().getAll());
List<Grade> gradesFromDb = account.getGradeList();
List<Grade> updatedGrades = EntitiesCompare.compareGradeList(gradesFromNet, gradesFromDb);
daoSession.getGradeDao().deleteInTx(gradesFromDb);
List<Grade> lastList = new ArrayList<>();
for (Grade grade : updatedGrades) {
grade.setUserId(userId);
grade.setSubjectId(daoSession.getSubjectDao().queryBuilder()
.where(SubjectDao.Properties.Name.eq(grade.getSubject()),
SubjectDao.Properties.UserId.eq(userId))
.build()
.uniqueOrThrow().getId());
lastList.add(grade);
}
daoSession.getGradeDao().deleteInTx(account.getGradeList());
daoSession.getGradeDao().insertInTx(lastList); daoSession.getGradeDao().insertInTx(lastList);
LogUtils.debug("Synchronization grades (amount = " + lastList.size() + ")"); LogUtils.debug("Synchronization grades (amount = " + lastList.size() + ")");
} }
private void resetAccountRelations(Account account) {
account.resetSubjectList();
account.resetGradeList();
}
private List<Grade> getUpdatedList(List<Grade> comparedList) {
List<Grade> updatedList = new ArrayList<>();
for (Grade grade : comparedList) {
grade.setUserId(userId);
grade.setSubjectId(getSubjectId(grade.getSubject()));
updatedList.add(grade);
}
return updatedList;
}
private List<Grade> getComparedList(Account account) throws IOException, VulcanException,
ParseException {
List<Grade> gradesFromNet = DataObjectConverter
.gradesToGradeEntities(vulcan.getGradesList().getAll());
List<Grade> gradesFromDb = account.getGradeList();
return EntitiesCompare.compareGradeList(gradesFromNet, gradesFromDb);
}
private Long getSubjectId(String subjectName) {
return daoSession.getSubjectDao().queryBuilder()
.where(SubjectDao.Properties.Name.eq(subjectName),
SubjectDao.Properties.UserId.eq(userId))
.build()
.uniqueOrThrow()
.getId();
}
} }

View File

@ -1,19 +0,0 @@
package io.github.wulkanowy.data.sync.login;
import java.io.IOException;
import io.github.wulkanowy.api.login.AccountPermissionException;
import io.github.wulkanowy.api.login.BadCredentialsException;
import io.github.wulkanowy.api.login.NotLoggedInErrorException;
import io.github.wulkanowy.api.login.VulcanOfflineException;
import io.github.wulkanowy.utils.security.CryptoException;
public interface LoginSyncContract {
void loginUser(String email, String password, String symbol)
throws NotLoggedInErrorException, AccountPermissionException, IOException,
CryptoException, VulcanOfflineException, BadCredentialsException;
void loginCurrentUser() throws NotLoggedInErrorException, AccountPermissionException, IOException,
CryptoException, VulcanOfflineException, BadCredentialsException;
}

View File

@ -9,10 +9,10 @@ import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import io.github.wulkanowy.api.Vulcan; import io.github.wulkanowy.api.Vulcan;
import io.github.wulkanowy.api.login.NotLoggedInErrorException; import io.github.wulkanowy.api.VulcanException;
import io.github.wulkanowy.data.db.dao.entities.Account;
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.Subject; import io.github.wulkanowy.data.db.dao.entities.Subject;
import io.github.wulkanowy.data.db.dao.entities.SubjectDao;
import io.github.wulkanowy.data.db.shared.SharedPrefContract; import io.github.wulkanowy.data.db.shared.SharedPrefContract;
import io.github.wulkanowy.data.sync.SyncContract; import io.github.wulkanowy.data.sync.SyncContract;
import io.github.wulkanowy.utils.DataObjectConverter; import io.github.wulkanowy.utils.DataObjectConverter;
@ -21,41 +21,51 @@ import io.github.wulkanowy.utils.LogUtils;
@Singleton @Singleton
public class SubjectSync implements SyncContract { public class SubjectSync implements SyncContract {
private final SubjectDao subjectDao; private final DaoSession daoSession;
private final Vulcan vulcan; private final Vulcan vulcan;
private final SharedPrefContract sharedPref; private final SharedPrefContract sharedPref;
private Long userId;
@Inject @Inject
SubjectSync(DaoSession daoSession, SharedPrefContract sharedPref, Vulcan vulcan) { SubjectSync(DaoSession daoSession, SharedPrefContract sharedPref, Vulcan vulcan) {
this.subjectDao = daoSession.getSubjectDao(); this.daoSession = daoSession;
this.sharedPref = sharedPref; this.sharedPref = sharedPref;
this.vulcan = vulcan; this.vulcan = vulcan;
} }
@Override @Override
public void sync() throws NotLoggedInErrorException, IOException, ParseException { public void sync() throws VulcanException, IOException, ParseException {
long userId = sharedPref.getCurrentUserId(); userId = sharedPref.getCurrentUserId();
List<Subject> subjectsFromNet = DataObjectConverter List<Subject> lastList = getUpdatedList(getSubjectsFromNet());
.subjectsToSubjectEntities(vulcan.getSubjectsList().getAll());
subjectDao.deleteInTx(subjectDao.queryBuilder() daoSession.getSubjectDao().deleteInTx(getSubjectsFromDb());
.where(SubjectDao.Properties.UserId.eq(userId)) daoSession.getSubjectDao().insertInTx(lastList);
.build()
.list());
List<Subject> lastList = new ArrayList<>();
for (Subject subject : subjectsFromNet) {
subject.setUserId(userId);
lastList.add(subject);
}
subjectDao.insertInTx(lastList);
LogUtils.debug("Synchronization subjects (amount = " + lastList.size() + ")"); LogUtils.debug("Synchronization subjects (amount = " + lastList.size() + ")");
} }
private List<Subject> getSubjectsFromNet() throws VulcanException, IOException {
return DataObjectConverter.subjectsToSubjectEntities(vulcan.getSubjectsList().getAll());
}
private List<Subject> getSubjectsFromDb() {
Account account = daoSession.getAccountDao().load(userId);
account.resetSubjectList();
return account.getSubjectList();
}
private List<Subject> getUpdatedList(List<Subject> subjectsFromNet) {
List<Subject> updatedList = new ArrayList<>();
for (Subject subject : subjectsFromNet) {
subject.setUserId(userId);
updatedList.add(subject);
}
return updatedList;
}
} }

View File

@ -9,8 +9,8 @@ import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import io.github.wulkanowy.api.Vulcan; import io.github.wulkanowy.api.Vulcan;
import io.github.wulkanowy.api.VulcanException;
import io.github.wulkanowy.api.generic.Lesson; import io.github.wulkanowy.api.generic.Lesson;
import io.github.wulkanowy.api.login.NotLoggedInErrorException;
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.Day; import io.github.wulkanowy.data.db.dao.entities.Day;
import io.github.wulkanowy.data.db.dao.entities.DayDao; import io.github.wulkanowy.data.db.dao.entities.DayDao;
@ -42,12 +42,12 @@ public class TimetableSync implements TimetableSyncContract {
} }
@Override @Override
public void syncTimetable() throws NotLoggedInErrorException, IOException, ParseException { public void syncTimetable() throws IOException, ParseException, VulcanException {
syncTimetable(null); syncTimetable(null);
} }
@Override @Override
public void syncTimetable(String date) throws NotLoggedInErrorException, IOException, ParseException { public void syncTimetable(String date) throws IOException, ParseException, VulcanException {
this.userId = sharedPref.getCurrentUserId(); this.userId = sharedPref.getCurrentUserId();
io.github.wulkanowy.api.generic.Week<io.github.wulkanowy.api.generic.Day> weekApi = getWeekFromApi(getNormalizedDate(date)); io.github.wulkanowy.api.generic.Week<io.github.wulkanowy.api.generic.Day> weekApi = getWeekFromApi(getNormalizedDate(date));
@ -59,7 +59,7 @@ public class TimetableSync implements TimetableSyncContract {
daoSession.getTimetableLessonDao().saveInTx(lessonList); daoSession.getTimetableLessonDao().saveInTx(lessonList);
LogUtils.debug("Synchronization lessons (amount = " + lessonList.size() + ")"); LogUtils.debug("Synchronization timetable lessons (amount = " + lessonList.size() + ")");
} }
private String getNormalizedDate(String date) throws ParseException { private String getNormalizedDate(String date) throws ParseException {
@ -67,7 +67,7 @@ public class TimetableSync implements TimetableSyncContract {
} }
private io.github.wulkanowy.api.generic.Week<io.github.wulkanowy.api.generic.Day> getWeekFromApi(String date) private io.github.wulkanowy.api.generic.Week<io.github.wulkanowy.api.generic.Day> getWeekFromApi(String date)
throws IOException, NotLoggedInErrorException, ParseException { throws IOException, VulcanException, ParseException {
return vulcan.getTimetable().getWeekTable(date); return vulcan.getTimetable().getWeekTable(date);
} }

View File

@ -3,11 +3,11 @@ package io.github.wulkanowy.data.sync.timetable;
import java.io.IOException; import java.io.IOException;
import java.text.ParseException; import java.text.ParseException;
import io.github.wulkanowy.api.login.NotLoggedInErrorException; import io.github.wulkanowy.api.VulcanException;
public interface TimetableSyncContract { public interface TimetableSyncContract {
void syncTimetable(String date) throws NotLoggedInErrorException, IOException, ParseException; void syncTimetable(String date) throws VulcanException, IOException, ParseException;
void syncTimetable() throws NotLoggedInErrorException, IOException, ParseException; void syncTimetable() throws VulcanException, IOException, ParseException;
} }

View File

@ -21,11 +21,11 @@ import io.github.wulkanowy.data.db.resources.ResourcesContract;
import io.github.wulkanowy.data.db.shared.SharedPref; import io.github.wulkanowy.data.db.shared.SharedPref;
import io.github.wulkanowy.data.db.shared.SharedPrefContract; import io.github.wulkanowy.data.db.shared.SharedPrefContract;
import io.github.wulkanowy.data.sync.SyncContract; import io.github.wulkanowy.data.sync.SyncContract;
import io.github.wulkanowy.data.sync.account.AccountSync;
import io.github.wulkanowy.data.sync.account.AccountSyncContract;
import io.github.wulkanowy.data.sync.attendance.AttendanceSync; import io.github.wulkanowy.data.sync.attendance.AttendanceSync;
import io.github.wulkanowy.data.sync.attendance.AttendanceSyncContract; import io.github.wulkanowy.data.sync.attendance.AttendanceSyncContract;
import io.github.wulkanowy.data.sync.grades.GradeSync; import io.github.wulkanowy.data.sync.grades.GradeSync;
import io.github.wulkanowy.data.sync.login.LoginSync;
import io.github.wulkanowy.data.sync.login.LoginSyncContract;
import io.github.wulkanowy.data.sync.subjects.SubjectSync; import io.github.wulkanowy.data.sync.subjects.SubjectSync;
import io.github.wulkanowy.data.sync.timetable.TimetableSync; import io.github.wulkanowy.data.sync.timetable.TimetableSync;
import io.github.wulkanowy.data.sync.timetable.TimetableSyncContract; import io.github.wulkanowy.data.sync.timetable.TimetableSyncContract;
@ -100,8 +100,8 @@ public class ApplicationModule {
@Singleton @Singleton
@Provides @Provides
LoginSyncContract provideLoginSync(LoginSync loginSync) { AccountSyncContract provideLoginSync(AccountSync accountSync) {
return loginSync; return accountSync;
} }
@SyncGrades @SyncGrades

View File

@ -62,7 +62,7 @@ public class SyncJob extends SimpleJobService {
@Override @Override
public int onRunJob(JobParameters job) { public int onRunJob(JobParameters job) {
try { try {
repository.loginCurrentUser(); repository.initLastUser();
repository.syncAll(); repository.syncAll();
gradeList = repository.getNewGrades(); gradeList = repository.getNewGrades();

View File

@ -42,6 +42,8 @@ public interface LoginContract {
void onStartAsync(); void onStartAsync();
void onDoInBackground(int stepNumber) throws Exception;
void onLoginProgress(int step); void onLoginProgress(int step);
void onEndAsync(boolean success, Exception exception); void onEndAsync(boolean success, Exception exception);

View File

@ -17,6 +17,12 @@ public class LoginPresenter extends BasePresenter<LoginContract.View>
private LoginTask loginAsync; private LoginTask loginAsync;
private String email;
private String password;
private String symbol;
@Inject @Inject
LoginPresenter(RepositoryContract repository) { LoginPresenter(RepositoryContract repository) {
super(repository); super(repository);
@ -26,17 +32,17 @@ public class LoginPresenter extends BasePresenter<LoginContract.View>
public void attemptLogin(String email, String password, String symbol) { public void attemptLogin(String email, String password, String symbol) {
getView().resetViewErrors(); getView().resetViewErrors();
this.email = email;
this.password = password;
this.symbol = getNormalizedSymbol(symbol);
if (!isAllFieldCorrect(password, email)) { if (!isAllFieldCorrect(password, email)) {
getView().showSoftInput(); getView().showSoftInput();
return; return;
} }
if (getView().isNetworkConnected()) { if (getView().isNetworkConnected()) {
// Dopóki używamy AsyncTask presenter będzie musiał "wiedzieć" o AsyncTaskach loginAsync = new LoginTask(this);
loginAsync = new LoginTask(this,
email,
password,
getNormalizedSymbol(symbol));
loginAsync.execute(); loginAsync.execute();
} else { } else {
@ -53,6 +59,18 @@ public class LoginPresenter extends BasePresenter<LoginContract.View>
} }
} }
@Override
public void onDoInBackground(int stepNumber) throws Exception {
switch (stepNumber) {
case 1:
getRepository().registerUser(email, password, symbol);
break;
case 2:
getRepository().syncAll();
break;
}
}
@Override @Override
public void onLoginProgress(int step) { public void onLoginProgress(int step) {
if (step == 1) { if (step == 1) {

View File

@ -4,21 +4,12 @@ import android.os.AsyncTask;
public class LoginTask extends AsyncTask<Void, Integer, Boolean> { public class LoginTask extends AsyncTask<Void, Integer, Boolean> {
private String email;
private String password;
private String symbol;
private LoginContract.Presenter presenter; private LoginContract.Presenter presenter;
private Exception exception; private Exception exception;
LoginTask(LoginContract.Presenter presenter, String email, String password, String symbol) { LoginTask(LoginContract.Presenter presenter) {
this.presenter = presenter; this.presenter = presenter;
this.email = email;
this.password = password;
this.symbol = symbol;
} }
@Override @Override
@ -30,10 +21,10 @@ public class LoginTask extends AsyncTask<Void, Integer, Boolean> {
protected Boolean doInBackground(Void... params) { protected Boolean doInBackground(Void... params) {
try { try {
publishProgress(1); publishProgress(1);
presenter.getRepository().loginUser(email, password, symbol); presenter.onDoInBackground(1);
publishProgress(2); publishProgress(2);
presenter.getRepository().syncAll(); presenter.onDoInBackground(2);
} catch (Exception e) { } catch (Exception e) {
exception = e; exception = e;
return false; return false;

View File

@ -153,7 +153,6 @@ public class AttendanceTabPresenter extends BasePresenter<AttendanceTabContract.
} }
private void syncData() throws Exception { private void syncData() throws Exception {
getRepository().loginCurrentUser();
getRepository().syncAttendance(date); getRepository().syncAttendance(date);
} }

View File

@ -71,7 +71,6 @@ public class GradesPresenter extends BasePresenter<GradesContract.View>
@Override @Override
public void onDoInBackgroundRefresh() throws Exception { public void onDoInBackgroundRefresh() throws Exception {
getRepository().loginCurrentUser();
getRepository().syncSubjects(); getRepository().syncSubjects();
getRepository().syncGrades(); getRepository().syncGrades();
} }

View File

@ -157,7 +157,6 @@ public class TimetableTabPresenter extends BasePresenter<TimetableTabContract.Vi
} }
private void syncData() throws Exception { private void syncData() throws Exception {
getRepository().loginCurrentUser();
getRepository().syncTimetable(date); getRepository().syncTimetable(date);
} }

View File

@ -6,6 +6,7 @@ import javax.inject.Inject;
import io.github.wulkanowy.data.RepositoryContract; import io.github.wulkanowy.data.RepositoryContract;
import io.github.wulkanowy.ui.base.BasePresenter; import io.github.wulkanowy.ui.base.BasePresenter;
import io.github.wulkanowy.utils.LogUtils;
public class SplashPresenter extends BasePresenter<SplashContract.View> public class SplashPresenter extends BasePresenter<SplashContract.View>
implements SplashContract.Presenter { implements SplashContract.Presenter {
@ -23,7 +24,12 @@ public class SplashPresenter extends BasePresenter<SplashContract.View>
if (getRepository().getCurrentUserId() == 0) { if (getRepository().getCurrentUserId() == 0) {
getView().openLoginActivity(); getView().openLoginActivity();
} else { } else {
getView().openMainActivity(); try {
getRepository().initLastUser();
getView().openMainActivity();
} catch (Exception e) {
LogUtils.error("An error occurred when the application was started", e);
}
} }
} }
} }

View File

@ -6,10 +6,10 @@ import org.junit.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import io.github.wulkanowy.api.grades.Grade;
import io.github.wulkanowy.api.grades.Subject;
import io.github.wulkanowy.api.generic.Day; import io.github.wulkanowy.api.generic.Day;
import io.github.wulkanowy.api.generic.Lesson; import io.github.wulkanowy.api.generic.Lesson;
import io.github.wulkanowy.api.grades.Grade;
import io.github.wulkanowy.api.grades.Subject;
import io.github.wulkanowy.data.db.dao.entities.TimetableLesson; import io.github.wulkanowy.data.db.dao.entities.TimetableLesson;
public class DataObjectConverterTest { public class DataObjectConverterTest {