diff --git a/.circleci/config.yml b/.circleci/config.yml index c807f018..789123fa 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -7,7 +7,7 @@ references: container_config: &container_config docker: - - image: circleci/android:api-27-alpha + - image: circleci/android:api-28-alpha working_directory: *workspace_root environment: environment: @@ -38,7 +38,7 @@ jobs: command: ./gradlew build -x test -x lint -x fabricGenerateResourcesRelease -x packageRelease --no-daemon --stacktrace --console=plain -PdisablePreDex - run: name: Run FOSSA - command: fossa --no-ansi + command: fossa --no-ansi || true - persist_to_workspace: root: *workspace_root paths: @@ -89,28 +89,6 @@ jobs: paths: - "./app/build/jacoco" - api-test: - <<: *container_config - steps: - - *attach_workspace - - restore_cache: - <<: *general_cache_key - - run: - name: Run api tests - command: ./gradlew :api:test :api:jacocoTestReport --no-daemon --stacktrace --console=plain -PdisablePreDex - - run: - name: Upload code coverage to codecov - command: bash <(curl -s https://codecov.io/bash) -F api - - store_artifacts: - path: ./api/build/reports/ - destination: reports/ - - store_test_results: - path: ./api/build/test-results - - persist_to_workspace: - root: *workspace_root - paths: - - "./api/build/jacoco" - instrumented: <<: *container_config steps: @@ -135,10 +113,11 @@ jobs: adb shell input keyevent 82 - run: name: Run instrumented tests - command: ./gradlew clean createDebugCoverageReport jacocoTestReport --no-daemon --stacktrace --console=plain -PdisablePreDex + command: ./gradlew clean createDebugCoverageReport jacocoTestReport --no-daemon --stacktrace --console=plain -PdisablePreDex -PdisableCrashlytics - run: name: Collect logs from emulator command: adb logcat -d > ./app/build/reports/logcat_emulator.txt + when: always - run: name: Upload code covarage to codecov command: bash <(curl -s https://codecov.io/bash) -F instrumented @@ -201,12 +180,6 @@ workflows: only: /.*/ requires: - build - - api-test: - filters: - tags: - only: /.*/ - requires: - - build - instrumented: filters: tags: @@ -221,7 +194,6 @@ workflows: - build - lint - app-test - - api-test - instrumented - deploy: requires: @@ -230,4 +202,4 @@ workflows: tags: only: /\d+\.\d+\.\d+/ branches: - ignore: /.*/ + ignore: /.*/ \ No newline at end of file diff --git a/.gitignore b/.gitignore index 8ad04ebf..3eb9aa65 100644 --- a/.gitignore +++ b/.gitignore @@ -33,7 +33,6 @@ local.properties .idea/vcs.xml .idea/workspace.xml .idea/caches/ -.idea/codeStyles/ *.iml # OS-specific files @@ -44,7 +43,7 @@ local.properties .Trashes ehthumbs.db Thumbs.db -.idea/codeStyles/ .idea/caches/ ./app/key.p12 ./app/upload-key.jks +*.log diff --git a/.idea/codeStyleSettings.xml b/.idea/codeStyleSettings.xml deleted file mode 100644 index f5bd97e6..00000000 --- a/.idea/codeStyleSettings.xml +++ /dev/null @@ -1,226 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 00000000..7bfdc60b --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,173 @@ + + + + \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 00000000..0f7bc519 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + diff --git a/.idea/gradle.xml b/.idea/gradle.xml index 48777522..7ac24c77 100644 --- a/.idea/gradle.xml +++ b/.idea/gradle.xml @@ -8,7 +8,6 @@ diff --git a/README.md b/README.md index 8f809f82..9951cb8e 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,6 @@ [![Codecov](https://img.shields.io/codecov/c/github/wulkanowy/wulkanowy/master.svg?style=flat-square)](https://codecov.io/gh/wulkanowy/wulkanowy) [![BCH compliance](https://bettercodehub.com/edge/badge/wulkanowy/wulkanowy?branch=master)](https://bettercodehub.com/) [![Scrutinizer](https://img.shields.io/scrutinizer/g/wulkanowy/wulkanowy.svg?style=flat-square)](https://scrutinizer-ci.com/g/wulkanowy/wulkanowy/?branch=master) -[![Bintray](https://img.shields.io/bintray/v/wulkanowy/wulkanowy/api.svg?style=flat-square)](https://bintray.com/wulkanowy/wulkanowy/api) [![Discord](https://img.shields.io/discord/390889354199040011.svg?style=flat-square)](https://discord.gg/vccAQBr) [![FOSSA Status](https://app.fossa.io/api/projects/custom%2B5644%2Fgit%40github.com%3Awulkanowy%2Fwulkanowy.git.svg?type=shield)](https://app.fossa.io/projects/custom%2B5644%2Fgit%40github.com%3Awulkanowy%2Fwulkanowy.git?ref=badge_shield) diff --git a/api/build.gradle b/api/build.gradle deleted file mode 100644 index 5e5eeee3..00000000 --- a/api/build.gradle +++ /dev/null @@ -1,121 +0,0 @@ -apply plugin: 'java-library' -apply plugin: 'kotlin' -apply plugin: 'org.sonarqube' -apply plugin: 'jacoco' -apply plugin: 'com.jfrog.bintray' -apply plugin: 'com.github.dcendents.android-maven' - -compileJava.options.encoding = "UTF-8" -compileTestJava.options.encoding = "UTF-8" - -ext { - PUBLISH_GROUP_ID = GROUP_ID - PUBLISH_ARTIFACT_ID = 'api' - PUBLISH_VERSION = System.getenv('GIT_TAG') -} - -test { - testLogging { - events "passed", "skipped", "failed", "standardOut", "standardError" - outputs.upToDateWhen {false} - showStandardStreams = true - } -} - -jacocoTestReport { - reports { - xml.enabled true - } -} - -dependencies { - implementation "org.jsoup:jsoup:$jsoup" - implementation "org.apache.commons:commons-lang3:$apacheLang" - implementation "com.google.code.gson:gson:$gson" - implementation "org.slf4j:slf4j-api:$slf4jApi" - - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - - testImplementation "junit:junit:$junit" - testImplementation "org.mockito:mockito-core:$mockito" -} - -version = PUBLISH_VERSION -group = GROUP_ID - -sonarqube { - properties { - property "sonar.projectName", GROUP_ID + ":api" - property "sonar.projectKey", GROUP_ID + ":wulkanowy-api" - } -} - -def siteUrl = 'https://github.com/wulkanowy/wulkanowy' -def gitUrl = 'https://github.com/wulkanowy/wulkanowy.git' - -bintray { - user = System.getenv('BINTRAY_USER') - key = System.getenv('BINTRAY_KEY') - configurations = ['archives'] - pkg { - repo = 'wulkanowy' - name = 'api' - userOrg = 'wulkanowy' - licenses = ['Apache-2.0'] - vcsUrl = gitUrl - labels = ['aar', 'android', 'wulkanowy', 'api'] - publicDownloadNumbers = true - publish = true - - version { - name = PUBLISH_VERSION - vcsTag = PUBLISH_VERSION - released = new Date() - } - } -} - -install { - repositories.mavenInstaller { - pom { - project { - packaging 'aar' - name 'Bintray publish Gradle aar' - url siteUrl - licenses { - license { - name 'The Apache Software License, Version 2.0' - url 'http://www.apache.org/licenses/LICENSE-2.0.txt' - } - } - developers { - developer { - id 'mklkj' - name 'Mikołaj Pich' - email 'm.pich@outlook.com' - } - } - scm { - connection gitUrl - developerConnection gitUrl - url siteUrl - } - } - } - } -} - -task sourcesJar(type: Jar, dependsOn: classes) { - classifier = 'sources' - from sourceSets.main.allSource -} - -task javadocJar(type: Jar, dependsOn: javadoc) { - classifier = 'javadoc' - from javadoc.destinationDir -} - -artifacts { - archives sourcesJar - archives javadocJar -} diff --git a/api/src/main/java/io/github/wulkanowy/api/Client.java b/api/src/main/java/io/github/wulkanowy/api/Client.java deleted file mode 100644 index c6360d04..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/Client.java +++ /dev/null @@ -1,255 +0,0 @@ -package io.github.wulkanowy.api; - -import org.jsoup.Connection; -import org.jsoup.Jsoup; -import org.jsoup.nodes.Document; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import io.github.wulkanowy.api.generic.School; -import io.github.wulkanowy.api.login.Login; - -public class Client { - - private String protocol = "https"; - - private String host = "vulcan.net.pl"; - - private String email; - - private String password; - - private String symbol; - - private String schoolId; - - private List schools; - - private Date lastSuccessRequest; - - private Cookies cookies = new Cookies(); - - private static final Logger logger = LoggerFactory.getLogger(Client.class); - - Client(String email, String password, String symbol, String schoolId) { - this.email = email; - this.password = password; - this.symbol = symbol; - this.schoolId = schoolId; - - setFullEndpointInfo(email); - } - - private void setFullEndpointInfo(String info) { - String[] creds = info.split("\\\\"); - - email = info; - - if (creds.length > 2) { - String[] url = creds[0].split("://"); - - protocol = url[0]; - String[] path = url[1].split("/"); - host = path[0]; - if (path.length > 1) { - symbol = path[1]; - } - email = creds[2]; - } - } - - private void login() throws IOException, VulcanException { - if (isLoggedIn()) { - return; - } - - logger.info("Not logged. Login..."); - - clearCookies(); - new Login(this).login(email, password, symbol); - lastSuccessRequest = new Date(); - - logger.info("Login successful on {} at {}", getHost(), new Date()); - } - - private boolean isLoggedIn() { - logger.trace("Last success request: {}", lastSuccessRequest); - logger.trace("Cookies: {}", getCookies().size()); - - return getCookies().size() > 0 && lastSuccessRequest != null && - 5 > TimeUnit.MILLISECONDS.toMinutes(new Date().getTime() - lastSuccessRequest.getTime()); - - } - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - private Map getCookies() { - return cookies.getItems(); - } - - public void clearCookies() { - cookies = new Cookies(); - } - - public String getHost() { - return host; - } - - public void setSchools(List schools) { - this.schools = schools; - this.schoolId = schools.get(0).getId(); - } - - public List getSchools() throws IOException, VulcanException { - login(); - return schools; - } - - public String getSchoolId() throws IOException, VulcanException { - return schoolId != null ? schoolId : getSchools().get(0).getId(); - } - - String getFilledUrl(String url) { - return url - .replace("{schema}", protocol) - .replace("{host}", host) - .replace("{symbol}", symbol) - .replace("{ID}", schoolId != null ? schoolId : ""); - } - - public Document getPageByUrl(String url) throws IOException, VulcanException { - return getPageByUrl(url, true, null); - } - - public Document getPageByUrl(String url, boolean loginBefore) throws IOException, VulcanException { - return getPageByUrl(url, loginBefore, null); - } - - public synchronized Document getPageByUrl(String url, boolean loginBefore, Map cookies) throws IOException, VulcanException { - if (loginBefore) { - login(); - } - - if (null != cookies) { - this.cookies.addItems(cookies); - } - - url = getFilledUrl(url); - - logger.debug("GET {}", url); - - Connection.Response response = Jsoup.connect(url) - .followRedirects(true) - .cookies(getCookies()) - .execute(); - - this.cookies.addItems(response.cookies()); - - Document doc = checkForErrors(response.parse(), response.statusCode()); - - if (loginBefore) { - lastSuccessRequest = new Date(); - } - - return doc; - } - - public synchronized Document postPageByUrl(String url, String[][] params) throws IOException, VulcanException { - url = getFilledUrl(url); - - logger.debug("POST {}", url); - - Connection connection = Jsoup.connect(url); - - for (String[] data : params) { - connection.data(data[0], data[1]); - } - - Connection.Response response = connection - .followRedirects(true) - .method(Connection.Method.POST) - .cookies(getCookies()) - .execute(); - - this.cookies.addItems(response.cookies()); - - response.bufferUp(); // fixes cert parsing issues #109 - - return checkForErrors(response.parse(), response.statusCode()); - } - - public String getJsonStringByUrl(String url) throws IOException, VulcanException { - login(); - - url = getFilledUrl(url); - - logger.debug("GET {}", url); - - Connection.Response response = Jsoup.connect(url) - .followRedirects(true) - .ignoreContentType(true) - .cookies(getCookies()) - .execute(); - - this.cookies.addItems(response.cookies()); - - return response.body(); - } - - public String postJsonStringByUrl(String url, String[][] params) throws IOException, VulcanException { - login(); - - url = getFilledUrl(url); - - logger.debug("POST {}", url); - - Connection connection = Jsoup.connect(url); - - for (String[] data : params) { - connection.data(data[0], data[1]); - } - - Connection.Response response = connection - .followRedirects(true) - .ignoreContentType(true) - .method(Connection.Method.POST) - .cookies(getCookies()) - .execute(); - - this.cookies.addItems(response.cookies()); - - return response.body(); - } - - Document checkForErrors(Document doc, int code) throws VulcanException { - lastSuccessRequest = null; - - String title = doc.select("title").text(); - if ("Przerwa techniczna".equals(title)) { - throw new VulcanOfflineException(title); - } - - String singIn = doc.select(".loginButton").text(); - if ("Zaloguj się".equals(singIn)) { - throw new NotLoggedInErrorException(singIn); - } - - if ("Błąd strony".equals(title)) { - throw new NotLoggedInErrorException(title + " " + doc.body() + ", status: " + code); - } - - return doc; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/Cookies.java b/api/src/main/java/io/github/wulkanowy/api/Cookies.java deleted file mode 100644 index dfe4c4b5..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/Cookies.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.github.wulkanowy.api; - -import java.util.HashMap; -import java.util.Map; - -class Cookies { - - private Map jar = new HashMap<>(); - - Map getItems() { - return jar; - } - - void addItems(Map items) { - jar.putAll(items); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/DateTimeUtils.kt b/api/src/main/java/io/github/wulkanowy/api/DateTimeUtils.kt deleted file mode 100644 index 7ea6c066..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/DateTimeUtils.kt +++ /dev/null @@ -1,54 +0,0 @@ -package io.github.wulkanowy.api - -import java.text.SimpleDateFormat -import java.util.* - -const val LOG_DATE_PATTERN = "dd.MM.yyyy" -const val API_DATE_PATTERN = "yyyy-MM-dd" - -const val TICKS_AT_EPOCH = 621355968000000000L -const val TICKS_PER_MILLISECOND = 10000 - -fun getFormattedDate(date: String?): String { - return getFormattedDate(date, API_DATE_PATTERN) -} - -fun getFormattedDate(date: String?, format: String): String { - return getFormattedDate(date, LOG_DATE_PATTERN, format) -} - -fun getFormattedDate(date: String?, fromFormat: String, toFormat: String): String { - if (date.isNullOrEmpty()) return "" - val sdf = SimpleDateFormat(fromFormat, Locale.ROOT) - val d = sdf.parse(date) - sdf.applyPattern(toFormat) - - return sdf.format(d) -} - -fun getDateAsTick(dateString: String?): String { - if (dateString.isNullOrEmpty()) { - return "" - } - - return getDateAsTick(dateString as String, API_DATE_PATTERN).toString() -} - -fun getDateAsTick(dateString: String, dateFormat: String): Long { - val format = SimpleDateFormat(dateFormat, Locale.ROOT) - format.timeZone = TimeZone.getTimeZone("UTC") - val dateObject = format.parse(dateString) - - return getDateAsTick(dateObject) -} - -fun getDateAsTick(date: Date): Long { - val calendar = Calendar.getInstance() - calendar.time = date - - return calendar.timeInMillis * TICKS_PER_MILLISECOND + TICKS_AT_EPOCH -} - -fun getDate(netTicks: Long): Date { - return Date((netTicks - TICKS_AT_EPOCH) / TICKS_PER_MILLISECOND) -} diff --git a/api/src/main/java/io/github/wulkanowy/api/NotLoggedInErrorException.java b/api/src/main/java/io/github/wulkanowy/api/NotLoggedInErrorException.java deleted file mode 100644 index 179fc8cc..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/NotLoggedInErrorException.java +++ /dev/null @@ -1,8 +0,0 @@ -package io.github.wulkanowy.api; - -public class NotLoggedInErrorException extends VulcanException { - - public NotLoggedInErrorException(String message) { - super(message); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/SnP.java b/api/src/main/java/io/github/wulkanowy/api/SnP.java deleted file mode 100644 index 84ec1aed..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/SnP.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.github.wulkanowy.api; - -import org.jsoup.nodes.Document; -import org.jsoup.nodes.Element; - -import java.io.IOException; -import java.util.List; - -import io.github.wulkanowy.api.generic.Diary; -import io.github.wulkanowy.api.generic.ParamItem; -import io.github.wulkanowy.api.generic.Semester; -import io.github.wulkanowy.api.generic.Student; - -public interface SnP { - - void setDiaryID(String id); - - String getStudentID(); - - List getStudents() throws IOException, VulcanException; - - StudentAndParent setUp() throws IOException, VulcanException; - - String getRowDataChildValue(Element e, int index); - - Document getSnPPageDocument(String url) throws IOException, VulcanException; - - List getDiaries() throws IOException, VulcanException; - - List getSemesters() throws IOException, VulcanException; - - List getSemesters(Document gradesPage); - - T getCurrent(List list); -} diff --git a/api/src/main/java/io/github/wulkanowy/api/StudentAndParent.java b/api/src/main/java/io/github/wulkanowy/api/StudentAndParent.java deleted file mode 100644 index ba527f6a..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/StudentAndParent.java +++ /dev/null @@ -1,171 +0,0 @@ -package io.github.wulkanowy.api; - -import org.jsoup.nodes.Document; -import org.jsoup.nodes.Element; -import org.jsoup.select.Elements; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.net.URL; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import io.github.wulkanowy.api.generic.Diary; -import io.github.wulkanowy.api.generic.ParamItem; -import io.github.wulkanowy.api.generic.Semester; -import io.github.wulkanowy.api.generic.Student; - -public class StudentAndParent implements SnP { - - private static final String BASE_URL = "{schema}://uonetplus-opiekun.{host}/{symbol}/{ID}/"; - - private static final String GRADES_PAGE_URL = "Oceny/Wszystkie"; - - private Client client; - - private String studentID; - - private String diaryID; - - private static final Logger logger = LoggerFactory.getLogger(StudentAndParent.class); - - StudentAndParent(Client client, String studentID, String diaryID) { - this.client = client; - this.studentID = studentID; - this.diaryID = diaryID; - } - - public StudentAndParent setUp() throws IOException, VulcanException { - if (null == getStudentID() || "".equals(getStudentID())) { - Document doc = client.getPageByUrl(BASE_URL); - - if (doc.select("#idSection").isEmpty()) { - logger.error("Expected SnP page, got page with title: {} {}", doc.title(), doc.selectFirst("body")); - throw new VulcanException("Nieznany błąd podczas pobierania danych. Strona: " + doc.title()); - } - - Student student = getCurrent(getStudents(doc)); - studentID = student.getId(); - - Diary diary = getCurrent(getDiaries(doc)); - diaryID = diary.getId(); - } - - return this; - } - - public String getStudentID() { - return studentID; - } - - public String getRowDataChildValue(Element e, int index) { - return e.select(".daneWiersz .wartosc").get(index - 1).text(); - } - - public void setDiaryID(String id) { - this.diaryID = id; - } - - public Document getSnPPageDocument(String url) throws IOException, VulcanException { - Map cookies = new HashMap<>(); - cookies.put("idBiezacyDziennik", diaryID); - cookies.put("idBiezacyUczen", studentID); - - Document doc = client.getPageByUrl(BASE_URL + url, true, cookies); - - if (!doc.title().startsWith("Witryna ucznia i rodzica")) { - logger.error("Expected SnP page, got page with title: {} {}", doc.title(), doc.selectFirst("body")); - throw new VulcanException("Nieznany błąd podczas pobierania danych. Strona: " + doc.title()); - } - - if (doc.title().endsWith("Strona główna")) { - throw new VulcanException("Sesja została nieprawidłowo zainicjowana"); - } - - return doc; - } - - public List getDiaries() throws IOException, VulcanException { - return getDiaries(client.getPageByUrl(BASE_URL)); - } - - private List getDiaries(Document doc) throws IOException, VulcanException { - return getList(doc.select("#dziennikDropDownList option"), Diary.class); - } - - public List getStudents() throws IOException, VulcanException { - return getStudents(client.getPageByUrl(BASE_URL)); - } - - private List getStudents(Document doc) throws IOException, VulcanException { - return getList(doc.select("#uczenDropDownList option"), Student.class); - } - - public List getSemesters() throws IOException, VulcanException { - return getSemesters(getSnPPageDocument(GRADES_PAGE_URL)); - } - - public List getSemesters(Document gradesPage) { - Elements semesterOptions = gradesPage.select("#okresyKlasyfikacyjneDropDownList option"); - - List semesters = new ArrayList<>(); - - for (Element e : semesterOptions) { - Semester semester = new Semester() - .setId(e.attr("value")) - .setName(e.text()); - - if (isCurrent(e)) { - semester.setCurrent(true); - } - - semesters.add(semester); - } - - return semesters; - } - - @SuppressWarnings("unchecked") - private List getList(Elements options, Class type) throws IOException, VulcanException { - List list = new ArrayList<>(); - - for (Element e : options) { - URL url = new URL(e.val()); - try { - ParamItem item = type.newInstance() - .setId(url.getQuery().split("=")[1]) - .setName(e.text()); - - if (isCurrent(e)) { - item.setCurrent(true); - } - - list.add((T) item); - } catch (Exception ex) { - throw new VulcanException("Error while trying to parse params list", ex); - } - } - - return list; - } - - @SuppressWarnings("unchecked") - public T getCurrent(List list) { - ParamItem current = null; - for (ParamItem s : list) { - if (s.isCurrent()) { - current = s; - break; - } - } - - return (T) current; - } - - private boolean isCurrent(Element e) { - return "selected".equals(e.attr("selected")); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/Vulcan.java b/api/src/main/java/io/github/wulkanowy/api/Vulcan.java deleted file mode 100644 index 70cf382e..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/Vulcan.java +++ /dev/null @@ -1,174 +0,0 @@ -package io.github.wulkanowy.api; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.List; - -import io.github.wulkanowy.api.attendance.Attendance; -import io.github.wulkanowy.api.attendance.AttendanceLesson; -import io.github.wulkanowy.api.attendance.AttendanceStatistics; -import io.github.wulkanowy.api.attendance.AttendanceTable; -import io.github.wulkanowy.api.exams.ExamEntry; -import io.github.wulkanowy.api.exams.Exams; -import io.github.wulkanowy.api.exams.ExamsWeek; -import io.github.wulkanowy.api.generic.School; -import io.github.wulkanowy.api.grades.GradeKt; -import io.github.wulkanowy.api.grades.Grades; -import io.github.wulkanowy.api.grades.GradesList; -import io.github.wulkanowy.api.grades.GradesSummary; -import io.github.wulkanowy.api.grades.SubjectsList; -import io.github.wulkanowy.api.grades.Summary; -import io.github.wulkanowy.api.homework.Homework; -import io.github.wulkanowy.api.homework.HomeworkList; -import io.github.wulkanowy.api.messages.Messages; -import io.github.wulkanowy.api.mobile.RegisterDevice; -import io.github.wulkanowy.api.mobile.RegisteredDevices; -import io.github.wulkanowy.api.notes.AchievementsList; -import io.github.wulkanowy.api.notes.NotesList; -import io.github.wulkanowy.api.school.SchoolInfo; -import io.github.wulkanowy.api.school.TeachersInfo; -import io.github.wulkanowy.api.timetable.Timetable; -import io.github.wulkanowy.api.timetable.TimetableKt; -import io.github.wulkanowy.api.timetable.TimetableLesson; -import io.github.wulkanowy.api.user.BasicInformation; -import io.github.wulkanowy.api.user.FamilyInformation; - -public class Vulcan { - - private SnP snp; - - private Client client; - - private String studentId; - - private String diaryId; - - private static final Logger logger = LoggerFactory.getLogger(Vulcan.class); - - public void setCredentials(String email, String password, String symbol, String schoolId, String studentId, String diaryId) { - this.studentId = studentId; - this.diaryId = diaryId; - - client = new Client(email, password, symbol, schoolId); - - logger.debug("Client created with symbol " + symbol); - } - - public Client getClient() throws NotLoggedInErrorException { - if (null == client) { - throw new NotLoggedInErrorException("Vulcan must be initialized by calling setCredentials() prior to fetch data"); - } - - return client; - } - - public String getSymbol() throws NotLoggedInErrorException { - return getClient().getSymbol(); - } - - public List getSchools() throws VulcanException, IOException { - return getClient().getSchools(); - } - - public SnP getStudentAndParent() throws VulcanException, IOException { - if (null != this.snp) { - return this.snp; - } - - this.snp = new StudentAndParent(getClient(), studentId, diaryId) - .setUp(); - - return this.snp; - } - - public List getAttendance(String dateStart) throws VulcanException, IOException { - return new Attendance(getStudentAndParent()).getAttendance(dateStart); - } - - @Deprecated - public AttendanceTable getAttendanceTable() throws IOException, VulcanException { - return new AttendanceTable(getStudentAndParent()); - } - - public AttendanceStatistics getAttendanceStatistics() throws IOException, VulcanException { - return new AttendanceStatistics(getStudentAndParent()); - } - - public List getExams(String dateStart) throws VulcanException, IOException { - return new Exams(getStudentAndParent()).getExams(dateStart); - } - - @Deprecated - public ExamsWeek getExamsList() throws IOException, VulcanException { - return new ExamsWeek(getStudentAndParent()); - } - - public List getGrades(String semester) throws VulcanException, IOException { - return new Grades(getStudentAndParent()).getGrades(semester); - } - - @Deprecated - public GradesList getGradesList() throws IOException, VulcanException { - return new GradesList(getStudentAndParent()); - } - - public List getGradesSummary(String semester) throws VulcanException, IOException { - return new GradesSummary(getStudentAndParent()).getSummary(semester); - } - - public List getHomework(String date) throws VulcanException, IOException { - return new HomeworkList(getStudentAndParent()).getHomework(date); - } - - @Deprecated - public SubjectsList getSubjectsList() throws IOException, VulcanException { - return new SubjectsList(getStudentAndParent()); - } - - public AchievementsList getAchievementsList() throws IOException, VulcanException { - return new AchievementsList(getStudentAndParent()); - } - - public NotesList getNotesList() throws IOException, VulcanException { - return new NotesList(getStudentAndParent()); - } - - public SchoolInfo getSchoolInfo() throws IOException, VulcanException { - return new SchoolInfo(getStudentAndParent()); - } - - public TeachersInfo getTeachersInfo() throws IOException, VulcanException { - return new TeachersInfo(getStudentAndParent()); - } - - public List getTimetable(String dateStart) throws VulcanException, IOException { - return new TimetableKt(getStudentAndParent()).getTimetable(dateStart); - } - - @Deprecated - public Timetable getTimetable() throws IOException, VulcanException { - return new Timetable(getStudentAndParent()); - } - - public BasicInformation getBasicInformation() throws IOException, VulcanException { - return new BasicInformation(getStudentAndParent()); - } - - public FamilyInformation getFamilyInformation() throws IOException, VulcanException { - return new FamilyInformation(getStudentAndParent()); - } - - public RegisteredDevices getRegisteredDevices() throws VulcanException, IOException { - return new RegisteredDevices(getStudentAndParent()); - } - - public RegisterDevice getRegisterDevice() throws VulcanException, IOException { - return new RegisterDevice(getStudentAndParent()); - } - - public Messages getMessages() throws VulcanException { - return new Messages(getClient()); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/VulcanException.java b/api/src/main/java/io/github/wulkanowy/api/VulcanException.java deleted file mode 100644 index 0bc0c51f..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/VulcanException.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.github.wulkanowy.api; - -public class VulcanException extends Exception { - - public VulcanException(String message) { - super(message); - } - - protected VulcanException(String message, Exception e) { - super(message, e); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/VulcanOfflineException.java b/api/src/main/java/io/github/wulkanowy/api/VulcanOfflineException.java deleted file mode 100644 index 24ab48e6..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/VulcanOfflineException.java +++ /dev/null @@ -1,8 +0,0 @@ -package io.github.wulkanowy.api; - -public class VulcanOfflineException extends VulcanException { - - VulcanOfflineException(String message) { - super(message); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/attendance/Attendance.kt b/api/src/main/java/io/github/wulkanowy/api/attendance/Attendance.kt deleted file mode 100644 index b66a3623..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/attendance/Attendance.kt +++ /dev/null @@ -1,69 +0,0 @@ -package io.github.wulkanowy.api.attendance - -import io.github.wulkanowy.api.SnP -import io.github.wulkanowy.api.getDateAsTick -import io.github.wulkanowy.api.getFormattedDate -import org.jsoup.nodes.Element -import org.jsoup.select.Elements - -class Attendance(private val snp: SnP) { - - fun getAttendance() = getAttendance("") - - fun getAttendance(start: String): List { - val table = snp.getSnPPageDocument("Frekwencja.mvc?data=" + getDateAsTick(start)) - .selectFirst(".mainContainer .presentData") - - val days = getDays(table.select("thead th")) - - return table.select("tbody tr").map { - val hours = it.select("td") - hours.drop(1).mapIndexed { i, item -> - getLesson(item, days[i], hours[0].text().toInt()) - } - }.flatten().sortedBy { - it.date - }.filter { - it.subject.isNotBlank() - } - } - - private fun getDays(el: Elements): List { - return el.drop(1).map { - getFormattedDate(it.html().split("
")[1]) - } - } - - private fun getLesson(cell: Element, date: String, number: Int): AttendanceLesson { - val lesson = AttendanceLesson(number = number, date = date, subject = cell.select("span").text()) - - if (Types.CLASS_NOT_EXIST == cell.attr("class")) { - lesson.notExist = true - - return lesson - } - - when (cell.select("div").attr("class")) { - Types.CLASS_PRESENCE -> lesson.presence = true - Types.CLASS_ABSENCE_UNEXCUSED -> lesson.absenceUnexcused = true - Types.CLASS_ABSENCE_EXCUSED -> lesson.absenceExcused = true - Types.CLASS_ABSENCE_FOR_SCHOOL_REASONS -> lesson.absenceForSchoolReasons = true - Types.CLASS_UNEXCUSED_LATENESS -> lesson.unexcusedLateness = true - Types.CLASS_EXCUSED_LATENESS -> lesson.excusedLateness = true - Types.CLASS_EXEMPTION -> lesson.exemption = true - } - - return lesson - } - - private object Types { - const val CLASS_NOT_EXIST = "x-sp-nieobecny-w-oddziale" - const val CLASS_PRESENCE = "x-obecnosc" - const val CLASS_ABSENCE_UNEXCUSED = "x-nieobecnosc-nieuspr" - const val CLASS_ABSENCE_EXCUSED = "x-nieobecnosc-uspr" - const val CLASS_ABSENCE_FOR_SCHOOL_REASONS = "x-nieobecnosc-przycz-szkol" - const val CLASS_UNEXCUSED_LATENESS = "x-sp-nieusprawiedliwione" - const val CLASS_EXCUSED_LATENESS = "x-sp-spr" - const val CLASS_EXEMPTION = "x-sp-zwolnienie" - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/attendance/AttendanceLesson.kt b/api/src/main/java/io/github/wulkanowy/api/attendance/AttendanceLesson.kt deleted file mode 100644 index 4edf8648..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/attendance/AttendanceLesson.kt +++ /dev/null @@ -1,26 +0,0 @@ -package io.github.wulkanowy.api.attendance - -data class AttendanceLesson( - - val number: Int, - - val date: String, - - val subject: String, - - var notExist: Boolean = false, - - var presence: Boolean = false, - - var absenceUnexcused: Boolean = false, - - var absenceExcused: Boolean = false, - - var unexcusedLateness: Boolean = false, - - var absenceForSchoolReasons: Boolean = false, - - var excusedLateness: Boolean = false, - - var exemption: Boolean = false -) diff --git a/api/src/main/java/io/github/wulkanowy/api/attendance/AttendanceStatistics.java b/api/src/main/java/io/github/wulkanowy/api/attendance/AttendanceStatistics.java deleted file mode 100644 index 29b6a6d9..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/attendance/AttendanceStatistics.java +++ /dev/null @@ -1,89 +0,0 @@ -package io.github.wulkanowy.api.attendance; - -import org.apache.commons.lang3.math.NumberUtils; -import org.jsoup.nodes.Element; -import org.jsoup.select.Elements; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -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.Subject; - -public class AttendanceStatistics { - - private SnP snp; - - private String attendancePageUrl = "Frekwencja.mvc"; - - public AttendanceStatistics(SnP snp) { - this.snp = snp; - } - - public Types getTypesTable() throws IOException, VulcanException { - return getTypesTable(""); - } - - public Types getTypesTable(String tick) throws IOException, VulcanException { - return getTypesTable(tick, -1); - } - - public List getSubjectList() throws IOException, VulcanException { - Element mainContainer = snp.getSnPPageDocument(attendancePageUrl) - .select(".mainContainer #idPrzedmiot").first(); - - List subjectList = new ArrayList<>(); - - for (Element subject : mainContainer.select("option")) { - subjectList.add(new Subject() - .setId(Integer.parseInt(subject.attr("value"))) - .setName(subject.text()) - ); - } - - return subjectList; - } - - public Types getTypesTable(String tick, Integer subjectId) throws IOException, VulcanException { - Element mainContainer = snp.getSnPPageDocument((attendancePageUrl - + "?data={tick}&idPrzedmiot={subject}") - .replace("{tick}", tick) - .replace("{subject}", subjectId.toString()) - ).select(".mainContainer").first(); - - Element table = mainContainer.select("table:nth-of-type(2)").first(); - - Elements headerCells = table.select("thead th"); - List typeList = new ArrayList<>(); - - Elements typesRows = table.select("tbody tr"); - - // fill types with months - for (Element row : typesRows) { - Elements monthsCells = row.select("td"); - - List monthList = new ArrayList<>(); - - // iterate over month in type, first column is empty, last is `total`; (0, n-1) - for (int i = 1; i < monthsCells.size() - 1; i++) { - monthList.add(new Month() - .setValue(NumberUtils.toInt(monthsCells.get(i).text(), 0)) - .setName(headerCells.get(i).text())); - } - - typeList.add(new Type() - .setTotal(NumberUtils.toInt(monthsCells.last().text(), 0)) - .setName(monthsCells.get(0).text()) - .setMonthList(monthList)); - } - - String total = mainContainer.select("h2").text().split(": ")[1]; - - return new Types() - .setTotal(NumberUtils.toDouble(total.replace("%", "").replace(",", "."))) - .setTypeList(typeList); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/attendance/AttendanceTable.java b/api/src/main/java/io/github/wulkanowy/api/attendance/AttendanceTable.java deleted file mode 100644 index 489b2472..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/attendance/AttendanceTable.java +++ /dev/null @@ -1,112 +0,0 @@ -package io.github.wulkanowy.api.attendance; - -import org.jsoup.nodes.Element; -import org.jsoup.select.Elements; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -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.Lesson; -import io.github.wulkanowy.api.generic.Week; - -import static io.github.wulkanowy.api.DateTimeUtilsKt.getDateAsTick; -import static io.github.wulkanowy.api.DateTimeUtilsKt.getFormattedDate; - -@Deprecated -public class AttendanceTable { - - private final static String ATTENDANCE_PAGE_URL = "Frekwencja.mvc?data="; - - private SnP snp; - - public AttendanceTable(SnP snp) { - this.snp = snp; - } - - public Week getWeekTable() throws IOException, VulcanException { - return getWeekTable(""); - } - - public Week getWeekTable(String date) throws IOException, VulcanException { - Element table = snp.getSnPPageDocument(ATTENDANCE_PAGE_URL + getDateAsTick(date)) - .select(".mainContainer .presentData").first(); - - Elements headerCells = table.select("thead th"); - List days = new ArrayList<>(); - - for (int i = 1; i < headerCells.size(); i++) { - String[] dayHeaderCell = headerCells.get(i).html().split("
"); - - days.add(new Day() - .setDayName(dayHeaderCell[0]) - .setDate(getFormattedDate(dayHeaderCell[1].trim())) - ); - } - - Elements hoursInDays = table.select("tbody tr"); - - // fill days in week with lessons - for (Element row : hoursInDays) { - Elements hours = row.select("td"); - - // fill hours in day - int size = hours.size(); - for (int i = 1; i < size; i++) { - Lesson lesson = new Lesson(); - lesson.setDate(days.get(i - 1).getDate()); - lesson.setNumber(Integer.valueOf(hours.get(0).text())); - - addLessonDetails(lesson, hours.get(i)); - - days.get(i - 1).setLesson(lesson); - } - } - - return new Week() - .setStartDayDate(days.get(0).getDate()) - .setDays(days); - } - - private void addLessonDetails(Lesson lesson, Element cell) { - lesson.setSubject(cell.select("span").text()); - - if (LessonTypes.CLASS_NOT_EXIST.equals(cell.attr("class"))) { - lesson.setNotExist(true); - lesson.setEmpty(true); - - return; - } - - switch (cell.select("div").attr("class")) { - case LessonTypes.CLASS_PRESENCE: - lesson.setPresence(true); - break; - case LessonTypes.CLASS_ABSENCE_UNEXCUSED: - lesson.setAbsenceUnexcused(true); - break; - case LessonTypes.CLASS_ABSENCE_EXCUSED: - lesson.setAbsenceExcused(true); - break; - case LessonTypes.CLASS_ABSENCE_FOR_SCHOOL_REASONS: - lesson.setAbsenceForSchoolReasons(true); - break; - case LessonTypes.CLASS_UNEXCUSED_LATENESS: - lesson.setUnexcusedLateness(true); - break; - case LessonTypes.CLASS_EXCUSED_LATENESS: - lesson.setExcusedLateness(true); - break; - case LessonTypes.CLASS_EXEMPTION: - lesson.setExemption(true); - break; - - default: - lesson.setEmpty(true); - break; - } - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/attendance/LessonTypes.java b/api/src/main/java/io/github/wulkanowy/api/attendance/LessonTypes.java deleted file mode 100644 index 8cd1ebfc..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/attendance/LessonTypes.java +++ /dev/null @@ -1,25 +0,0 @@ -package io.github.wulkanowy.api.attendance; - -@Deprecated -class LessonTypes { - - static final String CLASS_NOT_EXIST = "x-sp-nieobecny-w-oddziale"; - - static final String CLASS_PRESENCE = "x-obecnosc"; - - static final String CLASS_ABSENCE_UNEXCUSED = "x-nieobecnosc-nieuspr"; - - static final String CLASS_ABSENCE_EXCUSED = "x-nieobecnosc-uspr"; - - static final String CLASS_ABSENCE_FOR_SCHOOL_REASONS = "x-nieobecnosc-przycz-szkol"; - - static final String CLASS_UNEXCUSED_LATENESS = "x-sp-nieusprawiedliwione"; - - static final String CLASS_EXCUSED_LATENESS = "x-sp-spr"; - - static final String CLASS_EXEMPTION = "x-sp-zwolnienie"; - - private LessonTypes() { - throw new IllegalStateException("Utility class"); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/attendance/Type.java b/api/src/main/java/io/github/wulkanowy/api/attendance/Type.java deleted file mode 100644 index 6deb003e..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/attendance/Type.java +++ /dev/null @@ -1,42 +0,0 @@ -package io.github.wulkanowy.api.attendance; - -import java.util.ArrayList; -import java.util.List; - -import io.github.wulkanowy.api.generic.Month; - -public class Type { - - private String name = ""; - - private int total = 0; - - private List monthList = new ArrayList<>(); - - public String getName() { - return name; - } - - public Type setName(String name) { - this.name = name; - return this; - } - - public int getTotal() { - return total; - } - - public Type setTotal(int total) { - this.total = total; - return this; - } - - public List getMonthList() { - return monthList; - } - - public Type setMonthList(List monthList) { - this.monthList = monthList; - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/attendance/Types.java b/api/src/main/java/io/github/wulkanowy/api/attendance/Types.java deleted file mode 100644 index d1b1777d..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/attendance/Types.java +++ /dev/null @@ -1,29 +0,0 @@ -package io.github.wulkanowy.api.attendance; - -import java.util.ArrayList; -import java.util.List; - -public class Types { - - private double total = 0; - - private List typeList = new ArrayList<>(); - - public double getTotal() { - return total; - } - - public Types setTotal(double total) { - this.total = total; - return this; - } - - public List getTypeList() { - return typeList; - } - - public Types setTypeList(List typeList) { - this.typeList = typeList; - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/exams/Exam.java b/api/src/main/java/io/github/wulkanowy/api/exams/Exam.java deleted file mode 100644 index b0a83c21..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/exams/Exam.java +++ /dev/null @@ -1,60 +0,0 @@ -package io.github.wulkanowy.api.exams; - -@Deprecated -public class Exam { - - private String subjectAndGroup = ""; - - private String type = ""; - - private String description = ""; - - private String teacher = ""; - - private String entryDate = ""; - - public String getSubjectAndGroup() { - return subjectAndGroup; - } - - public Exam setSubjectAndGroup(String subjectAndGroup) { - this.subjectAndGroup = subjectAndGroup; - return this; - } - - public String getType() { - return type; - } - - public Exam setType(String type) { - this.type = type; - return this; - } - - public String getDescription() { - return description; - } - - public Exam setDescription(String description) { - this.description = description; - return this; - } - - public String getTeacher() { - return teacher; - } - - public Exam setTeacher(String teacher) { - this.teacher = teacher; - return this; - } - - public String getEntryDate() { - return entryDate; - } - - public Exam setEntryDate(String entryDate) { - this.entryDate = entryDate; - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/exams/ExamDay.java b/api/src/main/java/io/github/wulkanowy/api/exams/ExamDay.java deleted file mode 100644 index 22f77419..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/exams/ExamDay.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.github.wulkanowy.api.exams; - -import java.util.ArrayList; -import java.util.List; - -import io.github.wulkanowy.api.generic.Day; - -@Deprecated -public class ExamDay extends Day { - - private List examList = new ArrayList<>(); - - public List getExamList() { - return examList; - } - - public void addExam(Exam exam) { - this.examList.add(exam); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/exams/ExamEntry.kt b/api/src/main/java/io/github/wulkanowy/api/exams/ExamEntry.kt deleted file mode 100644 index e9c2ca28..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/exams/ExamEntry.kt +++ /dev/null @@ -1,20 +0,0 @@ -package io.github.wulkanowy.api.exams - -data class ExamEntry( - - val date: String, - - val entryDate: String, - - val subject: String, - - val group: String, - - val type: String, - - val description: String, - - val teacher: String, - - val teacherSymbol: String -) diff --git a/api/src/main/java/io/github/wulkanowy/api/exams/Exams.kt b/api/src/main/java/io/github/wulkanowy/api/exams/Exams.kt deleted file mode 100644 index f95c2554..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/exams/Exams.kt +++ /dev/null @@ -1,40 +0,0 @@ -package io.github.wulkanowy.api.exams - -import io.github.wulkanowy.api.SnP -import io.github.wulkanowy.api.getDateAsTick -import io.github.wulkanowy.api.getFormattedDate -import org.jsoup.nodes.Element - -class Exams(private val snp: SnP) { - - fun getExams() = getExams("") - - fun getExams(start: String): List { - return snp.getSnPPageDocument("Sprawdziany.mvc/Terminarz?rodzajWidoku=2&data=" + getDateAsTick(start)) - .select(".mainContainer > div:not(.navigation)").map { - val date = getFormattedDate(it.selectFirst("h2")?.text()?.split(", ")?.last()?.trim()) - - it.select("article").mapIndexed { _, element -> getExam(element, date) } - }.flatten() - } - - private fun getExam(e: Element, date: String): ExamEntry { - val subjectAndGroup = snp.getRowDataChildValue(e, 1) - val groupAndClass = subjectAndGroup.split(" ").last() - val group = if (groupAndClass.contains("|")) groupAndClass.split("|").last() else "" - val teacherAndDate = snp.getRowDataChildValue(e, 4).split(", ") - val teacherSymbol = teacherAndDate.first().split(" ").last().removeSurrounding("[", "]") - val teacher = teacherAndDate.first().replace(" [$teacherSymbol]", "") - - return ExamEntry( - date = date, - entryDate = getFormattedDate(teacherAndDate.last()), - subject = subjectAndGroup.replace(groupAndClass, "").trim(), - group = group, - type = snp.getRowDataChildValue(e, 2), - description = snp.getRowDataChildValue(e, 3), - teacher = teacher, - teacherSymbol = teacherSymbol - ) - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/exams/ExamsWeek.java b/api/src/main/java/io/github/wulkanowy/api/exams/ExamsWeek.java deleted file mode 100644 index b15dbd44..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/exams/ExamsWeek.java +++ /dev/null @@ -1,74 +0,0 @@ -package io.github.wulkanowy.api.exams; - -import org.apache.commons.lang3.StringUtils; -import org.jsoup.nodes.Document; -import org.jsoup.nodes.Element; -import org.jsoup.select.Elements; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import io.github.wulkanowy.api.SnP; -import io.github.wulkanowy.api.VulcanException; -import io.github.wulkanowy.api.generic.Week; - -import static io.github.wulkanowy.api.DateTimeUtilsKt.getDateAsTick; -import static io.github.wulkanowy.api.DateTimeUtilsKt.getFormattedDate; - -@Deprecated -public class ExamsWeek { - - private static final String EXAMS_PAGE_URL = "Sprawdziany.mvc/Terminarz?rodzajWidoku=2&data="; - - private final SnP snp; - - public ExamsWeek(SnP snp) { - this.snp = snp; - } - - public Week getCurrent() throws IOException, VulcanException { - return getWeek("", true); - } - - public Week getWeek(String date, final boolean onlyNotEmpty) throws IOException, VulcanException { - Document examsPage = snp.getSnPPageDocument(EXAMS_PAGE_URL + getDateAsTick(date)); - Elements examsDays = examsPage.select(".mainContainer > div:not(.navigation)"); - - List days = new ArrayList<>(); - - for (Element item : examsDays) { - ExamDay day = new ExamDay(); - Element dayHeading = item.select("h2").first(); - - if (null == dayHeading && onlyNotEmpty) { - continue; - } - - if (null != dayHeading) { - String[] dateHeader = dayHeading.text().split(", "); - day.setDayName(StringUtils.capitalize(dateHeader[0])); - day.setDate(getFormattedDate(dateHeader[1])); - } - - Elements exams = item.select("article"); - for (Element e : exams) { - day.addExam(new Exam() - .setSubjectAndGroup(snp.getRowDataChildValue(e, 1)) - .setType(snp.getRowDataChildValue(e, 2)) - .setDescription(snp.getRowDataChildValue(e, 3)) - .setTeacher(snp.getRowDataChildValue(e, 4).split(", ")[0]) - .setEntryDate(getFormattedDate(snp.getRowDataChildValue(e, 4).split(", ")[1])) - ); - } - - days.add(day); - } - - - return new Week() - .setStartDayDate(getFormattedDate(examsPage.select(".mainContainer > h2") - .first().text().split(" ")[1])) - .setDays(days); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/generic/Day.java b/api/src/main/java/io/github/wulkanowy/api/generic/Day.java deleted file mode 100644 index 879f4108..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/generic/Day.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.github.wulkanowy.api.generic; - -import java.util.ArrayList; -import java.util.List; - -@Deprecated -public class Day { - - private List lessons = new ArrayList<>(); - - protected String date = ""; - - private String dayName = ""; - - public Lesson getLesson(int index) { - return lessons.get(index); - } - - public List getLessons() { - return lessons; - } - - public Day setLesson(Lesson lesson) { - this.lessons.add(lesson); - return this; - } - - public String getDate() { - return date; - } - - public Day setDate(String date) { - this.date = date; - return this; - } - - public String getDayName() { - return dayName; - } - - public Day setDayName(String dayName) { - this.dayName = dayName; - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/generic/Diary.java b/api/src/main/java/io/github/wulkanowy/api/generic/Diary.java deleted file mode 100644 index 5c7c8593..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/generic/Diary.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.github.wulkanowy.api.generic; - -public class Diary implements ParamItem { - - private String id = ""; - - private String name = ""; - - private boolean current = false; - - public String getId() { - return id; - } - - public Diary setId(String id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public Diary setName(String name) { - this.name = name; - return this; - } - - @Override - public boolean isCurrent() { - return current; - } - - public Diary setCurrent(boolean current) { - this.current = current; - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/generic/Lesson.java b/api/src/main/java/io/github/wulkanowy/api/generic/Lesson.java deleted file mode 100644 index f5270334..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/generic/Lesson.java +++ /dev/null @@ -1,242 +0,0 @@ -package io.github.wulkanowy.api.generic; - -@Deprecated -public class Lesson { - - private int number = 0; - - private String subject = ""; - - private String teacher = ""; - - private String room = ""; - - private String description = ""; - - private String groupName = ""; - - private String startTime = ""; - - private String endTime = ""; - - private String date = ""; - - private boolean isEmpty = false; - - private boolean isDivisionIntoGroups = false; - - private boolean isPlanning = false; - - private boolean isRealized = false; - - private boolean isMovedOrCanceled = false; - - private boolean isNewMovedInOrChanged = false; - - private boolean isNotExist = false; - - private boolean isPresence = false; - - private boolean isAbsenceUnexcused = false; - - private boolean isAbsenceExcused = false; - - private boolean isUnexcusedLateness = false; - - private boolean isAbsenceForSchoolReasons = false; - - private boolean isExcusedLateness = false; - - private boolean isExemption = false; - - public int getNumber() { - return number; - } - - public Lesson setNumber(int number) { - this.number = number; - return this; - } - - public String getSubject() { - return subject; - } - - public Lesson setSubject(String subject) { - this.subject = subject; - return this; - } - - public String getTeacher() { - return teacher; - } - - public Lesson setTeacher(String teacher) { - this.teacher = teacher; - return this; - } - - public String getRoom() { - return room; - } - - public Lesson setRoom(String room) { - this.room = room; - return this; - } - - public String getDescription() { - return description; - } - - public Lesson setDescription(String description) { - this.description = description; - return this; - } - - public String getGroupName() { - return groupName; - } - - public void setGroupName(String groupName) { - this.groupName = groupName; - } - - public String getStartTime() { - return startTime; - } - - public void setStartTime(String startTime) { - this.startTime = startTime; - } - - public String getEndTime() { - return endTime; - } - - public void setEndTime(String endTime) { - this.endTime = endTime; - } - - public String getDate() { - return date; - } - - public Lesson setDate(String date) { - this.date = date; - return this; - } - - public boolean isEmpty() { - return isEmpty; - } - - public Lesson setEmpty(boolean empty) { - isEmpty = empty; - return this; - } - - public boolean isDivisionIntoGroups() { - return isDivisionIntoGroups; - } - - public void setDivisionIntoGroups(boolean divisionIntoGroups) { - isDivisionIntoGroups = divisionIntoGroups; - } - - public boolean isPlanning() { - return isPlanning; - } - - public void setPlanning(boolean planning) { - isPlanning = planning; - } - - public boolean isRealized() { - return isRealized; - } - - public void setRealized(boolean realized) { - isRealized = realized; - } - - public boolean isMovedOrCanceled() { - return isMovedOrCanceled; - } - - public void setMovedOrCanceled(boolean movedOrCanceled) { - isMovedOrCanceled = movedOrCanceled; - } - - public boolean isNewMovedInOrChanged() { - return isNewMovedInOrChanged; - } - - public void setNewMovedInOrChanged(boolean newMovedInOrChanged) { - isNewMovedInOrChanged = newMovedInOrChanged; - } - - public boolean isNotExist() { - return isNotExist; - } - - public void setNotExist(boolean notExist) { - isNotExist = notExist; - } - - public boolean isPresence() { - return isPresence; - } - - public void setPresence(boolean presence) { - isPresence = presence; - } - - public boolean isAbsenceUnexcused() { - return isAbsenceUnexcused; - } - - public void setAbsenceUnexcused(boolean absenceUnexcused) { - isAbsenceUnexcused = absenceUnexcused; - } - - public boolean isAbsenceExcused() { - return isAbsenceExcused; - } - - public void setAbsenceExcused(boolean absenceExcused) { - isAbsenceExcused = absenceExcused; - } - - public boolean isUnexcusedLateness() { - return isUnexcusedLateness; - } - - public void setUnexcusedLateness(boolean unexcusedLateness) { - isUnexcusedLateness = unexcusedLateness; - } - - public boolean isAbsenceForSchoolReasons() { - return isAbsenceForSchoolReasons; - } - - public void setAbsenceForSchoolReasons(boolean absenceForSchoolReasons) { - isAbsenceForSchoolReasons = absenceForSchoolReasons; - } - - public boolean isExcusedLateness() { - return isExcusedLateness; - } - - public void setExcusedLateness(boolean excusedLateness) { - isExcusedLateness = excusedLateness; - } - - public boolean isExemption() { - return isExemption; - } - - public void setExemption(boolean exemption) { - isExemption = exemption; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/generic/Month.java b/api/src/main/java/io/github/wulkanowy/api/generic/Month.java deleted file mode 100644 index e38ef3a3..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/generic/Month.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.github.wulkanowy.api.generic; - -public class Month { - - private String name = ""; - - private int value = 0; - - public String getName() { - return name; - } - - public Month setName(String name) { - this.name = name; - return this; - } - - public int getValue() { - return value; - } - - public Month setValue(int value) { - this.value = value; - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/generic/ParamItem.java b/api/src/main/java/io/github/wulkanowy/api/generic/ParamItem.java deleted file mode 100644 index e7edfbf4..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/generic/ParamItem.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.github.wulkanowy.api.generic; - -public interface ParamItem { - - ParamItem setId(String id); - - ParamItem setName(String name); - - ParamItem setCurrent(boolean isCurrent); - - boolean isCurrent(); -} diff --git a/api/src/main/java/io/github/wulkanowy/api/generic/School.kt b/api/src/main/java/io/github/wulkanowy/api/generic/School.kt deleted file mode 100644 index c14fc5d2..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/generic/School.kt +++ /dev/null @@ -1,7 +0,0 @@ -package io.github.wulkanowy.api.generic - -data class School( - val name: String, - val id: String, - val current: Boolean -) diff --git a/api/src/main/java/io/github/wulkanowy/api/generic/Semester.java b/api/src/main/java/io/github/wulkanowy/api/generic/Semester.java deleted file mode 100644 index db4a724d..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/generic/Semester.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.github.wulkanowy.api.generic; - -public class Semester implements ParamItem { - - private String id = ""; - - private String name = ""; - - private boolean current = false; - - public String getId() { - return id; - } - - public Semester setId(String id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public Semester setName(String number) { - this.name = number; - return this; - } - - public boolean isCurrent() { - return current; - } - - public Semester setCurrent(boolean current) { - this.current = current; - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/generic/Student.java b/api/src/main/java/io/github/wulkanowy/api/generic/Student.java deleted file mode 100644 index 4ed5dd37..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/generic/Student.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.github.wulkanowy.api.generic; - -public class Student implements ParamItem { - - private String id = ""; - - private String name = ""; - - private boolean current = false; - - public String getId() { - return id; - } - - public Student setId(String id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public Student setName(String name) { - this.name = name; - return this; - } - - public boolean isCurrent() { - return current; - } - - public Student setCurrent(boolean current) { - this.current = current; - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/generic/Subject.java b/api/src/main/java/io/github/wulkanowy/api/generic/Subject.java deleted file mode 100644 index fcf27bef..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/generic/Subject.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.github.wulkanowy.api.generic; - -public class Subject { - - private int id = -1; - - private String name = ""; - - public int getId() { - return id; - } - - public Subject setId(int id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public Subject setName(String name) { - this.name = name; - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/generic/Week.java b/api/src/main/java/io/github/wulkanowy/api/generic/Week.java deleted file mode 100644 index 0a9fd8c8..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/generic/Week.java +++ /dev/null @@ -1,34 +0,0 @@ -package io.github.wulkanowy.api.generic; - -import java.util.ArrayList; -import java.util.List; - -@Deprecated -public class Week { - - private List days = new ArrayList<>(); - - private String startDayDate = ""; - - public T getDay(int index) { - return days.get(index); - } - - public List getDays() { - return days; - } - - public Week setDays(List days) { - this.days = days; - return this; - } - - public String getStartDayDate() { - return startDayDate; - } - - public Week setStartDayDate(String startDayDate) { - this.startDayDate = startDayDate; - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/grades/Grade.java b/api/src/main/java/io/github/wulkanowy/api/grades/Grade.java deleted file mode 100644 index a19207dc..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/grades/Grade.java +++ /dev/null @@ -1,101 +0,0 @@ -package io.github.wulkanowy.api.grades; - -@Deprecated -public class Grade { - - protected String value = ""; - - private String subject = ""; - - private String color = ""; - - private String symbol = ""; - - private String description = ""; - - private String weight = ""; - - private String date = ""; - - private String teacher = ""; - - public String getSubject() { - return subject; - } - - public Grade setSubject(String subject) { - this.subject = subject; - - return this; - } - - public String getValue() { - return value; - } - - public Grade setValue(String value) { - this.value = value; - - return this; - } - - public String getColor() { - return color; - } - - public Grade setColor(String color) { - this.color = color; - - return this; - } - - public String getSymbol() { - return symbol; - } - - public Grade setSymbol(String symbol) { - this.symbol = symbol; - - return this; - } - - public String getDescription() { - return description; - } - - public Grade setDescription(String description) { - this.description = description; - - return this; - } - - public String getWeight() { - return weight; - } - - public Grade setWeight(String weight) { - this.weight = weight; - - return this; - } - - public String getDate() { - return date; - } - - public Grade setDate(String date) { - this.date = date; - - return this; - } - - public String getTeacher() { - return teacher; - } - - public Grade setTeacher(String teacher) { - this.teacher = teacher; - - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/grades/GradeKt.kt b/api/src/main/java/io/github/wulkanowy/api/grades/GradeKt.kt deleted file mode 100644 index 29a4385f..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/grades/GradeKt.kt +++ /dev/null @@ -1,20 +0,0 @@ -package io.github.wulkanowy.api.grades - -data class GradeKt( - - val subject: String, - - val value: String, - - val color: String, - - val symbol: String, - - val description: String, - - val weight: String, - - val date: String, - - val teacher: String -) diff --git a/api/src/main/java/io/github/wulkanowy/api/grades/Grades.kt b/api/src/main/java/io/github/wulkanowy/api/grades/Grades.kt deleted file mode 100644 index 7595148d..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/grades/Grades.kt +++ /dev/null @@ -1,45 +0,0 @@ -package io.github.wulkanowy.api.grades - -import io.github.wulkanowy.api.SnP -import io.github.wulkanowy.api.getFormattedDate -import org.jsoup.nodes.Element -import java.util.regex.Pattern - -class Grades(private val snp: SnP) { - - private val colorPattern by lazy { Pattern.compile("#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})") } - - fun getGrades() = getGrades("") - - fun getGrades(semester: String): List { - return snp.getSnPPageDocument("Oceny/Wszystkie?details=2&okres=$semester") - .select(".ocenySzczegoly-table > tbody > tr").map { getGrade(it) }.filter { - it.value != "Brak ocen" - } - } - - private fun getGrade(e: Element): GradeKt { - val tds = e.select("td") - val symbol = tds[2].text().split(", ").first() - - return GradeKt( - subject = tds[0].text(), - value = tds[1].text(), - color = getColor(tds[1].select(".ocenaCzastkowa").attr("style")), - symbol = symbol, - description = tds[2].text().replaceFirst(symbol, "").replaceFirst(", ", ""), - weight = tds[3].text(), - date = getFormattedDate(tds[4].text()), - teacher = tds[5].text() - ) - } - - private fun getColor(styleAttr: String): String { - val matcher = colorPattern.matcher(styleAttr) - while (matcher.find()) { - return matcher.group(1) - } - - return "" - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/grades/GradesList.java b/api/src/main/java/io/github/wulkanowy/api/grades/GradesList.java deleted file mode 100644 index c79e5a97..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/grades/GradesList.java +++ /dev/null @@ -1,76 +0,0 @@ -package io.github.wulkanowy.api.grades; - -import org.jsoup.nodes.Document; -import org.jsoup.nodes.Element; -import org.jsoup.select.Elements; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import io.github.wulkanowy.api.SnP; -import io.github.wulkanowy.api.VulcanException; - -import static io.github.wulkanowy.api.DateTimeUtilsKt.getFormattedDate; - -@Deprecated -public class GradesList { - - private static final String GRADES_PAGE_URL = "Oceny/Wszystkie?details=2&okres="; - - private SnP snp; - - public GradesList(SnP snp) { - this.snp = snp; - } - - public List getAll(String semester) throws IOException, VulcanException { - Document gradesPage = snp.getSnPPageDocument(GRADES_PAGE_URL + semester); - Elements gradesRows = gradesPage.select(".ocenySzczegoly-table > tbody > tr"); - - List grades = new ArrayList<>(); - - for (Element row : gradesRows) { - if ("Brak ocen".equals(row.select("td:nth-child(2)").text())) { - continue; - } - - grades.add(getGrade(row)); - } - - return grades; - } - - private Grade getGrade(Element row) { - String descriptions = row.select("td:nth-child(3)").text(); - - String symbol = descriptions.split(", ")[0]; - String description = descriptions.replaceFirst(Pattern.quote(symbol), "").replaceFirst(", ", ""); - String color = getColor(row.select("td:nth-child(2) span.ocenaCzastkowa").attr("style")); - String date = getFormattedDate(row.select("td:nth-child(5)").text()); - - return new Grade() - .setSubject(row.select("td:nth-child(1)").text()) - .setValue(row.select("td:nth-child(2)").text()) - .setColor(color) - .setSymbol(symbol) - .setDescription(description) - .setWeight(row.select("td:nth-child(4)").text()) - .setDate(date) - .setTeacher(row.select("td:nth-child(6)").text()); - } - - private String getColor(String styleAttr) { - Pattern pattern = Pattern.compile("#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})"); - Matcher matcher = pattern.matcher(styleAttr); - - String color = ""; - while (matcher.find()) { - color = matcher.group(1); - } - - return color; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/grades/GradesSummary.kt b/api/src/main/java/io/github/wulkanowy/api/grades/GradesSummary.kt deleted file mode 100644 index 4ab3451f..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/grades/GradesSummary.kt +++ /dev/null @@ -1,22 +0,0 @@ -package io.github.wulkanowy.api.grades - -import io.github.wulkanowy.api.SnP - -class GradesSummary(private val snp: SnP) { - - fun getSummary() = getSummary("") - - fun getSummary(semester: String): List { - val subjects = snp.getSnPPageDocument("Oceny/Wszystkie?details=2&okres=$semester") - .select(".ocenyZwykle-table > tbody > tr") - - return subjects.map { - val tds = it.select("td") - Summary( - name = tds[0].text(), - predicted = tds[tds.size - 2].text(), - final = tds[tds.size - 1].text() - ) - } - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/grades/Subject.java b/api/src/main/java/io/github/wulkanowy/api/grades/Subject.java deleted file mode 100644 index 03036ab4..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/grades/Subject.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.github.wulkanowy.api.grades; - -@Deprecated -public class Subject { - - private String name; - - private String predictedRating; - - private String finalRating; - - public String getName() { - return name; - } - - public Subject setName(String name) { - this.name = name; - - return this; - } - - public String getPredictedRating() { - return predictedRating; - } - - public Subject setPredictedRating(String predictedRating) { - this.predictedRating = predictedRating; - - return this; - } - - public String getFinalRating() { - return finalRating; - } - - public Subject setFinalRating(String finalRating) { - this.finalRating = finalRating; - - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/grades/SubjectsList.java b/api/src/main/java/io/github/wulkanowy/api/grades/SubjectsList.java deleted file mode 100644 index e87e781e..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/grades/SubjectsList.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.github.wulkanowy.api.grades; - -import org.jsoup.nodes.Document; -import org.jsoup.nodes.Element; -import org.jsoup.select.Elements; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import io.github.wulkanowy.api.SnP; -import io.github.wulkanowy.api.VulcanException; - -@Deprecated -public class SubjectsList { - - private static final String SUBJECTS_PAGE_URL = "Oceny/Wszystkie?details=1&okres="; - - private SnP snp; - - public SubjectsList(SnP snp) { - this.snp = snp; - } - - - public List getAll() throws IOException, VulcanException { - return getAll(""); - } - - public List getAll(String semester) throws IOException, VulcanException { - Document subjectPage = snp.getSnPPageDocument(SUBJECTS_PAGE_URL + semester); - - Elements rows = subjectPage.select(".ocenyZwykle-table > tbody > tr"); - - List subjects = new ArrayList<>(); - - for (Element subjectRow : rows) { - subjects.add(new Subject() - .setName(subjectRow.select("td:nth-child(1)").text()) - .setPredictedRating(subjectRow.select("td:nth-last-child(2)").text()) - .setFinalRating(subjectRow.select("td:nth-last-child(1)").text()) - ); - } - - return subjects; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/grades/Summary.kt b/api/src/main/java/io/github/wulkanowy/api/grades/Summary.kt deleted file mode 100644 index 3cf12e7b..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/grades/Summary.kt +++ /dev/null @@ -1,10 +0,0 @@ -package io.github.wulkanowy.api.grades - -data class Summary( - - val name: String, - - val predicted: String, - - val final: String -) diff --git a/api/src/main/java/io/github/wulkanowy/api/homework/Homework.kt b/api/src/main/java/io/github/wulkanowy/api/homework/Homework.kt deleted file mode 100644 index 6c1cdac4..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/homework/Homework.kt +++ /dev/null @@ -1,16 +0,0 @@ -package io.github.wulkanowy.api.homework - -data class Homework( - - val date: String, - - val subject: String, - - val content: String, - - val teacher: String, - - val teacherSymbol: String, - - val entryDate: String -) diff --git a/api/src/main/java/io/github/wulkanowy/api/homework/HomeworkList.kt b/api/src/main/java/io/github/wulkanowy/api/homework/HomeworkList.kt deleted file mode 100644 index 1a6ea398..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/homework/HomeworkList.kt +++ /dev/null @@ -1,28 +0,0 @@ -package io.github.wulkanowy.api.homework - -import io.github.wulkanowy.api.SnP -import io.github.wulkanowy.api.getDateAsTick -import io.github.wulkanowy.api.getFormattedDate -import org.jsoup.nodes.Element - -class HomeworkList(private val snp: SnP) { - - fun getHomework(date: String = ""): List { - return snp.getSnPPageDocument("ZadaniaDomowe.mvc?data=${getDateAsTick(date)}&rodzajWidoku=Dzien") - .select(".mainContainer article").map { - getItem(it, date) - } - } - - private fun getItem(e: Element, date: String): Homework { - val teacherAndDate = snp.getRowDataChildValue(e, 3).split(", ") - return Homework( - date = date, - subject = snp.getRowDataChildValue(e, 1), - teacher = teacherAndDate.first().split(" [").first(), - teacherSymbol = teacherAndDate.first().split(" [").last().replace("]", ""), - content = snp.getRowDataChildValue(e, 2), - entryDate = getFormattedDate(teacherAndDate.last()) - ) - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/login/AccountPermissionException.java b/api/src/main/java/io/github/wulkanowy/api/login/AccountPermissionException.java deleted file mode 100644 index de3901ff..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/login/AccountPermissionException.java +++ /dev/null @@ -1,10 +0,0 @@ -package io.github.wulkanowy.api.login; - -import io.github.wulkanowy.api.VulcanException; - -public class AccountPermissionException extends VulcanException { - - AccountPermissionException(String message) { - super(message); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/login/BadCredentialsException.java b/api/src/main/java/io/github/wulkanowy/api/login/BadCredentialsException.java deleted file mode 100644 index 13efd4a1..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/login/BadCredentialsException.java +++ /dev/null @@ -1,10 +0,0 @@ -package io.github.wulkanowy.api.login; - -import io.github.wulkanowy.api.VulcanException; - -public class BadCredentialsException extends VulcanException { - - BadCredentialsException(String message) { - super(message); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/login/Login.java b/api/src/main/java/io/github/wulkanowy/api/login/Login.java deleted file mode 100644 index 443a9387..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/login/Login.java +++ /dev/null @@ -1,146 +0,0 @@ -package io.github.wulkanowy.api.login; - -import org.jsoup.Jsoup; -import org.jsoup.nodes.Document; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Parser; -import org.jsoup.select.Elements; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; - -import io.github.wulkanowy.api.Client; -import io.github.wulkanowy.api.NotLoggedInErrorException; -import io.github.wulkanowy.api.VulcanException; - -public class Login { - - protected static final String LOGIN_PAGE_URL = "{schema}://cufs.{host}/{symbol}/Account/LogOn"; - - private static final String LOGIN_PAGE_URL_QUERY = "?ReturnUrl=%2F{symbol}%2FFS%2FLS%3Fwa%3Dwsignin1.0%26wtrealm%3D" + - "{schema}%253a%252f%252fuonetplus.{host}%252f{symbol}%252fLoginEndpoint.aspx%26wctx%3D" + - "{schema}%253a%252f%252fuonetplus.{host}%252f{symbol}%252fLoginEndpoint.aspx"; - - private Client client; - - private static final Logger logger = LoggerFactory.getLogger(Login.class); - - public Login(Client client) { - this.client = client; - } - - public void login(String email, String password, String symbol) throws VulcanException, IOException { - Document certDoc = sendCredentials(email, password); - - if ("Błąd".equals(certDoc.title())) { - client.clearCookies(); - throw new NotLoggedInErrorException(certDoc.body().text()); - } - - sendCertificate(certDoc, symbol); - } - - Document sendCredentials(String email, String password) throws IOException, VulcanException { - String[][] credentials = new String[][]{ - {"LoginName", email}, - {"Password", password} - }; - - Document nextDoc = sendCredentialsData(credentials, LOGIN_PAGE_URL + LOGIN_PAGE_URL_QUERY.replace(":", "%253A")); - - Element errorMessage = nextDoc.selectFirst(".ErrorMessage, #ErrorTextLabel"); - if (null != errorMessage) { - throw new BadCredentialsException(errorMessage.text()); - } - - return nextDoc; - } - - private Document sendCredentialsData(String[][] credentials, String nextUrl) throws IOException, VulcanException { - Element formFirst = client.getPageByUrl(nextUrl, false).selectFirst("#form1"); - - if (null != formFirst) { // only on adfs login - Document formSecond = client.postPageByUrl( - formFirst.attr("abs:action"), - getFormStateParams(formFirst, "", "") - ); - credentials = getFormStateParams(formSecond, credentials[0][1], credentials[1][1]); - nextUrl = formSecond.selectFirst("#form1").attr("abs:action"); - } - - return client.postPageByUrl(nextUrl, credentials); - } - - private String[][] getFormStateParams(Element form, String email, String password) { - return new String[][]{ - {"__VIEWSTATE", form.select("#__VIEWSTATE").val()}, - {"__VIEWSTATEGENERATOR", form.select("#__VIEWSTATEGENERATOR").val()}, - {"__EVENTVALIDATION", form.select("#__EVENTVALIDATION").val()}, - {"__db", form.select("input[name=__db]").val()}, - {"PassiveSignInButton.x", "0"}, - {"PassiveSignInButton.y", "0"}, - {"SubmitButton.x", "0"}, - {"SubmitButton.y", "0"}, - {"UsernameTextBox", email}, - {"PasswordTextBox", password}, - }; - } - - void sendCertificate(Document doc, String defaultSymbol) throws IOException, VulcanException { - client.setSymbol(findSymbol(defaultSymbol, doc.select("input[name=wresult]").val())); - - Document targetDoc = sendCertData(doc); - String title = targetDoc.title(); - - if ("Working...".equals(title)) { // on adfs login - logger.info("ADFS login"); - title = sendCertData(targetDoc).title(); - } - - if ("Logowanie".equals(title)) { - throw new AccountPermissionException("No account access. Try another symbol"); - } - - if (!"Uonet+".equals(title)) { - logger.debug("Login failed. Body: {}", targetDoc.body()); - throw new LoginErrorException("Expected page title `UONET+`, got " + title); - } - - client.setSchools(new StartPage(client).getSchools(targetDoc)); - } - - private Document sendCertData(Document doc) throws IOException, VulcanException { - String url = doc.select("form[name=hiddenform]").attr("action"); - - return client.postPageByUrl(url.replaceFirst("Default", "{symbol}"), new String[][]{ - {"wa", "wsignin1.0"}, - {"wresult", doc.select("input[name=wresult]").val()}, - {"wctx", doc.select("input[name=wctx]").val()} - }); - } - - private String findSymbol(String symbol, String certificate) throws AccountPermissionException { - if ("Default".equals(symbol)) { - return findSymbolInCertificate(certificate); - } - - return symbol; - } - - String findSymbolInCertificate(String certificate) throws AccountPermissionException { - Elements instances = Jsoup - .parse(certificate.replaceAll(":", ""), "", Parser.xmlParser()) - .select("[AttributeName=\"UserInstance\"] samlAttributeValue"); - - if (instances.isEmpty()) { // on adfs login - return ""; - } - - if (instances.size() < 2) { // 1st index is always `Default` - throw new AccountPermissionException("First login detected, specify symbol"); - } - - return instances.get(1).text(); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/login/LoginErrorException.java b/api/src/main/java/io/github/wulkanowy/api/login/LoginErrorException.java deleted file mode 100644 index be7439df..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/login/LoginErrorException.java +++ /dev/null @@ -1,10 +0,0 @@ -package io.github.wulkanowy.api.login; - -import io.github.wulkanowy.api.NotLoggedInErrorException; - -class LoginErrorException extends NotLoggedInErrorException { - - LoginErrorException(String message) { - super(message); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/login/StartPage.kt b/api/src/main/java/io/github/wulkanowy/api/login/StartPage.kt deleted file mode 100644 index 6f6b1490..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/login/StartPage.kt +++ /dev/null @@ -1,45 +0,0 @@ -package io.github.wulkanowy.api.login - -import io.github.wulkanowy.api.Client -import io.github.wulkanowy.api.VulcanException -import io.github.wulkanowy.api.generic.School -import org.jsoup.nodes.Document -import org.slf4j.LoggerFactory - -class StartPage(val client: Client) { - - private val logger = LoggerFactory.getLogger(StartPage::class.java) - - fun getSchools(startPage: Document): MutableList { - val schoolList = mutableListOf() - - val snpLinks = startPage.select(".panel.linkownia.pracownik.klient a") - - logger.debug("SnP links: {}", snpLinks.size) - - if (snpLinks.isEmpty()) { - throw VulcanException("Na pewno używasz konta z dostępem do Witryny ucznia i rodzica?") - } - - snpLinks.map { - schoolList.add(School( - it.text(), - getExtractedIdFromUrl(it.attr("href")), - it == snpLinks.first() - )) - } - - return schoolList - } - - internal fun getExtractedIdFromUrl(snpPageUrl: String): String { - val path = snpPageUrl.split(client.host).getOrNull(1)?.split("/") - - if (6 != path?.size) { - logger.error("Expected snp url, got {}", snpPageUrl) - throw VulcanException("Na pewno używasz konta z dostępem do Witryny ucznia i rodzica?") - } - - return path[2] - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/messages/BadRequestException.java b/api/src/main/java/io/github/wulkanowy/api/messages/BadRequestException.java deleted file mode 100644 index 14dca67b..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/messages/BadRequestException.java +++ /dev/null @@ -1,10 +0,0 @@ -package io.github.wulkanowy.api.messages; - -import io.github.wulkanowy.api.VulcanException; - -class BadRequestException extends VulcanException { - - BadRequestException(String message) { - super(message); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/messages/Message.java b/api/src/main/java/io/github/wulkanowy/api/messages/Message.java deleted file mode 100644 index 331ec819..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/messages/Message.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.github.wulkanowy.api.messages; - -import com.google.gson.annotations.SerializedName; - -public class Message { - - @SerializedName("Nieprzeczytana") - public boolean unread; - - @SerializedName("Data") - public String date; - - @SerializedName("Tresc") - public String content; - - @SerializedName("Temat") - public String subject; - - @SerializedName("NadawcaNazwa") - public String sender; - - @SerializedName("IdWiadomosci") - public int messageID; - - @SerializedName("IdNadawca") - public int senderID; - - @SerializedName("Id") - public int id; -} diff --git a/api/src/main/java/io/github/wulkanowy/api/messages/Messages.java b/api/src/main/java/io/github/wulkanowy/api/messages/Messages.java deleted file mode 100644 index ec2a3fba..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/messages/Messages.java +++ /dev/null @@ -1,99 +0,0 @@ -package io.github.wulkanowy.api.messages; - -import com.google.gson.Gson; -import com.google.gson.JsonParseException; - -import java.io.IOException; -import java.util.List; - -import io.github.wulkanowy.api.Client; -import io.github.wulkanowy.api.NotLoggedInErrorException; -import io.github.wulkanowy.api.VulcanException; - -public class Messages { - - private static final String BASE_URL = "{schema}://uonetplus-uzytkownik.{host}/{symbol}/"; - - private static final String LIST_BASE_URL = BASE_URL + "Wiadomosc.mvc/"; - - private static final String RECEIVED_URL = LIST_BASE_URL + "GetWiadomosciOdebrane"; - - private static final String SENT_URL = LIST_BASE_URL + "GetWiadomosciWyslane"; - - private static final String DELETED_URL = LIST_BASE_URL + "GetWiadomosciUsuniete"; - - private static final String MESSAGE_URL = LIST_BASE_URL + "GetTrescWiadomosci"; - - public static final int RECEIVED_FOLDER = 1; - - public static final int SENT_FOLDER = 2; - - public static final int DELETED_FOLDER = 3; - - private static final String ERROR_TITLE = "Błąd strony"; - - private Client client; - - public Messages(Client client) { - this.client = client; - } - - public List getReceived() throws IOException, VulcanException { - return getMessages(RECEIVED_URL); - } - - public List getSent() throws IOException, VulcanException { - return getMessages(SENT_URL); - } - - public List getDeleted() throws IOException, VulcanException { - return getMessages(DELETED_URL); - } - - private List getMessages(String url) throws IOException, VulcanException { - String res = client.getJsonStringByUrl(url); - - List messages; - - try { - messages = new Gson().fromJson(res, MessagesContainer.class).data; - } catch (JsonParseException e) { - if (res.contains(ERROR_TITLE)) { - throw new BadRequestException(ERROR_TITLE); - } - - throw new NotLoggedInErrorException("You are probably not logged in"); - } - - return messages; - } - - public Message getMessage(int id, int folder) throws IOException, VulcanException { - String res = client.postJsonStringByUrl(MESSAGE_URL, new String[][]{ - {"idWiadomosc", String.valueOf(id)}, - {"Folder", String.valueOf(folder)} - }); - - Message message; - - try { - message = new Gson().fromJson(res, MessageContainer.class).data; - } catch (JsonParseException e) { - if (res.contains(ERROR_TITLE)) { - throw new BadRequestException(ERROR_TITLE); - } - - throw new NotLoggedInErrorException("You are probably not logged in. Force login"); - } - - return message; - } - - private static class MessagesContainer { - private List data; - } - - private static class MessageContainer { - private Message data; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/mobile/RegisterDevice.kt b/api/src/main/java/io/github/wulkanowy/api/mobile/RegisterDevice.kt deleted file mode 100644 index f0da01e9..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/mobile/RegisterDevice.kt +++ /dev/null @@ -1,33 +0,0 @@ -package io.github.wulkanowy.api.mobile - -import io.github.wulkanowy.api.SnP -import org.jsoup.nodes.Element - -class RegisterDevice(private val snp: SnP) { - - companion object { - const val REGISTER_URL = "DostepMobilny.mvc/Rejestruj" - } - - data class Token( - val token: String, - val symbol: String, - val pin: String - ) - - fun getToken(): Token { - val form = snp.getSnPPageDocument(REGISTER_URL).selectFirst("#rejestracja-formularz") - - val fields = form.select(".blockElement") - - return Token( - getValue(fields[1]), - getValue(fields[2]), - getValue(fields[3]) - ) - } - - fun getValue(e: Element): String { - return e.text().split(":")[1].trim() - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/mobile/RegisteredDevices.kt b/api/src/main/java/io/github/wulkanowy/api/mobile/RegisteredDevices.kt deleted file mode 100644 index d622b4de..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/mobile/RegisteredDevices.kt +++ /dev/null @@ -1,38 +0,0 @@ -package io.github.wulkanowy.api.mobile - -import io.github.wulkanowy.api.SnP -import io.github.wulkanowy.api.getFormattedDate - -class RegisteredDevices(private val snp: SnP) { - - companion object { - const val DEVICES_LIST_URL = "DostepMobilny.mvc" - } - - data class Device( - val name: String, - val system: String, - val date: String, - val id: Int - ) - - fun getList(): List { - val items = snp.getSnPPageDocument(DEVICES_LIST_URL).select("table tbody tr") - val devices: MutableList = mutableListOf() - - for (item in items) { - val cells = item.select("td") - val system = cells[0].text().split("(").last().removeSuffix(")") - - devices.add(Device( - cells[0].text().replace(" ($system)", ""), - system, - getFormattedDate(cells[1].text(), "dd.MM.yyyy 'godz:' HH:mm:ss", "yyyy-MM-dd HH:mm:ss"), - cells[2].select("a").attr("href") - .split("/").last().toInt() - )) - } - - return devices - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/notes/AchievementsList.java b/api/src/main/java/io/github/wulkanowy/api/notes/AchievementsList.java deleted file mode 100644 index 346df832..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/notes/AchievementsList.java +++ /dev/null @@ -1,36 +0,0 @@ -package io.github.wulkanowy.api.notes; - -import org.jsoup.nodes.Element; -import org.jsoup.select.Elements; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import io.github.wulkanowy.api.SnP; -import io.github.wulkanowy.api.VulcanException; - -public class AchievementsList { - - private static final String NOTES_PAGE_URL = "UwagiOsiagniecia.mvc/Wszystkie"; - - private SnP snp; - - public AchievementsList(SnP snp) { - this.snp = snp; - } - - public List getAllAchievements() throws IOException, VulcanException { - Element pageFragment = snp.getSnPPageDocument(NOTES_PAGE_URL) - .select(".mainContainer > div").get(1); - Elements items = pageFragment.select("article"); - - List achievements = new ArrayList<>(); - - for (Element item : items) { - achievements.add(item.text()); - } - - return achievements; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/notes/Note.java b/api/src/main/java/io/github/wulkanowy/api/notes/Note.java deleted file mode 100644 index b1fa68b9..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/notes/Note.java +++ /dev/null @@ -1,48 +0,0 @@ -package io.github.wulkanowy.api.notes; - -public class Note { - - private String date; - - private String teacher; - - private String category; - - private String content; - - public String getDate() { - return date; - } - - public Note setDate(String date) { - this.date = date; - return this; - } - - public String getTeacher() { - return teacher; - } - - public Note setTeacher(String teacher) { - this.teacher = teacher; - return this; - } - - public String getCategory() { - return category; - } - - public Note setCategory(String category) { - this.category = category; - return this; - } - - public String getContent() { - return content; - } - - public Note setContent(String content) { - this.content = content; - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/notes/NotesList.java b/api/src/main/java/io/github/wulkanowy/api/notes/NotesList.java deleted file mode 100644 index 54f57edf..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/notes/NotesList.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.github.wulkanowy.api.notes; - -import org.jsoup.nodes.Element; -import org.jsoup.select.Elements; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import io.github.wulkanowy.api.SnP; -import io.github.wulkanowy.api.VulcanException; - -import static io.github.wulkanowy.api.DateTimeUtilsKt.getFormattedDate; - -public class NotesList { - - private static final String NOTES_PAGE_URL = "UwagiOsiagniecia.mvc/Wszystkie"; - - private SnP snp; - - public NotesList(SnP snp) { - this.snp = snp; - } - - public List getAllNotes() throws IOException, VulcanException { - Element pageFragment = snp.getSnPPageDocument(NOTES_PAGE_URL) - .select(".mainContainer > div").get(0); - Elements items = pageFragment.select("article"); - Elements dates = pageFragment.select("h2"); - - List notes = new ArrayList<>(); - - int index = 0; - for (Element item : items) { - notes.add(new Note() - .setDate(getFormattedDate(dates.get(index++).text())) - .setTeacher(snp.getRowDataChildValue(item, 1)) - .setCategory(snp.getRowDataChildValue(item, 2)) - .setContent(snp.getRowDataChildValue(item, 3)) - ); - } - - return notes; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/school/SchoolData.java b/api/src/main/java/io/github/wulkanowy/api/school/SchoolData.java deleted file mode 100644 index f135163a..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/school/SchoolData.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.github.wulkanowy.api.school; - -public class SchoolData { - - private String name = ""; - - private String address = ""; - - private String phoneNumber = ""; - - private String headmaster = ""; - - private String[] pedagogue; - - public String getName() { - return name; - } - - public SchoolData setName(String name) { - this.name = name; - return this; - } - - public String getAddress() { - return address; - } - - public SchoolData setAddress(String address) { - this.address = address; - return this; - } - - public String getPhoneNumber() { - return phoneNumber; - } - - public SchoolData setPhoneNumber(String phoneNumber) { - this.phoneNumber = phoneNumber; - return this; - } - - public String getHeadmaster() { - return headmaster; - } - - public SchoolData setHeadmaster(String headmaster) { - this.headmaster = headmaster; - return this; - } - - public String[] getPedagogues() { - return pedagogue; - } - - public SchoolData setPedagogue(String[] pedagogue) { - this.pedagogue = pedagogue; - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/school/SchoolInfo.java b/api/src/main/java/io/github/wulkanowy/api/school/SchoolInfo.java deleted file mode 100644 index f0dcd43d..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/school/SchoolInfo.java +++ /dev/null @@ -1,31 +0,0 @@ -package io.github.wulkanowy.api.school; - -import org.jsoup.nodes.Element; - -import java.io.IOException; - -import io.github.wulkanowy.api.SnP; -import io.github.wulkanowy.api.VulcanException; - -public class SchoolInfo { - - private static final String SCHOOL_PAGE_URL = "Szkola.mvc/Nauczyciele"; - - private SnP snp; - - public SchoolInfo(SnP snp) { - this.snp = snp; - } - - public SchoolData getSchoolData() throws IOException, VulcanException { - Element e = snp.getSnPPageDocument(SCHOOL_PAGE_URL) - .select(".mainContainer > article").get(0); - - return new SchoolData() - .setName(snp.getRowDataChildValue(e, 1)) - .setAddress(snp.getRowDataChildValue(e, 2)) - .setPhoneNumber(snp.getRowDataChildValue(e, 3)) - .setHeadmaster(snp.getRowDataChildValue(e, 4)) - .setPedagogue(snp.getRowDataChildValue(e, 5).split(", ")); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/school/Subject.java b/api/src/main/java/io/github/wulkanowy/api/school/Subject.java deleted file mode 100644 index 0a3c0957..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/school/Subject.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.github.wulkanowy.api.school; - -public class Subject { - - private String name = ""; - - private String[] teachers; - - public String getName() { - return name; - } - - public Subject setName(String name) { - this.name = name; - return this; - } - - public String[] getTeachers() { - return teachers; - } - - public Subject setTeachers(String[] teachers) { - this.teachers = teachers; - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/school/TeachersData.java b/api/src/main/java/io/github/wulkanowy/api/school/TeachersData.java deleted file mode 100644 index 7d41162e..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/school/TeachersData.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.github.wulkanowy.api.school; - -import java.util.List; - -public class TeachersData { - - private String className = ""; - - private String[] classTeacher; - - private List subjects; - - public String getClassName() { - return className; - } - - public TeachersData setClassName(String className) { - this.className = className; - return this; - } - - public String[] getClassTeacher() { - return classTeacher; - } - - public TeachersData setClassTeacher(String[] classTeacher) { - this.classTeacher = classTeacher; - return this; - } - - public List getSubjects() { - return subjects; - } - - public TeachersData setSubjects(List subjects) { - this.subjects = subjects; - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/school/TeachersInfo.java b/api/src/main/java/io/github/wulkanowy/api/school/TeachersInfo.java deleted file mode 100644 index ec8429bd..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/school/TeachersInfo.java +++ /dev/null @@ -1,43 +0,0 @@ -package io.github.wulkanowy.api.school; - -import org.jsoup.nodes.Document; -import org.jsoup.nodes.Element; -import org.jsoup.select.Elements; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import io.github.wulkanowy.api.SnP; -import io.github.wulkanowy.api.VulcanException; - -public class TeachersInfo { - - private static final String SCHOOL_PAGE_URL = "Szkola.mvc/Nauczyciele"; - - private SnP snp; - - public TeachersInfo(SnP snp) { - this.snp = snp; - } - - public TeachersData getTeachersData() throws IOException, VulcanException { - Document doc = snp.getSnPPageDocument(SCHOOL_PAGE_URL); - Elements rows = doc.select(".mainContainer > table tbody tr"); - String description = doc.select(".mainContainer > p").first().text(); - - List subjects = new ArrayList<>(); - - for (Element subject : rows) { - subjects.add(new Subject() - .setName(subject.select("td").get(1).text()) - .setTeachers(subject.select("td").get(2).text().split(", ")) - ); - } - - return new TeachersData() - .setClassName(description.split(", ")[0].split(": ")[1].trim()) - .setClassTeacher(description.split("Wychowawcy:")[1].trim().split(", ")) - .setSubjects(subjects); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/timetable/LessonTypes.java b/api/src/main/java/io/github/wulkanowy/api/timetable/LessonTypes.java deleted file mode 100644 index e98ef2b2..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/timetable/LessonTypes.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.github.wulkanowy.api.timetable; - -@Deprecated -class LessonTypes { - - static final String CLASS_PLANNING = "x-treelabel-ppl"; - - static final String CLASS_REALIZED = "x-treelabel-rlz"; - - static final String CLASS_MOVED_OR_CANCELED = "x-treelabel-inv"; - - static final String CLASS_NEW_MOVED_IN_OR_CHANGED = "x-treelabel-zas"; - - private LessonTypes() { - throw new IllegalStateException("Utility class"); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/timetable/Timetable.java b/api/src/main/java/io/github/wulkanowy/api/timetable/Timetable.java deleted file mode 100644 index d0c9109e..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/timetable/Timetable.java +++ /dev/null @@ -1,244 +0,0 @@ -package io.github.wulkanowy.api.timetable; - -import org.apache.commons.lang3.StringUtils; -import org.jsoup.nodes.Element; -import org.jsoup.select.Elements; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import io.github.wulkanowy.api.SnP; -import io.github.wulkanowy.api.VulcanException; -import io.github.wulkanowy.api.generic.Lesson; -import io.github.wulkanowy.api.generic.Week; - -import static io.github.wulkanowy.api.DateTimeUtilsKt.getDateAsTick; -import static io.github.wulkanowy.api.DateTimeUtilsKt.getFormattedDate; - -@Deprecated -public class Timetable { - - private static final String TIMETABLE_PAGE_URL = "Lekcja.mvc/PlanZajec?data="; - - private SnP snp; - - private static final Logger logger = LoggerFactory.getLogger(Timetable.class); - - public Timetable(SnP snp) { - this.snp = snp; - } - - public Week getWeekTable() throws IOException, VulcanException { - return getWeekTable(""); - } - - public Week getWeekTable(final String date) throws IOException, VulcanException { - Element table = snp.getSnPPageDocument(TIMETABLE_PAGE_URL + getDateAsTick(date)) - .select(".mainContainer .presentData").first(); - - List days = getDays(table.select("thead th")); - - setLessonToDays(table, days); - - return new Week() - .setStartDayDate(days.get(0).getDate()) - .setDays(days); - } - - private List getDays(Elements tableHeaderCells) { - List days = new ArrayList<>(); - int numberOfDays = tableHeaderCells.size(); - - if (numberOfDays > 7) { - logger.info("Number of days: {}", numberOfDays); - } - - for (int i = 2; i < numberOfDays; i++) { - String[] dayHeaderCell = tableHeaderCells.get(i).html().split("
"); - - TimetableDay day = new TimetableDay(); - day.setDayName(dayHeaderCell[0]); - day.setDate(getFormattedDate(dayHeaderCell[1].trim())); - - if (tableHeaderCells.get(i).hasClass("free-day")) { - day.setFreeDay(true); - day.setFreeDayName(dayHeaderCell[2]); - } - - days.add(day); - } - - return days; - } - - private void setLessonToDays(Element table, List days) { - for (Element row : table.select("tbody tr")) { - Elements hours = row.select("td"); - - // fill hours in day - for (int i = 2; i < hours.size(); i++) { - Lesson lesson = new Lesson(); - - String[] startEndEnd = hours.get(1).text().split(" "); - lesson.setStartTime(startEndEnd[0]); - lesson.setEndTime(startEndEnd[1]); - lesson.setDate(days.get(i - 2).getDate()); - lesson.setNumber(Integer.valueOf(hours.get(0).text())); - - addLessonDetails(lesson, hours.get(i).select("div")); - - days.get(i - 2).setLesson(lesson); - } - } - } - - private void addLessonDetails(Lesson lesson, Elements e) { - moveWarningToLessonNode(e); - - switch (e.size()) { - case 1: - addLessonInfoFromElement(lesson, e.first()); - break; - case 2: - Element span = e.last().selectFirst("span"); - if (null == span) { - addLessonInfoFromElement(lesson, e.first()); - } else if (span.hasClass(LessonTypes.CLASS_MOVED_OR_CANCELED)) { - lesson.setNewMovedInOrChanged(true); - lesson.setDescription("poprzednio: " + getLessonAndGroupInfoFromSpan(span)[0]); - addLessonInfoFromElement(lesson, e.first()); - } else { - addLessonInfoFromElement(lesson, e.last()); - } - break; - case 3: - addLessonInfoFromElement(lesson, e.get(1)); - break; - default: - lesson.setEmpty(true); - break; - } - } - - private void moveWarningToLessonNode(Elements e) { - Elements warn = e.select(".uwaga-panel"); - - if (!warn.isEmpty()) { - e.select("span").last() - .addClass("x-treelabel-rlz") - .text(warn.text()); - e.remove(1); - } - } - - private void addLessonInfoFromElement(Lesson lesson, Element e) { - Elements spans = e.select("span"); - - if (spans.isEmpty()) { - logger.warn("Lesson span is empty"); - return; - } - - addTypeInfo(lesson, spans); - addNormalLessonInfo(lesson, spans); - addChangesInfo(lesson, spans); - addGroupLessonInfo(lesson, spans); - } - - private void addTypeInfo(Lesson lesson, Elements spans) { - if (spans.first().hasClass(LessonTypes.CLASS_PLANNING)) { - lesson.setPlanning(true); - } - - if (spans.first().hasClass(LessonTypes.CLASS_MOVED_OR_CANCELED)) { - lesson.setMovedOrCanceled(true); - } - - if (spans.first().hasClass(LessonTypes.CLASS_NEW_MOVED_IN_OR_CHANGED)) { - lesson.setNewMovedInOrChanged(true); - } - - if (spans.last().hasClass(LessonTypes.CLASS_REALIZED) || "".equals(spans.first().attr("class"))) { - lesson.setRealized(true); - } - } - - private void addNormalLessonInfo(Lesson lesson, Elements spans) { - if (3 == spans.size()) { - lesson.setSubject(spans.get(0).text()); - lesson.setTeacher(spans.get(1).text()); - lesson.setRoom(spans.get(2).text()); - } - } - - private void addChangesInfo(Lesson lesson, Elements spans) { - if (!spans.last().hasClass(LessonTypes.CLASS_REALIZED)) { - return; - } - - if (7 == spans.size()) { - lesson.setSubject(spans.get(3).text()); - lesson.setTeacher(spans.get(4).text()); - lesson.setRoom(spans.get(5).text()); - lesson.setMovedOrCanceled(false); - lesson.setNewMovedInOrChanged(true); - lesson.setDescription(StringUtils.defaultString(StringUtils.substringBetween( - spans.last().text(), "(", ")"), spans.last().text()) - + " (poprzednio: " + spans.get(0).text() + ")"); - } else if (9 == spans.size()) { - String[] subjectAndGroupInfo = getLessonAndGroupInfoFromSpan(spans.get(4)); - lesson.setSubject(subjectAndGroupInfo[0]); - lesson.setGroupName(subjectAndGroupInfo[1]); - lesson.setTeacher(spans.get(6).text()); - lesson.setRoom(spans.get(7).text()); - lesson.setMovedOrCanceled(false); - lesson.setNewMovedInOrChanged(true); - lesson.setDivisionIntoGroups(true); - lesson.setDescription(StringUtils.defaultString(StringUtils.substringBetween( - spans.last().text(), "(", ")"), spans.last().text()) - + " (poprzednio: " + getLessonAndGroupInfoFromSpan(spans.get(0))[0] + ")"); - } else if (4 <= spans.size()) { - lesson.setSubject(spans.get(0).text()); - lesson.setTeacher(spans.get(1).text()); - lesson.setRoom(spans.get(2).text()); - lesson.setDescription(StringUtils.defaultString(StringUtils.substringBetween( - spans.last().text(), "(", ")"), spans.last().text())); - } - } - - private void addGroupLessonInfo(Lesson lesson, Elements spans) { - if (4 == spans.size() && !spans.last().hasClass(LessonTypes.CLASS_REALIZED)) { - lesson.setRoom(spans.last().text()); - } - - if ((4 == spans.size() && !spans.last().hasClass(LessonTypes.CLASS_REALIZED) || 5 == spans.size())) { - String[] subjectAndGroupInfo = getLessonAndGroupInfoFromSpan(spans.get(0)); - lesson.setSubject(subjectAndGroupInfo[0]); - lesson.setGroupName(subjectAndGroupInfo[1]); - lesson.setTeacher(spans.get(2).text()); - lesson.setDivisionIntoGroups(true); - } - - if (5 == spans.size()) { - lesson.setRoom(spans.get(3).text()); - } - } - - private String[] getLessonAndGroupInfoFromSpan(Element span) { - if (!span.text().contains("[")) { - return new String[] {span.text(), ""}; - } - - String[] subjectNameArray = span.text().split(" "); - String groupName = subjectNameArray[subjectNameArray.length - 1]; - - return new String[]{ - span.text().replace(" " + groupName, ""), - StringUtils.defaultString(StringUtils.substringBetween( - groupName, "[", "]"), groupName) - }; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/timetable/TimetableDay.java b/api/src/main/java/io/github/wulkanowy/api/timetable/TimetableDay.java deleted file mode 100644 index 58380476..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/timetable/TimetableDay.java +++ /dev/null @@ -1,27 +0,0 @@ -package io.github.wulkanowy.api.timetable; - -import io.github.wulkanowy.api.generic.Day; - -@Deprecated -public class TimetableDay extends Day { - - private boolean isFreeDay = false; - - private String freeDayName = ""; - - public boolean isFreeDay() { - return isFreeDay; - } - - public void setFreeDay(boolean freeDay) { - isFreeDay = freeDay; - } - - public String getFreeDayName() { - return freeDayName; - } - - public void setFreeDayName(String freeDayName) { - this.freeDayName = freeDayName; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/timetable/TimetableKt.kt b/api/src/main/java/io/github/wulkanowy/api/timetable/TimetableKt.kt deleted file mode 100644 index 04a16fb8..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/timetable/TimetableKt.kt +++ /dev/null @@ -1,201 +0,0 @@ -package io.github.wulkanowy.api.timetable - -import io.github.wulkanowy.api.SnP -import io.github.wulkanowy.api.getDateAsTick -import io.github.wulkanowy.api.getFormattedDate -import org.apache.commons.lang3.StringUtils -import org.jsoup.nodes.Element -import org.jsoup.select.Elements - -class TimetableKt(private val snp: SnP) { - - fun getTimetable() = getTimetable("") - - fun getTimetable(start: String): List { - val table = snp.getSnPPageDocument("Lekcja.mvc/PlanZajec?data=" + getDateAsTick(start)) - .select(".mainContainer .presentData").first() - - val days = getDays(table.select("thead th")) - - return table.select("tbody tr").map { - val hours = it.select("td") - hours.drop(2).mapIndexed { i, item -> - getLesson(item, days[i], hours[1].text().split(" "), hours[0].text().toInt()) - } - }.flatten().sortedBy { - it.date - }.filter { - it.subject.isNotBlank() - } - } - - private fun getDays(el: Elements): List> { - return el.drop(2).map { - val info = it.html().split("
") - - Pair(getFormattedDate(info[1].trim()), info.getOrElse(2) { "" }.trim()) - } - } - - private fun getLesson(cell: Element, day: Pair, hours: List, number: Int): TimetableLesson { - val lesson = TimetableLesson( - number = number, - date = day.first, - freeDayName = day.second, - startTime = hours[0], - endTime = hours[1] - ) - - addLessonDetails(lesson, cell.select("div")) - - return lesson - } - - private fun addLessonDetails(lesson: TimetableLesson, e: Elements) { - moveWarningToLessonNode(e) - - when (e.size) { - 1 -> addLessonInfoFromElement(lesson, e.first()) - 2 -> { - val span = e.last().selectFirst("span") - when { - null == span -> addLessonInfoFromElement(lesson, e.first()) - span.hasClass(Types.CLASS_MOVED_OR_CANCELED) -> { - lesson.newMovedInOrChanged = true - lesson.description = "poprzednio: " + getLessonAndGroupInfoFromSpan(span)[0] - addLessonInfoFromElement(lesson, e.first()) - } - else -> addLessonInfoFromElement(lesson, e.last()) - } - } - 3 -> addLessonInfoFromElement(lesson, e[1]) - else -> lesson.empty = true - } - } - - private fun moveWarningToLessonNode(e: Elements) { - val warn = e.select(".uwaga-panel") - - if (!warn.isEmpty()) { - e.select("span").last() - .addClass("x-treelabel-rlz") - .text(warn.text()) - e.removeAt(1) - } - } - - private fun addLessonInfoFromElement(lesson: TimetableLesson, e: Element) { - val spans = e.select("span") - - if (spans.isEmpty()) { - return - } - - addTypeInfo(lesson, spans) - addNormalLessonInfo(lesson, spans) - addChangesInfo(lesson, spans) - addGroupLessonInfo(lesson, spans) - } - - private fun addTypeInfo(lesson: TimetableLesson, spans: Elements) { - if (spans.first().hasClass(Types.CLASS_PLANNING)) { - lesson.planning = true - } - - if (spans.first().hasClass(Types.CLASS_MOVED_OR_CANCELED)) { - lesson.movedOrCanceled = true - } - - if (spans.first().hasClass(Types.CLASS_NEW_MOVED_IN_OR_CHANGED)) { - lesson.newMovedInOrChanged = true - } - - if (spans.last().hasClass(Types.CLASS_REALIZED) || "" == spans.first().attr("class")) { - lesson.realized = true - } - } - - private fun addNormalLessonInfo(lesson: TimetableLesson, spans: Elements) { - if (3 == spans.size) { - lesson.subject = spans[0].text() - lesson.teacher = spans[1].text() - lesson.room = spans[2].text() - } - } - - private fun addChangesInfo(lesson: TimetableLesson, spans: Elements) { - if (!spans.last().hasClass(Types.CLASS_REALIZED)) { - return - } - - when { - 7 == spans.size -> { - lesson.subject = spans[3].text() - lesson.teacher = spans[4].text() - lesson.room = spans[5].text() - lesson.movedOrCanceled = false - lesson.newMovedInOrChanged = true - lesson.description = (StringUtils.defaultString(StringUtils.substringBetween( - spans.last().text(), "(", ")"), spans.last().text()) - + " (poprzednio: " + spans[0].text() + ")") - } - 9 == spans.size -> { - val subjectAndGroupInfo = getLessonAndGroupInfoFromSpan(spans[4]) - lesson.subject = subjectAndGroupInfo[0] - lesson.groupName = subjectAndGroupInfo[1] - lesson.teacher = spans[6].text() - lesson.room = spans[7].text() - lesson.movedOrCanceled = false - lesson.newMovedInOrChanged = true - lesson.divisionIntoGroups = true - lesson.description = (StringUtils.defaultString(StringUtils.substringBetween( - spans.last().text(), "(", ")"), spans.last().text()) - + " (poprzednio: " + getLessonAndGroupInfoFromSpan(spans[0])[0] + ")") - } - 4 <= spans.size -> { - lesson.subject = spans[0].text() - lesson.teacher = spans[1].text() - lesson.room = spans[2].text() - lesson.description = StringUtils.defaultString(StringUtils.substringBetween( - spans.last().text(), "(", ")"), spans.last().text()) - } - } - } - - private fun addGroupLessonInfo(lesson: TimetableLesson, spans: Elements) { - if (4 == spans.size && !spans.last().hasClass(Types.CLASS_REALIZED)) { - lesson.room = spans.last().text() - } - - if (4 == spans.size && !spans.last().hasClass(Types.CLASS_REALIZED) || 5 == spans.size) { - val subjectAndGroupInfo = getLessonAndGroupInfoFromSpan(spans[0]) - lesson.subject = subjectAndGroupInfo[0] - lesson.groupName = subjectAndGroupInfo[1] - lesson.teacher = spans[2].text() - lesson.divisionIntoGroups = true - } - - if (5 == spans.size) { - lesson.room = spans[3].text() - } - } - - private fun getLessonAndGroupInfoFromSpan(span: Element): Array { - if (!span.text().contains("[")) { - return arrayOf(span.text(), "") - } - - val subjectNameArray = span.text().split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() - val groupName = subjectNameArray[subjectNameArray.size - 1] - - return arrayOf(span.text().replace(" $groupName", ""), StringUtils.defaultString(StringUtils.substringBetween( - groupName, "[", "]"), groupName)) - } - - private object Types { - const val CLASS_PLANNING = "x-treelabel-ppl" - const val CLASS_REALIZED = "x-treelabel-rlz" - const val CLASS_MOVED_OR_CANCELED = "x-treelabel-inv" - const val CLASS_NEW_MOVED_IN_OR_CHANGED = "x-treelabel-zas" - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/timetable/TimetableLesson.kt b/api/src/main/java/io/github/wulkanowy/api/timetable/TimetableLesson.kt deleted file mode 100644 index 8769d6c6..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/timetable/TimetableLesson.kt +++ /dev/null @@ -1,36 +0,0 @@ -package io.github.wulkanowy.api.timetable - -data class TimetableLesson( - - val number: Int, - - val date: String, - - val freeDayName: String, - - val startTime: String, - - val endTime: String, - - var subject: String = "", - - var teacher: String = "", - - var room: String = "", - - var description: String = "", - - var groupName: String = "", - - var empty: Boolean = false, - - var divisionIntoGroups: Boolean = false, - - var planning: Boolean = false, - - var realized: Boolean = false, - - var movedOrCanceled: Boolean = false, - - var newMovedInOrChanged: Boolean = false -) diff --git a/api/src/main/java/io/github/wulkanowy/api/user/AddressData.java b/api/src/main/java/io/github/wulkanowy/api/user/AddressData.java deleted file mode 100644 index 3d6fc6d5..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/user/AddressData.java +++ /dev/null @@ -1,40 +0,0 @@ -package io.github.wulkanowy.api.user; - -public class AddressData { - - private String address = ""; - - private String registeredAddress = ""; - - private String correspondenceAddress = ""; - - public String getAddress() { - return address; - } - - public AddressData setAddress(String address) { - this.address = address; - - return this; - } - - public String getRegisteredAddress() { - return registeredAddress; - } - - public AddressData setRegisteredAddress(String registeredAddress) { - this.registeredAddress = registeredAddress; - - return this; - } - - public String getCorrespondenceAddress() { - return correspondenceAddress; - } - - public AddressData setCorrespondenceAddress(String correspondenceAddress) { - this.correspondenceAddress = correspondenceAddress; - - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/user/BasicInformation.java b/api/src/main/java/io/github/wulkanowy/api/user/BasicInformation.java deleted file mode 100644 index 4edc5117..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/user/BasicInformation.java +++ /dev/null @@ -1,70 +0,0 @@ -package io.github.wulkanowy.api.user; - -import org.jsoup.nodes.Document; -import org.jsoup.nodes.Element; - -import java.io.IOException; - -import io.github.wulkanowy.api.SnP; -import io.github.wulkanowy.api.VulcanException; - -public class BasicInformation { - - private static final String STUDENT_DATA_PAGE_URL = "Uczen.mvc/DanePodstawowe"; - - private static final String CONTENT_QUERY = ".mainContainer > article"; - - private Document studentDataPageDocument; - - private SnP snp; - - public BasicInformation(SnP snp) { - this.snp = snp; - } - - public Document getStudentDataPageDocument() throws IOException, VulcanException { - if (null == studentDataPageDocument) { - studentDataPageDocument = snp.getSnPPageDocument(STUDENT_DATA_PAGE_URL); - } - - return studentDataPageDocument; - } - - public PersonalData getPersonalData() throws IOException, VulcanException { - Element e = getStudentDataPageDocument().select(CONTENT_QUERY).get(0); - - String name = snp.getRowDataChildValue(e, 1); - String[] names = name.split(" "); - - return new PersonalData() - .setName(name) - .setFirstName(names[0]) - .setSurname(names[names.length - 1]) - .setFirstAndLastName(names[0] + " " + names[names.length - 1]) - .setDateAndBirthPlace(snp.getRowDataChildValue(e, 2)) - .setPesel(snp.getRowDataChildValue(e, 3)) - .setGender(snp.getRowDataChildValue(e, 4)) - .setPolishCitizenship("Tak".equals(snp.getRowDataChildValue(e, 5))) - .setFamilyName(snp.getRowDataChildValue(e, 6)) - .setParentsNames(snp.getRowDataChildValue(e, 7)); - } - - public AddressData getAddressData() throws IOException, VulcanException { - Element e = getStudentDataPageDocument().select(CONTENT_QUERY).get(1); - - return new AddressData() - .setAddress(snp.getRowDataChildValue(e, 1)) - .setRegisteredAddress(snp.getRowDataChildValue(e, 2)) - .setCorrespondenceAddress(snp.getRowDataChildValue(e, 3)); - - } - - public ContactDetails getContactDetails() throws IOException, VulcanException { - Element e = getStudentDataPageDocument().select(CONTENT_QUERY).get(2); - - return new ContactDetails() - .setPhoneNumber(snp.getRowDataChildValue(e, 1)) - .setCellPhoneNumber(snp.getRowDataChildValue(e, 2)) - .setEmail(snp.getRowDataChildValue(e, 3)); - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/user/ContactDetails.java b/api/src/main/java/io/github/wulkanowy/api/user/ContactDetails.java deleted file mode 100644 index c8556944..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/user/ContactDetails.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.github.wulkanowy.api.user; - -public class ContactDetails { - - private String phoneNumber = ""; - - private String cellPhoneNumber = ""; - - private String email = ""; - - public String getPhoneNumber() { - return phoneNumber; - } - - public ContactDetails setPhoneNumber(String phoneNumber) { - this.phoneNumber = phoneNumber; - return this; - } - - public String getCellPhoneNumber() { - return cellPhoneNumber; - } - - public ContactDetails setCellPhoneNumber(String cellPhoneNumber) { - this.cellPhoneNumber = cellPhoneNumber; - return this; - } - - public String getEmail() { - return email; - } - - public ContactDetails setEmail(String email) { - this.email = email; - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/user/FamilyInformation.java b/api/src/main/java/io/github/wulkanowy/api/user/FamilyInformation.java deleted file mode 100644 index f5a459ee..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/user/FamilyInformation.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.github.wulkanowy.api.user; - -import org.jsoup.nodes.Element; -import org.jsoup.select.Elements; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import io.github.wulkanowy.api.SnP; -import io.github.wulkanowy.api.VulcanException; - -public class FamilyInformation { - - private static final String STUDENT_DATA_PAGE_URL = "Uczen.mvc/DanePodstawowe"; - - private SnP snp; - - public FamilyInformation(SnP snp) { - this.snp = snp; - } - - public List getFamilyMembers() throws IOException, VulcanException { - Elements membersElements = snp.getSnPPageDocument(STUDENT_DATA_PAGE_URL) - .select(".mainContainer > article:nth-of-type(n+4)"); - - List familyMembers = new ArrayList<>(); - - for (Element e : membersElements) { - familyMembers.add(new FamilyMember() - .setName(snp.getRowDataChildValue(e, 1)) - .setKinship(snp.getRowDataChildValue(e, 2)) - .setAddress(snp.getRowDataChildValue(e, 3)) - .setTelephones(snp.getRowDataChildValue(e, 4)) - .setEmail(snp.getRowDataChildValue(e, 5)) - ); - } - - return familyMembers; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/user/FamilyMember.java b/api/src/main/java/io/github/wulkanowy/api/user/FamilyMember.java deleted file mode 100644 index dfb96674..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/user/FamilyMember.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.github.wulkanowy.api.user; - -public class FamilyMember { - - private String name = ""; - - private String kinship = ""; - - private String address = ""; - - private String telephones = ""; - - private String email = ""; - - public String getName() { - return name; - } - - public FamilyMember setName(String name) { - this.name = name; - return this; - } - - public String getKinship() { - return kinship; - } - - public FamilyMember setKinship(String kinship) { - this.kinship = kinship; - return this; - } - - public String getAddress() { - return address; - } - - public FamilyMember setAddress(String address) { - this.address = address; - return this; - } - - public String getTelephones() { - return telephones; - } - - public FamilyMember setTelephones(String telephones) { - this.telephones = telephones; - return this; - } - - public String getEmail() { - return email; - } - - public FamilyMember setEmail(String email) { - this.email = email; - return this; - } -} diff --git a/api/src/main/java/io/github/wulkanowy/api/user/PersonalData.java b/api/src/main/java/io/github/wulkanowy/api/user/PersonalData.java deleted file mode 100644 index d2991e61..00000000 --- a/api/src/main/java/io/github/wulkanowy/api/user/PersonalData.java +++ /dev/null @@ -1,114 +0,0 @@ -package io.github.wulkanowy.api.user; - -public class PersonalData { - - private String name = ""; - - private String firstName = ""; - - private String surname = ""; - - private String firstAndLastName = ""; - - private String dateAndBirthPlace = ""; - - private String pesel = ""; - - private String gender = ""; - - private boolean isPolishCitizenship; - - private String familyName = ""; - - private String parentsNames = ""; - - public String getName() { - return name; - } - - public PersonalData setName(String name) { - this.name = name; - return this; - } - - public String getFirstName() { - return firstName; - } - - public PersonalData setFirstName(String firstName) { - this.firstName = firstName; - return this; - } - - public String getSurname() { - return surname; - } - - public PersonalData setSurname(String surname) { - this.surname = surname; - return this; - } - - public String getFirstAndLastName() { - return firstAndLastName; - } - - public PersonalData setFirstAndLastName(String firstAndLastName) { - this.firstAndLastName = firstAndLastName; - return this; - } - - public String getDateAndBirthPlace() { - return dateAndBirthPlace; - } - - public PersonalData setDateAndBirthPlace(String dateAndBirthPlace) { - this.dateAndBirthPlace = dateAndBirthPlace; - return this; - } - - public String getPesel() { - return pesel; - } - - public PersonalData setPesel(String pesel) { - this.pesel = pesel; - return this; - } - - public String getGender() { - return gender; - } - - public PersonalData setGender(String gender) { - this.gender = gender; - return this; - } - - public boolean isPolishCitizenship() { - return isPolishCitizenship; - } - - public PersonalData setPolishCitizenship(boolean polishCitizenship) { - isPolishCitizenship = polishCitizenship; - return this; - } - - public String getFamilyName() { - return familyName; - } - - public PersonalData setFamilyName(String familyName) { - this.familyName = familyName; - return this; - } - - public String getParentsNames() { - return parentsNames; - } - - public PersonalData setParentsNames(String parentsNames) { - this.parentsNames = parentsNames; - return this; - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/ClientTest.java b/api/src/test/java/io/github/wulkanowy/api/ClientTest.java deleted file mode 100644 index 298affac..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/ClientTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package io.github.wulkanowy.api; - -import org.jsoup.Jsoup; -import org.jsoup.nodes.Document; -import org.junit.Assert; -import org.junit.Test; - -public class ClientTest { - - private String getFixtureAsString(String fixtureFileName) { - return FixtureHelper.getAsString(getClass().getResourceAsStream(fixtureFileName)); - } - - @Test - public void setFullEndpointInfoTest() { - Client client = new Client("http://fakelog.cf\\\\admin", "pass", "Default", "123"); - - Assert.assertEquals("fakelog.cf", client.getHost()); - Assert.assertEquals("Default", client.getSymbol()); - } - - @Test - public void setFullEndpointInfoWithSymbolTest() { - Client client = new Client("http://fakelog.cf/notdefault\\\\admin", "pass", "Default", "123"); - - Assert.assertEquals("fakelog.cf", client.getHost()); - Assert.assertEquals("notdefault", client.getSymbol()); // - } - - @Test - public void checkForNoErrorsTest() throws Exception { - Client client = new Client("", "", "", "123"); - - Document doc = Jsoup.parse(getFixtureAsString("login/Logowanie-success.html")); - - Assert.assertEquals(doc, client.checkForErrors(doc, 200)); - } - - @Test(expected = VulcanOfflineException.class) - public void checkForErrorsOffline() throws Exception { - Client client = new Client("", "", "", "123"); - - Document doc = Jsoup.parse(getFixtureAsString("login/PrzerwaTechniczna.html")); - - client.checkForErrors(doc, 200); - } - - @Test(expected = NotLoggedInErrorException.class) - public void checkForErrors() throws Exception { - Client client = new Client("", "", "", "123"); - - Document doc = Jsoup.parse(getFixtureAsString("login/Logowanie-notLoggedIn.html")); - - client.checkForErrors(doc, 200); - } - - @Test - public void getFilledUrlTest() throws Exception { - Client client = new Client("http://fakelog.cf\\\\admin", "", "symbol123", "321"); - - Assert.assertEquals("http://uonetplus-opiekun.fakelog.cf/symbol123/321/Oceny/Wszystkie", - client.getFilledUrl("{schema}://uonetplus-opiekun.{host}/{symbol}/{ID}/Oceny/Wszystkie")); - } - - @Test - public void getSymbolTest() { - Client client = new Client("", "", "symbol4321", "123"); - - Assert.assertEquals("symbol4321", client.getSymbol()); - } - - @Test - public void getSchoolIdTest() throws Exception { - Client client = new Client("", "", "1", "123456"); - - Assert.assertEquals("123456", client.getSchoolId()); - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/DateTimeUtilsTest.kt b/api/src/test/java/io/github/wulkanowy/api/DateTimeUtilsTest.kt deleted file mode 100644 index 1105b2a7..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/DateTimeUtilsTest.kt +++ /dev/null @@ -1,53 +0,0 @@ -package io.github.wulkanowy.api - -import org.junit.Assert -import org.junit.Test -import java.text.ParseException -import java.text.SimpleDateFormat -import java.util.* - -class DateTimeUtilsTest { - - @Test - fun getTicksDateObjectTest() { - val format = SimpleDateFormat("dd.MM.yyyy", Locale.ROOT) - format.timeZone = TimeZone.getTimeZone("UTC") - val date = format.parse("31.07.2017") - - Assert.assertEquals(636370560000000000L, getDateAsTick(date)) - - val calendar = Calendar.getInstance() - calendar.time = date - calendar.add(Calendar.DAY_OF_YEAR, -14) - val dateTwoWeekBefore = calendar.time - - Assert.assertEquals(636358464000000000L, getDateAsTick(dateTwoWeekBefore)) - } - - @Test(expected = ParseException::class) - fun getTicsStringInvalidFormatTest() { - Assert.assertEquals(636370560000000000L, getDateAsTick("31.07.2017", "dd.MMM.yyyy")) - } - - @Test - fun getTicsStringFormatTest() { - Assert.assertEquals(636370560000000000L, getDateAsTick("31.07.2017", "dd.MM.yyyy")) - } - - @Test - fun getTicsStringTest() { - Assert.assertEquals("636370560000000000", getDateAsTick("2017-07-31")) - Assert.assertEquals("636334272000000000", getDateAsTick("2017-06-19")) - Assert.assertEquals("636189120000000000", getDateAsTick("2017-01-02")) - Assert.assertEquals("636080256000000000", getDateAsTick("2016-08-29")) - } - - @Test - fun getDateTest() { - val format = SimpleDateFormat("dd.MM.yyyy", Locale.ROOT) - format.timeZone = TimeZone.getTimeZone("UTC") - val date = format.parse("31.07.2017") - - Assert.assertEquals(date, getDate(636370560000000000L)) - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/FixtureHelper.java b/api/src/test/java/io/github/wulkanowy/api/FixtureHelper.java deleted file mode 100644 index 94dd47b8..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/FixtureHelper.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.github.wulkanowy.api; - -import java.io.InputStream; -import java.util.Scanner; - -public class FixtureHelper { - - public static String getAsString(InputStream inputStream) { - Scanner s = new Scanner(inputStream).useDelimiter("\\A"); - return s.hasNext() ? s.next() : ""; - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/StudentAndParentTest.java b/api/src/test/java/io/github/wulkanowy/api/StudentAndParentTest.java deleted file mode 100644 index 4c6443b1..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/StudentAndParentTest.java +++ /dev/null @@ -1,103 +0,0 @@ -package io.github.wulkanowy.api; - -import org.jsoup.Jsoup; -import org.jsoup.nodes.Document; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import io.github.wulkanowy.api.generic.Semester; - -public class StudentAndParentTest { - - private Client client; - - @Before - public void setUp() throws Exception { - String input = FixtureHelper.getAsString( - getClass().getResourceAsStream("OcenyWszystkie-semester.html")); - Document gradesPageDocument = Jsoup.parse(input); - - client = Mockito.mock(Client.class); - Mockito.when(client.getPageByUrl(Mockito.anyString())).thenReturn(gradesPageDocument); - Mockito.when(client.getPageByUrl( - Mockito.anyString(), - Mockito.anyBoolean(), Mockito.anyMap())).thenReturn(gradesPageDocument); - } - - @Test - public void snpTest() { - StudentAndParent snp = new StudentAndParent(client, "1234", null); - Assert.assertEquals("1234", snp.getStudentID()); - } - - @Test - public void getSemestersTest() throws Exception { - SnP snp = new StudentAndParent(client, null, null); - List semesters = snp.getSemesters(); - - Assert.assertEquals(2, semesters.size()); - - Assert.assertEquals("1", semesters.get(0).getName()); - Assert.assertEquals("1234", semesters.get(0).getId()); - Assert.assertFalse(semesters.get(0).isCurrent()); - - Assert.assertEquals("2", semesters.get(1).getName()); - Assert.assertEquals("1235", semesters.get(1).getId()); - Assert.assertTrue(semesters.get(1).isCurrent()); - } - - @Test - public void getCurrentSemesterTest() { - List semesters = new ArrayList<>(); - semesters.add(new Semester().setName("1500100900").setId("1").setCurrent(false)); - semesters.add(new Semester().setName("1500100901").setId("2").setCurrent(true)); - - SnP snp = new StudentAndParent(client, null, null); - Semester semester = snp.getCurrent(semesters); - - Assert.assertTrue(semester.isCurrent()); - Assert.assertEquals("2", semester.getId()); - Assert.assertEquals("1500100901", semester.getName()); - } - - @Test - public void getCurrentSemesterFromEmptyTest() { - SnP snp = new StudentAndParent(client, null, null); - List semesters = new ArrayList<>(); - - Assert.assertNull(snp.getCurrent(semesters)); - } - - @Test - public void getDiariesAndStudentTest() throws IOException, VulcanException { - String input = FixtureHelper.getAsString(getClass().getResourceAsStream("WitrynaUczniaIRodzica.html")); - Document snpHome = Jsoup.parse(input); - - client = Mockito.mock(Client.class); - Mockito.when(client.getPageByUrl(Mockito.anyString())).thenReturn(snpHome); - SnP snp = new StudentAndParent(client, null, null); - - snp.setUp(); - - Assert.assertEquals("3Ti 2017", snp.getDiaries().get(0).getName()); - Assert.assertEquals("2Ti 2016", snp.getDiaries().get(1).getName()); - Assert.assertEquals("1Ti 2015", snp.getDiaries().get(2).getName()); - - Assert.assertEquals("1300", snp.getDiaries().get(0).getId()); - Assert.assertEquals("1200", snp.getDiaries().get(1).getId()); - Assert.assertEquals("1100", snp.getDiaries().get(2).getId()); - - Assert.assertTrue(snp.getDiaries().get(0).isCurrent()); - Assert.assertFalse(snp.getDiaries().get(1).isCurrent()); - Assert.assertFalse(snp.getDiaries().get(2).isCurrent()); - - Assert.assertEquals("Jan Kowal", snp.getStudents().get(0).getName()); - Assert.assertEquals("100", snp.getStudents().get(0).getId()); - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/StudentAndParentTestCase.java b/api/src/test/java/io/github/wulkanowy/api/StudentAndParentTestCase.java deleted file mode 100644 index 764e8009..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/StudentAndParentTestCase.java +++ /dev/null @@ -1,28 +0,0 @@ -package io.github.wulkanowy.api; - -import org.jsoup.Jsoup; -import org.jsoup.nodes.Document; -import org.jsoup.nodes.Element; -import org.mockito.Mockito; - -import io.github.wulkanowy.api.generic.Semester; - -public abstract class StudentAndParentTestCase { - - protected StudentAndParent getSnp(String fixtureFileName) throws Exception { - String input = FixtureHelper.getAsString(getClass().getResourceAsStream(fixtureFileName)); - - Document tablePageDocument = Jsoup.parse(input); - - StudentAndParent snp = Mockito.mock(StudentAndParent.class); - Mockito.when(snp.getSnPPageDocument(Mockito.anyString())) - .thenReturn(tablePageDocument); - Mockito.when(snp.getSemesters(Mockito.any(Document.class))).thenCallRealMethod(); - Mockito.when(snp.getCurrent(Mockito.anyList())) - .thenCallRealMethod(); - Mockito.when(snp.getRowDataChildValue(Mockito.any(Element.class), - Mockito.anyInt())).thenCallRealMethod(); - - return snp; - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/VulcanTest.java b/api/src/test/java/io/github/wulkanowy/api/VulcanTest.java deleted file mode 100644 index 287935c0..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/VulcanTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package io.github.wulkanowy.api; - -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Test; - -public class VulcanTest { - - @Test(expected = NotLoggedInErrorException.class) - public void getClientWithoutLoginTest() throws Exception { - Vulcan vulcan = new Vulcan(); - - vulcan.getClient(); - } - - @Test - public void getClientTest() throws Exception { - Vulcan vulcan = new Vulcan(); - vulcan.setCredentials("email", "password", "symbol", null, null, null); - - Assert.assertThat(vulcan.getClient(), CoreMatchers.instanceOf(Client.class)); - } - - @Test - public void getClientTwiceTest() throws Exception { - Vulcan vulcan = new Vulcan(); - vulcan.setCredentials("email", "password", "symbol", null, null, null); - - Assert.assertEquals(vulcan.getClient(), vulcan.getClient()); - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/attendance/AttendanceStatisticsTest.java b/api/src/test/java/io/github/wulkanowy/api/attendance/AttendanceStatisticsTest.java deleted file mode 100644 index ca50f378..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/attendance/AttendanceStatisticsTest.java +++ /dev/null @@ -1,144 +0,0 @@ -package io.github.wulkanowy.api.attendance; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.List; - -import io.github.wulkanowy.api.StudentAndParentTestCase; -import io.github.wulkanowy.api.generic.Month; - -public class AttendanceStatisticsTest extends StudentAndParentTestCase { - - private AttendanceStatistics excellent; - - private AttendanceStatistics full; - - @Before - public void setUp() throws Exception { - this.excellent = new AttendanceStatistics(getSnp("Frekwencja-excellent.html")); - this.full = new AttendanceStatistics(getSnp("Frekwencja-full.html")); - } - - @Test - public void getSubjectList() throws Exception { - Assert.assertEquals(26, excellent.getSubjectList().size()); - Assert.assertEquals(23, full.getSubjectList().size()); - } - - @Test - public void getSubjectListId() throws Exception { - Assert.assertEquals(-1, excellent.getSubjectList().get(0).getId()); - Assert.assertEquals(63, excellent.getSubjectList().get(10).getId()); - Assert.assertEquals(0, excellent.getSubjectList().get(25).getId()); - - Assert.assertEquals(-1, full.getSubjectList().get(0).getId()); - Assert.assertEquals(108, full.getSubjectList().get(14).getId()); - Assert.assertEquals(492, full.getSubjectList().get(21).getId()); - } - - @Test - public void getSubjectListName() throws Exception { - Assert.assertEquals("Wszystkie", excellent.getSubjectList().get(0).getName()); - Assert.assertEquals("Fizyka", excellent.getSubjectList().get(8).getName()); - Assert.assertEquals("Sieci komputerowe i administrowanie sieciami", - excellent.getSubjectList().get(21).getName()); - - Assert.assertEquals("Praktyka zawodowa", full.getSubjectList().get(11).getName()); - Assert.assertEquals("Użytkowanie urządzeń peryferyjnych komputera", - full.getSubjectList().get(16).getName()); - Assert.assertEquals("Brak opisu lekcji", full.getSubjectList().get(22).getName()); - } - - @Test - public void getTypesTotal() throws Exception { - Assert.assertEquals(100.0, excellent.getTypesTable().getTotal(), 0); - Assert.assertEquals(80.94, full.getTypesTable().getTotal(), 0); - } - - @Test - public void getTypeName() throws Exception { - List typeList1 = excellent.getTypesTable().getTypeList(); - Assert.assertEquals("Obecność", typeList1.get(0).getName()); - Assert.assertEquals("Nieobecność nieusprawiedliwiona", typeList1.get(1).getName()); - Assert.assertEquals("Nieobecność usprawiedliwiona", typeList1.get(2).getName()); - Assert.assertEquals("Nieobecność z przyczyn szkolnych", typeList1.get(3).getName()); - - List typeList2 = full.getTypesTable().getTypeList(); - Assert.assertEquals("Spóźnienie nieusprawiedliwione", typeList2.get(4).getName()); - Assert.assertEquals("Spóźnienie usprawiedliwione", typeList2.get(5).getName()); - Assert.assertEquals("Zwolnienie", typeList2.get(6).getName()); - } - - @Test - public void getTypeTotal() throws Exception { - List typeList1 = excellent.getTypesTable().getTypeList(); - Assert.assertEquals(1211, typeList1.get(0).getTotal()); - Assert.assertEquals(0, typeList1.get(1).getTotal()); - Assert.assertEquals(0, typeList1.get(2).getTotal()); - Assert.assertEquals(0, typeList1.get(3).getTotal()); - Assert.assertEquals(0, typeList1.get(4).getTotal()); - Assert.assertEquals(0, typeList1.get(5).getTotal()); - Assert.assertEquals(0, typeList1.get(6).getTotal()); - - List typeList2 = full.getTypesTable().getTypeList(); - Assert.assertEquals(822, typeList2.get(0).getTotal()); - Assert.assertEquals(6, typeList2.get(1).getTotal()); - Assert.assertEquals(192, typeList2.get(2).getTotal()); - Assert.assertEquals(7, typeList2.get(3).getTotal()); - Assert.assertEquals(12, typeList2.get(4).getTotal()); - Assert.assertEquals(1, typeList2.get(5).getTotal()); - Assert.assertEquals(2, typeList2.get(6).getTotal()); - } - - @Test - public void getTypeList() throws Exception { - List typesList1 = excellent.getTypesTable().getTypeList(); - Assert.assertEquals(12, typesList1.get(0).getMonthList().size()); - Assert.assertEquals(12, typesList1.get(5).getMonthList().size()); - - List typesList2 = full.getTypesTable().getTypeList(); - Assert.assertEquals(12, typesList2.get(0).getMonthList().size()); - Assert.assertEquals(12, typesList2.get(5).getMonthList().size()); - } - - @Test - public void getMonthList() throws Exception { - List typeList1 = excellent.getTypesTable().getTypeList(); - Assert.assertEquals(12, typeList1.get(0).getMonthList().size()); - - List typeList2 = full.getTypesTable().getTypeList(); - Assert.assertEquals(12, typeList2.get(0).getMonthList().size()); - } - - @Test - public void getMonthName() throws Exception { - List monthsList1 = excellent.getTypesTable().getTypeList().get(0).getMonthList(); - Assert.assertEquals("IX", monthsList1.get(0).getName()); - Assert.assertEquals("III", monthsList1.get(6).getName()); - Assert.assertEquals("VIII", monthsList1.get(11).getName()); - - List monthsList2 = full.getTypesTable().getTypeList().get(0).getMonthList(); - Assert.assertEquals("XI", monthsList2.get(2).getName()); - Assert.assertEquals("II", monthsList2.get(5).getName()); - Assert.assertEquals("VI", monthsList2.get(9).getName()); - } - - @Test - public void getMonthValue() throws Exception { - List monthsList1 = excellent.getTypesTable().getTypeList().get(0).getMonthList(); - Assert.assertEquals(142, monthsList1.get(0).getValue()); - Assert.assertEquals(131, monthsList1.get(4).getValue()); - Assert.assertEquals(139, monthsList1.get(7).getValue()); - Assert.assertEquals(114, monthsList1.get(9).getValue()); - Assert.assertEquals(0, monthsList1.get(11).getValue()); - - List typeList1 = full.getTypesTable().getTypeList(); - Assert.assertEquals(135, typeList1.get(0).getMonthList().get(0).getValue()); - Assert.assertEquals(7, typeList1.get(3).getMonthList().get(5).getValue()); - Assert.assertEquals(1, typeList1.get(5).getMonthList().get(0).getValue()); - Assert.assertEquals(27, typeList1.get(2).getMonthList().get(9).getValue()); - Assert.assertEquals(0, typeList1.get(0).getMonthList().get(11).getValue()); - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/attendance/AttendanceTableTest.java b/api/src/test/java/io/github/wulkanowy/api/attendance/AttendanceTableTest.java deleted file mode 100644 index 40ff4f06..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/attendance/AttendanceTableTest.java +++ /dev/null @@ -1,165 +0,0 @@ -package io.github.wulkanowy.api.attendance; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import io.github.wulkanowy.api.StudentAndParentTestCase; - -public class AttendanceTableTest extends StudentAndParentTestCase { - - private AttendanceTable excellent; - - private AttendanceTable full; - - @Before - public void setUp() throws Exception { - excellent = new AttendanceTable(getSnp("Frekwencja-excellent.html")); - full = new AttendanceTable(getSnp("Frekwencja-full.html")); - } - - @Test - public void getWeekStartByDate() throws Exception { - Assert.assertEquals("2015-08-31", excellent.getWeekTable().getStartDayDate()); - Assert.assertEquals("2016-09-05", full.getWeekTable().getStartDayDate()); - } - - @Test - public void getWeekDaysNumber() throws Exception { - Assert.assertEquals(5, excellent.getWeekTable().getDays().size()); - Assert.assertEquals(5, full.getWeekTable().getDays().size()); - } - - @Test - public void getDayLessonsNumber() throws Exception { - Assert.assertEquals(14, excellent.getWeekTable().getDay(0).getLessons().size()); - Assert.assertEquals(14, full.getWeekTable().getDay(0).getLessons().size()); - } - - @Test - public void getDayDate() throws Exception { - Assert.assertEquals("2015-08-31", excellent.getWeekTable().getDay(0).getDate()); - Assert.assertEquals("2015-09-02", excellent.getWeekTable().getDay(2).getDate()); - Assert.assertEquals("2015-09-04", excellent.getWeekTable().getDay(4).getDate()); - - Assert.assertEquals("2016-09-05", full.getWeekTable().getDay(0).getDate()); - Assert.assertEquals("2016-09-07", full.getWeekTable().getDay(2).getDate()); - Assert.assertEquals("2016-09-09", full.getWeekTable().getDay(4).getDate()); - } - - @Test - public void getLessonSubject() throws Exception { - Assert.assertEquals("", - excellent.getWeekTable().getDay(0).getLesson(7).getSubject()); - Assert.assertEquals("Uroczyste rozpoczęcie roku szkolnego 2015/2016", - excellent.getWeekTable().getDay(1).getLesson(1).getSubject()); - Assert.assertEquals("Geografia", - excellent.getWeekTable().getDay(3).getLesson(4).getSubject()); - - Assert.assertEquals("Naprawa komputera", - full.getWeekTable().getDay(1).getLesson(8).getSubject()); - Assert.assertEquals("Religia", - full.getWeekTable().getDay(3).getLesson(1).getSubject()); - Assert.assertEquals("Metodologia programowania", - full.getWeekTable().getDay(4).getLesson(5).getSubject()); - } - - @Test - public void getLessonIsNotExist() throws Exception { - Assert.assertTrue(excellent.getWeekTable().getDay(0).getLesson(5).isNotExist()); - Assert.assertFalse(excellent.getWeekTable().getDay(2).getLesson(1).isNotExist()); - Assert.assertFalse(excellent.getWeekTable().getDay(4).getLesson(12).isNotExist()); - - Assert.assertFalse(full.getWeekTable().getDay(1).getLesson(12).isAbsenceUnexcused()); - Assert.assertFalse(full.getWeekTable().getDay(3).getLesson(1).isAbsenceUnexcused()); - Assert.assertFalse(full.getWeekTable().getDay(4).getLesson(5).isAbsenceUnexcused()); - } - - @Test - public void getLessonIsEmpty() throws Exception { - Assert.assertTrue(excellent.getWeekTable().getDay(0).getLesson(0).isEmpty()); - Assert.assertFalse(excellent.getWeekTable().getDay(2).getLesson(6).isEmpty()); - Assert.assertTrue(excellent.getWeekTable().getDay(4).getLesson(12).isEmpty()); - - Assert.assertTrue(full.getWeekTable().getDay(1).getLesson(9).isEmpty()); - Assert.assertFalse(full.getWeekTable().getDay(2).getLesson(5).isEmpty()); - Assert.assertFalse(full.getWeekTable().getDay(4).getLesson(2).isEmpty()); - } - - @Test - public void getLessonIsPresence() throws Exception { - Assert.assertFalse(excellent.getWeekTable().getDay(0).getLesson(7).isPresence()); - Assert.assertTrue(excellent.getWeekTable().getDay(1).getLesson(1).isPresence()); - Assert.assertTrue(excellent.getWeekTable().getDay(3).getLesson(7).isPresence()); - - Assert.assertTrue(full.getWeekTable().getDay(0).getLesson(1).isPresence()); - Assert.assertTrue(full.getWeekTable().getDay(2).getLesson(6).isPresence()); - Assert.assertFalse(full.getWeekTable().getDay(4).getLesson(7).isPresence()); - } - - @Test - public void getLessonIsAbsenceUnexcused() throws Exception { - Assert.assertFalse(excellent.getWeekTable().getDay(0).getLesson(7).isAbsenceUnexcused()); - Assert.assertFalse(excellent.getWeekTable().getDay(2).getLesson(0).isAbsenceUnexcused()); - Assert.assertFalse(excellent.getWeekTable().getDay(4).getLesson(4).isAbsenceUnexcused()); - - Assert.assertTrue(full.getWeekTable().getDay(1).getLesson(8).isAbsenceUnexcused()); - Assert.assertFalse(full.getWeekTable().getDay(3).getLesson(1).isAbsenceUnexcused()); - Assert.assertFalse(full.getWeekTable().getDay(4).getLesson(8).isAbsenceUnexcused()); - } - - @Test - public void getLessonIsAbsenceExcused() throws Exception { - Assert.assertFalse(excellent.getWeekTable().getDay(0).getLesson(7).isAbsenceExcused()); - Assert.assertFalse(excellent.getWeekTable().getDay(2).getLesson(0).isAbsenceExcused()); - Assert.assertFalse(excellent.getWeekTable().getDay(4).getLesson(4).isAbsenceExcused()); - - Assert.assertFalse(full.getWeekTable().getDay(2).getLesson(5).isAbsenceExcused()); - Assert.assertFalse(full.getWeekTable().getDay(3).getLesson(1).isAbsenceExcused()); - Assert.assertTrue(full.getWeekTable().getDay(4).getLesson(3).isAbsenceExcused()); - } - - @Test - public void getLessonIsAbsenceForSchoolReasons() throws Exception { - Assert.assertFalse(excellent.getWeekTable().getDay(0).getLesson(4).isAbsenceForSchoolReasons()); - Assert.assertFalse(excellent.getWeekTable().getDay(2).getLesson(8).isAbsenceForSchoolReasons()); - Assert.assertFalse(excellent.getWeekTable().getDay(4).getLesson(12).isAbsenceForSchoolReasons()); - - Assert.assertTrue(full.getWeekTable().getDay(2).getLesson(5).isAbsenceForSchoolReasons()); - Assert.assertFalse(full.getWeekTable().getDay(3).getLesson(1).isAbsenceForSchoolReasons()); - Assert.assertFalse(full.getWeekTable().getDay(4).getLesson(8).isAbsenceForSchoolReasons()); - } - - @Test - public void getLessonIsUnexcusedLateness() throws Exception { - Assert.assertFalse(excellent.getWeekTable().getDay(0).getLesson(4).isUnexcusedLateness()); - Assert.assertFalse(excellent.getWeekTable().getDay(2).getLesson(8).isUnexcusedLateness()); - Assert.assertFalse(excellent.getWeekTable().getDay(4).getLesson(12).isUnexcusedLateness()); - - Assert.assertTrue(full.getWeekTable().getDay(1).getLesson(6).isUnexcusedLateness()); - Assert.assertFalse(full.getWeekTable().getDay(3).getLesson(1).isUnexcusedLateness()); - Assert.assertFalse(full.getWeekTable().getDay(4).getLesson(8).isUnexcusedLateness()); - } - - @Test - public void getLessonIsExcusedLateness() throws Exception { - Assert.assertFalse(excellent.getWeekTable().getDay(0).getLesson(4).isExcusedLateness()); - Assert.assertFalse(excellent.getWeekTable().getDay(2).getLesson(8).isExcusedLateness()); - Assert.assertFalse(excellent.getWeekTable().getDay(4).getLesson(12).isExcusedLateness()); - - Assert.assertTrue(full.getWeekTable().getDay(1).getLesson(7).isExcusedLateness()); - Assert.assertFalse(full.getWeekTable().getDay(3).getLesson(1).isExcusedLateness()); - Assert.assertFalse(full.getWeekTable().getDay(4).getLesson(8).isExcusedLateness()); - } - - @Test - public void getLessonIsExemption() throws Exception { - Assert.assertFalse(excellent.getWeekTable().getDay(0).getLesson(4).isExemption()); - Assert.assertFalse(excellent.getWeekTable().getDay(2).getLesson(8).isExemption()); - Assert.assertFalse(excellent.getWeekTable().getDay(4).getLesson(12).isExemption()); - - Assert.assertFalse(full.getWeekTable().getDay(2).getLesson(5).isExemption()); - Assert.assertFalse(full.getWeekTable().getDay(3).getLesson(1).isExemption()); - Assert.assertTrue(full.getWeekTable().getDay(4).getLesson(8).isExemption()); - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/attendance/AttendanceTest.kt b/api/src/test/java/io/github/wulkanowy/api/attendance/AttendanceTest.kt deleted file mode 100644 index 40a21c9c..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/attendance/AttendanceTest.kt +++ /dev/null @@ -1,90 +0,0 @@ -package io.github.wulkanowy.api.attendance - -import io.github.wulkanowy.api.StudentAndParentTestCase -import org.junit.Assert.* -import org.junit.Test - -class AttendanceTest : StudentAndParentTestCase() { - - private val full by lazy { Attendance(getSnp("Frekwencja-full.html")) } - - private val excellent by lazy { Attendance(getSnp("Frekwencja-excellent.html")) } - - @Test fun getAttendanceFull() { - assertTrue(full.getAttendance().isNotEmpty()) - assertEquals(38, full.getAttendance().size) - } - - @Test fun getAttendanceExcellent() { - assertTrue(excellent.getAttendance().isNotEmpty()) - assertEquals(22, excellent.getAttendance().size) - } - - @Test fun getLessonSubject() { - assertEquals("Uroczyste rozpoczęcie roku szkolnego 2015/2016", excellent.getAttendance()[0].subject) - assertEquals("Geografia", excellent.getAttendance()[11].subject) - - assertEquals("Naprawa komputera", full.getAttendance()[14].subject) - assertEquals("Religia", full.getAttendance()[23].subject) - assertEquals("Metodologia programowania", full.getAttendance()[34].subject) - } - - @Test fun getLessonIsPresence() { - assertTrue(excellent.getAttendance()[0].presence) - assertTrue(excellent.getAttendance()[15].presence) - - assertTrue(full.getAttendance()[0].presence) - assertTrue(full.getAttendance()[21].presence) - assertFalse(full.getAttendance()[36].presence) - assertFalse(full.getAttendance()[37].presence) - } - - - @Test fun getLessonIsAbsenceUnexcused() { - assertFalse(excellent.getAttendance()[0].absenceUnexcused) - - assertTrue(full.getAttendance()[14].absenceUnexcused) - assertFalse(full.getAttendance()[24].absenceUnexcused) - assertFalse(full.getAttendance()[37].absenceUnexcused) - } - - @Test fun getLessonIsAbsenceExcused() { - assertFalse(excellent.getAttendance()[0].absenceExcused) - - assertFalse(full.getAttendance()[5].absenceExcused) - assertFalse(full.getAttendance()[10].absenceExcused) - assertTrue(full.getAttendance()[36].absenceExcused) - } - - @Test fun getLessonIsAbsenceForSchoolReasons() { - assertFalse(excellent.getAttendance()[6].absenceForSchoolReasons) - - assertTrue(full.getAttendance()[19].absenceForSchoolReasons) - assertFalse(full.getAttendance()[0].absenceForSchoolReasons) - assertFalse(full.getAttendance()[37].absenceForSchoolReasons) - } - - @Test fun getLessonIsUnexcusedLateness() { - assertFalse(excellent.getAttendance()[7].unexcusedLateness) - - assertTrue(full.getAttendance()[12].unexcusedLateness) - assertFalse(full.getAttendance()[13].unexcusedLateness) - assertFalse(full.getAttendance()[36].unexcusedLateness) - } - - @Test fun getLessonIsExcusedLateness() { - assertFalse(excellent.getAttendance()[8].excusedLateness) - - assertTrue(full.getAttendance()[13].excusedLateness) - assertFalse(full.getAttendance()[14].excusedLateness) - assertFalse(full.getAttendance()[35].excusedLateness) - } - - @Test fun getLessonIsExemption() { - assertFalse(excellent.getAttendance()[9].exemption) - - assertFalse(full.getAttendance()[0].exemption) - assertFalse(full.getAttendance()[15].exemption) - assertTrue(full.getAttendance()[37].exemption) - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/exams/ExamsTest.kt b/api/src/test/java/io/github/wulkanowy/api/exams/ExamsTest.kt deleted file mode 100644 index 8e94e4f2..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/exams/ExamsTest.kt +++ /dev/null @@ -1,70 +0,0 @@ -package io.github.wulkanowy.api.exams - -import io.github.wulkanowy.api.StudentAndParentTestCase -import org.junit.Assert.assertEquals -import org.junit.Test - -class ExamsTest : StudentAndParentTestCase() { - - private val onePerDay by lazy { Exams(getSnp("Sprawdziany-one-per-day.html")) } - - private val empty by lazy { Exams(getSnp("Sprawdziany-empty.html")) } - - @Test fun getExamsSizeTest() { - assertEquals(6, onePerDay.getExams().size) - assertEquals(0, empty.getExams().size) - } - - @Test fun getExamsDateTest() { - assertEquals("2017-10-23", onePerDay.getExams()[0].date) - assertEquals("2017-10-24", onePerDay.getExams()[1].date) - assertEquals("2017-10-25", onePerDay.getExams()[2].date) - assertEquals("2017-10-25", onePerDay.getExams()[3].date) - assertEquals("2017-10-26", onePerDay.getExams()[4].date) - assertEquals("2017-10-27", onePerDay.getExams()[5].date) - } - - @Test fun getExamSubjectTest() { - assertEquals("Sieci komputerowe", onePerDay.getExams()[0].subject) - assertEquals("Język angielski", onePerDay.getExams()[1].subject) - assertEquals("Język polski", onePerDay.getExams()[4].subject) - assertEquals("Metodologia programowania", onePerDay.getExams()[5].subject) - } - - @Test fun getExamGroupTest() { - assertEquals("zaw2", onePerDay.getExams()[0].group) - assertEquals("J1", onePerDay.getExams()[1].group) - assertEquals("", onePerDay.getExams()[4].group) - } - - @Test fun getExamTypeTest() { - assertEquals("Sprawdzian", onePerDay.getExams()[0].type) - assertEquals("Sprawdzian", onePerDay.getExams()[1].type) - assertEquals("Sprawdzian", onePerDay.getExams()[2].type) - assertEquals("Kartkówka", onePerDay.getExams()[3].type) - } - - @Test fun getExamDescriptionTest() { - assertEquals("Łącza danych", onePerDay.getExams()[0].description) - assertEquals("Czasy teraźniejsze", onePerDay.getExams()[1].description) - assertEquals("", onePerDay.getExams()[5].description) - } - - @Test fun getExamTeacherTest() { - assertEquals("Adam Wiśniewski", onePerDay.getExams()[0].teacher) - assertEquals("Natalia Nowak", onePerDay.getExams()[1].teacher) - assertEquals("Małgorzata Nowacka", onePerDay.getExams()[5].teacher) - } - - @Test fun getExamTeacherSymbolTest() { - assertEquals("AW", onePerDay.getExams()[0].teacherSymbol) - assertEquals("NN", onePerDay.getExams()[1].teacherSymbol) - assertEquals("MN", onePerDay.getExams()[5].teacherSymbol) - } - - @Test fun getExamEntryDateTest() { - assertEquals("2017-10-16", onePerDay.getExams()[0].entryDate) - assertEquals("2017-10-17", onePerDay.getExams()[1].entryDate) - assertEquals("2017-10-16", onePerDay.getExams()[5].entryDate) - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/exams/ExamsWeekTest.java b/api/src/test/java/io/github/wulkanowy/api/exams/ExamsWeekTest.java deleted file mode 100644 index 357cca54..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/exams/ExamsWeekTest.java +++ /dev/null @@ -1,111 +0,0 @@ -package io.github.wulkanowy.api.exams; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.List; - -import io.github.wulkanowy.api.StudentAndParentTestCase; - -public class ExamsWeekTest extends StudentAndParentTestCase { - - private ExamsWeek onePerDay; - - private ExamsWeek empty; - - @Before - public void getCurrent() throws Exception { - onePerDay = new ExamsWeek(getSnp("Sprawdziany-one-per-day.html")); - empty = new ExamsWeek(getSnp("Sprawdziany-empty.html")); - } - - @Test - public void getWeekTest() throws Exception { - Assert.assertEquals("2017-10-23", onePerDay.getCurrent().getStartDayDate()); - Assert.assertEquals("2018-04-30", empty.getCurrent().getStartDayDate()); - } - - @Test - public void getDaysListTest() throws Exception { - Assert.assertEquals(5, onePerDay.getCurrent().getDays().size()); - Assert.assertEquals(7, onePerDay.getWeek("", false).getDays().size()); - Assert.assertEquals(0, empty.getCurrent().getDays().size()); - } - - @Test - public void getExamsListTest() throws Exception { - List notEmpty = onePerDay.getCurrent().getDays(); - Assert.assertEquals(1, notEmpty.get(0).getExamList().size()); - Assert.assertEquals(1, notEmpty.get(1).getExamList().size()); - Assert.assertEquals(1, notEmpty.get(4).getExamList().size()); - - List emptyToo = onePerDay.getWeek("", false).getDays(); - Assert.assertEquals(1, emptyToo.get(0).getExamList().size()); - Assert.assertEquals(1, emptyToo.get(1).getExamList().size()); - Assert.assertEquals(1, emptyToo.get(4).getExamList().size()); - } - - @Test - public void getDayDateTest() throws Exception { - List dayList = onePerDay.getCurrent().getDays(); - - Assert.assertEquals("2017-10-23", dayList.get(0).getDate()); - Assert.assertEquals("2017-10-24", dayList.get(1).getDate()); - Assert.assertEquals("2017-10-27", dayList.get(4).getDate()); - } - - @Test - public void getDayNameTest() throws Exception { - List dayList = onePerDay.getCurrent().getDays(); - - Assert.assertEquals("Poniedziałek", dayList.get(0).getDayName()); - Assert.assertEquals("Wtorek", dayList.get(1).getDayName()); - Assert.assertEquals("Piątek", dayList.get(4).getDayName()); - } - - @Test - public void getExamSubjectAndGroupTest() throws Exception { - List dayList = onePerDay.getCurrent().getDays(); - - Assert.assertEquals("Sieci komputerowe 3Ti|zaw2", dayList.get(0).getExamList().get(0).getSubjectAndGroup()); - Assert.assertEquals("Język angielski 3Ti|J1", dayList.get(1).getExamList().get(0).getSubjectAndGroup()); - Assert.assertEquals("Metodologia programowania 3Ti|zaw2", dayList.get(4).getExamList().get(0).getSubjectAndGroup()); - } - - @Test - public void getExamTypeTest() throws Exception { - List dayList = onePerDay.getCurrent().getDays(); - - Assert.assertEquals("Sprawdzian", dayList.get(0).getExamList().get(0).getType()); - Assert.assertEquals("Sprawdzian", dayList.get(1).getExamList().get(0).getType()); - Assert.assertEquals("Sprawdzian", dayList.get(4).getExamList().get(0).getType()); - } - - @Test - public void getExamDescriptionTest() throws Exception { - List dayList = onePerDay.getCurrent().getDays(); - - Assert.assertEquals("Łącza danych", dayList.get(0).getExamList().get(0).getDescription()); - Assert.assertEquals("Czasy teraźniejsze", dayList.get(1).getExamList().get(0).getDescription()); - Assert.assertEquals("", dayList.get(4).getExamList().get(0).getDescription()); - } - - @Test - public void getExamTeacherTest() throws Exception { - List dayList = onePerDay.getCurrent().getDays(); - - Assert.assertEquals("Adam Wiśniewski [AW]", dayList.get(0).getExamList().get(0).getTeacher()); - Assert.assertEquals("Natalia Nowak [NN]", dayList.get(1).getExamList().get(0).getTeacher()); - Assert.assertEquals("Małgorzata Nowacka [MN]", dayList.get(4).getExamList().get(0).getTeacher()); - } - - @Test - public void getExamEntryDateTest() throws Exception { - List dayList = onePerDay.getCurrent().getDays(); - - Assert.assertEquals("2017-10-16", dayList.get(0).getExamList().get(0).getEntryDate()); - Assert.assertEquals("2017-10-17", dayList.get(1).getExamList().get(0).getEntryDate()); - Assert.assertEquals("2017-10-16", dayList.get(4).getExamList().get(0).getEntryDate()); - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/grades/GradesListTest.java b/api/src/test/java/io/github/wulkanowy/api/grades/GradesListTest.java deleted file mode 100644 index deab7617..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/grades/GradesListTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package io.github.wulkanowy.api.grades; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.List; - -import io.github.wulkanowy.api.StudentAndParentTestCase; - -public class GradesListTest extends StudentAndParentTestCase { - - private GradesList filled; - - @Before - public void setUp() throws Exception { - filled = new GradesList(getSnp("OcenyWszystkie-filled.html")); - } - - @Test - public void getAllTest() throws Exception { - Assert.assertEquals(7, filled.getAll("").size()); // 2 items are skipped - } - - @Test - public void getSubjectTest() throws Exception { - List list = filled.getAll(""); - - Assert.assertEquals("Zajęcia z wychowawcą", list.get(0).getSubject()); - Assert.assertEquals("Język angielski", list.get(3).getSubject()); - Assert.assertEquals("Wychowanie fizyczne", list.get(4).getSubject()); - Assert.assertEquals("Język polski", list.get(5).getSubject()); - } - - @Test - public void getValueTest() throws Exception { - List list = filled.getAll(""); - - Assert.assertEquals("5", list.get(0).getValue()); - Assert.assertEquals("5", list.get(3).getValue()); - Assert.assertEquals("1", list.get(4).getValue()); - Assert.assertEquals("1", list.get(5).getValue()); - } - - @Test - public void getColorTest() throws Exception { - List list = filled.getAll(""); - - Assert.assertEquals("000000", list.get(0).getColor()); - Assert.assertEquals("1289F7", list.get(3).getColor()); - Assert.assertEquals("6ECD07", list.get(4).getColor()); - Assert.assertEquals("6ECD07", list.get(5).getColor()); - } - - @Test - public void getSymbolTest() throws Exception { - List list = filled.getAll(""); - - Assert.assertEquals("A1", list.get(0).getSymbol()); - Assert.assertEquals("BW3", list.get(3).getSymbol()); - Assert.assertEquals("STR", list.get(4).getSymbol()); - Assert.assertEquals("K", list.get(5).getSymbol()); - Assert.assertEquals("+Odp", list.get(6).getSymbol()); - } - - @Test - public void getDescriptionTest() throws Exception { - List list = filled.getAll(""); - - Assert.assertEquals("Dzień Kobiet w naszej klasie", list.get(0).getDescription()); - Assert.assertEquals("Writing", list.get(3).getDescription()); - Assert.assertEquals("", list.get(4).getDescription()); - Assert.assertEquals("Kordian", list.get(5).getDescription()); - Assert.assertEquals("Kordian", list.get(6).getDescription()); - } - - @Test - public void getWeightTest() throws Exception { - List list = filled.getAll(""); - - Assert.assertEquals("1,00", list.get(0).getWeight()); - Assert.assertEquals("3,00", list.get(3).getWeight()); - Assert.assertEquals("8,00", list.get(4).getWeight()); - Assert.assertEquals("5,00", list.get(5).getWeight()); - } - - @Test - public void getDateTest() throws Exception { - List list = filled.getAll(""); - - Assert.assertEquals("2017-03-21", list.get(0).getDate()); - Assert.assertEquals("2017-06-02", list.get(3).getDate()); - Assert.assertEquals("2017-04-02", list.get(4).getDate()); - Assert.assertEquals("2017-02-06", list.get(5).getDate()); - } - - @Test - public void getTeacherTest() throws Exception { - List list = filled.getAll(""); - - Assert.assertEquals("Patryk Maciejewski", list.get(0).getTeacher()); - Assert.assertEquals("Oliwia Woźniak", list.get(3).getTeacher()); - Assert.assertEquals("Klaudia Dziedzic", list.get(4).getTeacher()); - Assert.assertEquals("Amelia Stępień", list.get(5).getTeacher()); - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/grades/GradesSummaryTest.kt b/api/src/test/java/io/github/wulkanowy/api/grades/GradesSummaryTest.kt deleted file mode 100644 index 4eff4390..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/grades/GradesSummaryTest.kt +++ /dev/null @@ -1,59 +0,0 @@ -package io.github.wulkanowy.api.grades - -import io.github.wulkanowy.api.StudentAndParentTestCase -import org.junit.Assert.assertEquals -import org.junit.Test - -class GradesSummaryTest : StudentAndParentTestCase() { - - private val std by lazy { GradesSummary(getSnp("OcenyWszystkie-subjects.html")) } - - private val average by lazy { GradesSummary(getSnp("OcenyWszystkie-subjects-average.html")) } - - @Test fun getSummaryTest() { - assertEquals(5, std.getSummary().size) - assertEquals(5, average.getSummary().size) - } - - @Test fun getNameTest() { - assertEquals("Zachowanie", std.getSummary()[0].name) - assertEquals("Praktyka zawodowa", std.getSummary()[1].name) - assertEquals("Metodologia programowania", std.getSummary()[2].name) - assertEquals("Podstawy przedsiębiorczości", std.getSummary()[3].name) - assertEquals("Wychowanie do życia w rodzinie", std.getSummary()[4].name) - - assertEquals("Zachowanie", average.getSummary()[0].name) - assertEquals("Język polski", average.getSummary()[1].name) - assertEquals("Wychowanie fizyczne", average.getSummary()[2].name) - assertEquals("Język angielski", average.getSummary()[3].name) - assertEquals("Wiedza o społeczeństwie", average.getSummary()[4].name) - } - - @Test fun getPredictedRatingTest() { - assertEquals("bardzo dobre", std.getSummary()[0].predicted) - assertEquals("-", std.getSummary()[1].predicted) - assertEquals("bardzo dobry", std.getSummary()[2].predicted) - assertEquals("3/4", std.getSummary()[3].predicted) - assertEquals("-", std.getSummary()[4].predicted) - - assertEquals("bardzo dobre", average.getSummary()[0].predicted) - assertEquals("-", average.getSummary()[1].predicted) - assertEquals("bardzo dobry", average.getSummary()[2].predicted) - assertEquals("4/5", average.getSummary()[3].predicted) - assertEquals("-", average.getSummary()[4].predicted) - } - - @Test fun getFinalRatingTest() { - assertEquals("bardzo dobre", std.getSummary()[0].final) - assertEquals("celujący", std.getSummary()[1].final) - assertEquals("celujący", std.getSummary()[2].final) - assertEquals("dostateczny", std.getSummary()[3].final) - assertEquals("-", std.getSummary()[4].final) - - assertEquals("bardzo dobre", average.getSummary()[0].final) - assertEquals("dobry", average.getSummary()[1].final) - assertEquals("celujący", average.getSummary()[2].final) - assertEquals("bardzo dobry", average.getSummary()[3].final) - assertEquals("-", average.getSummary()[4].final) - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/grades/GradesTest.kt b/api/src/test/java/io/github/wulkanowy/api/grades/GradesTest.kt deleted file mode 100644 index 958364fd..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/grades/GradesTest.kt +++ /dev/null @@ -1,74 +0,0 @@ -package io.github.wulkanowy.api.grades - -import io.github.wulkanowy.api.StudentAndParentTestCase -import org.junit.Assert -import org.junit.Test - -import org.junit.Assert.* - -class GradesTest : StudentAndParentTestCase() { - - private val filled by lazy { Grades(getSnp("OcenyWszystkie-filled.html")) } - - @Test fun getAllTest() { - Assert.assertEquals(7, filled.getGrades().size) // 2 items are skipped - } - - @Test fun getSubjectTest() { - assertEquals("Zajęcia z wychowawcą", filled.getGrades()[0].subject) - assertEquals("Język angielski", filled.getGrades()[3].subject) - assertEquals("Wychowanie fizyczne", filled.getGrades()[4].subject) - assertEquals("Język polski", filled.getGrades()[5].subject) - } - - @Test fun getValueTest() { - assertEquals("5", filled.getGrades()[0].value) - assertEquals("5", filled.getGrades()[3].value) - assertEquals("1", filled.getGrades()[4].value) - assertEquals("1", filled.getGrades()[5].value) - } - - @Test fun getColorTest() { - assertEquals("000000", filled.getGrades()[0].color) - assertEquals("1289F7", filled.getGrades()[3].color) - assertEquals("6ECD07", filled.getGrades()[4].color) - assertEquals("6ECD07", filled.getGrades()[5].color) - } - - @Test fun getSymbolTest() { - assertEquals("A1", filled.getGrades()[0].symbol) - assertEquals("BW3", filled.getGrades()[3].symbol) - assertEquals("STR", filled.getGrades()[4].symbol) - assertEquals("K", filled.getGrades()[5].symbol) - assertEquals("+Odp", filled.getGrades()[6].symbol) - } - - @Test fun getDescriptionTest() { - assertEquals("Dzień Kobiet w naszej klasie", filled.getGrades()[0].description) - assertEquals("Writing", filled.getGrades()[3].description) - assertEquals("", filled.getGrades()[4].description) - assertEquals("Kordian", filled.getGrades()[5].description) - assertEquals("Kordian", filled.getGrades()[6].description) - } - - @Test fun getWeightTest() { - assertEquals("1,00", filled.getGrades()[0].weight) - assertEquals("3,00", filled.getGrades()[3].weight) - assertEquals("8,00", filled.getGrades()[4].weight) - assertEquals("5,00", filled.getGrades()[5].weight) - } - - @Test fun getDateTest() { - assertEquals("2017-03-21", filled.getGrades()[0].date) - assertEquals("2017-06-02", filled.getGrades()[3].date) - assertEquals("2017-04-02", filled.getGrades()[4].date) - assertEquals("2017-02-06", filled.getGrades()[5].date) - } - - @Test fun getTeacherTest() { - assertEquals("Patryk Maciejewski", filled.getGrades()[0].teacher) - assertEquals("Oliwia Woźniak", filled.getGrades()[3].teacher) - assertEquals("Klaudia Dziedzic", filled.getGrades()[4].teacher) - assertEquals("Amelia Stępień", filled.getGrades()[5].teacher) - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/grades/SubjectsListTest.java b/api/src/test/java/io/github/wulkanowy/api/grades/SubjectsListTest.java deleted file mode 100644 index d3228378..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/grades/SubjectsListTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package io.github.wulkanowy.api.grades; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.List; - -import io.github.wulkanowy.api.StudentAndParentTestCase; - -public class SubjectsListTest extends StudentAndParentTestCase { - - private SubjectsList std; - - private SubjectsList average; - - @Before - public void setUp() throws Exception { - std = new SubjectsList(getSnp("OcenyWszystkie-subjects.html")); - average = new SubjectsList(getSnp("OcenyWszystkie-subjects-average.html")); - } - - @Test - public void getAllTest() throws Exception { - Assert.assertEquals(5, std.getAll().size()); - Assert.assertEquals(5, average.getAll().size()); - } - - @Test - public void getNameTest() throws Exception { - List stdList = std.getAll(); - - Assert.assertEquals("Zachowanie", stdList.get(0).getName()); - Assert.assertEquals("Praktyka zawodowa", stdList.get(1).getName()); - Assert.assertEquals("Metodologia programowania", stdList.get(2).getName()); - Assert.assertEquals("Podstawy przedsiębiorczości", stdList.get(3).getName()); - Assert.assertEquals("Wychowanie do życia w rodzinie", stdList.get(4).getName()); - - List averageList = average.getAll(); - Assert.assertEquals("Zachowanie", averageList.get(0).getName()); - Assert.assertEquals("Język polski", averageList.get(1).getName()); - Assert.assertEquals("Wychowanie fizyczne", averageList.get(2).getName()); - Assert.assertEquals("Język angielski", averageList.get(3).getName()); - Assert.assertEquals("Wiedza o społeczeństwie", averageList.get(4).getName()); - } - - @Test - public void getPredictedRatingTest() throws Exception { - List stdList = std.getAll(); - - Assert.assertEquals("bardzo dobre", stdList.get(0).getPredictedRating()); - Assert.assertEquals("-", stdList.get(1).getPredictedRating()); - Assert.assertEquals("bardzo dobry", stdList.get(2).getPredictedRating()); - Assert.assertEquals("3/4", stdList.get(3).getPredictedRating()); - Assert.assertEquals("-", stdList.get(4).getPredictedRating()); - - List averageList = average.getAll(); - Assert.assertEquals("bardzo dobre", averageList.get(0).getPredictedRating()); - Assert.assertEquals("-", averageList.get(1).getPredictedRating()); - Assert.assertEquals("bardzo dobry", averageList.get(2).getPredictedRating()); - Assert.assertEquals("4/5", averageList.get(3).getPredictedRating()); - Assert.assertEquals("-", averageList.get(4).getPredictedRating()); - } - - @Test - public void getFinalRatingTest() throws Exception { - List stdList = std.getAll(); - - Assert.assertEquals("bardzo dobre", stdList.get(0).getFinalRating()); - Assert.assertEquals("celujący", stdList.get(1).getFinalRating()); - Assert.assertEquals("celujący", stdList.get(2).getFinalRating()); - Assert.assertEquals("dostateczny", stdList.get(3).getFinalRating()); - Assert.assertEquals("-", stdList.get(4).getFinalRating()); - - List averageList = average.getAll(); - Assert.assertEquals("bardzo dobre", averageList.get(0).getFinalRating()); - Assert.assertEquals("dobry", averageList.get(1).getFinalRating()); - Assert.assertEquals("celujący", averageList.get(2).getFinalRating()); - Assert.assertEquals("bardzo dobry", averageList.get(3).getFinalRating()); - Assert.assertEquals("-", averageList.get(4).getFinalRating()); - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/homework/HomeworkListTest.kt b/api/src/test/java/io/github/wulkanowy/api/homework/HomeworkListTest.kt deleted file mode 100644 index 5fe53a78..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/homework/HomeworkListTest.kt +++ /dev/null @@ -1,44 +0,0 @@ -package io.github.wulkanowy.api.homework - -import io.github.wulkanowy.api.StudentAndParentTestCase -import org.junit.Assert.assertEquals -import org.junit.Test - -class HomeworkListTest : StudentAndParentTestCase() { - - private val snp by lazy { getSnp("ZadaniaDomowe.html") } - - @Test fun getHomework() { - assertEquals(2, HomeworkList(snp).getHomework().size) - } - - @Test fun getDate() { - assertEquals("2018-08-13", HomeworkList(snp).getHomework("2018-08-13")[0].date) - assertEquals("1970-01-01", HomeworkList(snp).getHomework("1970-01-01")[1].date) - } - - @Test fun getSubject() { - assertEquals("Sieci komputerowe i administrowanie sieciami", HomeworkList(snp).getHomework()[0].subject) - assertEquals("Naprawa komputera", HomeworkList(snp).getHomework()[1].subject) - } - - @Test fun getContent() { - assertEquals("Zadania egzaminacyjne", HomeworkList(snp).getHomework()[0].content) - assertEquals("Test diagnozujący", HomeworkList(snp).getHomework()[1].content) - } - - @Test fun getTeacher() { - assertEquals("Słowacki Juliusz", HomeworkList(snp).getHomework()[0].teacher) - assertEquals("Mickiewicz Adam", HomeworkList(snp).getHomework()[1].teacher) - } - - @Test fun getTeacherSymbol() { - assertEquals("SJ", HomeworkList(snp).getHomework()[0].teacherSymbol) - assertEquals("MA", HomeworkList(snp).getHomework()[1].teacherSymbol) - } - - @Test fun getEntryDate() { - assertEquals("2017-10-16", HomeworkList(snp).getHomework()[0].entryDate) - assertEquals("2017-10-25", HomeworkList(snp).getHomework()[1].entryDate) - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/login/LoginTest.java b/api/src/test/java/io/github/wulkanowy/api/login/LoginTest.java deleted file mode 100644 index 86a3ef40..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/login/LoginTest.java +++ /dev/null @@ -1,131 +0,0 @@ -package io.github.wulkanowy.api.login; - -import org.jsoup.Jsoup; -import org.jsoup.nodes.Document; -import org.junit.Assert; -import org.junit.Test; -import org.mockito.Mockito; - -import io.github.wulkanowy.api.Client; -import io.github.wulkanowy.api.FixtureHelper; - -public class LoginTest { - - private Document getFixtureAsDocument(String fixtureFileName) { - return Jsoup.parse(getFixtureAsString(fixtureFileName)); - } - - private String getFixtureAsString(String fixtureFileName) { - return FixtureHelper.getAsString(getClass().getResourceAsStream(fixtureFileName)); - } - - private Client getClient(String fixtureFileName) throws Exception { - Document doc = getFixtureAsDocument(fixtureFileName); - - Client client = Mockito.mock(Client.class); - Mockito.when(client.postPageByUrl(Mockito.anyString(), Mockito.any(String[][].class))).thenReturn(doc); - Mockito.when(client.getPageByUrl(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(doc); - - return client; - } - - @Test - public void loginTest() throws Exception { - Client client = getClient("Logowanie-success.html"); - Mockito.when(client.getPageByUrl(Mockito.anyString(), Mockito.anyBoolean())) - .thenReturn(getFixtureAsDocument("Logowanie-error.html")); - Mockito.when(client.postPageByUrl(Mockito.eq(Login.LOGIN_PAGE_URL), Mockito.any(String[][].class))) - .thenReturn(getFixtureAsDocument("Logowanie-certyfikat.html")); - Mockito.doCallRealMethod().when(client).setSymbol(Mockito.anyString()); - Mockito.when(client.getSymbol()).thenCallRealMethod(); - Mockito.when(client.getHost()).thenReturn("fakelog.cf"); - Login login = new Login(client); - login.login("a@a", "pswd", "d123"); - - Assert.assertEquals("d123", client.getSymbol()); - } - - @Test(expected = BadCredentialsException.class) - public void sendWrongCredentialsTest() throws Exception { - Client client = getClient("Logowanie-error.html"); - Mockito.when(client.getPageByUrl(Mockito.anyString(), Mockito.anyBoolean())) - .thenReturn(getFixtureAsDocument("Logowanie-error.html")); // -error.html because it html with form used by - Login login = new Login(client); - - login.sendCredentials("a@a", "pswd"); - } - - @Test - public void sendCredentialsCertificateTest() throws Exception { - Client client = getClient("Logowanie-certyfikat.html"); - Mockito.when(client.getPageByUrl(Mockito.anyString(), Mockito.anyBoolean())) - .thenReturn(getFixtureAsDocument("Logowanie-error.html")); // -error.html because it html with form used by - Login login = new Login(client); - - Assert.assertEquals( - getFixtureAsString("cert-stock.xml").replaceAll("\\s+", ""), - login.sendCredentials("a@a", "passwd") - .select("input[name=wresult]") - .attr("value") - .replaceAll("\\s+", "") - ); - } - - @Test - public void sendCertificateNotDefaultSymbolSuccessTest() throws Exception { - Client client = getClient("Logowanie-success.html"); - Mockito.doCallRealMethod().when(client).setSymbol(Mockito.anyString()); - Mockito.when(client.getSymbol()).thenCallRealMethod(); - Mockito.when(client.getHost()).thenReturn("fakelog.cf"); - Login login = new Login(client); - - login.sendCertificate(getFixtureAsDocument("Logowanie-certyfikat.html"), "wulkanowyschool321"); - - Assert.assertEquals("wulkanowyschool321", client.getSymbol()); - } - - @Test - public void sendCertificateDefaultSymbolSuccessTest() throws Exception { - Client client = getClient("Logowanie-success.html"); - Mockito.doCallRealMethod().when(client).setSymbol(Mockito.anyString()); - Mockito.when(client.getSymbol()).thenCallRealMethod(); - Mockito.when(client.getHost()).thenReturn("fakelog.cf"); - Login login = new Login(client); - - login.sendCertificate(getFixtureAsDocument("Logowanie-certyfikat.html"), "Default"); - - Assert.assertEquals("demo12345", client.getSymbol()); - } - - @Test(expected = AccountPermissionException.class) - public void sendCertificateAccountPermissionTest() throws Exception { - Client client = getClient("Logowanie-brak-dostepu.html"); - - Login login = new Login(client); - - login.sendCertificate(getFixtureAsDocument("Logowanie-certyfikat.html"), "demo123"); - } - - @Test(expected = LoginErrorException.class) - public void sendCertificateLoginErrorTest() throws Exception { - Login login = new Login(getClient("Logowanie-certyfikat.html")); // change to other document - - login.sendCertificate(getFixtureAsDocument("Logowanie-certyfikat.html"), "demo123"); - } - - @Test - public void findSymbolInCertificateTest() throws Exception { - Login login = new Login(getClient("Logowanie-certyfikat.html")); - - String certificate = getFixtureAsString("cert-stock.xml"); - - Assert.assertEquals("demo12345", login.findSymbolInCertificate(certificate)); - } - - @Test(expected = AccountPermissionException.class) - public void findSymbolInCertificateWithoutSecondInstanceTest() throws Exception { - Login login = new Login(getClient("Logowanie-certyfikat.html")); - - login.findSymbolInCertificate(getFixtureAsString("cert-no-symbols.xml")); - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/login/StartPageTest.kt b/api/src/test/java/io/github/wulkanowy/api/login/StartPageTest.kt deleted file mode 100644 index 271b3bb0..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/login/StartPageTest.kt +++ /dev/null @@ -1,68 +0,0 @@ -package io.github.wulkanowy.api.login - -import io.github.wulkanowy.api.Client -import io.github.wulkanowy.api.FixtureHelper -import io.github.wulkanowy.api.VulcanException -import org.jsoup.Jsoup -import org.jsoup.nodes.Document -import org.junit.Assert.assertEquals -import org.junit.Before -import org.junit.Test -import org.mockito.Mockito -import org.mockito.Mockito.mock - -class StartPageTest { - - private val client: Client = mock(Client::class.java) - - @Before fun setUp() { - Mockito.`when`(client.host).thenReturn("fakelog.cf") - } - - private fun getDoc(name: String): Document = Jsoup.parse(FixtureHelper.getAsString(javaClass.getResourceAsStream(name))) - - @Test fun getSchoolTest() { - assertEquals("534213", StartPage(client).getSchools(getDoc("../Start-std.html"))[0].id) - } - - @Test fun getMultiSchoolTest() { - val schools = StartPage(client).getSchools(getDoc("../Start-multi.html")) - - assertEquals("123456", schools[0].id) - assertEquals("123457", schools[1].id) - } - - @Test fun getSchoolNameTest() { - assertEquals("Uczeń", StartPage(client).getSchools(getDoc("../Start-std.html"))[0].name) - } - - @Test fun getMultiSchoolNameTest() { - val schools = StartPage(client).getSchools(getDoc("../Start-multi.html")) - - assertEquals("GIMBB", schools[0].name) - assertEquals("SPBB", schools[1].name) - } - - @Test(expected = VulcanException::class) - fun getSnpPageUrlWithWrongPage() { - StartPage(client).getSchools(getDoc("../OcenyWszystkie-semester.html")) - } - - @Test - fun getExtractedIDStandardTest() { - assertEquals("123456", StartPage(client) - .getExtractedIdFromUrl("https://uonetplus-opiekun.fakelog.cf/powiat/123456/Start/Index/")) - } - - @Test - fun getExtractedIDDemoTest() { - assertEquals("demo12345", StartPage(client) - .getExtractedIdFromUrl("https://uonetplus-opiekun.fakelog.cf/demoupowiat/demo12345/Start/Index/")) - } - - @Test(expected = VulcanException::class) - fun getExtractedIDNotLoggedTest() { - assertEquals("123", StartPage(client) - .getExtractedIdFromUrl("https://uonetplus.NOTfakelog.cf/powiat/")) - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/messages/MessagesTest.java b/api/src/test/java/io/github/wulkanowy/api/messages/MessagesTest.java deleted file mode 100644 index 14fa4627..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/messages/MessagesTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package io.github.wulkanowy.api.messages; - -import org.junit.Assert; -import org.junit.Test; -import org.mockito.Mockito; - -import java.util.List; - -import io.github.wulkanowy.api.Client; -import io.github.wulkanowy.api.FixtureHelper; -import io.github.wulkanowy.api.NotLoggedInErrorException; - -public class MessagesTest { - - private Client getFixtureAsString(String fixtureFileName) throws Exception { - Client client = Mockito.mock(Client.class); - Mockito.when(client.getJsonStringByUrl(Mockito.anyString())) - .thenReturn(FixtureHelper.getAsString(getClass().getResourceAsStream(fixtureFileName))); - Mockito.when(client.postJsonStringByUrl(Mockito.anyString(), Mockito.any())) - .thenReturn(FixtureHelper.getAsString(getClass().getResourceAsStream(fixtureFileName))); - return client; - } - - @Test - public void getMessages() throws Exception { - Client client = getFixtureAsString("GetWiadomosciOdebrane.json"); - - Messages messages = new Messages(client); - List messageList = messages.getReceived(); - - Assert.assertEquals(true, messageList.get(1).unread); - Assert.assertEquals("2016-03-15 09:00:00", messageList.get(0).date); - Assert.assertEquals(null, messageList.get(0).content); - Assert.assertEquals("Kowalski Jan", messageList.get(0).sender); - Assert.assertEquals(12347, messageList.get(2).id); - } - - @Test - public void getMessagesEmpty() throws Exception { - Client client = getFixtureAsString("GetWiadomosciUsuniete-empty.json"); - - Messages messages = new Messages(client); - List messageList = messages.getSent(); - - Assert.assertTrue(messageList.isEmpty()); - } - - @Test(expected = NotLoggedInErrorException.class) - public void getMessagesError() throws Exception { - Client client = getFixtureAsString("UndefinedError.txt"); - - Messages messages = new Messages(client); - messages.getDeleted(); - } - - @Test(expected = BadRequestException.class) - public void getMessagesBadRequest() throws Exception { - Client client = getFixtureAsString("PageError.html"); - - Messages messages = new Messages(client); - messages.getDeleted(); - } - - @Test - public void getMessage() throws Exception { - Client client = getFixtureAsString("GetTrescWiadomosci.json"); - - Messages messages = new Messages(client); - Message message = messages.getMessage(123, Messages.RECEIVED_FOLDER); - Assert.assertEquals(12345, message.id); - Assert.assertEquals("Witam, …. \nPozdrawiam Krzysztof Czerkas", message.content); - } - - @Test(expected = NotLoggedInErrorException.class) - public void getMessageError() throws Exception { - Client client = getFixtureAsString("UndefinedError.txt"); - - Messages messages = new Messages(client); - messages.getMessage(321, Messages.SENT_FOLDER); - } - - @Test(expected = BadRequestException.class) - public void getMessageBadRequest() throws Exception { - Client client = getFixtureAsString("PageError.html"); - - Messages messages = new Messages(client); - messages.getMessage(1, Messages.DELETED_FOLDER); - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/mobile/RegisterDevice.kt b/api/src/test/java/io/github/wulkanowy/api/mobile/RegisterDevice.kt deleted file mode 100644 index f67310c8..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/mobile/RegisterDevice.kt +++ /dev/null @@ -1,17 +0,0 @@ -package io.github.wulkanowy.api.mobile - -import io.github.wulkanowy.api.StudentAndParentTestCase -import org.junit.Assert.assertEquals -import org.junit.Test - -class RegisterDeviceTest : StudentAndParentTestCase() { - - @Test - fun getTokenTest() { - val registration = RegisterDevice(getSnp("Rejestruj.html")) - - assertEquals("3S1A1B2C", registration.getToken().token) - assertEquals("Default", registration.getToken().symbol) - assertEquals("1234567", registration.getToken().pin) - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/mobile/RegisteredDevicesListTest.kt b/api/src/test/java/io/github/wulkanowy/api/mobile/RegisteredDevicesListTest.kt deleted file mode 100644 index 3cd8b97c..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/mobile/RegisteredDevicesListTest.kt +++ /dev/null @@ -1,37 +0,0 @@ -package io.github.wulkanowy.api.mobile - -import io.github.wulkanowy.api.StudentAndParentTestCase -import org.junit.Assert.assertEquals -import org.junit.Test - -class RegisteredDevicesListTest : StudentAndParentTestCase() { - - private val filled = RegisteredDevices(getSnp("DostepMobilny-filled.html")) - - @Test - fun getListTest() { - assertEquals(2, filled.getList().size) - } - - @Test - fun getNameTest() { - assertEquals("google Android SDK built for x86", filled.getList()[0].name) - assertEquals("google (Android SDK) built for x86", filled.getList()[1].name) - } - - @Test - fun getSystemTest() { - assertEquals("Android 8.1.0", filled.getList()[0].system) - assertEquals("Android 8.1.0", filled.getList()[1].system) - } - - @Test - fun getDateTest() { - assertEquals("2018-01-20 22:35:30", filled.getList()[0].date) - } - - @Test - fun getIdTest() { - assertEquals(321, filled.getList()[0].id) - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/notes/AchievementsListTest.java b/api/src/test/java/io/github/wulkanowy/api/notes/AchievementsListTest.java deleted file mode 100644 index 0d7774bb..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/notes/AchievementsListTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package io.github.wulkanowy.api.notes; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.List; - -import io.github.wulkanowy.api.StudentAndParentTestCase; - -public class AchievementsListTest extends StudentAndParentTestCase { - - private AchievementsList filledAchievementsList; - - private AchievementsList emptyAchievementsList; - - @Before - public void setUp() throws Exception { - filledAchievementsList = new AchievementsList(getSnp("UwagiOsiagniecia-filled.html")); - emptyAchievementsList = new AchievementsList(getSnp("UwagiOsiagniecia-empty.html")); - } - - @Test - public void getAllAchievementsTest() throws Exception { - Assert.assertEquals(2, filledAchievementsList.getAllAchievements().size()); - Assert.assertEquals(0, emptyAchievementsList.getAllAchievements().size()); - } - - @Test - public void getAchievements() throws Exception { - List filledList = filledAchievementsList.getAllAchievements(); - - Assert.assertEquals("I miejsce w ogólnopolskim konkursie ortograficznym", filledList.get(0)); - Assert.assertEquals("III miejsce w ogólnopolskim konkursie plastycznym", filledList.get(1)); - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/notes/NotesListTest.java b/api/src/test/java/io/github/wulkanowy/api/notes/NotesListTest.java deleted file mode 100644 index 304eb01a..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/notes/NotesListTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package io.github.wulkanowy.api.notes; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.List; - -import io.github.wulkanowy.api.StudentAndParentTestCase; - -public class NotesListTest extends StudentAndParentTestCase { - - private NotesList filled; - - private NotesList empty; - - @Before - public void setUp() throws Exception { - filled = new NotesList(getSnp("UwagiOsiagniecia-filled.html")); - empty = new NotesList(getSnp("UwagiOsiagniecia-empty.html")); - } - - @Test - public void getAllNotesTest() throws Exception { - Assert.assertEquals(3, filled.getAllNotes().size()); - Assert.assertEquals(0, empty.getAllNotes().size()); - } - - @Test - public void getDateTest() throws Exception { - List filledList = filled.getAllNotes(); - - Assert.assertEquals("2017-06-06", filledList.get(0).getDate()); - Assert.assertEquals("2016-10-01", filledList.get(2).getDate()); - } - - @Test - public void getTeacherTest() throws Exception { - List filledList = filled.getAllNotes(); - - Assert.assertEquals("Jan Kowalski [JK]", filledList.get(0).getTeacher()); - Assert.assertEquals("Kochański Leszek [KL]", filledList.get(2).getTeacher()); - } - - @Test - public void getCategoryTest() throws Exception { - List filledList = filled.getAllNotes(); - - Assert.assertEquals("Zaangażowanie społeczne", filledList.get(0).getCategory()); - Assert.assertEquals("Zachowanie na lekcji", filledList.get(2).getCategory()); - } - - @Test - public void getContentTest() throws Exception { - List filledList = filled.getAllNotes(); - - Assert.assertEquals("Pomoc przy pikniku charytatywnym", filledList.get(0).getContent()); - Assert.assertEquals("Przeszkadzanie w prowadzeniu lekcji", filledList.get(2).getContent()); - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/school/SchoolInfoTest.java b/api/src/test/java/io/github/wulkanowy/api/school/SchoolInfoTest.java deleted file mode 100644 index 947db9b8..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/school/SchoolInfoTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package io.github.wulkanowy.api.school; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import io.github.wulkanowy.api.StudentAndParentTestCase; - -public class SchoolInfoTest extends StudentAndParentTestCase { - - private SchoolInfo schoolInfo; - - @Before - public void setUp() throws Exception { - schoolInfo = new SchoolInfo(getSnp("Szkola.html")); - } - - @Test - public void getNameTest() throws Exception { - Assert.assertEquals("Zespół Szkół nr 64", schoolInfo.getSchoolData().getName()); - } - - @Test - public void getAddressTest() throws Exception { - Assert.assertEquals("ul. Wiśniowa 128, 01-234 Rogalowo, Nibylandia", - schoolInfo.getSchoolData().getAddress()); - } - - @Test - public void getPhoneNumberTest() throws Exception { - Assert.assertEquals("55 5555555", schoolInfo.getSchoolData().getPhoneNumber()); - } - - @Test - public void getHeadmasterTest() throws Exception { - Assert.assertEquals("Antoni Sobczyk", schoolInfo.getSchoolData().getHeadmaster()); - } - - @Test - public void getPedagoguesTest() throws Exception { - Assert.assertArrayEquals(new String[]{ - "Zofia Czerwińska [ZC]", - "Aleksander Krzemiński [AK]", - "Karolina Kowalska [KK]", - "Bartek Dąbrowski [BD]" - }, schoolInfo.getSchoolData().getPedagogues()); - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/school/TeachersInfoTest.java b/api/src/test/java/io/github/wulkanowy/api/school/TeachersInfoTest.java deleted file mode 100644 index b0da356b..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/school/TeachersInfoTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package io.github.wulkanowy.api.school; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.List; - -import io.github.wulkanowy.api.StudentAndParentTestCase; - -public class TeachersInfoTest extends StudentAndParentTestCase { - - private TeachersInfo teachersInfo; - - @Before - public void setUp() throws Exception { - teachersInfo = new TeachersInfo(getSnp("Szkola.html")); - } - - @Test - public void getClassNameTest() throws Exception { - Assert.assertEquals("1a", teachersInfo.getTeachersData().getClassName()); - } - - @Test - public void getClassTeacherTest() throws Exception { - Assert.assertArrayEquals(new String[]{ - "Karolina Kowalska [AN]", - "Antoni Sobczyk [AS]" - }, teachersInfo.getTeachersData().getClassTeacher()); - } - - @Test - public void getTeachersDataSubjectsNameTest() throws Exception { - List subjects = teachersInfo.getTeachersData().getSubjects(); - - Assert.assertEquals("Biologia", subjects.get(0).getName()); - Assert.assertEquals("Język angielski", subjects.get(6).getName()); - } - - @Test - public void getTeachersDataSubjectsTeachersTest() throws Exception { - List subjects = teachersInfo.getTeachersData().getSubjects(); - - Assert.assertArrayEquals(new String[]{"Karolina Kowalska [AN]"}, - subjects.get(0).getTeachers()); - Assert.assertEquals("Karolina Kowalska [AN]", - subjects.get(0).getTeachers()[0]); - - Assert.assertArrayEquals(new String[]{ - "Karolina Kowalska [AN]", - "Mateusz Kowal [MK]", - "Amelia Mazur [AM]" - }, subjects.get(6).getTeachers()); - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/timetable/TimetableKtTest.kt b/api/src/test/java/io/github/wulkanowy/api/timetable/TimetableKtTest.kt deleted file mode 100644 index 503d8ede..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/timetable/TimetableKtTest.kt +++ /dev/null @@ -1,183 +0,0 @@ -package io.github.wulkanowy.api.timetable - -import io.github.wulkanowy.api.StudentAndParentTestCase -import org.junit.Assert.* -import org.junit.Test - -class TimetableKtTest : StudentAndParentTestCase() { - - private val std by lazy { TimetableKt(getSnp("PlanLekcji-std.html")) } - - private val full by lazy { TimetableKt(getSnp("PlanLekcji-full.html")) } - - private val holidays by lazy { TimetableKt(getSnp("PlanLekcji-holidays.html")) } - - @Test fun getTimetableTest() { - assertEquals(32, std.getTimetable().size) - assertEquals(43, full.getTimetable().size) - assertEquals(0, holidays.getTimetable().size) - } - - @Test fun getStartDayDateTest() { - assertEquals("2017-06-19", std.getTimetable()[0].date) - assertEquals("2017-06-20", std.getTimetable()[8].date) - assertEquals("2017-06-21", std.getTimetable()[16].date) - - assertEquals("2017-06-19", full.getTimetable()[0].date) - assertEquals("2017-06-20", full.getTimetable()[10].date) - assertEquals("2017-06-22", full.getTimetable()[30].date) - } - - @Test fun getDayIsFreeTest() { - assertFalse(std.getTimetable().first().freeDayName.isNotEmpty()) - assertFalse(full.getTimetable().last().freeDayName.isNotEmpty()) - } - - @Test fun getDayFreeDayName() { - assertNotEquals("Wakacje", std.getTimetable()[0].freeDayName) - assertNotEquals("Ferie letnie", full.getTimetable()[15].freeDayName) - } - - @Test fun getLessonNumberTest() { - assertEquals(2, std.getTimetable()[1].number) - assertEquals(5, std.getTimetable()[10].number) - - assertEquals(0, full.getTimetable()[0].number) - assertEquals(9, full.getTimetable()[19].number) - } - - @Test fun getLessonSubjectTest() { - assertEquals("Historia", std.getTimetable()[1].subject) - assertEquals("Zajęcia techniczne", std.getTimetable()[17].subject) - assertEquals("Wychowanie fizyczne", std.getTimetable()[7].subject) - - assertEquals("Fizyka", full.getTimetable()[0].subject) - assertEquals("Język angielski", full.getTimetable()[1].subject) - assertEquals("Wychowanie fizyczne", full.getTimetable()[9].subject) - assertEquals("Metodologia programowania", full.getTimetable()[10].subject) - assertEquals("Wychowanie do życia w rodzinie", full.getTimetable()[20].subject) - assertEquals("Wychowanie fizyczne", full.getTimetable()[30].subject) - assertEquals("Uroczyste zakończenie roku szkolnego", full.getTimetable()[37].subject) - assertEquals("Język niemiecki", full.getTimetable()[39].subject) - } - - @Test fun getLessonTeacherTest() { - assertEquals("Bogatka Katarzyna", std.getTimetable()[1].teacher) - assertEquals("Chlebowski Stanisław", std.getTimetable()[17].teacher) - - assertEquals("Kobczyk Iwona", full.getTimetable()[1].teacher) - assertEquals("Bączek Grzegorz", full.getTimetable()[7].teacher) - assertEquals("Nowak Jadwiga", full.getTimetable()[20].teacher) - assertEquals("Nowicka Irena", full.getTimetable()[30].teacher) - assertEquals("Baran Małgorzata", full.getTimetable()[37].teacher) - assertEquals("", full.getTimetable()[38].teacher) - } - - @Test fun getLessonRoomTest() { - assertEquals("", std.getTimetable()[15].room) - - assertEquals("19", full.getTimetable()[0].room) - assertEquals("33", full.getTimetable()[7].room) - assertEquals("32", full.getTimetable()[10].room) - assertEquals("32", full.getTimetable()[18].room) - assertEquals("32", full.getTimetable()[28].room) - assertEquals("G4", full.getTimetable()[30].room) - assertEquals("37", full.getTimetable()[37].room) - } - - @Test fun getLessonDescriptionTest() { - assertEquals("", std.getTimetable()[15].description) - - assertEquals("okienko dla uczniów", full.getTimetable()[7].description) - assertEquals("przeniesiona z lekcji 7, 01.12.2017", full.getTimetable()[11].description) - assertEquals("przeniesiona z lekcji 7, 20.06.2017", full.getTimetable()[12].description) - assertEquals("przeniesiona z lekcji 4, 20.06.2017", full.getTimetable()[13].description) - assertEquals("zastępstwo (poprzednio: Religia)", full.getTimetable()[20].description) - assertEquals("egzamin", full.getTimetable()[29].description) - assertEquals("zastępstwo (poprzednio: Wychowanie fizyczne)", full.getTimetable()[30].description) - assertEquals("", full.getTimetable()[37].description) - assertEquals("", full.getTimetable()[38].description) - assertEquals("poprzednio: Wychowanie fizyczne", full.getTimetable()[39].description) - assertEquals("bez nawiasów (poprzednio: Religia)", full.getTimetable()[40].description) - assertEquals("opis w uwadze bez klasy w spanie", full.getTimetable()[41].description) - assertEquals("poprzednio: Zajęcia z wychowawcą", full.getTimetable()[42].description) - } - - @Test fun getLessonGroupNameTest() { - assertEquals("CH", std.getTimetable()[2].groupName) - assertEquals("JNPW", std.getTimetable()[26].groupName) - - assertEquals("", full.getTimetable()[7].groupName) - assertEquals("zaw2", full.getTimetable()[10].groupName) - assertEquals("wf2", full.getTimetable()[13].groupName) - assertEquals("zaw1", full.getTimetable()[30].groupName) - } - - @Test fun getLessonStartTimeTest() { - assertEquals("08:00", std.getTimetable()[0].startTime) - assertEquals("13:20", std.getTimetable()[12].startTime) - - assertEquals("07:10", full.getTimetable()[0].startTime) - assertEquals("12:20", full.getTimetable()[26].startTime) - } - - @Test fun getLessonEndTimeTest() { - assertEquals("08:45", std.getTimetable()[0].endTime) - assertEquals("14:05", std.getTimetable()[12].endTime) - - assertEquals("07:55", full.getTimetable()[10].endTime) - assertEquals("13:55", full.getTimetable()[36].endTime) - } - - @Test fun getLessonIsEmptyTest() { - assertFalse(std.getTimetable()[9].empty) - - assertFalse(full.getTimetable()[7].empty) - assertFalse(full.getTimetable()[10].empty) - assertFalse(full.getTimetable()[12].empty) - } - - @Test fun getLessonIsDivisionIntoGroupsTest() { - assertTrue(std.getTimetable()[2].divisionIntoGroups) - assertTrue(std.getTimetable()[26].divisionIntoGroups) - - assertFalse(full.getTimetable()[7].divisionIntoGroups) - assertTrue(full.getTimetable()[13].divisionIntoGroups) - assertTrue(full.getTimetable()[30].divisionIntoGroups) - } - - @Test fun getLessonIsPlanningTest() { - assertFalse(std.getTimetable()[30].planning) - - assertFalse(full.getTimetable()[1].planning) - assertTrue(full.getTimetable()[13].planning) - assertTrue(full.getTimetable()[37].planning) - } - - @Test fun getLessonIsRealizedTest() { - assertTrue(std.getTimetable()[15].realized) - - assertTrue(full.getTimetable()[1].realized) - assertTrue(full.getTimetable()[13].realized) - assertFalse(full.getTimetable()[37].realized) - } - - @Test fun getLessonIsMovedOrCanceledTest() { - assertFalse(std.getTimetable()[15].movedOrCanceled) - - assertTrue(full.getTimetable()[7].movedOrCanceled) - assertFalse(full.getTimetable()[13].movedOrCanceled) - assertFalse(full.getTimetable()[37].movedOrCanceled) - } - - @Test fun getLessonIsNewMovedInOrChangedTest() { - assertFalse(std.getTimetable()[15].newMovedInOrChanged) - - assertFalse(full.getTimetable()[1].newMovedInOrChanged) - assertTrue(full.getTimetable()[12].newMovedInOrChanged) - assertTrue(full.getTimetable()[13].newMovedInOrChanged) - assertTrue(full.getTimetable()[30].newMovedInOrChanged) - assertFalse(full.getTimetable()[38].newMovedInOrChanged) - assertTrue(full.getTimetable()[39].newMovedInOrChanged) - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/timetable/TimetableTest.java b/api/src/test/java/io/github/wulkanowy/api/timetable/TimetableTest.java deleted file mode 100644 index 7b3cce6e..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/timetable/TimetableTest.java +++ /dev/null @@ -1,253 +0,0 @@ -package io.github.wulkanowy.api.timetable; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import io.github.wulkanowy.api.StudentAndParentTestCase; - -public class TimetableTest extends StudentAndParentTestCase { - - private Timetable std; - - private Timetable full; - - private Timetable holidays; - - @Before - public void setUp() throws Exception { - std = new Timetable(getSnp("PlanLekcji-std.html")); - full = new Timetable(getSnp("PlanLekcji-full.html")); - holidays = new Timetable(getSnp("PlanLekcji-holidays.html")); - } - - // Week - - @Test - public void getWeekTableTest() throws Exception { - Assert.assertEquals(5, std.getWeekTable().getDays().size()); - Assert.assertEquals(5, full.getWeekTable().getDays().size()); - Assert.assertEquals(5, holidays.getWeekTable().getDays().size()); - } - - @Test - public void getStartDayDateTest() throws Exception { - Assert.assertEquals("2017-06-19", std.getWeekTable().getStartDayDate()); - Assert.assertEquals("2017-06-19", full.getWeekTable().getStartDayDate()); - Assert.assertEquals("2017-07-31", holidays.getWeekTable().getStartDayDate()); - } - - // ExamDay - - @Test - public void getDayNameTest() throws Exception { - Assert.assertEquals("poniedziałek", std.getWeekTable().getDay(0).getDayName()); - Assert.assertEquals("piątek", std.getWeekTable().getDay(4).getDayName()); - Assert.assertEquals("wtorek", full.getWeekTable().getDay(1).getDayName()); - Assert.assertEquals("czwartek", full.getWeekTable().getDay(3).getDayName()); - Assert.assertEquals("środa", holidays.getWeekTable().getDay(2).getDayName()); - } - - @Test - public void getDayDateTest() throws Exception { - Assert.assertEquals("2017-06-19", std.getWeekTable().getDay(0).getDate()); - Assert.assertEquals("2017-06-23", std.getWeekTable().getDay(4).getDate()); - Assert.assertEquals("2017-06-20", full.getWeekTable().getDay(1).getDate()); - Assert.assertEquals("2017-06-22", full.getWeekTable().getDay(3).getDate()); - Assert.assertEquals("2017-08-02", holidays.getWeekTable().getDay(2).getDate()); - } - - @Test - public void getDayIsFreeTest() throws Exception { - Assert.assertFalse(std.getWeekTable().getDay(0).isFreeDay()); - Assert.assertFalse(full.getWeekTable().getDay(2).isFreeDay()); - Assert.assertTrue(holidays.getWeekTable().getDay(4).isFreeDay()); - } - - @Test - public void getDayFreeDayName() throws Exception { - Assert.assertNotEquals("Wakacje", std.getWeekTable().getDay(0).getFreeDayName()); - Assert.assertNotEquals("Ferie letnie", full.getWeekTable().getDay(1).getFreeDayName()); - Assert.assertNotEquals("Wakacje", holidays.getWeekTable().getDay(2).getFreeDayName()); - Assert.assertEquals("Ferie letnie", holidays.getWeekTable().getDay(4).getFreeDayName()); - } - - @Test - public void getDayLessonsTest() throws Exception { - Assert.assertEquals(8, std.getWeekTable().getDay(0).getLessons().size()); - Assert.assertEquals(14, full.getWeekTable().getDay(2).getLessons().size()); - Assert.assertEquals(14, holidays.getWeekTable().getDay(4).getLessons().size()); - } - - // Lesson - - @Test - public void getLessonNumberTest() throws Exception { - Assert.assertEquals(2, std.getWeekTable().getDay(0).getLesson(1).getNumber()); - Assert.assertEquals(5, std.getWeekTable().getDay(2).getLesson(4).getNumber()); - Assert.assertEquals(0, full.getWeekTable().getDay(0).getLesson(0).getNumber()); - Assert.assertEquals(13, full.getWeekTable().getDay(4).getLesson(13).getNumber()); - Assert.assertEquals(3, holidays.getWeekTable().getDay(3).getLesson(3).getNumber()); - } - - @Test - public void getLessonDayTest() throws Exception { - Assert.assertEquals("2017-06-19", std.getWeekTable().getDay(0).getLesson(1).getDate()); - Assert.assertEquals("2017-06-23", std.getWeekTable().getDay(4).getLesson(4).getDate()); - Assert.assertEquals("2017-06-20", full.getWeekTable().getDay(1).getLesson(6).getDate()); - Assert.assertEquals("2017-06-22", full.getWeekTable().getDay(3).getLesson(3).getDate()); - Assert.assertEquals("2017-08-02", holidays.getWeekTable().getDay(2).getLesson(8).getDate()); - } - - @Test - public void getLessonSubjectTest() throws Exception { - Assert.assertEquals("Historia", std.getWeekTable().getDay(0).getLesson(1).getSubject()); - Assert.assertEquals("Zajęcia techniczne", std.getWeekTable().getDay(2).getLesson(4).getSubject()); - Assert.assertEquals("Wychowanie fizyczne", std.getWeekTable().getDay(1).getLesson(1).getSubject()); - Assert.assertEquals("Język angielski", full.getWeekTable().getDay(0).getLesson(1).getSubject()); - Assert.assertEquals("Wychowanie fizyczne", full.getWeekTable().getDay(0).getLesson(9).getSubject()); - Assert.assertEquals("Wychowanie do życia w rodzinie", full.getWeekTable().getDay(2).getLesson(0).getSubject()); - Assert.assertEquals("Wychowanie fizyczne", full.getWeekTable().getDay(3).getLesson(1).getSubject()); - Assert.assertEquals("Uroczyste zakończenie roku szkolnego", full.getWeekTable().getDay(4).getLesson(0).getSubject()); - Assert.assertEquals("Fizyka", full.getWeekTable().getDay(0).getLesson(0).getSubject()); - Assert.assertEquals("Metodologia programowania", full.getWeekTable().getDay(1).getLesson(0).getSubject()); - Assert.assertEquals("Język niemiecki", full.getWeekTable().getDay(4).getLesson(2).getSubject()); - Assert.assertEquals("", holidays.getWeekTable().getDay(3).getLesson(3).getSubject()); - } - - @Test - public void getLessonTeacherTest() throws Exception { - Assert.assertEquals("Bogatka Katarzyna", std.getWeekTable().getDay(0).getLesson(1).getTeacher()); - Assert.assertEquals("Chlebowski Stanisław", std.getWeekTable().getDay(2).getLesson(4).getTeacher()); - Assert.assertEquals("Kobczyk Iwona", full.getWeekTable().getDay(0).getLesson(1).getTeacher()); - Assert.assertEquals("Bączek Grzegorz", full.getWeekTable().getDay(0).getLesson(7).getTeacher()); - Assert.assertEquals("Nowak Jadwiga", full.getWeekTable().getDay(2).getLesson(0).getTeacher()); - Assert.assertEquals("Nowicka Irena", full.getWeekTable().getDay(3).getLesson(1).getTeacher()); - Assert.assertEquals("Baran Małgorzata", full.getWeekTable().getDay(4).getLesson(0).getTeacher()); - Assert.assertEquals("", full.getWeekTable().getDay(4).getLesson(1).getTeacher()); - Assert.assertEquals("", holidays.getWeekTable().getDay(3).getLesson(3).getTeacher()); - } - - @Test - public void getLessonRoomTest() throws Exception { - Assert.assertEquals("", std.getWeekTable().getDay(3).getLesson(3).getRoom()); - Assert.assertEquals("33", full.getWeekTable().getDay(0).getLesson(7).getRoom()); - Assert.assertEquals("19", full.getWeekTable().getDay(0).getLesson(0).getRoom()); - Assert.assertEquals("32", full.getWeekTable().getDay(1).getLesson(0).getRoom()); - Assert.assertEquals("32", full.getWeekTable().getDay(1).getLesson(8).getRoom()); - Assert.assertEquals("32", full.getWeekTable().getDay(2).getLesson(8).getRoom()); - Assert.assertEquals("G4", full.getWeekTable().getDay(3).getLesson(1).getRoom()); - Assert.assertEquals("37", full.getWeekTable().getDay(4).getLesson(0).getRoom()); - Assert.assertEquals("", holidays.getWeekTable().getDay(3).getLesson(3).getRoom()); - } - - @Test - public void getLessonDescriptionTest() throws Exception { - Assert.assertEquals("", std.getWeekTable().getDay(3).getLesson(3).getDescription()); - Assert.assertEquals("przeniesiona z lekcji 7, 01.12.2017", full.getWeekTable().getDay(1).getLesson(1).getDescription()); - Assert.assertEquals("okienko dla uczniów", full.getWeekTable().getDay(0).getLesson(7).getDescription()); - Assert.assertEquals("przeniesiona z lekcji 7, 20.06.2017", full.getWeekTable().getDay(1).getLesson(2).getDescription()); - Assert.assertEquals("przeniesiona z lekcji 4, 20.06.2017", full.getWeekTable().getDay(1).getLesson(3).getDescription()); - Assert.assertEquals("zastępstwo (poprzednio: Religia)", full.getWeekTable().getDay(2).getLesson(0).getDescription()); - Assert.assertEquals("zastępstwo (poprzednio: Wychowanie fizyczne)", full.getWeekTable().getDay(3).getLesson(1).getDescription()); - Assert.assertEquals("", full.getWeekTable().getDay(4).getLesson(0).getDescription()); - Assert.assertEquals("", full.getWeekTable().getDay(4).getLesson(1).getDescription()); - Assert.assertEquals("bez nawiasów (poprzednio: Religia)", full.getWeekTable().getDay(4).getLesson(3).getDescription()); - Assert.assertEquals("poprzednio: Wychowanie fizyczne", full.getWeekTable().getDay(4).getLesson(2).getDescription()); - Assert.assertEquals("egzamin", full.getWeekTable().getDay(3).getLesson(0).getDescription()); - Assert.assertEquals("", full.getWeekTable().getDay(4).getLesson(1).getDescription()); - Assert.assertEquals("poprzednio: Zajęcia z wychowawcą", full.getWeekTable().getDay(4).getLesson(5).getDescription()); - Assert.assertEquals("opis w uwadze bez klasy w spanie", full.getWeekTable().getDay(4).getLesson(4).getDescription()); - Assert.assertEquals("", holidays.getWeekTable().getDay(3).getLesson(3).getDescription()); - } - - @Test - public void getLessonGroupNameTest() throws Exception { - Assert.assertEquals("CH", std.getWeekTable().getDay(0).getLesson(2).getGroupName()); - Assert.assertEquals("JNPW", std.getWeekTable().getDay(4).getLesson(0).getGroupName()); - Assert.assertEquals("", full.getWeekTable().getDay(0).getLesson(7).getGroupName()); - Assert.assertEquals("zaw2", full.getWeekTable().getDay(1).getLesson(0).getGroupName()); - Assert.assertEquals("wf2", full.getWeekTable().getDay(1).getLesson(3).getGroupName()); - Assert.assertEquals("zaw1", full.getWeekTable().getDay(3).getLesson(1).getGroupName()); - Assert.assertEquals("", holidays.getWeekTable().getDay(3).getLesson(3).getGroupName()); - } - - @Test - public void getLessonStartTimeTest() throws Exception { - Assert.assertEquals("08:00", std.getWeekTable().getDay(0).getLesson(0).getStartTime()); - Assert.assertEquals("14:10", std.getWeekTable().getDay(3).getLesson(7).getStartTime()); - Assert.assertEquals("07:10", full.getWeekTable().getDay(0).getLesson(0).getStartTime()); - Assert.assertEquals("12:20", full.getWeekTable().getDay(2).getLesson(6).getStartTime()); - Assert.assertEquals("12:20", holidays.getWeekTable().getDay(2).getLesson(6).getStartTime()); - } - - @Test - public void getLessonEndTimeTest() throws Exception { - Assert.assertEquals("08:45", std.getWeekTable().getDay(1).getLesson(0).getEndTime()); - Assert.assertEquals("12:15", std.getWeekTable().getDay(2).getLesson(4).getEndTime()); - Assert.assertEquals("07:55", full.getWeekTable().getDay(1).getLesson(0).getEndTime()); - Assert.assertEquals("19:00", full.getWeekTable().getDay(3).getLesson(13).getEndTime()); - Assert.assertEquals("19:00", holidays.getWeekTable().getDay(3).getLesson(13).getEndTime()); - } - - @Test - public void getLessonIsEmptyTest() throws Exception { - Assert.assertFalse(std.getWeekTable().getDay(1).getLesson(4).isEmpty()); - Assert.assertTrue(std.getWeekTable().getDay(3).getLesson(7).isEmpty()); - Assert.assertFalse(full.getWeekTable().getDay(1).getLesson(1).isEmpty()); - Assert.assertFalse(full.getWeekTable().getDay(1).getLesson(2).isEmpty()); - Assert.assertFalse(full.getWeekTable().getDay(0).getLesson(7).isEmpty()); - Assert.assertTrue(full.getWeekTable().getDay(2).getLesson(9).isEmpty()); - Assert.assertTrue(holidays.getWeekTable().getDay(0).getLesson(5).isEmpty()); - Assert.assertTrue(holidays.getWeekTable().getDay(4).getLesson(13).isEmpty()); - } - - @Test - public void getLessonIsDivisionIntoGroupsTest() throws Exception { - Assert.assertTrue(std.getWeekTable().getDay(0).getLesson(2).isDivisionIntoGroups()); - Assert.assertTrue(std.getWeekTable().getDay(4).getLesson(0).isDivisionIntoGroups()); - Assert.assertFalse(full.getWeekTable().getDay(0).getLesson(7).isDivisionIntoGroups()); - Assert.assertTrue(full.getWeekTable().getDay(1).getLesson(3).isDivisionIntoGroups()); - Assert.assertTrue(full.getWeekTable().getDay(3).getLesson(1).isDivisionIntoGroups()); - Assert.assertFalse(holidays.getWeekTable().getDay(3).getLesson(3).isDivisionIntoGroups()); - } - - @Test - public void getLessonIsPlanningTest() throws Exception { - Assert.assertFalse(std.getWeekTable().getDay(4).getLesson(4).isPlanning()); - Assert.assertFalse(full.getWeekTable().getDay(0).getLesson(1).isPlanning()); - Assert.assertTrue(full.getWeekTable().getDay(1).getLesson(3).isPlanning()); - Assert.assertTrue(full.getWeekTable().getDay(4).getLesson(0).isPlanning()); - Assert.assertFalse(holidays.getWeekTable().getDay(3).getLesson(3).isPlanning()); - } - - @Test - public void getLessonIsRealizedTest() throws Exception { - Assert.assertTrue(std.getWeekTable().getDay(3).getLesson(3).isRealized()); - Assert.assertTrue(full.getWeekTable().getDay(0).getLesson(1).isRealized()); - Assert.assertTrue(full.getWeekTable().getDay(1).getLesson(3).isRealized()); - Assert.assertFalse(full.getWeekTable().getDay(4).getLesson(0).isRealized()); - Assert.assertFalse(holidays.getWeekTable().getDay(3).getLesson(3).isRealized()); - } - - @Test - public void getLessonIsMovedOrCanceledTest() throws Exception { - Assert.assertFalse(std.getWeekTable().getDay(3).getLesson(3).isMovedOrCanceled()); - Assert.assertTrue(full.getWeekTable().getDay(0).getLesson(7).isMovedOrCanceled()); - Assert.assertFalse(full.getWeekTable().getDay(1).getLesson(3).isMovedOrCanceled()); - Assert.assertFalse(full.getWeekTable().getDay(4).getLesson(0).isMovedOrCanceled()); - Assert.assertFalse(holidays.getWeekTable().getDay(3).getLesson(3).isMovedOrCanceled()); - } - - @Test - public void getLessonIsNewMovedInOrChangedTest() throws Exception { - Assert.assertFalse(std.getWeekTable().getDay(3).getLesson(3).isNewMovedInOrChanged()); - Assert.assertFalse(full.getWeekTable().getDay(0).getLesson(1).isNewMovedInOrChanged()); - Assert.assertTrue(full.getWeekTable().getDay(1).getLesson(2).isNewMovedInOrChanged()); - Assert.assertTrue(full.getWeekTable().getDay(1).getLesson(3).isNewMovedInOrChanged()); - Assert.assertTrue(full.getWeekTable().getDay(3).getLesson(1).isNewMovedInOrChanged()); - Assert.assertFalse(full.getWeekTable().getDay(4).getLesson(1).isNewMovedInOrChanged()); - Assert.assertTrue(full.getWeekTable().getDay(4).getLesson(2).isNewMovedInOrChanged()); - Assert.assertFalse(holidays.getWeekTable().getDay(3).getLesson(3).isNewMovedInOrChanged()); - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/user/BasicInformationTest.java b/api/src/test/java/io/github/wulkanowy/api/user/BasicInformationTest.java deleted file mode 100644 index 6b729c95..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/user/BasicInformationTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package io.github.wulkanowy.api.user; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import io.github.wulkanowy.api.StudentAndParentTestCase; - -public class BasicInformationTest extends StudentAndParentTestCase { - - private BasicInformation basicInformation; - - @Before - public void setUp() throws Exception { - basicInformation = new BasicInformation(getSnp("UczenDanePodstawowe.html")); - } - - @Test - public void getPersonalFirstNameTest() throws Exception { - Assert.assertEquals("Maria", basicInformation.getPersonalData().getFirstName()); - } - - @Test - public void getPersonalSurnameTest() throws Exception { - Assert.assertEquals("Kamińska", basicInformation.getPersonalData().getSurname()); - } - - @Test - public void getPersonalFirstAndLastNameTest() throws Exception { - Assert.assertEquals("Maria Kamińska", - basicInformation.getPersonalData().getFirstAndLastName()); - } - - @Test - public void getPersonalNameTest() throws Exception { - Assert.assertEquals("Maria Aneta Kamińska", basicInformation.getPersonalData().getName()); - } - - @Test - public void getPersonalDateAndBirthPlaceTest() throws Exception { - Assert.assertEquals("01.01.1900, Warszawa", - basicInformation.getPersonalData().getDateAndBirthPlace()); - } - - @Test - public void getPersonalPeselTest() throws Exception { - Assert.assertEquals("12345678900", basicInformation.getPersonalData().getPesel()); - } - - @Test - public void getPersonalGenderTest() throws Exception { - Assert.assertEquals("Kobieta", basicInformation.getPersonalData().getGender()); - } - - @Test - public void isPersonalPolishCitizenshipTest() throws Exception { - Assert.assertTrue(basicInformation.getPersonalData().isPolishCitizenship()); - } - - @Test - public void getPersonalFamilyNameTest() throws Exception { - Assert.assertEquals("Nowak", basicInformation.getPersonalData().getFamilyName()); - } - - @Test - public void getPersonalParentsNames() throws Exception { - Assert.assertEquals("Gabriela, Kamil", - basicInformation.getPersonalData().getParentsNames()); - } - - @Test - public void getBasicAddressTest() throws Exception { - Assert.assertEquals("ul. Sportowa 16, 00-123 Warszawa", - basicInformation.getAddressData().getAddress()); - } - - @Test - public void getBasicRegisteredAddressTest() throws Exception { - Assert.assertEquals("ul. Sportowa 17, 00-123 Warszawa", - basicInformation.getAddressData().getRegisteredAddress()); - } - - @Test - public void getBasicCorrespondenceAddressTest() throws Exception { - Assert.assertEquals("ul. Sportowa 18, 00-123 Warszawa", - basicInformation.getAddressData().getCorrespondenceAddress()); - } - - @Test - public void getContactPhoneNumberTest() throws Exception { - Assert.assertEquals("005554433", - basicInformation.getContactDetails().getPhoneNumber()); - } - - @Test - public void getContactCellPhoneNumberTest() throws Exception { - Assert.assertEquals("555444333", - basicInformation.getContactDetails().getCellPhoneNumber()); - } - - @Test - public void getContactEmailTest() throws Exception { - Assert.assertEquals("wulkanowy@example.null", - basicInformation.getContactDetails().getEmail()); - } -} diff --git a/api/src/test/java/io/github/wulkanowy/api/user/FamilyInformationTest.java b/api/src/test/java/io/github/wulkanowy/api/user/FamilyInformationTest.java deleted file mode 100644 index b4f858ec..00000000 --- a/api/src/test/java/io/github/wulkanowy/api/user/FamilyInformationTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.github.wulkanowy.api.user; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.List; - -import io.github.wulkanowy.api.StudentAndParentTestCase; - -public class FamilyInformationTest extends StudentAndParentTestCase { - - private FamilyInformation familyInformation; - - @Before - public void setUp() throws Exception { - familyInformation = new FamilyInformation(getSnp("UczenDanePodstawowe.html")); - } - - @Test - public void getFamilyMembers() throws Exception { - Assert.assertEquals(2, familyInformation.getFamilyMembers().size()); - } - - @Test - public void getNameTest() throws Exception { - List list = familyInformation.getFamilyMembers(); - Assert.assertEquals("Marianna Pająk", list.get(0).getName()); - Assert.assertEquals("Dawid Świątek", list.get(1).getName()); - } - - @Test - public void getKinshipTest() throws Exception { - List list = familyInformation.getFamilyMembers(); - Assert.assertEquals("matka", list.get(0).getKinship()); - Assert.assertEquals("ojciec", list.get(1).getKinship()); - } - - @Test - public void getAddressTest() throws Exception { - List list = familyInformation.getFamilyMembers(); - Assert.assertEquals("ul. Sportowa 16, 00-123 Warszawa", list.get(0).getAddress()); - Assert.assertEquals("ul. Sportowa 18, 00-123 Warszawa", list.get(1).getAddress()); - } - - @Test - public void getTelephonesTest() throws Exception { - List list = familyInformation.getFamilyMembers(); - Assert.assertEquals("555111222", list.get(0).getTelephones()); - Assert.assertEquals("555222111", list.get(1).getTelephones()); - } - - @Test - public void getEmailTest() throws Exception { - List list = familyInformation.getFamilyMembers(); - Assert.assertEquals("wulkanowy@example.null", list.get(0).getEmail()); - Assert.assertEquals("wulkanowy@example.null", list.get(1).getEmail()); - } -} diff --git a/api/src/test/resources/io/github/wulkanowy/api/OcenyWszystkie-semester.html b/api/src/test/resources/io/github/wulkanowy/api/OcenyWszystkie-semester.html deleted file mode 100644 index dc7c6c3b..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/OcenyWszystkie-semester.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - Witryna ucznia i rodzica – Oceny - - -
-

Oceny

-
-
- - -
-
-
-
wersja: 17.05.0000.24042
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/Start-multi.html b/api/src/test/resources/io/github/wulkanowy/api/Start-multi.html deleted file mode 100644 index 98d385ee..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/Start-multi.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - Uonet+ - - -
-
-
- -
-
-
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/Start-std.html b/api/src/test/resources/io/github/wulkanowy/api/Start-std.html deleted file mode 100644 index 574bd9b9..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/Start-std.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - Uonet+ - - -
- -
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/WitrynaUczniaIRodzica.html b/api/src/test/resources/io/github/wulkanowy/api/WitrynaUczniaIRodzica.html deleted file mode 100644 index 66e2942f..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/WitrynaUczniaIRodzica.html +++ /dev/null @@ -1,37 +0,0 @@ - - - - - Witryna ucznia i rodzica – Strona główna - - -
    -
  • - - -
  • -
  • - - -
  • -
- -
wersja: 17.09.0008.26553
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/attendance/Frekwencja-excellent.html b/api/src/test/resources/io/github/wulkanowy/api/attendance/Frekwencja-excellent.html deleted file mode 100644 index 5eaf50df..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/attendance/Frekwencja-excellent.html +++ /dev/null @@ -1,408 +0,0 @@ - - - - - Witryna ucznia i rodzica – Frekwencja - - - -
-

Frekwencja

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Lekcjaponiedziałek
31.08.2015
wtorek
01.09.2015
środa
02.09.2015
czwartek
03.09.2015
piątek
04.09.2015
0
1 -
- Uroczyste rozpoczęcie roku szkolnego 2015/2016 -
-
-
- Wychowanie do życia w rodzinie -
-
-
- Urządzenia techniki komputerowej -
-
2 -
- Język angielski -
-
-
- Język niemiecki -
-
-
- Urządzenia techniki komputerowej -
-
3 -
- Systemy operacyjne -
-
-
- Chemia -
-
-
- Urządzenia techniki komputerowej -
-
4 -
- Systemy operacyjne -
-
-
- Geografia -
-
-
- Urządzenia techniki komputerowej -
-
5 -
- Tworzenie stron internetowych -
-
-
- Matematyka -
-
-
- Język polski -
-
6 -
- Tworzenie stron internetowych -
-
-
- Fizyka -
-
-
- Matematyka -
-
7 -
- Wychowanie fizyczne -
-
-
- Język polski -
-
-
- Historia -
-
8 -
- Wychowanie fizyczne -
-
9
10
11
12
13
-

Statystyki

-
- - -
-

Frekwencja od początku roku szkolnego: 100,00%

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IXXXIXIIIIIIIIIVVVIVIIVIIIRazem
Obecność14214313911013175126139921141211
Nieobecność nieusprawiedliwiona
Nieobecność usprawiedliwiona
Nieobecność z przyczyn szkolnych
Spóźnienie nieusprawiedliwione
Spóźnienie usprawiedliwione
Zwolnienie
-
-
wersja: 17.07.0002.24480
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/attendance/Frekwencja-full.html b/api/src/test/resources/io/github/wulkanowy/api/attendance/Frekwencja-full.html deleted file mode 100644 index aa995305..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/attendance/Frekwencja-full.html +++ /dev/null @@ -1,498 +0,0 @@ - - - - - Witryna ucznia i rodzica – Frekwencja - - - -
-

Frekwencja

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Lekcjaponiedziałek
05.09.2016
wtorek
06.09.2016
środa
07.09.2016
czwartek
08.09.2016
piątek
09.09.2016
0
1 -
- Urządzenia techniki komputerowej -
-
-
- Multimedia i grafika komputerowa -
-
-
- Użytkowanie urządzeń peryferyjnych komputera -
-
-
- Religia -
-
2 -
- Urządzenia techniki komputerowej -
-
-
- Język niemiecki -
-
-
- Użytkowanie urządzeń peryferyjnych komputera -
-
-
- Język niemiecki -
-
-
- Sieci komputerowe i administrowanie sieciami -
-
3 -
- Urządzenia techniki komputerowej -
-
-
- Fizyka -
-
-
- Historia -
-
-
- Wychowanie fizyczne -
-
-
- Wiedza o kulturze -
-
4 -
- Naprawa komputera -
-
-
- Wychowanie fizyczne -
-
-
- Język angielski -
-
-
- Wychowanie fizyczne -
-
-
- Język polski -
-
5 -
- Sieci komputerowe i administrowanie sieciami -
-
-
- Metodologia programowania -
-
-
- Urządzenia techniki komputerowej -
-
-
- Matematyka -
-
-
- Metodologia programowania -
-
6 -
- Język niemiecki -
-
-
- Sieci komputerowe i administrowanie sieciami -
-
-
- Język polski -
-
-
- Podstawy przedsiębiorczości -
-
-
- Matematyka -
-
7 -
- Fizyka -
-
-
- Język polski -
-
-
- Systemy operacyjne -
-
-
- Zajęcia z wychowawcą -
-
-
- Religia -
-
8 -
- Naprawa komputera -
-
-
- Systemy operacyjne -
-
-
- Urządzenia techniki komputerowej -
-
-
- Zajęcia z wychowawcą -
-
9
10
11
12
13
-

Statystyki

-
- - -
-

Frekwencja od początku roku szkolnego: 80,94%

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IXXXIXIIIIIIIIIVVVIVIIVIIIRazem
Obecność1351031085437100339010359822
Nieobecność nieusprawiedliwiona246
Nieobecność usprawiedliwiona627293044161327192
Nieobecność z przyczyn szkolnych77
Spóźnienie nieusprawiedliwione41222112
Spóźnienie usprawiedliwione11
Zwolnienie112
-
-
wersja: 17.07.0002.24480
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/exams/Sprawdziany-empty.html b/api/src/test/resources/io/github/wulkanowy/api/exams/Sprawdziany-empty.html deleted file mode 100644 index bf1032b4..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/exams/Sprawdziany-empty.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - Witryna ucznia i rodzica – Terminarz sprawdzianów - - -
-

Sprawdziany

-

Tydzień 30.04.2018 - 06.05.2018

-

Nie zaplanowano żadnych sprawdzianów na wybrany tydzień

- -
-
wersja: 17.09.0009.26859
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/exams/Sprawdziany-one-per-day.html b/api/src/test/resources/io/github/wulkanowy/api/exams/Sprawdziany-one-per-day.html deleted file mode 100644 index 81b3052b..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/exams/Sprawdziany-one-per-day.html +++ /dev/null @@ -1,143 +0,0 @@ - - - - - Witryna ucznia i rodzica – Terminarz sprawdzianów - - -
-

Sprawdziany

-

Tydzień 23.10.2017 - 29.10.2017

-
-

poniedziałek, 23.10.2017

-
-
-
Przedmiot i grupa:
-
Sieci komputerowe 3Ti|zaw2
-
-
-
Rodzaj sprawdzianu:
-
Sprawdzian
-
-
-
Opis:
-
Łącza danych
-
-
-
Nauczyciel i data wpisu:
-
Adam Wiśniewski [AW], 16.10.2017
-
-
-
-
-

wtorek, 24.10.2017

-
-
-
Przedmiot i grupa:
-
Język angielski 3Ti|J1
-
-
-
Rodzaj sprawdzianu:
-
Sprawdzian
-
-
-
Opis:
-
Czasy teraźniejsze
-
-
-
Nauczyciel i data wpisu:
-
Natalia Nowak [NN], 17.10.2017
-
-
-
-
-

środa, 25.10.2017

-
-
-
Przedmiot i grupa:
-
Język angielski 3Ti|J2
-
-
-
Rodzaj sprawdzianu:
-
Sprawdzian
-
-
-
Opis:
-
słownictwo (zdrowie)
-
-
-
Nauczyciel i data wpisu:
-
Natalia Nowak [NN], 17.10.2017
-
-
-
-
-
Przedmiot i grupa:
-
Metodologia programowania 3Ti|zaw1
-
-
-
Rodzaj sprawdzianu:
-
Kartkówka
-
-
-
Opis:
-
programowanie obiektowe
-
-
-
Nauczyciel i data wpisu:
-
Małgorzata Nowacka [MN], 16.10.2017
-
-
-
-
-

czwartek, 26.10.2017

-
-
-
Przedmiot i grupa:
-
Język polski 3Ti
-
-
-
Rodzaj sprawdzianu:
-
Sprawdzian
-
-
-
Opis:
-
Dwudziestolecie
-
-
-
Nauczyciel i data wpisu:
-
Czerwieńska Agata [CA], 16.10.2017
-
-
-
-
-

piątek, 27.10.2017

-
-
-
Przedmiot i grupa:
-
Metodologia programowania 3Ti|zaw2
-
-
-
Rodzaj sprawdzianu:
-
Sprawdzian
-
-
-
Opis:
-
-
-
-
Nauczyciel i data wpisu:
-
Małgorzata Nowacka [MN], 16.10.2017
-
-
-
-
-
- -
-
wersja: 17.08.0001.24874
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/grades/OcenyWszystkie-filled.html b/api/src/test/resources/io/github/wulkanowy/api/grades/OcenyWszystkie-filled.html deleted file mode 100644 index d0cdb664..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/grades/OcenyWszystkie-filled.html +++ /dev/null @@ -1,116 +0,0 @@ - - - - - Witryna ucznia i rodzica – Oceny - - -
-

Oceny

-
-
- - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PrzedmiotOcena cząstkowaOpisWagaDataNauczyciel
ZachowanieBrak ocen
Zajęcia z wychowawcą - 5 - A1, Dzień Kobiet w naszej klasie1,0021.03.2017Patryk Maciejewski
Edukacja dla bezpieczeństwa - 4- - S1, PIERWSZA POMOC I RESUSCYTACJA5,0031.03.2017Weronika Ratajczak
Fizyka - 2 - O, Odpowiedź3,0025.06.2017Jakub Michalak
Język angielski - 5 - BW3, Writing3,0002.06.2017Oliwia Woźniak
Wiedza o społeczeństwieBrak ocen
Wychowanie fizyczne1STR8,0002.04.2017Klaudia Dziedzic
Język polski1K, Kordian5,0006.02.2017Amelia Stępień
Język polski5+Odp, Kordian5,0011.05.2017Amelia Stępień
-
-
wersja: 17.02.0000.23328
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/grades/OcenyWszystkie-subjects-average.html b/api/src/test/resources/io/github/wulkanowy/api/grades/OcenyWszystkie-subjects-average.html deleted file mode 100644 index 023b5405..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/grades/OcenyWszystkie-subjects-average.html +++ /dev/null @@ -1,70 +0,0 @@ - - - - - Witryna ucznia i rodzica – Oceny - - -
-

Oceny

-
-
- - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PrzedmiotOceny cząstkoweŚredniaPrzewidywana ocena rocznaOcena roczna
ZachowanieBrak ocen-bardzo dobrebardzo dobre
Język polski03,53-dobry
Wychowanie fizyczne05,05bardzo dobrycelujący
Język angielski04,44/5bardzo dobry
Wiedza o społeczeństwieBrak ocen---
-
-
wersja: 17.02.0000.23328
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/grades/OcenyWszystkie-subjects.html b/api/src/test/resources/io/github/wulkanowy/api/grades/OcenyWszystkie-subjects.html deleted file mode 100644 index 0f6da414..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/grades/OcenyWszystkie-subjects.html +++ /dev/null @@ -1,64 +0,0 @@ - - - - - Witryna ucznia i rodzica – Oceny - - -
-

Oceny

-
-
- - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PrzedmiotOceny cząstkowePrzewidywana ocena rocznaOcena roczna
Zachowanie-bardzo dobrebardzo dobre
Praktyka zawodowa--celujący
Metodologia programowania-bardzo dobrycelujący
Podstawy przedsiębiorczości-3/4dostateczny
Wychowanie do życia w rodzinie---
-
-
wersja: 17.05.0000.24042
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/homework/ZadaniaDomowe.html b/api/src/test/resources/io/github/wulkanowy/api/homework/ZadaniaDomowe.html deleted file mode 100644 index ec68d2ab..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/homework/ZadaniaDomowe.html +++ /dev/null @@ -1,46 +0,0 @@ - - - - - Witryna ucznia i rodzica – Zadania domowe - - -
-

Zadania domowe

- -

poniedziałek, 23.10.2017

- -
-
-
Przedmiot:
-
Sieci komputerowe i administrowanie sieciami
-
-
-
Opis:
-
Zadania egzaminacyjne -
-
-
-
Nauczyciel i data wpisu:
-
Słowacki Juliusz [SJ], 16.10.2017
-
-
-
-
-
Przedmiot:
-
Naprawa komputera
-
-
-
Opis:
-
Test diagnozujący
-
-
-
Nauczyciel i data wpisu:
-
Mickiewicz Adam [MA], 25.10.2017
-
-
- -
-
wersja: 18.02.0007.28151
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/login/Logowanie-brak-dostepu.html b/api/src/test/resources/io/github/wulkanowy/api/login/Logowanie-brak-dostepu.html deleted file mode 100644 index 2911f1d2..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/login/Logowanie-brak-dostepu.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - Logowanie - - -
-
- Adres example@wulkanowy.io nie został zarejestrowany w dzienniku uczniowskim jako adres rodzica, bądź ucznia. - Jeśli jesteś rodzicem (prawnym opiekunem) ucznia (lub uczniem) szkoły korzystającej z dziennika „UONET +” udaj się do - wychowawcy i poproś o wprowadzenie Twojego adresu e-mail do Twoich danych. -
-
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/login/Logowanie-certyfikat.html b/api/src/test/resources/io/github/wulkanowy/api/login/Logowanie-certyfikat.html deleted file mode 100644 index f53a3485..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/login/Logowanie-certyfikat.html +++ /dev/null @@ -1,17 +0,0 @@ - - - Working... - - -
- - - - -
- - - diff --git a/api/src/test/resources/io/github/wulkanowy/api/login/Logowanie-error.html b/api/src/test/resources/io/github/wulkanowy/api/login/Logowanie-error.html deleted file mode 100644 index afb044d7..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/login/Logowanie-error.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - Logowanie (demo123) - - -
-
-
-

Logowanie

-
-
- Zła nazwa użytkownika lub hasło -
-
-
- - - diff --git a/api/src/test/resources/io/github/wulkanowy/api/login/Logowanie-notLoggedIn.html b/api/src/test/resources/io/github/wulkanowy/api/login/Logowanie-notLoggedIn.html deleted file mode 100644 index f961bf82..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/login/Logowanie-notLoggedIn.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - Dziennik UONET+ - - -
-
-
-
-
- - Zaloguj się -
-
-
-
Uonet+ wersja 17.09.0007.26300
-
-
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/login/Logowanie-success.html b/api/src/test/resources/io/github/wulkanowy/api/login/Logowanie-success.html deleted file mode 100644 index f35e6866..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/login/Logowanie-success.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - - Uonet+ - - -
-
-
- example@wulkanowy.io (wyloguj) -
-
- -
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/login/PrzerwaTechniczna.html b/api/src/test/resources/io/github/wulkanowy/api/login/PrzerwaTechniczna.html deleted file mode 100644 index 062f9b60..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/login/PrzerwaTechniczna.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - Przerwa techniczna - - -
-
-
-

Przerwa techniczna

-

Aktualnie trwają prace konserwacyjne. Witryna będzie dostępna za kilka minut.

> -
- -
-
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/login/cert-no-symbols.xml b/api/src/test/resources/io/github/wulkanowy/api/login/cert-no-symbols.xml deleted file mode 100644 index ca14bdf5..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/login/cert-no-symbols.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - Default - - - - - - diff --git a/api/src/test/resources/io/github/wulkanowy/api/login/cert-stock.xml b/api/src/test/resources/io/github/wulkanowy/api/login/cert-stock.xml deleted file mode 100644 index 31aa19b2..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/login/cert-stock.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - Default - demo12345 - incorrect value - warszawa - asdf - asdfsdf - - - - - - diff --git a/api/src/test/resources/io/github/wulkanowy/api/messages/GetTrescWiadomosci.json b/api/src/test/resources/io/github/wulkanowy/api/messages/GetTrescWiadomosci.json deleted file mode 100644 index 1ba54a32..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/messages/GetTrescWiadomosci.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "success": true, - "data": { - "Id": 12345, - "Tresc": "Witam, …. \nPozdrawiam Krzysztof Czerkas" - } -} diff --git a/api/src/test/resources/io/github/wulkanowy/api/messages/GetWiadomosciOdebrane.json b/api/src/test/resources/io/github/wulkanowy/api/messages/GetWiadomosciOdebrane.json deleted file mode 100644 index 326390ed..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/messages/GetWiadomosciOdebrane.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "success": true, - "data": [ - { - "Nieprzeczytana": false, - "Data": "2016-03-15 09:00:00", - "Tresc": null, - "Temat": "Wycieczka", - "NadawcaNazwa": "Kowalski Jan", - "IdWiadomosci": 1234, - "IdNadawca": 4321, - "Id": 12345 - }, - { - "Nieprzeczytana": true, - "Data": "2016-04-20 22:00:00", - "Tresc": null, - "Temat": "\"Dzień dobrego słowa\"", - "NadawcaNazwa": "Pazura Agnieszka", - "IdWiadomosci": 1235, - "IdNadawca": 12, - "Id": 12346 - }, - { - "Nieprzeczytana": false, - "Data": "2016-04-29 10:00:00", - "Tresc": null, - "Temat": "Rozdajemy oceny celujące", - "NadawcaNazwa": "Kowalski Jan", - "IdWiadomosci": 1236, - "IdNadawca": 4321, - "Id": 12347 - } - ] -} diff --git a/api/src/test/resources/io/github/wulkanowy/api/messages/GetWiadomosciUsuniete-empty.json b/api/src/test/resources/io/github/wulkanowy/api/messages/GetWiadomosciUsuniete-empty.json deleted file mode 100644 index 36f89aa1..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/messages/GetWiadomosciUsuniete-empty.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "success": true, - "data": [] -} diff --git a/api/src/test/resources/io/github/wulkanowy/api/messages/PageError.html b/api/src/test/resources/io/github/wulkanowy/api/messages/PageError.html deleted file mode 100644 index ae976af1..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/messages/PageError.html +++ /dev/null @@ -1,88 +0,0 @@ - - - - - - - - - - Błąd strony - - - -
- -
-
- Wystąpił nieoczekiwany błąd -
-
Wystąpił błąd aplikacji. Prosimy zalogować się ponownie. Jeśli problem będzie się powtarzał, prosimy o kontakt z serwisem.
-
-
-
- -
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/messages/UndefinedError.txt b/api/src/test/resources/io/github/wulkanowy/api/messages/UndefinedError.txt deleted file mode 100644 index c8d55a96..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/messages/UndefinedError.txt +++ /dev/null @@ -1 +0,0 @@ -The custom error module does not recognize this error. \ No newline at end of file diff --git a/api/src/test/resources/io/github/wulkanowy/api/mobile/DostepMobilny-filled.html b/api/src/test/resources/io/github/wulkanowy/api/mobile/DostepMobilny-filled.html deleted file mode 100644 index 9fbfd403..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/mobile/DostepMobilny-filled.html +++ /dev/null @@ -1,44 +0,0 @@ - - - - - Witryna ucznia i rodzica – dostęp mobilny - - - -
-

Dostęp mobilny

- -
-

Zarejestrowane urządzenia

-
- - - - - - - - - - - - - - - - - - - - -
UrządzenieData rejestracji
google Android SDK built for x86 (Android 8.1.0)20.01.2018 godz: 22:35:30 - Wyrejestruj -
google (Android SDK) built for x86 (Android 8.1.0)20.01.2018 godz: 22:35:30 - Wyrejestruj -
-
- -
wersja: 18.01.0001.27311
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/mobile/Rejestruj.html b/api/src/test/resources/io/github/wulkanowy/api/mobile/Rejestruj.html deleted file mode 100644 index 15d08d07..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/mobile/Rejestruj.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - Witryna ucznia i rodzica – Rejestracja urządzenia mobilnego - - - -
-

Rejestracja urządzenia mobilnego

-
- Za pomocą aplikacji "Dzienniczek+" zeskanuj kod QR. - Kod QR - Token: 3S1A1B2C - Symbol: Default - PIN: 1234567 -
-
-
wersja: 18.01.0001.27311
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/notes/UwagiOsiagniecia-empty.html b/api/src/test/resources/io/github/wulkanowy/api/notes/UwagiOsiagniecia-empty.html deleted file mode 100644 index b15bb6e7..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/notes/UwagiOsiagniecia-empty.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - Witryna ucznia i rodzica – Uwagi i osiągnięcia - - -
-
-

Uwagi

-

Brak informacji do wyświetlenia

-
-
-

Osiągnięcia

-

Brak informacji do wyświetlenia

-
-
-
wersja: 17.05.0000.24042
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/notes/UwagiOsiagniecia-filled.html b/api/src/test/resources/io/github/wulkanowy/api/notes/UwagiOsiagniecia-filled.html deleted file mode 100644 index 50e74058..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/notes/UwagiOsiagniecia-filled.html +++ /dev/null @@ -1,65 +0,0 @@ - - - - - Witryna ucznia i rodzica – Uwagi i osiągnięcia - - -
-
-

Uwagi

-

06.06.2017

-
-
-
Nauczyciel:
-
Jan Kowalski [JK]
-
-
-
Kategoria:
-
Zaangażowanie społeczne
-
-
-
Treść:
-
Pomoc przy pikniku charytatywnym
-
-
-

01.12.2016

-
-
-
Nauczyciel:
-
Ochocka Zofia [PZ]
-
-
-
Kategoria:
-
Reprezentowanie szkoły
-
-
-
Treść:
-
Udział w przygotowaniu spektaklu
-
-
-

01.10.2016

-
-
-
Nauczyciel:
-
Kochański Leszek [KL]
-
-
-
Kategoria:
-
Zachowanie na lekcji
-
-
-
Treść:
-
Przeszkadzanie w prowadzeniu lekcji
-
-
-
-
-

Osiągnięcia

-
I miejsce w ogólnopolskim konkursie ortograficznym
-
III miejsce w ogólnopolskim konkursie plastycznym
-
-
-
wersja: 17.05.0000.24042
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/school/Szkola.html b/api/src/test/resources/io/github/wulkanowy/api/school/Szkola.html deleted file mode 100644 index 05a698a0..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/school/Szkola.html +++ /dev/null @@ -1,136 +0,0 @@ - - - - - Witryna ucznia i rodzica – Szkoła i nauczyciele - - -
-

Szkoła

-
-
- Nazwa szkoły: - Zespół Szkół nr 64 -
-
- Adres szkoły: - ul. Wiśniowa 128, 01-234 Rogalowo, Nibylandia -
-
- Telefon: - 55 5555555 -
-
- Imię i nazwisko dyrektora: - Antoni Sobczyk -
-
- Imię i nazwisko pedagoga: - Zofia Czerwińska [ZC], Aleksander Krzemiński [AK], Karolina Kowalska [KK], Bartek Dąbrowski [BD] -
-
-

Nauczyciele

-

- Klasa: 1a, Wychowawcy: - Karolina Kowalska [AN], Antoni Sobczyk [AS]

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Lp.PrzedmiotNauczyciel
1BiologiaKarolina Kowalska [AN]
2ChemiaZofia Czerwińska [NA]
3Edukacja dla bezpieczeństwaAleksandra Krajewska [AK]
4FizykaStanisław Krupa [BS]
5GeografiaAleksandra Wójtowicz [AW]
6HistoriaSara Wierzbicka [KB]
7Język angielskiKarolina Kowalska [AN], Mateusz Kowal [MK], Amelia Mazur [AM]
8Język niemieckiMateusz Kowal [MK], Barbara Markowska [BM]
9Język polskiMichał Mazur [MM]
10MatematykaSzymon Wojciechowski [SW]
11PlastykaMichał Mazur [MM]
12ReligiaMaja Wiśniewska [M]
13Wiedza o społeczeństwieKarolina Kowalska [AN]
14Wychowanie do życia w rodzinieZofia Czerwińska [NA]
15Wychowanie fizyczneKarolina Kowalska [AN], Liliana Kowal [LK]
16Zajęcia techniczneBartek Dąbrowski [BD]
17Zajęcia z wychowawcąKarolina Kowalska [AN]
-
-
wersja: 17.02.0000.23328
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/timetable/PlanLekcji-full.html b/api/src/test/resources/io/github/wulkanowy/api/timetable/PlanLekcji-full.html deleted file mode 100644 index c3dbfebe..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/timetable/PlanLekcji-full.html +++ /dev/null @@ -1,567 +0,0 @@ - - - - - Witryna ucznia i rodzica – Plan lekcji - - - -
-

Plan lekcji

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
LekcjaPora lekcjiponiedziałek
19.06.2017
wtorek
20.06.2017
środa
21.06.2017
czwartek
22.06.2017
piątek
23.06.2017
007:10 07:55 -
- Fizyka [zaw2] - - Bączek Grzegorz - 19 - (uczniowie zwolnieni do domu) -
-
-
- Metodologia programowania [zaw2] - - - 32 -
-
-
- Religia - Cyranka Krystian - 3 - Wychowanie do życia w rodzinie - Nowak Jadwiga - 3 - (zastępstwo) -
-
-
- Język polski - - 16 - (oddział nieobecny) -
- -
egzamin
-
-
- Uroczyste zakończenie roku szkolnego - Baran Małgorzata - 37 -
-
108:00 08:45 -
- Język angielski [J1] - - Kobczyk Iwona - -
-
-
- Wychowanie fizyczne [zaw2] - - - G3 - (przeniesiona z lekcji 7, 01.12.2017) -
-
- Metodologia programowania [zaw2] - - Baran Małgorzata - 36 - (zmiana organizacji zajęć) -
-
-
- Użytkowanie urządzeń peryferyjnych komputera [zaw2] - - Bączek Robert - -
-
-
- Wychowanie fizyczne [zaw1] - - Jarocki Krzysztof - G4 - Wychowanie fizyczne [zaw1] - - Nowicka Irena - G4 - (zastępstwo) -
-
-
- Uroczyste rozpoczecie roku szkolnego 2017/2018 - - -
-
- Uroczyste rozpoczecie roku szkolnego 2017/2018 - - -
-
208:50 09:35 -
- Język polski - Bocian Natalia - -
-
-
- Język niemiecki [J1] - - Rożeniec Honorata - 25 - (okienko dla uczniów) -
-
- Język polski - Bocian Natalia - - (przeniesiona z lekcji 7, 20.06.2017) -
-
- Język polski - Bocian Natalia - -
-
-
- Urządzenia techniki komputerowej [zaw2] - - Bocian Grzegorz - -
-
-
- Matematyka - Baran Małgorzata - -
-
-
- Język niemiecki [wf_grupa_2] - - - -
-
- Wychowanie fizyczne [wf_grupa_2] - - Nauczycielel - 106 -
-
309:40 10:25 -
- Język polski - Bocian Natalia - -
-
-
- Fizyka - Bączek Grzegorz - 19 - (okienko dla uczniów) -
-
- Wychowanie fizyczne [wf2] - - Nowicka Irena - - (przeniesiona z lekcji 4, 20.06.2017) -
-
- Wychowanie fizyczne [wf2] - - Nowicka Irena - -
-
-
- Metodologia programowania [zaw2] - - Baran Małgorzata - -
-
-
- Wychowanie fizyczne [wf2] - - Nowicka Irena - -
-
-
- Religia - Cyranka Krystian - 3 - Wychowanie do życia w rodzinie - Nowak Jadwiga - 3 - bez nawiasów -
-
410:40 11:25 -
- Urządzenia techniki komputerowej [zaw2] - - Bocian Grzegorz - -
-
-
- Wychowanie fizyczne [wf2] - - Nowicka Irena - - (przeniesiona na lekcję 3, 20.06.2017) -
-
-
- Matematyka - Baran Małgorzata - -
-
-
- Wychowanie fizyczne [wf2] - - Nowicka Irena - -
-
-
- Język polski - - 16 - (oddział nieobecny) -
- -
opis w uwadze bez klasy w spanie
-
511:30 12:15 -
- Urządzenia techniki komputerowej [zaw2] - - Bocian Grzegorz - -
-
-
- Podstawy przedsiębiorczości - Bogatka Anna - W12 - (okienko dla uczniów) -
-
-
- Religia - Cyranka Krystian - -
-
-
- Sieci komputerowe i administrowanie sieciami [zaw2] - - Rożeniec Piotr - -
-
-
- Tworzenie i administrowanie bazami danych [zaw2] - - - -
-
- Zajęcia z wychowawcą - Małgorzata Kowal - 43 - (zmiana organizacji zajęć) -
-
612:20 13:05 -
- Matematyka - Baran Małgorzata - -
-
-
- Podstawy przedsiębiorczości - Bogatka Anna - W12 - (okienko dla uczniów) -
-
-
- Język angielski [J1] - - Brodziec Sylwia - -
-
-
- Religia - Cyranka Krystian - -
-
713:10 13:55 -
- Fizyka - Bączek Grzegorz - 33 - (okienko dla uczniów) -
-
-
- Język polski - Bocian Natalia - - (przeniesiona na lekcję 2, 20.06.2017) -
-
-
- Multimedia i grafika komputerowa [zaw2] - - Bocian Konrad - -
-
-
- Wiedza o kulturze - Bocian Natalia - -
-
814:00 14:45 -
- Zajęcia z wychowawcą - Baran Małgorzata - -
-
-
- Naprawa komputera [zaw2] - - Kraska Maciej - 32 - (okienko dla uczniów) -
-
-
- Systemy operacyjne [zaw2] - - Kraska Maciej - 32 -
-
914:50 15:35 -
- Wychowanie fizyczne [zaw2] - - - G3 - (przeniesiona z lekcji 7, 01.12.2017) -
-
- -
-
-
- Język niemiecki [J1] - - Rożeniec Honorata - 25 - (uczniowie zwolnieni do domu) -
-
1015:40 16:25
1116:35 17:20
1217:25 18:10
1318:15 19:00
-
-
-
- Kursywa- planowane -
-
- Zwykła czcionka- zrealizowane -
-
- Przekreślone- odwołane lub przeniesione -
-
- Pogrubione- nowe lekcje, przeniesione z innego terminu, zastępstwa -
-
-
-
wersja: 17.05.0000.24042
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/timetable/PlanLekcji-holidays.html b/api/src/test/resources/io/github/wulkanowy/api/timetable/PlanLekcji-holidays.html deleted file mode 100644 index 09555cf3..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/timetable/PlanLekcji-holidays.html +++ /dev/null @@ -1,156 +0,0 @@ - - - - - Witryna ucznia i rodzica – Plan lekcji - - -
-

Plan lekcji

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
LekcjaPora lekcjiponiedziałek
31.07.2017
Ferie letnie
wtorek
01.08.2017
Ferie letnie
środa
02.08.2017
Ferie letnie
czwartek
03.08.2017
Ferie letnie
piątek
04.08.2017
Ferie letnie
007:10 07:55
108:00 08:45
208:50 09:35
309:40 10:25
410:40 11:25
511:30 12:15
612:20 13:05
713:10 13:55
814:00 14:45
914:50 15:35
1015:40 16:25
1116:35 17:20
1217:25 18:10
1318:15 19:00
-
-
-
wersja: 17.05.0000.24042
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/timetable/PlanLekcji-std.html b/api/src/test/resources/io/github/wulkanowy/api/timetable/PlanLekcji-std.html deleted file mode 100644 index 8bcc9794..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/timetable/PlanLekcji-std.html +++ /dev/null @@ -1,303 +0,0 @@ - - - - - Witryna ucznia i rodzica – Plan lekcji - - -
-

Plan lekcji

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
LekcjaPora lekcjiponiedziałek
19.06.2017
wtorek
20.06.2017
środa
21.06.2017
czwartek
22.06.2017
piątek
23.06.2017
108:00 08:45 -
- Edukacja dla bezpieczeństwa - Kobczyk Iwona - -
-
-
- Język niemiecki [JNPW] - - Dzwoniec Ewa - -
-
-
- Wychowanie do życia w rodzinie - Baran Dominika - -
-
-
- Język niemiecki [JNPW] - - Dzwoniec Ewa - -
-
208:50 09:35 -
- Historia - Bogatka Katarzyna - -
-
-
- Wychowanie fizyczne [CH] - - Brodziec Dominika - -
-
-
- Fizyka - Bocian Łukasz - -
-
-
- Biologia - Kowalska Anna - -
-
-
- Religia - Kraska Maciej - -
-
309:40 10:25 -
- Wychowanie fizyczne [CH] - - Brodziec Dominika - -
-
-
- Język polski - Rożeniec Paulina - -
-
-
- Matematyka - Bączek Dominika - -
-
-
- Plastyka - Rożeniec Paulina - -
-
-
- Zajęcia z wychowawcą - Kowalska Anna - -
-
410:30 11:15 -
- Geografia - Orłowski Konrad - -
-
-
- Matematyka - Bączek Dominika - -
-
-
- Język angielski [JAPN] - - Biegus Kazimiera - -
-
-
- Matematyka - Bączek Dominika - -
-
-
- Historia - Bogatka Katarzyna - -
-
511:30 12:15 -
- Matematyka - Bączek Dominika - -
-
-
- Biologia - Kowalska Anna - -
-
-
- Zajęcia techniczne - Chlebowski Stanisław - -
-
-
- Język angielski [JAPN] - - Biegus Kazimiera - -
-
-
- Język polski - Rożeniec Paulina - -
-
612:30 13:15 -
- Matematyka - Bączek Dominika - -
-
-
- Fizyka - Bocian Łukasz - -
-
-
- Język polski - Rożeniec Paulina - -
-
-
- Wychowanie fizyczne [CH] - - Brodziec Dominika - -
-
-
- Język polski - Rożeniec Paulina - -
-
713:20 14:05 -
- Język angielski [JAPN] - - Biegus Kazimiera - -
-
-
- Religia - Kraska Maciej - -
-
-
- Wychowanie fizyczne [CH] - - Brodziec Dominika - -
-
814:10 14:55
-
-
-
wersja: 17.02.0000.23328
- - diff --git a/api/src/test/resources/io/github/wulkanowy/api/user/UczenDanePodstawowe.html b/api/src/test/resources/io/github/wulkanowy/api/user/UczenDanePodstawowe.html deleted file mode 100644 index c54dd861..00000000 --- a/api/src/test/resources/io/github/wulkanowy/api/user/UczenDanePodstawowe.html +++ /dev/null @@ -1,119 +0,0 @@ - - - - - Witryna ucznia i rodzica – Dane ucznia - - -
-

Dane podstawowe

-

Dane osobowe

-
-
- Imię (imiona) nazwisko: - Maria Aneta Kamińska -
-
- Data i miejsce urodzenia: - 01.01.1900, Warszawa -
-
- PESEL: - 12345678900 -
-
- Płeć: - Kobieta -
-
- Obywatelstwo polskie: - Tak -
-
- Nazwisko rodowe: - Nowak -
-
- Imię matki i ojca: - Gabriela, Kamil -
-
-

Dane adresowe

-
-
- Adres zamieszkania: - ul. Sportowa 16, 00-123 Warszawa -
-
- Adres zameldowania: - ul. Sportowa 17, 00-123 Warszawa -
-
- Adres korespondencji: - ul. Sportowa 18, 00-123 Warszawa -
-
-

Kontakt

-
-
- Telefon: - 005554433 -
-
- Telefon komórkowy: - 555444333 -
-
- E-mail: - wulkanowy@example.null -
-
-

Rodzina

-
-
- Nazwisko i imię: - Marianna Pająk -
-
- Stopień pokrewieństwa: - matka -
-
- Adres: - ul. Sportowa 16, 00-123 Warszawa -
-
- Telefony: - 555111222 -
-
- E-mail: - wulkanowy@example.null -
-
-
-
- Nazwisko i imię: - Dawid Świątek -
-
- Stopień pokrewieństwa: - ojciec -
-
- Adres: - ul. Sportowa 18, 00-123 Warszawa -
-
- Telefony: - 555222111 -
-
- E-mail: - wulkanowy@example.null -
-
-
-
wersja: 17.02.0000.23328
- - diff --git a/app/build.gradle b/app/build.gradle index 7d5ec8a3..59f90fdb 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,35 +1,17 @@ -apply plugin: 'org.greenrobot.greendao' apply plugin: 'com.android.application' apply plugin: 'kotlin-android' -apply plugin: 'kotlin-kapt' // sync warning probably caused by bug https://issuetracker.google.com/issues/74537216 +apply plugin: 'kotlin-kapt' +apply plugin: 'kotlin-android-extensions' apply plugin: 'io.fabric' -apply from: 'jacoco.gradle' -apply from: 'android-sonarqube.gradle' -apply plugin: 'com.google.gms.oss.licenses.plugin' apply plugin: 'com.github.triplet.play' +apply from: 'jacoco.gradle' +apply from: 'sonarqube.gradle' -buildscript { - repositories { - maven { url "https://plugins.gradle.org/m2/" } - maven { url 'https://maven.fabric.io/public' } - google() - } - - dependencies { - classpath "org.greenrobot:greendao-gradle-plugin:$greenDaoGradle" - classpath "io.fabric.tools:gradle:$fabricGradle" - classpath "com.google.gms:oss-licenses:0.9.2" - classpath "com.github.triplet.gradle:play-publisher:$playPublisher" - } -} - -repositories { - maven { url 'https://maven.fabric.io/public' } -} +def fabricApiKey = System.getenv("FABRIC_API_KEY") ?: "null" android { - compileSdkVersion 27 - buildToolsVersion '27.0.3' + compileSdkVersion 28 + buildToolsVersion '28.0.3' playAccountConfigs { defaultAccountConfig { @@ -42,15 +24,14 @@ android { applicationId "io.github.wulkanowy" testApplicationId "io.github.tests.wulkanowy" minSdkVersion 15 - targetSdkVersion 27 + targetSdkVersion 28 versionCode 16 versionName "0.5.2" - testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + multiDexEnabled true + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" vectorDrawables.useSupportLibrary = true playAccountConfig = playAccountConfigs.defaultAccountConfig - manifestPlaceholders = [ - fabricApiKey: System.getenv("FABRIC_API_KEY") ?: "null" - ] + manifestPlaceholders = [ fabricApiKey: fabricApiKey ] } signingConfigs { @@ -64,82 +45,93 @@ android { buildTypes { release { + buildConfigField "boolean", "FABRIC_ENABLED", "true" minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' signingConfig signingConfigs.release } debug { + buildConfigField "boolean", "FABRIC_ENABLED", fabricApiKey == "null" ? "false" : "true" applicationIdSuffix ".dev" versionNameSuffix "-dev" testCoverageEnabled = true - ext.enableCrashlytics = false + ext.enableCrashlytics = fabricApiKey != "null" && !project.hasProperty("disableCrashlytics") + multiDexKeepProguard file('proguard-multidex-rules.pro') } } - testOptions { - unitTests.all { - testLogging { - events "passed", "skipped", "failed", "standardOut", "standardError" - outputs.upToDateWhen { false } - showStandardStreams = true - } - } + lintOptions { + disable 'HardwareIds' } } +androidExtensions { + experimental = true +} + play { track = 'alpha' uploadImages = true } -greendao { - schemaVersion 29 - generateTests = true -} - -configurations.all { - resolutionStrategy.force "com.android.support:support-annotations:$supportVersion" -} +ext.androidx_version = "1.0.0" dependencies { - implementation project(':api') implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - implementation "com.android.support:support-v4:$supportVersion" - implementation "com.android.support:design:$supportVersion" - implementation "com.android.support:cardview-v7:$supportVersion" - implementation "com.android.support:customtabs:$supportVersion" - implementation "com.android.support:preference-v14:$supportVersion" - implementation "com.firebase:firebase-jobdispatcher:$firebaseJob" - implementation "org.apache.commons:commons-lang3:$apacheLang" - implementation "org.apache.commons:commons-collections4:$apacheCollections" - implementation "eu.davidea:flexible-adapter:$flexibleAdapter" - implementation "eu.davidea:flexible-adapter-ui:$flexibleUi" - implementation "org.greenrobot:greendao:$greenDao" - implementation "com.jakewharton:butterknife:$butterknife" - implementation "com.google.dagger:dagger-android-support:$dagger2" - implementation "com.aurelhubert:ahbottomnavigation:$ahbottom" - implementation "com.jakewharton.threetenabp:threetenabp:$threeTenABP" - implementation "com.google.android.gms:play-services-oss-licenses:$ossLicenses" - implementation "com.jakewharton.timber:timber:$timber" - implementation "at.favre.lib:slf4j-timber:$slf4jTimber" + implementation('com.github.wulkanowy:api:e829b094de') { exclude module: "threetenbp" } - implementation("com.crashlytics.sdk.android:crashlytics:$crashlyticsSdk@aar") { + implementation "androidx.legacy:legacy-support-v4:$androidx_version" + implementation "androidx.appcompat:appcompat:$androidx_version" + implementation "androidx.cardview:cardview:$androidx_version" + implementation "com.google.android.material:material:$androidx_version" + implementation 'androidx.multidex:multidex:2.0.0' + + implementation 'com.takisoft.preferencex:preferencex:1.0.0' + implementation "com.mikepenz:aboutlibraries:6.2.0" + implementation "com.firebase:firebase-jobdispatcher:0.8.5" + + //Do not update dagger https://github.com/google/dagger/issues/1245 + implementation "com.google.dagger:dagger-android-support:2.16" + kapt "com.google.dagger:dagger-compiler:2.16" + kapt "com.google.dagger:dagger-android-processor:2.16" + + implementation "androidx.room:room-runtime:2.1.0-alpha02" + implementation "androidx.room:room-rxjava2:2.1.0-alpha02" + kapt "androidx.room:room-compiler:2.1.0-alpha02" + + implementation "eu.davidea:flexible-adapter:5.1.0" + implementation "eu.davidea:flexible-adapter-ui:1.0.0" + + implementation "com.aurelhubert:ahbottomnavigation:2.2.0" + implementation 'com.ncapdevi:frag-nav:3.0.0-RC3' + + implementation 'com.github.pwittchen:reactivenetwork-rx2:3.0.0' + implementation 'io.reactivex.rxjava2:rxandroid:2.1.0' + implementation "io.reactivex.rxjava2:rxjava:2.2.2" + + implementation "com.jakewharton.threetenabp:threetenabp:1.1.0" + + implementation "com.jakewharton.timber:timber:4.7.1" + implementation "at.favre.lib:slf4j-timber:1.0.1" + implementation 'com.akaita.java:rxjava2-debug:1.3.0' + implementation("com.crashlytics.sdk.android:crashlytics:2.9.5@aar") { transitive = true } - implementation("com.crashlytics.sdk.android:answers:$crashlyticsAnswers@aar") { + implementation("com.crashlytics.sdk.android:answers:1.4.3@aar") { transitive = true } - kapt "com.google.dagger:dagger-compiler:$dagger2" - kapt "com.google.dagger:dagger-android-processor:$dagger2" - kapt "com.jakewharton:butterknife-compiler:$butterknife" + debugImplementation "com.amitshekhar.android:debug-db:1.0.4" - debugImplementation "com.amitshekhar.android:debug-db:$debugDb" + testImplementation "junit:junit:4.12" + testImplementation "io.mockk:mockk:1.8.9" + testImplementation "org.mockito:mockito-inline:2.23.0" + testImplementation 'org.threeten:threetenbp:1.3.8' - testImplementation "junit:junit:$junit" - testImplementation "org.mockito:mockito-core:$mockito" + androidTestImplementation 'androidx.test:core:1.0.0' + androidTestImplementation 'androidx.test:runner:1.1.0' + androidTestImplementation 'androidx.test.ext:junit:1.0.0' + androidTestImplementation "org.mockito:mockito-android:2.23.0" - androidTestImplementation "com.android.support.test:runner:$testRunner" - androidTestImplementation "org.mockito:mockito-android:$mockito" androidTestImplementation "org.jetbrains.kotlin:kotlin-test:$kotlin_version" } diff --git a/app/jacoco.gradle b/app/jacoco.gradle index f59b3857..4f94ef19 100644 --- a/app/jacoco.gradle +++ b/app/jacoco.gradle @@ -1,7 +1,7 @@ apply plugin: "jacoco" jacoco { - toolVersion "0.8.1" + toolVersion "0.8.2" reportsDir = file("$buildDir/reports") } @@ -9,7 +9,6 @@ tasks.withType(Test) { jacoco.includeNoLocationClasses = true } -// run ./gradlew clean createDebugCoverageReport jacocoTestReport task jacocoTestReport(type: JacocoReport) { group = "Reporting" @@ -20,37 +19,29 @@ task jacocoTestReport(type: JacocoReport) { html.enabled = true } - def excludes = [ - "**/R.class", - "**/R\$*.class", - "**/*\$ViewInjector*.*", - "**/BuildConfig.*", - "**/Manifest*.*", - "**/*Test*.*", - "android/**/*.*", - "**/*Fragment.*", - "**/*Activity.*" - ] + def excludes = ['**/R.class', + '**/R$*.class', + '**/BuildConfig.*', + '**/Manifest*.*', + '**/*Test*.*', + 'android/**/*.*', + '**/*Module.*', + '**/*Dagger*.*', + '**/*MembersInjector*.*', + '**/*_Provide*Factory*.*', + '**/*_Factory.*'] - // generated classes classDirectories = fileTree( - // Java generated classes on Android project (debug build) dir: "$buildDir/intermediates/classes/debug", excludes: excludes ) + fileTree( - // Kotlin generated classes on Android project (debug build) dir: "$buildDir/tmp/kotlin-classes/debug", excludes: excludes ) - // sources - sourceDirectories = files([ - android.sourceSets.main.java.srcDirs, - "src/main/kotlin" - ]) - + sourceDirectories = files("$project.projectDir/src/main/java") executionData = fileTree( dir: project.projectDir, - includes: ["**/*.exec" , "**/*.ec"] + includes: ["**/*.exec", "**/*.ec"] ) } diff --git a/app/proguard-multidex-rules.pro b/app/proguard-multidex-rules.pro new file mode 100644 index 00000000..7c3895b6 --- /dev/null +++ b/app/proguard-multidex-rules.pro @@ -0,0 +1,3 @@ +-keep class android.support.test.internal** { *; } +-keep class org.junit.** { *; } +-keep public class io.github.wulkanowy** { *; } \ No newline at end of file diff --git a/app/android-sonarqube.gradle b/app/sonarqube.gradle similarity index 80% rename from app/android-sonarqube.gradle rename to app/sonarqube.gradle index b9284eea..9fd890d8 100644 --- a/app/android-sonarqube.gradle +++ b/app/sonarqube.gradle @@ -4,16 +4,13 @@ sonarqube { //noinspection GroovyAssignabilityCheck properties { - def files = fileTree("${rootProject.projectDir}/api/build/libs/").filter { it.isFile() }.files.name - def libraries = project.android.sdkDirectory.getPath() + "/platforms/android-27/android.jar," + - "${project.rootDir}/api/build/libs/" + files[0] + def libraries = project.android.sdkDirectory.getPath() + "/platforms/android-27/android.jar" property "sonar.projectName", GROUP_ID + ":app" property "sonar.projectKey", GROUP_ID + ":app" property "sonar.sources", "src/main/java" - property "sonar.exclusions", "build/**,**/*.png,*.iml, **/*generated*," + - "src/**/entities/*.java, src/androidTest/**/entities/*.java" + property "sonar.exclusions", "build/**,**/*.png,*.iml, **/*generated*," property "sonar.import_unknown_files", true // Defines where the java files are diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/AccountTest.java b/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/AccountTest.java deleted file mode 100644 index e5330b62..00000000 --- a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/AccountTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.github.wulkanowy.data.db.dao.entities; - -import org.greenrobot.greendao.test.AbstractDaoTestLongPk; - -public class AccountTest extends AbstractDaoTestLongPk { - - public AccountTest() { - super(AccountDao.class); - } - - @Override - protected Account createEntity(Long key) { - Account entity = new Account(); - entity.setId(key); - return entity; - } - -} diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/AttendanceLessonTest.java b/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/AttendanceLessonTest.java deleted file mode 100644 index 0aca371a..00000000 --- a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/AttendanceLessonTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package io.github.wulkanowy.data.db.dao.entities; - -import org.greenrobot.greendao.test.AbstractDaoTestLongPk; - -public class AttendanceLessonTest extends AbstractDaoTestLongPk { - - public AttendanceLessonTest() { - super(AttendanceLessonDao.class); - } - - @Override - protected AttendanceLesson createEntity(Long key) { - AttendanceLesson entity = new AttendanceLesson(); - entity.setId(key); - entity.setPresence(false); - entity.setAbsenceUnexcused(false); - entity.setAbsenceExcused(false); - entity.setUnexcusedLateness(false); - entity.setAbsenceForSchoolReasons(false); - entity.setExcusedLateness(false); - entity.setExemption(false); - return entity; - } - -} diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/DayTest.java b/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/DayTest.java deleted file mode 100644 index cdab015a..00000000 --- a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/DayTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package io.github.wulkanowy.data.db.dao.entities; - -import org.greenrobot.greendao.test.AbstractDaoTestLongPk; - -public class DayTest extends AbstractDaoTestLongPk { - - public DayTest() { - super(DayDao.class); - } - - @Override - protected Day createEntity(Long key) { - Day entity = new Day(); - entity.setId(key); - entity.setFreeDay(false); - return entity; - } - -} diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/DiaryTest.java b/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/DiaryTest.java deleted file mode 100644 index 2951aec8..00000000 --- a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/DiaryTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package io.github.wulkanowy.data.db.dao.entities; - -import org.greenrobot.greendao.test.AbstractDaoTestLongPk; - -public class DiaryTest extends AbstractDaoTestLongPk { - - public DiaryTest() { - super(DiaryDao.class); - } - - @Override - protected Diary createEntity(Long key) { - Diary entity = new Diary(); - entity.setId(key); - entity.setCurrent(false); - return entity; - } - -} diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/ExamTest.java b/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/ExamTest.java deleted file mode 100644 index 271e811f..00000000 --- a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/ExamTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.github.wulkanowy.data.db.dao.entities; - -import org.greenrobot.greendao.test.AbstractDaoTestLongPk; - -public class ExamTest extends AbstractDaoTestLongPk { - - public ExamTest() { - super(ExamDao.class); - } - - @Override - protected Exam createEntity(Long key) { - Exam entity = new Exam(); - entity.setId(key); - return entity; - } - -} diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/GradeTest.java b/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/GradeTest.java deleted file mode 100644 index ea026559..00000000 --- a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/GradeTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.github.wulkanowy.data.db.dao.entities; - -import org.greenrobot.greendao.test.AbstractDaoTestLongPk; - -public class GradeTest extends AbstractDaoTestLongPk { - - public GradeTest() { - super(GradeDao.class); - } - - @Override - protected Grade createEntity(Long key) { - Grade entity = new Grade(); - entity.setId(key); - entity.setIsNew(false); - entity.setRead(false); - return entity; - } - -} diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SchoolTest.java b/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SchoolTest.java deleted file mode 100644 index 13f63e0d..00000000 --- a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SchoolTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package io.github.wulkanowy.data.db.dao.entities; - -import org.greenrobot.greendao.test.AbstractDaoTestLongPk; - -import io.github.wulkanowy.data.db.dao.entities.School; -import io.github.wulkanowy.data.db.dao.entities.SchoolDao; - -public class SchoolTest extends AbstractDaoTestLongPk { - - public SchoolTest() { - super(SchoolDao.class); - } - - @Override - protected School createEntity(Long key) { - School entity = new School(); - entity.setId(key); - entity.setCurrent(false); - return entity; - } - -} diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SemesterTest.java b/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SemesterTest.java deleted file mode 100644 index a18a7674..00000000 --- a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SemesterTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.github.wulkanowy.data.db.dao.entities; - -import org.greenrobot.greendao.test.AbstractDaoTestLongPk; - -import io.github.wulkanowy.data.db.dao.entities.Semester; -import io.github.wulkanowy.data.db.dao.entities.SemesterDao; - -public class SemesterTest extends AbstractDaoTestLongPk { - - public SemesterTest() { - super(SemesterDao.class); - } - - @Override - protected Semester createEntity(Long key) { - Semester entity = new Semester(); - entity.setId(key); - return entity; - } - -} diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/StudentTest.java b/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/StudentTest.java deleted file mode 100644 index 1ba8fd46..00000000 --- a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/StudentTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.github.wulkanowy.data.db.dao.entities; - -import org.greenrobot.greendao.test.AbstractDaoTestLongPk; - -import io.github.wulkanowy.data.db.dao.entities.Student; -import io.github.wulkanowy.data.db.dao.entities.StudentDao; - -public class StudentTest extends AbstractDaoTestLongPk { - - public StudentTest() { - super(StudentDao.class); - } - - @Override - protected Student createEntity(Long key) { - Student entity = new Student(); - entity.setId(key); - return entity; - } - -} diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SubjectTest.java b/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SubjectTest.java deleted file mode 100644 index 81a2e724..00000000 --- a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SubjectTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.github.wulkanowy.data.db.dao.entities; - -import org.greenrobot.greendao.test.AbstractDaoTestLongPk; - -public class SubjectTest extends AbstractDaoTestLongPk { - - public SubjectTest() { - super(SubjectDao.class); - } - - @Override - protected Subject createEntity(Long key) { - Subject entity = new Subject(); - entity.setId(key); - return entity; - } - -} diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SymbolTest.java b/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SymbolTest.java deleted file mode 100644 index e1bad201..00000000 --- a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SymbolTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.github.wulkanowy.data.db.dao.entities; - -import org.greenrobot.greendao.test.AbstractDaoTestLongPk; - -import io.github.wulkanowy.data.db.dao.entities.Symbol; -import io.github.wulkanowy.data.db.dao.entities.SymbolDao; - -public class SymbolTest extends AbstractDaoTestLongPk { - - public SymbolTest() { - super(SymbolDao.class); - } - - @Override - protected Symbol createEntity(Long key) { - Symbol entity = new Symbol(); - entity.setId(key); - return entity; - } - -} diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/TimetableLessonTest.java b/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/TimetableLessonTest.java deleted file mode 100644 index 190f09b7..00000000 --- a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/TimetableLessonTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package io.github.wulkanowy.data.db.dao.entities; - -import org.greenrobot.greendao.test.AbstractDaoTestLongPk; - -public class TimetableLessonTest extends AbstractDaoTestLongPk { - - public TimetableLessonTest() { - super(TimetableLessonDao.class); - } - - @Override - protected TimetableLesson createEntity(Long key) { - TimetableLesson entity = new TimetableLesson(); - entity.setId(key); - entity.setEmpty(false); - entity.setDivisionIntoGroups(false); - entity.setPlanning(false); - entity.setRealized(false); - entity.setMovedOrCanceled(false); - entity.setNewMovedInOrChanged(false); - return entity; - } - -} diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/WeekTest.java b/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/WeekTest.java deleted file mode 100644 index 86e7a8be..00000000 --- a/app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/WeekTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.github.wulkanowy.data.db.dao.entities; - -import org.greenrobot.greendao.test.AbstractDaoTestLongPk; - -public class WeekTest extends AbstractDaoTestLongPk { - - public WeekTest() { - super(WeekDao.class); - } - - @Override - protected Week createEntity(Long key) { - Week entity = new Week(); - entity.setId(key); - return entity; - } - -} diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/repositories/local/AttendanceLocalTest.kt b/app/src/androidTest/java/io/github/wulkanowy/data/repositories/local/AttendanceLocalTest.kt new file mode 100644 index 00000000..47116483 --- /dev/null +++ b/app/src/androidTest/java/io/github/wulkanowy/data/repositories/local/AttendanceLocalTest.kt @@ -0,0 +1,52 @@ +package io.github.wulkanowy.data.repositories.local + +import androidx.room.Room +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import io.github.wulkanowy.data.db.AppDatabase +import io.github.wulkanowy.data.db.entities.Attendance +import io.github.wulkanowy.data.db.entities.Semester +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.threeten.bp.LocalDate +import kotlin.test.assertEquals + +@RunWith(AndroidJUnit4::class) +class AttendanceLocalTest { + + private lateinit var attendanceLocal: AttendanceLocal + + private lateinit var testDb: AppDatabase + + @Before + fun createDb() { + testDb = Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), AppDatabase::class.java).build() + attendanceLocal = AttendanceLocal(testDb.attendanceDao()) + } + + @After + fun closeDb() { + testDb.close() + } + + @Test + fun saveAndReadTest() { + attendanceLocal.saveAttendance(listOf( + Attendance(1, 2, LocalDate.of(2018, 9, 10), 0, "", ""), + Attendance(1, 2, LocalDate.of(2018, 9, 14), 0, "", ""), + Attendance(1, 2, LocalDate.of(2018, 9, 17), 0, "", "") + )) + + val attendance = attendanceLocal + .getAttendance(Semester(1, 1, 2, "", 3, 1), + LocalDate.of(2018, 9, 10), + LocalDate.of(2018, 9, 14) + ) + .blockingGet() + assertEquals(2, attendance.size) + assertEquals(attendance[0].date, LocalDate.of(2018, 9, 10)) + assertEquals(attendance[1].date, LocalDate.of(2018, 9, 14)) + } +} diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/repositories/local/ExamLocalTest.kt b/app/src/androidTest/java/io/github/wulkanowy/data/repositories/local/ExamLocalTest.kt new file mode 100644 index 00000000..7e4217f1 --- /dev/null +++ b/app/src/androidTest/java/io/github/wulkanowy/data/repositories/local/ExamLocalTest.kt @@ -0,0 +1,52 @@ +package io.github.wulkanowy.data.repositories.local + +import androidx.room.Room +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import io.github.wulkanowy.data.db.AppDatabase +import io.github.wulkanowy.data.db.entities.Exam +import io.github.wulkanowy.data.db.entities.Semester +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.threeten.bp.LocalDate +import kotlin.test.assertEquals + +@RunWith(AndroidJUnit4::class) +class ExamLocalTest { + + private lateinit var examLocal: ExamLocal + + private lateinit var testDb: AppDatabase + + @Before + fun createDb() { + testDb = Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), AppDatabase::class.java).build() + examLocal = ExamLocal(testDb.examsDao()) + } + + @After + fun closeDb() { + testDb.close() + } + + @Test + fun saveAndReadTest() { + examLocal.saveExams(listOf( + Exam(1, 2, LocalDate.of(2018, 9, 10), LocalDate.now(), "", "", "", "", "", ""), + Exam(1, 2, LocalDate.of(2018, 9, 14), LocalDate.now(), "", "", "", "", "", ""), + Exam(1, 2, LocalDate.of(2018, 9, 17), LocalDate.now(), "", "", "", "", "", "") + )) + + val exams = examLocal + .getExams(Semester(1, 1, 2, "", 3, 1), + LocalDate.of(2018, 9, 10), + LocalDate.of(2018, 9, 14) + ) + .blockingGet() + assertEquals(2, exams.size) + assertEquals(exams[0].date, LocalDate.of(2018, 9, 10)) + assertEquals(exams[1].date, LocalDate.of(2018, 9, 14)) + } +} diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/repositories/local/SessionLocalTest.kt b/app/src/androidTest/java/io/github/wulkanowy/data/repositories/local/SessionLocalTest.kt new file mode 100644 index 00000000..ba9273f4 --- /dev/null +++ b/app/src/androidTest/java/io/github/wulkanowy/data/repositories/local/SessionLocalTest.kt @@ -0,0 +1,49 @@ +package io.github.wulkanowy.data.repositories.local + +import android.content.Context +import androidx.room.Room +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import io.github.wulkanowy.data.db.AppDatabase +import io.github.wulkanowy.data.db.SharedPrefHelper +import io.github.wulkanowy.data.db.entities.Student +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import kotlin.test.assertEquals + +@RunWith(AndroidJUnit4::class) +class SessionLocalTest { + + private lateinit var sessionLocal: SessionLocal + + private lateinit var testDb: AppDatabase + + private lateinit var sharedHelper: SharedPrefHelper + + @Before + fun createDb() { + val context = ApplicationProvider.getApplicationContext() + testDb = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java) + .build() + sharedHelper = SharedPrefHelper(context.getSharedPreferences("TEST", Context.MODE_PRIVATE)) + sessionLocal = SessionLocal(testDb.studentDao(), testDb.semesterDao(), sharedHelper, context) + } + + @After + fun closeDb() { + testDb.close() + } + + @Test + fun saveAndReadTest() { + sessionLocal.saveStudent(Student(email = "test", password = "test123", schoolSymbol = "23", endpoint = "fakelog.cf", loginType = "AUTO")).blockingAwait() + assert(sharedHelper.getLong(SessionLocal.LAST_USER_KEY, 0) == 1L) + + assert(sessionLocal.isSessionSaved) + + val student = sessionLocal.getLastStudent().blockingGet() + assertEquals("23", student.schoolSymbol) + } +} diff --git a/app/src/androidTest/java/io/github/wulkanowy/data/repositories/local/TimetableLocalTest.kt b/app/src/androidTest/java/io/github/wulkanowy/data/repositories/local/TimetableLocalTest.kt new file mode 100644 index 00000000..81d822ea --- /dev/null +++ b/app/src/androidTest/java/io/github/wulkanowy/data/repositories/local/TimetableLocalTest.kt @@ -0,0 +1,55 @@ +package io.github.wulkanowy.data.repositories.local + +import androidx.room.Room +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import io.github.wulkanowy.data.db.AppDatabase +import io.github.wulkanowy.data.db.entities.Semester +import io.github.wulkanowy.data.db.entities.Timetable +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.threeten.bp.LocalDate +import org.threeten.bp.LocalDateTime +import kotlin.test.assertEquals + +@RunWith(AndroidJUnit4::class) +class TimetableLocalTest { + + private lateinit var timetableDb: TimetableLocal + + private lateinit var testDb: AppDatabase + + @Before + fun createDb() { + testDb = Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), AppDatabase::class.java).build() + timetableDb = TimetableLocal(testDb.timetableDao()) + } + + @After + fun closeDb() { + testDb.close() + } + + @Test + fun saveAndReadTest() { + timetableDb.saveTimetable(listOf( + Timetable(1, 2, 1, LocalDateTime.now(), LocalDateTime.now(), + LocalDate.of(2018, 9, 10), "", "", "", "", ""), + Timetable(1, 2, 1, LocalDateTime.now(), LocalDateTime.now(), + LocalDate.of(2018, 9, 14), "", "", "", "", ""), + Timetable(1, 2, 1, LocalDateTime.now(), LocalDateTime.now(), + LocalDate.of(2018, 9, 17), "", "", "", "", "") + )) + + val exams = timetableDb.getTimetable( + Semester(0, 1, 2, "3", 1, 1), + LocalDate.of(2018, 9, 10), + LocalDate.of(2018, 9, 14) + ).blockingGet() + assertEquals(2, exams.size) + assertEquals(exams[0].date, LocalDate.of(2018, 9, 10)) + assertEquals(exams[1].date, LocalDate.of(2018, 9, 14)) + } +} diff --git a/app/src/androidTest/java/io/github/wulkanowy/utils/security/ScramblerTest.kt b/app/src/androidTest/java/io/github/wulkanowy/utils/security/ScramblerTest.kt index 162008de..a6e7e918 100644 --- a/app/src/androidTest/java/io/github/wulkanowy/utils/security/ScramblerTest.kt +++ b/app/src/androidTest/java/io/github/wulkanowy/utils/security/ScramblerTest.kt @@ -1,48 +1,47 @@ package io.github.wulkanowy.utils.security -import android.support.test.InstrumentationRegistry -import android.support.test.filters.SdkSuppress -import android.support.test.filters.SmallTest -import android.support.test.runner.AndroidJUnit4 +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.filters.SdkSuppress +import androidx.test.filters.SmallTest import org.junit.Test import org.junit.runner.RunWith import java.security.KeyStore import kotlin.test.assertEquals import kotlin.test.assertFailsWith - @SmallTest @RunWith(AndroidJUnit4::class) class ScramblerTest { @Test fun encryptDecryptTest() { - assertEquals("TEST", Scrambler.decrypt(Scrambler.encrypt("TEST", - InstrumentationRegistry.getTargetContext()))) + assertEquals("TEST", decrypt(encrypt("TEST", + ApplicationProvider.getApplicationContext()))) } @Test fun emptyTextEncryptTest() { assertFailsWith { - Scrambler.decrypt("") + decrypt("") } assertFailsWith { - Scrambler.encrypt("", InstrumentationRegistry.getTargetContext()) + encrypt("", ApplicationProvider.getApplicationContext()) } } @Test @SdkSuppress(minSdkVersion = 18) fun emptyKeyStoreTest() { - val text = Scrambler.encrypt("test", InstrumentationRegistry.getTargetContext()) + val text = encrypt("test", ApplicationProvider.getApplicationContext()) val keyStore = KeyStore.getInstance("AndroidKeyStore") keyStore.load(null) keyStore.deleteEntry("USER_PASSWORD") assertFailsWith { - Scrambler.decrypt(text) + decrypt(text) } } } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 59963c45..5f21c0c0 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,5 +1,6 @@ @@ -13,12 +14,14 @@ android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" - android:theme="@style/WulkanowyTheme"> + android:supportsRtl="false" + android:theme="@style/WulkanowyTheme" + android:usesCleartextTraffic="true" + tools:ignore="GoogleAppIndexingWarning"> + android:name=".ui.modules.splash.SplashActivity" + android:screenOrientation="portrait" + android:theme="@style/WulkanowyTheme.SplashScreen"> @@ -26,46 +29,41 @@ - - + android:label="@string/main_title" + android:launchMode="singleTop" + android:theme="@style/WulkanowyTheme.NoActionBar" /> - + + android:resource="@xml/provider_widget_timetable" /> - diff --git a/app/src/main/java/io/github/wulkanowy/WulkanowyApp.kt b/app/src/main/java/io/github/wulkanowy/WulkanowyApp.kt index 3e440ef1..b7d7c489 100644 --- a/app/src/main/java/io/github/wulkanowy/WulkanowyApp.kt +++ b/app/src/main/java/io/github/wulkanowy/WulkanowyApp.kt @@ -1,5 +1,8 @@ package io.github.wulkanowy +import android.content.Context +import androidx.multidex.MultiDex +import com.akaita.java.rxjava2debug.RxJava2Debug import com.crashlytics.android.Crashlytics import com.crashlytics.android.answers.Answers import com.crashlytics.android.core.CrashlyticsCore @@ -7,68 +10,43 @@ import com.jakewharton.threetenabp.AndroidThreeTen import dagger.android.AndroidInjector import dagger.android.support.DaggerApplication import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.utils.Log import io.fabric.sdk.android.Fabric -import io.github.wulkanowy.data.RepositoryContract +import io.github.wulkanowy.BuildConfig.DEBUG import io.github.wulkanowy.di.DaggerAppComponent -import io.github.wulkanowy.utils.FabricUtils -import io.github.wulkanowy.utils.LoggerUtils -import io.github.wulkanowy.utils.security.ScramblerException -import org.greenrobot.greendao.query.QueryBuilder +import io.github.wulkanowy.utils.CrashlyticsTree +import io.github.wulkanowy.utils.DebugLogTree import timber.log.Timber -import javax.inject.Inject class WulkanowyApp : DaggerApplication() { - @Inject - internal lateinit var repository: RepositoryContract + override fun attachBaseContext(base: Context?) { + super.attachBaseContext(base) + MultiDex.install(this) + } override fun onCreate() { super.onCreate() AndroidThreeTen.init(this) - - if (BuildConfig.DEBUG) { - enableDebugLog() - } initializeFabric() - initializeUserSession() - } - - private fun initializeUserSession() { - if (repository.sharedRepo.isUserLoggedIn) { - try { - repository.syncRepo.initLastUser() - FabricUtils.logLogin("Open app", true) - } catch (e: Exception) { - FabricUtils.logLogin("Open app", false) - Timber.e(e, "An error occurred when the application was started") - } catch (e: ScramblerException) { - FabricUtils.logLogin("Open app", false) - Timber.e(e, "A security error has occurred") - repository.cleanAllData() - } - - } + if (DEBUG) enableDebugLog() + RxJava2Debug.enableRxJava2AssemblyTracking(arrayOf(BuildConfig.APPLICATION_ID)) } private fun enableDebugLog() { - QueryBuilder.LOG_VALUES = true - FlexibleAdapter.enableLogs(eu.davidea.flexibleadapter.utils.Log.Level.DEBUG) - Timber.plant(LoggerUtils.DebugLogTree()) + Timber.plant(DebugLogTree()) + FlexibleAdapter.enableLogs(Log.Level.DEBUG) } private fun initializeFabric() { - Fabric.with(Fabric.Builder(this) - .kits( - Crashlytics.Builder() - .core(CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build()) - .build(), - Answers() - ) - .debuggable(BuildConfig.DEBUG) - .build()) - Timber.plant(LoggerUtils.CrashlyticsTree()) + Fabric.with(Fabric.Builder(this).kits( + Crashlytics.Builder().core(CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG || !BuildConfig.FABRIC_ENABLED).build()).build(), + Answers() + ).debuggable(BuildConfig.DEBUG).build()) + Timber.plant(CrashlyticsTree()) } - override fun applicationInjector(): AndroidInjector = - DaggerAppComponent.builder().create(this) + override fun applicationInjector(): AndroidInjector { + return DaggerAppComponent.builder().create(this) + } } diff --git a/app/src/main/java/io/github/wulkanowy/data/ErrorHandler.kt b/app/src/main/java/io/github/wulkanowy/data/ErrorHandler.kt new file mode 100644 index 00000000..481690a7 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/ErrorHandler.kt @@ -0,0 +1,31 @@ +package io.github.wulkanowy.data + +import android.content.res.Resources +import com.akaita.java.rxjava2debug.RxJava2Debug +import io.github.wulkanowy.R +import io.github.wulkanowy.api.login.NotLoggedInException +import timber.log.Timber +import java.io.IOException +import java.net.SocketTimeoutException +import java.net.UnknownHostException +import javax.inject.Inject + +open class ErrorHandler @Inject constructor(private val resources: Resources) { + + var showErrorMessage: (String) -> Unit = {} + + open fun proceed(error: Throwable) { + Timber.e(RxJava2Debug.getEnhancedStackTrace(error), "An exception occurred while the Wulkanowy was running") + + showErrorMessage((when (error) { + is UnknownHostException -> resources.getString(R.string.all_no_internet) + is SocketTimeoutException -> resources.getString(R.string.all_timeout) + is NotLoggedInException, is IOException -> resources.getString(R.string.all_login_failed) + else -> error.localizedMessage + })) + } + + open fun clear() { + showErrorMessage = {} + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/Repository.java b/app/src/main/java/io/github/wulkanowy/data/Repository.java deleted file mode 100644 index ac6a8b42..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/Repository.java +++ /dev/null @@ -1,56 +0,0 @@ -package io.github.wulkanowy.data; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import io.github.wulkanowy.data.db.dao.DbContract; -import io.github.wulkanowy.data.db.resources.ResourcesContract; -import io.github.wulkanowy.data.db.shared.SharedPrefContract; -import io.github.wulkanowy.data.sync.SyncContract; - -@Singleton -public class Repository implements RepositoryContract { - - private final DbContract database; - - private final ResourcesContract resources; - - private final SharedPrefContract sharedPref; - - private final SyncContract synchronization; - - @Inject - Repository(DbContract database, ResourcesContract resources, SharedPrefContract sharedPref, - SyncContract synchronization) { - this.database = database; - this.resources = resources; - this.sharedPref = sharedPref; - this.synchronization = synchronization; - } - - @Override - public SharedPrefContract getSharedRepo() { - return sharedPref; - } - - @Override - public ResourcesContract getResRepo() { - return resources; - } - - @Override - public DbContract getDbRepo() { - return database; - } - - @Override - public SyncContract getSyncRepo() { - return synchronization; - } - - @Override - public void cleanAllData() { - sharedPref.cleanSharedPref(); - database.recreateDatabase(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/RepositoryContract.java b/app/src/main/java/io/github/wulkanowy/data/RepositoryContract.java deleted file mode 100644 index e4dbd26b..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/RepositoryContract.java +++ /dev/null @@ -1,22 +0,0 @@ -package io.github.wulkanowy.data; - -import javax.inject.Singleton; - -import io.github.wulkanowy.data.db.dao.DbContract; -import io.github.wulkanowy.data.db.resources.ResourcesContract; -import io.github.wulkanowy.data.db.shared.SharedPrefContract; -import io.github.wulkanowy.data.sync.SyncContract; - -@Singleton -public interface RepositoryContract { - - SharedPrefContract getSharedRepo(); - - ResourcesContract getResRepo(); - - DbContract getDbRepo(); - - SyncContract getSyncRepo(); - - void cleanAllData(); -} diff --git a/app/src/main/java/io/github/wulkanowy/data/RepositoryModule.kt b/app/src/main/java/io/github/wulkanowy/data/RepositoryModule.kt new file mode 100644 index 00000000..df14b4f5 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/RepositoryModule.kt @@ -0,0 +1,70 @@ +package io.github.wulkanowy.data + +import android.content.Context +import android.content.SharedPreferences +import androidx.preference.PreferenceManager +import com.github.pwittchen.reactivenetwork.library.rx2.internet.observing.InternetObservingSettings +import com.github.pwittchen.reactivenetwork.library.rx2.internet.observing.strategy.SocketInternetObservingStrategy +import dagger.Module +import dagger.Provides +import io.github.wulkanowy.api.Api +import io.github.wulkanowy.data.db.AppDatabase +import javax.inject.Singleton + +@Module +internal class RepositoryModule { + + @Singleton + @Provides + fun provideInternetObservingSettings(): InternetObservingSettings { + return InternetObservingSettings.builder() + .strategy(SocketInternetObservingStrategy()) + .host("www.google.com") + .build() + } + + @Singleton + @Provides + fun provideApi() = Api() + + @Singleton + @Provides + fun provideDatabase(context: Context) = AppDatabase.newInstance(context) + + @Provides + fun provideErrorHandler(context: Context) = ErrorHandler(context.resources) + + @Singleton + @Provides + fun provideSharedPref(context: Context): SharedPreferences { + return PreferenceManager.getDefaultSharedPreferences(context) + } + + @Singleton + @Provides + fun provideStudentDao(database: AppDatabase) = database.studentDao() + + @Singleton + @Provides + fun provideSemesterDao(database: AppDatabase) = database.semesterDao() + + @Singleton + @Provides + fun provideGradeDao(database: AppDatabase) = database.gradeDao() + + @Singleton + @Provides + fun provideGradeSummaryDao(database: AppDatabase) = database.gradeSummaryDao() + + @Singleton + @Provides + fun provideExamDao(database: AppDatabase) = database.examsDao() + + @Singleton + @Provides + fun provideAttendanceDao(database: AppDatabase) = database.attendanceDao() + + @Singleton + @Provides + fun provideTimetableDao(database: AppDatabase) = database.timetableDao() +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/AppDatabase.kt b/app/src/main/java/io/github/wulkanowy/data/db/AppDatabase.kt new file mode 100644 index 00000000..2f5920a5 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/AppDatabase.kt @@ -0,0 +1,49 @@ +package io.github.wulkanowy.data.db + +import android.content.Context +import androidx.room.Database +import androidx.room.Room +import androidx.room.RoomDatabase +import androidx.room.TypeConverters +import io.github.wulkanowy.data.db.dao.* +import io.github.wulkanowy.data.db.entities.* +import javax.inject.Singleton + +@Singleton +@Database( + entities = [ + Student::class, + Semester::class, + Exam::class, + Timetable::class, + Attendance::class, + Grade::class, + GradeSummary::class + ], + version = 1, + exportSchema = false +) +@TypeConverters(Converters::class) +abstract class AppDatabase : RoomDatabase() { + + companion object { + fun newInstance(context: Context): AppDatabase { + return Room.databaseBuilder(context, AppDatabase::class.java, "wulkanowy_database") + .build() + } + } + + abstract fun studentDao(): StudentDao + + abstract fun semesterDao(): SemesterDao + + abstract fun examsDao(): ExamDao + + abstract fun timetableDao(): TimetableDao + + abstract fun attendanceDao(): AttendanceDao + + abstract fun gradeDao(): GradeDao + + abstract fun gradeSummaryDao(): GradeSummaryDao +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/Converters.kt b/app/src/main/java/io/github/wulkanowy/data/db/Converters.kt new file mode 100644 index 00000000..0700dd43 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/Converters.kt @@ -0,0 +1,28 @@ +package io.github.wulkanowy.data.db + +import androidx.room.TypeConverter +import org.threeten.bp.* +import java.util.* + +class Converters { + + @TypeConverter + fun timestampToDate(value: Long?): LocalDate? = value?.run { + DateTimeUtils.toInstant(Date(value)).atZone(ZoneOffset.UTC).toLocalDate() + } + + @TypeConverter + fun dateToTimestamp(date: LocalDate?): Long? { + return date?.atStartOfDay()?.toInstant(ZoneOffset.UTC)?.toEpochMilli() + } + + @TypeConverter + fun timestampToTime(value: Long?): LocalDateTime? = value?.let { + LocalDateTime.ofInstant(Instant.ofEpochMilli(value), ZoneOffset.UTC) + } + + @TypeConverter + fun timeToTimestamp(date: LocalDateTime?): Long? { + return date?.atZone(ZoneOffset.UTC)?.toInstant()?.toEpochMilli() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/SharedPrefHelper.kt b/app/src/main/java/io/github/wulkanowy/data/db/SharedPrefHelper.kt new file mode 100644 index 00000000..b3b6f5e3 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/SharedPrefHelper.kt @@ -0,0 +1,25 @@ +package io.github.wulkanowy.data.db + +import android.annotation.SuppressLint +import android.content.SharedPreferences +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class SharedPrefHelper @Inject constructor(private val sharedPref: SharedPreferences) { + + @SuppressLint("ApplySharedPref") + fun putLong(key: String, value: Long, sync: Boolean = false) { + sharedPref.edit().putLong(key, value).apply { + if (sync) commit() else apply() + } + } + + fun getLong(key: String, defaultValue: Long): Long { + return sharedPref.getLong(key, defaultValue) + } + + fun delete(key: String) { + sharedPref.edit().remove(key).apply() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/AttendanceDao.kt b/app/src/main/java/io/github/wulkanowy/data/db/dao/AttendanceDao.kt new file mode 100644 index 00000000..7babb76e --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/dao/AttendanceDao.kt @@ -0,0 +1,22 @@ +package io.github.wulkanowy.data.db.dao + +import androidx.room.Dao +import androidx.room.Delete +import androidx.room.Insert +import androidx.room.Query +import io.github.wulkanowy.data.db.entities.Attendance +import io.reactivex.Maybe +import org.threeten.bp.LocalDate + +@Dao +interface AttendanceDao { + + @Insert + fun insertAll(exams: List): List + + @Delete + fun deleteAll(exams: List) + + @Query("SELECT * FROM Attendance WHERE diary_id = :diaryId AND student_id = :studentId AND date >= :from AND date <= :end") + fun getExams(diaryId: Int, studentId: Int, from: LocalDate, end: LocalDate): Maybe> +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/DbContract.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/DbContract.java deleted file mode 100644 index 22eaa944..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/DbContract.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.github.wulkanowy.data.db.dao; - -import java.util.List; - -import io.github.wulkanowy.data.db.dao.entities.Grade; -import io.github.wulkanowy.data.db.dao.entities.Subject; -import io.github.wulkanowy.data.db.dao.entities.Symbol; -import io.github.wulkanowy.data.db.dao.entities.Week; - -public interface DbContract { - - Week getWeek(String date); - - Week getWeek(long diaryId, String date); - - List getSubjectList(int semesterName); - - List getNewGrades(int semesterName); - - long getCurrentSchoolId(); - - long getCurrentStudentId(); - - long getCurrentSymbolId(); - - Symbol getCurrentSymbol(); - - long getCurrentDiaryId(); - - long getSemesterId(int name); - - long getCurrentSemesterId(); - - int getCurrentSemesterName(); - - void recreateDatabase(); -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/DbHelper.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/DbHelper.java deleted file mode 100644 index 33b19311..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/DbHelper.java +++ /dev/null @@ -1,102 +0,0 @@ -package io.github.wulkanowy.data.db.dao; - -import android.content.Context; -import android.database.sqlite.SQLiteDatabase; - -import org.greenrobot.greendao.database.Database; -import org.greenrobot.greendao.database.StandardDatabase; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import io.github.wulkanowy.api.Vulcan; -import io.github.wulkanowy.data.db.dao.entities.DaoMaster; -import io.github.wulkanowy.data.db.dao.migrations.Migration23; -import io.github.wulkanowy.data.db.dao.migrations.Migration26; -import io.github.wulkanowy.data.db.dao.migrations.Migration27; -import io.github.wulkanowy.data.db.dao.migrations.Migration28; -import io.github.wulkanowy.data.db.dao.migrations.Migration29; -import io.github.wulkanowy.data.db.shared.SharedPrefContract; -import timber.log.Timber; - -@Singleton -public class DbHelper extends DaoMaster.OpenHelper { - - private final SharedPrefContract sharedPref; - - private final Vulcan vulcan; - - @Inject - DbHelper(Context context, @Named("dbName") String dbName, - SharedPrefContract sharedPref, Vulcan vulcan) { - super(context, dbName); - this.sharedPref = sharedPref; - this.vulcan = vulcan; - } - - @Override - public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { - Timber.i("Cleaning user data oldVersion=%s newVersion=%s", oldVersion, newVersion); - Database database = new StandardDatabase(db); - recreateDatabase(database); - } - - @Override - public void onUpgrade(Database db, int oldVersion, int newVersion) { - List migrations = getMigrations(); - - // Only run migrations past the old version - for (Migration migration : migrations) { - if (oldVersion < migration.getVersion()) { - try { - Timber.i("Applying migration to db schema v%s...", migration.getVersion()); - migration.runMigration(db, sharedPref, vulcan); - Timber.i("Migration %s complete", migration.getVersion()); - } catch (Exception e) { - Timber.e(e, "Failed to apply migration"); - recreateDatabase(db); - break; - } - } - } - } - - private void recreateDatabase(Database db) { - Timber.i("Database is recreating..."); - sharedPref.setCurrentUserId(0); - DaoMaster.dropAllTables(db, true); - onCreate(db); - } - - private List getMigrations() { - List migrations = new ArrayList<>(); - migrations.add(new Migration23()); - migrations.add(new Migration26()); - migrations.add(new Migration27()); - migrations.add(new Migration28()); - migrations.add(new Migration29()); - - // Sorting just to be safe, in case other people add migrations in the wrong order. - Comparator migrationComparator = new Comparator() { - @Override - public int compare(Migration m1, Migration m2) { - return m1.getVersion().compareTo(m2.getVersion()); - } - }; - Collections.sort(migrations, migrationComparator); - - return migrations; - } - - public interface Migration { - Integer getVersion(); - - void runMigration(Database db, SharedPrefContract sharedPref, Vulcan vulcan) throws Exception; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/DbRepository.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/DbRepository.java deleted file mode 100644 index d869bfe9..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/DbRepository.java +++ /dev/null @@ -1,132 +0,0 @@ -package io.github.wulkanowy.data.db.dao; - -import org.greenrobot.greendao.database.Database; - -import java.util.List; - -import javax.inject.Inject; - -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.DiaryDao; -import io.github.wulkanowy.data.db.dao.entities.Grade; -import io.github.wulkanowy.data.db.dao.entities.GradeDao; -import io.github.wulkanowy.data.db.dao.entities.SchoolDao; -import io.github.wulkanowy.data.db.dao.entities.Semester; -import io.github.wulkanowy.data.db.dao.entities.SemesterDao; -import io.github.wulkanowy.data.db.dao.entities.StudentDao; -import io.github.wulkanowy.data.db.dao.entities.Subject; -import io.github.wulkanowy.data.db.dao.entities.Symbol; -import io.github.wulkanowy.data.db.dao.entities.SymbolDao; -import io.github.wulkanowy.data.db.dao.entities.Week; -import io.github.wulkanowy.data.db.dao.entities.WeekDao; -import io.github.wulkanowy.data.db.shared.SharedPrefContract; - -public class DbRepository implements DbContract { - - private final DaoSession daoSession; - - private final SharedPrefContract sharedPref; - - @Inject - DbRepository(DaoSession daoSession, SharedPrefContract sharedPrefContract) { - this.daoSession = daoSession; - this.sharedPref = sharedPrefContract; - } - - - @Override - public Week getWeek(String date) { - return getWeek(getCurrentDiaryId(), date); - } - - @Override - public Week getWeek(long diaryId, String date) { - return daoSession.getWeekDao().queryBuilder().where( - WeekDao.Properties.StartDayDate.eq(date), - WeekDao.Properties.DiaryId.eq(diaryId) - ).unique(); - } - - @Override - public List getSubjectList(int semesterName) { - return daoSession.getSemesterDao().load(getSemesterId(semesterName)).getSubjectList(); - } - - @Override - public List getNewGrades(int semesterName) { - return daoSession.getGradeDao().queryBuilder().where( - GradeDao.Properties.IsNew.eq(1), - GradeDao.Properties.SemesterId.eq(getSemesterId(semesterName)) - ).list(); - } - - @Override - public Symbol getCurrentSymbol() { - return daoSession.getSymbolDao().queryBuilder().where( - SymbolDao.Properties.UserId.eq(sharedPref.getCurrentUserId()) - ).unique(); - } - - @Override - public long getCurrentSymbolId() { - return getCurrentSymbol().getId(); - } - - @Override - public long getCurrentSchoolId() { - return daoSession.getSchoolDao().queryBuilder().where( - SchoolDao.Properties.SymbolId.eq(getCurrentSymbolId()), - SchoolDao.Properties.Current.eq(true) - ).unique().getId(); - } - - @Override - public long getCurrentStudentId() { - return daoSession.getStudentDao().queryBuilder().where( - StudentDao.Properties.SchoolId.eq(getCurrentSchoolId()), - StudentDao.Properties.Current.eq(true) - ).unique().getId(); - } - - @Override - public long getCurrentDiaryId() { - return daoSession.getDiaryDao().queryBuilder().where( - DiaryDao.Properties.StudentId.eq(getCurrentStudentId()), - DiaryDao.Properties.Current.eq(true) - ).unique().getId(); - } - - @Override - public long getSemesterId(int name) { - return daoSession.getSemesterDao().queryBuilder().where( - SemesterDao.Properties.DiaryId.eq(getCurrentDiaryId()), - SemesterDao.Properties.Name.eq(String.valueOf(name)) - ).unique().getId(); - } - - @Override - public long getCurrentSemesterId() { - return getCurrentSemester().getId(); - } - - @Override - public int getCurrentSemesterName() { - return Integer.valueOf(getCurrentSemester().getName()); - } - - private Semester getCurrentSemester() { - return daoSession.getSemesterDao().queryBuilder().where( - SemesterDao.Properties.DiaryId.eq(getCurrentDiaryId()), - SemesterDao.Properties.Current.eq(true) - ).unique(); - } - - @Override - public void recreateDatabase() { - Database database = daoSession.getDatabase(); - - DaoMaster.dropAllTables(database, true); - DaoMaster.createAllTables(database, true); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/ExamDao.kt b/app/src/main/java/io/github/wulkanowy/data/db/dao/ExamDao.kt new file mode 100644 index 00000000..58c7867b --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/dao/ExamDao.kt @@ -0,0 +1,22 @@ +package io.github.wulkanowy.data.db.dao + +import androidx.room.Dao +import androidx.room.Delete +import androidx.room.Insert +import androidx.room.Query +import io.github.wulkanowy.data.db.entities.Exam +import io.reactivex.Maybe +import org.threeten.bp.LocalDate + +@Dao +interface ExamDao { + + @Insert + fun insertAll(exams: List): List + + @Delete + fun deleteAll(exams: List) + + @Query("SELECT * FROM Exams WHERE diary_id = :diaryId AND student_id = :studentId AND date >= :from AND date <= :end") + fun getExams(diaryId: Int, studentId: Int, from: LocalDate, end: LocalDate): Maybe> +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/GradeDao.kt b/app/src/main/java/io/github/wulkanowy/data/db/dao/GradeDao.kt new file mode 100644 index 00000000..e5a153a6 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/dao/GradeDao.kt @@ -0,0 +1,27 @@ +package io.github.wulkanowy.data.db.dao + +import androidx.room.* +import io.github.wulkanowy.data.db.entities.Grade +import io.reactivex.Maybe + +@Dao +interface GradeDao { + + @Insert + fun insertAll(grades: List) + + @Update + fun update(grade: Grade) + + @Update + fun updateAll(grade: List) + + @Delete + fun deleteAll(grades: List) + + @Query("SELECT * FROM Grades WHERE semester_id = :semesterId AND student_id = :studentId") + fun getGrades(semesterId: Int, studentId: Int): Maybe> + + @Query("SELECT * FROM Grades WHERE is_read = 0 AND semester_id = :semesterId AND student_id = :studentId") + fun getNewGrades(semesterId: Int, studentId: Int): Maybe> +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/GradeSummaryDao.kt b/app/src/main/java/io/github/wulkanowy/data/db/dao/GradeSummaryDao.kt new file mode 100644 index 00000000..3a9b9d81 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/dao/GradeSummaryDao.kt @@ -0,0 +1,22 @@ +package io.github.wulkanowy.data.db.dao + +import androidx.room.Dao +import androidx.room.Delete +import androidx.room.Insert +import androidx.room.OnConflictStrategy.REPLACE +import androidx.room.Query +import io.github.wulkanowy.data.db.entities.GradeSummary +import io.reactivex.Maybe + +@Dao +interface GradeSummaryDao { + + @Insert + fun insertAll(gradesSummary: List) + + @Delete + fun deleteAll(gradesSummary: List) + + @Query("SELECT * FROM grades_summary WHERE student_id = :studentId AND semester_id = :semesterId") + fun getGradesSummary(semesterId: Int, studentId: Int): Maybe> +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/SemesterDao.kt b/app/src/main/java/io/github/wulkanowy/data/db/dao/SemesterDao.kt new file mode 100644 index 00000000..135e65e5 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/dao/SemesterDao.kt @@ -0,0 +1,23 @@ +package io.github.wulkanowy.data.db.dao + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.Query +import io.github.wulkanowy.data.db.entities.Semester +import io.reactivex.Single + +@Dao +interface SemesterDao { + + @Insert + fun insertAll(semester: List) + + @Query("SELECT * FROM Semesters WHERE student_id = :studentId") + fun getSemester(studentId: Int): Single> + + @Query("UPDATE Semesters SET is_current = 0") + fun resetCurrentSemester() + + @Query("UPDATE Semesters SET is_current = 1 WHERE semester_id = :semesterId") + fun setCurrentSemester(semesterId: Int) +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/StudentDao.kt b/app/src/main/java/io/github/wulkanowy/data/db/dao/StudentDao.kt new file mode 100644 index 00000000..41bf5da9 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/dao/StudentDao.kt @@ -0,0 +1,17 @@ +package io.github.wulkanowy.data.db.dao + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.Query +import io.github.wulkanowy.data.db.entities.Student +import io.reactivex.Maybe + +@Dao +interface StudentDao { + + @Insert + fun insert(student: Student): Long + + @Query("SELECT * FROM Students WHERE id = :id") + fun load(id: Long): Maybe +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/TimetableDao.kt b/app/src/main/java/io/github/wulkanowy/data/db/dao/TimetableDao.kt new file mode 100644 index 00000000..2624e94a --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/dao/TimetableDao.kt @@ -0,0 +1,22 @@ +package io.github.wulkanowy.data.db.dao + +import androidx.room.Dao +import androidx.room.Delete +import androidx.room.Insert +import androidx.room.Query +import io.github.wulkanowy.data.db.entities.Timetable +import io.reactivex.Maybe +import org.threeten.bp.LocalDate + +@Dao +interface TimetableDao { + + @Insert + fun insertAll(exams: List): List + + @Delete + fun deleteAll(exams: List) + + @Query("SELECT * FROM Timetable WHERE diary_id = :diaryId AND student_id = :studentId AND date >= :from AND date <= :end") + fun getTimetable(diaryId: Int, studentId: Int, from: LocalDate, end: LocalDate): Maybe> +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Account.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Account.java deleted file mode 100644 index 78dff361..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Account.java +++ /dev/null @@ -1,153 +0,0 @@ -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 org.greenrobot.greendao.annotation.Unique; - -import java.util.List; - -@Entity( - nameInDb = "Accounts", - active = true -) -public class Account { - - @Id(autoincrement = true) - private Long id; - - @Unique - @Property(nameInDb = "email") - private String email; - - @Property(nameInDb = "password") - private String password; - - @ToMany(referencedJoinProperty = "userId") - private List symbolList; - - /** - * Used to resolve relations - */ - @Generated(hash = 2040040024) - private transient DaoSession daoSession; - - /** - * Used for active entity operations. - */ - @Generated(hash = 335469827) - private transient AccountDao myDao; - - @Generated(hash = 1104194311) - public Account(Long id, String email, String password) { - this.id = id; - this.email = email; - this.password = password; - } - - @Generated(hash = 882125521) - public Account() { - } - - public Long getId() { - return this.id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getEmail() { - return this.email; - } - - public Account setEmail(String email) { - this.email = email; - return this; - } - - public String getPassword() { - return this.password; - } - - public Account setPassword(String password) { - this.password = password; - 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 = 822972496) - public List getSymbolList() { - if (symbolList == null) { - final DaoSession daoSession = this.daoSession; - if (daoSession == null) { - throw new DaoException("Entity is detached from DAO context"); - } - SymbolDao targetDao = daoSession.getSymbolDao(); - List symbolListNew = targetDao._queryAccount_SymbolList(id); - synchronized (this) { - if (symbolList == null) { - symbolList = symbolListNew; - } - } - } - return symbolList; - } - - /** - * Resets a to-many relationship, making the next get call to query for a fresh result. - */ - @Generated(hash = 1716801695) - public synchronized void resetSymbolList() { - symbolList = 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 = 1812283172) - public void __setDaoSession(DaoSession daoSession) { - this.daoSession = daoSession; - myDao = daoSession != null ? daoSession.getAccountDao() : null; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/AttendanceLesson.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/AttendanceLesson.java deleted file mode 100644 index 81235e59..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/AttendanceLesson.java +++ /dev/null @@ -1,254 +0,0 @@ -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.Index; -import org.greenrobot.greendao.annotation.Property; -import org.greenrobot.greendao.annotation.Transient; - -import java.io.Serializable; - -@Entity( - nameInDb = "AttendanceLessons", - active = true, - indexes = {@Index(value = "dayId,date,number", unique = true)} -) -public class AttendanceLesson implements Serializable { - - @Id(autoincrement = true) - private Long id; - - @Property(nameInDb = "day_id") - private Long dayId; - - @Property(nameInDb = "date") - private String date = ""; - - @Property(nameInDb = "number_of_lesson") - private int number = 0; - - @Property(nameInDb = "subject") - private String subject = ""; - - @Property(nameInDb = "presence") - private boolean presence = false; - - @Property(nameInDb = "absence_unexcused") - private boolean absenceUnexcused = false; - - @Property(nameInDb = "absence_excused") - private boolean absenceExcused = false; - - @Property(nameInDb = "unexcused_lateness") - private boolean unexcusedLateness = false; - - @Property(nameInDb = "absence_for_school_reasons") - private boolean absenceForSchoolReasons = false; - - @Property(nameInDb = "excused_lateness") - private boolean excusedLateness = false; - - @Property(nameInDb = "exemption") - private boolean exemption = false; - - @Transient - private String description = ""; - - private static final long serialVersionUID = 42L; - - /** - * Used to resolve relations - */ - @Generated(hash = 2040040024) - private transient DaoSession daoSession; - - /** - * Used for active entity operations. - */ - @Generated(hash = 1936953859) - private transient AttendanceLessonDao myDao; - - @Generated(hash = 1741231228) - public AttendanceLesson(Long id, Long dayId, String date, int number, - String subject, boolean presence, boolean absenceUnexcused, - boolean absenceExcused, boolean unexcusedLateness, - boolean absenceForSchoolReasons, boolean excusedLateness, - boolean exemption) { - this.id = id; - this.dayId = dayId; - this.date = date; - this.number = number; - this.subject = subject; - this.presence = presence; - this.absenceUnexcused = absenceUnexcused; - this.absenceExcused = absenceExcused; - this.unexcusedLateness = unexcusedLateness; - this.absenceForSchoolReasons = absenceForSchoolReasons; - this.excusedLateness = excusedLateness; - this.exemption = exemption; - } - - @Generated(hash = 921806575) - public AttendanceLesson() { - } - - public Long getId() { - return this.id; - } - - public void setId(Long id) { - this.id = id; - } - - public Long getDayId() { - return this.dayId; - } - - public void setDayId(Long dayId) { - this.dayId = dayId; - } - - public String getDate() { - return this.date; - } - - public AttendanceLesson setDate(String date) { - this.date = date; - return this; - } - - public int getNumber() { - return this.number; - } - - public AttendanceLesson setNumber(int number) { - this.number = number; - return this; - } - - public String getSubject() { - return this.subject; - } - - public AttendanceLesson setSubject(String subject) { - this.subject = subject; - return this; - } - - public boolean getPresence() { - return this.presence; - } - - public AttendanceLesson setPresence(boolean presence) { - this.presence = presence; - return this; - } - - public boolean getAbsenceUnexcused() { - return this.absenceUnexcused; - } - - public AttendanceLesson setAbsenceUnexcused(boolean absenceUnexcused) { - this.absenceUnexcused = absenceUnexcused; - return this; - } - - public boolean getAbsenceExcused() { - return this.absenceExcused; - } - - public AttendanceLesson setAbsenceExcused(boolean absenceExcused) { - this.absenceExcused = absenceExcused; - return this; - } - - public boolean getUnexcusedLateness() { - return this.unexcusedLateness; - } - - public AttendanceLesson setUnexcusedLateness(boolean unexcusedLateness) { - this.unexcusedLateness = unexcusedLateness; - return this; - } - - public boolean getAbsenceForSchoolReasons() { - return this.absenceForSchoolReasons; - } - - public AttendanceLesson setAbsenceForSchoolReasons(boolean absenceForSchoolReasons) { - this.absenceForSchoolReasons = absenceForSchoolReasons; - return this; - } - - public boolean getExcusedLateness() { - return this.excusedLateness; - } - - public AttendanceLesson setExcusedLateness(boolean excusedLateness) { - this.excusedLateness = excusedLateness; - return this; - } - - public boolean getExemption() { - return this.exemption; - } - - public AttendanceLesson setExemption(boolean exemption) { - this.exemption = exemption; - return this; - } - - public String getDescription() { - return description; - } - - public AttendanceLesson setDescription(String description) { - this.description = description; - return this; - } - - /** - * 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 = 1157101112) - public void __setDaoSession(DaoSession daoSession) { - this.daoSession = daoSession; - myDao = daoSession != null ? daoSession.getAttendanceLessonDao() : null; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Day.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Day.java deleted file mode 100644 index c5472e98..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Day.java +++ /dev/null @@ -1,263 +0,0 @@ -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.Index; -import org.greenrobot.greendao.annotation.OrderBy; -import org.greenrobot.greendao.annotation.Property; -import org.greenrobot.greendao.annotation.ToMany; - -import java.util.List; - -@Entity( - nameInDb = "Days", - active = true, - indexes = {@Index(value = "weekId,date", unique = true)} -) -public class Day { - - @Id(autoincrement = true) - private Long id; - - @Property(nameInDb = "week_id") - private Long weekId; - - @Property(nameInDb = "date") - private String date = ""; - - @Property(nameInDb = "day_name") - private String dayName = ""; - - @Property(nameInDb = "free_day") - private boolean freeDay = false; - - @Property(nameInDb = "free_day_name") - private String freeDayName = ""; - - @OrderBy("number ASC") - @ToMany(referencedJoinProperty = "dayId") - private List timetableLessons; - - @OrderBy("number ASC") - @ToMany(referencedJoinProperty = "dayId") - private List attendanceLessons; - - @ToMany(referencedJoinProperty = "dayId") - private List exams; - - /** - * Used to resolve relations - */ - @Generated(hash = 2040040024) - private transient DaoSession daoSession; - - /** Used for active entity operations. */ - @Generated(hash = 312167767) - private transient DayDao myDao; - - @Generated(hash = 523139020) - public Day(Long id, Long weekId, String date, String dayName, boolean freeDay, - String freeDayName) { - this.id = id; - this.weekId = weekId; - this.date = date; - this.dayName = dayName; - this.freeDay = freeDay; - this.freeDayName = freeDayName; - } - - @Generated(hash = 866989762) - public Day() { - } - - public Long getId() { - return this.id; - } - - public void setId(Long id) { - this.id = id; - } - - public Long getWeekId() { - return this.weekId; - } - - public void setWeekId(Long weekId) { - this.weekId = weekId; - } - - public String getDate() { - return this.date; - } - - public Day setDate(String date) { - this.date = date; - return this; - } - - public String getDayName() { - return this.dayName; - } - - public Day setDayName(String dayName) { - this.dayName = dayName; - return this; - } - - public boolean getFreeDay() { - return this.freeDay; - } - - public Day setFreeDay(boolean freeDay) { - this.freeDay = freeDay; - return this; - } - - public String getFreeDayName() { - return this.freeDayName; - } - - public Day setFreeDayName(String freeDayName) { - this.freeDayName = freeDayName; - 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 = 218588195) - public List getTimetableLessons() { - if (timetableLessons == null) { - final DaoSession daoSession = this.daoSession; - if (daoSession == null) { - throw new DaoException("Entity is detached from DAO context"); - } - TimetableLessonDao targetDao = daoSession.getTimetableLessonDao(); - List timetableLessonsNew = targetDao - ._queryDay_TimetableLessons(id); - synchronized (this) { - if (timetableLessons == null) { - timetableLessons = timetableLessonsNew; - } - } - } - return timetableLessons; - } - - /** - * Resets a to-many relationship, making the next get call to query for a fresh result. - */ - @Generated(hash = 1687683740) - public synchronized void resetTimetableLessons() { - timetableLessons = null; - } - - /** - * 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 = 1166820581) - public List getAttendanceLessons() { - if (attendanceLessons == null) { - final DaoSession daoSession = this.daoSession; - if (daoSession == null) { - throw new DaoException("Entity is detached from DAO context"); - } - AttendanceLessonDao targetDao = daoSession.getAttendanceLessonDao(); - List attendanceLessonsNew = targetDao - ._queryDay_AttendanceLessons(id); - synchronized (this) { - if (attendanceLessons == null) { - attendanceLessons = attendanceLessonsNew; - } - } - } - return attendanceLessons; - } - - /** - * Resets a to-many relationship, making the next get call to query for a fresh result. - */ - @Generated(hash = 1343075564) - public synchronized void resetAttendanceLessons() { - attendanceLessons = null; - } - - /** - * 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 = 1231531946) - public List getExams() { - if (exams == null) { - final DaoSession daoSession = this.daoSession; - if (daoSession == null) { - throw new DaoException("Entity is detached from DAO context"); - } - ExamDao targetDao = daoSession.getExamDao(); - List examsNew = targetDao._queryDay_Exams(id); - synchronized (this) { - if (exams == null) { - exams = examsNew; - } - } - } - return exams; - } - - /** - * Resets a to-many relationship, making the next get call to query for a fresh result. - */ - @Generated(hash = 841969952) - public synchronized void resetExams() { - exams = 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 = 1409317752) - public void __setDaoSession(DaoSession daoSession) { - this.daoSession = daoSession; - myDao = daoSession != null ? daoSession.getDayDao() : null; - } - - -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Diary.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Diary.java deleted file mode 100644 index b0b145da..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Diary.java +++ /dev/null @@ -1,177 +0,0 @@ -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 = "Diaries", - active = true -) -public class Diary { - - @Id(autoincrement = true) - private Long id; - - @Property(nameInDb = "student_id") - private Long studentId; - - @Property(nameInDb = "current") - private boolean current; - - @Property(nameInDb = "name") - private String name; - - @Property(nameInDb = "value") - private String value; - - @ToMany(referencedJoinProperty = "diaryId") - private List semesterList; - - /** - * Used to resolve relations - */ - @Generated(hash = 2040040024) - private transient DaoSession daoSession; - - /** - * Used for active entity operations. - */ - @Generated(hash = 21166549) - private transient DiaryDao myDao; - - @Generated(hash = 277096196) - public Diary(Long id, Long studentId, boolean current, String name, String value) { - this.id = id; - this.studentId = studentId; - this.current = current; - this.name = name; - this.value = value; - } - - @Generated(hash = 112123061) - public Diary() { - } - - public Long getId() { - return this.id; - } - - public void setId(Long id) { - this.id = id; - } - - public Long getStudentId() { - return this.studentId; - } - - public Diary setStudentId(Long studentId) { - this.studentId = studentId; - return this; - } - - public String getName() { - return this.name; - } - - public Diary setName(String name) { - this.name = name; - return this; - } - - public String getValue() { - return this.value; - } - - public Diary setValue(String value) { - this.value = value; - return this; - } - - public boolean getCurrent() { - return this.current; - } - - public Diary setCurrent(boolean current) { - this.current = current; - 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 = 1738383053) - public List getSemesterList() { - if (semesterList == null) { - final DaoSession daoSession = this.daoSession; - if (daoSession == null) { - throw new DaoException("Entity is detached from DAO context"); - } - SemesterDao targetDao = daoSession.getSemesterDao(); - List semesterListNew = targetDao._queryDiary_SemesterList(id); - synchronized (this) { - if (semesterList == null) { - semesterList = semesterListNew; - } - } - } - return semesterList; - } - - /** - * Resets a to-many relationship, making the next get call to query for a fresh result. - */ - @Generated(hash = 995060657) - public synchronized void resetSemesterList() { - semesterList = 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 = 629297785) - public void __setDaoSession(DaoSession daoSession) { - this.daoSession = daoSession; - myDao = daoSession != null ? daoSession.getDiaryDao() : null; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Exam.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Exam.java deleted file mode 100644 index 543b6859..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Exam.java +++ /dev/null @@ -1,177 +0,0 @@ -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.Index; -import org.greenrobot.greendao.annotation.Property; - -import java.io.Serializable; - -@Entity( - nameInDb = "Exams", - active = true, - indexes = {@Index(value = "dayId,entryDate,subjectAndGroup,type,teacher", unique = true)} -) - -public class Exam implements Serializable { - - @Id(autoincrement = true) - private Long id; - - @Property(nameInDb = "day_id") - private Long dayId; - - @Property(nameInDb = "subject_and_group") - private String subjectAndGroup = ""; - - @Property(nameInDb = "type") - private String type = ""; - - @Property(nameInDb = "description") - private String description = ""; - - @Property(nameInDb = "teacher") - private String teacher = ""; - - @Property(nameInDb = "entry_date") - private String entryDate = ""; - - private static final long serialVersionUID = 42L; - - /** - * Used to resolve relations - */ - @Generated(hash = 2040040024) - private transient DaoSession daoSession; - - /** - * Used for active entity operations. - */ - @Generated(hash = 973692038) - private transient ExamDao myDao; - - @Generated(hash = 998653360) - public Exam(Long id, Long dayId, String subjectAndGroup, String type, String description, - String teacher, String entryDate) { - this.id = id; - this.dayId = dayId; - this.subjectAndGroup = subjectAndGroup; - this.type = type; - this.description = description; - this.teacher = teacher; - this.entryDate = entryDate; - } - - @Generated(hash = 945526930) - public Exam() { - } - - public Long getId() { - return id; - } - - public Exam setId(Long id) { - this.id = id; - return this; - } - - public Long getDayId() { - return this.dayId; - } - - public Exam setDayId(Long dayId) { - this.dayId = dayId; - return this; - } - - public String getSubjectAndGroup() { - return subjectAndGroup; - } - - public Exam setSubjectAndGroup(String subjectAndGroup) { - this.subjectAndGroup = subjectAndGroup; - return this; - } - - public String getType() { - return type; - } - - public Exam setType(String type) { - this.type = type; - return this; - } - - public String getDescription() { - return description; - } - - public Exam setDescription(String description) { - this.description = description; - return this; - } - - public String getTeacher() { - return teacher; - } - - public Exam setTeacher(String teacher) { - this.teacher = teacher; - return this; - } - - public String getEntryDate() { - return entryDate; - } - - public Exam setEntryDate(String entryDate) { - this.entryDate = entryDate; - return this; - } - - /** - * 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 = 1730563422) - public void __setDaoSession(DaoSession daoSession) { - this.daoSession = daoSession; - myDao = daoSession != null ? daoSession.getExamDao() : null; - } - -} \ No newline at end of file diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Grade.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Grade.java deleted file mode 100644 index 537b9e75..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Grade.java +++ /dev/null @@ -1,293 +0,0 @@ -package io.github.wulkanowy.data.db.dao.entities; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; -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 java.io.Serializable; - -@Entity( - nameInDb = "Grades", - active = true -) -public class Grade implements Serializable { - - @Id(autoincrement = true) - protected Long id; - - @Property(nameInDb = "semester_id") - private Long semesterId; - - @Property(nameInDb = "subject_id") - private Long subjectId; - - @Property(nameInDb = "subject") - private String subject = ""; - - @Property(nameInDb = "value") - protected String value = ""; - - @Property(nameInDb = "weight") - private String weight = ""; - - @Property(nameInDb = "date") - private String date = ""; - - @Property(nameInDb = "symbol") - private String symbol = ""; - - @Property(nameInDb = "color") - private String color = ""; - - @Property(nameInDb = "description") - private String description = ""; - - @Property(nameInDb = "teacher") - private String teacher = ""; - - @Property(nameInDb = "is_new") - private boolean isNew = false; - - @Property(nameInDb = "read") - private boolean read = true; - - private static final long serialVersionUID = 42L; - - /** - * Used to resolve relations - */ - @Generated(hash = 2040040024) - private transient DaoSession daoSession; - - /** - * Used for active entity operations. - */ - @Generated(hash = 681281562) - private transient GradeDao myDao; - - @Generated(hash = 2042976393) - public Grade() { - } - - @Generated(hash = 619853992) - public Grade(Long id, Long semesterId, Long subjectId, String subject, String value, - String weight, String date, String symbol, String color, String description, - String teacher, boolean isNew, boolean read) { - this.id = id; - this.semesterId = semesterId; - this.subjectId = subjectId; - this.subject = subject; - this.value = value; - this.weight = weight; - this.date = date; - this.symbol = symbol; - this.color = color; - this.description = description; - this.teacher = teacher; - this.isNew = isNew; - this.read = read; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - - if (o == null || getClass() != o.getClass()) return false; - - Grade grade = (Grade) o; - - return new EqualsBuilder() - .append(semesterId, grade.semesterId) - .append(subject, grade.subject) - .append(value, grade.value) - .append(color, grade.color) - .append(symbol, grade.symbol) - .append(description, grade.description) - .append(weight, grade.weight) - .append(date, grade.date) - .append(teacher, grade.teacher) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) - .append(semesterId) - .append(subject) - .append(value) - .append(color) - .append(symbol) - .append(description) - .append(weight) - .append(date) - .append(teacher) - .toHashCode(); - } - - public Long getId() { - return this.id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getValue() { - return this.value; - } - - public Grade setValue(String value) { - this.value = value; - return this; - } - - public Long getSemesterId() { - return this.semesterId; - } - - public Grade setSemesterId(Long semesterId) { - this.semesterId = semesterId; - return this; - } - - public String getSubject() { - return this.subject; - } - - public Grade setSubject(String subject) { - this.subject = subject; - return this; - } - - public String getColor() { - return this.color; - } - - public Grade setColor(String color) { - this.color = color; - return this; - } - - public String getSymbol() { - return this.symbol; - } - - public Grade setSymbol(String symbol) { - this.symbol = symbol; - return this; - } - - public String getDescription() { - return this.description; - } - - public Grade setDescription(String description) { - this.description = description; - return this; - } - - public String getWeight() { - return this.weight; - } - - public Grade setWeight(String weight) { - this.weight = weight; - return this; - } - - public String getDate() { - return this.date; - } - - public Grade setDate(String date) { - this.date = date; - return this; - } - - public String getTeacher() { - return this.teacher; - } - - public Grade setTeacher(String teacher) { - this.teacher = teacher; - return this; - } - - public boolean getIsNew() { - return this.isNew; - } - - public void setIsNew(boolean isNew) { - this.isNew = isNew; - } - - public boolean getRead() { - return this.read; - } - - public Grade setRead(boolean read) { - this.read = read; - return this; - } - - - public Long getSubjectId() { - return this.subjectId; - } - - - public void setSubjectId(Long subjectId) { - this.subjectId = subjectId; - } - - - /** - * 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 = 1187286414) - public void __setDaoSession(DaoSession daoSession) { - this.daoSession = daoSession; - myDao = daoSession != null ? daoSession.getGradeDao() : null; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/School.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/School.java deleted file mode 100644 index 59860e9e..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/School.java +++ /dev/null @@ -1,179 +0,0 @@ -package io.github.wulkanowy.data.db.dao.entities; - -import org.greenrobot.greendao.DaoException; -import org.greenrobot.greendao.annotation.Entity; -import org.greenrobot.greendao.annotation.Generated; -import org.greenrobot.greendao.annotation.Id; -import org.greenrobot.greendao.annotation.Property; -import org.greenrobot.greendao.annotation.ToMany; - -import java.util.List; - -@Entity( - nameInDb = "Schools", - active = true -) -public class School { - - @Id(autoincrement = true) - private Long id; - - @Property(nameInDb = "symbol_id") - private Long symbolId; - - @Property(nameInDb = "current") - private boolean current; - - @Property(nameInDb = "real_id") - private String realId; - - @Property(nameInDb = "name") - private String name; - - @ToMany(referencedJoinProperty = "schoolId") - private List studentList; - - /** - * Used to resolve relations - */ - @Generated(hash = 2040040024) - private transient DaoSession daoSession; - - /** - * Used for active entity operations. - */ - @Generated(hash = 1796006707) - private transient SchoolDao myDao; - - @Generated(hash = 975562398) - public School(Long id, Long symbolId, boolean current, String realId, - String name) { - this.id = id; - this.symbolId = symbolId; - this.current = current; - this.realId = realId; - this.name = name; - } - - @Generated(hash = 1579966795) - public School() { - } - - public Long getId() { - return this.id; - } - - public School setId(Long id) { - this.id = id; - return this; - } - - public Long getSymbolId() { - return this.symbolId; - } - - public School setSymbolId(Long symbolId) { - this.symbolId = symbolId; - return this; - } - - public boolean getCurrent() { - return this.current; - } - - public School setCurrent(boolean current) { - this.current = current; - return this; - } - - public String getRealId() { - return this.realId; - } - - public School setRealId(String realId) { - this.realId = realId; - return this; - } - - public String getName() { - return this.name; - } - - public School setName(String name) { - this.name = name; - return this; - } - - /** - * To-many relationship, resolved on first access (and after reset). - * Changes to to-many relations are not persisted, make changes to the target entity. - */ - @Generated(hash = 180118651) - public List getStudentList() { - if (studentList == null) { - final DaoSession daoSession = this.daoSession; - if (daoSession == null) { - throw new DaoException("Entity is detached from DAO context"); - } - StudentDao targetDao = daoSession.getStudentDao(); - List studentListNew = targetDao._querySchool_StudentList(id); - synchronized (this) { - if (studentList == null) { - studentList = studentListNew; - } - } - } - return studentList; - } - - /** - * Resets a to-many relationship, making the next get call to query for a fresh result. - */ - @Generated(hash = 1628625923) - public synchronized void resetStudentList() { - studentList = null; - } - - /** - * Convenient call for {@link org.greenrobot.greendao.AbstractDao#delete(Object)}. - * Entity must attached to an entity context. - */ - @Generated(hash = 128553479) - public void delete() { - if (myDao == null) { - throw new DaoException("Entity is detached from DAO context"); - } - myDao.delete(this); - } - - /** - * Convenient call for {@link org.greenrobot.greendao.AbstractDao#refresh(Object)}. - * Entity must attached to an entity context. - */ - @Generated(hash = 1942392019) - public void refresh() { - if (myDao == null) { - throw new DaoException("Entity is detached from DAO context"); - } - myDao.refresh(this); - } - - /** - * Convenient call for {@link org.greenrobot.greendao.AbstractDao#update(Object)}. - * Entity must attached to an entity context. - */ - @Generated(hash = 713229351) - public void update() { - if (myDao == null) { - throw new DaoException("Entity is detached from DAO context"); - } - myDao.update(this); - } - - /** called by internal mechanisms, do not call yourself. */ - @Generated(hash = 234091322) - public void __setDaoSession(DaoSession daoSession) { - this.daoSession = daoSession; - myDao = daoSession != null ? daoSession.getSchoolDao() : null; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Semester.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Semester.java deleted file mode 100644 index c739688f..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Semester.java +++ /dev/null @@ -1,208 +0,0 @@ -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 = "Semesters", - active = true -) -public class Semester { - - @Id(autoincrement = true) - private Long id; - - @Property(nameInDb = "diary_id") - private Long diaryId; - - @Property(nameInDb = "current") - private boolean current; - - @Property(nameInDb = "name") - private String name; - - @Property(nameInDb = "value") - private String value; - - @ToMany(referencedJoinProperty = "semesterId") - private List subjectList; - - @ToMany(referencedJoinProperty = "semesterId") - private List gradeList; - - /** - * Used to resolve relations - */ - @Generated(hash = 2040040024) - private transient DaoSession daoSession; - - /** - * Used for active entity operations. - */ - @Generated(hash = 282930393) - private transient SemesterDao myDao; - - @Generated(hash = 1661077309) - public Semester(Long id, Long diaryId, boolean current, String name, String value) { - this.id = id; - this.diaryId = diaryId; - this.current = current; - this.name = name; - this.value = value; - } - - @Generated(hash = 58335877) - public Semester() { - } - - public Long getId() { - return this.id; - } - - public void setId(Long id) { - this.id = id; - } - - public Long getDiaryId() { - return this.diaryId; - } - - public Semester setDiaryId(Long diaryId) { - this.diaryId = diaryId; - return this; - } - - public String getName() { - return this.name; - } - - public Semester setName(String name) { - this.name = name; - return this; - } - - public String getValue() { - return this.value; - } - - public Semester setValue(String value) { - this.value = value; - return this; - } - - public boolean getCurrent() { - return this.current; - } - - public Semester setCurrent(boolean current) { - this.current = current; - 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 = 723353662) - public List getSubjectList() { - if (subjectList == null) { - final DaoSession daoSession = this.daoSession; - if (daoSession == null) { - throw new DaoException("Entity is detached from DAO context"); - } - SubjectDao targetDao = daoSession.getSubjectDao(); - List subjectListNew = targetDao._querySemester_SubjectList(id); - synchronized (this) { - if (subjectList == null) { - subjectList = subjectListNew; - } - } - } - return subjectList; - } - - /** - * Resets a to-many relationship, making the next get call to query for a fresh result. - */ - @Generated(hash = 594294258) - public synchronized void resetSubjectList() { - subjectList = 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); - } - - /** - * 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 = 390330007) - public List getGradeList() { - if (gradeList == null) { - final DaoSession daoSession = this.daoSession; - if (daoSession == null) { - throw new DaoException("Entity is detached from DAO context"); - } - GradeDao targetDao = daoSession.getGradeDao(); - List gradeListNew = targetDao._querySemester_GradeList(id); - synchronized (this) { - if (gradeList == null) { - gradeList = gradeListNew; - } - } - } - return gradeList; - } - - /** Resets a to-many relationship, making the next get call to query for a fresh result. */ - @Generated(hash = 1939990047) - public synchronized void resetGradeList() { - gradeList = null; - } - - /** called by internal mechanisms, do not call yourself. */ - @Generated(hash = 676204164) - public void __setDaoSession(DaoSession daoSession) { - this.daoSession = daoSession; - myDao = daoSession != null ? daoSession.getSemesterDao() : null; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Student.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Student.java deleted file mode 100644 index 1d545473..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Student.java +++ /dev/null @@ -1,178 +0,0 @@ -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 = "Students", - active = true -) -public class Student { - - @Id(autoincrement = true) - private Long id; - - @Property(nameInDb = "school_id") - private Long schoolId; - - @Property(nameInDb = "current") - private boolean current; - - @Property(nameInDb = "real_id") - private String realId; - - @Property(nameInDb = "name") - private String name; - - @ToMany(referencedJoinProperty = "studentId") - private List diaryList; - - /** - * Used to resolve relations - */ - @Generated(hash = 2040040024) - private transient DaoSession daoSession; - - /** - * Used for active entity operations. - */ - @Generated(hash = 1943931642) - private transient StudentDao myDao; - - @Generated(hash = 470181623) - public Student(Long id, Long schoolId, boolean current, String realId, String name) { - this.id = id; - this.schoolId = schoolId; - this.current = current; - this.realId = realId; - this.name = name; - } - - @Generated(hash = 1556870573) - public Student() { - } - - public Long getId() { - return this.id; - } - - public void setId(Long id) { - this.id = id; - } - - public Long getSchoolId() { - return this.schoolId; - } - - public Student setSchoolId(Long schoolId) { - this.schoolId = schoolId; - return this; - } - - public String getRealId() { - return this.realId; - } - - public Student setRealId(String realId) { - this.realId = realId; - return this; - } - - public String getName() { - return this.name; - } - - public Student setName(String name) { - this.name = name; - return this; - } - - public boolean getCurrent() { - return this.current; - } - - public Student setCurrent(boolean current) { - this.current = current; - 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 = 508305571) - public List getDiaryList() { - if (diaryList == null) { - final DaoSession daoSession = this.daoSession; - if (daoSession == null) { - throw new DaoException("Entity is detached from DAO context"); - } - DiaryDao targetDao = daoSession.getDiaryDao(); - List diaryListNew = targetDao._queryStudent_DiaryList(id); - synchronized (this) { - if (diaryList == null) { - diaryList = diaryListNew; - } - } - } - return diaryList; - } - - /** - * Resets a to-many relationship, making the next get call to query for a fresh result. - */ - @Generated(hash = 1078514341) - public synchronized void resetDiaryList() { - diaryList = 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 = 1701634981) - public void __setDaoSession(DaoSession daoSession) { - this.daoSession = daoSession; - myDao = daoSession != null ? daoSession.getStudentDao() : null; - } - -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Subject.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Subject.java deleted file mode 100644 index 285cd7c0..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Subject.java +++ /dev/null @@ -1,176 +0,0 @@ -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 = "Subjects", - active = true -) -public class Subject { - - @Id(autoincrement = true) - private Long id; - - @Property(nameInDb = "semester_id") - private Long semesterId; - - @Property(nameInDb = "name") - private String name; - - @Property(nameInDb = "predicted_rating") - private String predictedRating; - - @Property(nameInDb = "final_rating") - private String finalRating; - - @ToMany(referencedJoinProperty = "subjectId") - private List gradeList; - - /** - * Used to resolve relations - */ - @Generated(hash = 2040040024) - private transient DaoSession daoSession; - - /** - * Used for active entity operations. - */ - @Generated(hash = 1644932788) - private transient SubjectDao myDao; - - @Generated(hash = 1817932538) - public Subject(Long id, Long semesterId, String name, String predictedRating, - String finalRating) { - this.id = id; - this.semesterId = semesterId; - this.name = name; - this.predictedRating = predictedRating; - this.finalRating = finalRating; - } - - @Generated(hash = 1617906264) - public Subject() { - } - - public Long getId() { - return this.id; - } - - public void setId(Long id) { - this.id = id; - } - - public Long getSemesterId() { - return this.semesterId; - } - - public Subject setSemesterId(Long semesterId) { - this.semesterId = semesterId; - return this; - } - - public String getName() { - return this.name; - } - - public Subject setName(String name) { - this.name = name; - return this; - } - - public String getPredictedRating() { - return this.predictedRating; - } - - public Subject setPredictedRating(String predictedRating) { - this.predictedRating = predictedRating; - return this; - } - - public String getFinalRating() { - return this.finalRating; - } - - public Subject setFinalRating(String finalRating) { - this.finalRating = finalRating; - return this; - } - - /** - * 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); - } - - /** - * 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 = 1358847893) - public List getGradeList() { - if (gradeList == null) { - final DaoSession daoSession = this.daoSession; - if (daoSession == null) { - throw new DaoException("Entity is detached from DAO context"); - } - GradeDao targetDao = daoSession.getGradeDao(); - List gradeListNew = targetDao._querySubject_GradeList(id); - synchronized (this) { - if (gradeList == null) { - gradeList = gradeListNew; - } - } - } - return gradeList; - } - - /** Resets a to-many relationship, making the next get call to query for a fresh result. */ - @Generated(hash = 1939990047) - public synchronized void resetGradeList() { - gradeList = null; - } - - /** called by internal mechanisms, do not call yourself. */ - @Generated(hash = 937984622) - public void __setDaoSession(DaoSession daoSession) { - this.daoSession = daoSession; - myDao = daoSession != null ? daoSession.getSubjectDao() : null; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Symbol.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Symbol.java deleted file mode 100644 index 7cc46111..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Symbol.java +++ /dev/null @@ -1,175 +0,0 @@ -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 = "Symbols", - active = true -) -public class Symbol { - - @Id(autoincrement = true) - private Long id; - - @Property(nameInDb = "user_id") - private Long userId; - - @Property(nameInDb = "host") - private String host; - - @Property(nameInDb = "symbol") - private String symbol; - - @Property(nameInDb = "type") - private String type; - - @ToMany(referencedJoinProperty = "symbolId") - private List schoolList; - - /** - * Used to resolve relations - */ - @Generated(hash = 2040040024) - private transient DaoSession daoSession; - - /** - * Used for active entity operations. - */ - @Generated(hash = 684907977) - private transient SymbolDao myDao; - - @Generated(hash = 1034469460) - public Symbol(Long id, Long userId, String host, String symbol, String type) { - this.id = id; - this.userId = userId; - this.host = host; - this.symbol = symbol; - this.type = type; - } - - @Generated(hash = 460475327) - public Symbol() { - } - - public Long getId() { - return this.id; - } - - public void setId(Long id) { - this.id = id; - } - - public Long getUserId() { - return this.userId; - } - - public Symbol setUserId(Long userId) { - this.userId = userId; - return this; - } - - public String getHost() { - return this.host; - } - - public Symbol setHost(String host) { - this.host = host; - return this; - } - - public String getSymbol() { - return this.symbol; - } - - public Symbol setSymbol(String symbol) { - this.symbol = symbol; - return this; - } - - public String getType() { - return this.type; - } - - public Symbol setType(String type) { - this.type = type; - 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 = 1733082867) - public List getSchoolList() { - if (schoolList == null) { - final DaoSession daoSession = this.daoSession; - if (daoSession == null) { - throw new DaoException("Entity is detached from DAO context"); - } - SchoolDao targetDao = daoSession.getSchoolDao(); - List schoolListNew = targetDao._querySymbol_SchoolList(id); - synchronized (this) { - if (schoolList == null) { - schoolList = schoolListNew; - } - } - } - return schoolList; - } - - /** Resets a to-many relationship, making the next get call to query for a fresh result. */ - @Generated(hash = 1757777300) - public synchronized void resetSchoolList() { - schoolList = null; - } - - /** - * 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 = 632145708) - public void __setDaoSession(DaoSession daoSession) { - this.daoSession = daoSession; - myDao = daoSession != null ? daoSession.getSymbolDao() : null; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/TimetableLesson.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/TimetableLesson.java deleted file mode 100644 index f3fdf6a8..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/TimetableLesson.java +++ /dev/null @@ -1,332 +0,0 @@ -package io.github.wulkanowy.data.db.dao.entities; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; -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.Index; -import org.greenrobot.greendao.annotation.Property; - -import java.io.Serializable; - -@Entity( - nameInDb = "TimetableLessons", - active = true, - indexes = {@Index(value = "dayId,date,number,startTime,endTime", unique = true)} -) -public class TimetableLesson implements Serializable { - - private static final long serialVersionUID = 42L; - - @Id(autoincrement = true) - private Long id; - - @Property(nameInDb = "day_id") - private Long dayId; - - @Property(nameInDb = "number") - private int number = 0; - - @Property(nameInDb = "subject") - private String subject = ""; - - @Property(nameInDb = "teacher") - private String teacher = ""; - - @Property(nameInDb = "room") - private String room = ""; - - @Property(nameInDb = "description") - private String description = ""; - - @Property(nameInDb = "group") - private String group = ""; - - @Property(nameInDb = "start_time") - private String startTime = ""; - - @Property(nameInDb = "end_time") - private String endTime = ""; - - @Property(nameInDb = "date") - private String date = ""; - - @Property(nameInDb = "empty") - private boolean empty = false; - - @Property(nameInDb = "division_into_groups") - private boolean divisionIntoGroups = false; - - @Property(nameInDb = "planning") - private boolean planning = false; - - @Property(nameInDb = "realized") - private boolean realized = false; - - @Property(nameInDb = "moved_canceled") - private boolean movedOrCanceled = false; - - @Property(nameInDb = "new_moved_in_canceled") - private boolean newMovedInOrChanged = false; - - /** - * Used to resolve relations - */ - @Generated(hash = 2040040024) - private transient DaoSession daoSession; - - /** Used for active entity operations. */ - @Generated(hash = 1119360138) - private transient TimetableLessonDao myDao; - - @Generated(hash = 1665905034) - public TimetableLesson(Long id, Long dayId, int number, String subject, String teacher, - String room, String description, String group, String startTime, String endTime, - String date, boolean empty, boolean divisionIntoGroups, boolean planning, - boolean realized, boolean movedOrCanceled, boolean newMovedInOrChanged) { - this.id = id; - this.dayId = dayId; - this.number = number; - this.subject = subject; - this.teacher = teacher; - this.room = room; - this.description = description; - this.group = group; - this.startTime = startTime; - this.endTime = endTime; - this.date = date; - this.empty = empty; - this.divisionIntoGroups = divisionIntoGroups; - this.planning = planning; - this.realized = realized; - this.movedOrCanceled = movedOrCanceled; - this.newMovedInOrChanged = newMovedInOrChanged; - } - - @Generated(hash = 1878030142) - public TimetableLesson() { - } - - public Long getId() { - return this.id; - } - - public void setId(Long id) { - this.id = id; - } - - public Long getDayId() { - return this.dayId; - } - - public TimetableLesson setDayId(Long dayId) { - this.dayId = dayId; - return this; - } - - public int getNumber() { - return this.number; - } - - public TimetableLesson setNumber(int number) { - this.number = number; - return this; - } - - public String getSubject() { - return this.subject; - } - - public TimetableLesson setSubject(String subject) { - this.subject = subject; - return this; - } - - public String getTeacher() { - return this.teacher; - } - - public TimetableLesson setTeacher(String teacher) { - this.teacher = teacher; - return this; - } - - public String getRoom() { - return this.room; - } - - public TimetableLesson setRoom(String room) { - this.room = room; - return this; - } - - public String getDescription() { - return this.description; - } - - public TimetableLesson setDescription(String description) { - this.description = description; - return this; - } - - public String getGroup() { - return this.group; - } - - public TimetableLesson setGroup(String group) { - this.group = group; - return this; - } - - public String getStartTime() { - return this.startTime; - } - - public TimetableLesson setStartTime(String startTime) { - this.startTime = startTime; - return this; - } - - public String getEndTime() { - return this.endTime; - } - - public TimetableLesson setEndTime(String endTime) { - this.endTime = endTime; - return this; - } - - public String getDate() { - return this.date; - } - - public TimetableLesson setDate(String date) { - this.date = date; - return this; - } - - public boolean getEmpty() { - return this.empty; - } - - public TimetableLesson setEmpty(boolean empty) { - this.empty = empty; - return this; - } - - public boolean getDivisionIntoGroups() { - return this.divisionIntoGroups; - } - - public TimetableLesson setDivisionIntoGroups(boolean divisionIntoGroups) { - this.divisionIntoGroups = divisionIntoGroups; - return this; - } - - public boolean getPlanning() { - return this.planning; - } - - public TimetableLesson setPlanning(boolean planning) { - this.planning = planning; - return this; - } - - public boolean getRealized() { - return this.realized; - } - - public TimetableLesson setRealized(boolean realized) { - this.realized = realized; - return this; - } - - public boolean getMovedOrCanceled() { - return this.movedOrCanceled; - } - - public TimetableLesson setMovedOrCanceled(boolean movedOrCanceled) { - this.movedOrCanceled = movedOrCanceled; - return this; - } - - public boolean getNewMovedInOrChanged() { - return this.newMovedInOrChanged; - } - - public TimetableLesson setNewMovedInOrChanged(boolean newMovedInOrChanged) { - this.newMovedInOrChanged = newMovedInOrChanged; - return this; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - - if (o == null || getClass() != o.getClass()) return false; - - TimetableLesson lesson = (TimetableLesson) o; - - return new EqualsBuilder() - .append(number, lesson.number) - .append(startTime, lesson.startTime) - .append(endTime, lesson.endTime) - .append(date, lesson.date) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) - .append(number) - .append(startTime) - .append(endTime) - .append(date) - .toHashCode(); - } - - /** - * 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 = 1885258429) - public void __setDaoSession(DaoSession daoSession) { - this.daoSession = daoSession; - myDao = daoSession != null ? daoSession.getTimetableLessonDao() : null; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Week.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Week.java deleted file mode 100644 index 1edfa245..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Week.java +++ /dev/null @@ -1,194 +0,0 @@ -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.Index; -import org.greenrobot.greendao.annotation.Property; -import org.greenrobot.greendao.annotation.ToMany; - -import java.util.List; - -@Entity( - nameInDb = "Weeks", - active = true, - indexes = {@Index(value = "diaryId,startDayDate", unique = true)} -) -public class Week { - - @Id(autoincrement = true) - private Long id; - - @Property(nameInDb = "diary_id") - private Long diaryId; - - @Property(nameInDb = "start_day_date") - private String startDayDate = ""; - - @Property(nameInDb = "attendance_synced") - private boolean attendanceSynced = false; - - @Property(nameInDb = "timetable_synced") - private boolean timetableSynced = false; - - @Property(nameInDb = "exams_synced") - private boolean examsSynced = false; - - @ToMany(referencedJoinProperty = "weekId") - private List dayList; - - /** - * Used to resolve relations - */ - @Generated(hash = 2040040024) - private transient DaoSession daoSession; - - /** - * Used for active entity operations. - */ - @Generated(hash = 1019310398) - private transient WeekDao myDao; - - @Generated(hash = 23357599) - public Week(Long id, Long diaryId, String startDayDate, boolean attendanceSynced, - boolean timetableSynced, boolean examsSynced) { - this.id = id; - this.diaryId = diaryId; - this.startDayDate = startDayDate; - this.attendanceSynced = attendanceSynced; - this.timetableSynced = timetableSynced; - this.examsSynced = examsSynced; - } - - @Generated(hash = 2135529658) - public Week() { - } - - public Long getId() { - return id; - } - - public Week setId(Long id) { - this.id = id; - return this; - } - - public Long getDiaryId() { - return diaryId; - } - - public Week setDiaryId(Long diaryId) { - this.diaryId = diaryId; - return this; - } - - public String getStartDayDate() { - return startDayDate; - } - - public Week setStartDayDate(String startDayDate) { - this.startDayDate = startDayDate; - return this; - } - - public boolean getAttendanceSynced() { - return this.attendanceSynced; - } - - public Week setAttendanceSynced(boolean attendanceSynced) { - this.attendanceSynced = attendanceSynced; - return this; - } - - public boolean getTimetableSynced() { - return this.timetableSynced; - } - - public Week setTimetableSynced(boolean timetableSynced) { - this.timetableSynced = timetableSynced; - return this; - } - - public Week setExamsSynced(boolean examsSynced) { - this.examsSynced = examsSynced; - return this; - } - - public boolean getExamsSynced() { - return examsSynced; - } - - /** - * 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 = 1562119145) - public List getDayList() { - if (dayList == null) { - final DaoSession daoSession = this.daoSession; - if (daoSession == null) { - throw new DaoException("Entity is detached from DAO context"); - } - DayDao targetDao = daoSession.getDayDao(); - List dayListNew = targetDao._queryWeek_DayList(id); - synchronized (this) { - if (dayList == null) { - dayList = dayListNew; - } - } - } - return dayList; - } - - /** - * Resets a to-many relationship, making the next get call to query for a fresh result. - */ - @Generated(hash = 1010399236) - public synchronized void resetDayList() { - dayList = 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 = 665278367) - public void __setDaoSession(DaoSession daoSession) { - this.daoSession = daoSession; - myDao = daoSession != null ? daoSession.getWeekDao() : null; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration23.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration23.java deleted file mode 100644 index 519d9153..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration23.java +++ /dev/null @@ -1,114 +0,0 @@ -package io.github.wulkanowy.data.db.dao.migrations; - -import android.database.Cursor; -import android.os.AsyncTask; - -import org.greenrobot.greendao.database.Database; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import io.github.wulkanowy.api.Vulcan; -import io.github.wulkanowy.api.generic.Diary; -import io.github.wulkanowy.data.db.dao.DbHelper; -import io.github.wulkanowy.data.db.shared.SharedPrefContract; -import io.github.wulkanowy.utils.security.Scrambler; - -public class Migration23 implements DbHelper.Migration { - - @Override - public Integer getVersion() { - return 23; - } - - @Override - public void runMigration(final Database db, final SharedPrefContract sharedPref, final Vulcan vulcan) throws Exception { - createDiaryTable(db); - migrateAccountsTable(db); - - final Map user = getAccountData(db); - vulcan.setCredentials( - user.get("email"), - Scrambler.decrypt(user.get("password")), - user.get("symbol"), - user.get("school_id"), - "", // inserted in code bellow - "" - ); - - AsyncTask.execute(new Runnable() { - @Override - public void run() { - try { - insertDiaries(db, vulcan.getStudentAndParent().getDiaries()); - updateAccount(db, vulcan.getStudentAndParent().getStudentID()); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - - private void createDiaryTable(Database db) { - db.execSQL("DROP TABLE IF EXISTS Diaries"); - db.execSQL("CREATE TABLE IF NOT EXISTS \"Diaries\" (" + // - "\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id - "\"STUDENT_ID\" TEXT," + // 1: studentId - "\"NAME\" TEXT," + // 2: name - "\"VALUE\" TEXT," + // 3: value - "\"IS_CURRENT\" INTEGER NOT NULL );"); // 4: isCurrent - } - - private void migrateAccountsTable(Database db) { - db.execSQL("DROP TABLE IF EXISTS tmp_account"); - db.execSQL("ALTER TABLE Accounts RENAME TO tmp_account"); - db.execSQL("CREATE TABLE IF NOT EXISTS \"Accounts\" (" + // - "\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id - "\"REAL_ID\" TEXT," + // 1: realId - "\"SYMBOL\" TEXT," + // 2: symbol - "\"SCHOOL_ID\" TEXT," + // 3: schoolId - "\"NAME\" TEXT," + // 4: name - "\"E_MAIL\" TEXT," + // 5: email - "\"PASSWORD\" TEXT);"); // 6: password - // Add Indexes - db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS IDX_Accounts_REAL_ID ON \"Accounts\" (\"REAL_ID\" ASC);"); - db.execSQL("INSERT INTO Accounts(NAME, E_MAIL, PASSWORD, SYMBOL, SCHOOL_ID)" + - "SELECT `NAME`, `E-MAIL`, `PASSWORD`, `SYMBOL`, `SNPID` FROM tmp_account"); - db.execSQL("DROP TABLE tmp_account"); - } - - private Map getAccountData(Database db) { - Map values = new HashMap<>(); - Cursor cursor = db.rawQuery("SELECT SYMBOL, SCHOOL_ID, NAME, E_MAIL, PASSWORD FROM Accounts", null); - - if (cursor.moveToFirst()) { - do { - values.put("symbol", cursor.getString(cursor.getColumnIndex("SYMBOL"))); - values.put("school_id", cursor.getString(cursor.getColumnIndex("SCHOOL_ID"))); - values.put("name", cursor.getString(cursor.getColumnIndex("NAME"))); - values.put("email", cursor.getString(cursor.getColumnIndex("E_MAIL"))); - values.put("password", cursor.getString(cursor.getColumnIndex("PASSWORD"))); - } while (cursor.moveToNext()); - } - - cursor.close(); - - return values; - } - - private void insertDiaries(Database db, List list) { - for (Diary diary : list) { - db.execSQL("INSERT INTO Diaries(STUDENT_ID, NAME, VALUE, IS_CURRENT) VALUES(" + - "\"" + diary.getId() + "\"," + - "\"" + diary.getName() + "\"," + - "\"" + diary.getId() + "\"," + - "\"" + (diary.isCurrent() ? "1" : "0") + "\"" + - ")"); - } - } - - private void updateAccount(Database db, String realId) { - db.execSQL("UPDATE Accounts SET REAL_ID = ?", new String[]{realId}); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration26.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration26.java deleted file mode 100644 index 332f2dd2..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration26.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.github.wulkanowy.data.db.dao.migrations; - -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; - -public class Migration26 implements DbHelper.Migration { - - @Override - public Integer getVersion() { - return 26; - } - - @Override - public void runMigration(final Database db, final SharedPrefContract sharedPref, final Vulcan vulcan) throws Exception { - throw new Exception("No migrations"); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration27.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration27.java deleted file mode 100644 index 922079f4..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration27.java +++ /dev/null @@ -1,24 +0,0 @@ -package io.github.wulkanowy.data.db.dao.migrations; - -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.dao.entities.ExamDao; -import io.github.wulkanowy.data.db.shared.SharedPrefContract; - -public class Migration27 implements DbHelper.Migration { - - @Override - public Integer getVersion() { - return 27; - } - - @Override - public void runMigration(Database db, SharedPrefContract sharedPref, Vulcan vulcan) { - ExamDao.dropTable(db, true); - ExamDao.createTable(db, true); - - db.execSQL("UPDATE Weeks SET exams_synced = 0"); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration28.java b/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration28.java deleted file mode 100644 index 3970df4c..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration28.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.github.wulkanowy.data.db.dao.migrations; - -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; - -public class Migration28 implements DbHelper.Migration { - - @Override - public Integer getVersion() { - return 28; - } - - @Override - public void runMigration(final Database db, final SharedPrefContract sharedPref, final Vulcan vulcan) throws Exception { - throw new Exception("No migrations"); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration29.kt b/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration29.kt deleted file mode 100644 index e318b5fd..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration29.kt +++ /dev/null @@ -1,60 +0,0 @@ -package io.github.wulkanowy.data.db.dao.migrations - -import android.database.Cursor - -import org.greenrobot.greendao.database.Database - -import io.github.wulkanowy.api.Vulcan -import io.github.wulkanowy.data.db.dao.DbHelper -import io.github.wulkanowy.data.db.shared.SharedPrefContract - -class Migration29 : DbHelper.Migration { - - override fun getVersion(): Int? { - return 29 - } - - override fun runMigration(db: Database, sharedPref: SharedPrefContract, vulcan: Vulcan) { - createSchoolsTable(db) - modifyStudents(db) - insertSchool(db, getRealSchoolId(db)) - } - - private fun createSchoolsTable(db: Database) { - db.execSQL("DROP TABLE IF EXISTS \"Schools\";") - db.execSQL("CREATE TABLE IF NOT EXISTS \"Schools\" (" + // - "\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id - "\"symbol_id\" INTEGER," + // 1: symbolId - "\"current\" INTEGER NOT NULL ," + // 2: current - "\"real_id\" TEXT," + // 3: realId - "\"name\" TEXT);") // 4: name - } - - private fun modifyStudents(db: Database) { - db.execSQL("ALTER TABLE Students ADD COLUMN school_id INTEGER") - db.execSQL("UPDATE Students SET school_id = '1'") - } - - private fun getRealSchoolId(db: Database): String { - var cursor: Cursor? = null - try { - cursor = db.rawQuery("SELECT school_id FROM Symbols WHERE _id=?", arrayOf("1")) - - return if (cursor!!.count > 0) { - cursor.moveToFirst() - cursor.getString(cursor.getColumnIndex("school_id")) - } else "" - } finally { - cursor!!.close() - } - } - - private fun insertSchool(db: Database, realId: String) { - db.execSQL("INSERT INTO Schools(symbol_id, current, real_id, name) VALUES(" + - "\"1\"," + - "\"1\"," + - "\"" + realId + "\"," + - "\"Uczeń\"" + - ")") - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/entities/Attendance.kt b/app/src/main/java/io/github/wulkanowy/data/db/entities/Attendance.kt new file mode 100644 index 00000000..bd571240 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/entities/Attendance.kt @@ -0,0 +1,41 @@ +package io.github.wulkanowy.data.db.entities + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey +import org.threeten.bp.LocalDate +import java.io.Serializable + +@Entity(tableName = "Attendance") +data class Attendance( + + @ColumnInfo(name = "student_id") + var studentId: Int, + + @ColumnInfo(name = "diary_id") + var diaryId: Int, + + var date: LocalDate, + + var number: Int, + + var subject: String, + + var name: String, + + var presence: Boolean = false, + + var absence: Boolean = false, + + var exemption: Boolean = false, + + var lateness: Boolean = false, + + var excused: Boolean = false, + + var deleted: Boolean = false +) : Serializable { + + @PrimaryKey(autoGenerate = true) + var id: Long = 0 +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/entities/Exam.kt b/app/src/main/java/io/github/wulkanowy/data/db/entities/Exam.kt new file mode 100644 index 00000000..daa886d5 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/entities/Exam.kt @@ -0,0 +1,39 @@ +package io.github.wulkanowy.data.db.entities + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey +import org.threeten.bp.LocalDate +import java.io.Serializable + +@Entity(tableName = "Exams") +data class Exam( + + @ColumnInfo(name = "student_id") + var studentId: Int, + + @ColumnInfo(name = "diary_id") + var diaryId: Int, + + var date: LocalDate, + + @ColumnInfo(name = "entry_date") + var entryDate: LocalDate = LocalDate.now(), + + var subject: String, + + var group: String, + + var type: String, + + var description: String, + + var teacher: String, + + @ColumnInfo(name = "teacher_symbol") + var teacherSymbol: String +) : Serializable { + + @PrimaryKey(autoGenerate = true) + var id: Long = 0 +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/entities/Grade.kt b/app/src/main/java/io/github/wulkanowy/data/db/entities/Grade.kt new file mode 100644 index 00000000..d665f9d2 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/entities/Grade.kt @@ -0,0 +1,52 @@ +package io.github.wulkanowy.data.db.entities + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey +import org.threeten.bp.LocalDate +import java.io.Serializable + +@Entity(tableName = "Grades") +data class Grade( + + @ColumnInfo(name = "semester_id") + var semesterId: Int, + + @ColumnInfo(name = "student_id") + var studentId: Int, + + var subject: String, + + var entry: String, + + var value: Int, + + var modifier: Double, + + var comment: String, + + var color: String, + + @ColumnInfo(name = "grade_symbol") + var gradeSymbol: String, + + var description: String, + + var weight: String, + + var weightValue: Int, + + var date: LocalDate, + + var teacher: String +) : Serializable { + + @PrimaryKey(autoGenerate = true) + var id: Long = 0 + + @ColumnInfo(name = "is_read") + var isRead: Boolean = true + + @ColumnInfo(name = "is_notified") + var isNotified: Boolean = true +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/entities/GradeSummary.kt b/app/src/main/java/io/github/wulkanowy/data/db/entities/GradeSummary.kt new file mode 100644 index 00000000..74d709bb --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/entities/GradeSummary.kt @@ -0,0 +1,25 @@ +package io.github.wulkanowy.data.db.entities + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "Grades_Summary") +data class GradeSummary( + + @ColumnInfo(name = "semester_id") + var semesterId: Int, + + @ColumnInfo(name = "student_id") + var studentId: Int, + + var subject: String, + + var predictedGrade: String, + + var finalGrade: String +) { + @PrimaryKey(autoGenerate = true) + var id: Long = 0 + +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/entities/Semester.kt b/app/src/main/java/io/github/wulkanowy/data/db/entities/Semester.kt new file mode 100644 index 00000000..fc776e9b --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/entities/Semester.kt @@ -0,0 +1,30 @@ +package io.github.wulkanowy.data.db.entities + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "Semesters") +data class Semester( + + @PrimaryKey(autoGenerate = true) + var id: Long = 0, + + @ColumnInfo(name = "student_id") + var studentId: Int, + + @ColumnInfo(name = "diary_id") + var diaryId: Int, + + @ColumnInfo(name = "diary_name") + var diaryName: String, + + @ColumnInfo(name = "semester_id") + var semesterId: Int, + + @ColumnInfo(name = "semester_name") + var semesterName: Int, + + @ColumnInfo(name = "is_current") + var current: Boolean = false +) diff --git a/app/src/main/java/io/github/wulkanowy/data/db/entities/Student.kt b/app/src/main/java/io/github/wulkanowy/data/db/entities/Student.kt new file mode 100644 index 00000000..a9f405c8 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/entities/Student.kt @@ -0,0 +1,34 @@ +package io.github.wulkanowy.data.db.entities + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "Students") +data class Student( + + @PrimaryKey(autoGenerate = true) + var id: Long = 0, + + var endpoint: String, + + var loginType: String, + + var email: String, + + var password: String, + + var symbol: String = "", + + @ColumnInfo(name = "student_id") + var studentId: Int = 0, + + @ColumnInfo(name = "student_name") + var studentName: String = "", + + @ColumnInfo(name = "school_id") + var schoolSymbol: String = "", + + @ColumnInfo(name = "school_name") + var schoolName: String = "" +) diff --git a/app/src/main/java/io/github/wulkanowy/data/db/entities/Timetable.kt b/app/src/main/java/io/github/wulkanowy/data/db/entities/Timetable.kt new file mode 100644 index 00000000..2aa1eafa --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/entities/Timetable.kt @@ -0,0 +1,44 @@ +package io.github.wulkanowy.data.db.entities + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey +import org.threeten.bp.LocalDate +import org.threeten.bp.LocalDateTime +import java.io.Serializable + +@Entity(tableName = "Timetable") +data class Timetable( + + @ColumnInfo(name = "student_id") + var studentId: Int, + + @ColumnInfo(name = "diary_id") + var diaryId: Int, + + val number: Int = 0, + + val start: LocalDateTime = LocalDateTime.now(), + + val end: LocalDateTime = LocalDateTime.now(), + + val date: LocalDate, + + val subject: String, + + val group: String, + + val room: String, + + val teacher: String, + + val info: String, + + val changes: Boolean = false, + + val canceled: Boolean = false +) : Serializable { + + @PrimaryKey(autoGenerate = true) + var id: Long = 0 +} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/resources/ResourcesContract.java b/app/src/main/java/io/github/wulkanowy/data/db/resources/ResourcesContract.java deleted file mode 100644 index 0e654997..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/resources/ResourcesContract.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.github.wulkanowy.data.db.resources; - -import javax.inject.Singleton; - -import io.github.wulkanowy.data.db.dao.entities.AttendanceLesson; - -@Singleton -public interface ResourcesContract { - - String[] getSymbolsKeysArray(); - - String[] getSymbolsValuesArray(); - - String getErrorLoginMessage(Exception e); - - String getAttendanceLessonDescription(AttendanceLesson lesson); -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/resources/ResourcesRepository.java b/app/src/main/java/io/github/wulkanowy/data/db/resources/ResourcesRepository.java deleted file mode 100644 index 1151e797..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/resources/ResourcesRepository.java +++ /dev/null @@ -1,84 +0,0 @@ -package io.github.wulkanowy.data.db.resources; - -import android.content.Context; -import android.content.res.Resources; - -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import io.github.wulkanowy.R; -import io.github.wulkanowy.api.NotLoggedInErrorException; -import io.github.wulkanowy.data.db.dao.entities.AttendanceLesson; -import io.github.wulkanowy.utils.AppConstant; -import timber.log.Timber; - -@Singleton -public class ResourcesRepository implements ResourcesContract { - - private Resources resources; - - @Inject - ResourcesRepository(Context context) { - resources = context.getResources(); - } - - @Override - public String[] getSymbolsKeysArray() { - return resources.getStringArray(R.array.symbols); - } - - @Override - public String[] getSymbolsValuesArray() { - return resources.getStringArray(R.array.symbols_values); - } - - @Override - public String getErrorLoginMessage(Exception exception) { - Timber.e(exception, "%s encountered a error", AppConstant.APP_NAME); - - if (exception instanceof UnknownHostException) { - return resources.getString(R.string.noInternet_text); - } else if (exception instanceof SocketTimeoutException) { - return resources.getString(R.string.generic_timeout_error); - } else if (exception instanceof NotLoggedInErrorException || exception instanceof IOException) { - return resources.getString(R.string.login_failed_text); - } else { - return exception.getMessage(); - } - } - - @Override - public String getAttendanceLessonDescription(AttendanceLesson lesson) { - int id = R.string.attendance_present; - - if (lesson.getAbsenceForSchoolReasons()) { - id = R.string.attendance_absence_for_school_reasons; - } - - if (lesson.getAbsenceExcused()) { - id = R.string.attendance_absence_excused; - } - - if (lesson.getAbsenceUnexcused()) { - id = R.string.attendance_absence_unexcused; - } - - if (lesson.getExemption()) { - id = R.string.attendance_exemption; - } - - if (lesson.getExcusedLateness()) { - id = R.string.attendance_excused_lateness; - } - - if (lesson.getUnexcusedLateness()) { - id = R.string.attendance_unexcused_lateness; - } - - return resources.getString(id); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/shared/SharedPrefContract.java b/app/src/main/java/io/github/wulkanowy/data/db/shared/SharedPrefContract.java deleted file mode 100644 index 370f8dfe..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/shared/SharedPrefContract.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.github.wulkanowy.data.db.shared; - -import javax.inject.Singleton; - -@Singleton -public interface SharedPrefContract { - - long getCurrentUserId(); - - boolean isUserLoggedIn(); - - void setCurrentUserId(long userId); - - void setTimetableWidgetState(boolean nextDay); - - boolean getTimetableWidgetState(); - - int getStartupTab(); - - boolean isShowGradesSummary(); - - boolean isShowAttendancePresent(); - - int getCurrentTheme(); - - int getServicesInterval(); - - boolean isMobileDisable(); - - boolean isServicesEnable(); - - boolean isNotifyEnable(); - - void cleanSharedPref(); -} diff --git a/app/src/main/java/io/github/wulkanowy/data/db/shared/SharedPrefRepository.java b/app/src/main/java/io/github/wulkanowy/data/db/shared/SharedPrefRepository.java deleted file mode 100644 index adedbda4..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/db/shared/SharedPrefRepository.java +++ /dev/null @@ -1,102 +0,0 @@ -package io.github.wulkanowy.data.db.shared; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import io.github.wulkanowy.ui.main.settings.SettingsFragment; - -@Singleton -public class SharedPrefRepository implements SharedPrefContract { - - private static final String SHARED_KEY_USER_ID = "USER_ID"; - - private static final String SHARED_KEY_TIMETABLE_WIDGET_STATE = "TIMETABLE_WIDGET_STATE"; - - private final SharedPreferences appSharedPref; - - private final SharedPreferences settingsSharedPref; - - @Inject - SharedPrefRepository(Context context, @Named("sharedPrefName") String sharedName) { - appSharedPref = context.getSharedPreferences(sharedName, Context.MODE_PRIVATE); - settingsSharedPref = PreferenceManager.getDefaultSharedPreferences(context); - } - - @Override - public long getCurrentUserId() { - return appSharedPref.getLong(SHARED_KEY_USER_ID, 0); - } - - @Override - public boolean isUserLoggedIn() { - return getCurrentUserId() != 0; - } - - @Override - public void setCurrentUserId(long userId) { - appSharedPref.edit().putLong(SHARED_KEY_USER_ID, userId).apply(); - } - - @SuppressLint("ApplySharedPref") - @Override - public void setTimetableWidgetState(boolean nextDay) { - appSharedPref.edit().putBoolean(SHARED_KEY_TIMETABLE_WIDGET_STATE, nextDay).commit(); - } - - @Override - public boolean getTimetableWidgetState() { - return appSharedPref.getBoolean(SHARED_KEY_TIMETABLE_WIDGET_STATE, false); - } - - @Override - public int getStartupTab() { - return Integer.parseInt(settingsSharedPref.getString(SettingsFragment.SHARED_KEY_START_TAB, "0")); - } - - @Override - public boolean isShowGradesSummary() { - return settingsSharedPref.getBoolean(SettingsFragment.SHARED_KEY_GRADES_SUMMARY, false); - } - - @Override - public boolean isShowAttendancePresent() { - return settingsSharedPref.getBoolean(SettingsFragment.SHARED_KEY_ATTENDANCE_PRESENT, false); - } - - @Override - public int getCurrentTheme() { - return Integer.parseInt(settingsSharedPref.getString(SettingsFragment.SHARED_KEY_THEME, "1")); - } - - @Override - public int getServicesInterval() { - return Integer.parseInt(settingsSharedPref.getString(SettingsFragment.SHARED_KEY_SERVICES_INTERVAL, "60")); - } - - @Override - public boolean isServicesEnable() { - return settingsSharedPref.getBoolean(SettingsFragment.SHARED_KEY_SERVICES_ENABLE, true); - } - - @Override - public boolean isNotifyEnable() { - return settingsSharedPref.getBoolean(SettingsFragment.SHARED_KEY_NOTIFY_ENABLE, true); - } - - @Override - public boolean isMobileDisable() { - return settingsSharedPref.getBoolean(SettingsFragment.SHARED_KEY_SERVICES_MOBILE_DISABLED, false); - } - - @Override - public void cleanSharedPref() { - appSharedPref.edit().clear().apply(); - settingsSharedPref.edit().clear().apply(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/AttendanceRepository.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/AttendanceRepository.kt new file mode 100644 index 00000000..ce62cafa --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/AttendanceRepository.kt @@ -0,0 +1,45 @@ +package io.github.wulkanowy.data.repositories + +import com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork +import com.github.pwittchen.reactivenetwork.library.rx2.internet.observing.InternetObservingSettings +import io.github.wulkanowy.data.db.entities.Attendance +import io.github.wulkanowy.data.db.entities.Semester +import io.github.wulkanowy.data.repositories.local.AttendanceLocal +import io.github.wulkanowy.data.repositories.remote.AttendanceRemote +import io.github.wulkanowy.utils.friday +import io.github.wulkanowy.utils.monday +import io.reactivex.Single +import org.threeten.bp.LocalDate +import java.net.UnknownHostException +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class AttendanceRepository @Inject constructor( + private val settings: InternetObservingSettings, + private val local: AttendanceLocal, + private val remote: AttendanceRemote +) { + + fun getAttendance(semester: Semester, startDate: LocalDate, endDate: LocalDate, forceRefresh: Boolean) + : Single> { + return Single.fromCallable { startDate.monday to endDate.friday } + .flatMap { dates -> + local.getAttendance(semester, dates.first, dates.second).filter { !forceRefresh } + .switchIfEmpty(ReactiveNetwork.checkInternetConnectivity(settings).flatMap { + if (it) remote.getAttendance(semester, dates.first, dates.second) + else Single.error(UnknownHostException()) + }.flatMap { newAttendance -> + local.getAttendance(semester, dates.first, dates.second) + .toSingle(emptyList()) + .doOnSuccess { oldAttendance -> + local.deleteAttendance(oldAttendance - newAttendance) + local.saveAttendance(newAttendance - oldAttendance) + } + }.flatMap { + local.getAttendance(semester, dates.first, dates.second) + .toSingle(emptyList()) + }).map { list -> list.filter { it.date in startDate..endDate } } + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/ExamRepository.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/ExamRepository.kt new file mode 100644 index 00000000..d956d913 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/ExamRepository.kt @@ -0,0 +1,45 @@ +package io.github.wulkanowy.data.repositories + +import com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork +import com.github.pwittchen.reactivenetwork.library.rx2.internet.observing.InternetObservingSettings +import io.github.wulkanowy.data.db.entities.Exam +import io.github.wulkanowy.data.db.entities.Semester +import io.github.wulkanowy.data.repositories.local.ExamLocal +import io.github.wulkanowy.data.repositories.remote.ExamRemote +import io.github.wulkanowy.utils.friday +import io.github.wulkanowy.utils.monday +import io.reactivex.Single +import org.threeten.bp.LocalDate +import java.net.UnknownHostException +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class ExamRepository @Inject constructor( + private val settings: InternetObservingSettings, + private val local: ExamLocal, + private val remote: ExamRemote +) { + + fun getExams(semester: Semester, startDate: LocalDate, endDate: LocalDate, forceRefresh: Boolean = false): Single> { + return Single.fromCallable { startDate.monday to endDate.friday } + .flatMap { dates -> + local.getExams(semester, dates.first, dates.second).filter { !forceRefresh } + .switchIfEmpty(ReactiveNetwork.checkInternetConnectivity(settings) + .flatMap { + if (it) remote.getExams(semester, dates.first, dates.second) + else Single.error(UnknownHostException()) + }.flatMap { newExams -> + local.getExams(semester, dates.first, dates.second) + .toSingle(emptyList()) + .doOnSuccess { oldExams -> + local.deleteExams(oldExams - newExams) + local.saveExams(newExams - oldExams) + } + }.flatMap { + local.getExams(semester, dates.first, dates.second) + .toSingle(emptyList()) + }).map { list -> list.filter { it.date in startDate..endDate } } + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/GradeRepository.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/GradeRepository.kt new file mode 100644 index 00000000..42266955 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/GradeRepository.kt @@ -0,0 +1,52 @@ +package io.github.wulkanowy.data.repositories + +import com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork +import com.github.pwittchen.reactivenetwork.library.rx2.internet.observing.InternetObservingSettings +import io.github.wulkanowy.data.db.entities.Grade +import io.github.wulkanowy.data.db.entities.Semester +import io.github.wulkanowy.data.repositories.local.GradeLocal +import io.github.wulkanowy.data.repositories.remote.GradeRemote +import io.reactivex.Completable +import io.reactivex.Single +import java.net.UnknownHostException +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class GradeRepository @Inject constructor( + private val settings: InternetObservingSettings, + private val local: GradeLocal, + private val remote: GradeRemote +) { + + fun getGrades(semester: Semester, forceRefresh: Boolean = false, notify: Boolean = false): Single> { + return local.getGrades(semester).filter { !forceRefresh } + .switchIfEmpty(ReactiveNetwork.checkInternetConnectivity(settings) + .flatMap { + if (it) remote.getGrades(semester) + else Single.error(UnknownHostException()) + }.flatMap { newGrades -> + local.getGrades(semester).toSingle(emptyList()) + .doOnSuccess { oldGrades -> + local.deleteGrades(oldGrades - newGrades) + local.saveGrades((newGrades - oldGrades) + .onEach { + if (oldGrades.isNotEmpty()) it.isRead = false + if (notify) it.isNotified = false + }) + } + }.flatMap { local.getGrades(semester).toSingle(emptyList()) }) + } + + fun getNewGrades(semester: Semester): Single> { + return local.getNewGrades(semester).toSingle(emptyList()) + } + + fun updateGrade(grade: Grade): Completable { + return local.updateGrade(grade) + } + + fun updateGrades(grades: List): Completable { + return local.updateGrades(grades) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/GradeSummaryRepository.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/GradeSummaryRepository.kt new file mode 100644 index 00000000..e809ff59 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/GradeSummaryRepository.kt @@ -0,0 +1,35 @@ +package io.github.wulkanowy.data.repositories + +import com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork +import com.github.pwittchen.reactivenetwork.library.rx2.internet.observing.InternetObservingSettings +import io.github.wulkanowy.data.db.entities.GradeSummary +import io.github.wulkanowy.data.db.entities.Semester +import io.github.wulkanowy.data.repositories.local.GradeSummaryLocal +import io.github.wulkanowy.data.repositories.remote.GradeSummaryRemote +import io.reactivex.Single +import java.net.UnknownHostException +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class GradeSummaryRepository @Inject constructor( + private val settings: InternetObservingSettings, + private val local: GradeSummaryLocal, + private val remote: GradeSummaryRemote +) { + + fun getGradesSummary(semester: Semester, forceRefresh: Boolean = false): Single> { + return local.getGradesSummary(semester).filter { !forceRefresh } + .switchIfEmpty(ReactiveNetwork.checkInternetConnectivity(settings) + .flatMap { + if (it) remote.getGradeSummary(semester) + else Single.error(UnknownHostException()) + }.flatMap { newGradesSummary -> + local.getGradesSummary(semester).toSingle(emptyList()) + .doOnSuccess { oldGradesSummary -> + local.deleteGradesSummary(oldGradesSummary - newGradesSummary) + local.saveGradesSummary(newGradesSummary - oldGradesSummary) + } + }.flatMap { local.getGradesSummary(semester).toSingle(emptyList()) }) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/PreferencesRepository.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/PreferencesRepository.kt new file mode 100644 index 00000000..2c4a1242 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/PreferencesRepository.kt @@ -0,0 +1,39 @@ +package io.github.wulkanowy.data.repositories + +import android.content.Context +import android.content.SharedPreferences +import io.github.wulkanowy.R +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class PreferencesRepository @Inject constructor( + private val sharedPref: SharedPreferences, + val context: Context +) { + + val startMenuIndex: Int + get() = sharedPref.getString(context.getString(R.string.pref_key_start_menu), "0")?.toInt() ?: 0 + + val showPresent: Boolean + get() = sharedPref.getBoolean(context.getString(R.string.pref_key_attendance_present), true) + + val currentThemeKey: String = context.getString(R.string.pref_key_theme) + val currentTheme: Int + get() = sharedPref.getString(currentThemeKey, "1")?.toInt() ?: 1 + + val serviceEnablesKey: String = context.getString(R.string.pref_key_services_enable) + val serviceEnabled: Boolean + get() = sharedPref.getBoolean(serviceEnablesKey, true) + + val servicesIntervalKey: String = context.getString(R.string.pref_key_services_interval) + val servicesInterval: Int + get() = sharedPref.getString(servicesIntervalKey, "60")?.toInt() ?: 60 + + val servicesOnlyWifiKey: String = context.getString(R.string.pref_key_services_wifi_only) + val servicesOnlyWifi: Boolean + get() = sharedPref.getBoolean(servicesOnlyWifiKey, true) + + val notificationsEnable: Boolean + get() = sharedPref.getBoolean(context.getString(R.string.pref_key_notifications_enable), true) +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/SessionRepository.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/SessionRepository.kt new file mode 100644 index 00000000..93c8e2b7 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/SessionRepository.kt @@ -0,0 +1,68 @@ +package io.github.wulkanowy.data.repositories + +import com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork +import com.github.pwittchen.reactivenetwork.library.rx2.internet.observing.InternetObservingSettings +import io.github.wulkanowy.data.db.entities.Semester +import io.github.wulkanowy.data.db.entities.Student +import io.github.wulkanowy.data.repositories.local.SessionLocal +import io.github.wulkanowy.data.repositories.remote.SessionRemote +import io.reactivex.Completable +import io.reactivex.Single +import java.net.UnknownHostException +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class SessionRepository @Inject constructor( + private val local: SessionLocal, + private val remote: SessionRemote, + private val settings: InternetObservingSettings +) { + + val isSessionSaved + get() = local.isSessionSaved + + lateinit var cachedStudents: Single> + private set + + fun getConnectedStudents(email: String, password: String, symbol: String, endpoint: String): Single> { + cachedStudents = ReactiveNetwork.checkInternetConnectivity(settings) + .flatMap { isConnected -> + if (isConnected) remote.getConnectedStudents(email, password, symbol, endpoint) + else Single.error>(UnknownHostException("No internet connection")) + }.doOnSuccess { cachedStudents = Single.just(it) } + return cachedStudents + } + + fun saveStudent(student: Student): Completable { + return remote.getSemesters(student) + .flatMapCompletable { local.saveSemesters(it) } + .concatWith(local.saveStudent(student)) + } + + fun getSemesters(forceRefresh: Boolean = false): Single> { + return local.getLastStudent() + .flatMapSingle { student -> + remote.initApi(student) + local.getSemesters(student).filter { !forceRefresh } + .switchIfEmpty(ReactiveNetwork.checkInternetConnectivity(settings).flatMap { + if (it) remote.getCurrentSemester(student) + else Single.error(UnknownHostException()) + }.flatMap { current -> + local.getSemesters(student).doOnSuccess { semesters -> + if (semesters.single { it.current }.semesterId != current.semesterId) { + local.saveSemesters(listOf(current)).andThen { + local.setCurrentSemester(current.semesterId) + } + } + } + }.flatMap { + local.getSemesters(student) + }) + } + } + + fun clearCache() { + cachedStudents = Single.just(emptyList()) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/TimetableRepository.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/TimetableRepository.kt new file mode 100644 index 00000000..95a1563f --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/TimetableRepository.kt @@ -0,0 +1,46 @@ +package io.github.wulkanowy.data.repositories + +import com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork +import com.github.pwittchen.reactivenetwork.library.rx2.internet.observing.InternetObservingSettings +import io.github.wulkanowy.data.db.entities.Semester +import io.github.wulkanowy.data.db.entities.Timetable +import io.github.wulkanowy.data.repositories.local.TimetableLocal +import io.github.wulkanowy.data.repositories.remote.TimetableRemote +import io.github.wulkanowy.utils.friday +import io.github.wulkanowy.utils.monday +import io.reactivex.Single +import org.threeten.bp.LocalDate +import java.net.UnknownHostException +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class TimetableRepository @Inject constructor( + private val settings: InternetObservingSettings, + private val local: TimetableLocal, + private val remote: TimetableRemote +) { + + fun getTimetable(semester: Semester, startDate: LocalDate, endDate: LocalDate, forceRefresh: Boolean = false) + : Single> { + return Single.fromCallable { startDate.monday to endDate.friday } + .flatMap { dates -> + local.getTimetable(semester, dates.first, dates.second).filter { !forceRefresh } + .switchIfEmpty(ReactiveNetwork.checkInternetConnectivity(settings) + .flatMap { + if (it) remote.getTimetable(semester, dates.first, dates.second) + else Single.error(UnknownHostException()) + }.flatMap { newTimetable -> + local.getTimetable(semester, dates.first, dates.second) + .toSingle(emptyList()) + .doOnSuccess { oldTimetable -> + local.deleteTimetable(oldTimetable - newTimetable) + local.saveTimetable(newTimetable - oldTimetable) + } + }.flatMap { + local.getTimetable(semester, dates.first, dates.second) + .toSingle(emptyList()) + }).map { list -> list.filter { it.date in startDate..endDate } } + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/local/AttendanceLocal.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/local/AttendanceLocal.kt new file mode 100644 index 00000000..79ab5ec0 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/local/AttendanceLocal.kt @@ -0,0 +1,24 @@ +package io.github.wulkanowy.data.repositories.local + +import io.github.wulkanowy.data.db.dao.AttendanceDao +import io.github.wulkanowy.data.db.entities.Attendance +import io.github.wulkanowy.data.db.entities.Semester +import io.reactivex.Maybe +import org.threeten.bp.LocalDate +import javax.inject.Inject + +class AttendanceLocal @Inject constructor(private val attendanceDb: AttendanceDao) { + + fun getAttendance(semester: Semester, startDate: LocalDate, endDate: LocalDate): Maybe> { + return attendanceDb.getExams(semester.diaryId, semester.studentId, startDate, endDate) + .filter { !it.isEmpty() } + } + + fun saveAttendance(attendance: List) { + attendanceDb.insertAll(attendance) + } + + fun deleteAttendance(attendance: List) { + attendanceDb.deleteAll(attendance) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/local/ExamLocal.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/local/ExamLocal.kt new file mode 100644 index 00000000..b8c3c0e2 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/local/ExamLocal.kt @@ -0,0 +1,24 @@ +package io.github.wulkanowy.data.repositories.local + +import io.github.wulkanowy.data.db.dao.ExamDao +import io.github.wulkanowy.data.db.entities.Exam +import io.github.wulkanowy.data.db.entities.Semester +import io.reactivex.Maybe +import org.threeten.bp.LocalDate +import javax.inject.Inject + +class ExamLocal @Inject constructor(private val examDb: ExamDao) { + + fun getExams(semester: Semester, startDate: LocalDate, endDate: LocalDate): Maybe> { + return examDb.getExams(semester.diaryId, semester.studentId, startDate, endDate) + .filter { !it.isEmpty() } + } + + fun saveExams(exams: List) { + examDb.insertAll(exams) + } + + fun deleteExams(exams: List) { + examDb.deleteAll(exams) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/local/GradeLocal.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/local/GradeLocal.kt new file mode 100644 index 00000000..4110bc3a --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/local/GradeLocal.kt @@ -0,0 +1,37 @@ +package io.github.wulkanowy.data.repositories.local + +import io.github.wulkanowy.data.db.dao.GradeDao +import io.github.wulkanowy.data.db.entities.Grade +import io.github.wulkanowy.data.db.entities.Semester +import io.reactivex.Completable +import io.reactivex.Maybe +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class GradeLocal @Inject constructor(private val gradeDb: GradeDao) { + + fun getGrades(semester: Semester): Maybe> { + return gradeDb.getGrades(semester.semesterId, semester.studentId).filter { !it.isEmpty() } + } + + fun getNewGrades(semester: Semester): Maybe> { + return gradeDb.getNewGrades(semester.semesterId, semester.studentId) + } + + fun saveGrades(grades: List) { + gradeDb.insertAll(grades) + } + + fun updateGrade(grade: Grade): Completable { + return Completable.fromCallable { gradeDb.update(grade) } + } + + fun updateGrades(grade: List): Completable { + return Completable.fromCallable { gradeDb.updateAll(grade) } + } + + fun deleteGrades(grades: List) { + gradeDb.deleteAll(grades) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/local/GradeSummaryLocal.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/local/GradeSummaryLocal.kt new file mode 100644 index 00000000..3b7c2d7b --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/local/GradeSummaryLocal.kt @@ -0,0 +1,25 @@ +package io.github.wulkanowy.data.repositories.local + +import io.github.wulkanowy.data.db.dao.GradeSummaryDao +import io.github.wulkanowy.data.db.entities.GradeSummary +import io.github.wulkanowy.data.db.entities.Semester +import io.reactivex.Maybe +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class GradeSummaryLocal @Inject constructor(private val gradeSummaryDb: GradeSummaryDao) { + + fun getGradesSummary(semester: Semester): Maybe> { + return gradeSummaryDb.getGradesSummary(semester.semesterId, semester.studentId) + .filter { !it.isEmpty() } + } + + fun saveGradesSummary(gradesSummary: List) { + gradeSummaryDb.insertAll(gradesSummary) + } + + fun deleteGradesSummary(gradesSummary: List) { + gradeSummaryDb.deleteAll(gradesSummary) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/local/SessionLocal.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/local/SessionLocal.kt new file mode 100644 index 00000000..008cd8e3 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/local/SessionLocal.kt @@ -0,0 +1,55 @@ +package io.github.wulkanowy.data.repositories.local + +import android.content.Context +import io.github.wulkanowy.data.db.SharedPrefHelper +import io.github.wulkanowy.data.db.dao.SemesterDao +import io.github.wulkanowy.data.db.dao.StudentDao +import io.github.wulkanowy.data.db.entities.Semester +import io.github.wulkanowy.data.db.entities.Student +import io.github.wulkanowy.utils.security.decrypt +import io.github.wulkanowy.utils.security.encrypt +import io.reactivex.Completable +import io.reactivex.Maybe +import io.reactivex.Single +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class SessionLocal @Inject constructor( + private val studentDb: StudentDao, + private val semesterDb: SemesterDao, + private val sharedPref: SharedPrefHelper, + private val context: Context) { + + companion object { + const val LAST_USER_KEY: String = "last_user_id" + } + + val isSessionSaved + get() = sharedPref.getLong(LAST_USER_KEY, defaultValue = 0L) != 0L + + fun saveStudent(student: Student): Completable { + return Single.fromCallable { studentDb.insert(student.copy(password = encrypt(student.password, context))) } + .map { sharedPref.putLong(LAST_USER_KEY, it) } + .ignoreElement() + } + + fun getLastStudent(): Maybe { + return studentDb.load(sharedPref.getLong(LAST_USER_KEY, defaultValue = 0)) + .map { it.apply { password = decrypt(password) } } + } + + fun saveSemesters(semesters: List): Completable { + return Single.fromCallable { semesterDb.insertAll(semesters) }.ignoreElement() + } + + fun getSemesters(student: Student): Single> { + return semesterDb.getSemester(student.studentId) + } + + fun setCurrentSemester(semesterId: Int): Completable { + return Single.fromCallable { semesterDb.resetCurrentSemester() }.ignoreElement().andThen { + semesterDb.setCurrentSemester(semesterId) + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/local/TimetableLocal.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/local/TimetableLocal.kt new file mode 100644 index 00000000..de5329eb --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/local/TimetableLocal.kt @@ -0,0 +1,24 @@ +package io.github.wulkanowy.data.repositories.local + +import io.github.wulkanowy.data.db.dao.TimetableDao +import io.github.wulkanowy.data.db.entities.Semester +import io.github.wulkanowy.data.db.entities.Timetable +import io.reactivex.Maybe +import org.threeten.bp.LocalDate +import javax.inject.Inject + +class TimetableLocal @Inject constructor(private val timetableDb: TimetableDao) { + + fun getTimetable(semester: Semester, startDate: LocalDate, endDate: LocalDate): Maybe> { + return timetableDb.getTimetable(semester.diaryId, semester.studentId, startDate, endDate) + .filter { !it.isEmpty() } + } + + fun saveTimetable(timetables: List) { + timetableDb.insertAll(timetables) + } + + fun deleteTimetable(timetables: List) { + timetableDb.deleteAll(timetables) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/remote/AttendanceRemote.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/remote/AttendanceRemote.kt new file mode 100644 index 00000000..4d17c24c --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/remote/AttendanceRemote.kt @@ -0,0 +1,38 @@ +package io.github.wulkanowy.data.repositories.remote + +import io.github.wulkanowy.api.Api +import io.github.wulkanowy.data.db.entities.Attendance +import io.github.wulkanowy.data.db.entities.Semester +import io.github.wulkanowy.utils.toLocalDate +import io.reactivex.Single +import org.threeten.bp.LocalDate +import javax.inject.Inject + +class AttendanceRemote @Inject constructor(private val api: Api) { + + fun getAttendance(semester: Semester, startDate: LocalDate, endDate: LocalDate): Single> { + return Single.just(api.run { + if (diaryId != semester.diaryId) { + diaryId = semester.diaryId + notifyDataChanged() + } + }).flatMap { api.getAttendance(startDate, endDate) }.map { attendance -> + attendance.map { + Attendance( + studentId = semester.studentId, + diaryId = semester.diaryId, + date = it.date.toLocalDate(), + number = it.number, + subject = it.subject, + name = it.name, + presence = it.presence, + absence = it.absence, + exemption = it.exemption, + lateness = it.lateness, + excused = it.excused, + deleted = it.deleted + ) + } + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/remote/ExamRemote.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/remote/ExamRemote.kt new file mode 100644 index 00000000..719d561d --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/remote/ExamRemote.kt @@ -0,0 +1,36 @@ +package io.github.wulkanowy.data.repositories.remote + +import io.github.wulkanowy.api.Api +import io.github.wulkanowy.data.db.entities.Exam +import io.github.wulkanowy.data.db.entities.Semester +import io.github.wulkanowy.utils.toLocalDate +import io.reactivex.Single +import org.threeten.bp.LocalDate +import javax.inject.Inject + +class ExamRemote @Inject constructor(private val api: Api) { + + fun getExams(semester: Semester, startDate: LocalDate, endDate: LocalDate): Single> { + return Single.just(api.run { + if (diaryId != semester.diaryId) { + diaryId = semester.diaryId + notifyDataChanged() + } + }).flatMap { api.getExams(startDate, endDate) }.map { exams -> + exams.map { + Exam( + studentId = semester.studentId, + diaryId = semester.diaryId, + date = it.date.toLocalDate(), + entryDate = it.entryDate.toLocalDate(), + subject = it.subject, + group = it.group, + type = it.type, + description = it.description, + teacher = it.teacher, + teacherSymbol = it.teacherSymbol + ) + } + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/remote/GradeRemote.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/remote/GradeRemote.kt new file mode 100644 index 00000000..52940231 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/remote/GradeRemote.kt @@ -0,0 +1,42 @@ +package io.github.wulkanowy.data.repositories.remote + +import io.github.wulkanowy.api.Api +import io.github.wulkanowy.data.db.entities.Grade +import io.github.wulkanowy.data.db.entities.Semester +import io.github.wulkanowy.utils.toLocalDate +import io.reactivex.Single +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class GradeRemote @Inject constructor(private val api: Api) { + + fun getGrades(semester: Semester): Single> { + return Single.just(api.run { + if (diaryId != semester.diaryId) { + diaryId = semester.diaryId + notifyDataChanged() + } + }).flatMap { api.getGrades(semester.semesterId) } + .map { grades -> + grades.map { + Grade( + semesterId = semester.semesterId, + studentId = semester.studentId, + subject = it.subject, + entry = it.entry, + value = it.value, + modifier = it.modifier, + comment = it.comment, + color = it.color, + gradeSymbol = it.symbol, + description = it.description, + weight = it.weight, + weightValue = it.weightValue, + date = it.date.toLocalDate(), + teacher = it.teacher + ) + } + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/remote/GradeSummaryRemote.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/remote/GradeSummaryRemote.kt new file mode 100644 index 00000000..f8cbdca4 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/remote/GradeSummaryRemote.kt @@ -0,0 +1,32 @@ +package io.github.wulkanowy.data.repositories.remote + +import io.github.wulkanowy.api.Api +import io.github.wulkanowy.data.db.entities.GradeSummary +import io.github.wulkanowy.data.db.entities.Semester +import io.reactivex.Single +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class GradeSummaryRemote @Inject constructor(private val api: Api) { + + fun getGradeSummary(semester: Semester): Single> { + return Single.just(api.run { + if (diaryId != semester.diaryId) { + diaryId = semester.diaryId + notifyDataChanged() + } + }).flatMap { api.getGradesSummary(semester.semesterId) } + .map { gradesSummary -> + gradesSummary.map { + GradeSummary( + semesterId = semester.semesterId, + studentId = semester.studentId, + subject = it.name, + predictedGrade = it.predicted, + finalGrade = it.final + ) + } + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/remote/SessionRemote.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/remote/SessionRemote.kt new file mode 100644 index 00000000..c6757ab6 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/remote/SessionRemote.kt @@ -0,0 +1,96 @@ +package io.github.wulkanowy.data.repositories.remote + +import io.github.wulkanowy.api.Api +import io.github.wulkanowy.data.db.entities.Semester +import io.github.wulkanowy.data.db.entities.Student +import io.reactivex.Single +import okhttp3.logging.HttpLoggingInterceptor +import timber.log.Timber +import java.net.URL +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class SessionRemote @Inject constructor(private val api: Api) { + + fun getConnectedStudents(email: String, password: String, symbol: String, endpoint: String): Single> { + return Single.just( + initApi( + Student( + email = email, + password = password, + symbol = symbol, + endpoint = endpoint, + loginType = "AUTO" + ), true + ) + ).flatMap { + api.getPupils().map { students -> + students.map { pupil -> + Student( + email = email, + password = password, + symbol = pupil.symbol, + studentId = pupil.studentId, + studentName = pupil.studentName, + schoolSymbol = pupil.schoolSymbol, + schoolName = pupil.schoolName, + endpoint = endpoint, + loginType = pupil.loginType.name + ) + } + } + } + } + + fun getSemesters(student: Student): Single> { + return Single.just(initApi(student)).flatMap { + api.getSemesters().map { semesters -> + semesters.map { semester -> + Semester( + studentId = student.studentId, + diaryId = semester.diaryId, + diaryName = semester.diaryName, + semesterId = semester.semesterId, + semesterName = semester.semesterNumber, + current = semester.current + ) + } + + } + } + } + + fun getCurrentSemester(student: Student): Single { + return api.getCurrentSemester().map { + Semester( + studentId = student.studentId, + diaryId = it.diaryId, + diaryName = it.diaryName, + semesterId = it.semesterId, + semesterName = it.semesterNumber, + current = it.current + ) + } + } + + fun initApi(student: Student, reInitialize: Boolean = false) { + if (if (reInitialize) true else 0 == api.studentId) { + api.run { + logLevel = HttpLoggingInterceptor.Level.NONE + email = student.email + password = student.password + symbol = student.symbol + host = URL(student.endpoint).run { host + ":$port".removeSuffix(":-1") } + ssl = student.endpoint.startsWith("https") + schoolSymbol = student.schoolSymbol + studentId = student.studentId + loginType = Api.LoginType.valueOf(student.loginType) + notifyDataChanged() + setInterceptor(HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { + Timber.d(it) + }).setLevel(HttpLoggingInterceptor.Level.BASIC)) + } + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/remote/TimetableRemote.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/remote/TimetableRemote.kt new file mode 100644 index 00000000..64386395 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/remote/TimetableRemote.kt @@ -0,0 +1,40 @@ +package io.github.wulkanowy.data.repositories.remote + +import io.github.wulkanowy.api.Api +import io.github.wulkanowy.data.db.entities.Semester +import io.github.wulkanowy.data.db.entities.Timetable +import io.github.wulkanowy.utils.toLocalDate +import io.github.wulkanowy.utils.toLocalDateTime +import io.reactivex.Single +import org.threeten.bp.LocalDate +import javax.inject.Inject + +class TimetableRemote @Inject constructor(private val api: Api) { + + fun getTimetable(semester: Semester, startDate: LocalDate, endDate: LocalDate): Single> { + return Single.just(api.run { + if (diaryId != semester.diaryId) { + diaryId = semester.diaryId + notifyDataChanged() + } + }).flatMap { api.getTimetable(startDate, endDate) }.map { lessons -> + lessons.map { + Timetable( + studentId = semester.studentId, + diaryId = semester.diaryId, + number = it.number, + start = it.start.toLocalDateTime(), + end = it.end.toLocalDateTime(), + date = it.date.toLocalDate(), + subject = it.subject, + group = it.group, + room = it.room, + teacher = it.teacher, + info = it.info, + changes = it.changes, + canceled = it.canceled + ) + } + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/sync/AccountSync.java b/app/src/main/java/io/github/wulkanowy/data/sync/AccountSync.java deleted file mode 100644 index cb51c1bb..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/sync/AccountSync.java +++ /dev/null @@ -1,197 +0,0 @@ -package io.github.wulkanowy.data.sync; - -import android.content.Context; - -import org.greenrobot.greendao.database.Database; - -import java.io.IOException; -import java.util.List; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import io.github.wulkanowy.api.Vulcan; -import io.github.wulkanowy.api.VulcanException; -import io.github.wulkanowy.data.db.dao.entities.Account; -import io.github.wulkanowy.data.db.dao.entities.DaoMaster; -import io.github.wulkanowy.data.db.dao.entities.DaoSession; -import io.github.wulkanowy.data.db.dao.entities.Diary; -import io.github.wulkanowy.data.db.dao.entities.DiaryDao; -import io.github.wulkanowy.data.db.dao.entities.School; -import io.github.wulkanowy.data.db.dao.entities.SchoolDao; -import io.github.wulkanowy.data.db.dao.entities.Semester; -import io.github.wulkanowy.data.db.dao.entities.Student; -import io.github.wulkanowy.data.db.dao.entities.StudentDao; -import io.github.wulkanowy.data.db.dao.entities.Symbol; -import io.github.wulkanowy.data.db.dao.entities.SymbolDao; -import io.github.wulkanowy.data.db.shared.SharedPrefContract; -import io.github.wulkanowy.utils.DataObjectConverter; -import io.github.wulkanowy.utils.security.Scrambler; -import io.github.wulkanowy.utils.security.ScramblerException; -import timber.log.Timber; - -@Singleton -public class AccountSync { - - private final DaoSession daoSession; - - private final SharedPrefContract sharedPref; - - private final Vulcan vulcan; - - private final Context context; - - @Inject - AccountSync(DaoSession daoSession, SharedPrefContract sharedPref, - Vulcan vulcan, Context context) { - this.daoSession = daoSession; - this.sharedPref = sharedPref; - this.vulcan = vulcan; - this.context = context; - } - - public void registerUser(String email, String password, String symbol) - throws VulcanException, IOException, ScramblerException { - - clearUserData(); - - vulcan.setCredentials(email, password, symbol, null, null, null); - - daoSession.getDatabase().beginTransaction(); - - Timber.i("Register start"); - - try { - Account account = insertAccount(email, password); - Symbol symbolEntity = insertSymbol(account); - School schoolEntity = insertSchools(symbolEntity); - Student student = insertStudents(schoolEntity); - Diary diary = insertDiaries(student); - insertSemesters(diary); - - sharedPref.setCurrentUserId(account.getId()); - - daoSession.getDatabase().setTransactionSuccessful(); - } finally { - daoSession.getDatabase().endTransaction(); - } - - Timber.i("Register end"); - } - - private Account insertAccount(String email, String password) throws ScramblerException { - Timber.d("Register account"); - Account account = new Account() - .setEmail(email) - .setPassword(Scrambler.encrypt(password, context)); - daoSession.getAccountDao().insert(account); - return account; - } - - private Symbol insertSymbol(Account account) throws VulcanException, IOException { - vulcan.getSchools(); - Timber.d("Register symbol (%s)", vulcan.getSymbol()); - Symbol symbol = new Symbol() - .setUserId(account.getId()) - .setSymbol(vulcan.getSymbol()); - daoSession.getSymbolDao().insert(symbol); - - return symbol; - } - - private School insertSchools(Symbol symbol) throws VulcanException, IOException { - List schoolList = DataObjectConverter.schoolsToSchoolsEntities( - vulcan.getSchools(), - symbol.getId() - ); - Timber.d("Register schools (%s)", schoolList.size()); - daoSession.getSchoolDao().insertInTx(schoolList); - - return daoSession.getSchoolDao().queryBuilder().where( - SchoolDao.Properties.SymbolId.eq(symbol.getId()), - SchoolDao.Properties.Current.eq(true) - ).unique(); - } - - private Student insertStudents(School school) throws VulcanException, IOException { - List studentList = DataObjectConverter.studentsToStudentEntities( - vulcan.getStudentAndParent().getStudents(), - school.getId() - ); - Timber.d("Register students (%s)", studentList.size()); - daoSession.getStudentDao().insertInTx(studentList); - - return daoSession.getStudentDao().queryBuilder().where( - StudentDao.Properties.SchoolId.eq(school.getId()), - StudentDao.Properties.Current.eq(true) - ).unique(); - } - - private Diary insertDiaries(Student student) throws VulcanException, IOException { - List diaryList = DataObjectConverter.diariesToDiaryEntities( - vulcan.getStudentAndParent().getDiaries(), - student.getId() - ); - Timber.d("Register diaries (%s)", diaryList.size()); - daoSession.getDiaryDao().insertInTx(diaryList); - - return daoSession.getDiaryDao().queryBuilder().where( - DiaryDao.Properties.StudentId.eq(student.getId()), - DiaryDao.Properties.Current.eq(true) - ).unique(); - } - - private void insertSemesters(Diary diary) throws VulcanException, IOException { - List semesterList = DataObjectConverter.semestersToSemesterEntities( - vulcan.getStudentAndParent().getSemesters(), - diary.getId() - ); - Timber.d("Register semesters (%s)", semesterList.size()); - daoSession.getSemesterDao().insertInTx(semesterList); - } - - public void initLastUser() throws ScramblerException { - - long userId = sharedPref.getCurrentUserId(); - - if (userId == 0) { - throw new NotRegisteredUserException("Can't find user id in SharedPreferences"); - } - - Timber.d("Init current user (%s)", userId); - - Account account = daoSession.getAccountDao().load(userId); - - Symbol symbol = daoSession.getSymbolDao().queryBuilder().where( - SymbolDao.Properties.UserId.eq(account.getId())).unique(); - - School school = daoSession.getSchoolDao().queryBuilder().where( - SchoolDao.Properties.SymbolId.eq(symbol.getId())).unique(); - - Student student = daoSession.getStudentDao().queryBuilder().where( - StudentDao.Properties.SchoolId.eq(school.getId()), - StudentDao.Properties.Current.eq(true) - ).unique(); - - Diary diary = daoSession.getDiaryDao().queryBuilder().where( - DiaryDao.Properties.StudentId.eq(student.getId()), - DiaryDao.Properties.Current.eq(true) - ).unique(); - - vulcan.setCredentials( - account.getEmail(), - Scrambler.decrypt(account.getPassword()), - symbol.getSymbol(), - school.getRealId(), - student.getRealId(), - diary.getValue() - ); - } - - private void clearUserData() { - Database database = daoSession.getDatabase(); - DaoMaster.dropAllTables(database, true); - DaoMaster.createAllTables(database, true); - sharedPref.setCurrentUserId(0); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/sync/AttendanceSync.java b/app/src/main/java/io/github/wulkanowy/data/sync/AttendanceSync.java deleted file mode 100644 index 18769418..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/sync/AttendanceSync.java +++ /dev/null @@ -1,140 +0,0 @@ -package io.github.wulkanowy.data.sync; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import io.github.wulkanowy.api.Vulcan; -import io.github.wulkanowy.api.VulcanException; -import io.github.wulkanowy.api.generic.Lesson; -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.DaoSession; -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.Week; -import io.github.wulkanowy.data.db.dao.entities.WeekDao; -import io.github.wulkanowy.utils.DataObjectConverter; -import timber.log.Timber; - -@Singleton -public class AttendanceSync { - - private final DaoSession daoSession; - - private final Vulcan vulcan; - - private long diaryId; - - @Inject - AttendanceSync(DaoSession daoSession, Vulcan vulcan) { - this.daoSession = daoSession; - this.vulcan = vulcan; - } - - public void syncAttendance(long diaryId, String date) throws IOException, VulcanException { - this.diaryId = diaryId; - - io.github.wulkanowy.api.generic.Week weekApi = getWeekFromApi(date); - Week weekDb = getWeekFromDb(weekApi.getStartDayDate()); - - long weekId = updateWeekInDb(weekDb, weekApi); - - List lessonList = updateDays(weekApi.getDays(), weekId); - - daoSession.getAttendanceLessonDao().saveInTx(lessonList); - - Timber.d("Attendance synchronization complete (%s)", lessonList.size()); - } - - private io.github.wulkanowy.api.generic.Week getWeekFromApi(String date) - throws IOException, VulcanException { - return vulcan.getAttendanceTable().getWeekTable(date); - } - - private Week getWeekFromDb(String date) { - return daoSession.getWeekDao().queryBuilder().where( - WeekDao.Properties.DiaryId.eq(diaryId), - WeekDao.Properties.StartDayDate.eq(date) - ).unique(); - } - - private Long updateWeekInDb(Week dbWeekEntity, io.github.wulkanowy.api.generic.Week fromApi) { - if (dbWeekEntity != null) { - dbWeekEntity.setAttendanceSynced(true); - dbWeekEntity.update(); - - return dbWeekEntity.getId(); - } - - Week apiWeekEntity = DataObjectConverter.weekToWeekEntity(fromApi).setDiaryId(diaryId); - apiWeekEntity.setAttendanceSynced(true); - - return daoSession.getWeekDao().insert(apiWeekEntity); - } - - private List updateDays(List dayListFromApi, long weekId) { - List updatedLessonList = new ArrayList<>(); - - for (io.github.wulkanowy.api.generic.Day dayFromApi : dayListFromApi) { - - Day dbDayEntity = getDayFromDb(dayFromApi.getDate(), weekId); - - Day apiDayEntity = DataObjectConverter.dayToDayEntity(dayFromApi); - - long dayId = updateDay(dbDayEntity, apiDayEntity, weekId); - - updateLessons(dayFromApi.getLessons(), updatedLessonList, dayId); - } - - return updatedLessonList; - } - - private Day getDayFromDb(String date, long weekId) { - return daoSession.getDayDao().queryBuilder() - .where( - DayDao.Properties.WeekId.eq(weekId), - DayDao.Properties.Date.eq(date) - ).unique(); - } - - private long updateDay(Day dbDayEntity, Day apiDayEntity, long weekId) { - if (null != dbDayEntity) { - return dbDayEntity.getId(); - } - - apiDayEntity.setWeekId(weekId); - - return daoSession.getDayDao().insert(apiDayEntity); - } - - private void updateLessons(List lessons, List updatedLessons, long dayId) { - List lessonsFromApiEntities = DataObjectConverter - .lessonsToAttendanceLessonsEntities(lessons); - - for (AttendanceLesson apiLessonEntity : lessonsFromApiEntities) { - AttendanceLesson lessonFromDb = getLessonFromDb(apiLessonEntity, dayId); - - apiLessonEntity.setDayId(dayId); - - if (lessonFromDb != null) { - apiLessonEntity.setId(lessonFromDb.getId()); - } - - if (!"".equals(apiLessonEntity.getSubject())) { - updatedLessons.add(apiLessonEntity); - } - } - } - - private AttendanceLesson getLessonFromDb(AttendanceLesson apiEntity, long dayId) { - return daoSession.getAttendanceLessonDao().queryBuilder() - .where(AttendanceLessonDao.Properties.DayId.eq(dayId), - AttendanceLessonDao.Properties.Date.eq(apiEntity.getDate()), - AttendanceLessonDao.Properties.Number.eq(apiEntity.getNumber())) - .unique(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/sync/ExamsSync.java b/app/src/main/java/io/github/wulkanowy/data/sync/ExamsSync.java deleted file mode 100644 index db473092..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/sync/ExamsSync.java +++ /dev/null @@ -1,135 +0,0 @@ -package io.github.wulkanowy.data.sync; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import io.github.wulkanowy.api.Vulcan; -import io.github.wulkanowy.api.VulcanException; -import io.github.wulkanowy.api.exams.ExamDay; -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.DayDao; -import io.github.wulkanowy.data.db.dao.entities.Exam; -import io.github.wulkanowy.data.db.dao.entities.ExamDao; -import io.github.wulkanowy.data.db.dao.entities.Week; -import io.github.wulkanowy.data.db.dao.entities.WeekDao; -import io.github.wulkanowy.utils.DataObjectConverter; -import timber.log.Timber; - -public class ExamsSync { - - private final DaoSession daoSession; - - private final Vulcan vulcan; - - private long diaryId; - - @Inject - ExamsSync(DaoSession daoSession, Vulcan vulcan) { - this.daoSession = daoSession; - this.vulcan = vulcan; - } - - public void syncExams(long diaryId, String date) throws IOException, VulcanException { - this.diaryId = diaryId; - - io.github.wulkanowy.api.generic.Week weekApi = getWeekFromApi(date); - Week weekDb = getWeekFromDb(weekApi.getStartDayDate()); - - long weekId = updateWeekInDb(weekDb, weekApi); - - List examList = getPreparedExams(weekApi.getDays(), weekId); - - daoSession.getExamDao().saveInTx(examList); - - Timber.d("Exams synchronization complete (%s)", examList.size()); - } - - private Week getWeekFromDb(String date) { - return daoSession.getWeekDao().queryBuilder().where( - WeekDao.Properties.DiaryId.eq(diaryId), - WeekDao.Properties.StartDayDate.eq(date) - ).unique(); - } - - private io.github.wulkanowy.api.generic.Week getWeekFromApi(String date) - throws VulcanException, IOException { - return vulcan.getExamsList().getWeek(date, true); - } - - private Long updateWeekInDb(Week weekDb, io.github.wulkanowy.api.generic.Week weekApi) { - if (weekDb != null) { - weekDb.setExamsSynced(true); - weekDb.update(); - - return weekDb.getId(); - } - - Week weekApiEntity = DataObjectConverter.weekToWeekEntity(weekApi).setDiaryId(diaryId); - weekApiEntity.setExamsSynced(true); - - return daoSession.getWeekDao().insert(weekApiEntity); - } - - private Day getDayFromDb(String date, long weekId) { - return daoSession.getDayDao().queryBuilder().where( - DayDao.Properties.WeekId.eq(weekId), - DayDao.Properties.Date.eq(date) - ).unique(); - } - - private List getPreparedExams(List dayListFromApi, - long weekId) { - List preparedExamList = new ArrayList<>(); - - for (ExamDay dayFromApi : dayListFromApi) { - - Day dayDb = getDayFromDb(dayFromApi.getDate(), weekId); - - Day dayApiEntity = DataObjectConverter.dayToDayEntity(dayFromApi); - - long dayId = updateDayInDb(dayDb, dayApiEntity, weekId); - - prepareExam(dayFromApi.getExamList(), preparedExamList, dayId); - } - return preparedExamList; - } - - private long updateDayInDb(Day dayDb, Day dayApi, long weekId) { - dayApi.setWeekId(weekId); - - if (null != dayDb) { - return dayDb.getId(); - } - return daoSession.getDayDao().insert(dayApi); - } - - private void prepareExam(List examList, - List preparedExams, long dayId) { - List examsApiEntity = DataObjectConverter.examsToExamsEntity(examList); - - for (Exam examApi : examsApiEntity) { - Exam examDb = getExamFromDb(examApi, dayId); - - examApi.setDayId(dayId); - - if (examDb != null) { - examApi.setId(examDb.getId()); - } - preparedExams.add(examApi); - } - } - - private Exam getExamFromDb(Exam examApi, long dayId) { - return daoSession.getExamDao().queryBuilder() - .where(ExamDao.Properties.DayId.eq(dayId), - ExamDao.Properties.EntryDate.eq(examApi.getEntryDate()), - ExamDao.Properties.SubjectAndGroup.eq(examApi.getSubjectAndGroup()), - ExamDao.Properties.Type.eq(examApi.getType()), - ExamDao.Properties.Teacher.eq(examApi.getTeacher())) - .unique(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/sync/GradeSync.java b/app/src/main/java/io/github/wulkanowy/data/sync/GradeSync.java deleted file mode 100644 index 59a71845..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/sync/GradeSync.java +++ /dev/null @@ -1,81 +0,0 @@ -package io.github.wulkanowy.data.sync; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import io.github.wulkanowy.api.Vulcan; -import io.github.wulkanowy.api.VulcanException; -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.Semester; -import io.github.wulkanowy.data.db.dao.entities.SubjectDao; -import io.github.wulkanowy.utils.DataObjectConverter; -import io.github.wulkanowy.utils.EntitiesCompare; -import timber.log.Timber; - -@Singleton -public class GradeSync { - - private final DaoSession daoSession; - - private final Vulcan vulcan; - - private long semesterId; - - @Inject - GradeSync(DaoSession daoSession, Vulcan vulcan) { - this.daoSession = daoSession; - this.vulcan = vulcan; - } - - public void sync(long semesterId) throws IOException, VulcanException { - this.semesterId = semesterId; - - Semester semester = daoSession.getSemesterDao().load(semesterId); - resetSemesterRelations(semester); - - List lastList = getUpdatedList(getComparedList(semester)); - - daoSession.getGradeDao().deleteInTx(semester.getGradeList()); - daoSession.getGradeDao().insertInTx(lastList); - - Timber.d("Grades synchronization complete (%s)", lastList.size()); - } - - private void resetSemesterRelations(Semester semester) { - semester.resetSubjectList(); - semester.resetGradeList(); - } - - private List getUpdatedList(List comparedList) { - List updatedList = new ArrayList<>(); - - for (Grade grade : comparedList) { - grade.setSemesterId(semesterId); - grade.setSubjectId(getSubjectId(grade.getSubject())); - updatedList.add(grade); - } - - return updatedList; - } - - private List getComparedList(Semester semester) throws IOException, VulcanException { - List gradesFromNet = DataObjectConverter.gradesToGradeEntities( - vulcan.getGradesList().getAll(semester.getValue()), semesterId); - - List gradesFromDb = semester.getGradeList(); - - return EntitiesCompare.compareGradeList(gradesFromNet, gradesFromDb); - } - - private Long getSubjectId(String subjectName) { - return daoSession.getSubjectDao().queryBuilder().where( - SubjectDao.Properties.Name.eq(subjectName), - SubjectDao.Properties.SemesterId.eq(semesterId) - ).build().uniqueOrThrow().getId(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/sync/NotRegisteredUserException.java b/app/src/main/java/io/github/wulkanowy/data/sync/NotRegisteredUserException.java deleted file mode 100644 index ddba1a21..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/sync/NotRegisteredUserException.java +++ /dev/null @@ -1,8 +0,0 @@ -package io.github.wulkanowy.data.sync; - -public class NotRegisteredUserException extends RuntimeException { - - public NotRegisteredUserException(String message) { - super(message); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/sync/SubjectSync.java b/app/src/main/java/io/github/wulkanowy/data/sync/SubjectSync.java deleted file mode 100644 index 1d0300d6..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/sync/SubjectSync.java +++ /dev/null @@ -1,66 +0,0 @@ -package io.github.wulkanowy.data.sync; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import io.github.wulkanowy.api.Vulcan; -import io.github.wulkanowy.api.VulcanException; -import io.github.wulkanowy.data.db.dao.entities.DaoSession; -import io.github.wulkanowy.data.db.dao.entities.Semester; -import io.github.wulkanowy.data.db.dao.entities.Subject; -import io.github.wulkanowy.utils.DataObjectConverter; -import timber.log.Timber; - -@Singleton -public class SubjectSync { - - private final DaoSession daoSession; - - private final Vulcan vulcan; - - private long semesterId; - - @Inject - SubjectSync(DaoSession daoSession, Vulcan vulcan) { - this.daoSession = daoSession; - this.vulcan = vulcan; - } - - public void sync(long semesterId) throws VulcanException, IOException { - this.semesterId = semesterId; - - Semester semester = daoSession.getSemesterDao().load(semesterId); - - List lastList = getUpdatedList(getSubjectsFromNet(semester)); - - daoSession.getSubjectDao().deleteInTx(getSubjectsFromDb()); - daoSession.getSubjectDao().insertInTx(lastList); - - Timber.d("Subjects synchronization complete (%s)", lastList.size()); - } - - private List getSubjectsFromNet(Semester semester) throws VulcanException, IOException { - return DataObjectConverter.subjectsToSubjectEntities( - vulcan.getSubjectsList().getAll(semester.getValue()), semesterId); - } - - private List getSubjectsFromDb() { - Semester semester = daoSession.getSemesterDao().load(semesterId); - semester.resetSubjectList(); - return semester.getSubjectList(); - } - - private List getUpdatedList(List subjectsFromNet) { - List updatedList = new ArrayList<>(); - - for (Subject subject : subjectsFromNet) { - subject.setSemesterId(semesterId); - updatedList.add(subject); - } - return updatedList; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/sync/SyncContract.java b/app/src/main/java/io/github/wulkanowy/data/sync/SyncContract.java deleted file mode 100644 index 6f4df657..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/sync/SyncContract.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.github.wulkanowy.data.sync; - -import java.io.IOException; -import java.text.ParseException; - -import javax.inject.Singleton; - -import io.github.wulkanowy.api.VulcanException; -import io.github.wulkanowy.utils.security.ScramblerException; - -@Singleton -public interface SyncContract { - - void registerUser(String email, String password, String symbol) throws VulcanException, - IOException, ScramblerException; - - void initLastUser() throws IOException, ScramblerException; - - - void syncGrades(int semesterName) throws VulcanException, IOException, ParseException; - - void syncGrades() throws VulcanException, IOException, ParseException; - - void syncSubjects(int semesterName) throws VulcanException, IOException; - - void syncSubjects() throws VulcanException, IOException; - - void syncAttendance() throws ParseException, IOException, VulcanException; - - void syncAttendance(long diaryId, String date) throws ParseException, IOException, VulcanException; - - void syncTimetable() throws VulcanException, IOException, ParseException; - - void syncTimetable(long diaryId, String date) throws VulcanException, IOException, ParseException; - - void syncExams() throws VulcanException, IOException, ParseException; - - void syncExams(long diaryId, String date) throws VulcanException, IOException, ParseException; - - void syncAll() throws VulcanException, IOException, ParseException; -} diff --git a/app/src/main/java/io/github/wulkanowy/data/sync/SyncRepository.java b/app/src/main/java/io/github/wulkanowy/data/sync/SyncRepository.java deleted file mode 100644 index eb6b4454..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/sync/SyncRepository.java +++ /dev/null @@ -1,123 +0,0 @@ -package io.github.wulkanowy.data.sync; - -import java.io.IOException; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import io.github.wulkanowy.api.VulcanException; -import io.github.wulkanowy.data.db.dao.DbContract; -import io.github.wulkanowy.utils.security.ScramblerException; - -@Singleton -public class SyncRepository implements SyncContract { - - private final GradeSync gradeSync; - - private final SubjectSync subjectSync; - - private final AttendanceSync attendanceSync; - - private final TimetableSync timetableSync; - - private final AccountSync accountSync; - - private final ExamsSync examsSync; - - private final DbContract database; - - @Inject - SyncRepository(GradeSync gradeSync, SubjectSync subjectSync, AttendanceSync attendanceSync, - TimetableSync timetableSync, AccountSync accountSync, ExamsSync examsSync, - DbContract database) { - this.gradeSync = gradeSync; - this.subjectSync = subjectSync; - this.attendanceSync = attendanceSync; - this.timetableSync = timetableSync; - this.accountSync = accountSync; - this.examsSync = examsSync; - this.database = database; - } - - @Override - public void registerUser(String email, String password, String symbol) throws VulcanException, - IOException, ScramblerException { - accountSync.registerUser(email, password, symbol); - } - - @Override - public void initLastUser() throws ScramblerException { - accountSync.initLastUser(); - } - - @Override - public void syncGrades(int semesterName) throws VulcanException, IOException { - gradeSync.sync(semesterName); - } - - @Override - public void syncGrades() throws VulcanException, IOException { - gradeSync.sync(database.getCurrentSemesterId()); - } - - @Override - public void syncSubjects(int semesterName) throws VulcanException, IOException { - subjectSync.sync(semesterName); - } - - @Override - public void syncSubjects() throws VulcanException, IOException { - subjectSync.sync(database.getCurrentSemesterId()); - } - - @Override - public void syncAttendance() throws IOException, VulcanException { - attendanceSync.syncAttendance(database.getCurrentDiaryId(), null); - } - - @Override - public void syncAttendance(long diaryId, String date) throws IOException, VulcanException { - if (diaryId != 0) { - attendanceSync.syncAttendance(diaryId, date); - } else { - attendanceSync.syncAttendance(database.getCurrentDiaryId(), date); - } - } - - @Override - public void syncTimetable() throws VulcanException, IOException { - timetableSync.syncTimetable(database.getCurrentDiaryId(), null); - } - - @Override - public void syncTimetable(long diaryId, String date) throws VulcanException, IOException { - if (diaryId != 0) { - timetableSync.syncTimetable(diaryId, date); - } else { - timetableSync.syncTimetable(database.getCurrentDiaryId(), date); - } - } - - @Override - public void syncExams() throws VulcanException, IOException { - examsSync.syncExams(database.getCurrentDiaryId(), null); - } - - @Override - public void syncExams(long diaryId, String date) throws VulcanException, IOException { - if (diaryId != 0) { - examsSync.syncExams(diaryId, date); - } else { - examsSync.syncExams(database.getCurrentDiaryId(), date); - } - } - - @Override - public void syncAll() throws VulcanException, IOException { - syncSubjects(); - syncGrades(); - syncAttendance(); - syncTimetable(); - syncExams(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/data/sync/TimetableSync.java b/app/src/main/java/io/github/wulkanowy/data/sync/TimetableSync.java deleted file mode 100644 index 1ea2fa48..00000000 --- a/app/src/main/java/io/github/wulkanowy/data/sync/TimetableSync.java +++ /dev/null @@ -1,161 +0,0 @@ -package io.github.wulkanowy.data.sync; - -import org.apache.commons.collections4.CollectionUtils; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import io.github.wulkanowy.api.Vulcan; -import io.github.wulkanowy.api.VulcanException; -import io.github.wulkanowy.api.generic.Lesson; -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.DayDao; -import io.github.wulkanowy.data.db.dao.entities.TimetableLesson; -import io.github.wulkanowy.data.db.dao.entities.TimetableLessonDao; -import io.github.wulkanowy.data.db.dao.entities.Week; -import io.github.wulkanowy.data.db.dao.entities.WeekDao; -import io.github.wulkanowy.utils.DataObjectConverter; -import timber.log.Timber; - -@Singleton -public class TimetableSync { - - private final DaoSession daoSession; - - private final Vulcan vulcan; - - private long diaryId; - - @Inject - TimetableSync(DaoSession daoSession, Vulcan vulcan) { - this.daoSession = daoSession; - this.vulcan = vulcan; - } - - public void syncTimetable(long diaryId, String date) throws IOException, VulcanException { - this.diaryId = diaryId; - - io.github.wulkanowy.api.generic.Week weekApi = getWeekFromApi(date); - Week weekDb = getWeekFromDb(weekApi.getStartDayDate()); - - long weekId = updateWeekInDb(weekDb, weekApi); - - List lessonList = updateDays(weekApi.getDays(), weekId); - - daoSession.getTimetableLessonDao().saveInTx(lessonList); - - Timber.d("Timetable synchronization complete (%s)", lessonList.size()); - } - - private io.github.wulkanowy.api.generic.Week getWeekFromApi(String date) - throws IOException, VulcanException { - return vulcan.getTimetable().getWeekTable(date); - } - - private Week getWeekFromDb(String date) { - return daoSession.getWeekDao().queryBuilder().where( - WeekDao.Properties.DiaryId.eq(diaryId), - WeekDao.Properties.StartDayDate.eq(date) - ).unique(); - } - - private Long updateWeekInDb(Week dbEntity, io.github.wulkanowy.api.generic.Week fromApi) { - if (dbEntity != null) { - dbEntity.setTimetableSynced(true); - dbEntity.update(); - - return dbEntity.getId(); - } - - Week apiEntity = DataObjectConverter.weekToWeekEntity(fromApi).setDiaryId(diaryId); - apiEntity.setTimetableSynced(true); - - return daoSession.getWeekDao().insert(apiEntity); - } - - private List updateDays(List dayListFromApi, long weekId) { - List updatedLessonList = new ArrayList<>(); - - for (io.github.wulkanowy.api.timetable.TimetableDay dayFromApi : dayListFromApi) { - - Day dbDayEntity = getDayFromDb(dayFromApi.getDate(), weekId); - - Day apiDayEntity = DataObjectConverter.timetableDayToDayEntity(dayFromApi); - - long dayId = updateDay(dbDayEntity, apiDayEntity, weekId); - - updateLessons(dayFromApi.getLessons(), updatedLessonList, dayId); - } - - return updatedLessonList; - } - - private Day getDayFromDb(String date, long weekId) { - return daoSession.getDayDao().queryBuilder().where( - DayDao.Properties.WeekId.eq(weekId), - DayDao.Properties.Date.eq(date) - ).unique(); - } - - private long updateDay(Day dayFromDb, Day apiDayEntity, long weekId) { - apiDayEntity.setWeekId(weekId); - - if (null != dayFromDb) { - apiDayEntity.setId(dayFromDb.getId()); - - daoSession.getDayDao().save(apiDayEntity); - dayFromDb.refresh(); - - return dayFromDb.getId(); - } - - return daoSession.getDayDao().insert(apiDayEntity); - } - - private void updateLessons(List lessons, List updatedLessons, long dayId) { - List lessonsFromApiEntities = DataObjectConverter - .lessonsToTimetableLessonsEntities(lessons); - - List lessonsFromDbEntities = getLessonsFromDb(dayId); - - if (!lessonsFromDbEntities.isEmpty()) { - List lessonToRemove = new ArrayList<>(CollectionUtils.removeAll(lessonsFromDbEntities, lessonsFromApiEntities)); - - for (TimetableLesson timetableLesson : lessonToRemove) { - daoSession.getTimetableLessonDao().delete(timetableLesson); - } - } - - for (TimetableLesson apiLessonEntity : lessonsFromApiEntities) { - TimetableLesson lessonFromDb = getLessonFromDb(apiLessonEntity, dayId); - - apiLessonEntity.setDayId(dayId); - - if (lessonFromDb != null) { - apiLessonEntity.setId(lessonFromDb.getId()); - } - - if (!"".equals(apiLessonEntity.getSubject())) { - updatedLessons.add(apiLessonEntity); - } - } - } - - private TimetableLesson getLessonFromDb(TimetableLesson apiEntity, long dayId) { - return daoSession.getTimetableLessonDao().queryBuilder() - .where(TimetableLessonDao.Properties.DayId.eq(dayId), - TimetableLessonDao.Properties.Date.eq(apiEntity.getDate()), - TimetableLessonDao.Properties.StartTime.eq(apiEntity.getStartTime()), - TimetableLessonDao.Properties.EndTime.eq(apiEntity.getEndTime())) - .unique(); - } - - private List getLessonsFromDb(long dayId) { - return daoSession.getDayDao().load(dayId).getTimetableLessons(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/di/AppComponent.java b/app/src/main/java/io/github/wulkanowy/di/AppComponent.java deleted file mode 100644 index 92f5d9a1..00000000 --- a/app/src/main/java/io/github/wulkanowy/di/AppComponent.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.github.wulkanowy.di; - -import javax.inject.Singleton; - -import dagger.Component; -import dagger.android.AndroidInjector; -import dagger.android.support.AndroidSupportInjectionModule; -import io.github.wulkanowy.WulkanowyApp; - -@Singleton -@Component(modules = { - AndroidSupportInjectionModule.class, - AppModule.class, - BuilderModule.class -}) -public interface AppComponent extends AndroidInjector { - @Component.Builder - abstract class Builder extends AndroidInjector.Builder { - } -} diff --git a/app/src/main/java/io/github/wulkanowy/di/AppComponent.kt b/app/src/main/java/io/github/wulkanowy/di/AppComponent.kt new file mode 100644 index 00000000..21c193e5 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/di/AppComponent.kt @@ -0,0 +1,20 @@ +package io.github.wulkanowy.di + +import dagger.Component +import dagger.android.AndroidInjector +import dagger.android.support.AndroidSupportInjectionModule +import io.github.wulkanowy.WulkanowyApp +import io.github.wulkanowy.data.RepositoryModule +import javax.inject.Singleton + +@Singleton +@Component(modules = [ + AndroidSupportInjectionModule::class, + AppModule::class, + RepositoryModule::class, + BuilderModule::class]) +interface AppComponent : AndroidInjector { + + @Component.Builder + abstract class Builder : AndroidInjector.Builder() +} diff --git a/app/src/main/java/io/github/wulkanowy/di/AppModule.java b/app/src/main/java/io/github/wulkanowy/di/AppModule.java deleted file mode 100644 index d6d4dfa2..00000000 --- a/app/src/main/java/io/github/wulkanowy/di/AppModule.java +++ /dev/null @@ -1,78 +0,0 @@ -package io.github.wulkanowy.di; - -import android.content.Context; - -import javax.inject.Named; -import javax.inject.Singleton; - -import dagger.Binds; -import dagger.Module; -import dagger.Provides; -import io.github.wulkanowy.WulkanowyApp; -import io.github.wulkanowy.api.Vulcan; -import io.github.wulkanowy.data.Repository; -import io.github.wulkanowy.data.RepositoryContract; -import io.github.wulkanowy.data.db.dao.DbContract; -import io.github.wulkanowy.data.db.dao.DbHelper; -import io.github.wulkanowy.data.db.dao.DbRepository; -import io.github.wulkanowy.data.db.dao.entities.DaoMaster; -import io.github.wulkanowy.data.db.dao.entities.DaoSession; -import io.github.wulkanowy.data.db.resources.ResourcesContract; -import io.github.wulkanowy.data.db.resources.ResourcesRepository; -import io.github.wulkanowy.data.db.shared.SharedPrefContract; -import io.github.wulkanowy.data.db.shared.SharedPrefRepository; -import io.github.wulkanowy.data.sync.SyncContract; -import io.github.wulkanowy.data.sync.SyncRepository; -import io.github.wulkanowy.utils.AppConstant; - -@Module -public abstract class AppModule { - - @Binds - abstract Context provideContext(WulkanowyApp app); - - @Singleton - @Binds - abstract RepositoryContract provideRepository(Repository repository); - - @Singleton - @Binds - abstract DbContract provideDatabse(DbRepository dbRepository); - - @Singleton - @Binds - abstract SharedPrefContract provideSharedPref(SharedPrefRepository sharedPrefRepository); - - @Singleton - @Binds - abstract SyncContract provideSync(SyncRepository syncRepository); - - @Singleton - @Binds - abstract ResourcesContract provideResources(ResourcesRepository resourcesRepository); - - @Singleton - @Provides - static DaoSession provideDaoSession(DbHelper dbHelper) { - return new DaoMaster(dbHelper.getWritableDb()).newSession(); - } - - @Singleton - @Provides - static Vulcan provideVulcan() { - return new Vulcan(); - } - - @Provides - @Named("dbName") - static String provideDbName() { - return AppConstant.DATABASE_NAME; - } - - @Provides - @Named("sharedPrefName") - static String provideSharedPrefName() { - return AppConstant.SHARED_PREFERENCES_NAME; - } - -} diff --git a/app/src/main/java/io/github/wulkanowy/di/AppModule.kt b/app/src/main/java/io/github/wulkanowy/di/AppModule.kt new file mode 100644 index 00000000..430b5c29 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/di/AppModule.kt @@ -0,0 +1,33 @@ +package io.github.wulkanowy.di + +import android.content.Context +import com.firebase.jobdispatcher.FirebaseJobDispatcher +import com.firebase.jobdispatcher.GooglePlayDriver +import dagger.Module +import dagger.Provides +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import io.github.wulkanowy.WulkanowyApp +import io.github.wulkanowy.utils.SchedulersProvider +import javax.inject.Singleton + +@Module +internal class AppModule { + + @Singleton + @Provides + fun provideContext(app: WulkanowyApp): Context = app + + @Singleton + @Provides + fun provideSchedulersProvider() = SchedulersProvider() + + @Provides + fun provideFlexibleAdapter() = FlexibleAdapter>(null, null, true) + + @Singleton + @Provides + fun provideJobDispatcher(context: Context): FirebaseJobDispatcher { + return FirebaseJobDispatcher(GooglePlayDriver(context)) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/di/BuilderModule.java b/app/src/main/java/io/github/wulkanowy/di/BuilderModule.java deleted file mode 100644 index 74b77d52..00000000 --- a/app/src/main/java/io/github/wulkanowy/di/BuilderModule.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.github.wulkanowy.di; - -import dagger.Module; -import dagger.android.ContributesAndroidInjector; -import io.github.wulkanowy.di.scopes.PerActivity; -import io.github.wulkanowy.services.jobs.SyncJob; -import io.github.wulkanowy.services.widgets.TimetableWidgetServices; -import io.github.wulkanowy.ui.login.LoginActivity; -import io.github.wulkanowy.ui.login.LoginModule; -import io.github.wulkanowy.ui.main.MainActivity; -import io.github.wulkanowy.ui.main.MainModule; -import io.github.wulkanowy.ui.splash.SplashActivity; -import io.github.wulkanowy.ui.splash.SplashModule; -import io.github.wulkanowy.ui.widgets.TimetableWidgetProvider; - -@Module -abstract class BuilderModule { - - @PerActivity - @ContributesAndroidInjector(modules = SplashModule.class) - abstract SplashActivity bindSplashActivity(); - - @PerActivity - @ContributesAndroidInjector(modules = LoginModule.class) - abstract LoginActivity bindLoginActivity(); - - @PerActivity - @ContributesAndroidInjector(modules = MainModule.class) - abstract MainActivity bindMainActivity(); - - @ContributesAndroidInjector - abstract SyncJob bindSyncJob(); - - @ContributesAndroidInjector - abstract TimetableWidgetServices bindTimetableWidgetServices(); - - @ContributesAndroidInjector - abstract TimetableWidgetProvider bindTimetableWidgetProvider(); -} diff --git a/app/src/main/java/io/github/wulkanowy/di/BuilderModule.kt b/app/src/main/java/io/github/wulkanowy/di/BuilderModule.kt new file mode 100644 index 00000000..9f4ecb80 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/di/BuilderModule.kt @@ -0,0 +1,38 @@ +package io.github.wulkanowy.di + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import io.github.wulkanowy.di.scopes.PerActivity +import io.github.wulkanowy.services.job.SyncWorker +import io.github.wulkanowy.services.widgets.TimetableWidgetService +import io.github.wulkanowy.ui.modules.login.LoginActivity +import io.github.wulkanowy.ui.modules.login.LoginModule +import io.github.wulkanowy.ui.modules.main.MainActivity +import io.github.wulkanowy.ui.modules.main.MainModule +import io.github.wulkanowy.ui.modules.splash.SplashActivity +import io.github.wulkanowy.ui.widgets.timetable.TimetableWidgetProvider + +@Module +internal abstract class BuilderModule { + + @PerActivity + @ContributesAndroidInjector() + abstract fun bindSplashActivity(): SplashActivity + + @PerActivity + @ContributesAndroidInjector(modules = [LoginModule::class]) + abstract fun bindLoginActivity(): LoginActivity + + @PerActivity + @ContributesAndroidInjector(modules = [MainModule::class]) + abstract fun bindMainActivity(): MainActivity + + @ContributesAndroidInjector + abstract fun bindTimetableWidgetService(): TimetableWidgetService + + @ContributesAndroidInjector + abstract fun bindTimetableWidgetProvider(): TimetableWidgetProvider + + @ContributesAndroidInjector + abstract fun bindSyncJob(): SyncWorker +} diff --git a/app/src/main/java/io/github/wulkanowy/di/scopes/PerActivity.java b/app/src/main/java/io/github/wulkanowy/di/scopes/PerActivity.java deleted file mode 100644 index c9fc8a5b..00000000 --- a/app/src/main/java/io/github/wulkanowy/di/scopes/PerActivity.java +++ /dev/null @@ -1,11 +0,0 @@ -package io.github.wulkanowy.di.scopes; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -import javax.inject.Scope; - -@Scope -@Retention(RetentionPolicy.RUNTIME) -public @interface PerActivity { -} diff --git a/app/src/main/java/io/github/wulkanowy/di/scopes/PerActivity.kt b/app/src/main/java/io/github/wulkanowy/di/scopes/PerActivity.kt new file mode 100644 index 00000000..c1b4352a --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/di/scopes/PerActivity.kt @@ -0,0 +1,7 @@ +package io.github.wulkanowy.di.scopes + +import javax.inject.Scope + +@Scope +@Retention(AnnotationRetention.RUNTIME) +annotation class PerActivity diff --git a/app/src/main/java/io/github/wulkanowy/di/scopes/PerChildFragment.java b/app/src/main/java/io/github/wulkanowy/di/scopes/PerChildFragment.java deleted file mode 100644 index 67a9f820..00000000 --- a/app/src/main/java/io/github/wulkanowy/di/scopes/PerChildFragment.java +++ /dev/null @@ -1,11 +0,0 @@ -package io.github.wulkanowy.di.scopes; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -import javax.inject.Scope; - -@Scope -@Retention(RetentionPolicy.RUNTIME) -public @interface PerChildFragment { -} diff --git a/app/src/main/java/io/github/wulkanowy/di/scopes/PerChildFragment.kt b/app/src/main/java/io/github/wulkanowy/di/scopes/PerChildFragment.kt new file mode 100644 index 00000000..08884dac --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/di/scopes/PerChildFragment.kt @@ -0,0 +1,7 @@ +package io.github.wulkanowy.di.scopes + +import javax.inject.Scope + +@Scope +@Retention(AnnotationRetention.RUNTIME) +annotation class PerChildFragment diff --git a/app/src/main/java/io/github/wulkanowy/di/scopes/PerFragment.java b/app/src/main/java/io/github/wulkanowy/di/scopes/PerFragment.java deleted file mode 100644 index a4d37c38..00000000 --- a/app/src/main/java/io/github/wulkanowy/di/scopes/PerFragment.java +++ /dev/null @@ -1,11 +0,0 @@ -package io.github.wulkanowy.di.scopes; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -import javax.inject.Scope; - -@Scope -@Retention(RetentionPolicy.RUNTIME) -public @interface PerFragment { -} diff --git a/app/src/main/java/io/github/wulkanowy/di/scopes/PerFragment.kt b/app/src/main/java/io/github/wulkanowy/di/scopes/PerFragment.kt new file mode 100644 index 00000000..1203d7d8 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/di/scopes/PerFragment.kt @@ -0,0 +1,7 @@ +package io.github.wulkanowy.di.scopes + +import javax.inject.Scope + +@Scope +@Retention(AnnotationRetention.RUNTIME) +annotation class PerFragment diff --git a/app/src/main/java/io/github/wulkanowy/services/job/ServiceHelper.kt b/app/src/main/java/io/github/wulkanowy/services/job/ServiceHelper.kt new file mode 100644 index 00000000..ab88edd8 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/services/job/ServiceHelper.kt @@ -0,0 +1,57 @@ +package io.github.wulkanowy.services.job + +import com.firebase.jobdispatcher.Constraint.ON_ANY_NETWORK +import com.firebase.jobdispatcher.Constraint.ON_UNMETERED_NETWORK +import com.firebase.jobdispatcher.FirebaseJobDispatcher +import com.firebase.jobdispatcher.Lifetime.FOREVER +import com.firebase.jobdispatcher.RetryStrategy.DEFAULT_EXPONENTIAL +import com.firebase.jobdispatcher.Trigger.executionWindow +import io.github.wulkanowy.data.repositories.PreferencesRepository +import io.github.wulkanowy.utils.isHolidays +import org.threeten.bp.LocalDate +import timber.log.Timber +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class ServiceHelper @Inject constructor( + private val prefRepository: PreferencesRepository, + private val dispatcher: FirebaseJobDispatcher +) { + + fun reloadFullSyncService() { + startFullSyncService(true) + } + + fun startFullSyncService(replaceCurrent: Boolean = false) { + if (LocalDate.now().isHolidays || !prefRepository.serviceEnabled) { + Timber.d("Services disabled or it's holidays") + return + } + + dispatcher.mustSchedule( + dispatcher.newJobBuilder() + .setLifetime(FOREVER) + .setRecurring(true) + .setService(SyncWorker::class.java) + .setTag(SyncWorker.WORK_TAG) + .setTrigger( + executionWindow( + prefRepository.servicesInterval * 60, + (prefRepository.servicesInterval + 10) * 60 + ) + ) + .setConstraints(if (prefRepository.servicesOnlyWifi) ON_UNMETERED_NETWORK else ON_ANY_NETWORK) + .setReplaceCurrent(replaceCurrent) + .setRetryStrategy(DEFAULT_EXPONENTIAL) + .build() + ) + + Timber.d("Services started") + } + + fun stopFullSyncService() { + dispatcher.cancel(SyncWorker.WORK_TAG) + Timber.d("Services stopped") + } +} diff --git a/app/src/main/java/io/github/wulkanowy/services/job/SyncWorker.kt b/app/src/main/java/io/github/wulkanowy/services/job/SyncWorker.kt new file mode 100644 index 00000000..e9f446ac --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/services/job/SyncWorker.kt @@ -0,0 +1,110 @@ +package io.github.wulkanowy.services.job + +import com.firebase.jobdispatcher.JobParameters +import com.firebase.jobdispatcher.SimpleJobService +import dagger.android.AndroidInjection +import io.github.wulkanowy.data.repositories.AttendanceRepository +import io.github.wulkanowy.data.repositories.ExamRepository +import io.github.wulkanowy.data.repositories.GradeRepository +import io.github.wulkanowy.data.repositories.GradeSummaryRepository +import io.github.wulkanowy.data.repositories.PreferencesRepository +import io.github.wulkanowy.data.repositories.SessionRepository +import io.github.wulkanowy.data.repositories.TimetableRepository +import io.github.wulkanowy.services.notification.GradeNotification +import io.github.wulkanowy.utils.friday +import io.github.wulkanowy.utils.isHolidays +import io.github.wulkanowy.utils.monday +import io.reactivex.Single +import io.reactivex.disposables.CompositeDisposable +import org.threeten.bp.LocalDate +import timber.log.Timber +import javax.inject.Inject + +class SyncWorker : SimpleJobService() { + + @Inject + lateinit var session: SessionRepository + + @Inject + lateinit var gradesDetails: GradeRepository + + @Inject + lateinit var gradesSummary: GradeSummaryRepository + + @Inject + lateinit var attendance: AttendanceRepository + + @Inject + lateinit var exam: ExamRepository + + @Inject + lateinit var timetable: TimetableRepository + + @Inject + lateinit var prefRepository: PreferencesRepository + + private val disposable = CompositeDisposable() + + companion object { + const val WORK_TAG = "FULL_SYNC" + } + + override fun onCreate() { + super.onCreate() + AndroidInjection.inject(this) + } + + override fun onRunJob(job: JobParameters?): Int { + Timber.d("Synchronization started") + + val start = LocalDate.now().monday + val end = LocalDate.now().friday + + if (start.isHolidays) return RESULT_FAIL_NORETRY + + var error: Throwable? = null + + disposable.add(session.getSemesters(true) + .map { it.single { semester -> semester.current } } + .flatMapPublisher { + Single.merge( + listOf( + gradesDetails.getGrades(it, true, true), + gradesSummary.getGradesSummary(it, true), + attendance.getAttendance(it, start, end, true), + exam.getExams(it, start, end, true), + timetable.getTimetable(it, start, end, true) + ) + ) + } + .subscribe({}, { error = it })) + + return if (null === error) { + if (prefRepository.notificationsEnable) sendNotifications() + Timber.d("Synchronization successful") + RESULT_SUCCESS + } else { + Timber.e(error, "Synchronization failed") + RESULT_FAIL_RETRY + } + } + + private fun sendNotifications() { + disposable.add(session.getSemesters(true) + .map { it.single { semester -> semester.current } } + .flatMap { gradesDetails.getNewGrades(it) } + .map { it.filter { grade -> !grade.isNotified } } + .subscribe({ + if (it.isNotEmpty()) { + Timber.d("Found ${it.size} unread grades") + GradeNotification(applicationContext).sendNotification(it) + gradesDetails.updateGrades(it.map { grade -> grade.apply { isNotified = true } }).subscribe() + } + }) { Timber.e("Notifications sending failed") }) + } + + override fun onDestroy() { + super.onDestroy() + disposable.clear() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/services/jobs/SyncJob.java b/app/src/main/java/io/github/wulkanowy/services/jobs/SyncJob.java deleted file mode 100644 index 9854666e..00000000 --- a/app/src/main/java/io/github/wulkanowy/services/jobs/SyncJob.java +++ /dev/null @@ -1,148 +0,0 @@ -package io.github.wulkanowy.services.jobs; - -import android.app.PendingIntent; -import android.content.Context; -import android.support.v4.app.NotificationCompat; - -import com.firebase.jobdispatcher.Constraint; -import com.firebase.jobdispatcher.FirebaseJobDispatcher; -import com.firebase.jobdispatcher.GooglePlayDriver; -import com.firebase.jobdispatcher.JobParameters; -import com.firebase.jobdispatcher.JobService; -import com.firebase.jobdispatcher.Lifetime; -import com.firebase.jobdispatcher.RetryStrategy; -import com.firebase.jobdispatcher.SimpleJobService; -import com.firebase.jobdispatcher.Trigger; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import dagger.android.AndroidInjection; -import io.github.wulkanowy.R; -import io.github.wulkanowy.api.login.BadCredentialsException; -import io.github.wulkanowy.data.RepositoryContract; -import io.github.wulkanowy.data.db.dao.entities.Grade; -import io.github.wulkanowy.data.sync.NotRegisteredUserException; -import io.github.wulkanowy.services.notifies.GradeNotify; -import io.github.wulkanowy.ui.main.MainActivity; -import io.github.wulkanowy.utils.FabricUtils; -import timber.log.Timber; - -import static io.github.wulkanowy.utils.TimeUtilsKt.isHolidays; - -public class SyncJob extends SimpleJobService { - - public static final String JOB_TAG = "SyncJob"; - - private List gradeList = new ArrayList<>(); - - @Inject - RepositoryContract repository; - - public static void start(Context context, int interval, boolean useOnlyWifi) { - FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context)); - - dispatcher.mustSchedule(dispatcher.newJobBuilder() - .setLifetime(Lifetime.FOREVER) - .setService(SyncJob.class) - .setTag(JOB_TAG) - .setRecurring(true) - .setTrigger(Trigger.executionWindow(interval * 60, (interval + 10) * 60)) - .setConstraints(useOnlyWifi ? Constraint.ON_UNMETERED_NETWORK : Constraint.ON_ANY_NETWORK) - .setReplaceCurrent(false) - .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL) - .build()); - } - - public static void stop(Context context) { - new FirebaseJobDispatcher(new GooglePlayDriver(context)).cancel(JOB_TAG); - } - - @Override - public void onCreate() { - super.onCreate(); - AndroidInjection.inject(this); - } - - @Override - public int onRunJob(JobParameters job) { - if (isHolidays()) { - stop(getApplicationContext()); - - return JobService.RESULT_FAIL_NORETRY; - } - - try { - repository.getSyncRepo().initLastUser(); - repository.getSyncRepo().syncAll(); - - gradeList = repository.getDbRepo().getNewGrades(repository.getDbRepo().getCurrentSemesterName()); - - if (!gradeList.isEmpty() && repository.getSharedRepo().isNotifyEnable()) { - showNotification(); - } - - FabricUtils.logLogin("Background", true); - - return JobService.RESULT_SUCCESS; - } catch (NotRegisteredUserException e) { - logError(e); - stop(getApplicationContext()); - - return JobService.RESULT_FAIL_NORETRY; - } catch (BadCredentialsException e) { - logError(e); - repository.cleanAllData(); - stop(getApplicationContext()); - - return JobService.RESULT_FAIL_NORETRY; - } catch (Exception e) { - logError(e); - - return JobService.RESULT_FAIL_RETRY; - } - } - - private void showNotification() { - GradeNotify gradeNotify = new GradeNotify(getApplicationContext()); - - gradeNotify.notify(gradeNotify.notificationBuilder() - .setContentTitle(getStringTitle()) - .setContentText(getStringContent()) - .setSmallIcon(R.drawable.ic_notify_grade) - .setAutoCancel(true) - .setDefaults(NotificationCompat.DEFAULT_ALL) - .setPriority(NotificationCompat.PRIORITY_HIGH) - .setColor(getResources().getColor(R.color.colorPrimary)) - .setContentIntent(PendingIntent.getActivity(getApplicationContext(), 0, - MainActivity.getStartIntent(getApplicationContext()) - .putExtra(MainActivity.EXTRA_CARD_ID_KEY, 0) - , PendingIntent.FLAG_UPDATE_CURRENT - )) - .build()); - } - - private String getStringTitle() { - if (gradeList.size() == 1) { - return getResources().getQuantityString(R.plurals.newGradePlurals, 1); - } else { - return getResources().getQuantityString(R.plurals.newGradePlurals, 2); - } - } - - private String getStringContent() { - if (gradeList.size() == 1) { - return gradeList.get(0).getSubject(); - } else { - return getResources().getQuantityString(R.plurals.receivedNewGradePlurals, - gradeList.size(), gradeList.size()); - } - } - - private void logError(Exception e) { - FabricUtils.logLogin("Background", false); - Timber.e(e, "During background synchronization an error occurred"); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/services/notification/BaseNotification.kt b/app/src/main/java/io/github/wulkanowy/services/notification/BaseNotification.kt new file mode 100644 index 00000000..945d0b15 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/services/notification/BaseNotification.kt @@ -0,0 +1,34 @@ +package io.github.wulkanowy.services.notification + +import android.app.Notification +import android.app.NotificationManager +import android.content.Context +import android.content.Context.NOTIFICATION_SERVICE +import android.os.Build.VERSION.SDK_INT +import android.os.Build.VERSION_CODES.O +import androidx.core.app.NotificationCompat +import timber.log.Timber +import kotlin.random.Random + +abstract class BaseNotification(protected val context: Context) { + + protected val notificationManager: NotificationManager by lazy { + context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager + } + + fun notify(notification: Notification) { + notificationManager.notify(Random.nextInt(1000), notification) + } + + fun notificationBuilder(channelId: String): NotificationCompat.Builder { + if (SDK_INT >= O) createChannel(channelId) + return NotificationCompat.Builder(context, channelId) + } + + fun cancelAll() { + notificationManager.cancelAll() + Timber.d("Notifications canceled") + } + + abstract fun createChannel(channelId: String) +} diff --git a/app/src/main/java/io/github/wulkanowy/services/notification/GradeNotification.kt b/app/src/main/java/io/github/wulkanowy/services/notification/GradeNotification.kt new file mode 100644 index 00000000..df57ec28 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/services/notification/GradeNotification.kt @@ -0,0 +1,60 @@ +package io.github.wulkanowy.services.notification + +import android.annotation.TargetApi +import android.app.Notification.VISIBILITY_PUBLIC +import android.app.NotificationChannel +import android.app.NotificationManager.IMPORTANCE_HIGH +import android.app.PendingIntent +import android.app.PendingIntent.FLAG_UPDATE_CURRENT +import android.content.Context +import androidx.core.app.NotificationCompat +import androidx.core.content.ContextCompat +import io.github.wulkanowy.R +import io.github.wulkanowy.data.db.entities.Grade +import io.github.wulkanowy.ui.modules.main.MainActivity +import io.github.wulkanowy.ui.modules.main.MainActivity.Companion.EXTRA_START_MENU_INDEX +import timber.log.Timber + +class GradeNotification(context: Context) : BaseNotification(context) { + + private val channelId = "Grade_Notify" + + @TargetApi(26) + override fun createChannel(channelId: String) { + notificationManager.createNotificationChannel(NotificationChannel( + channelId, context.getString(R.string.notify_grade_channel), IMPORTANCE_HIGH + ).apply { + enableLights(true) + enableVibration(true) + lockscreenVisibility = VISIBILITY_PUBLIC + }) + } + + fun sendNotification(items: List) { + notify(notificationBuilder(channelId) + .setContentTitle(context.resources.getQuantityString(R.plurals.grade_new_items, items.size, items.size)) + .setContentText(context.resources.getQuantityString(R.plurals.notify_grade_new_items, items.size, items.size)) + .setSmallIcon(R.drawable.ic_stat_notify_grade) + .setAutoCancel(true) + .setDefaults(NotificationCompat.DEFAULT_ALL) + .setPriority(NotificationCompat.PRIORITY_HIGH) + .setColor(ContextCompat.getColor(context, R.color.colorPrimary)) + .setContentIntent( + PendingIntent.getActivity(context, 0, + MainActivity.getStartIntent(context).putExtra(EXTRA_START_MENU_INDEX, 0), + FLAG_UPDATE_CURRENT + ) + ) + .setStyle(NotificationCompat.InboxStyle().run { + setSummaryText(context.resources.getQuantityString(R.plurals.grade_number_item, items.size, items.size)) + items.forEach { + addLine("${it.subject}: ${it.entry}") + } + this + }) + .build() + ) + + Timber.d("Notification sent") + } +} diff --git a/app/src/main/java/io/github/wulkanowy/services/notifies/GradeNotify.java b/app/src/main/java/io/github/wulkanowy/services/notifies/GradeNotify.java deleted file mode 100644 index a554bea3..00000000 --- a/app/src/main/java/io/github/wulkanowy/services/notifies/GradeNotify.java +++ /dev/null @@ -1,36 +0,0 @@ -package io.github.wulkanowy.services.notifies; - -import android.annotation.TargetApi; -import android.app.Notification; -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.content.Context; - -import io.github.wulkanowy.R; - -public class GradeNotify extends NotificationService { - - private static final String CHANNEL_ID = "Grade_Notify"; - - public GradeNotify(Context context) { - super(context); - } - - @Override - @TargetApi(26) - void createChannel() { - String channelName = getString(R.string.notify_grade_channel); - - NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, channelName, - NotificationManager.IMPORTANCE_HIGH); - notificationChannel.enableLights(true); - notificationChannel.enableVibration(true); - notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); - getManager().createNotificationChannel(notificationChannel); - } - - @Override - String getChannelId() { - return CHANNEL_ID; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/services/notifies/NotificationService.java b/app/src/main/java/io/github/wulkanowy/services/notifies/NotificationService.java deleted file mode 100644 index 156de2bd..00000000 --- a/app/src/main/java/io/github/wulkanowy/services/notifies/NotificationService.java +++ /dev/null @@ -1,57 +0,0 @@ -package io.github.wulkanowy.services.notifies; - - -import android.annotation.TargetApi; -import android.app.Notification; -import android.app.NotificationManager; -import android.content.Context; -import android.os.Build; -import android.support.annotation.StringRes; -import android.support.v4.app.NotificationCompat; - -import java.util.Random; - -public class NotificationService { - - private NotificationManager manager; - - private Context context; - - public NotificationService(Context context) { - this.context = context; - } - - public void notify(Notification notification) { - getManager().notify(new Random().nextInt(1000), notification); - } - - public NotificationCompat.Builder notificationBuilder() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - createChannel(); - } - return new NotificationCompat.Builder(context, getChannelId()); - } - - public void cancelAll() { - getManager().cancelAll(); - } - - NotificationManager getManager() { - if (manager == null) { - manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); - } - return manager; - } - - String getString(@StringRes int stringId) { - return context.getString(stringId); - } - - @TargetApi(26) - void createChannel() { - } - - String getChannelId() { - return null; - } -} \ No newline at end of file diff --git a/app/src/main/java/io/github/wulkanowy/services/widgets/TimetableWidgetService.kt b/app/src/main/java/io/github/wulkanowy/services/widgets/TimetableWidgetService.kt new file mode 100644 index 00000000..1e5ac71f --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/services/widgets/TimetableWidgetService.kt @@ -0,0 +1,27 @@ +package io.github.wulkanowy.services.widgets + +import android.content.Intent +import android.widget.RemoteViewsService +import dagger.android.AndroidInjection +import io.github.wulkanowy.data.db.SharedPrefHelper +import io.github.wulkanowy.data.repositories.SessionRepository +import io.github.wulkanowy.data.repositories.TimetableRepository +import io.github.wulkanowy.ui.widgets.timetable.TimetableWidgetFactory +import javax.inject.Inject + +class TimetableWidgetService : RemoteViewsService() { + + @Inject + lateinit var timetableRepository: TimetableRepository + + @Inject + lateinit var sessionRepository: SessionRepository + + @Inject + lateinit var sharedPref: SharedPrefHelper + + override fun onGetViewFactory(intent: Intent?): RemoteViewsFactory { + AndroidInjection.inject(this) + return TimetableWidgetFactory(timetableRepository, sessionRepository, sharedPref, applicationContext, intent) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/services/widgets/TimetableWidgetServices.java b/app/src/main/java/io/github/wulkanowy/services/widgets/TimetableWidgetServices.java deleted file mode 100644 index f442542e..00000000 --- a/app/src/main/java/io/github/wulkanowy/services/widgets/TimetableWidgetServices.java +++ /dev/null @@ -1,22 +0,0 @@ -package io.github.wulkanowy.services.widgets; - -import android.content.Intent; -import android.widget.RemoteViewsService; - -import javax.inject.Inject; - -import dagger.android.AndroidInjection; -import io.github.wulkanowy.data.RepositoryContract; -import io.github.wulkanowy.ui.widgets.TimetableWidgetFactory; - -public class TimetableWidgetServices extends RemoteViewsService { - - @Inject - RepositoryContract repository; - - @Override - public RemoteViewsFactory onGetViewFactory(Intent intent) { - AndroidInjection.inject(this); - return new TimetableWidgetFactory(getApplicationContext(), repository); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/base/BaseActivity.java b/app/src/main/java/io/github/wulkanowy/ui/base/BaseActivity.java deleted file mode 100644 index 82ab9d19..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/base/BaseActivity.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.github.wulkanowy.ui.base; - -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.design.widget.Snackbar; -import android.support.v7.app.AppCompatDelegate; -import android.view.View; - -import butterknife.ButterKnife; -import butterknife.Unbinder; -import dagger.android.support.DaggerAppCompatActivity; -import io.github.wulkanowy.R; -import io.github.wulkanowy.utils.NetworkUtils; - -public abstract class BaseActivity extends DaggerAppCompatActivity implements BaseContract.View { - - private Unbinder unbinder; - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); - } - - protected void injectViews() { - unbinder = ButterKnife.bind(this); - } - - @Override - public void showMessage(@NonNull String text) { - if (getMessageView() != null) { - Snackbar.make(getMessageView(), text, Snackbar.LENGTH_LONG).show(); - } - } - - @Override - public void showNoNetworkMessage() { - showMessage(getString(R.string.noInternet_text)); - } - - @Override - public boolean isNetworkConnected() { - return NetworkUtils.isOnline(getApplicationContext()); - } - - protected View getMessageView() { - return null; - } - - @Override - protected void onDestroy() { - super.onDestroy(); - if (unbinder != null) { - unbinder.unbind(); - } - invalidateOptionsMenu(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/base/BaseActivity.kt b/app/src/main/java/io/github/wulkanowy/ui/base/BaseActivity.kt new file mode 100644 index 00000000..f02b6488 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/base/BaseActivity.kt @@ -0,0 +1,27 @@ +package io.github.wulkanowy.ui.base + +import android.os.Bundle +import android.view.View +import androidx.appcompat.app.AppCompatDelegate +import com.google.android.material.snackbar.Snackbar +import com.google.android.material.snackbar.Snackbar.LENGTH_LONG +import dagger.android.support.DaggerAppCompatActivity + +abstract class BaseActivity : DaggerAppCompatActivity(), BaseView { + + protected lateinit var messageContainer: View + + public override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) + } + + override fun showMessage(text: String) { + Snackbar.make(messageContainer, text, LENGTH_LONG).show() + } + + override fun onDestroy() { + super.onDestroy() + invalidateOptionsMenu() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/base/BaseContract.java b/app/src/main/java/io/github/wulkanowy/ui/base/BaseContract.java deleted file mode 100644 index 3bfa40d1..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/base/BaseContract.java +++ /dev/null @@ -1,22 +0,0 @@ -package io.github.wulkanowy.ui.base; - -import android.support.annotation.NonNull; - -public interface BaseContract { - - interface View { - - void showMessage(@NonNull String text); - - void showNoNetworkMessage(); - - boolean isNetworkConnected(); - } - - interface Presenter { - - void attachView(@NonNull V view); - - void detachView(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/base/BaseFragment.java b/app/src/main/java/io/github/wulkanowy/ui/base/BaseFragment.java deleted file mode 100644 index e2a5a9e0..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/base/BaseFragment.java +++ /dev/null @@ -1,56 +0,0 @@ -package io.github.wulkanowy.ui.base; - -import android.support.annotation.NonNull; -import android.support.annotation.StringRes; -import android.view.View; - -import butterknife.ButterKnife; -import butterknife.Unbinder; -import dagger.android.support.DaggerFragment; -import io.github.wulkanowy.utils.NetworkUtils; - -public abstract class BaseFragment extends DaggerFragment implements BaseContract.View { - - private Unbinder unbinder; - - protected void injectViews(@NonNull View view) { - unbinder = ButterKnife.bind(this, view); - } - - @Override - public void onDestroyView() { - if (unbinder != null) { - unbinder.unbind(); - } - super.onDestroyView(); - } - - public void setTitle(String title) { - if (getActivity() != null) { - getActivity().setTitle(title); - } - } - - @Override - public void showMessage(@NonNull String text) { - if (getActivity() != null) { - ((BaseActivity) getActivity()).showMessage(text); - } - } - - public void showMessage(@StringRes int stringId) { - showMessage(getString(stringId)); - } - - @Override - public void showNoNetworkMessage() { - if (getActivity() != null) { - ((BaseActivity) getActivity()).showNoNetworkMessage(); - } - } - - @Override - public boolean isNetworkConnected() { - return NetworkUtils.isOnline(getContext()); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/base/BaseFragment.kt b/app/src/main/java/io/github/wulkanowy/ui/base/BaseFragment.kt new file mode 100644 index 00000000..b0d6178e --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/base/BaseFragment.kt @@ -0,0 +1,16 @@ +package io.github.wulkanowy.ui.base + +import android.view.View +import com.google.android.material.snackbar.Snackbar +import com.google.android.material.snackbar.Snackbar.LENGTH_LONG +import dagger.android.support.DaggerFragment + +abstract class BaseFragment : DaggerFragment(), BaseView { + + protected var messageContainer: View? = null + + override fun showMessage(text: String) { + if (messageContainer == null) (activity as? BaseActivity)?.showMessage(text) + else messageContainer?.also { Snackbar.make(it, text, LENGTH_LONG).show() } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/base/BasePagerAdapter.java b/app/src/main/java/io/github/wulkanowy/ui/base/BasePagerAdapter.java deleted file mode 100644 index 178f0110..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/base/BasePagerAdapter.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.github.wulkanowy.ui.base; - -import android.support.annotation.NonNull; -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentManager; -import android.support.v4.app.FragmentStatePagerAdapter; - -import java.util.ArrayList; -import java.util.List; - -public class BasePagerAdapter extends FragmentStatePagerAdapter { - - private List fragmentList = new ArrayList<>(); - - private List titleList = new ArrayList<>(); - - public BasePagerAdapter(FragmentManager fragmentManager) { - super(fragmentManager); - } - - public void addFragment(@NonNull Fragment fragment, @NonNull String title) { - fragmentList.add(fragment); - titleList.add(title); - } - - public void addFragment(@NonNull Fragment fragment) { - fragmentList.add(fragment); - } - - @Override - public Fragment getItem(int position) { - return fragmentList.get(position); - } - - @Override - public int getCount() { - return fragmentList.size(); - } - - @Override - public CharSequence getPageTitle(int position) { - if (!titleList.isEmpty()) { - return titleList.get(position); - } - return null; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/base/BasePagerAdapter.kt b/app/src/main/java/io/github/wulkanowy/ui/base/BasePagerAdapter.kt new file mode 100644 index 00000000..000efdcd --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/base/BasePagerAdapter.kt @@ -0,0 +1,32 @@ +package io.github.wulkanowy.ui.base + +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.fragment.app.FragmentManager +import androidx.fragment.app.FragmentStatePagerAdapter + +class BasePagerAdapter(fragmentManager: FragmentManager) : FragmentStatePagerAdapter(fragmentManager) { + + val fragments = mutableMapOf() + + val registeredFragments = mutableMapOf() + + override fun getItem(position: Int) = fragments.values.elementAt(position) + + override fun getCount() = fragments.size + + override fun getPageTitle(position: Int): CharSequence? { + return fragments.keys.elementAtOrNull(position) + } + + override fun instantiateItem(container: ViewGroup, position: Int): Any { + return super.instantiateItem(container, position).also { + registeredFragments[position] = it as Fragment + } + } + + override fun destroyItem(container: ViewGroup, position: Int, fragment: Any) { + registeredFragments.remove(position) + super.destroyItem(container, position, fragment) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/base/BasePresenter.java b/app/src/main/java/io/github/wulkanowy/ui/base/BasePresenter.java deleted file mode 100644 index 8f9b8af0..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/base/BasePresenter.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.github.wulkanowy.ui.base; - -import android.support.annotation.NonNull; - -import javax.inject.Inject; - -import io.github.wulkanowy.data.RepositoryContract; - -public class BasePresenter implements BaseContract.Presenter { - - private final RepositoryContract repository; - - private V view; - - @Inject - public BasePresenter(RepositoryContract repository) { - this.repository = repository; - } - - @Override - public void attachView(@NonNull V view) { - this.view = view; - } - - @Override - public void detachView() { - view = null; - } - - protected boolean isViewAttached() { - return view != null; - } - - public final RepositoryContract getRepository() { - return repository; - } - - public V getView() { - return view; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/base/BasePresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/base/BasePresenter.kt new file mode 100644 index 00000000..9a0b5eda --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/base/BasePresenter.kt @@ -0,0 +1,23 @@ +package io.github.wulkanowy.ui.base + +import io.github.wulkanowy.data.ErrorHandler +import io.github.wulkanowy.ui.modules.main.MainView +import io.reactivex.disposables.CompositeDisposable + +open class BasePresenter(private val errorHandler: ErrorHandler) { + + val disposable = CompositeDisposable() + + var view: T? = null + + open fun onAttachView(view: T) { + this.view = view + errorHandler.showErrorMessage = { view.showMessage(it) } + } + + open fun onDetachView() { + view = null + disposable.clear() + errorHandler.clear() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/base/BaseView.kt b/app/src/main/java/io/github/wulkanowy/ui/base/BaseView.kt new file mode 100644 index 00000000..6352ca83 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/base/BaseView.kt @@ -0,0 +1,6 @@ +package io.github.wulkanowy.ui.base + +interface BaseView { + + fun showMessage(text: String) +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/login/LoginActivity.java b/app/src/main/java/io/github/wulkanowy/ui/login/LoginActivity.java deleted file mode 100644 index a0960af2..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/login/LoginActivity.java +++ /dev/null @@ -1,236 +0,0 @@ -package io.github.wulkanowy.ui.login; - -import android.animation.Animator; -import android.animation.AnimatorListenerAdapter; -import android.content.Context; -import android.content.Intent; -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.design.widget.TextInputLayout; -import android.support.v7.app.ActionBar; -import android.view.View; -import android.view.inputmethod.EditorInfo; -import android.widget.ArrayAdapter; -import android.widget.AutoCompleteTextView; -import android.widget.EditText; -import android.widget.TextView; -import android.widget.Toast; - -import javax.inject.Inject; - -import butterknife.BindView; -import butterknife.OnClick; -import butterknife.OnEditorAction; -import io.github.wulkanowy.R; -import io.github.wulkanowy.ui.base.BaseActivity; -import io.github.wulkanowy.ui.main.MainActivity; -import io.github.wulkanowy.utils.AppConstant; -import io.github.wulkanowy.utils.CommonUtils; -import io.github.wulkanowy.utils.KeyboardUtils; - -public class LoginActivity extends BaseActivity implements LoginContract.View { - - @BindView(R.id.login_activity_email_edit) - EditText emailView; - - @BindView(R.id.login_activity_pass_edit) - EditText passwordView; - - @BindView(R.id.login_activity_symbol_edit) - AutoCompleteTextView symbolView; - - @BindView(R.id.login_activity_form_scroll) - View loginFormView; - - @BindView(R.id.login_activity_progress_container) - View loadingBarView; - - @BindView(R.id.login_activity_progress_text) - TextView loginProgressText; - - @BindView(R.id.login_activity_symbol_text_input) - TextInputLayout symbolLayout; - - @Inject - LoginContract.Presenter presenter; - - private EditText requestedView; - - public static Intent getStartIntent(Context context) { - return new Intent(context, LoginActivity.class); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_login); - injectViews(); - - presenter.attachView(this); - setUpOnCreate(); - } - - protected void setUpOnCreate() { - symbolView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, - getResources().getStringArray(R.array.symbols))); - } - - @OnClick(R.id.login_activity_sign_button) - void onLoginButtonClick() { - presenter.attemptLogin( - emailView.getText().toString(), - passwordView.getText().toString(), - symbolView.getText().toString()); - } - - @OnEditorAction(value = {R.id.login_activity_symbol_edit, R.id.login_activity_pass_edit}) - boolean onEditorAction(int id) { - if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) { - onLoginButtonClick(); - return true; - } - return false; - } - - @OnClick(R.id.login_activity_create_text) - void onCreateAccountButtonClick() { - CommonUtils.openInternalBrowserViewer(this, AppConstant.VULCAN_CREATE_ACCOUNT_URL); - } - - @OnClick(R.id.login_activity_forgot_text) - void onForgotPasswordButtonClick() { - CommonUtils.openInternalBrowserViewer(this, AppConstant.VULCAN_FORGOT_PASS_URL); - } - - @Override - public void setErrorEmailRequired() { - emailView.requestFocus(); - emailView.setError(getString(R.string.error_field_required)); - requestedView = emailView; - } - - @Override - public void setErrorEmailInvalid() { - emailView.requestFocus(); - emailView.setError(getString(R.string.error_invalid_email)); - requestedView = emailView; - } - - @Override - public void setErrorPassRequired() { - passwordView.requestFocus(); - passwordView.setError(getString(R.string.error_field_required)); - requestedView = passwordView; - } - - @Override - public void setErrorPassInvalid() { - passwordView.requestFocus(); - passwordView.setError(getString(R.string.error_invalid_password)); - requestedView = passwordView; - } - - @Override - public void setErrorPassIncorrect() { - passwordView.requestFocus(); - passwordView.setError(getString(R.string.error_incorrect_password)); - requestedView = passwordView; - } - - @Override - public void setErrorSymbolRequired() { - symbolLayout.setVisibility(View.VISIBLE); - symbolView.setError(getString(R.string.error_bad_account_permission)); - symbolView.requestFocus(); - requestedView = symbolView; - } - - @Override - public void resetViewErrors() { - emailView.setError(null); - passwordView.setError(null); - } - - @Override - public void showSoftInput() { - KeyboardUtils.showSoftInput(requestedView, this); - } - - @Override - public void hideSoftInput() { - KeyboardUtils.hideSoftInput(this); - } - - @Override - public void setStepOneLoginProgress() { - onLoginProgressUpdate("1", getString(R.string.step_login)); - } - - @Override - public void setStepTwoLoginProgress() { - onLoginProgressUpdate("2", getString(R.string.step_synchronization)); - } - - @Override - public void openMainActivity() { - startActivity(MainActivity.getStartIntent(this)); - finish(); - } - - @Override - public void showLoginProgress(final boolean show) { - int animTime = getResources().getInteger(android.R.integer.config_shortAnimTime); - - loginFormView.setVisibility(show ? View.GONE : View.VISIBLE); - loginFormView.animate().setDuration(animTime).alpha( - show ? 0 : 1).setListener(new AnimatorListenerAdapter() { - @Override - public void onAnimationEnd(Animator animation) { - loginFormView.setVisibility(show ? View.GONE : View.VISIBLE); - } - }); - - loadingBarView.setVisibility(show ? View.VISIBLE : View.GONE); - loadingBarView.animate().setDuration(animTime).alpha( - show ? 1 : 0).setListener(new AnimatorListenerAdapter() { - @Override - public void onAnimationEnd(Animator animation) { - loadingBarView.setVisibility(show ? View.VISIBLE : View.GONE); - } - }); - } - - @Override - public void showActionBar(boolean show) { - ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - if (show) { - actionBar.show(); - } else { - actionBar.hide(); - } - } - } - - @NonNull - @Override - protected View getMessageView() { - return findViewById(R.id.login_activity_container); - } - - - @Override - public void onSyncFailed() { - Toast.makeText(getApplicationContext(), R.string.login_sync_error, Toast.LENGTH_LONG).show(); - } - - private void onLoginProgressUpdate(String step, String message) { - loginProgressText.setText(String.format("%1$s/2 - %2$s...", step, message)); - } - - @Override - public void onDestroy() { - presenter.detachView(); - super.onDestroy(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/login/LoginContract.java b/app/src/main/java/io/github/wulkanowy/ui/login/LoginContract.java deleted file mode 100644 index 96bb49d6..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/login/LoginContract.java +++ /dev/null @@ -1,54 +0,0 @@ -package io.github.wulkanowy.ui.login; - -import io.github.wulkanowy.ui.base.BaseContract; - -public interface LoginContract { - interface View extends BaseContract.View { - - void setErrorEmailRequired(); - - void setErrorPassRequired(); - - void setErrorSymbolRequired(); - - void setErrorEmailInvalid(); - - void setErrorPassInvalid(); - - void setErrorPassIncorrect(); - - void resetViewErrors(); - - void setStepOneLoginProgress(); - - void setStepTwoLoginProgress(); - - void openMainActivity(); - - void showLoginProgress(boolean show); - - void showSoftInput(); - - void hideSoftInput(); - - void showActionBar(boolean show); - - void onSyncFailed(); - - } - - interface Presenter extends BaseContract.Presenter { - - void attemptLogin(String email, String password, String symbol); - - void onStartAsync(); - - void onDoInBackground(int stepNumber) throws Exception; - - void onLoginProgress(int step); - - void onEndAsync(int success, Exception exception); - - void onCanceledAsync(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/login/LoginModule.java b/app/src/main/java/io/github/wulkanowy/ui/login/LoginModule.java deleted file mode 100644 index 0cb26c49..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/login/LoginModule.java +++ /dev/null @@ -1,13 +0,0 @@ -package io.github.wulkanowy.ui.login; - -import dagger.Binds; -import dagger.Module; -import io.github.wulkanowy.di.scopes.PerActivity; - -@Module -public abstract class LoginModule { - - @PerActivity - @Binds - abstract LoginContract.Presenter provideLoginPresenter(LoginPresenter loginPresenter); -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/login/LoginPresenter.java b/app/src/main/java/io/github/wulkanowy/ui/login/LoginPresenter.java deleted file mode 100644 index d8461bf3..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/login/LoginPresenter.java +++ /dev/null @@ -1,178 +0,0 @@ -package io.github.wulkanowy.ui.login; - -import android.text.TextUtils; - -import java.util.LinkedHashMap; - -import javax.inject.Inject; - -import io.github.wulkanowy.api.login.AccountPermissionException; -import io.github.wulkanowy.api.login.BadCredentialsException; -import io.github.wulkanowy.data.RepositoryContract; -import io.github.wulkanowy.ui.base.BasePresenter; -import io.github.wulkanowy.utils.AppConstant; -import io.github.wulkanowy.utils.FabricUtils; - -public class LoginPresenter extends BasePresenter - implements LoginContract.Presenter { - - private LoginTask loginAsync; - - private String email; - - private String password; - - private String symbol; - - @Inject - LoginPresenter(RepositoryContract repository) { - super(repository); - } - - @Override - public void attemptLogin(String email, String password, String symbol) { - getView().resetViewErrors(); - - this.email = email; - this.password = password; - this.symbol = getNormalizedSymbol(symbol); - - if (!isAllFieldCorrect(password, email)) { - getView().showSoftInput(); - return; - } - - if (getView().isNetworkConnected()) { - loginAsync = new LoginTask(this); - loginAsync.execute(); - - } else { - getView().showNoNetworkMessage(); - } - - getView().hideSoftInput(); - } - - @Override - public void onStartAsync() { - if (isViewAttached()) { - getView().showActionBar(false); - getView().showLoginProgress(true); - } - } - - @Override - public void onDoInBackground(int stepNumber) throws Exception { - switch (stepNumber) { - case 1: - getRepository().getSyncRepo().registerUser(email, password, symbol); - break; - case 2: - getRepository().getSyncRepo().syncAll(); - break; - } - } - - @Override - public void onLoginProgress(int step) { - if (step == 1) { - getView().setStepOneLoginProgress(); - } else if (step == 2) { - getView().setStepTwoLoginProgress(); - } - } - - @Override - public void onEndAsync(int success, Exception exception) { - switch (success) { - case LoginTask.LOGIN_AND_SYNC_SUCCESS: - FabricUtils.logRegister(true, getRepository().getDbRepo().getCurrentSymbol().getSymbol(), "Success"); - getView().openMainActivity(); - return; - case LoginTask.SYNC_FAILED: - FabricUtils.logRegister(true, symbol, exception.getMessage()); - getView().onSyncFailed(); - getView().openMainActivity(); - return; - case LoginTask.LOGIN_FAILED: - if (exception instanceof BadCredentialsException) { - getView().setErrorPassIncorrect(); - getView().showSoftInput(); - } else if (exception instanceof AccountPermissionException) { - getView().setErrorSymbolRequired(); - getView().showSoftInput(); - } else { - FabricUtils.logRegister(false, symbol, exception.getMessage()); - getView().showMessage(getRepository().getResRepo().getErrorLoginMessage(exception)); - } - break; - } - getView().showActionBar(true); - getView().showLoginProgress(false); - } - - @Override - public void onCanceledAsync() { - if (isViewAttached()) { - getView().showActionBar(true); - getView().showLoginProgress(false); - } - } - - private boolean isEmailValid(String email) { - return email.contains("@") || email.contains("\\\\"); - } - - private boolean isPasswordValid(String password) { - return password.length() > 4; - } - - private String getNormalizedSymbol(String symbol) { - if (TextUtils.isEmpty(symbol)) { - return AppConstant.DEFAULT_SYMBOL; - } - - String[] keys = getRepository().getResRepo().getSymbolsKeysArray(); - String[] values = getRepository().getResRepo().getSymbolsValuesArray(); - LinkedHashMap map = new LinkedHashMap<>(); - - for (int i = 0; i < Math.min(keys.length, values.length); ++i) { - map.put(keys[i], values[i]); - } - - if (map.containsKey(symbol)) { - return map.get(symbol); - } - return AppConstant.DEFAULT_SYMBOL; - } - - private boolean isAllFieldCorrect(String password, String email) { - boolean correct = true; - - if (TextUtils.isEmpty(password)) { - getView().setErrorPassRequired(); - correct = false; - } else if (!isPasswordValid(password)) { - getView().setErrorPassInvalid(); - correct = false; - } - - if (TextUtils.isEmpty(email)) { - getView().setErrorEmailRequired(); - correct = false; - } else if (!isEmailValid(email)) { - getView().setErrorEmailInvalid(); - correct = false; - } - return correct; - } - - @Override - public void detachView() { - if (loginAsync != null) { - loginAsync.cancel(true); - loginAsync = null; - } - super.detachView(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/login/LoginTask.java b/app/src/main/java/io/github/wulkanowy/ui/login/LoginTask.java deleted file mode 100644 index 2938a836..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/login/LoginTask.java +++ /dev/null @@ -1,60 +0,0 @@ -package io.github.wulkanowy.ui.login; - -import android.os.AsyncTask; - -public class LoginTask extends AsyncTask { - - public final static int LOGIN_AND_SYNC_SUCCESS = 1; - - public final static int LOGIN_FAILED = -1; - - public final static int SYNC_FAILED = 2; - - private LoginContract.Presenter presenter; - - private Exception exception; - - LoginTask(LoginContract.Presenter presenter) { - this.presenter = presenter; - } - - @Override - protected void onPreExecute() { - presenter.onStartAsync(); - } - - @Override - protected Integer doInBackground(Void... params) { - try { - publishProgress(1); - presenter.onDoInBackground(1); - } catch (Exception e) { - exception = e; - return LOGIN_FAILED; - } - - try { - publishProgress(2); - presenter.onDoInBackground(2); - } catch (Exception e) { - exception = e; - return SYNC_FAILED; - } - return LOGIN_AND_SYNC_SUCCESS; - } - - @Override - protected void onProgressUpdate(Integer... progress) { - presenter.onLoginProgress(progress[0]); - } - - @Override - protected void onPostExecute(Integer success) { - presenter.onEndAsync(success, exception); - } - - @Override - protected void onCancelled() { - presenter.onCanceledAsync(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/MainActivity.java b/app/src/main/java/io/github/wulkanowy/ui/main/MainActivity.java deleted file mode 100644 index b739ae98..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/MainActivity.java +++ /dev/null @@ -1,170 +0,0 @@ -package io.github.wulkanowy.ui.main; - -import android.content.Context; -import android.content.Intent; -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.design.widget.AppBarLayout; -import android.support.v7.app.ActionBar; -import android.support.v7.widget.Toolbar; -import android.view.View; - -import com.aurelhubert.ahbottomnavigation.AHBottomNavigation; -import com.aurelhubert.ahbottomnavigation.AHBottomNavigationItem; -import com.aurelhubert.ahbottomnavigation.AHBottomNavigationViewPager; - -import javax.inject.Inject; -import javax.inject.Named; - -import butterknife.BindView; -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.RepositoryContract; -import io.github.wulkanowy.services.jobs.SyncJob; -import io.github.wulkanowy.ui.base.BaseActivity; -import io.github.wulkanowy.ui.base.BasePagerAdapter; -import io.github.wulkanowy.ui.main.attendance.AttendanceFragment; -import io.github.wulkanowy.ui.main.exams.ExamsFragment; -import io.github.wulkanowy.ui.main.grades.GradesFragment; -import io.github.wulkanowy.ui.main.settings.SettingsFragment; -import io.github.wulkanowy.ui.main.timetable.TimetableFragment; -import io.github.wulkanowy.utils.CommonUtils; - -public class MainActivity extends BaseActivity implements MainContract.View, - AHBottomNavigation.OnTabSelectedListener, OnFragmentIsReadyListener { - - public static final String EXTRA_CARD_ID_KEY = "cardId"; - - @BindView(R.id.main_activity_nav) - AHBottomNavigation bottomNavigation; - - @BindView(R.id.main_activity_view_pager) - AHBottomNavigationViewPager viewPager; - - @BindView(R.id.main_activity_progress_bar) - View progressBar; - - @BindView(R.id.main_activity_appbar) - AppBarLayout appBar; - - @Named("Main") - @Inject - BasePagerAdapter pagerAdapter; - - @Inject - MainContract.Presenter presenter; - - @Inject - RepositoryContract repository; - - public static Intent getStartIntent(Context context) { - return new Intent(context, MainActivity.class); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - setSupportActionBar((Toolbar) findViewById(R.id.main_activity_toolbar)); - injectViews(); - - presenter.attachView(this, getIntent().getIntExtra(EXTRA_CARD_ID_KEY, -1)); - } - - @Override - public void showProgressBar(boolean show) { - progressBar.setVisibility(show ? View.VISIBLE : View.INVISIBLE); - viewPager.setVisibility(show ? View.INVISIBLE : View.VISIBLE); - bottomNavigation.setVisibility(show ? View.INVISIBLE : View.VISIBLE); - } - - @Override - public void showActionBar() { - ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.show(); - } - } - - @Override - public void hideActionBar() { - ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.hide(); - } - } - - @Override - public boolean onTabSelected(int position, boolean wasSelected) { - presenter.onTabSelected(position, wasSelected); - appBar.setExpanded(true, true); - invalidateOptionsMenu(); - return true; - } - - @Override - public void setCurrentPage(int position) { - viewPager.setCurrentItem(position, false); - } - - @Override - public void onFragmentIsReady() { - presenter.onFragmentIsReady(); - } - - @Override - public void initiationBottomNav(int tabPosition) { - bottomNavigation.addItem(new AHBottomNavigationItem(getString(R.string.grades_text), - R.drawable.ic_menu_grade_26dp)); - - bottomNavigation.addItem(new AHBottomNavigationItem(getString(R.string.attendance_text), - R.drawable.ic_menu_attendance_24dp)); - - bottomNavigation.addItem(new AHBottomNavigationItem(getString(R.string.exams_text), - R.drawable.ic_menu_exams_24dp)); - - bottomNavigation.addItem(new AHBottomNavigationItem(getString(R.string.timetable_text), - R.drawable.ic_menu_timetable_24dp)); - - bottomNavigation.addItem(new AHBottomNavigationItem(getString(R.string.settings_text), - R.drawable.ic_menu_other_24dp)); - - bottomNavigation.setAccentColor(getResources().getColor(R.color.colorPrimary)); - bottomNavigation.setInactiveColor(CommonUtils.getThemeAttrColor(this, android.R.attr.textColorTertiary)); - bottomNavigation.setDefaultBackgroundColor(CommonUtils.getThemeAttrColor(this, R.attr.bottomNavBackground)); - bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW); - bottomNavigation.setOnTabSelectedListener(this); - bottomNavigation.setCurrentItem(tabPosition); - bottomNavigation.setBehaviorTranslationEnabled(false); - } - - @Override - public void initiationViewPager(int tabPosition) { - pagerAdapter.addFragment(new GradesFragment()); - pagerAdapter.addFragment(new AttendanceFragment()); - pagerAdapter.addFragment(new ExamsFragment()); - pagerAdapter.addFragment(new TimetableFragment()); - pagerAdapter.addFragment(new SettingsFragment()); - - viewPager.setPagingEnabled(false); - viewPager.setAdapter(pagerAdapter); - viewPager.setOffscreenPageLimit(4); - viewPager.setCurrentItem(tabPosition, false); - } - - @Override - public void startSyncService(int interval, boolean useOnlyWifi) { - SyncJob.start(getApplicationContext(), interval, useOnlyWifi); - } - - @NonNull - @Override - protected View getMessageView() { - return findViewById(R.id.main_activity_view_pager); - } - - @Override - protected void onDestroy() { - presenter.detachView(); - super.onDestroy(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/MainContract.java b/app/src/main/java/io/github/wulkanowy/ui/main/MainContract.java deleted file mode 100644 index cb4e29e4..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/MainContract.java +++ /dev/null @@ -1,34 +0,0 @@ -package io.github.wulkanowy.ui.main; - -import android.support.annotation.NonNull; - -import io.github.wulkanowy.ui.base.BaseContract; - -public interface MainContract { - - interface View extends BaseContract.View { - - void setCurrentPage(int position); - - void showProgressBar(boolean show); - - void showActionBar(); - - void hideActionBar(); - - void initiationViewPager(int tabPosition); - - void initiationBottomNav(int tabPosition); - - void startSyncService(int interval, boolean useOnlyWifi); - } - - interface Presenter extends BaseContract.Presenter { - - void attachView(@NonNull View view, int initTabId); - - void onTabSelected(int position, boolean wasSelected); - - void onFragmentIsReady(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/MainModule.java b/app/src/main/java/io/github/wulkanowy/ui/main/MainModule.java deleted file mode 100644 index ff3fed67..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/MainModule.java +++ /dev/null @@ -1,50 +0,0 @@ -package io.github.wulkanowy.ui.main; - -import javax.inject.Named; - -import dagger.Binds; -import dagger.Module; -import dagger.Provides; -import dagger.android.ContributesAndroidInjector; -import io.github.wulkanowy.di.scopes.PerActivity; -import io.github.wulkanowy.di.scopes.PerFragment; -import io.github.wulkanowy.ui.base.BasePagerAdapter; -import io.github.wulkanowy.ui.main.attendance.AttendanceFragment; -import io.github.wulkanowy.ui.main.attendance.AttendanceModule; -import io.github.wulkanowy.ui.main.exams.ExamsFragment; -import io.github.wulkanowy.ui.main.exams.ExamsModule; -import io.github.wulkanowy.ui.main.grades.GradesFragment; -import io.github.wulkanowy.ui.main.grades.GradesModule; -import io.github.wulkanowy.ui.main.timetable.TimetableFragment; -import io.github.wulkanowy.ui.main.timetable.TimetableModule; - -@Module -public abstract class MainModule { - - @PerActivity - @Binds - abstract MainContract.Presenter provideMainPresenter(MainPresenter mainPresenter); - - @Named("Main") - @PerActivity - @Provides - static BasePagerAdapter provideAdapter(MainActivity activity) { - return new BasePagerAdapter(activity.getSupportFragmentManager()); - } - - @PerFragment - @ContributesAndroidInjector(modules = GradesModule.class) - abstract GradesFragment bindsGradesFragment(); - - @PerFragment - @ContributesAndroidInjector(modules = TimetableModule.class) - abstract TimetableFragment bindTimetableFragment(); - - @PerFragment - @ContributesAndroidInjector(modules = ExamsModule.class) - abstract ExamsFragment bindExamsFragment(); - - @PerFragment - @ContributesAndroidInjector(modules = AttendanceModule.class) - abstract AttendanceFragment bindAttendanceFramgnet(); -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/MainPresenter.java b/app/src/main/java/io/github/wulkanowy/ui/main/MainPresenter.java deleted file mode 100644 index 2ca9eefa..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/MainPresenter.java +++ /dev/null @@ -1,63 +0,0 @@ -package io.github.wulkanowy.ui.main; - -import android.support.annotation.NonNull; - -import javax.inject.Inject; - -import io.github.wulkanowy.data.RepositoryContract; -import io.github.wulkanowy.ui.base.BasePresenter; - -import static io.github.wulkanowy.utils.TimeUtilsKt.isHolidays; - -public class MainPresenter extends BasePresenter - implements MainContract.Presenter { - - private int fragmentCount = 0; - - @Inject - MainPresenter(RepositoryContract repository) { - super(repository); - } - - @Override - public void attachView(@NonNull MainContract.View view, int initTabId) { - super.attachView(view); - getView().showProgressBar(true); - getView().hideActionBar(); - - int tabPosition; - - if (initTabId != -1) { - tabPosition = initTabId; - } else { - tabPosition = getRepository().getSharedRepo().getStartupTab(); - } - - getView().initiationBottomNav(tabPosition); - getView().initiationViewPager(tabPosition); - - if (getRepository().getSharedRepo().isServicesEnable() && !isHolidays()) { - getView().startSyncService(getRepository().getSharedRepo().getServicesInterval(), - getRepository().getSharedRepo().isMobileDisable()); - } - } - - @Override - public void onTabSelected(int position, boolean wasSelected) { - if (!wasSelected) { - getView().setCurrentPage(position); - } - } - - @Override - public void onFragmentIsReady() { - if (fragmentCount < 4) { - fragmentCount++; - } - - if (fragmentCount == 4) { - getView().showActionBar(); - getView().showProgressBar(false); - } - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/OnFragmentIsReadyListener.java b/app/src/main/java/io/github/wulkanowy/ui/main/OnFragmentIsReadyListener.java deleted file mode 100644 index 21e3ba12..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/OnFragmentIsReadyListener.java +++ /dev/null @@ -1,6 +0,0 @@ -package io.github.wulkanowy.ui.main; - -public interface OnFragmentIsReadyListener { - - void onFragmentIsReady(); -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendanceContract.java b/app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendanceContract.java deleted file mode 100644 index 1ad66787..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendanceContract.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.github.wulkanowy.ui.main.attendance; - -import android.support.annotation.NonNull; - -import io.github.wulkanowy.ui.base.BaseContract; -import io.github.wulkanowy.ui.main.OnFragmentIsReadyListener; - -public interface AttendanceContract { - - interface View extends BaseContract.View { - - void setActivityTitle(); - - void scrollViewPagerToPosition(int position); - - void setTabDataToAdapter(String date); - - void setAdapterWithTabLayout(); - - boolean isMenuVisible(); - - void setThemeForTab(int position); - } - - interface Presenter extends BaseContract.Presenter { - - void onFragmentActivated(boolean isVisible); - - void attachView(@NonNull View view, OnFragmentIsReadyListener listener); - - void setRestoredPosition(int position); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendanceDialogFragment.java b/app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendanceDialogFragment.java deleted file mode 100644 index ea38e51d..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendanceDialogFragment.java +++ /dev/null @@ -1,91 +0,0 @@ -package io.github.wulkanowy.ui.main.attendance; - -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.v4.app.DialogFragment; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.db.dao.entities.AttendanceLesson; - -public class AttendanceDialogFragment extends DialogFragment { - - private static final String ARGUMENT_KEY = "Item"; - - private AttendanceLesson lesson; - - @BindView(R.id.attendance_dialog_subject_value) - TextView subject; - - @BindView(R.id.attendance_dialog_date_value) - TextView date; - - @BindView(R.id.attendance_dialog_number_value) - TextView number; - - @BindView(R.id.attendance_dialog_description_value) - TextView description; - - public AttendanceDialogFragment() { - //empty constructor for fragment - } - - public static AttendanceDialogFragment newInstance(AttendanceLesson lesson) { - AttendanceDialogFragment dialogFragment = new AttendanceDialogFragment(); - - Bundle bundle = new Bundle(); - bundle.putSerializable(ARGUMENT_KEY, lesson); - - dialogFragment.setArguments(bundle); - - return dialogFragment; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - lesson = (AttendanceLesson) getArguments().getSerializable(ARGUMENT_KEY); - } - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.attendance_dialog, container, false); - - ButterKnife.bind(this, view); - - if (!lesson.getSubject().isEmpty()) { - subject.setText(lesson.getSubject()); - } - - if (!lesson.getDate().isEmpty()) { - date.setText(lesson.getDate()); - } - - if (0 != lesson.getNumber()) { - number.setText(String.valueOf(lesson.getNumber())); - } - - description.setText(lesson.getDescription()); - - if (lesson.getAbsenceUnexcused()) { - description.setTextColor(getResources().getColor(R.color.colorPrimary)); - } - - return view; - } - - @OnClick(R.id.attendance_dialog_close) - void onClickCloseButton() { - dismiss(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendanceFragment.java b/app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendanceFragment.java deleted file mode 100644 index 732806db..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendanceFragment.java +++ /dev/null @@ -1,102 +0,0 @@ -package io.github.wulkanowy.ui.main.attendance; - -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.design.widget.TabLayout; -import android.support.v4.view.ViewPager; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import javax.inject.Inject; -import javax.inject.Named; - -import butterknife.BindView; -import io.github.wulkanowy.R; -import io.github.wulkanowy.ui.base.BaseFragment; -import io.github.wulkanowy.ui.base.BasePagerAdapter; -import io.github.wulkanowy.ui.main.OnFragmentIsReadyListener; -import io.github.wulkanowy.ui.main.attendance.tab.AttendanceTabFragment; - -public class AttendanceFragment extends BaseFragment implements AttendanceContract.View { - - private static final String CURRENT_ITEM_KEY = "CurrentItem"; - - @BindView(R.id.attendance_fragment_viewpager) - ViewPager viewPager; - - @BindView(R.id.attendance_fragment_tab_layout) - TabLayout tabLayout; - - @Inject - @Named("Attendance") - BasePagerAdapter pagerAdapter; - - @Inject - AttendanceContract.Presenter presenter; - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_attendance, container, false); - injectViews(view); - - presenter.attachView(this, (OnFragmentIsReadyListener) getActivity()); - - if (savedInstanceState != null) { - presenter.setRestoredPosition(savedInstanceState.getInt(CURRENT_ITEM_KEY)); - } - return view; - } - - @Override - public void setMenuVisibility(boolean menuVisible) { - super.setMenuVisibility(menuVisible); - if (presenter != null) { - presenter.onFragmentActivated(menuVisible); - } - } - - @Override - public void setTabDataToAdapter(String date) { - pagerAdapter.addFragment(AttendanceTabFragment.newInstance(date), date); - } - - @Override - public void setAdapterWithTabLayout() { - viewPager.setAdapter(pagerAdapter); - tabLayout.setupWithViewPager(viewPager); - } - - @Override - public void scrollViewPagerToPosition(int position) { - viewPager.setCurrentItem(position, false); - } - - @Override - public void setThemeForTab(int position) { - TabLayout.Tab tab = tabLayout.getTabAt(position); - if (tab != null) { - tab.setCustomView(R.layout.current_week_tab); - } - } - - @Override - public void setActivityTitle() { - setTitle(getString(R.string.attendance_text)); - } - - @Override - public void onSaveInstanceState(Bundle outState) { - outState.putInt(CURRENT_ITEM_KEY, viewPager.getCurrentItem()); - super.onSaveInstanceState(outState); - } - - @Override - public void onDestroyView() { - presenter.detachView(); - super.onDestroyView(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendanceModule.java b/app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendanceModule.java deleted file mode 100644 index 8679cf10..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendanceModule.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.github.wulkanowy.ui.main.attendance; - -import javax.inject.Named; - -import dagger.Binds; -import dagger.Module; -import dagger.Provides; -import dagger.android.ContributesAndroidInjector; -import io.github.wulkanowy.di.scopes.PerChildFragment; -import io.github.wulkanowy.di.scopes.PerFragment; -import io.github.wulkanowy.ui.base.BasePagerAdapter; -import io.github.wulkanowy.ui.main.attendance.tab.AttendanceTabFragment; -import io.github.wulkanowy.ui.main.attendance.tab.AttendanceTabModule; - -@Module -public abstract class AttendanceModule { - - @PerFragment - @Binds - abstract AttendanceContract.Presenter provideAttendancePresenter(AttendancePresenter attendancePresenter); - - @PerFragment - @Named("Attendance") - @Provides - static BasePagerAdapter providePagerAdapter(AttendanceFragment fragment) { - return new BasePagerAdapter(fragment.getChildFragmentManager()); - } - - @PerChildFragment - @ContributesAndroidInjector(modules = AttendanceTabModule.class) - abstract AttendanceTabFragment bindAttendanceTabFragment(); -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendancePresenter.java b/app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendancePresenter.java deleted file mode 100644 index 73a2837c..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendancePresenter.java +++ /dev/null @@ -1,108 +0,0 @@ -package io.github.wulkanowy.ui.main.attendance; - -import android.support.annotation.NonNull; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import io.github.wulkanowy.data.RepositoryContract; -import io.github.wulkanowy.ui.base.BasePresenter; -import io.github.wulkanowy.ui.main.OnFragmentIsReadyListener; -import io.github.wulkanowy.utils.async.AbstractTask; -import io.github.wulkanowy.utils.async.AsyncListeners; - -import static io.github.wulkanowy.utils.TimeUtilsKt.getFirstDayOfCurrentWeek; -import static io.github.wulkanowy.utils.TimeUtilsKt.getMondaysFromCurrentSchoolYear; - -public class AttendancePresenter extends BasePresenter - implements AttendanceContract.Presenter, AsyncListeners.OnFirstLoadingListener { - - private AbstractTask loadingTask; - - private List dates = new ArrayList<>(); - - private OnFragmentIsReadyListener listener; - - private int positionToScroll = 0; - - private boolean isFirstSight = false; - - @Inject - AttendancePresenter(RepositoryContract repository) { - super(repository); - } - - @Override - public void attachView(@NonNull AttendanceContract.View view, OnFragmentIsReadyListener listener) { - super.attachView(view); - this.listener = listener; - - if (getView().isMenuVisible()) { - getView().setActivityTitle(); - } - - if (dates.isEmpty()) { - dates = getMondaysFromCurrentSchoolYear(); - } - - if (positionToScroll == 0) { - positionToScroll = dates.indexOf(getFirstDayOfCurrentWeek()); - } - - if (!isFirstSight) { - isFirstSight = true; - - loadingTask = new AbstractTask(); - loadingTask.setOnFirstLoadingListener(this); - loadingTask.execute(); - } - } - - @Override - public void onFragmentActivated(boolean isVisible) { - if (isVisible) { - getView().setActivityTitle(); - } - } - - @Override - public void onDoInBackgroundLoading() { - for (String date : dates) { - getView().setTabDataToAdapter(date); - } - } - - @Override - public void onCanceledLoadingAsync() { - //do nothing - - } - - @Override - public void onEndLoadingAsync(boolean result, Exception exception) { - if (result) { - getView().setAdapterWithTabLayout(); - getView().setThemeForTab(positionToScroll); - getView().scrollViewPagerToPosition(positionToScroll); - listener.onFragmentIsReady(); - } - } - - @Override - public void setRestoredPosition(int position) { - this.positionToScroll = position; - } - - @Override - public void detachView() { - isFirstSight = false; - - if (loadingTask != null) { - loadingTask.cancel(true); - loadingTask = null; - } - super.detachView(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceHeader.java b/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceHeader.java deleted file mode 100644 index 86128109..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceHeader.java +++ /dev/null @@ -1,151 +0,0 @@ -package io.github.wulkanowy.ui.main.attendance.tab; - -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.drawable.Drawable; -import android.view.View; -import android.widget.FrameLayout; -import android.widget.ImageView; -import android.widget.TextView; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; - -import java.util.List; - -import butterknife.BindView; -import butterknife.ButterKnife; -import eu.davidea.flexibleadapter.FlexibleAdapter; -import eu.davidea.flexibleadapter.items.AbstractExpandableHeaderItem; -import eu.davidea.flexibleadapter.items.IFlexible; -import eu.davidea.viewholders.ExpandableViewHolder; -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.db.dao.entities.Day; -import io.github.wulkanowy.utils.CommonUtils; - -public class AttendanceHeader - extends AbstractExpandableHeaderItem { - - private Day day; - - AttendanceHeader(Day day) { - this.day = day; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - - if (o == null || getClass() != o.getClass()) return false; - - AttendanceHeader that = (AttendanceHeader) o; - - return new EqualsBuilder() - .append(day, that.day) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) - .append(day) - .toHashCode(); - } - - @Override - public int getLayoutRes() { - return R.layout.attendance_header; - } - - @Override - public HeaderViewHolder createViewHolder(View view, FlexibleAdapter adapter) { - return new HeaderViewHolder(view, adapter); - } - - @Override - public void bindViewHolder(FlexibleAdapter adapter, HeaderViewHolder holder, - int position, List payloads) { - holder.onBind(day, getSubItems()); - } - - static class HeaderViewHolder extends ExpandableViewHolder { - - @BindView(R.id.attendance_header_day) - TextView dayName; - - @BindView(R.id.attendance_header_date) - TextView date; - - @BindView(R.id.attendance_header_description) - TextView description; - - @BindView(R.id.attendance_header_alert_image) - ImageView alert; - - @BindView(R.id.attendance_header_free_name) - TextView freeName; - - private Context context; - - HeaderViewHolder(View view, FlexibleAdapter adapter) { - super(view, adapter); - view.setOnClickListener(this); - ButterKnife.bind(this, view); - context = view.getContext(); - } - - void onBind(Day item, List subItems) { - dayName.setText(StringUtils.capitalize(item.getDayName())); - date.setText(item.getDate()); - - int numberOfHours = countNotPresentHours(subItems); - description.setText((getContentView().getResources().getQuantityString(R.plurals.numberOfAbsences, - numberOfHours, numberOfHours))); - description.setVisibility(numberOfHours > 0 ? View.VISIBLE : View.INVISIBLE); - alert.setVisibility(isSubItemsHasChanges(subItems) ? View.VISIBLE : View.INVISIBLE); - freeName.setVisibility(subItems.isEmpty() ? View.VISIBLE : View.INVISIBLE); - setInactiveHeader(item.getAttendanceLessons().isEmpty()); - } - - private void setInactiveHeader(boolean inactive) { - ((FrameLayout) getContentView()).setForeground(inactive ? null : getSelectableDrawable()); - dayName.setTextColor(CommonUtils.getThemeAttrColor(context, - inactive ? android.R.attr.textColorSecondary : android.R.attr.textColorPrimary)); - - if (inactive) { - getContentView().setBackgroundColor(CommonUtils.getThemeAttrColor(context, R.attr.colorControlHighlight)); - } else { - getContentView().setBackgroundDrawable(context.getResources().getDrawable(R.drawable.ic_border)); - } - } - - private Drawable getSelectableDrawable() { - int[] attrs = new int[]{R.attr.selectableItemBackground}; - TypedArray typedArray = context.obtainStyledAttributes(attrs); - Drawable drawable = typedArray.getDrawable(0); - typedArray.recycle(); - return drawable; - } - - private int countNotPresentHours(List subItems) { - int i = 0; - for (AttendanceSubItem subItem : subItems) { - if (subItem.getLesson().getAbsenceUnexcused()) { - i++; - } - } - return i; - } - - private boolean isSubItemsHasChanges(List subItems) { - for (AttendanceSubItem subItem : subItems) { - if (subItem.getLesson().getAbsenceUnexcused() || subItem.getLesson() - .getUnexcusedLateness()) { - return true; - } - } - return false; - } - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceSubItem.java b/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceSubItem.java deleted file mode 100644 index 65c8329e..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceSubItem.java +++ /dev/null @@ -1,122 +0,0 @@ -package io.github.wulkanowy.ui.main.attendance.tab; - -import android.content.Context; -import android.support.v4.app.DialogFragment; -import android.support.v4.app.FragmentActivity; -import android.view.View; -import android.widget.ImageView; -import android.widget.TextView; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; - -import java.util.List; - -import butterknife.BindView; -import butterknife.ButterKnife; -import eu.davidea.flexibleadapter.FlexibleAdapter; -import eu.davidea.flexibleadapter.items.AbstractSectionableItem; -import eu.davidea.flexibleadapter.items.IFlexible; -import eu.davidea.viewholders.FlexibleViewHolder; -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.db.dao.entities.AttendanceLesson; -import io.github.wulkanowy.ui.main.attendance.AttendanceDialogFragment; - -class AttendanceSubItem - extends AbstractSectionableItem { - - private AttendanceLesson lesson; - - AttendanceSubItem(AttendanceHeader header, AttendanceLesson lesson) { - super(header); - this.lesson = lesson; - } - - AttendanceLesson getLesson() { - return lesson; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - - if (o == null || getClass() != o.getClass()) return false; - - AttendanceSubItem that = (AttendanceSubItem) o; - - return new EqualsBuilder() - .append(lesson, that.lesson) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) - .append(lesson) - .toHashCode(); - } - - @Override - public int getLayoutRes() { - return R.layout.attendance_subitem; - } - - @Override - public SubItemViewHolder createViewHolder(View view, FlexibleAdapter adapter) { - return new SubItemViewHolder(view, adapter); - } - - @Override - public void bindViewHolder(FlexibleAdapter adapter, SubItemViewHolder holder, - int position, List payloads) { - holder.onBind(lesson); - } - - static class SubItemViewHolder extends FlexibleViewHolder { - - @BindView(R.id.attendance_subItem_lesson) - TextView lessonName; - - @BindView(R.id.attendance_subItem_number) - TextView lessonNumber; - - @BindView(R.id.attendance_subItem_description) - TextView lessonDescription; - - @BindView(R.id.attendance_subItem_alert_image) - ImageView alert; - - private Context context; - - private AttendanceLesson item; - - SubItemViewHolder(View view, FlexibleAdapter adapter) { - super(view, adapter); - ButterKnife.bind(this, view); - context = view.getContext(); - view.setOnClickListener(this); - } - - void onBind(AttendanceLesson lesson) { - item = lesson; - - lessonName.setText(lesson.getSubject()); - lessonNumber.setText((String.valueOf(lesson.getNumber()))); - lessonDescription.setText(lesson.getDescription()); - alert.setVisibility(lesson.getAbsenceUnexcused() || lesson.getUnexcusedLateness() - ? View.VISIBLE : View.INVISIBLE); - } - - @Override - public void onClick(View view) { - super.onClick(view); - showDialog(); - } - - private void showDialog() { - AttendanceDialogFragment dialogFragment = AttendanceDialogFragment.newInstance(item); - dialogFragment.setStyle(DialogFragment.STYLE_NO_TITLE, 0); - dialogFragment.show(((FragmentActivity) context).getSupportFragmentManager(), item.toString()); - } - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceTabContract.java b/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceTabContract.java deleted file mode 100644 index a83e67e8..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceTabContract.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.github.wulkanowy.ui.main.attendance.tab; - -import java.util.List; - -import io.github.wulkanowy.ui.base.BaseContract; - -public interface AttendanceTabContract { - - interface View extends BaseContract.View { - - void updateAdapterList(List headerItems); - - void onRefreshSuccess(); - - void hideRefreshingBar(); - - void showNoItem(boolean show); - - void showProgressBar(boolean show); - } - - interface Presenter extends BaseContract.Presenter { - - void onFragmentActivated(boolean isSelected); - - void setArgumentDate(String date); - - void onRefresh(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceTabFragment.java b/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceTabFragment.java deleted file mode 100644 index 8de47469..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceTabFragment.java +++ /dev/null @@ -1,129 +0,0 @@ -package io.github.wulkanowy.ui.main.attendance.tab; - -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.v4.widget.SwipeRefreshLayout; -import android.support.v7.widget.RecyclerView; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import java.util.List; - -import javax.inject.Inject; - -import butterknife.BindView; -import eu.davidea.flexibleadapter.FlexibleAdapter; -import eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager; -import io.github.wulkanowy.R; -import io.github.wulkanowy.ui.base.BaseFragment; - -public class AttendanceTabFragment extends BaseFragment implements AttendanceTabContract.View, - SwipeRefreshLayout.OnRefreshListener { - - private static final String ARGUMENT_KEY = "date"; - - @BindView(R.id.attendance_tab_fragment_recycler) - RecyclerView recyclerView; - - @BindView(R.id.attendance_tab_fragment_swipe_refresh) - SwipeRefreshLayout refreshLayout; - - @BindView(R.id.attendance_tab_fragment_progress_bar) - View progressBar; - - @BindView(R.id.attendance_tab_fragment_no_item_container) - View noItemView; - - @Inject - AttendanceTabContract.Presenter presenter; - - @Inject - FlexibleAdapter adapter; - - private boolean isFragmentVisible = false; - - public static AttendanceTabFragment newInstance(String date) { - AttendanceTabFragment fragmentTab = new AttendanceTabFragment(); - - Bundle bundle = new Bundle(); - bundle.putString(ARGUMENT_KEY, date); - fragmentTab.setArguments(bundle); - - return fragmentTab; - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_attendance_tab, container, false); - injectViews(view); - - if (getArguments() != null) { - presenter.setArgumentDate(getArguments().getString(ARGUMENT_KEY)); - } - - presenter.attachView(this); - presenter.onFragmentActivated(isFragmentVisible); - return view; - } - - @Override - public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { - adapter.setAutoCollapseOnExpand(true); - adapter.setAutoScrollOnExpand(true); - adapter.expandItemsAtStartUp(); - - recyclerView.setLayoutManager(new SmoothScrollLinearLayoutManager(view.getContext())); - recyclerView.setAdapter(adapter); - - refreshLayout.setColorSchemeResources(android.R.color.black); - refreshLayout.setOnRefreshListener(this); - } - - @Override - public void updateAdapterList(List headerItems) { - adapter.updateDataSet(headerItems); - } - - @Override - public void setMenuVisibility(boolean menuVisible) { - super.setMenuVisibility(menuVisible); - isFragmentVisible = menuVisible; - if (presenter != null) { - presenter.onFragmentActivated(menuVisible); - } - } - - @Override - public void onRefresh() { - presenter.onRefresh(); - } - - @Override - public void onRefreshSuccess() { - showMessage(R.string.sync_completed); - } - - @Override - public void hideRefreshingBar() { - refreshLayout.setRefreshing(false); - } - - @Override - public void showProgressBar(boolean show) { - progressBar.setVisibility(show ? View.VISIBLE : View.INVISIBLE); - } - - @Override - public void showNoItem(boolean show) { - noItemView.setVisibility(show ? View.VISIBLE : View.INVISIBLE); - } - - @Override - public void onDestroyView() { - presenter.detachView(); - super.onDestroyView(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceTabModule.java b/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceTabModule.java deleted file mode 100644 index 380a221f..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceTabModule.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.github.wulkanowy.ui.main.attendance.tab; - -import dagger.Binds; -import dagger.Module; -import dagger.Provides; -import eu.davidea.flexibleadapter.FlexibleAdapter; -import io.github.wulkanowy.di.scopes.PerChildFragment; - -@Module -public abstract class AttendanceTabModule { - - @PerChildFragment - @Binds - abstract AttendanceTabContract.Presenter provideAttendanceTabPresenter(AttendanceTabPresenter attendanceTabPresenter); - - @PerChildFragment - @Provides - static FlexibleAdapter provideAdapter() { - return new FlexibleAdapter<>(null); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceTabPresenter.java b/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceTabPresenter.java deleted file mode 100644 index 7d0c26e5..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceTabPresenter.java +++ /dev/null @@ -1,194 +0,0 @@ -package io.github.wulkanowy.ui.main.attendance.tab; - -import android.support.annotation.NonNull; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import io.github.wulkanowy.data.RepositoryContract; -import io.github.wulkanowy.data.db.dao.entities.AttendanceLesson; -import io.github.wulkanowy.data.db.dao.entities.Day; -import io.github.wulkanowy.data.db.dao.entities.Week; -import io.github.wulkanowy.ui.base.BasePresenter; -import io.github.wulkanowy.utils.FabricUtils; -import io.github.wulkanowy.utils.async.AbstractTask; -import io.github.wulkanowy.utils.async.AsyncListeners; - -public class AttendanceTabPresenter extends BasePresenter - implements AttendanceTabContract.Presenter, AsyncListeners.OnRefreshListener, - AsyncListeners.OnFirstLoadingListener { - - private AbstractTask refreshTask; - - private AbstractTask loadingTask; - - private List headerItems = new ArrayList<>(); - - private String date; - - private boolean isFirstSight = false; - - @Inject - AttendanceTabPresenter(RepositoryContract repository) { - super(repository); - } - - @Override - public void attachView(@NonNull AttendanceTabContract.View view) { - super.attachView(view); - - getView().showProgressBar(true); - getView().showNoItem(false); - } - - @Override - public void onFragmentActivated(boolean isSelected) { - if (!isFirstSight && isSelected && isViewAttached()) { - isFirstSight = true; - - loadingTask = new AbstractTask(); - loadingTask.setOnFirstLoadingListener(this); - loadingTask.execute(); - } else if (!isSelected) { - cancelAsyncTasks(); - } - } - - @Override - public void onRefresh() { - if (getView().isNetworkConnected()) { - refreshTask = new AbstractTask(); - refreshTask.setOnRefreshListener(this); - refreshTask.execute(); - } else { - getView().showNoNetworkMessage(); - getView().hideRefreshingBar(); - } - } - - @Override - public void onDoInBackgroundRefresh() throws Exception { - syncData(); - } - - @Override - public void onCanceledRefreshAsync() { - if (isViewAttached()) { - getView().hideRefreshingBar(); - } - } - - @Override - public void onEndRefreshAsync(boolean result, Exception exception) { - if (result) { - loadingTask = new AbstractTask(); - loadingTask.setOnFirstLoadingListener(this); - loadingTask.execute(); - - getView().onRefreshSuccess(); - } else { - getView().showMessage(getRepository().getResRepo().getErrorLoginMessage(exception)); - } - getView().hideRefreshingBar(); - - FabricUtils.logRefresh("Attendance", result, date); - } - - @Override - public void onDoInBackgroundLoading() throws Exception { - Week week = getRepository().getDbRepo().getWeek(date); - boolean isShowPresent = getRepository().getSharedRepo().isShowAttendancePresent(); - - if (week == null || !week.getAttendanceSynced()) { - syncData(); - week = getRepository().getDbRepo().getWeek(date); - } - - week.resetDayList(); - List dayList = week.getDayList(); - - headerItems = new ArrayList<>(); - - boolean isEmptyWeek = true; - - for (Day day : dayList) { - day.resetAttendanceLessons(); - AttendanceHeader headerItem = new AttendanceHeader(day); - - if (isEmptyWeek) { - isEmptyWeek = day.getAttendanceLessons().isEmpty(); - } - - List lessonList = day.getAttendanceLessons(); - - List subItems = new ArrayList<>(); - - for (AttendanceLesson lesson : lessonList) { - if (!isShowPresent && lesson.getPresence()) { - continue; - } - - lesson.setDescription(getRepository().getResRepo().getAttendanceLessonDescription(lesson)); - subItems.add(new AttendanceSubItem(headerItem, lesson)); - } - - if (!isShowPresent && subItems.isEmpty()) { - continue; - } - - headerItem.setSubItems(subItems); - headerItem.setExpanded(false); - headerItems.add(headerItem); - } - - if (isEmptyWeek) { - headerItems = new ArrayList<>(); - } - } - - @Override - public void onCanceledLoadingAsync() { - // do nothing - } - - @Override - public void onEndLoadingAsync(boolean result, Exception exception) { - if (headerItems.isEmpty()) { - getView().showNoItem(true); - getView().updateAdapterList(null); - } else { - getView().updateAdapterList(headerItems); - getView().showNoItem(false); - } - getView().showProgressBar(false); - } - - @Override - public void setArgumentDate(String date) { - this.date = date; - } - - private void syncData() throws Exception { - getRepository().getSyncRepo().syncAttendance(0, date); - } - - private void cancelAsyncTasks() { - if (refreshTask != null) { - refreshTask.cancel(true); - refreshTask = null; - } - if (loadingTask != null) { - loadingTask.cancel(true); - loadingTask = null; - } - } - - @Override - public void detachView() { - cancelAsyncTasks(); - isFirstSight = false; - super.detachView(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsContract.java b/app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsContract.java deleted file mode 100644 index aeeecea8..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsContract.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.github.wulkanowy.ui.main.exams; - -import android.support.annotation.NonNull; - -import io.github.wulkanowy.ui.base.BaseContract; -import io.github.wulkanowy.ui.main.OnFragmentIsReadyListener; - -public interface ExamsContract { - - interface View extends BaseContract.View { - - void setActivityTitle(); - - boolean isMenuVisible(); - - void scrollViewPagerToPosition(int position); - - void setTabDataToAdapter(String date); - - void setAdapterWithTabLayout(); - - void setThemeForTab(int position); - } - - interface Presenter extends BaseContract.Presenter { - - void attachView(@NonNull View view, OnFragmentIsReadyListener listener); - - void onFragmentActivated(boolean isVisible); - - void setRestoredPosition(int position); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsDialogFragment.java b/app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsDialogFragment.java deleted file mode 100644 index 8c4fafcd..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsDialogFragment.java +++ /dev/null @@ -1,81 +0,0 @@ -package io.github.wulkanowy.ui.main.exams; - - -import android.os.Bundle; -import android.support.annotation.Nullable; -import android.support.v4.app.DialogFragment; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.db.dao.entities.Exam; - -public class ExamsDialogFragment extends DialogFragment { - - private static final String ARGUMENT_KEY = "Item"; - - private Exam exam; - - @BindView(R.id.exams_dialog_subject_value) - TextView subject; - - @BindView(R.id.exams_dialog_type_value) - TextView type; - - @BindView(R.id.exams_dialog_teacher_value) - TextView teacher; - - @BindView(R.id.exams_dialog_date_value) - TextView entryDate; - - @BindView(R.id.exams_dialog_description_value) - TextView description; - - public static ExamsDialogFragment newInstance(Exam exam) { - ExamsDialogFragment dialogFragment = new ExamsDialogFragment(); - - Bundle bundle = new Bundle(); - bundle.putSerializable(ARGUMENT_KEY, exam); - - dialogFragment.setArguments(bundle); - - return dialogFragment; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - exam = (Exam) getArguments().getSerializable(ARGUMENT_KEY); - } - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.exams_dialog, container, false); - - ButterKnife.bind(this, view); - - subject.setText(exam.getSubjectAndGroup()); - teacher.setText(exam.getTeacher()); - type.setText(exam.getType()); - entryDate.setText(exam.getEntryDate()); - - if (!exam.getDescription().isEmpty()) { - description.setText(exam.getDescription()); - } - - return view; - } - - @OnClick(R.id.exams_dialog_close) - void onClickCloseButton() { - dismiss(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsFragment.java b/app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsFragment.java deleted file mode 100644 index 05557b81..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsFragment.java +++ /dev/null @@ -1,100 +0,0 @@ -package io.github.wulkanowy.ui.main.exams; - -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.design.widget.TabLayout; -import android.support.v4.view.ViewPager; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import javax.inject.Inject; -import javax.inject.Named; - -import butterknife.BindView; -import io.github.wulkanowy.R; -import io.github.wulkanowy.ui.base.BaseFragment; -import io.github.wulkanowy.ui.base.BasePagerAdapter; -import io.github.wulkanowy.ui.main.OnFragmentIsReadyListener; -import io.github.wulkanowy.ui.main.exams.tab.ExamsTabFragment; - -public class ExamsFragment extends BaseFragment implements ExamsContract.View { - - private static final String CURRENT_ITEM_KEY = "CurrentItem"; - - @BindView(R.id.exams_fragment_viewpager) - ViewPager viewPager; - - @BindView(R.id.exams_fragment_tab_layout) - TabLayout tabLayout; - - @Inject - @Named("Exams") - BasePagerAdapter pagerAdapter; - - @Inject - ExamsContract.Presenter presenter; - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_exams, container, false); - injectViews(view); - - presenter.attachView(this, (OnFragmentIsReadyListener) getActivity()); - - if (savedInstanceState != null) { - presenter.setRestoredPosition(savedInstanceState.getInt(CURRENT_ITEM_KEY)); - } - return view; - } - - @Override - public void setMenuVisibility(boolean menuVisible) { - super.setMenuVisibility(menuVisible); - if (presenter != null) { - presenter.onFragmentActivated(menuVisible); - } - } - - @Override - public void setActivityTitle() { - setTitle(getString(R.string.exams_text)); - } - - @Override - public void scrollViewPagerToPosition(int position) { - viewPager.setCurrentItem(position, false); - } - - @Override - public void setThemeForTab(int position) { - TabLayout.Tab tab = tabLayout.getTabAt(position); - if (tab != null) { - tab.setCustomView(R.layout.current_week_tab); - } - } - - @Override - public void setTabDataToAdapter(String date) { - pagerAdapter.addFragment(ExamsTabFragment.newInstance(date), date); - } - - @Override - public void setAdapterWithTabLayout() { - viewPager.setAdapter(pagerAdapter); - tabLayout.setupWithViewPager(viewPager); - } - - @Override - public void onSaveInstanceState(Bundle outState) { - outState.putInt(CURRENT_ITEM_KEY, viewPager.getCurrentItem()); - super.onSaveInstanceState(outState); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - presenter.detachView(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsModule.java b/app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsModule.java deleted file mode 100644 index 8d56cf23..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsModule.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.github.wulkanowy.ui.main.exams; - -import javax.inject.Named; - -import dagger.Binds; -import dagger.Module; -import dagger.Provides; -import dagger.android.ContributesAndroidInjector; -import io.github.wulkanowy.di.scopes.PerChildFragment; -import io.github.wulkanowy.di.scopes.PerFragment; -import io.github.wulkanowy.ui.base.BasePagerAdapter; -import io.github.wulkanowy.ui.main.exams.tab.ExamsTabFragment; -import io.github.wulkanowy.ui.main.exams.tab.ExamsTabModule; - -@Module -public abstract class ExamsModule { - - @PerFragment - @Binds - abstract ExamsContract.Presenter provideExamsPresneter(ExamsPresenter examsPresenter); - - @Named("Exams") - @PerFragment - @Provides - static BasePagerAdapter providePagerAdapter(ExamsFragment fragment) { - return new BasePagerAdapter(fragment.getChildFragmentManager()); - } - - @PerChildFragment - @ContributesAndroidInjector(modules = ExamsTabModule.class) - abstract ExamsTabFragment bindExamsTabFragment(); -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsPresenter.java b/app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsPresenter.java deleted file mode 100644 index 20c0fe2e..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsPresenter.java +++ /dev/null @@ -1,107 +0,0 @@ -package io.github.wulkanowy.ui.main.exams; - -import android.support.annotation.NonNull; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import io.github.wulkanowy.data.RepositoryContract; -import io.github.wulkanowy.ui.base.BasePresenter; -import io.github.wulkanowy.ui.main.OnFragmentIsReadyListener; -import io.github.wulkanowy.utils.async.AbstractTask; -import io.github.wulkanowy.utils.async.AsyncListeners; - -import static io.github.wulkanowy.utils.TimeUtilsKt.getFirstDayOfCurrentWeek; -import static io.github.wulkanowy.utils.TimeUtilsKt.getMondaysFromCurrentSchoolYear; - -public class ExamsPresenter extends BasePresenter - implements ExamsContract.Presenter, AsyncListeners.OnFirstLoadingListener { - - private AbstractTask loadingTask; - - private List dates = new ArrayList<>(); - - private OnFragmentIsReadyListener listener; - - private int positionToScroll = 0; - - private boolean isFirstSight = false; - - @Inject - ExamsPresenter(RepositoryContract repository) { - super(repository); - } - - @Override - public void attachView(@NonNull ExamsContract.View view, OnFragmentIsReadyListener listener) { - super.attachView(view); - this.listener = listener; - - if (getView().isMenuVisible()) { - getView().setActivityTitle(); - } - - if (dates.isEmpty()) { - dates = getMondaysFromCurrentSchoolYear(); - } - - if (positionToScroll == 0) { - positionToScroll = dates.indexOf(getFirstDayOfCurrentWeek()); - } - - if (!isFirstSight) { - isFirstSight = true; - - loadingTask = new AbstractTask(); - loadingTask.setOnFirstLoadingListener(this); - loadingTask.execute(); - } - } - - @Override - public void onFragmentActivated(boolean isVisible) { - if (isVisible) { - getView().setActivityTitle(); - } - } - - @Override - public void setRestoredPosition(int position) { - this.positionToScroll = position; - } - - @Override - public void onDoInBackgroundLoading() { - for (String date : dates) { - getView().setTabDataToAdapter(date); - } - } - - @Override - public void onCanceledLoadingAsync() { - // do nothing - } - - @Override - public void onEndLoadingAsync(boolean result, Exception exception) { - if (result) { - getView().setAdapterWithTabLayout(); - getView().setThemeForTab(positionToScroll); - getView().scrollViewPagerToPosition(positionToScroll); - listener.onFragmentIsReady(); - } - } - - @Override - public void detachView() { - isFirstSight = false; - - if (loadingTask != null) { - loadingTask.cancel(true); - loadingTask = null; - } - super.detachView(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsHeader.java b/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsHeader.java deleted file mode 100644 index 6c0c364e..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsHeader.java +++ /dev/null @@ -1,82 +0,0 @@ -package io.github.wulkanowy.ui.main.exams.tab; - -import android.view.View; -import android.widget.TextView; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; - -import java.util.List; - -import butterknife.BindView; -import butterknife.ButterKnife; -import eu.davidea.flexibleadapter.FlexibleAdapter; -import eu.davidea.flexibleadapter.items.AbstractHeaderItem; -import eu.davidea.flexibleadapter.items.IFlexible; -import eu.davidea.viewholders.FlexibleViewHolder; -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.db.dao.entities.Day; - -public class ExamsHeader extends AbstractHeaderItem { - - private Day day; - - ExamsHeader(Day day) { - this.day = day; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - - if (o == null || getClass() != o.getClass()) return false; - - ExamsHeader that = (ExamsHeader) o; - - return new EqualsBuilder() - .append(day, that.day) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) - .append(day) - .toHashCode(); - } - - @Override - public int getLayoutRes() { - return R.layout.exams_header; - } - - @Override - public HeaderVieHolder createViewHolder(View view, FlexibleAdapter adapter) { - return new HeaderVieHolder(view, adapter); - } - - @Override - public void bindViewHolder(FlexibleAdapter adapter, HeaderVieHolder holder, int position, List payloads) { - holder.onBind(day); - } - - static class HeaderVieHolder extends FlexibleViewHolder { - - @BindView(R.id.exams_header_name) - TextView name; - - @BindView(R.id.exams_header_date) - TextView date; - - HeaderVieHolder(View view, FlexibleAdapter adapter) { - super(view, adapter); - ButterKnife.bind(this, view); - } - - void onBind(Day item) { - name.setText(StringUtils.capitalize(item.getDayName())); - date.setText(item.getDate()); - } - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsSubItem.java b/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsSubItem.java deleted file mode 100644 index 9ff10ebc..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsSubItem.java +++ /dev/null @@ -1,109 +0,0 @@ -package io.github.wulkanowy.ui.main.exams.tab; - -import android.support.v4.app.DialogFragment; -import android.support.v4.app.FragmentActivity; -import android.view.View; -import android.widget.TextView; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; - -import java.util.List; - -import butterknife.BindView; -import butterknife.ButterKnife; -import eu.davidea.flexibleadapter.FlexibleAdapter; -import eu.davidea.flexibleadapter.items.AbstractSectionableItem; -import eu.davidea.flexibleadapter.items.IFlexible; -import eu.davidea.viewholders.FlexibleViewHolder; -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.db.dao.entities.Exam; -import io.github.wulkanowy.ui.main.exams.ExamsDialogFragment; - -public class ExamsSubItem - extends AbstractSectionableItem { - - private Exam exam; - - ExamsSubItem(ExamsHeader header, Exam exam) { - super(header); - this.exam = exam; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - - if (o == null || getClass() != o.getClass()) return false; - - ExamsSubItem that = (ExamsSubItem) o; - - return new EqualsBuilder() - .append(exam, that.exam) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) - .append(exam) - .toHashCode(); - } - - @Override - public int getLayoutRes() { - return R.layout.exams_subitem; - } - - @Override - public SubItemViewHolder createViewHolder(View view, FlexibleAdapter adapter) { - return new SubItemViewHolder(view, adapter); - } - - @Override - public void bindViewHolder(FlexibleAdapter adapter, SubItemViewHolder holder, int position, List payloads) { - holder.onBind(exam); - } - - static class SubItemViewHolder extends FlexibleViewHolder { - - @BindView(R.id.exams_subitem_subject) - TextView subject; - - @BindView(R.id.exams_subitems_teacher) - TextView teacher; - - @BindView(R.id.exams_subitems_type) - TextView type; - - private Exam item; - - SubItemViewHolder(View view, FlexibleAdapter adapter) { - super(view, adapter); - ButterKnife.bind(this, view); - view.setOnClickListener(this); - } - - void onBind(Exam exam) { - item = exam; - - subject.setText(item.getSubjectAndGroup()); - teacher.setText(item.getTeacher()); - type.setText(item.getType()); - } - - @Override - public void onClick(View view) { - super.onClick(view); - showDialog(); - - } - - private void showDialog() { - ExamsDialogFragment dialogFragment = ExamsDialogFragment.newInstance(item); - dialogFragment.setStyle(DialogFragment.STYLE_NO_TITLE, 0); - dialogFragment.show(((FragmentActivity) getContentView().getContext()).getSupportFragmentManager(), - item.toString()); - } - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsTabContract.java b/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsTabContract.java deleted file mode 100644 index 4e0785bb..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsTabContract.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.github.wulkanowy.ui.main.exams.tab; - -import java.util.List; - -import io.github.wulkanowy.ui.base.BaseContract; - -public interface ExamsTabContract { - - interface View extends BaseContract.View { - - void onRefreshSuccess(); - - void hideRefreshingBar(); - - void showNoItem(boolean show); - - void showProgressBar(boolean show); - - void updateAdapterList(List headerItems); - } - - interface Presenter extends BaseContract.Presenter { - - void onFragmentActivated(boolean isSelected); - - void setArgumentDate(String date); - - void onRefresh(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsTabFragment.java b/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsTabFragment.java deleted file mode 100644 index 1b6f361a..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsTabFragment.java +++ /dev/null @@ -1,126 +0,0 @@ -package io.github.wulkanowy.ui.main.exams.tab; - -import android.os.Bundle; -import android.support.annotation.Nullable; -import android.support.v4.widget.SwipeRefreshLayout; -import android.support.v7.widget.RecyclerView; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import java.util.List; - -import javax.inject.Inject; - -import butterknife.BindView; -import eu.davidea.flexibleadapter.FlexibleAdapter; -import eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager; -import io.github.wulkanowy.R; -import io.github.wulkanowy.ui.base.BaseFragment; - -public class ExamsTabFragment extends BaseFragment implements ExamsTabContract.View, - SwipeRefreshLayout.OnRefreshListener { - - private static final String ARGUMENT_KEY = "date"; - - @BindView(R.id.exams_tab_fragment_recycler) - RecyclerView recyclerView; - - @BindView(R.id.exams_tab_fragment_swipe_refresh) - SwipeRefreshLayout refreshLayout; - - @BindView(R.id.exams_tab_fragment_progress_bar) - View progressBar; - - @BindView(R.id.exams_tab_fragment_no_item_container) - View noItemView; - - @Inject - ExamsTabContract.Presenter presenter; - - @Inject - FlexibleAdapter adapter; - - private boolean isFragmentVisible = false; - - public static ExamsTabFragment newInstance(String date) { - ExamsTabFragment tabFragment = new ExamsTabFragment(); - - Bundle bundle = new Bundle(); - bundle.putString(ARGUMENT_KEY, date); - tabFragment.setArguments(bundle); - - return tabFragment; - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_exams_tab, container, false); - injectViews(view); - - if (getArguments() != null) { - presenter.setArgumentDate(getArguments().getString(ARGUMENT_KEY)); - } - presenter.attachView(this); - presenter.onFragmentActivated(isFragmentVisible); - return view; - } - - @Override - public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { - adapter.setDisplayHeadersAtStartUp(true); - - recyclerView.setLayoutManager(new SmoothScrollLinearLayoutManager(view.getContext())); - recyclerView.setAdapter(adapter); - - refreshLayout.setColorSchemeResources(android.R.color.black); - refreshLayout.setOnRefreshListener(this); - } - - @Override - public void setMenuVisibility(boolean menuVisible) { - super.setMenuVisibility(menuVisible); - isFragmentVisible = menuVisible; - if (presenter != null) { - presenter.onFragmentActivated(menuVisible); - } - } - - @Override - public void updateAdapterList(List headerItems) { - adapter.updateDataSet(headerItems); - } - - @Override - public void onRefresh() { - presenter.onRefresh(); - } - - @Override - public void onRefreshSuccess() { - showMessage(R.string.sync_completed); - } - - @Override - public void hideRefreshingBar() { - refreshLayout.setRefreshing(false); - } - - @Override - public void showNoItem(boolean show) { - noItemView.setVisibility(show ? View.VISIBLE : View.INVISIBLE); - } - - @Override - public void showProgressBar(boolean show) { - progressBar.setVisibility(show ? View.VISIBLE : View.INVISIBLE); - } - - - @Override - public void onDestroyView() { - presenter.detachView(); - super.onDestroyView(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsTabModule.java b/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsTabModule.java deleted file mode 100644 index fc9a7595..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsTabModule.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.github.wulkanowy.ui.main.exams.tab; - -import dagger.Binds; -import dagger.Module; -import dagger.Provides; -import eu.davidea.flexibleadapter.FlexibleAdapter; -import io.github.wulkanowy.di.scopes.PerChildFragment; - -@Module -public abstract class ExamsTabModule { - - @PerChildFragment - @Binds - abstract ExamsTabContract.Presenter provideExamsTabPresenter(ExamsTabPresenter examsTabPresenter); - - @PerChildFragment - @Provides - static FlexibleAdapter provideAdapter() { - return new FlexibleAdapter<>(null); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsTabPresenter.java b/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsTabPresenter.java deleted file mode 100644 index b60a4607..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsTabPresenter.java +++ /dev/null @@ -1,167 +0,0 @@ -package io.github.wulkanowy.ui.main.exams.tab; - -import android.support.annotation.NonNull; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import io.github.wulkanowy.data.RepositoryContract; -import io.github.wulkanowy.data.db.dao.entities.Day; -import io.github.wulkanowy.data.db.dao.entities.Exam; -import io.github.wulkanowy.data.db.dao.entities.Week; -import io.github.wulkanowy.ui.base.BasePresenter; -import io.github.wulkanowy.utils.FabricUtils; -import io.github.wulkanowy.utils.async.AbstractTask; -import io.github.wulkanowy.utils.async.AsyncListeners; - -public class ExamsTabPresenter extends BasePresenter - implements ExamsTabContract.Presenter, AsyncListeners.OnFirstLoadingListener, - AsyncListeners.OnRefreshListener { - - private AbstractTask refreshTask; - - private AbstractTask loadingTask; - - private List subItems = new ArrayList<>(); - - private String date; - - private boolean isFirstSight = false; - - @Inject - ExamsTabPresenter(RepositoryContract repository) { - super(repository); - } - - @Override - public void attachView(@NonNull ExamsTabContract.View view) { - super.attachView(view); - getView().showProgressBar(true); - getView().showNoItem(false); - } - - @Override - public void onFragmentActivated(boolean isSelected) { - if (!isFirstSight && isSelected && isViewAttached()) { - isFirstSight = true; - - loadingTask = new AbstractTask(); - loadingTask.setOnFirstLoadingListener(this); - loadingTask.execute(); - } else if (!isSelected) { - cancelAsyncTasks(); - } - } - - @Override - public void setArgumentDate(String date) { - this.date = date; - } - - @Override - public void onRefresh() { - if (getView().isNetworkConnected()) { - refreshTask = new AbstractTask(); - refreshTask.setOnRefreshListener(this); - refreshTask.execute(); - } else { - getView().showNoNetworkMessage(); - getView().hideRefreshingBar(); - } - } - - @Override - public void onDoInBackgroundRefresh() throws Exception { - syncData(); - } - - @Override - public void onCanceledRefreshAsync() { - if (isViewAttached()) { - getView().hideRefreshingBar(); - } - } - - @Override - public void onEndRefreshAsync(boolean result, Exception exception) { - if (result) { - loadingTask = new AbstractTask(); - loadingTask.setOnFirstLoadingListener(this); - loadingTask.execute(); - - getView().onRefreshSuccess(); - } else { - getView().showMessage(getRepository().getResRepo().getErrorLoginMessage(exception)); - } - getView().hideRefreshingBar(); - - FabricUtils.logRefresh("Exams", result, date); - } - - @Override - public void onDoInBackgroundLoading() throws Exception { - Week week = getRepository().getDbRepo().getWeek(date); - - if (week == null || !week.getExamsSynced()) { - syncData(); - week = getRepository().getDbRepo().getWeek(date); - } - - week.resetDayList(); - List dayList = week.getDayList(); - - subItems = new ArrayList<>(); - - for (Day day : dayList) { - day.resetExams(); - ExamsHeader headerItem = new ExamsHeader(day); - - List examList = day.getExams(); - - for (Exam exam : examList) { - subItems.add(new ExamsSubItem(headerItem, exam)); - } - } - } - - @Override - public void onCanceledLoadingAsync() { - // do nothing - } - - @Override - public void onEndLoadingAsync(boolean result, Exception exception) { - if (subItems.isEmpty()) { - getView().showNoItem(true); - getView().updateAdapterList(null); - } else { - getView().updateAdapterList(subItems); - getView().showNoItem(false); - } - getView().showProgressBar(false); - } - - private void syncData() throws Exception { - getRepository().getSyncRepo().syncExams(0, date); - } - - private void cancelAsyncTasks() { - if (refreshTask != null) { - refreshTask.cancel(true); - refreshTask = null; - } - if (loadingTask != null) { - loadingTask.cancel(true); - loadingTask = null; - } - } - - @Override - public void detachView() { - isFirstSight = false; - cancelAsyncTasks(); - super.detachView(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesContract.java b/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesContract.java deleted file mode 100644 index d2423ec8..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesContract.java +++ /dev/null @@ -1,49 +0,0 @@ -package io.github.wulkanowy.ui.main.grades; - -import android.support.annotation.NonNull; -import android.support.v4.widget.SwipeRefreshLayout; - -import java.util.List; - -import io.github.wulkanowy.ui.base.BaseContract; -import io.github.wulkanowy.ui.main.OnFragmentIsReadyListener; - -public interface GradesContract { - - interface View extends BaseContract.View, SwipeRefreshLayout.OnRefreshListener { - - void updateAdapterList(List headerItems); - - void updateSummaryAdapterList(List summarySubItems); - - void showNoItem(boolean show); - - void onRefreshSuccessNoGrade(); - - void onRefreshSuccess(int number); - - void hideRefreshingBar(); - - void setActivityTitle(); - - void setCurrentSemester(int semester); - - boolean isMenuVisible(); - - void setSummaryAverages(String calculatedValue, String predictedValue, String finalValue ); - - } - - interface Presenter extends BaseContract.Presenter { - - void onFragmentVisible(boolean isVisible); - - void onRefresh(); - - void attachView(@NonNull View view, OnFragmentIsReadyListener listener); - - void onSemesterChange(int which); - - void onSemesterSwitchActive(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesDialogFragment.java b/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesDialogFragment.java deleted file mode 100644 index 17ebc6e6..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesDialogFragment.java +++ /dev/null @@ -1,117 +0,0 @@ -package io.github.wulkanowy.ui.main.grades; - - -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.v4.app.DialogFragment; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.db.dao.entities.Grade; -import io.github.wulkanowy.utils.CommonUtils; -import io.github.wulkanowy.utils.GradeUtils; - -public class GradesDialogFragment extends DialogFragment { - - private static final String ARGUMENT_KEY = "Item"; - - private Grade grade; - - @BindView(R.id.grade_dialog_value) - TextView value; - - @BindView(R.id.grade_dialog_subject) - TextView subject; - - @BindView(R.id.grade_dialog_description_value) - TextView description; - - @BindView(R.id.grade_dialog_weight_value) - TextView weight; - - @BindView(R.id.grade_dialog_teacher_value) - TextView teacher; - - @BindView(R.id.grade_dialog_color_value) - TextView color; - - @BindView(R.id.grade_dialog_date_value) - TextView date; - - public GradesDialogFragment() { - //empty constructor for fragment - } - - public static GradesDialogFragment newInstance(Grade item) { - GradesDialogFragment dialogFragment = new GradesDialogFragment(); - - Bundle bundle = new Bundle(); - bundle.putSerializable(ARGUMENT_KEY, item); - - dialogFragment.setArguments(bundle); - - return dialogFragment; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - grade = (Grade) getArguments().getSerializable(ARGUMENT_KEY); - } - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.grades_dialog, container, false); - - ButterKnife.bind(this, view); - - subject.setText(grade.getSubject()); - value.setText(grade.getValue()); - value.setBackgroundResource(GradeUtils.getValueColor(grade.getValue())); - weight.setText(grade.getWeight()); - date.setText(grade.getDate()); - color.setText(CommonUtils.colorHexToColorName(grade.getColor())); - teacher.setText(getTeacherString()); - description.setText(getDescriptionString()); - - - return view; - } - - @OnClick(R.id.grade_dialog_close_button) - void onClickClose() { - dismiss(); - } - - private String getDescriptionString() { - if ("".equals(grade.getDescription())) { - if (!"".equals(grade.getSymbol())) { - return grade.getSymbol(); - } else { - return getString(R.string.noDescription_text); - } - } else if (!"".equals(grade.getSymbol())) { - return String.format("%1$s - %2$s", grade.getSymbol(), grade.getDescription()); - } else { - return grade.getDescription(); - } - } - - private String getTeacherString() { - if (grade.getTeacher() != null && !"".equals(grade.getTeacher())) { - return grade.getTeacher(); - } else { - return getString(R.string.generic_app_no_data); - } - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesFragment.java b/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesFragment.java deleted file mode 100644 index ca1b949c..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesFragment.java +++ /dev/null @@ -1,213 +0,0 @@ -package io.github.wulkanowy.ui.main.grades; - -import android.content.DialogInterface; -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.v4.widget.SwipeRefreshLayout; -import android.support.v7.app.AlertDialog; -import android.support.v7.widget.RecyclerView; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import java.util.List; - -import javax.inject.Inject; - -import butterknife.BindView; -import eu.davidea.flexibleadapter.FlexibleAdapter; -import eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager; -import io.github.wulkanowy.R; -import io.github.wulkanowy.ui.base.BaseFragment; -import io.github.wulkanowy.ui.main.OnFragmentIsReadyListener; - -public class GradesFragment extends BaseFragment implements GradesContract.View { - - @BindView(R.id.grade_fragment_summary_container) - View summary; - - @BindView(R.id.grade_fragment_details_container) - View details; - - @BindView(R.id.grade_fragment_recycler) - RecyclerView recyclerView; - - @BindView(R.id.grade_fragment_summary_recycler) - RecyclerView summaryRecyclerView; - - @BindView(R.id.grade_fragment_no_item_container) - View noItemView; - - @BindView(R.id.grade_fragment_swipe_refresh) - SwipeRefreshLayout refreshLayout; - - @BindView(R.id.grade_fragment_summary_predicted_average) - TextView predictedAverage; - - @BindView(R.id.grade_fragment_summary_calculated_average) - TextView calculatedAverage; - - @BindView(R.id.grade_fragment_summary_final_average) - TextView finalAverage; - - @Inject - FlexibleAdapter adapter; - - @Inject - FlexibleAdapter summaryAdapter; - - @Inject - GradesContract.Presenter presenter; - - int currentSemester = -1; - - public GradesFragment() { - // empty constructor for fragment - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_grades, container, false); - injectViews(view); - - presenter.attachView(this, (OnFragmentIsReadyListener) getActivity()); - return view; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setHasOptionsMenu(true); - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - menu.clear(); - inflater.inflate(R.menu.grades_action_menu, menu); - super.onCreateOptionsMenu(menu, inflater); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case R.id.action_semester_switch: - presenter.onSemesterSwitchActive(); - CharSequence[] items = new CharSequence[]{ - getResources().getString(R.string.semester_text, 1), - getResources().getString(R.string.semester_text, 2), - }; - new AlertDialog.Builder(getContext()) - .setTitle(R.string.switch_semester) - .setNegativeButton(R.string.cancel, null) - .setSingleChoiceItems(items, this.currentSemester, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - presenter.onSemesterChange(which); - dialog.cancel(); - } - }).show(); - return true; - case R.id.action_summary_switch: - boolean isDetailsVisible = details.getVisibility() == View.VISIBLE; - - item.setTitle(isDetailsVisible ? R.string.action_title_details : R.string.action_title_summary); - details.setVisibility(isDetailsVisible ? View.INVISIBLE : View.VISIBLE); - summary.setVisibility(isDetailsVisible ? View.VISIBLE : View.INVISIBLE); - return true; - default: - return super.onOptionsItemSelected(item); - } - } - - @Override - public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { - noItemView.setVisibility(View.GONE); - summary.setVisibility(View.INVISIBLE); - details.setVisibility(View.VISIBLE); - - adapter.setAutoCollapseOnExpand(true); - adapter.setAutoScrollOnExpand(true); - adapter.expandItemsAtStartUp(); - summaryAdapter.setDisplayHeadersAtStartUp(true); - - recyclerView.setLayoutManager(new SmoothScrollLinearLayoutManager(view.getContext())); - recyclerView.setAdapter(adapter); - summaryRecyclerView.setLayoutManager(new SmoothScrollLinearLayoutManager(view.getContext())); - summaryRecyclerView.setAdapter(summaryAdapter); - summaryRecyclerView.setNestedScrollingEnabled(false); - - refreshLayout.setColorSchemeResources(android.R.color.black); - refreshLayout.setOnRefreshListener(this); - } - - @Override - public void setMenuVisibility(boolean menuVisible) { - super.setMenuVisibility(menuVisible); - if (presenter != null) { - presenter.onFragmentVisible(menuVisible); - } - } - - @Override - public void setSummaryAverages(String calculatedValue, String predictedValue, String finalValue) { - calculatedAverage.setText(calculatedValue); - predictedAverage.setText(predictedValue); - finalAverage.setText(finalValue); - } - - @Override - public void setActivityTitle() { - setTitle(getString(R.string.grades_text)); - } - - public void setCurrentSemester(int currentSemester) { - this.currentSemester = currentSemester; - } - - @Override - public void onRefresh() { - presenter.onRefresh(); - } - - @Override - public void showNoItem(boolean show) { - noItemView.setVisibility(show ? View.VISIBLE : View.INVISIBLE); - } - - @Override - public void hideRefreshingBar() { - refreshLayout.setRefreshing(false); - } - - @Override - public void updateAdapterList(List headerItems) { - adapter.updateDataSet(headerItems); - } - - @Override - public void updateSummaryAdapterList(List summarySubItems) { - summaryAdapter.updateDataSet(summarySubItems); - } - - @Override - public void onRefreshSuccessNoGrade() { - showMessage(R.string.snackbar_no_grades); - } - - @Override - public void onRefreshSuccess(int number) { - showMessage(getString(R.string.snackbar_new_grade, number)); - } - - @Override - public void onDestroyView() { - presenter.detachView(); - super.onDestroyView(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesHeader.java b/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesHeader.java deleted file mode 100644 index 03f8564a..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesHeader.java +++ /dev/null @@ -1,199 +0,0 @@ -package io.github.wulkanowy.ui.main.grades; - - -import android.content.res.Resources; -import android.view.View; -import android.widget.TextView; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; - -import java.util.List; - -import butterknife.BindView; -import butterknife.ButterKnife; -import eu.davidea.flexibleadapter.FlexibleAdapter; -import eu.davidea.flexibleadapter.items.AbstractExpandableHeaderItem; -import eu.davidea.viewholders.ExpandableViewHolder; -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.db.dao.entities.Subject; -import io.github.wulkanowy.utils.AnimationUtils; -import io.github.wulkanowy.utils.GradeUtils; - -public class GradesHeader - extends AbstractExpandableHeaderItem { - - private Subject subject; - - private final boolean isShowSummary; - - GradesHeader(Subject subject, boolean isShowSummary) { - this.subject = subject; - this.isShowSummary = isShowSummary; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - - if (o == null || getClass() != o.getClass()) return false; - - GradesHeader that = (GradesHeader) o; - - return new EqualsBuilder() - .append(subject, that.subject) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) - .append(subject) - .toHashCode(); - } - - @Override - public int getLayoutRes() { - return R.layout.grades_header; - } - - @Override - public HeaderViewHolder createViewHolder(View view, FlexibleAdapter adapter) { - return new HeaderViewHolder(view, adapter, isShowSummary); - } - - @Override - public void bindViewHolder(FlexibleAdapter adapter, HeaderViewHolder holder, int position, List payloads) { - holder.onBind(subject, getSubItems()); - } - - static class HeaderViewHolder extends ExpandableViewHolder { - - @BindView(R.id.grade_header_subject_text) - TextView subjectName; - - @BindView(R.id.grade_header_average_text) - TextView averageText; - - @BindView(R.id.grade_header_number_of_grade_text) - TextView numberText; - - @BindView(R.id.grade_header_predicted_rating_text) - TextView predictedText; - - @BindView(R.id.grade_header_final_rating_text) - TextView finalText; - - @BindView(R.id.grade_header_alert_image) - View alertImage; - - private Resources resources; - - private Subject item; - - private FlexibleAdapter adapter; - - private boolean isShowSummary; - - HeaderViewHolder(View view, FlexibleAdapter adapter, boolean isShowSummary) { - super(view, adapter); - ButterKnife.bind(this, view); - resources = view.getResources(); - view.setOnClickListener(this); - this.isShowSummary = isShowSummary; - this.adapter = adapter; - } - - void onBind(Subject item, List subItems) { - this.item = item; - - subjectName.setText(item.getName()); - numberText.setText(resources.getQuantityString(R.plurals.numberOfGradesPlurals, - subItems.size(), subItems.size())); - averageText.setText(getGradesAverageString()); - - predictedText.setText(resources.getString(R.string.info_grades_predicted_rating, - GradeUtils.getShortGradeValue(item.getPredictedRating()))); - finalText.setText(resources.getString(R.string.info_grades_final_rating, - GradeUtils.getShortGradeValue(item.getFinalRating()))); - - resetViews(); - toggleSubjectText(); - toggleSummary(); - - alertImage.setVisibility(isSubItemsReadAndSaveAlertView(subItems) - ? View.INVISIBLE : View.VISIBLE); - } - - private String getGradesAverageString() { - float average = GradeUtils.calculateWeightedAverage(item.getGradeList()); - - if (average < 0) { - return resources.getString(R.string.info_no_average); - } - - return resources.getString(R.string.info_average_grades, average); - } - - @Override - public void onClick(View view) { - super.onClick(view); - toggleSubjectText(); - toggleSummary(); - } - - private void resetViews() { - subjectName.setMaxLines(1); - setDefaultSummaryVisibility(predictedText, item.getPredictedRating()); - setDefaultSummaryVisibility(finalText, item.getFinalRating()); - } - - private void setDefaultSummaryVisibility(View view, String value) { - if (!"-".equals(value) && isShowSummary) { - view.setVisibility(View.VISIBLE); - } else { - view.setVisibility(View.GONE); - } - } - - private void toggleSubjectText() { - if (isExpand()) { - subjectName.setMaxLines(3); - } else { - subjectName.setMaxLines(1); - } - } - - private void toggleSummary() { - toggleSummaryView(predictedText, item.getPredictedRating(), isExpand()); - toggleSummaryView(finalText, item.getFinalRating(), isExpand()); - } - - private boolean isExpand() { - return adapter.isExpanded(getFlexibleAdapterPosition()); - } - - private void toggleSummaryView(View view, String value, boolean expand) { - if ("-".equals(value) || isShowSummary) { - return; - } - - if (expand) { - AnimationUtils.slideDown(view); - } else { - AnimationUtils.slideUp(view); - } - } - - private boolean isSubItemsReadAndSaveAlertView(List subItems) { - boolean isRead = true; - - for (GradesSubItem gradesSubItem : subItems) { - isRead = gradesSubItem.getGrade().getRead(); - gradesSubItem.setSubjectAlertImage(alertImage); - } - - return isRead; - } - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesModule.java b/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesModule.java deleted file mode 100644 index 25eeef48..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesModule.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.github.wulkanowy.ui.main.grades; - -import dagger.Binds; -import dagger.Module; -import dagger.Provides; -import eu.davidea.flexibleadapter.FlexibleAdapter; - -@Module -public abstract class GradesModule { - - @Binds - abstract GradesContract.Presenter provideGradesPresenter(GradesPresenter gradesPresenter); - - @Provides - static FlexibleAdapter provideGradesAdapter() { - return new FlexibleAdapter<>(null); - } - - @Provides - static FlexibleAdapter provideGradesSummaryAdapter() { - return new FlexibleAdapter<>(null); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesPresenter.java b/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesPresenter.java deleted file mode 100644 index 0f4d363c..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesPresenter.java +++ /dev/null @@ -1,230 +0,0 @@ -package io.github.wulkanowy.ui.main.grades; - -import android.support.annotation.NonNull; - -import com.crashlytics.android.answers.Answers; -import com.crashlytics.android.answers.CustomEvent; - -import org.threeten.bp.LocalDate; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import javax.inject.Inject; - -import io.github.wulkanowy.data.RepositoryContract; -import io.github.wulkanowy.data.db.dao.entities.Grade; -import io.github.wulkanowy.data.db.dao.entities.Subject; -import io.github.wulkanowy.ui.base.BasePresenter; -import io.github.wulkanowy.ui.main.OnFragmentIsReadyListener; -import io.github.wulkanowy.utils.FabricUtils; -import io.github.wulkanowy.utils.GradeUtils; -import io.github.wulkanowy.utils.async.AbstractTask; -import io.github.wulkanowy.utils.async.AsyncListeners; - -public class GradesPresenter extends BasePresenter - implements GradesContract.Presenter, AsyncListeners.OnRefreshListener, - AsyncListeners.OnFirstLoadingListener { - - private AbstractTask refreshTask; - - private AbstractTask loadingTask; - - private OnFragmentIsReadyListener listener; - - private List headerItems = new ArrayList<>(); - - private List summarySubItems = new ArrayList<>(); - - private boolean isFirstSight = false; - - private int semesterName; - - private float finalAverage; - - private float predictedAverage; - - private float calculatedAverage; - - @Inject - GradesPresenter(RepositoryContract repository) { - super(repository); - } - - @Override - public void attachView(@NonNull GradesContract.View view, OnFragmentIsReadyListener listener) { - super.attachView(view); - this.listener = listener; - - if (getView().isMenuVisible()) { - getView().setActivityTitle(); - } - - semesterName = getRepository().getDbRepo().getCurrentSemesterName(); - getView().setCurrentSemester(semesterName - 1); - - if (!isFirstSight) { - isFirstSight = true; - reloadGrades(); - } - } - - @Override - public void onSemesterSwitchActive() { - cancelAsyncTasks(); - } - - @Override - public void onSemesterChange(int which) { - semesterName = which + 1; - getView().setCurrentSemester(which); - reloadGrades(); - - Answers.getInstance().logCustom(new CustomEvent("Semester change") - .putCustomAttribute("Name", semesterName)); - } - - @Override - public void onFragmentVisible(boolean isVisible) { - if (isVisible) { - getView().setActivityTitle(); - } - } - - @Override - public void onRefresh() { - if (getView().isNetworkConnected()) { - refreshTask = new AbstractTask(); - refreshTask.setOnRefreshListener(this); - refreshTask.execute(); - } else { - getView().showNoNetworkMessage(); - getView().hideRefreshingBar(); - } - } - - @Override - public void onDoInBackgroundRefresh() throws Exception { - getRepository().getSyncRepo().syncSubjects(semesterName); - getRepository().getSyncRepo().syncGrades(semesterName); - } - - @Override - public void onCanceledRefreshAsync() { - if (isViewAttached()) { - getView().hideRefreshingBar(); - } - } - - @Override - public void onEndRefreshAsync(boolean result, Exception exception) { - if (result) { - reloadGrades(); - - int numberOfNewGrades = getRepository().getDbRepo().getNewGrades(semesterName).size(); - - if (numberOfNewGrades <= 0) { - getView().onRefreshSuccessNoGrade(); - } else { - getView().onRefreshSuccess(numberOfNewGrades); - } - } else { - getView().showMessage(getRepository().getResRepo().getErrorLoginMessage(exception)); - } - getView().hideRefreshingBar(); - - FabricUtils.logRefresh("Grades", result, LocalDate.now().toString()); - } - - @Override - public void onDoInBackgroundLoading() { - List subjectList = getRepository().getDbRepo().getSubjectList(semesterName); - boolean isShowSummary = getRepository().getSharedRepo().isShowGradesSummary(); - - headerItems = new ArrayList<>(); - summarySubItems = new ArrayList<>(); - - for (Subject subject : subjectList) { - subject.resetGradeList(); - List gradeList = subject.getGradeList(); - - GradesSummaryHeader summaryHeader = new GradesSummaryHeader(subject, GradeUtils.calculateWeightedAverage(gradeList)); - summarySubItems.add(new GradesSummarySubItem(summaryHeader, subject)); - - if (!gradeList.isEmpty()) { - GradesHeader headerItem = new GradesHeader(subject, isShowSummary); - - List subItems = new ArrayList<>(); - - for (Grade grade : gradeList) { - subItems.add(new GradesSubItem(headerItem, grade)); - } - - headerItem.setSubItems(subItems); - headerItem.setExpanded(false); - headerItems.add(headerItem); - } - } - - finalAverage = GradeUtils.calculateSubjectsAverage(subjectList, false); - predictedAverage = GradeUtils.calculateSubjectsAverage(subjectList, true); - calculatedAverage = GradeUtils.calculateDetailedSubjectsAverage(subjectList); - } - - @Override - public void onCanceledLoadingAsync() { - // do nothing - } - - @Override - public void onEndLoadingAsync(boolean result, Exception exception) { - getView().showNoItem(headerItems.isEmpty()); - getView().updateAdapterList(headerItems); - - setSummaryAverages(); - getView().updateSummaryAdapterList(summarySubItems); - - listener.onFragmentIsReady(); - } - - private void setSummaryAverages() { - getView().setSummaryAverages( - getFormattedAverage(calculatedAverage), - getFormattedAverage(predictedAverage), - getFormattedAverage(finalAverage) - ); - } - - private String getFormattedAverage(float average) { - if (-1.0f == average) { - return "-- --"; - } - - return String.format(Locale.FRANCE, "%.2f", average); - } - - private void reloadGrades() { - loadingTask = new AbstractTask(); - loadingTask.setOnFirstLoadingListener(this); - loadingTask.execute(); - } - - private void cancelAsyncTasks() { - if (refreshTask != null) { - refreshTask.cancel(true); - refreshTask = null; - } - if (loadingTask != null) { - loadingTask.cancel(true); - loadingTask = null; - } - } - - @Override - public void detachView() { - isFirstSight = false; - cancelAsyncTasks(); - super.detachView(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesSubItem.java b/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesSubItem.java deleted file mode 100644 index ee995040..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesSubItem.java +++ /dev/null @@ -1,162 +0,0 @@ -package io.github.wulkanowy.ui.main.grades; - -import android.content.Context; -import android.support.v4.app.DialogFragment; -import android.support.v4.app.FragmentActivity; -import android.view.View; -import android.widget.TextView; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; - -import java.util.List; - -import butterknife.BindView; -import butterknife.ButterKnife; -import eu.davidea.flexibleadapter.FlexibleAdapter; -import eu.davidea.flexibleadapter.items.AbstractSectionableItem; -import eu.davidea.viewholders.FlexibleViewHolder; -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.db.dao.entities.Grade; -import io.github.wulkanowy.utils.GradeUtils; - -public class GradesSubItem - extends AbstractSectionableItem { - - private Grade grade; - - private static int numberOfNotReadGrade; - - private View subjectAlertImage; - - GradesSubItem(GradesHeader header, Grade grade) { - super(header); - this.grade = grade; - } - - public Grade getGrade() { - return grade; - } - - void setSubjectAlertImage(View subjectAlertImage) { - this.subjectAlertImage = subjectAlertImage; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - - if (o == null || getClass() != o.getClass()) return false; - - GradesSubItem that = (GradesSubItem) o; - - return new EqualsBuilder() - .append(grade, that.grade) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) - .append(grade) - .toHashCode(); - } - - @Override - public int getLayoutRes() { - return R.layout.grades_subitem; - } - - @Override - public SubItemViewHolder createViewHolder(View view, FlexibleAdapter adapter) { - return new SubItemViewHolder(view, adapter); - } - - @Override - public void bindViewHolder(FlexibleAdapter adapter, SubItemViewHolder holder, int position, List payloads) { - holder.onBind(grade, subjectAlertImage); - } - - static class SubItemViewHolder extends FlexibleViewHolder { - - @BindView(R.id.grade_subitem_value) - TextView value; - - @BindView(R.id.grade_subitem_description) - TextView description; - - @BindView(R.id.grade_subitem_date) - TextView date; - - @BindView(R.id.grade_subitem_weight) - TextView weight; - - @BindView(R.id.grade_subitem_alert_image) - View alert; - - private View subjectAlertImage; - - private Context context; - - private Grade item; - - SubItemViewHolder(View view, FlexibleAdapter adapter) { - super(view, adapter); - ButterKnife.bind(this, view); - context = view.getContext(); - view.setOnClickListener(this); - } - - void onBind(Grade item, View subjectAlertImage) { - this.item = item; - this.subjectAlertImage = subjectAlertImage; - - value.setText(item.getValue()); - value.setBackgroundResource(GradeUtils.getValueColor(item.getValue())); - description.setText(getDescriptionString()); - date.setText(item.getDate()); - weight.setText(String.format("%s: %s", context.getResources().getString(R.string.grade_weight_text), item.getWeight())); - alert.setVisibility(item.getRead() ? View.INVISIBLE : View.VISIBLE); - - if (!item.getRead()) { - numberOfNotReadGrade++; - } - } - - @Override - public void onClick(View view) { - super.onClick(view); - showDialog(); - - if (!item.getRead()) { - numberOfNotReadGrade--; - - if (numberOfNotReadGrade == 0) { - subjectAlertImage.setVisibility(View.INVISIBLE); - } - item.setIsNew(false); - item.setRead(true); - item.update(); - alert.setVisibility(View.INVISIBLE); - } - } - - private String getDescriptionString() { - if (item.getDescription() == null || "".equals(item.getDescription())) { - if (!"".equals(item.getSymbol())) { - return item.getSymbol(); - } else { - return context.getString(R.string.noDescription_text); - } - } else { - return item.getDescription(); - } - } - - private void showDialog() { - GradesDialogFragment dialogFragment = GradesDialogFragment.newInstance(item); - dialogFragment.setStyle(DialogFragment.STYLE_NO_TITLE, 0); - dialogFragment.show(((FragmentActivity) context).getSupportFragmentManager(), item.toString()); - } - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesSummaryHeader.java b/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesSummaryHeader.java deleted file mode 100644 index a06fa0d5..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesSummaryHeader.java +++ /dev/null @@ -1,87 +0,0 @@ -package io.github.wulkanowy.ui.main.grades; - -import android.view.View; -import android.widget.TextView; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; - -import java.util.List; -import java.util.Locale; - -import butterknife.BindView; -import butterknife.ButterKnife; -import eu.davidea.flexibleadapter.FlexibleAdapter; -import eu.davidea.flexibleadapter.items.AbstractHeaderItem; -import eu.davidea.flexibleadapter.items.IFlexible; -import eu.davidea.viewholders.FlexibleViewHolder; -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.db.dao.entities.Subject; - -class GradesSummaryHeader extends AbstractHeaderItem { - - private Subject subject; - - private String average; - - GradesSummaryHeader(Subject subject, float average) { - this.subject = subject; - this.average = String.format(Locale.FRANCE, "%.2f", average); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - - if (o == null || getClass() != o.getClass()) return false; - - GradesSummaryHeader that = (GradesSummaryHeader) o; - - return new EqualsBuilder() - .append(subject, that.subject) - .append(average, that.average) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) - .append(subject) - .append(average) - .toHashCode(); - } - - @Override - public int getLayoutRes() { - return R.layout.grades_summary_header; - } - - @Override - public HeaderViewHolder createViewHolder(View view, FlexibleAdapter adapter) { - return new HeaderViewHolder(view, adapter); - } - - @Override - public void bindViewHolder(FlexibleAdapter adapter, HeaderViewHolder holder, int position, List payloads) { - holder.onBind(subject, average); - } - - static class HeaderViewHolder extends FlexibleViewHolder { - - @BindView(R.id.grades_summary_header_name) - TextView name; - - @BindView(R.id.grades_summary_header_average) - TextView average; - - HeaderViewHolder(View view, FlexibleAdapter adapter) { - super(view, adapter); - ButterKnife.bind(this, view); - } - - void onBind(Subject item, String value) { - name.setText(item.getName()); - average.setText("-1,00".equals(value) ? "" : value); - } - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesSummarySubItem.java b/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesSummarySubItem.java deleted file mode 100644 index 58f418aa..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesSummarySubItem.java +++ /dev/null @@ -1,84 +0,0 @@ -package io.github.wulkanowy.ui.main.grades; - -import android.view.View; -import android.widget.TextView; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; - -import java.util.List; - -import butterknife.BindView; -import butterknife.ButterKnife; -import eu.davidea.flexibleadapter.FlexibleAdapter; -import eu.davidea.flexibleadapter.items.AbstractSectionableItem; -import eu.davidea.flexibleadapter.items.IFlexible; -import eu.davidea.viewholders.FlexibleViewHolder; -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.db.dao.entities.Subject; -import io.github.wulkanowy.utils.GradeUtils; - -public class GradesSummarySubItem - extends AbstractSectionableItem { - - private Subject subject; - - public GradesSummarySubItem(GradesSummaryHeader header, Subject subject) { - super(header); - this.subject = subject; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - - if (o == null || getClass() != o.getClass()) return false; - - GradesSummarySubItem that = (GradesSummarySubItem) o; - - return new EqualsBuilder() - .append(subject, that.subject) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) - .append(subject) - .toHashCode(); - } - - @Override - public int getLayoutRes() { - return R.layout.grades_summary_subitem; - } - - @Override - public SubItemViewHolder createViewHolder(View view, FlexibleAdapter adapter) { - return new SubItemViewHolder(view, adapter); - } - - @Override - public void bindViewHolder(FlexibleAdapter adapter, SubItemViewHolder holder, int position, List payloads) { - holder.onBind(subject); - } - - static class SubItemViewHolder extends FlexibleViewHolder { - - @BindView(R.id.grades_summary_subitem_final_grade) - TextView finalGrade; - - @BindView(R.id.grades_summary_subitem_predicted_grade) - TextView predictedGrade; - - SubItemViewHolder(View view, FlexibleAdapter adapter) { - super(view, adapter); - ButterKnife.bind(this, view); - } - - void onBind(Subject item) { - predictedGrade.setText(GradeUtils.getShortGradeValue(item.getPredictedRating())); - finalGrade.setText(GradeUtils.getShortGradeValue(item.getFinalRating())); - } - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/settings/SettingsFragment.java b/app/src/main/java/io/github/wulkanowy/ui/main/settings/SettingsFragment.java deleted file mode 100644 index 0f2009be..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/settings/SettingsFragment.java +++ /dev/null @@ -1,181 +0,0 @@ -package io.github.wulkanowy.ui.main.settings; - -import android.content.Intent; -import android.content.SharedPreferences; -import android.net.Uri; -import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.support.v7.app.AppCompatDelegate; -import android.support.v7.preference.Preference; -import android.support.v7.preference.PreferenceFragmentCompat; -import android.widget.Toast; - -import com.google.android.gms.oss.licenses.OssLicensesMenuActivity; - -import io.github.wulkanowy.BuildConfig; -import io.github.wulkanowy.R; -import io.github.wulkanowy.services.jobs.SyncJob; -import io.github.wulkanowy.ui.main.MainActivity; -import io.github.wulkanowy.utils.AppConstant; - -import static io.github.wulkanowy.utils.TimeUtilsKt.isHolidays; - -public class SettingsFragment extends PreferenceFragmentCompat - implements SharedPreferences.OnSharedPreferenceChangeListener { - - public static final String SHARED_KEY_START_TAB = "startup_tab"; - - public static final String SHARED_KEY_GRADES_SUMMARY = "grades_summary"; - - public static final String SHARED_KEY_ATTENDANCE_PRESENT = "attendance_present"; - - public static final String SHARED_KEY_THEME = "theme"; - - public static final String SHARED_KEY_SERVICES_ENABLE = "services_enable"; - - public static final String SHARED_KEY_NOTIFY_ENABLE = "notify_enable"; - - public static final String SHARED_KEY_SERVICES_INTERVAL = "services_interval"; - - public static final String SHARED_KEY_SERVICES_MOBILE_DISABLED = "services_disable_mobile"; - - public static final String SHARED_KEY_ABOUT_VERSION = "about_version"; - - public static final String SHARED_KEY_ABOUT_LICENSES = "about_osl"; - - public static final String SHARED_KEY_ABOUT_REPO = "about_repo"; - - private boolean isStarted; - - private boolean isVisible; - - private Preference.OnPreferenceClickListener onProgrammerListener = new Preference.OnPreferenceClickListener() { - private int clicks = 0; - - @Override - public boolean onPreferenceClick(Preference preference) { - Toast.makeText(getActivity(), getVersionToast(clicks++), Toast.LENGTH_SHORT).show(); - return true; - } - - private int getVersionToast(int click) { - if (0 == click) { - return R.string.about_programmer_step1; - } - - if (1 == click) { - return R.string.about_programmer_step2; - } - - if (9 > click) { - return R.string.about_programmer_step3; - } - - return R.string.about_programmer; - } - }; - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - addPreferencesFromResource(R.xml.preferences); - } - - @Override - public void onCreate(final Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - findPreference(SHARED_KEY_ABOUT_VERSION).setSummary(BuildConfig.VERSION_NAME); - findPreference(SHARED_KEY_ABOUT_VERSION).setOnPreferenceClickListener(onProgrammerListener); - findPreference(SHARED_KEY_ABOUT_REPO).setIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(AppConstant.REPO_URL))); - findPreference(SHARED_KEY_ABOUT_LICENSES).setIntent(new Intent(getActivity(), OssLicensesMenuActivity.class) - .putExtra("title", R.string.pref_about_osl)); - - if (isHolidays()) { - Preference services = findPreference(SHARED_KEY_SERVICES_ENABLE); - services.setSummary(R.string.pref_services_suspended_on_holidays); - services.setEnabled(false); - } - } - - @Override - public Fragment getCallbackFragment() { - return this; - } - - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - if (key.equals(SHARED_KEY_SERVICES_ENABLE) || key.equals(SHARED_KEY_SERVICES_INTERVAL) - || key.equals(SHARED_KEY_SERVICES_MOBILE_DISABLED)) { - launchServices(sharedPreferences.getBoolean(SHARED_KEY_SERVICES_ENABLE, true), - sharedPreferences); - } - - if (key.equals(SHARED_KEY_THEME)) { - setCurrentTheme(sharedPreferences); - } - } - - private void setCurrentTheme(SharedPreferences sharedPreferences) { - AppCompatDelegate.setDefaultNightMode(Integer.parseInt(sharedPreferences.getString(SHARED_KEY_THEME, "1"))); - getActivity().finish(); - startActivity(MainActivity - .getStartIntent(getContext()) - .putExtra(MainActivity.EXTRA_CARD_ID_KEY, 4) - ); - getActivity().overridePendingTransition(0, 0); - } - - private void launchServices(boolean start, SharedPreferences sharedPref) { - if (start) { - int newInterval = Integer.parseInt(sharedPref.getString(SHARED_KEY_SERVICES_INTERVAL, "60")); - boolean useOnlyWifi = sharedPref.getBoolean(SHARED_KEY_SERVICES_MOBILE_DISABLED, false); - - SyncJob.stop(getContext()); - SyncJob.start(getContext(), newInterval, useOnlyWifi); - } else { - SyncJob.stop(getContext()); - } - } - - private void setTitle() { - getActivity().setTitle(R.string.settings_text); - } - - @Override - public void setUserVisibleHint(boolean isVisibleToUser) { - super.setUserVisibleHint(isVisibleToUser); - isVisible = isVisibleToUser; - if (isVisible && isStarted) { - setTitle(); - } - } - - @Override - public void onStart() { - super.onStart(); - isStarted = true; - if (isVisible) { - setTitle(); - } - } - - @Override - public void onResume() { - super.onResume(); - getPreferenceScreen().getSharedPreferences() - .registerOnSharedPreferenceChangeListener(this); - } - - @Override - public void onPause() { - super.onPause(); - getPreferenceScreen().getSharedPreferences() - .unregisterOnSharedPreferenceChangeListener(this); - } - - @Override - public void onStop() { - super.onStop(); - isStarted = false; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetableContract.java b/app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetableContract.java deleted file mode 100644 index 8344ad76..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetableContract.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.github.wulkanowy.ui.main.timetable; - -import android.support.annotation.NonNull; - -import io.github.wulkanowy.ui.base.BaseContract; -import io.github.wulkanowy.ui.main.OnFragmentIsReadyListener; - -public interface TimetableContract { - - interface View extends BaseContract.View { - - void setActivityTitle(); - - void scrollViewPagerToPosition(int position); - - void setTabDataToAdapter(String date); - - void setAdapterWithTabLayout(); - - boolean isMenuVisible(); - - void setThemeForTab(int position); - } - - interface Presenter extends BaseContract.Presenter { - - void onFragmentActivated(boolean isVisible); - - void attachView(@NonNull View view, OnFragmentIsReadyListener listener); - - void setRestoredPosition(int position); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetableDialogFragment.java b/app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetableDialogFragment.java deleted file mode 100644 index cc668dc2..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetableDialogFragment.java +++ /dev/null @@ -1,127 +0,0 @@ -package io.github.wulkanowy.ui.main.timetable; - -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.v4.app.DialogFragment; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import org.apache.commons.lang3.StringUtils; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.db.dao.entities.TimetableLesson; - -public class TimetableDialogFragment extends DialogFragment { - - private static final String ARGUMENT_KEY = "Item"; - - private TimetableLesson lesson; - - @BindView(R.id.timetable_dialog_lesson_value) - TextView lessonName; - - @BindView(R.id.timetable_dialog_teacher_value) - TextView teacher; - - @BindView(R.id.timetable_dialog_group_value) - TextView group; - - @BindView(R.id.timetable_dialog_room_value) - TextView room; - - @BindView(R.id.timetable_dialog_time_value) - TextView time; - - @BindView(R.id.timetable_dialog_description_value) - TextView description; - - @BindView(R.id.timetable_dialog_description) - View descriptionLabel; - - @BindView(R.id.timetable_dialog_teacher) - View teacherLabel; - - @BindView(R.id.timetable_dialog_group) - View groupLabel; - - public TimetableDialogFragment() { - //empty constructor for fragment - } - - public static TimetableDialogFragment newInstance(TimetableLesson lesson) { - TimetableDialogFragment dialogFragment = new TimetableDialogFragment(); - - Bundle bundle = new Bundle(); - bundle.putSerializable(ARGUMENT_KEY, lesson); - - dialogFragment.setArguments(bundle); - - return dialogFragment; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - lesson = (TimetableLesson) getArguments().getSerializable(ARGUMENT_KEY); - } - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.timetable_dialog, container, false); - - ButterKnife.bind(this, view); - - if (!lesson.getSubject().isEmpty()) { - lessonName.setText(lesson.getSubject()); - } - - if (!lesson.getTeacher().isEmpty()) { - teacher.setText(lesson.getTeacher()); - } else { - teacher.setVisibility(View.GONE); - teacherLabel.setVisibility(View.GONE); - } - - if (!lesson.getGroup().isEmpty()) { - group.setText(lesson.getGroup()); - } else { - group.setVisibility(View.GONE); - groupLabel.setVisibility(View.GONE); - } - - if (!lesson.getRoom().isEmpty()) { - room.setText(lesson.getRoom()); - } - - if (!lesson.getEndTime().isEmpty() && !lesson.getStartTime().isEmpty()) { - time.setText(getTimeString()); - } - - if (!lesson.getDescription().isEmpty()) { - description.setText(StringUtils.capitalize(lesson.getDescription())); - } else { - description.setVisibility(View.GONE); - descriptionLabel.setVisibility(View.GONE); - } - - return view; - } - - private String getTimeString() { - return String.format("%1$s - %2$s", lesson.getStartTime(), lesson.getEndTime()); - } - - @OnClick(R.id.timetable_dialog_close) - void onClickCloseButton() { - dismiss(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetableFragment.java b/app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetableFragment.java deleted file mode 100644 index db3cc83c..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetableFragment.java +++ /dev/null @@ -1,101 +0,0 @@ -package io.github.wulkanowy.ui.main.timetable; - -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.design.widget.TabLayout; -import android.support.v4.view.ViewPager; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import javax.inject.Inject; -import javax.inject.Named; - -import butterknife.BindView; -import io.github.wulkanowy.R; -import io.github.wulkanowy.ui.base.BaseFragment; -import io.github.wulkanowy.ui.base.BasePagerAdapter; -import io.github.wulkanowy.ui.main.OnFragmentIsReadyListener; -import io.github.wulkanowy.ui.main.timetable.tab.TimetableTabFragment; - -public class TimetableFragment extends BaseFragment implements TimetableContract.View { - - private static final String CURRENT_ITEM_KEY = "CurrentItem"; - - @BindView(R.id.timetable_fragment_viewpager) - ViewPager viewPager; - - @BindView(R.id.timetable_fragment_tab_layout) - TabLayout tabLayout; - - @Named("Timetable") - @Inject - BasePagerAdapter pagerAdapter; - - @Inject - TimetableContract.Presenter presenter; - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_timetable, container, false); - injectViews(view); - - presenter.attachView(this, (OnFragmentIsReadyListener) getActivity()); - - if (savedInstanceState != null) { - presenter.setRestoredPosition(savedInstanceState.getInt(CURRENT_ITEM_KEY)); - } - return view; - } - - @Override - public void setMenuVisibility(boolean menuVisible) { - super.setMenuVisibility(menuVisible); - if (presenter != null) { - presenter.onFragmentActivated(menuVisible); - } - } - - @Override - public void setTabDataToAdapter(String date) { - pagerAdapter.addFragment(TimetableTabFragment.newInstance(date), date); - } - - @Override - public void setAdapterWithTabLayout() { - viewPager.setAdapter(pagerAdapter); - tabLayout.setupWithViewPager(viewPager); - } - - @Override - public void scrollViewPagerToPosition(int position) { - viewPager.setCurrentItem(position, false); - } - - @Override - public void setThemeForTab(int position) { - TabLayout.Tab tab = tabLayout.getTabAt(position); - if (tab != null) { - tab.setCustomView(R.layout.current_week_tab); - } - } - - @Override - public void setActivityTitle() { - setTitle(getString(R.string.timetable_text)); - } - - @Override - public void onSaveInstanceState(Bundle outState) { - outState.putInt(CURRENT_ITEM_KEY, viewPager.getCurrentItem()); - super.onSaveInstanceState(outState); - } - - @Override - public void onDestroyView() { - presenter.detachView(); - super.onDestroyView(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetableModule.java b/app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetableModule.java deleted file mode 100644 index 9ad1ee60..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetableModule.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.github.wulkanowy.ui.main.timetable; - -import javax.inject.Named; - -import dagger.Binds; -import dagger.Module; -import dagger.Provides; -import dagger.android.ContributesAndroidInjector; -import io.github.wulkanowy.di.scopes.PerChildFragment; -import io.github.wulkanowy.di.scopes.PerFragment; -import io.github.wulkanowy.ui.base.BasePagerAdapter; -import io.github.wulkanowy.ui.main.timetable.tab.TimetableTabFragment; -import io.github.wulkanowy.ui.main.timetable.tab.TimetableTabModule; - -@Module -public abstract class TimetableModule { - - @Named("Timetable") - @PerFragment - @Provides - static BasePagerAdapter providePagerAdapter(TimetableFragment fragment) { - return new BasePagerAdapter(fragment.getChildFragmentManager()); - } - - @PerFragment - @Binds - abstract TimetableContract.Presenter provideTimetablePresenter(TimetablePresenter timetablePresenter); - - @PerChildFragment - @ContributesAndroidInjector(modules = TimetableTabModule.class) - abstract TimetableTabFragment bindTimetableTabFragment(); -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetablePresenter.java b/app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetablePresenter.java deleted file mode 100644 index 1e9cf0b8..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetablePresenter.java +++ /dev/null @@ -1,107 +0,0 @@ -package io.github.wulkanowy.ui.main.timetable; - -import android.support.annotation.NonNull; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import io.github.wulkanowy.data.RepositoryContract; -import io.github.wulkanowy.ui.base.BasePresenter; -import io.github.wulkanowy.ui.main.OnFragmentIsReadyListener; -import io.github.wulkanowy.utils.async.AbstractTask; -import io.github.wulkanowy.utils.async.AsyncListeners; - -import static io.github.wulkanowy.utils.TimeUtilsKt.getFirstDayOfCurrentWeek; -import static io.github.wulkanowy.utils.TimeUtilsKt.getMondaysFromCurrentSchoolYear; - -public class TimetablePresenter extends BasePresenter - implements TimetableContract.Presenter, AsyncListeners.OnFirstLoadingListener { - - private AbstractTask loadingTask; - - private List dates = new ArrayList<>(); - - private OnFragmentIsReadyListener listener; - - private int positionToScroll = 0; - - private boolean isFirstSight = false; - - @Inject - TimetablePresenter(RepositoryContract repository) { - super(repository); - } - - @Override - public void attachView(@NonNull TimetableContract.View view, OnFragmentIsReadyListener listener) { - super.attachView(view); - this.listener = listener; - - if (getView().isMenuVisible()) { - getView().setActivityTitle(); - } - - if (dates.isEmpty()) { - dates = getMondaysFromCurrentSchoolYear(); - } - - if (positionToScroll == 0) { - positionToScroll = dates.indexOf(getFirstDayOfCurrentWeek()); - } - - if (!isFirstSight) { - isFirstSight = true; - - loadingTask = new AbstractTask(); - loadingTask.setOnFirstLoadingListener(this); - loadingTask.execute(); - } - } - - @Override - public void onFragmentActivated(boolean isVisible) { - if (isVisible) { - getView().setActivityTitle(); - } - } - - @Override - public void onDoInBackgroundLoading() { - for (String date : dates) { - getView().setTabDataToAdapter(date); - } - } - - @Override - public void onCanceledLoadingAsync() { - //do nothing - } - - @Override - public void onEndLoadingAsync(boolean result, Exception exception) { - if (result) { - getView().setAdapterWithTabLayout(); - getView().setThemeForTab(positionToScroll); - getView().scrollViewPagerToPosition(positionToScroll); - listener.onFragmentIsReady(); - } - } - - @Override - public void setRestoredPosition(int position) { - this.positionToScroll = position; - } - - @Override - public void detachView() { - isFirstSight = false; - - if (loadingTask != null) { - loadingTask.cancel(true); - loadingTask = null; - } - super.detachView(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableHeader.java b/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableHeader.java deleted file mode 100644 index cb877387..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableHeader.java +++ /dev/null @@ -1,136 +0,0 @@ -package io.github.wulkanowy.ui.main.timetable.tab; - -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.drawable.Drawable; -import android.view.View; -import android.widget.FrameLayout; -import android.widget.ImageView; -import android.widget.TextView; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; - -import java.util.List; - -import butterknife.BindView; -import butterknife.ButterKnife; -import eu.davidea.flexibleadapter.FlexibleAdapter; -import eu.davidea.flexibleadapter.items.AbstractExpandableHeaderItem; -import eu.davidea.flexibleadapter.items.IFlexible; -import eu.davidea.viewholders.ExpandableViewHolder; -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.db.dao.entities.Day; -import io.github.wulkanowy.utils.CommonUtils; - -public class TimetableHeader - extends AbstractExpandableHeaderItem { - - private Day day; - - TimetableHeader(Day day) { - this.day = day; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - - if (o == null || getClass() != o.getClass()) return false; - - TimetableHeader that = (TimetableHeader) o; - - return new EqualsBuilder() - .append(day, that.day) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) - .append(day) - .toHashCode(); - } - - @Override - public int getLayoutRes() { - return R.layout.timetable_header; - } - - @Override - public HeaderViewHolder createViewHolder(View view, FlexibleAdapter adapter) { - return new HeaderViewHolder(view, adapter); - } - - @Override - public void bindViewHolder(FlexibleAdapter adapter, HeaderViewHolder holder, - int position, List payloads) { - holder.onBind(day, getSubItems()); - } - - static class HeaderViewHolder extends ExpandableViewHolder { - - @BindView(R.id.timetable_header_day) - TextView dayName; - - @BindView(R.id.timetable_header_date) - TextView date; - - @BindView(R.id.timetable_header_alert_image) - ImageView alert; - - @BindView(R.id.timetable_header_free_name) - TextView freeName; - - private Context context; - - HeaderViewHolder(View view, FlexibleAdapter adapter) { - super(view, adapter); - view.setOnClickListener(this); - ButterKnife.bind(this, view); - context = view.getContext(); - } - - void onBind(Day item, List subItems) { - dayName.setText(StringUtils.capitalize(item.getDayName())); - date.setText(item.getDate()); - alert.setVisibility(isSubItemNewMovedInOrChanged(subItems) ? View.VISIBLE : View.INVISIBLE); - freeName.setVisibility(item.getFreeDay() ? View.VISIBLE : View.INVISIBLE); - freeName.setText(item.getFreeDayName()); - setInactiveHeader(item.getFreeDay()); - } - - private void setInactiveHeader(boolean inactive) { - ((FrameLayout) getContentView()).setForeground(inactive ? null : getSelectableDrawable()); - dayName.setTextColor(CommonUtils.getThemeAttrColor(context, - inactive ? android.R.attr.textColorSecondary : android.R.attr.textColorPrimary)); - - if (inactive) { - getContentView().setBackgroundColor(CommonUtils.getThemeAttrColor(context, R.attr.colorControlHighlight)); - } else { - getContentView().setBackgroundDrawable(context.getResources().getDrawable(R.drawable.ic_border)); - } - } - - private Drawable getSelectableDrawable() { - int[] attrs = new int[]{R.attr.selectableItemBackground}; - TypedArray typedArray = context.obtainStyledAttributes(attrs); - Drawable drawable = typedArray.getDrawable(0); - typedArray.recycle(); - return drawable; - } - - private boolean isSubItemNewMovedInOrChanged(List subItems) { - boolean isAlertActive = false; - - for (TimetableSubItem subItem : subItems) { - if (subItem.getLesson().getMovedOrCanceled() || - subItem.getLesson().getNewMovedInOrChanged()) { - isAlertActive = true; - } - } - return isAlertActive; - } - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableSubItem.java b/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableSubItem.java deleted file mode 100644 index 2bf47b33..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableSubItem.java +++ /dev/null @@ -1,144 +0,0 @@ -package io.github.wulkanowy.ui.main.timetable.tab; - -import android.content.Context; -import android.graphics.Paint; -import android.support.v4.app.DialogFragment; -import android.support.v4.app.FragmentActivity; -import android.view.View; -import android.widget.ImageView; -import android.widget.TextView; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; - -import java.util.List; - -import butterknife.BindView; -import butterknife.ButterKnife; -import eu.davidea.flexibleadapter.FlexibleAdapter; -import eu.davidea.flexibleadapter.items.AbstractSectionableItem; -import eu.davidea.flexibleadapter.items.IFlexible; -import eu.davidea.viewholders.FlexibleViewHolder; -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.db.dao.entities.TimetableLesson; -import io.github.wulkanowy.ui.main.timetable.TimetableDialogFragment; - - -public class TimetableSubItem - extends AbstractSectionableItem { - - private TimetableLesson lesson; - - TimetableSubItem(TimetableHeader header, TimetableLesson lesson) { - super(header); - this.lesson = lesson; - } - - public TimetableLesson getLesson() { - return lesson; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - - if (o == null || getClass() != o.getClass()) return false; - - TimetableSubItem that = (TimetableSubItem) o; - - return new EqualsBuilder() - .append(lesson, that.lesson) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) - .append(lesson) - .toHashCode(); - } - - @Override - public int getLayoutRes() { - return R.layout.timetable_subitem; - } - - @Override - public SubItemViewHolder createViewHolder(View view, FlexibleAdapter adapter) { - return new SubItemViewHolder(view, adapter); - } - - @Override - public void bindViewHolder(FlexibleAdapter adapter, SubItemViewHolder holder, - int position, List payloads) { - holder.onBind(lesson); - } - - static class SubItemViewHolder extends FlexibleViewHolder { - - @BindView(R.id.timetable_subItem_lesson) - TextView lessonName; - - @BindView(R.id.timetable_subItem_number_of_lesson) - TextView numberOfLesson; - - @BindView(R.id.timetable_subItem_time) - TextView lessonTime; - - @BindView(R.id.timetable_subItem_room) - TextView room; - - @BindView(R.id.timetable_subItem_alert_image) - ImageView alert; - - private Context context; - - private TimetableLesson item; - - SubItemViewHolder(View view, FlexibleAdapter adapter) { - super(view, adapter); - ButterKnife.bind(this, view); - context = view.getContext(); - view.setOnClickListener(this); - } - - void onBind(TimetableLesson lesson) { - item = lesson; - - lessonName.setText(lesson.getSubject()); - lessonTime.setText(getLessonTimeString()); - numberOfLesson.setText(String.valueOf(lesson.getNumber())); - room.setText(getRoomString()); - alert.setVisibility(lesson.getMovedOrCanceled() || lesson.getNewMovedInOrChanged() - ? View.VISIBLE : View.INVISIBLE); - lessonName.setPaintFlags(lesson.getMovedOrCanceled() ? lessonName.getPaintFlags() - | Paint.STRIKE_THRU_TEXT_FLAG : - lessonName.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG)); - room.setText(getRoomString()); - } - - @Override - public void onClick(View view) { - super.onClick(view); - showDialog(); - } - - private String getLessonTimeString() { - return String.format("%1$s - %2$s", item.getStartTime(), item.getEndTime()); - } - - private String getRoomString() { - if (!item.getRoom().isEmpty()) { - return context.getString(R.string.timetable_subitem_room, item.getRoom()); - } else { - return item.getRoom(); - } - } - - private void showDialog() { - TimetableDialogFragment dialogFragment = TimetableDialogFragment.newInstance(item); - dialogFragment.setStyle(DialogFragment.STYLE_NO_TITLE, 0); - dialogFragment.show(((FragmentActivity) context).getSupportFragmentManager(), item.toString()); - } - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableTabContract.java b/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableTabContract.java deleted file mode 100644 index 0814ff3c..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableTabContract.java +++ /dev/null @@ -1,34 +0,0 @@ -package io.github.wulkanowy.ui.main.timetable.tab; - -import java.util.List; - -import io.github.wulkanowy.ui.base.BaseContract; - -public interface TimetableTabContract { - - interface View extends BaseContract.View { - - void updateAdapterList(List headerItems); - - void expandItem(int item); - - void onRefreshSuccess(); - - void hideRefreshingBar(); - - void showNoItem(boolean show); - - void showProgressBar(boolean show); - - void setFreeWeekName(String text); - } - - interface Presenter extends BaseContract.Presenter { - - void onFragmentActivated(boolean isSelected); - - void setArgumentDate(String date); - - void onRefresh(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableTabFragment.java b/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableTabFragment.java deleted file mode 100644 index 87db5195..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableTabFragment.java +++ /dev/null @@ -1,143 +0,0 @@ -package io.github.wulkanowy.ui.main.timetable.tab; - -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.v4.widget.SwipeRefreshLayout; -import android.support.v7.widget.RecyclerView; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import java.util.List; - -import javax.inject.Inject; - -import butterknife.BindView; -import eu.davidea.flexibleadapter.FlexibleAdapter; -import eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager; -import io.github.wulkanowy.R; -import io.github.wulkanowy.ui.base.BaseFragment; - -public class TimetableTabFragment extends BaseFragment implements TimetableTabContract.View, - SwipeRefreshLayout.OnRefreshListener { - - private static final String ARGUMENT_KEY = "date"; - - @BindView(R.id.timetable_tab_fragment_recycler) - RecyclerView recyclerView; - - @BindView(R.id.timetable_tab_fragment_swipe_refresh) - SwipeRefreshLayout refreshLayout; - - @BindView(R.id.timetable_tab_fragment_progress_bar) - View progressBar; - - @BindView(R.id.timetable_tab_fragment_no_item_container) - View noItemView; - - @BindView(R.id.timetable_tab_fragment_no_item_name) - TextView noItemName; - - @Inject - TimetableTabContract.Presenter presenter; - - @Inject - FlexibleAdapter adapter; - - private boolean isFragmentVisible = false; - - public static TimetableTabFragment newInstance(String date) { - TimetableTabFragment fragmentTab = new TimetableTabFragment(); - - Bundle bundle = new Bundle(); - bundle.putString(ARGUMENT_KEY, date); - fragmentTab.setArguments(bundle); - - return fragmentTab; - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_timetable_tab, container, false); - injectViews(view); - - if (getArguments() != null) { - presenter.setArgumentDate(getArguments().getString(ARGUMENT_KEY)); - } - presenter.attachView(this); - presenter.onFragmentActivated(isFragmentVisible); - return view; - } - - @Override - public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { - adapter.setAutoCollapseOnExpand(true); - adapter.setAutoScrollOnExpand(true); - adapter.expandItemsAtStartUp(); - - recyclerView.setLayoutManager(new SmoothScrollLinearLayoutManager(view.getContext())); - recyclerView.setAdapter(adapter); - - refreshLayout.setColorSchemeResources(android.R.color.black); - refreshLayout.setOnRefreshListener(this); - } - - @Override - public void updateAdapterList(List headerItems) { - adapter.updateDataSet(headerItems); - } - - @Override - public void expandItem(int position) { - adapter.expand(adapter.getItem(position), true); - recyclerView.scrollToPosition(position); - } - - @Override - public void setMenuVisibility(boolean menuVisible) { - super.setMenuVisibility(menuVisible); - isFragmentVisible = menuVisible; - if (presenter != null) { - presenter.onFragmentActivated(menuVisible); - } - } - - @Override - public void setFreeWeekName(String text) { - noItemName.setText(text); - } - - @Override - public void onRefresh() { - presenter.onRefresh(); - } - - @Override - public void onRefreshSuccess() { - showMessage(R.string.sync_completed); - } - - @Override - public void hideRefreshingBar() { - refreshLayout.setRefreshing(false); - } - - @Override - public void showProgressBar(boolean show) { - progressBar.setVisibility(show ? View.VISIBLE : View.INVISIBLE); - } - - @Override - public void showNoItem(boolean show) { - noItemView.setVisibility(show ? View.VISIBLE : View.INVISIBLE); - } - - @Override - public void onDestroyView() { - presenter.detachView(); - super.onDestroyView(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableTabModule.java b/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableTabModule.java deleted file mode 100644 index 1afb055f..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableTabModule.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.github.wulkanowy.ui.main.timetable.tab; - -import dagger.Binds; -import dagger.Module; -import dagger.Provides; -import eu.davidea.flexibleadapter.FlexibleAdapter; -import io.github.wulkanowy.di.scopes.PerChildFragment; - -@Module -public abstract class TimetableTabModule { - - @PerChildFragment - @Binds - abstract TimetableTabContract.Presenter provideTimetableTabPresneter(TimetableTabPresenter timetableTabPresenter); - - @PerChildFragment - @Provides - static FlexibleAdapter provideTimetableAdapter() { - return new FlexibleAdapter<>(null); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableTabPresenter.java b/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableTabPresenter.java deleted file mode 100644 index f30dd804..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableTabPresenter.java +++ /dev/null @@ -1,200 +0,0 @@ -package io.github.wulkanowy.ui.main.timetable.tab; - -import android.support.annotation.NonNull; - -import org.threeten.bp.LocalDate; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import io.github.wulkanowy.data.RepositoryContract; -import io.github.wulkanowy.data.db.dao.entities.Day; -import io.github.wulkanowy.data.db.dao.entities.TimetableLesson; -import io.github.wulkanowy.data.db.dao.entities.Week; -import io.github.wulkanowy.ui.base.BasePresenter; -import io.github.wulkanowy.utils.AppConstant; -import io.github.wulkanowy.utils.FabricUtils; -import io.github.wulkanowy.utils.async.AbstractTask; -import io.github.wulkanowy.utils.async.AsyncListeners; - -import static io.github.wulkanowy.utils.TimeUtilsKt.getParsedDate; -import static io.github.wulkanowy.utils.TimeUtilsKt.isDateInWeek; - -public class TimetableTabPresenter extends BasePresenter - implements TimetableTabContract.Presenter, AsyncListeners.OnRefreshListener, - AsyncListeners.OnFirstLoadingListener { - - private AbstractTask refreshTask; - - private AbstractTask loadingTask; - - private List headerItems = new ArrayList<>(); - - private String date; - - private String freeWeekName; - - private boolean isFirstSight = false; - - @Inject - TimetableTabPresenter(RepositoryContract repository) { - super(repository); - } - - @Override - public void attachView(@NonNull TimetableTabContract.View view) { - super.attachView(view); - getView().showProgressBar(true); - getView().showNoItem(false); - } - - @Override - public void onFragmentActivated(boolean isSelected) { - if (!isFirstSight && isSelected && isViewAttached()) { - loadingTask = new AbstractTask(); - loadingTask.setOnFirstLoadingListener(this); - loadingTask.execute(); - } else if (!isSelected) { - cancelAsyncTasks(); - } - } - - @Override - public void onRefresh() { - if (getView().isNetworkConnected()) { - refreshTask = new AbstractTask(); - refreshTask.setOnRefreshListener(this); - refreshTask.execute(); - } else { - getView().showNoNetworkMessage(); - getView().hideRefreshingBar(); - } - } - - @Override - public void onDoInBackgroundRefresh() throws Exception { - syncData(); - } - - @Override - public void onCanceledRefreshAsync() { - if (isViewAttached()) { - getView().hideRefreshingBar(); - } - } - - @Override - public void onEndRefreshAsync(boolean result, Exception exception) { - if (result) { - loadingTask = new AbstractTask(); - loadingTask.setOnFirstLoadingListener(this); - loadingTask.execute(); - - getView().onRefreshSuccess(); - } else { - getView().showMessage(getRepository().getResRepo().getErrorLoginMessage(exception)); - } - getView().hideRefreshingBar(); - - FabricUtils.logRefresh("Timetable", result, date); - } - - @Override - public void onDoInBackgroundLoading() throws Exception { - Week week = getRepository().getDbRepo().getWeek(date); - - if (week == null || !week.getTimetableSynced()) { - syncData(); - week = getRepository().getDbRepo().getWeek(date); - } - - week.resetDayList(); - List dayList = week.getDayList(); - - headerItems = new ArrayList<>(); - - boolean isFreeWeek = true; - - for (Day day : dayList) { - day.resetTimetableLessons(); - TimetableHeader headerItem = new TimetableHeader(day); - - if (isFreeWeek) { - isFreeWeek = day.getFreeDay(); - } - - List lessonList = day.getTimetableLessons(); - - List subItems = new ArrayList<>(); - - for (TimetableLesson lesson : lessonList) { - subItems.add(new TimetableSubItem(headerItem, lesson)); - } - - headerItem.setSubItems(subItems); - headerItem.setExpanded(false); - headerItems.add(headerItem); - } - - if (isFreeWeek) { - freeWeekName = dayList.get(4).getFreeDayName(); - headerItems = new ArrayList<>(); - } - } - - @Override - public void onCanceledLoadingAsync() { - // do nothing - } - - @Override - public void onEndLoadingAsync(boolean result, Exception exception) { - getView().showNoItem(headerItems.isEmpty()); - getView().updateAdapterList(headerItems); - - if (headerItems.isEmpty()) { - getView().setFreeWeekName(freeWeekName); - } else { - expandCurrentDayHeader(); - } - getView().showProgressBar(false); - isFirstSight = true; - } - - private void expandCurrentDayHeader() { - LocalDate monday = getParsedDate(date, AppConstant.DATE_PATTERN); - - if (isDateInWeek(monday, LocalDate.now()) && !isFirstSight) { - getView().expandItem(LocalDate.now().getDayOfWeek().getValue() - 1); - } - } - - @Override - public void setArgumentDate(String date) { - this.date = date; - } - - private void syncData() throws Exception { - getRepository().getSyncRepo().syncTimetable(0, date); - } - - private void cancelAsyncTasks() { - if (refreshTask != null) { - refreshTask.cancel(true); - refreshTask = null; - } - if (loadingTask != null) { - loadingTask.cancel(true); - loadingTask = null; - } - } - - @Override - public void detachView() { - isFirstSight = false; - cancelAsyncTasks(); - super.detachView(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/about/AboutFragment.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/about/AboutFragment.kt new file mode 100644 index 00000000..b7c57cbc --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/about/AboutFragment.kt @@ -0,0 +1,68 @@ +package io.github.wulkanowy.ui.modules.about + +import android.content.Intent +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import com.mikepenz.aboutlibraries.LibsBuilder +import com.mikepenz.aboutlibraries.LibsFragmentCompat +import io.github.wulkanowy.R +import io.github.wulkanowy.ui.base.BaseFragment +import io.github.wulkanowy.ui.modules.main.MainView +import io.github.wulkanowy.utils.withOnExtraListener +import javax.inject.Inject + +class AboutFragment : BaseFragment(), AboutView, MainView.TitledView { + + @Inject + lateinit var presenter: AboutPresenter + + @Inject + lateinit var fragmentCompat: LibsFragmentCompat + + companion object { + fun newInstance() = AboutFragment() + } + + override val titleStringId: Int + get() = R.string.about_title + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + presenter.onAttachView(this) + return Bundle().apply { + putSerializable("data", LibsBuilder() + .withAboutAppName(getString(R.string.app_name)) + .withAboutVersionShown(true) + .withAboutIconShown(true) + .withLicenseShown(true) + .withAboutSpecial1(getString(R.string.about_source_code)) + .withAboutSpecial2(getString(R.string.about_feedback)) + .withCheckCachedDetection(false) + .withExcludedLibraries("fastadapter", "AndroidIconics", "gson", + "Jsoup", "Retrofit", "okio", "OkHttp") + .withOnExtraListener { presenter.onExtraSelect(it) }) + }.let { + fragmentCompat.onCreateView(inflater.context, inflater, container, savedInstanceState, it) + } + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + fragmentCompat.onViewCreated(view, savedInstanceState) + } + + override fun openSourceWebView() { + startActivity(Intent.parseUri("https://github.com/wulkanowy/wulkanowy", 0)) + } + + override fun openIssuesWebView() { + startActivity(Intent.parseUri("https://github.com/wulkanowy/wulkanowy/issues", 0)) + } + + override fun onDestroyView() { + fragmentCompat.onDestroyView() + presenter.onDetachView() + super.onDestroyView() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/about/AboutModule.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/about/AboutModule.kt new file mode 100644 index 00000000..cc5ba7cf --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/about/AboutModule.kt @@ -0,0 +1,14 @@ +package io.github.wulkanowy.ui.modules.about + +import com.mikepenz.aboutlibraries.LibsFragmentCompat +import dagger.Module +import dagger.Provides +import io.github.wulkanowy.di.scopes.PerFragment + +@Module +class AboutModule { + + @PerFragment + @Provides + fun provideLibsFragmentCompat() = LibsFragmentCompat() +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/about/AboutPresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/about/AboutPresenter.kt new file mode 100644 index 00000000..d0ca64f9 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/about/AboutPresenter.kt @@ -0,0 +1,29 @@ +package io.github.wulkanowy.ui.modules.about + +import com.mikepenz.aboutlibraries.Libs +import com.mikepenz.aboutlibraries.Libs.SpecialButton.SPECIAL1 +import com.mikepenz.aboutlibraries.Libs.SpecialButton.SPECIAL2 +import com.mikepenz.aboutlibraries.Libs.SpecialButton.SPECIAL3 +import io.github.wulkanowy.data.ErrorHandler +import io.github.wulkanowy.ui.base.BasePresenter +import timber.log.Timber +import javax.inject.Inject + +class AboutPresenter @Inject constructor(errorHandler: ErrorHandler) : BasePresenter(errorHandler) { + + fun onExtraSelect(type: Libs.SpecialButton?) { + view?.run { + when (type) { + SPECIAL1 -> { + Timber.i("Opening github page") + openSourceWebView() + } + SPECIAL2 -> { + Timber.i("Opening issues page") + openIssuesWebView() + } + SPECIAL3 -> { } + } + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/about/AboutView.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/about/AboutView.kt new file mode 100644 index 00000000..a3ae2ada --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/about/AboutView.kt @@ -0,0 +1,10 @@ +package io.github.wulkanowy.ui.modules.about + +import io.github.wulkanowy.ui.base.BaseView + +interface AboutView : BaseView { + + fun openSourceWebView() + + fun openIssuesWebView() +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/attendance/AttendanceDialog.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/attendance/AttendanceDialog.kt new file mode 100644 index 00000000..611dd999 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/attendance/AttendanceDialog.kt @@ -0,0 +1,48 @@ +package io.github.wulkanowy.ui.modules.attendance + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.DialogFragment +import io.github.wulkanowy.R +import io.github.wulkanowy.data.db.entities.Attendance +import io.github.wulkanowy.utils.toFormattedString +import kotlinx.android.synthetic.main.dialog_attendance.* + +class AttendanceDialog : DialogFragment() { + + private lateinit var attendance: Attendance + + companion object { + private const val ARGUMENT_KEY = "Item" + + fun newInstance(exam: Attendance): AttendanceDialog { + return AttendanceDialog().apply { + arguments = Bundle().apply { putSerializable(ARGUMENT_KEY, exam) } + } + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setStyle(STYLE_NO_TITLE, 0) + arguments?.run { + attendance = getSerializable(ARGUMENT_KEY) as Attendance + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.dialog_attendance, container, false) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + + attendanceDialogSubject.text = attendance.subject + attendanceDialogDescription.text = attendance.name + attendanceDialogDate.text = attendance.date.toFormattedString() + attendanceDialogNumber.text = attendance.number.toString() + attendanceDialogClose.setOnClickListener { dismiss() } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/attendance/AttendanceFragment.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/attendance/AttendanceFragment.kt new file mode 100644 index 00000000..92226be2 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/attendance/AttendanceFragment.kt @@ -0,0 +1,115 @@ +package io.github.wulkanowy.ui.modules.attendance + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import io.github.wulkanowy.R +import io.github.wulkanowy.data.db.entities.Attendance +import io.github.wulkanowy.ui.base.BaseFragment +import io.github.wulkanowy.ui.modules.main.MainView +import io.github.wulkanowy.utils.setOnItemClickListener +import kotlinx.android.synthetic.main.fragment_attendance.* +import javax.inject.Inject + +class AttendanceFragment : BaseFragment(), AttendanceView, MainView.MainChildView, MainView.TitledView { + + @Inject + lateinit var presenter: AttendancePresenter + + @Inject + lateinit var attendanceAdapter: FlexibleAdapter> + + companion object { + private const val SAVED_DATE_KEY = "CURRENT_DATE" + + fun newInstance() = AttendanceFragment() + } + + override val titleStringId: Int + get() = R.string.attendance_title + + override val isViewEmpty: Boolean + get() = attendanceAdapter.isEmpty + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_attendance, container, false) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + messageContainer = attendanceRecycler + presenter.onAttachView(this, savedInstanceState?.getLong(SAVED_DATE_KEY)) + } + + override fun initView() { + attendanceAdapter.apply { + setOnItemClickListener { presenter.onAttendanceItemSelected(getItem(it)) } + } + + attendanceRecycler.run { + layoutManager = SmoothScrollLinearLayoutManager(context) + adapter = attendanceAdapter + } + attendanceSwipe.setOnRefreshListener { presenter.onSwipeRefresh() } + attendancePreviousButton.setOnClickListener { presenter.onPreviousDay() } + attendanceNextButton.setOnClickListener { presenter.onNextDay() } + } + + override fun updateData(data: List) { + attendanceAdapter.updateDataSet(data, true) + } + + override fun updateNavigationDay(date: String) { + attendanceNavDate.text = date + } + + override fun clearData() { + attendanceAdapter.clear() + } + + override fun onFragmentReselected() { + presenter.onViewReselected() + } + + override fun showEmpty(show: Boolean) { + attendanceEmpty.visibility = if (show) View.VISIBLE else View.GONE + } + + override fun showProgress(show: Boolean) { + attendanceProgress.visibility = if (show) View.VISIBLE else View.GONE + } + + override fun showContent(show: Boolean) { + attendanceRecycler.visibility = if (show) View.VISIBLE else View.GONE + } + + override fun hideRefresh() { + attendanceSwipe.isRefreshing = false + } + + override fun showPreButton(show: Boolean) { + attendancePreviousButton.visibility = if (show) View.VISIBLE else View.INVISIBLE + } + + override fun showNextButton(show: Boolean) { + attendanceNextButton.visibility = if (show) View.VISIBLE else View.INVISIBLE + } + + override fun showAttendanceDialog(lesson: Attendance) { + AttendanceDialog.newInstance(lesson).show(fragmentManager, lesson.toString()) + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putLong(SAVED_DATE_KEY, presenter.currentDate.toEpochDay()) + } + + override fun onDestroyView() { + presenter.onDetachView() + super.onDestroyView() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/attendance/AttendanceItem.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/attendance/AttendanceItem.kt new file mode 100644 index 00000000..c2698ebb --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/attendance/AttendanceItem.kt @@ -0,0 +1,53 @@ +package io.github.wulkanowy.ui.modules.attendance + +import android.view.View +import android.view.View.INVISIBLE +import android.view.View.VISIBLE +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import eu.davidea.flexibleadapter.items.IFlexible +import eu.davidea.viewholders.FlexibleViewHolder +import io.github.wulkanowy.R +import io.github.wulkanowy.data.db.entities.Attendance +import kotlinx.android.extensions.LayoutContainer +import kotlinx.android.synthetic.main.item_attendance.* + +class AttendanceItem(val attendance: Attendance) : AbstractFlexibleItem() { + + override fun createViewHolder(view: View, adapter: FlexibleAdapter>): ViewHolder { + return ViewHolder(view, adapter) + } + + override fun getLayoutRes(): Int = R.layout.item_attendance + + override fun bindViewHolder(adapter: FlexibleAdapter>, holder: ViewHolder, + position: Int, payloads: MutableList?) { + holder.apply { + attendanceItemNumber.text = attendance.number.toString() + attendanceItemSubject.text = attendance.subject + attendanceItemDescription.text = attendance.name + attendanceItemAlert.visibility = attendance.run { if (absence && !excused) VISIBLE else INVISIBLE } + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as AttendanceItem + + if (attendance != other.attendance) return false + return true + } + + override fun hashCode(): Int { + return attendance.hashCode() + } + + class ViewHolder(val view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter), + LayoutContainer { + + override val containerView: View + get() = contentView + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/attendance/AttendancePresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/attendance/AttendancePresenter.kt new file mode 100644 index 00000000..7df50d9e --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/attendance/AttendancePresenter.kt @@ -0,0 +1,113 @@ +package io.github.wulkanowy.ui.modules.attendance + +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import io.github.wulkanowy.data.ErrorHandler +import io.github.wulkanowy.data.repositories.AttendanceRepository +import io.github.wulkanowy.data.repositories.PreferencesRepository +import io.github.wulkanowy.data.repositories.SessionRepository +import io.github.wulkanowy.ui.base.BasePresenter +import io.github.wulkanowy.utils.SchedulersProvider +import io.github.wulkanowy.utils.isHolidays +import io.github.wulkanowy.utils.logEvent +import io.github.wulkanowy.utils.nextSchoolDay +import io.github.wulkanowy.utils.previousOrSameSchoolDay +import io.github.wulkanowy.utils.previousSchoolDay +import io.github.wulkanowy.utils.toFormattedString +import org.threeten.bp.LocalDate +import org.threeten.bp.LocalDate.now +import org.threeten.bp.LocalDate.ofEpochDay +import java.util.concurrent.TimeUnit.MILLISECONDS +import javax.inject.Inject + +class AttendancePresenter @Inject constructor( + private val errorHandler: ErrorHandler, + private val schedulers: SchedulersProvider, + private val attendanceRepository: AttendanceRepository, + private val sessionRepository: SessionRepository, + private val prefRepository: PreferencesRepository +) : BasePresenter(errorHandler) { + + lateinit var currentDate: LocalDate + private set + + fun onAttachView(view: AttendanceView, date: Long?) { + super.onAttachView(view) + view.initView() + loadData(ofEpochDay(date ?: now().previousOrSameSchoolDay.toEpochDay())) + reloadView() + } + + fun onPreviousDay() { + loadData(currentDate.previousSchoolDay) + reloadView() + logEvent("Attendance day changed", mapOf("button" to "prev", "date" to currentDate.toFormattedString())) + } + + fun onNextDay() { + loadData(currentDate.nextSchoolDay) + reloadView() + logEvent("Attendance day changed", mapOf("button" to "next", "date" to currentDate.toFormattedString())) + } + + fun onSwipeRefresh() { + loadData(currentDate, true) + } + + fun onViewReselected() { + loadData(now().previousOrSameSchoolDay) + reloadView() + } + + fun onAttendanceItemSelected(item: AbstractFlexibleItem<*>?) { + if (item is AttendanceItem) view?.showAttendanceDialog(item.attendance) + } + + private fun loadData(date: LocalDate, forceRefresh: Boolean = false) { + currentDate = date + disposable.apply { + clear() + add(sessionRepository.getSemesters() + .delay(200, MILLISECONDS) + .map { it.single { semester -> semester.current } } + .flatMap { attendanceRepository.getAttendance(it, date, date, forceRefresh) } + .map { list -> + if (prefRepository.showPresent) list + else list.filter { !it.presence } + } + .map { items -> items.map { AttendanceItem(it) } } + .map { items -> items.sortedBy { it.attendance.number } } + .subscribeOn(schedulers.backgroundThread) + .observeOn(schedulers.mainThread) + .doFinally { + view?.run { + hideRefresh() + showProgress(false) + } + } + .subscribe({ + view?.apply { + updateData(it) + showEmpty(it.isEmpty()) + showContent(it.isNotEmpty()) + } + logEvent("Attendance load", mapOf("items" to it.size, "forceRefresh" to forceRefresh, "date" to currentDate.toFormattedString())) + }) { + view?.run { showEmpty(isViewEmpty) } + errorHandler.proceed(it) + } + ) + } + } + + private fun reloadView() { + view?.apply { + showProgress(true) + showContent(false) + showEmpty(false) + clearData() + showNextButton(!currentDate.plusDays(1).isHolidays) + showPreButton(!currentDate.minusDays(1).isHolidays) + updateNavigationDay(currentDate.toFormattedString("EEEE \n dd.MM.YYYY").capitalize()) + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/attendance/AttendanceView.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/attendance/AttendanceView.kt new file mode 100644 index 00000000..3479086a --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/attendance/AttendanceView.kt @@ -0,0 +1,31 @@ +package io.github.wulkanowy.ui.modules.attendance + +import io.github.wulkanowy.data.db.entities.Attendance +import io.github.wulkanowy.ui.base.BaseView + +interface AttendanceView : BaseView { + + val isViewEmpty: Boolean + + fun initView() + + fun updateData(data: List) + + fun updateNavigationDay(date: String) + + fun clearData() + + fun hideRefresh() + + fun showEmpty(show: Boolean) + + fun showProgress(show: Boolean) + + fun showContent(show: Boolean) + + fun showPreButton(show: Boolean) + + fun showNextButton(show: Boolean) + + fun showAttendanceDialog(lesson: Attendance) +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamDialog.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamDialog.kt new file mode 100644 index 00000000..ed5092c9 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamDialog.kt @@ -0,0 +1,50 @@ +package io.github.wulkanowy.ui.modules.exam + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.DialogFragment +import io.github.wulkanowy.R +import io.github.wulkanowy.data.db.entities.Exam +import io.github.wulkanowy.utils.toFormattedString +import kotlinx.android.synthetic.main.dialog_exam.* + +class ExamDialog : DialogFragment() { + + private lateinit var exam: Exam + + companion object { + private const val ARGUMENT_KEY = "Item" + + fun newInstance(exam: Exam): ExamDialog { + return ExamDialog().apply { + arguments = Bundle().apply { putSerializable(ARGUMENT_KEY, exam) } + } + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setStyle(STYLE_NO_TITLE, 0) + arguments?.run { + exam = getSerializable(ARGUMENT_KEY) as Exam + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.dialog_exam, container, false) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + + examDialogSubjectValue.text = exam.subject + examDialogTypeValue.text = exam.type + examDialogTeacherValue.text = exam.teacher + examDialogDateValue.text = exam.entryDate.toFormattedString() + examDialogDescriptionValue.text = exam.description + + examDialogClose.setOnClickListener { dismiss() } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamFragment.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamFragment.kt new file mode 100644 index 00000000..3e1f7cad --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamFragment.kt @@ -0,0 +1,115 @@ +package io.github.wulkanowy.ui.modules.exam + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.View.* +import android.view.ViewGroup +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import io.github.wulkanowy.R +import io.github.wulkanowy.data.db.entities.Exam +import io.github.wulkanowy.ui.base.BaseFragment +import io.github.wulkanowy.ui.modules.main.MainView +import io.github.wulkanowy.utils.setOnItemClickListener +import kotlinx.android.synthetic.main.fragment_exam.* +import javax.inject.Inject + +class ExamFragment : BaseFragment(), ExamView, MainView.MainChildView, MainView.TitledView { + + @Inject + lateinit var presenter: ExamPresenter + + @Inject + lateinit var examAdapter: FlexibleAdapter> + + companion object { + private const val SAVED_DATE_KEY = "CURRENT_DATE" + + fun newInstance() = ExamFragment() + } + + override val titleStringId: Int + get() = R.string.exam_title + + override val isViewEmpty: Boolean + get() = examAdapter.isEmpty + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_exam, container, false) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + messageContainer = examRecycler + presenter.onAttachView(this, savedInstanceState?.getLong(SAVED_DATE_KEY)) + } + + override fun initView() { + examAdapter.run { + setOnItemClickListener { presenter.onExamItemSelected(getItem(it)) } + } + examRecycler.run { + layoutManager = SmoothScrollLinearLayoutManager(context) + adapter = examAdapter + } + examSwipe.setOnRefreshListener { presenter.onSwipeRefresh() } + examPreviousButton.setOnClickListener { presenter.onPreviousWeek() } + examNextButton.setOnClickListener { presenter.onNextWeek() } + } + + override fun hideRefresh() { + examSwipe.isRefreshing = false + } + + override fun updateData(data: List) { + examAdapter.updateDataSet(data, true) + } + + override fun updateNavigationWeek(date: String) { + examNavDate.text = date + } + + override fun clearData() { + examAdapter.clear() + } + + override fun onFragmentReselected() { + presenter.onViewReselected() + } + + override fun showEmpty(show: Boolean) { + examEmpty.visibility = if (show) VISIBLE else GONE + } + + override fun showProgress(show: Boolean) { + examProgress.visibility = if (show) VISIBLE else GONE + } + + override fun showContent(show: Boolean) { + examRecycler.visibility = if (show) VISIBLE else GONE + } + + override fun showPreButton(show: Boolean) { + examPreviousButton.visibility = if (show) VISIBLE else INVISIBLE + } + + override fun showNextButton(show: Boolean) { + examNextButton.visibility = if (show) VISIBLE else INVISIBLE + } + + override fun showExamDialog(exam: Exam) { + ExamDialog.newInstance(exam).show(fragmentManager, exam.toString()) + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putLong(SAVED_DATE_KEY, presenter.currentDate.toEpochDay()) + } + + override fun onDestroyView() { + presenter.onDetachView() + super.onDestroyView() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamHeader.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamHeader.kt new file mode 100644 index 00000000..0a5b862c --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamHeader.kt @@ -0,0 +1,52 @@ +package io.github.wulkanowy.ui.modules.exam + +import android.view.View +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.items.AbstractHeaderItem +import eu.davidea.flexibleadapter.items.IFlexible +import eu.davidea.viewholders.ExpandableViewHolder +import io.github.wulkanowy.R +import io.github.wulkanowy.utils.toFormattedString +import io.github.wulkanowy.utils.weekDayName +import kotlinx.android.extensions.LayoutContainer +import kotlinx.android.synthetic.main.header_exam.* +import org.threeten.bp.LocalDate + +class ExamHeader(private val date: LocalDate) : AbstractHeaderItem() { + + override fun getLayoutRes() = R.layout.header_exam + + override fun createViewHolder(view: View?, adapter: FlexibleAdapter>?): ViewHolder { + return ViewHolder(view, adapter) + } + + override fun bindViewHolder(adapter: FlexibleAdapter>?, holder: ViewHolder, + position: Int, payloads: MutableList?) { + holder.run { + examHeaderDay.text = date.weekDayName.capitalize() + examHeaderDate.text = date.toFormattedString() + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as ExamHeader + + if (date != other.date) return false + + return true + } + + override fun hashCode(): Int { + return date.hashCode() + } + + class ViewHolder(view: View?, adapter: FlexibleAdapter>?) : ExpandableViewHolder(view, adapter), + LayoutContainer { + + override val containerView: View + get() = contentView + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamItem.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamItem.kt new file mode 100644 index 00000000..318685e9 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamItem.kt @@ -0,0 +1,51 @@ +package io.github.wulkanowy.ui.modules.exam + +import android.view.View +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.items.AbstractSectionableItem +import eu.davidea.flexibleadapter.items.IFlexible +import eu.davidea.viewholders.FlexibleViewHolder +import io.github.wulkanowy.R +import io.github.wulkanowy.data.db.entities.Exam +import kotlinx.android.extensions.LayoutContainer +import kotlinx.android.synthetic.main.item_exam.* + +class ExamItem(header: ExamHeader, val exam: Exam) : AbstractSectionableItem(header) { + + override fun getLayoutRes() = R.layout.item_exam + + override fun createViewHolder(view: View, adapter: FlexibleAdapter>): ViewHolder { + return ViewHolder(view, adapter) + } + + override fun bindViewHolder(adapter: FlexibleAdapter>, holder: ViewHolder, + position: Int, payloads: MutableList?) { + holder.run { + examItemSubject.text = exam.subject + examItemTeacher.text = exam.teacher + examItemType.text = exam.type + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as ExamItem + + if (exam != other.exam) return false + + return true + } + + override fun hashCode(): Int { + return exam.hashCode() + } + + class ViewHolder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter), + LayoutContainer { + + override val containerView: View + get() = contentView + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamPresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamPresenter.kt new file mode 100644 index 00000000..f2bf7b07 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamPresenter.kt @@ -0,0 +1,117 @@ +package io.github.wulkanowy.ui.modules.exam + +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import io.github.wulkanowy.data.ErrorHandler +import io.github.wulkanowy.data.db.entities.Exam +import io.github.wulkanowy.data.repositories.ExamRepository +import io.github.wulkanowy.data.repositories.SessionRepository +import io.github.wulkanowy.ui.base.BasePresenter +import io.github.wulkanowy.utils.SchedulersProvider +import io.github.wulkanowy.utils.friday +import io.github.wulkanowy.utils.isHolidays +import io.github.wulkanowy.utils.logEvent +import io.github.wulkanowy.utils.monday +import io.github.wulkanowy.utils.nextOrSameSchoolDay +import io.github.wulkanowy.utils.toFormattedString +import org.threeten.bp.LocalDate +import org.threeten.bp.LocalDate.now +import org.threeten.bp.LocalDate.ofEpochDay +import java.util.concurrent.TimeUnit.MILLISECONDS +import javax.inject.Inject + +class ExamPresenter @Inject constructor( + private val errorHandler: ErrorHandler, + private val schedulers: SchedulersProvider, + private val examRepository: ExamRepository, + private val sessionRepository: SessionRepository +) : BasePresenter(errorHandler) { + + lateinit var currentDate: LocalDate + private set + + fun onAttachView(view: ExamView, date: Long?) { + super.onAttachView(view) + view.initView() + loadData(ofEpochDay(date ?: now().nextOrSameSchoolDay.toEpochDay())) + reloadView() + } + + fun onPreviousWeek() { + loadData(currentDate.minusDays(7)) + reloadView() + logEvent("Exam week changed", mapOf("button" to "prev", "date" to currentDate.toFormattedString())) + } + + fun onNextWeek() { + loadData(currentDate.plusDays(7)) + reloadView() + logEvent("Exam week changed", mapOf("button" to "next", "date" to currentDate.toFormattedString())) + } + + fun onSwipeRefresh() { + loadData(currentDate, true) + } + + fun onExamItemSelected(item: AbstractFlexibleItem<*>?) { + if (item is ExamItem) view?.showExamDialog(item.exam) + } + + fun onViewReselected() { + loadData(now().nextOrSameSchoolDay) + reloadView() + } + + private fun loadData(date: LocalDate, forceRefresh: Boolean = false) { + currentDate = date + disposable.apply { + clear() + add(sessionRepository.getSemesters() + .delay(200, MILLISECONDS) + .map { it.single { semester -> semester.current } } + .flatMap { + examRepository.getExams(it, currentDate.monday, currentDate.friday, forceRefresh) + }.map { it.groupBy { exam -> exam.date }.toSortedMap() } + .map { createExamItems(it) } + .subscribeOn(schedulers.backgroundThread) + .observeOn(schedulers.mainThread) + .doFinally { + view?.run { + hideRefresh() + showProgress(false) + } + } + .subscribe({ + view?.apply { + updateData(it) + showEmpty(it.isEmpty()) + showContent(it.isNotEmpty()) + } + logEvent("Exam load", mapOf("items" to it.size, "forceRefresh" to forceRefresh, "date" to currentDate.toFormattedString())) + }) { + view?.run { showEmpty(isViewEmpty) } + errorHandler.proceed(it) + }) + } + } + + private fun createExamItems(items: Map>): List { + return items.flatMap { + ExamHeader(it.key).let { header -> + it.value.reversed().map { item -> ExamItem(header, item) } + } + } + } + + private fun reloadView() { + view?.apply { + showProgress(true) + showContent(false) + showEmpty(false) + clearData() + showPreButton(!currentDate.minusDays(7).isHolidays) + showNextButton(!currentDate.plusDays(7).isHolidays) + updateNavigationWeek("${currentDate.monday.toFormattedString("dd.MM")} - " + + currentDate.friday.toFormattedString("dd.MM")) + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamView.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamView.kt new file mode 100644 index 00000000..cfe1cb9b --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/exam/ExamView.kt @@ -0,0 +1,31 @@ +package io.github.wulkanowy.ui.modules.exam + +import io.github.wulkanowy.data.db.entities.Exam +import io.github.wulkanowy.ui.base.BaseView + +interface ExamView : BaseView { + + val isViewEmpty: Boolean + + fun initView() + + fun updateData(data: List) + + fun updateNavigationWeek(date: String) + + fun clearData() + + fun hideRefresh() + + fun showEmpty(show: Boolean) + + fun showProgress(show: Boolean) + + fun showContent(show: Boolean) + + fun showNextButton(show: Boolean) + + fun showPreButton(show: Boolean) + + fun showExamDialog(exam: Exam) +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/grade/GradeFragment.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/GradeFragment.kt new file mode 100644 index 00000000..57140c16 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/GradeFragment.kt @@ -0,0 +1,131 @@ +package io.github.wulkanowy.ui.modules.grade + +import android.os.Bundle +import android.view.* +import android.view.View.INVISIBLE +import android.view.View.VISIBLE +import androidx.appcompat.app.AlertDialog +import io.github.wulkanowy.R +import io.github.wulkanowy.ui.base.BaseFragment +import io.github.wulkanowy.ui.base.BasePagerAdapter +import io.github.wulkanowy.ui.modules.grade.details.GradeDetailsFragment +import io.github.wulkanowy.ui.modules.grade.summary.GradeSummaryFragment +import io.github.wulkanowy.ui.modules.main.MainView +import io.github.wulkanowy.utils.setOnSelectPageListener +import kotlinx.android.synthetic.main.fragment_grade.* +import javax.inject.Inject + +class GradeFragment : BaseFragment(), GradeView, MainView.MainChildView, MainView.TitledView { + + @Inject + lateinit var presenter: GradePresenter + + @Inject + lateinit var pagerAdapter: BasePagerAdapter + + companion object { + private const val SAVED_SEMESTER_KEY = "CURRENT_SEMESTER" + + fun newInstance() = GradeFragment() + } + + override val titleStringId: Int + get() = R.string.grade_title + + override val currentPageIndex: Int + get() = gradeViewPager.currentItem + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setHasOptionsMenu(true) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_grade, container, false) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + presenter.onAttachView(this, savedInstanceState?.getInt(SAVED_SEMESTER_KEY)) + } + + override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { + inflater?.inflate(R.menu.action_menu_grade, menu) + } + + override fun initView() { + pagerAdapter.fragments.putAll(mapOf( + getString(R.string.all_details) to GradeDetailsFragment.newInstance(), + getString(R.string.grade_menu_summary) to GradeSummaryFragment.newInstance() + )) + gradeViewPager.run { + adapter = pagerAdapter + setOnSelectPageListener { presenter.onPageSelected(it) } + } + gradeTabLayout.setupWithViewPager(gradeViewPager) + } + + override fun onOptionsItemSelected(item: MenuItem?): Boolean { + return if (item?.itemId == R.id.gradeMenuSemester) presenter.onSemesterSwitch() + else false + } + + override fun onFragmentReselected() { + presenter.onViewReselected() + } + + override fun showContent(show: Boolean) { + gradeViewPager.visibility = if (show) VISIBLE else INVISIBLE + gradeTabLayout.visibility = if (show) VISIBLE else INVISIBLE + } + + override fun showProgress(show: Boolean) { + gradeProgress.visibility = if (show) VISIBLE else INVISIBLE + } + + override fun showSemesterDialog(selectedIndex: Int) { + arrayOf(getString(R.string.grade_semester, 1), + getString(R.string.grade_semester, 2)).also { array -> + context?.let { + AlertDialog.Builder(it) + .setSingleChoiceItems(array, selectedIndex) { dialog, which -> + presenter.onSemesterSelected(which) + dialog.dismiss() + } + .setTitle(R.string.grade_switch_semester) + .setNegativeButton(R.string.all_cancel) { dialog, _ -> dialog.dismiss() } + .show() + } + } + } + + fun onChildRefresh() { + presenter.onChildViewRefresh() + } + + fun onChildFragmentLoaded(semesterId: Int) { + presenter.onChildViewLoaded(semesterId) + } + + override fun notifyChildLoadData(index: Int, semesterId: Int, forceRefresh: Boolean) { + (childFragmentManager.fragments[index] as GradeView.GradeChildView).onParentLoadData(semesterId, forceRefresh) + } + + override fun notifyChildParentReselected(index: Int) { + (pagerAdapter.registeredFragments[index] as? GradeView.GradeChildView)?.onParentReselected() + } + + override fun notifyChildSemesterChange(index: Int) { + (pagerAdapter.registeredFragments[index] as? GradeView.GradeChildView)?.onParentChangeSemester() + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putInt(SAVED_SEMESTER_KEY, presenter.selectedIndex) + } + + override fun onDestroyView() { + super.onDestroyView() + presenter.onDetachView() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/grade/GradeModule.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/GradeModule.kt new file mode 100644 index 00000000..eb032f79 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/GradeModule.kt @@ -0,0 +1,31 @@ +package io.github.wulkanowy.ui.modules.grade + +import dagger.Module +import dagger.Provides +import dagger.android.ContributesAndroidInjector +import io.github.wulkanowy.di.scopes.PerChildFragment +import io.github.wulkanowy.di.scopes.PerFragment +import io.github.wulkanowy.ui.base.BasePagerAdapter +import io.github.wulkanowy.ui.modules.grade.details.GradeDetailsFragment +import io.github.wulkanowy.ui.modules.grade.summary.GradeSummaryFragment + +@Module +abstract class GradeModule { + + @Module + companion object { + + @JvmStatic + @PerFragment + @Provides + fun provideGradePagerAdapter(fragment: GradeFragment) = BasePagerAdapter(fragment.childFragmentManager) + } + + @PerChildFragment + @ContributesAndroidInjector() + abstract fun bindGradeDetailsFragment(): GradeDetailsFragment + + @PerChildFragment + @ContributesAndroidInjector + abstract fun binGradeSummaryFragment(): GradeSummaryFragment +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/grade/GradePresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/GradePresenter.kt new file mode 100644 index 00000000..5d678915 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/GradePresenter.kt @@ -0,0 +1,97 @@ +package io.github.wulkanowy.ui.modules.grade + +import io.github.wulkanowy.data.ErrorHandler +import io.github.wulkanowy.data.db.entities.Semester +import io.github.wulkanowy.data.repositories.SessionRepository +import io.github.wulkanowy.ui.base.BasePresenter +import io.github.wulkanowy.utils.SchedulersProvider +import io.github.wulkanowy.utils.logEvent +import io.reactivex.Completable +import timber.log.Timber +import java.util.concurrent.TimeUnit.MILLISECONDS +import javax.inject.Inject + +class GradePresenter @Inject constructor( + private val errorHandler: ErrorHandler, + private val schedulers: SchedulersProvider, + private val sessionRepository: SessionRepository) : BasePresenter(errorHandler) { + + var selectedIndex = 0 + private set + + private var semesters = emptyList() + + private val loadedSemesterId = mutableMapOf() + + fun onAttachView(view: GradeView, savedIndex: Int?) { + super.onAttachView(view) + disposable.add(Completable.timer(150, MILLISECONDS, schedulers.mainThread) + .subscribe { + selectedIndex = savedIndex ?: 0 + view.initView() + loadData() + }) + } + + fun onViewReselected() { + view?.run { notifyChildParentReselected(currentPageIndex) } + } + + fun onSemesterSwitch(): Boolean { + if (semesters.isNotEmpty()) view?.showSemesterDialog(selectedIndex - 1) + return true + } + + fun onSemesterSelected(index: Int) { + if (selectedIndex != index - 1) { + selectedIndex = index + 1 + loadedSemesterId.clear() + view?.let { + notifyChildrenSemesterChange() + loadChild(it.currentPageIndex) + } + logEvent("Semester changed", mapOf("number" to index + 1)) + } + } + + fun onChildViewRefresh() { + view?.let { loadChild(it.currentPageIndex, true) } + } + + fun onChildViewLoaded(semesterId: Int) { + view?.apply { + showContent(true) + showProgress(false) + loadedSemesterId[currentPageIndex] = semesterId + } + } + + fun onPageSelected(index: Int) { + loadChild(index) + } + + private fun loadData() { + disposable.add(sessionRepository.getSemesters() + .doOnSuccess { + it.first { item -> item.current }.also { current -> + selectedIndex = if (selectedIndex == 0) current.semesterName else selectedIndex + semesters = it.filter { semester -> semester.diaryId == current.diaryId } + } + } + .subscribeOn(schedulers.backgroundThread) + .observeOn(schedulers.mainThread) + .subscribe({ view?.run { loadChild(currentPageIndex) } }) { errorHandler.proceed(it) }) + } + + private fun loadChild(index: Int, forceRefresh: Boolean = false) { + semesters.first { it.semesterName == selectedIndex }.semesterId.also { + if (forceRefresh || loadedSemesterId[index] != it) { + view?.notifyChildLoadData(index, it, forceRefresh) + } + } + } + + private fun notifyChildrenSemesterChange() { + for (i in 0..1) view?.notifyChildSemesterChange(i) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/grade/GradeView.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/GradeView.kt new file mode 100644 index 00000000..c48dcb95 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/GradeView.kt @@ -0,0 +1,31 @@ +package io.github.wulkanowy.ui.modules.grade + +import io.github.wulkanowy.ui.base.BaseView + +interface GradeView : BaseView { + + val currentPageIndex: Int + + fun initView() + + fun showContent(show: Boolean) + + fun showProgress(show: Boolean) + + fun showSemesterDialog(selectedIndex: Int) + + fun notifyChildLoadData(index: Int, semesterId: Int, forceRefresh: Boolean) + + fun notifyChildParentReselected(index: Int) + + fun notifyChildSemesterChange(index: Int) + + interface GradeChildView { + + fun onParentChangeSemester() + + fun onParentLoadData(semesterId: Int, forceRefresh: Boolean) + + fun onParentReselected() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsDialog.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsDialog.kt new file mode 100644 index 00000000..19b462b1 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsDialog.kt @@ -0,0 +1,78 @@ +package io.github.wulkanowy.ui.modules.grade.details + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.View.GONE +import android.view.ViewGroup +import androidx.fragment.app.DialogFragment +import io.github.wulkanowy.R +import io.github.wulkanowy.data.db.entities.Grade +import io.github.wulkanowy.utils.colorStringId +import io.github.wulkanowy.utils.toFormattedString +import io.github.wulkanowy.utils.valueColor +import kotlinx.android.synthetic.main.dialog_grade.* + + +class GradeDetailsDialog : DialogFragment() { + + private lateinit var grade: Grade + + companion object { + private const val ARGUMENT_KEY = "Item" + + fun newInstance(grade: Grade): GradeDetailsDialog { + return GradeDetailsDialog().apply { + arguments = Bundle().apply { putSerializable(ARGUMENT_KEY, grade) } + } + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setStyle(STYLE_NO_TITLE, 0) + arguments?.run { + grade = getSerializable(ARGUMENT_KEY) as Grade + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.dialog_grade, container, false) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + + gradeDialogSubject.text = grade.subject + gradeDialogWeightValue.text = grade.weight + gradeDialogDateValue.text = grade.date.toFormattedString() + gradeDialogColorValue.text = getString(grade.colorStringId) + + gradeDialogCommentValue.apply { + if (grade.comment.isBlank()) { + visibility = GONE + gradeDialogComment.visibility = GONE + } else text = grade.comment + } + + gradeDialogValue.run { + text = grade.entry + setBackgroundResource(grade.valueColor) + } + + gradeDialogTeacherValue.text = if (grade.teacher.isBlank()) { + getString(R.string.all_no_data) + } else grade.teacher + + gradeDialogDescriptionValue.text = grade.run { + when { + description.isBlank() && gradeSymbol.isNotBlank() -> gradeSymbol + description.isBlank() && gradeSymbol.isBlank() -> getString(R.string.all_no_description) + gradeSymbol.isNotBlank() && description.isNotBlank() -> "$gradeSymbol - $description" + else -> description + } + } + + gradeDialogClose.setOnClickListener { dismiss() } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsFragment.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsFragment.kt new file mode 100644 index 00000000..b10d3dec --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsFragment.kt @@ -0,0 +1,143 @@ +package io.github.wulkanowy.ui.modules.grade.details + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.View.* +import android.view.ViewGroup +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import eu.davidea.flexibleadapter.items.IExpandable +import eu.davidea.flexibleadapter.items.IFlexible +import io.github.wulkanowy.R +import io.github.wulkanowy.data.db.entities.Grade +import io.github.wulkanowy.ui.base.BaseFragment +import io.github.wulkanowy.ui.modules.grade.GradeFragment +import io.github.wulkanowy.ui.modules.grade.GradeView +import io.github.wulkanowy.utils.setOnItemClickListener +import kotlinx.android.synthetic.main.fragment_grade_details.* +import javax.inject.Inject + +class GradeDetailsFragment : BaseFragment(), GradeDetailsView, GradeView.GradeChildView { + + @Inject + lateinit var presenter: GradeDetailsPresenter + + @Inject + lateinit var gradeDetailsAdapter: FlexibleAdapter> + + companion object { + fun newInstance() = GradeDetailsFragment() + } + + override val emptyAverageString: String + get() = getString(R.string.grade_no_average) + + override val averageString: String + get() = getString(R.string.grade_average) + + override val weightString: String + get() = getString(R.string.grade_weight) + + override val isViewEmpty + get() = gradeDetailsAdapter.isEmpty + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_grade_details, container, false) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + messageContainer = gradeDetailsRecycler + presenter.onAttachView(this) + } + + override fun initView() { + gradeDetailsAdapter.run { + isAutoCollapseOnExpand = true + isAutoScrollOnExpand = true + setOnItemClickListener { presenter.onGradeItemSelected(getItem(it)) } + } + + gradeDetailsAdapter.getItemCountOfTypes() + + gradeDetailsRecycler.run { + layoutManager = SmoothScrollLinearLayoutManager(context) + adapter = gradeDetailsAdapter + } + gradeDetailsSwipe.setOnRefreshListener { presenter.onSwipeRefresh() } + } + + override fun updateData(data: List) { + gradeDetailsAdapter.updateDataSet(data, true) + } + + override fun updateItem(item: AbstractFlexibleItem<*>) { + gradeDetailsAdapter.updateItem(item) + } + + override fun clearView() { + gradeDetailsAdapter.clear() + } + + override fun resetView() { + gradeDetailsAdapter.apply { + smoothScrollToPosition(0) + collapseAll() + } + } + + override fun getHeaderOfItem(item: AbstractFlexibleItem<*>): IExpandable<*, out IFlexible<*>>? { + return gradeDetailsAdapter.getExpandableOf(item) + } + + override fun getGradeNumberString(number: Int): String { + return resources.getQuantityString(R.plurals.grade_number_item, number, number) + } + + override fun showProgress(show: Boolean) { + gradeDetailsProgress.visibility = if (show) VISIBLE else GONE + } + + override fun showContent(show: Boolean) { + gradeDetailsRecycler.visibility = if (show) VISIBLE else INVISIBLE + } + + override fun showEmpty(show: Boolean) { + gradeDetailsEmpty.visibility = if (show) VISIBLE else INVISIBLE + } + + override fun showRefresh(show: Boolean) { + gradeDetailsSwipe.isRefreshing = show + } + + override fun showGradeDialog(grade: Grade) { + GradeDetailsDialog.newInstance(grade).show(fragmentManager, grade.toString()) + } + + override fun onParentLoadData(semesterId: Int, forceRefresh: Boolean) { + presenter.onParentViewLoadData(semesterId, forceRefresh) + } + + override fun onParentReselected() { + presenter.onParentViewReselected() + } + + override fun onParentChangeSemester() { + presenter.onParentViewChangeSemester() + } + + override fun notifyParentDataLoaded(semesterId: Int) { + (parentFragment as? GradeFragment)?.onChildFragmentLoaded(semesterId) + } + + override fun notifyParentRefresh() { + (parentFragment as? GradeFragment)?.onChildRefresh() + } + + override fun onDestroyView() { + super.onDestroyView() + presenter.onDetachView() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsHeader.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsHeader.kt new file mode 100644 index 00000000..3b4ee8fb --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsHeader.kt @@ -0,0 +1,73 @@ +package io.github.wulkanowy.ui.modules.grade.details + +import android.view.View +import android.view.View.GONE +import android.view.View.VISIBLE +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.items.AbstractExpandableItem +import eu.davidea.flexibleadapter.items.IFlexible +import eu.davidea.viewholders.ExpandableViewHolder +import io.github.wulkanowy.R +import kotlinx.android.extensions.LayoutContainer +import kotlinx.android.synthetic.main.header_grade_details.* + +class GradeDetailsHeader( + private val subject: String, + private val number: String, + private val average: String, + var newGrades: Int) + : AbstractExpandableItem() { + + override fun getLayoutRes() = R.layout.header_grade_details + + override fun createViewHolder(view: View?, adapter: FlexibleAdapter>?): ViewHolder { + return ViewHolder(view, adapter) + } + + override fun bindViewHolder(adapter: FlexibleAdapter>?, holder: ViewHolder, + position: Int, payloads: MutableList?) { + holder.run { + gradeHeaderSubject.text = subject + gradeHeaderAverage.text = average + gradeHeaderNumber.text = number + gradeHeaderPredicted.visibility = GONE + gradeHeaderFinal.visibility = GONE + + gradeHeaderNote.visibility = if (newGrades > 0) VISIBLE else GONE + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as GradeDetailsHeader + + if (subject != other.subject) return false + if (number != other.number) return false + if (average != other.average) return false + + return true + } + + override fun hashCode(): Int { + var result = subject.hashCode() + result = 31 * result + number.hashCode() + result = 31 * result + average.hashCode() + return result + } + + + class ViewHolder(view: View?, adapter: FlexibleAdapter>?) : ExpandableViewHolder(view, adapter), + LayoutContainer { + + init { + contentView.setOnClickListener(this) + } + + override fun shouldNotifyParentOnClick() = true + + override val containerView: View + get() = contentView + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsItem.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsItem.kt new file mode 100644 index 00000000..18c2656d --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsItem.kt @@ -0,0 +1,68 @@ +package io.github.wulkanowy.ui.modules.grade.details + +import android.annotation.SuppressLint +import android.view.View +import android.view.View.GONE +import android.view.View.VISIBLE +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import eu.davidea.flexibleadapter.items.IFlexible +import eu.davidea.viewholders.FlexibleViewHolder +import io.github.wulkanowy.R +import io.github.wulkanowy.data.db.entities.Grade +import io.github.wulkanowy.utils.toFormattedString +import kotlinx.android.extensions.LayoutContainer +import kotlinx.android.synthetic.main.item_grade_details.* + +class GradeDetailsItem(val grade: Grade, private val weightString: String, private val valueColor: Int) + : AbstractFlexibleItem() { + + override fun getLayoutRes() = R.layout.item_grade_details + + override fun createViewHolder(view: View, adapter: FlexibleAdapter>): ViewHolder { + return ViewHolder(view, adapter) + } + + @SuppressLint("SetTextI18n") + override fun bindViewHolder(adapter: FlexibleAdapter>, holder: ViewHolder, + position: Int, payloads: MutableList?) { + holder.run { + gradeItemValue.run { + text = grade.entry + setBackgroundResource(valueColor) + } + gradeItemDescription.text = if (grade.description.isNotBlank()) grade.description else grade.gradeSymbol + gradeItemDate.text = grade.date.toFormattedString() + gradeItemWeight.text = "$weightString: ${grade.weight}" + gradeItemNote.visibility = if (!grade.isRead) VISIBLE else GONE + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as GradeDetailsItem + + if (grade != other.grade) return false + if (weightString != other.weightString) return false + if (valueColor != other.valueColor) return false + + return true + } + + override fun hashCode(): Int { + var result = grade.hashCode() + result = 31 * result + weightString.hashCode() + result = 31 * result + valueColor + return result + } + + + class ViewHolder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter), + LayoutContainer { + + override val containerView: View + get() = contentView + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsPresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsPresenter.kt new file mode 100644 index 00000000..46539aec --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsPresenter.kt @@ -0,0 +1,129 @@ +package io.github.wulkanowy.ui.modules.grade.details + +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import io.github.wulkanowy.data.ErrorHandler +import io.github.wulkanowy.data.db.entities.Grade +import io.github.wulkanowy.data.repositories.GradeRepository +import io.github.wulkanowy.data.repositories.SessionRepository +import io.github.wulkanowy.ui.base.BasePresenter +import io.github.wulkanowy.utils.SchedulersProvider +import io.github.wulkanowy.utils.calcAverage +import io.github.wulkanowy.utils.logEvent +import io.github.wulkanowy.utils.valueColor +import timber.log.Timber +import javax.inject.Inject + +class GradeDetailsPresenter @Inject constructor( + private val errorHandler: ErrorHandler, + private val schedulers: SchedulersProvider, + private val gradeRepository: GradeRepository, + private val sessionRepository: SessionRepository +) : BasePresenter(errorHandler) { + + override fun onAttachView(view: GradeDetailsView) { + super.onAttachView(view) + view.initView() + } + + fun onParentViewLoadData(semesterId: Int, forceRefresh: Boolean) { + disposable.add(sessionRepository.getSemesters() + .flatMap { gradeRepository.getGrades(it.first { item -> item.semesterId == semesterId }, forceRefresh) } + .map { createGradeItems(it.groupBy { grade -> grade.subject }.toSortedMap()) } + .subscribeOn(schedulers.backgroundThread) + .observeOn(schedulers.mainThread) + .doFinally { + view?.run { + showRefresh(false) + showProgress(false) + notifyParentDataLoaded(semesterId) + } + } + .subscribe({ + view?.run { + showEmpty(it.isEmpty()) + showContent(it.isNotEmpty()) + updateData(it) + } + logEvent("Grade details load", mapOf("items" to it.size, "forceRefresh" to forceRefresh)) + }) { + view?.run { showEmpty(isViewEmpty) } + errorHandler.proceed(it) + }) + } + + fun onGradeItemSelected(item: AbstractFlexibleItem<*>?) { + if (item is GradeDetailsItem) { + view?.apply { + showGradeDialog(item.grade) + if (!item.grade.isRead) { + item.grade.isRead = true + updateItem(item) + getHeaderOfItem(item)?.let { header -> + if (header is GradeDetailsHeader) { + header.newGrades-- + updateItem(header) + } + } + updateGrade(item.grade) + } + } + } + } + + fun onSwipeRefresh() { + view?.notifyParentRefresh() + } + + fun onParentViewReselected() { + view?.run { + if (!isViewEmpty) resetView() + } + } + + fun onParentViewChangeSemester() { + view?.run { + showProgress(true) + showRefresh(false) + showContent(false) + showEmpty(false) + clearView() + } + disposable.clear() + } + + private fun createGradeItems(items: Map>): List { + return items.map { + it.value.calcAverage().let { average -> + GradeDetailsHeader( + subject = it.key, + average = formatAverage(average), + number = view?.getGradeNumberString(it.value.size).orEmpty(), + newGrades = it.value.filter { grade -> !grade.isRead }.size + ).apply { + subItems = it.value.map { item -> + GradeDetailsItem( + grade = item, + weightString = view?.weightString.orEmpty(), + valueColor = item.valueColor + ) + } + } + } + } + } + + private fun formatAverage(average: Double): String { + return view?.run { + if (average == 0.0) emptyAverageString + else averageString.format(average) + }.orEmpty() + } + + private fun updateGrade(grade: Grade) { + disposable.add(gradeRepository.updateGrade(grade) + .subscribeOn(schedulers.backgroundThread) + .observeOn(schedulers.mainThread) + .subscribe({}) { error -> errorHandler.proceed(error) }) + Timber.d("Grade ${grade.id} updated") + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsView.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsView.kt new file mode 100644 index 00000000..2fb480b4 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/details/GradeDetailsView.kt @@ -0,0 +1,46 @@ +package io.github.wulkanowy.ui.modules.grade.details + +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import eu.davidea.flexibleadapter.items.IExpandable +import eu.davidea.flexibleadapter.items.IFlexible +import io.github.wulkanowy.data.db.entities.Grade +import io.github.wulkanowy.ui.base.BaseView + +interface GradeDetailsView : BaseView { + + val isViewEmpty: Boolean + + val emptyAverageString: String + + val averageString: String + + val weightString: String + + fun initView() + + fun updateData(data: List) + + fun updateItem(item: AbstractFlexibleItem<*>) + + fun resetView() + + fun clearView() + + fun showGradeDialog(grade: Grade) + + fun showContent(show: Boolean) + + fun showEmpty(show: Boolean) + + fun showProgress(show: Boolean) + + fun showRefresh(show: Boolean) + + fun notifyParentDataLoaded(semesterId: Int) + + fun notifyParentRefresh() + + fun getGradeNumberString(number: Int): String + + fun getHeaderOfItem(item: AbstractFlexibleItem<*>): IExpandable<*, out IFlexible<*>>? +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryFragment.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryFragment.kt new file mode 100644 index 00000000..76473b40 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryFragment.kt @@ -0,0 +1,115 @@ +package io.github.wulkanowy.ui.modules.grade.summary + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.View.* +import android.view.ViewGroup +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import io.github.wulkanowy.R +import io.github.wulkanowy.ui.base.BaseFragment +import io.github.wulkanowy.ui.modules.grade.GradeFragment +import io.github.wulkanowy.ui.modules.grade.GradeView +import kotlinx.android.synthetic.main.fragment_grade_summary.* +import javax.inject.Inject + +class GradeSummaryFragment : BaseFragment(), GradeSummaryView, GradeView.GradeChildView { + + @Inject + lateinit var presenter: GradeSummaryPresenter + + @Inject + lateinit var gradeSummaryAdapter: FlexibleAdapter> + + companion object { + fun newInstance() = GradeSummaryFragment() + } + + override val isViewEmpty + get() = gradeSummaryAdapter.isEmpty + + override val predictedString + get() = getString(R.string.grade_summary_predicted_grade) + + override val finalString + get() = getString(R.string.grade_summary_final_grade) + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_grade_summary, container, false) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + messageContainer = gradeSummaryRecycler + presenter.onAttachView(this) + } + + override fun initView() { + gradeSummaryAdapter.setDisplayHeadersAtStartUp(true) + + gradeSummaryRecycler.run { + layoutManager = SmoothScrollLinearLayoutManager(context) + adapter = gradeSummaryAdapter + } + gradeSummarySwipe.setOnRefreshListener { presenter.onSwipeRefresh() } + } + + override fun updateDataSet(data: List, header: GradeSummaryScrollableHeader) { + gradeSummaryAdapter.apply { + updateDataSet(data, true) + removeAllScrollableHeaders() + addScrollableHeader(header) + } + } + + override fun clearView() { + gradeSummaryAdapter.clear() + } + + override fun resetView() { + gradeSummaryAdapter.smoothScrollToPosition(0) + } + + override fun showContent(show: Boolean) { + gradeSummaryRecycler.visibility = if (show) VISIBLE else INVISIBLE + } + + override fun showEmpty(show: Boolean) { + gradeSummaryEmpty.visibility = if (show) VISIBLE else INVISIBLE + } + + override fun showProgress(show: Boolean) { + gradeSummaryProgress.visibility = if (show) VISIBLE else GONE + } + + override fun showRefresh(show: Boolean) { + gradeSummarySwipe.isRefreshing = show + } + + override fun onParentLoadData(semesterId: Int, forceRefresh: Boolean) { + presenter.onParentViewLoadData(semesterId, forceRefresh) + } + + override fun onParentReselected() { + presenter.onParentViewReselected() + } + + override fun onParentChangeSemester() { + presenter.onParentViewChangeSemester() + } + + override fun notifyParentDataLoaded(semesterId: Int) { + (parentFragment as? GradeFragment)?.onChildFragmentLoaded(semesterId) + } + + override fun notifyParentRefresh() { + (parentFragment as? GradeFragment)?.onChildRefresh() + } + + override fun onDestroyView() { + super.onDestroyView() + presenter.onDetachView() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryHeader.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryHeader.kt new file mode 100644 index 00000000..fba3fde6 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryHeader.kt @@ -0,0 +1,52 @@ +package io.github.wulkanowy.ui.modules.grade.summary + +import android.view.View +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.items.AbstractHeaderItem +import eu.davidea.flexibleadapter.items.IFlexible +import eu.davidea.viewholders.FlexibleViewHolder +import io.github.wulkanowy.R +import kotlinx.android.extensions.LayoutContainer +import kotlinx.android.synthetic.main.header_grade_summary.* + +class GradeSummaryHeader(private val name: String, private val average: String) : AbstractHeaderItem() { + + override fun getLayoutRes() = R.layout.header_grade_summary + + override fun createViewHolder(view: View?, adapter: FlexibleAdapter>?): ViewHolder { + return ViewHolder(view, adapter) + } + + override fun bindViewHolder(adapter: FlexibleAdapter>?, holder: ViewHolder?, + position: Int, payloads: MutableList?) { + holder?.run { + gradeSummaryHeaderName.text = name + gradeSummaryHeaderAverage.text = average + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as GradeSummaryHeader + + if (name != other.name) return false + if (average != other.average) return false + + return true + } + + override fun hashCode(): Int { + var result = name.hashCode() + result = 31 * result + average.hashCode() + return result + } + + class ViewHolder(view: View?, adapter: FlexibleAdapter>?) : + FlexibleViewHolder(view, adapter), LayoutContainer { + + override val containerView: View? + get() = contentView + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryItem.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryItem.kt new file mode 100644 index 00000000..98e5db92 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryItem.kt @@ -0,0 +1,56 @@ +package io.github.wulkanowy.ui.modules.grade.summary + +import android.view.View +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.items.AbstractSectionableItem +import eu.davidea.flexibleadapter.items.IFlexible +import eu.davidea.viewholders.FlexibleViewHolder +import io.github.wulkanowy.R +import kotlinx.android.extensions.LayoutContainer +import kotlinx.android.synthetic.main.item_grade_summary.* + +class GradeSummaryItem(header: GradeSummaryHeader, private val grade: String, private val title: String) + : AbstractSectionableItem(header) { + + override fun getLayoutRes() = R.layout.item_grade_summary + + override fun createViewHolder(view: View?, adapter: FlexibleAdapter>?): ViewHolder { + return ViewHolder(view, adapter) + } + + override fun bindViewHolder(adapter: FlexibleAdapter>?, holder: ViewHolder?, + position: Int, payloads: MutableList?) { + holder?.run { + gradeSummaryItemGrade.text = grade + gradeSummaryItemTitle.text = title + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as GradeSummaryItem + + if (grade != other.grade) return false + if (title != other.title) return false + if (header != other.header) return false + + return true + } + + override fun hashCode(): Int { + var result = header.hashCode() + result = 31 * result + grade.hashCode() + result = 31 * result + title.hashCode() + return result + } + + + class ViewHolder(view: View?, adapter: FlexibleAdapter>?) + : FlexibleViewHolder(view, adapter), LayoutContainer { + + override val containerView: View? + get() = contentView + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryPresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryPresenter.kt new file mode 100644 index 00000000..a6479e4d --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryPresenter.kt @@ -0,0 +1,123 @@ +package io.github.wulkanowy.ui.modules.grade.summary + +import io.github.wulkanowy.data.ErrorHandler +import io.github.wulkanowy.data.db.entities.GradeSummary +import io.github.wulkanowy.data.repositories.GradeRepository +import io.github.wulkanowy.data.repositories.GradeSummaryRepository +import io.github.wulkanowy.data.repositories.SessionRepository +import io.github.wulkanowy.ui.base.BasePresenter +import io.github.wulkanowy.utils.SchedulersProvider +import io.github.wulkanowy.utils.calcAverage +import io.github.wulkanowy.utils.logEvent +import java.lang.String.format +import java.util.Locale.FRANCE +import javax.inject.Inject + +class GradeSummaryPresenter @Inject constructor( + private val errorHandler: ErrorHandler, + private val gradeSummaryRepository: GradeSummaryRepository, + private val gradeRepository: GradeRepository, + private val sessionRepository: SessionRepository, + private val schedulers: SchedulersProvider +) : BasePresenter(errorHandler) { + + override fun onAttachView(view: GradeSummaryView) { + super.onAttachView(view) + view.initView() + } + + fun onParentViewLoadData(semesterId: Int, forceRefresh: Boolean) { + disposable.add(sessionRepository.getSemesters() + .map { semester -> semester.first { it.semesterId == semesterId } } + .flatMap { + gradeSummaryRepository.getGradesSummary(it, forceRefresh) + .flatMap { gradesSummary -> + gradeRepository.getGrades(it, forceRefresh) + .map { grades -> + grades.groupBy { grade -> grade.subject } + .mapValues { entry -> entry.value.calcAverage() } + .filterValues { value -> value != 0.0 } + .let { averages -> + createGradeSummaryItems(gradesSummary, averages) to + GradeSummaryScrollableHeader( + formatAverage(gradesSummary.calcAverage()), + formatAverage(averages.values.average()) + ) + } + } + } + } + .subscribeOn(schedulers.backgroundThread) + .observeOn(schedulers.mainThread) + .doFinally { + view?.run { + showRefresh(false) + showProgress(false) + notifyParentDataLoaded(semesterId) + } + }.subscribe({ + view?.run { + showEmpty(it.first.isEmpty()) + showContent(it.first.isNotEmpty()) + updateDataSet(it.first, it.second) + } + logEvent("Grade summary load", mapOf("items" to it.first.size, "forceRefresh" to forceRefresh)) + }) { + view?.run { showEmpty(isViewEmpty) } + errorHandler.proceed(it) + }) + } + + fun onSwipeRefresh() { + view?.notifyParentRefresh() + } + + fun onParentViewReselected() { + view?.run { + if (!isViewEmpty) resetView() + } + } + + fun onParentViewChangeSemester() { + view?.run { + showProgress(true) + showRefresh(false) + showContent(false) + showEmpty(false) + clearView() + } + disposable.clear() + } + + private fun createGradeSummaryItems(gradesSummary: List, averages: Map) + : List { + return gradesSummary.filter { !checkEmpty(it, averages) } + .flatMap { gradeSummary -> + GradeSummaryHeader( + name = gradeSummary.subject, + average = formatAverage(averages.getOrElse(gradeSummary.subject) { 0.0 }, "") + ).let { + listOf(GradeSummaryItem( + header = it, + title = view?.predictedString.orEmpty(), + grade = gradeSummary.predictedGrade + ), GradeSummaryItem( + header = it, + title = view?.finalString.orEmpty(), + grade = gradeSummary.finalGrade + )) + } + } + } + + private fun checkEmpty(gradeSummary: GradeSummary, averages: Map): Boolean { + return gradeSummary.run { + finalGrade.isBlank() && predictedGrade.isBlank() && averages[subject] == null + } + } + + private fun formatAverage(average: Double, defaultValue: String = "-- --"): String { + return if (average == 0.0) defaultValue + else format(FRANCE, "%.2f", average) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryScrollableHeader.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryScrollableHeader.kt new file mode 100644 index 00000000..f1c535c7 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryScrollableHeader.kt @@ -0,0 +1,53 @@ +package io.github.wulkanowy.ui.modules.grade.summary + +import android.view.View +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import eu.davidea.flexibleadapter.items.IFlexible +import eu.davidea.viewholders.FlexibleViewHolder +import io.github.wulkanowy.R +import kotlinx.android.extensions.LayoutContainer +import kotlinx.android.synthetic.main.scrollable_header_grade_summary.* + +class GradeSummaryScrollableHeader(private val finalAverage: String, private val calculatedAverage: String) + : AbstractFlexibleItem() { + + override fun getLayoutRes() = R.layout.scrollable_header_grade_summary + + override fun createViewHolder(view: View?, adapter: FlexibleAdapter>?): ViewHolder { + return ViewHolder(view, adapter) + } + + override fun bindViewHolder(adapter: FlexibleAdapter>?, holder: ViewHolder?, + position: Int, payloads: MutableList?) { + holder?.apply { + gradeSummaryScrollableHeaderFinal.text = finalAverage + gradeSummaryScrollableHeaderCalculated.text = calculatedAverage + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as GradeSummaryScrollableHeader + + if (calculatedAverage != other.calculatedAverage) return false + if (finalAverage != other.finalAverage) return false + + return true + } + + override fun hashCode(): Int { + var result = calculatedAverage.hashCode() + result = 31 * result + finalAverage.hashCode() + return result + } + + class ViewHolder(view: View?, adapter: FlexibleAdapter>?) : FlexibleViewHolder(view, adapter), + LayoutContainer { + + override val containerView: View? + get() = contentView + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryView.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryView.kt new file mode 100644 index 00000000..f7035abc --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/grade/summary/GradeSummaryView.kt @@ -0,0 +1,32 @@ +package io.github.wulkanowy.ui.modules.grade.summary + +import io.github.wulkanowy.ui.base.BaseView + +interface GradeSummaryView : BaseView { + + val isViewEmpty: Boolean + + val predictedString: String + + val finalString: String + + fun initView() + + fun updateDataSet(data: List, header: GradeSummaryScrollableHeader) + + fun resetView() + + fun clearView() + + fun showProgress(show: Boolean) + + fun showRefresh(show: Boolean) + + fun showContent(show: Boolean) + + fun showEmpty(show: Boolean) + + fun notifyParentDataLoaded(semesterId: Int) + + fun notifyParentRefresh() +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginActivity.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginActivity.kt new file mode 100644 index 00000000..c787e236 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginActivity.kt @@ -0,0 +1,73 @@ +package io.github.wulkanowy.ui.modules.login + +import android.content.Context +import android.content.Intent +import android.os.Bundle +import io.github.wulkanowy.R +import io.github.wulkanowy.ui.base.BaseActivity +import io.github.wulkanowy.ui.base.BasePagerAdapter +import io.github.wulkanowy.ui.modules.login.form.LoginFormFragment +import io.github.wulkanowy.ui.modules.login.options.LoginOptionsFragment +import io.github.wulkanowy.utils.setOnSelectPageListener +import kotlinx.android.synthetic.main.activity_login.* +import javax.inject.Inject + +class LoginActivity : BaseActivity(), LoginView, LoginSwitchListener { + + @Inject + lateinit var presenter: LoginPresenter + + @Inject + lateinit var loginAdapter: BasePagerAdapter + + companion object { + fun getStartIntent(context: Context) = Intent(context, LoginActivity::class.java) + } + + override val currentViewIndex: Int + get() = loginViewpager.currentItem + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_login) + messageContainer = loginContainer + + presenter.onAttachView(this) + } + + override fun onBackPressed() { + presenter.onBackPressed { super.onBackPressed() } + } + + override fun initAdapter() { + loginAdapter.fragments.putAll(mapOf( + "1" to LoginFormFragment.newInstance(), + "2" to LoginOptionsFragment.newInstance() + )) + loginViewpager.run { + adapter = loginAdapter + setOnSelectPageListener { presenter.onPageSelected(it) } + } + } + + override fun switchFragment(position: Int) { + presenter.onSwitchFragment(position) + } + + override fun switchView(position: Int) { + loginViewpager.setCurrentItem(position, false) + } + + override fun hideActionBar() { + supportActionBar?.hide() + } + + override fun loadOptionsView(index: Int) { + (loginAdapter.getItem(index) as LoginOptionsFragment).loadData() + } + + public override fun onDestroy() { + presenter.onDetachView() + super.onDestroy() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginErrorHandler.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginErrorHandler.kt new file mode 100644 index 00000000..418dbed9 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginErrorHandler.kt @@ -0,0 +1,22 @@ +package io.github.wulkanowy.ui.modules.login + +import android.content.res.Resources +import io.github.wulkanowy.api.login.BadCredentialsException +import io.github.wulkanowy.data.ErrorHandler + +class LoginErrorHandler(resources: Resources) : ErrorHandler(resources) { + + var doOnBadCredentials: () -> Unit = {} + + override fun proceed(error: Throwable) { + when (error) { + is BadCredentialsException -> doOnBadCredentials() + else -> super.proceed(error) + } + } + + override fun clear() { + super.clear() + doOnBadCredentials = {} + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginModule.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginModule.kt new file mode 100644 index 00000000..bbf71e22 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginModule.kt @@ -0,0 +1,37 @@ +package io.github.wulkanowy.ui.modules.login + +import android.content.Context +import dagger.Module +import dagger.Provides +import dagger.android.ContributesAndroidInjector +import io.github.wulkanowy.di.scopes.PerActivity +import io.github.wulkanowy.di.scopes.PerFragment +import io.github.wulkanowy.ui.base.BasePagerAdapter +import io.github.wulkanowy.ui.modules.login.form.LoginFormFragment +import io.github.wulkanowy.ui.modules.login.options.LoginOptionsFragment + +@Module +internal abstract class LoginModule { + + @Module + companion object { + + @JvmStatic + @PerActivity + @Provides + fun provideLoginAdapter(activity: LoginActivity) = BasePagerAdapter(activity.supportFragmentManager) + + @JvmStatic + @PerActivity + @Provides + fun provideLoginErrorHandler(context: Context) = LoginErrorHandler(context.resources) + } + + @PerFragment + @ContributesAndroidInjector() + abstract fun bindLoginFormFragment(): LoginFormFragment + + @PerFragment + @ContributesAndroidInjector() + abstract fun bindLoginOptionsFragment(): LoginOptionsFragment +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginPresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginPresenter.kt new file mode 100644 index 00000000..cbee0e82 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginPresenter.kt @@ -0,0 +1,34 @@ +package io.github.wulkanowy.ui.modules.login + +import io.github.wulkanowy.data.ErrorHandler +import io.github.wulkanowy.ui.base.BasePresenter +import javax.inject.Inject + +class LoginPresenter @Inject constructor(errorHandler: ErrorHandler) + : BasePresenter(errorHandler) { + + override fun onAttachView(view: LoginView) { + super.onAttachView(view) + view.run { + initAdapter() + hideActionBar() + } + } + + fun onPageSelected(index: Int) { + if (index == 1) view?.loadOptionsView(index) + } + + fun onSwitchFragment(position: Int) { + view?.switchView(position) + } + + fun onBackPressed(default: () -> Unit) { + view?.run { + if (currentViewIndex == 1) { + switchView(0) + hideActionBar() + } else default() + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginSwitchListener.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginSwitchListener.kt new file mode 100644 index 00000000..1e6d82c8 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginSwitchListener.kt @@ -0,0 +1,6 @@ +package io.github.wulkanowy.ui.modules.login + +interface LoginSwitchListener { + + fun switchFragment(position: Int) +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginView.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginView.kt new file mode 100644 index 00000000..cc9a04cc --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/login/LoginView.kt @@ -0,0 +1,16 @@ +package io.github.wulkanowy.ui.modules.login + +import io.github.wulkanowy.ui.base.BaseView + +interface LoginView : BaseView { + + val currentViewIndex: Int + + fun initAdapter() + + fun loadOptionsView(index: Int) + + fun switchView(position: Int) + + fun hideActionBar() +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/login/form/LoginFormFragment.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/login/form/LoginFormFragment.kt new file mode 100644 index 00000000..e6020342 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/login/form/LoginFormFragment.kt @@ -0,0 +1,144 @@ +package io.github.wulkanowy.ui.modules.login.form + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.View.GONE +import android.view.View.VISIBLE +import android.view.ViewGroup +import android.view.inputmethod.EditorInfo +import android.widget.ArrayAdapter +import io.github.wulkanowy.R +import io.github.wulkanowy.ui.base.BaseFragment +import io.github.wulkanowy.ui.modules.login.LoginSwitchListener +import io.github.wulkanowy.utils.hideSoftInput +import io.github.wulkanowy.utils.showSoftInput +import kotlinx.android.synthetic.main.fragment_login_form.* +import javax.inject.Inject + +class LoginFormFragment : BaseFragment(), LoginFormView { + + @Inject + lateinit var presenter: LoginFormPresenter + + companion object { + fun newInstance() = LoginFormFragment() + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_login_form, container, false) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + presenter.onAttachView(this) + } + + override fun initInputs() { + loginSignButton.setOnClickListener { + presenter.attemptLogin( + loginNicknameEdit.text.toString(), + loginPassEdit.text.toString(), + loginSymbolEdit.text.toString(), + resources.getStringArray(R.array.endpoints_values)[loginHostEdit.selectedItemPosition] + ) + } + + loginPassEdit.setOnEditorActionListener { _, id, _ -> onEditAction(id) } + + loginHostEdit.run { + adapter = ArrayAdapter.createFromResource(context, R.array.endpoints_keys, android.R.layout.simple_spinner_item).apply { + setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) + } + } + + loginSymbolEdit.run { + setAdapter(ArrayAdapter(context, android.R.layout.simple_list_item_1, resources.getStringArray(R.array.symbols_values))) + setOnEditorActionListener { _, id, _ -> onEditAction(id) } + } + } + + private fun onEditAction(actionId: Int): Boolean { + return when (actionId) { + EditorInfo.IME_ACTION_DONE, EditorInfo.IME_NULL -> loginSignButton.callOnClick() + else -> false + } + } + + override fun showSymbolInput() { + loginHeader.text = getString(R.string.login_header_symbol) + loginMainForm.visibility = GONE + loginSymbolInput.visibility = VISIBLE + loginSymbolEdit.requestFocus() + showSoftKeyboard() + } + + override fun switchNextView() { + (activity as LoginSwitchListener?)?.switchFragment(1) + } + + override fun setErrorNicknameRequired() { + loginNicknameEdit.run { + requestFocus() + error = getString(R.string.login_field_required) + } + } + + override fun setErrorPassRequired(focus: Boolean) { + loginPassEdit.run { + if (focus) requestFocus() + error = getString(R.string.login_field_required) + } + } + + override fun setErrorPassInvalid(focus: Boolean) { + loginPassEdit.run { + if (focus) requestFocus() + error = getString(R.string.login_invalid_password) + } + } + + override fun setErrorSymbolRequire() { + loginSymbolEdit.run { + requestFocus() + error = getString(R.string.login_field_required) + } + } + + override fun setErrorPassIncorrect() { + loginPassEdit.run { + requestFocus() + error = getString(R.string.login_incorrect_password) + } + } + + override fun setErrorSymbolIncorrect() { + loginSymbolEdit.run { + requestFocus() + error = getString(R.string.login_incorrect_symbol) + } + } + + override fun resetViewErrors() { + loginNicknameEdit.error = null + loginPassEdit.error = null + } + + override fun showSoftKeyboard() { + activity?.showSoftInput() + } + + override fun hideSoftKeyboard() { + activity?.hideSoftInput() + } + + override fun showLoginProgress(show: Boolean) { + loginFormContainer.visibility = if (show) GONE else VISIBLE + loginFormProgressContainer.visibility = if (show) VISIBLE else GONE + } + + override fun onDestroyView() { + super.onDestroyView() + presenter.onDetachView() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/login/form/LoginFormPresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/login/form/LoginFormPresenter.kt new file mode 100644 index 00000000..36912b2b --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/login/form/LoginFormPresenter.kt @@ -0,0 +1,87 @@ +package io.github.wulkanowy.ui.modules.login.form + +import io.github.wulkanowy.data.repositories.SessionRepository +import io.github.wulkanowy.ui.base.BasePresenter +import io.github.wulkanowy.ui.modules.login.LoginErrorHandler +import io.github.wulkanowy.utils.SchedulersProvider +import io.github.wulkanowy.utils.logEvent +import io.github.wulkanowy.utils.logRegister +import timber.log.Timber +import javax.inject.Inject + +class LoginFormPresenter @Inject constructor( + private val schedulers: SchedulersProvider, + private val errorHandler: LoginErrorHandler, + private val sessionRepository: SessionRepository +) : BasePresenter(errorHandler) { + + private var wasEmpty = false + + override fun onAttachView(view: LoginFormView) { + super.onAttachView(view) + view.initInputs() + } + + fun attemptLogin(email: String, password: String, symbol: String, endpoint: String) { + if (!validateCredentials(email, password, symbol)) return + disposable.add(sessionRepository.getConnectedStudents(email, password, symbol, endpoint) + .observeOn(schedulers.mainThread) + .subscribeOn(schedulers.backgroundThread) + .doOnSubscribe { + view?.run { + hideSoftKeyboard() + showLoginProgress(true) + errorHandler.doOnBadCredentials = { + setErrorPassIncorrect() + showSoftKeyboard() + Timber.i("Entered wrong username or password") + } + } + sessionRepository.clearCache() + } + .doFinally { view?.showLoginProgress(false) } + .subscribe({ + view?.run { + if (it.isEmpty() && !wasEmpty) { + showSymbolInput() + wasEmpty = true + } else if (it.isEmpty() && wasEmpty) { + showSymbolInput() + setErrorSymbolIncorrect() + logRegister("No student found", false, if (symbol.isEmpty()) "nil" else symbol, endpoint) + } else { + switchNextView() + logEvent("Found students", mapOf("students" to it.size, "symbol" to it.joinToString { student -> student.symbol }, "endpoint" to endpoint)) + } + } + }, { + errorHandler.proceed(it) + logRegister(it.localizedMessage, false, if (symbol.isEmpty()) "nil" else symbol, endpoint) + })) + } + + private fun validateCredentials(login: String, password: String, symbol: String): Boolean { + var isCorrect = true + + if (login.isEmpty()) { + view?.setErrorNicknameRequired() + isCorrect = false + } + + if (password.isEmpty()) { + view?.setErrorPassRequired(focus = isCorrect) + isCorrect = false + } + + if (symbol.isEmpty() && wasEmpty) { + view?.setErrorSymbolRequire() + isCorrect = false + } + + if (password.length < 6 && password.isNotEmpty()) { + view?.setErrorPassInvalid(focus = isCorrect) + isCorrect = false + } + return isCorrect + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/login/form/LoginFormView.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/login/form/LoginFormView.kt new file mode 100644 index 00000000..949d16b9 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/login/form/LoginFormView.kt @@ -0,0 +1,32 @@ +package io.github.wulkanowy.ui.modules.login.form + +import io.github.wulkanowy.ui.base.BaseView + +interface LoginFormView : BaseView { + + fun initInputs() + + fun setErrorNicknameRequired() + + fun setErrorPassRequired(focus: Boolean) + + fun setErrorSymbolRequire() + + fun setErrorPassInvalid(focus: Boolean) + + fun setErrorPassIncorrect() + + fun setErrorSymbolIncorrect() + + fun resetViewErrors() + + fun showSoftKeyboard() + + fun hideSoftKeyboard() + + fun showLoginProgress(show: Boolean) + + fun showSymbolInput() + + fun switchNextView() +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/login/options/LoginOptionsFragment.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/login/options/LoginOptionsFragment.kt new file mode 100644 index 00000000..ea1ccbed --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/login/options/LoginOptionsFragment.kt @@ -0,0 +1,85 @@ +package io.github.wulkanowy.ui.modules.login.options + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.View.GONE +import android.view.View.VISIBLE +import android.view.ViewGroup +import androidx.appcompat.app.AppCompatActivity +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import io.github.wulkanowy.R +import io.github.wulkanowy.ui.base.BaseFragment +import io.github.wulkanowy.ui.modules.main.MainActivity +import io.github.wulkanowy.utils.setOnItemClickListener +import kotlinx.android.synthetic.main.fragment_login_options.* +import javax.inject.Inject + +class LoginOptionsFragment : BaseFragment(), LoginOptionsView { + + @Inject + lateinit var presenter: LoginOptionsPresenter + + @Inject + lateinit var loginAdapter: FlexibleAdapter> + + companion object { + fun newInstance() = LoginOptionsFragment() + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_login_options, container, false) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + presenter.onAttachView(this) + } + + override fun initRecycler() { + loginAdapter.run { + setOnItemClickListener { position -> + (getItem(position) as? LoginOptionsItem)?.let { + presenter.onSelectStudent(it.student) + } + } + } + loginOptionsRecycler.run { + adapter = loginAdapter + layoutManager = SmoothScrollLinearLayoutManager(context) + } + } + + fun loadData() { + presenter.refreshData() + } + + override fun updateData(data: List) { + loginAdapter.run { + updateDataSet(data, true) + } + } + + override fun openMainView() { + activity?.let { + startActivity(MainActivity.getStartIntent(it)) + it.finish() + } + } + + override fun showLoginProgress(show: Boolean) { + loginOptionsProgressContainer.visibility = if (show) VISIBLE else GONE + loginOptionsRecycler.visibility = if (show) GONE else VISIBLE + } + + override fun showActionBar(show: Boolean) { + (activity as AppCompatActivity?)?.supportActionBar?.run { if (show) show() else hide() } + } + + override fun onDestroyView() { + super.onDestroyView() + presenter.onDetachView() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/login/options/LoginOptionsItem.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/login/options/LoginOptionsItem.kt new file mode 100644 index 00000000..2d4de475 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/login/options/LoginOptionsItem.kt @@ -0,0 +1,54 @@ +package io.github.wulkanowy.ui.modules.login.options + +import android.view.View +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import eu.davidea.flexibleadapter.items.IFlexible +import eu.davidea.viewholders.FlexibleViewHolder +import io.github.wulkanowy.R +import io.github.wulkanowy.data.db.entities.Student +import kotlinx.android.extensions.LayoutContainer +import kotlinx.android.synthetic.main.item_login_options.view.* + +class LoginOptionsItem(val student: Student) : AbstractFlexibleItem() { + + override fun getLayoutRes(): Int = R.layout.item_login_options + + override fun createViewHolder(view: View?, adapter: FlexibleAdapter>?): ItemViewHolder { + return ItemViewHolder(view, adapter) + } + + override fun bindViewHolder(adapter: FlexibleAdapter>?, holder: ItemViewHolder?, + position: Int, payloads: MutableList?) { + holder?.bind(student) + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as LoginOptionsItem + + if (student != other.student) return false + + return true + } + + override fun hashCode(): Int { + return student.hashCode() + } + + class ItemViewHolder(view: View?, adapter: FlexibleAdapter<*>?) + : FlexibleViewHolder(view, adapter), LayoutContainer { + + override val containerView: View? + get() = itemView + + fun bind(item: Student) { + itemView.run { + loginItemName.text = item.studentName + loginItemSchool.text = item.schoolName + } + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/login/options/LoginOptionsPresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/login/options/LoginOptionsPresenter.kt new file mode 100644 index 00000000..4a7bb38c --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/login/options/LoginOptionsPresenter.kt @@ -0,0 +1,50 @@ +package io.github.wulkanowy.ui.modules.login.options + +import io.github.wulkanowy.data.ErrorHandler +import io.github.wulkanowy.data.db.entities.Student +import io.github.wulkanowy.data.repositories.SessionRepository +import io.github.wulkanowy.ui.base.BasePresenter +import io.github.wulkanowy.utils.SchedulersProvider +import io.github.wulkanowy.utils.logRegister +import javax.inject.Inject + +class LoginOptionsPresenter @Inject constructor( + private val errorHandler: ErrorHandler, + private val repository: SessionRepository, + private val schedulers: SchedulersProvider +) : BasePresenter(errorHandler) { + + override fun onAttachView(view: LoginOptionsView) { + super.onAttachView(view) + view.initRecycler() + } + + fun refreshData() { + disposable.add(repository.cachedStudents + .observeOn(schedulers.mainThread) + .subscribeOn(schedulers.backgroundThread) + .doOnSubscribe { view?.showActionBar(true) } + .doFinally { repository.clearCache() } + .subscribe({ + view?.updateData(it.map { student -> + LoginOptionsItem(student) + }) + }, { errorHandler.proceed(it) })) + } + + fun onSelectStudent(student: Student) { + disposable.add(repository.saveStudent(student) + .subscribeOn(schedulers.backgroundThread) + .observeOn(schedulers.mainThread) + .doOnSubscribe { + view?.run { + showLoginProgress(true) + showActionBar(false) + } + } + .subscribe({ + logRegister("Success", true, student.symbol, student.endpoint) + view?.openMainView() + }, { errorHandler.proceed(it) })) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/login/options/LoginOptionsView.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/login/options/LoginOptionsView.kt new file mode 100644 index 00000000..306f8b31 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/login/options/LoginOptionsView.kt @@ -0,0 +1,16 @@ +package io.github.wulkanowy.ui.modules.login.options + +import io.github.wulkanowy.ui.base.BaseView + +interface LoginOptionsView : BaseView { + + fun updateData(data: List) + + fun initRecycler() + + fun openMainView() + + fun showLoginProgress(show: Boolean) + + fun showActionBar(show: Boolean) +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/main/MainActivity.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/main/MainActivity.kt new file mode 100644 index 00000000..704b9e7b --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/main/MainActivity.kt @@ -0,0 +1,148 @@ +package io.github.wulkanowy.ui.modules.main + +import android.content.Context +import android.content.Intent +import android.os.Bundle +import androidx.core.content.ContextCompat +import androidx.fragment.app.Fragment +import com.aurelhubert.ahbottomnavigation.AHBottomNavigation.TitleState.ALWAYS_SHOW +import com.aurelhubert.ahbottomnavigation.AHBottomNavigationItem +import com.ncapdevi.fragnav.FragNavController +import com.ncapdevi.fragnav.FragNavController.Companion.HIDE +import io.github.wulkanowy.R +import io.github.wulkanowy.services.notification.GradeNotification +import io.github.wulkanowy.ui.base.BaseActivity +import io.github.wulkanowy.ui.modules.attendance.AttendanceFragment +import io.github.wulkanowy.ui.modules.exam.ExamFragment +import io.github.wulkanowy.ui.modules.grade.GradeFragment +import io.github.wulkanowy.ui.modules.more.MoreFragment +import io.github.wulkanowy.ui.modules.timetable.TimetableFragment +import io.github.wulkanowy.utils.getThemeAttrColor +import io.github.wulkanowy.utils.logLogin +import io.github.wulkanowy.utils.safelyPopFragment +import io.github.wulkanowy.utils.setOnViewChangeListener +import kotlinx.android.synthetic.main.activity_main.* +import javax.inject.Inject + +class MainActivity : BaseActivity(), MainView { + + @Inject + lateinit var presenter: MainPresenter + + @Inject + lateinit var navController: FragNavController + + companion object { + const val EXTRA_START_MENU_INDEX = "extraStartMenuIndex" + + fun getStartIntent(context: Context) = Intent(context, MainActivity::class.java) + } + + override val isRootView: Boolean + get() = navController.isRootFragment + + override val currentViewTitle: String? + get() = (navController.currentFrag as? MainView.TitledView)?.titleStringId?.let { getString(it) } + + override val currentStackSize: Int? + get() = navController.currentStack?.size + + override var startMenuIndex = 0 + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + setSupportActionBar(mainToolbar) + messageContainer = mainFragmentContainer + + presenter.onAttachView(this, intent.getIntExtra(EXTRA_START_MENU_INDEX, -1)) + navController.initialize(startMenuIndex, savedInstanceState) + } + + override fun onStart() { + super.onStart() + presenter.onViewStart() + } + + override fun onSupportNavigateUp(): Boolean { + return presenter.onUpNavigate() + } + + override fun initView() { + mainBottomNav.run { + addItems( + mutableListOf( + AHBottomNavigationItem(R.string.grade_title, R.drawable.ic_menu_main_grade_26dp, 0), + AHBottomNavigationItem(R.string.attendance_title, R.drawable.ic_menu_main_attendance_24dp, 0), + AHBottomNavigationItem(R.string.exam_title, R.drawable.ic_menu_main_exam_24dp, 0), + AHBottomNavigationItem(R.string.timetable_title, R.drawable.ic_menu_main_timetable_24dp, 0), + AHBottomNavigationItem(R.string.more_title, R.drawable.ic_menu_main_more_24dp, 0) + ) + ) + accentColor = ContextCompat.getColor(context, R.color.colorPrimary) + inactiveColor = getThemeAttrColor(android.R.attr.textColorSecondary) + defaultBackgroundColor = getThemeAttrColor(R.attr.bottomNavBackground) + titleState = ALWAYS_SHOW + currentItem = startMenuIndex + isBehaviorTranslationEnabled = false + setTitleTextSizeInSp(10f, 10f) + setOnTabSelectedListener { position, wasSelected -> + presenter.onTabSelected(position, wasSelected) + } + } + + navController.run { + setOnViewChangeListener { presenter.onViewStart() } + fragmentHideStrategy = HIDE + rootFragments = listOf( + GradeFragment.newInstance(), + AttendanceFragment.newInstance(), + ExamFragment.newInstance(), + TimetableFragment.newInstance(), + MoreFragment.newInstance() + ) + } + } + + override fun switchMenuView(position: Int) { + navController.switchTab(position) + } + + override fun setViewTitle(title: String) { + supportActionBar?.title = title + } + + override fun showHomeArrow(show: Boolean) { + supportActionBar?.setDisplayHomeAsUpEnabled(show) + } + + override fun notifyMenuViewReselected() { + (navController.currentStack?.get(0) as? MainView.MainChildView)?.onFragmentReselected() + } + + fun pushView(fragment: Fragment) { + navController.pushFragment(fragment) + } + + override fun popView() { + navController.safelyPopFragment() + } + + override fun onBackPressed() { + presenter.onBackPressed { super.onBackPressed() } + } + + override fun cancelNotifications() { + GradeNotification(applicationContext).cancelAll() + } + + override fun onSaveInstanceState(outState: Bundle?) { + super.onSaveInstanceState(outState) + navController.onSaveInstanceState(outState) + } + + override fun onDestroy() { + super.onDestroy() + presenter.onDetachView() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/main/MainModule.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/main/MainModule.kt new file mode 100644 index 00000000..278c3f0b --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/main/MainModule.kt @@ -0,0 +1,60 @@ +package io.github.wulkanowy.ui.modules.main + +import com.ncapdevi.fragnav.FragNavController +import dagger.Module +import dagger.Provides +import dagger.android.ContributesAndroidInjector +import io.github.wulkanowy.R +import io.github.wulkanowy.di.scopes.PerActivity +import io.github.wulkanowy.di.scopes.PerFragment +import io.github.wulkanowy.ui.modules.about.AboutFragment +import io.github.wulkanowy.ui.modules.about.AboutModule +import io.github.wulkanowy.ui.modules.attendance.AttendanceFragment +import io.github.wulkanowy.ui.modules.exam.ExamFragment +import io.github.wulkanowy.ui.modules.grade.GradeFragment +import io.github.wulkanowy.ui.modules.grade.GradeModule +import io.github.wulkanowy.ui.modules.more.MoreFragment +import io.github.wulkanowy.ui.modules.settings.SettingsFragment +import io.github.wulkanowy.ui.modules.timetable.TimetableFragment + +@Module +abstract class MainModule { + + @Module + companion object { + + @JvmStatic + @PerActivity + @Provides + fun provideFragNavController(activity: MainActivity): FragNavController { + return FragNavController(activity.supportFragmentManager, R.id.mainFragmentContainer) + } + } + + @PerFragment + @ContributesAndroidInjector + abstract fun bindAttendanceFragment(): AttendanceFragment + + @PerFragment + @ContributesAndroidInjector + abstract fun bindExamFragment(): ExamFragment + + @PerFragment + @ContributesAndroidInjector(modules = [GradeModule::class]) + abstract fun bindGradeFragment(): GradeFragment + + @PerFragment + @ContributesAndroidInjector + abstract fun bindMoreFragment(): MoreFragment + + @PerFragment + @ContributesAndroidInjector + abstract fun bindTimetableFragment(): TimetableFragment + + @PerFragment + @ContributesAndroidInjector(modules = [AboutModule::class]) + abstract fun bindAboutFragment(): AboutFragment + + @ContributesAndroidInjector + abstract fun bindSettingsFragment(): SettingsFragment +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/main/MainPresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/main/MainPresenter.kt new file mode 100644 index 00000000..03dce3f2 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/main/MainPresenter.kt @@ -0,0 +1,66 @@ +package io.github.wulkanowy.ui.modules.main + +import io.github.wulkanowy.data.ErrorHandler +import io.github.wulkanowy.data.repositories.PreferencesRepository +import io.github.wulkanowy.services.job.ServiceHelper +import io.github.wulkanowy.ui.base.BasePresenter +import io.github.wulkanowy.utils.logLogin +import javax.inject.Inject + +class MainPresenter @Inject constructor( + errorHandler: ErrorHandler, + private val prefRepository: PreferencesRepository, + private val serviceHelper: ServiceHelper +) : BasePresenter(errorHandler) { + + fun onAttachView(view: MainView, initMenuIndex: Int) { + super.onAttachView(view) + + view.run { + cancelNotifications() + startMenuIndex = if (initMenuIndex != -1) initMenuIndex else prefRepository.startMenuIndex + initView() + } + + when (initMenuIndex) { + 1 -> logLogin("Grades") + 3 -> logLogin("Timetable") + } + + serviceHelper.startFullSyncService() + } + + fun onViewStart() { + view?.apply { + currentViewTitle?.let { setViewTitle(it) } + currentStackSize?.let { + if (it > 1) showHomeArrow(true) + else showHomeArrow(false) + } + } + } + + fun onUpNavigate(): Boolean { + view?.popView() + return true + } + + fun onBackPressed(default: () -> Unit) { + view?.run { + if (isRootView) default() + else popView() + } + } + + fun onTabSelected(index: Int, wasSelected: Boolean): Boolean { + return view?.run { + if (wasSelected) { + notifyMenuViewReselected() + false + } else { + switchMenuView(index) + true + } + } == true + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/main/MainView.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/main/MainView.kt new file mode 100644 index 00000000..8848f2f0 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/main/MainView.kt @@ -0,0 +1,38 @@ +package io.github.wulkanowy.ui.modules.main + +import io.github.wulkanowy.ui.base.BaseView + +interface MainView : BaseView { + + var startMenuIndex: Int + + val isRootView: Boolean + + val currentViewTitle: String? + + val currentStackSize: Int? + + fun initView() + + fun switchMenuView(position: Int) + + fun showHomeArrow(show: Boolean) + + fun notifyMenuViewReselected() + + fun setViewTitle(title: String) + + fun popView() + + fun cancelNotifications() + + interface MainChildView { + + fun onFragmentReselected() + } + + interface TitledView { + + val titleStringId: Int + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/more/MoreFragment.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/more/MoreFragment.kt new file mode 100644 index 00000000..8bb9b0e3 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/more/MoreFragment.kt @@ -0,0 +1,95 @@ +package io.github.wulkanowy.ui.modules.more + +import android.graphics.drawable.Drawable +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.core.content.ContextCompat +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import io.github.wulkanowy.R +import io.github.wulkanowy.ui.base.BaseFragment +import io.github.wulkanowy.ui.modules.about.AboutFragment +import io.github.wulkanowy.ui.modules.main.MainActivity +import io.github.wulkanowy.ui.modules.main.MainView +import io.github.wulkanowy.ui.modules.settings.SettingsFragment +import io.github.wulkanowy.utils.setOnItemClickListener +import kotlinx.android.synthetic.main.fragment_more.* +import javax.inject.Inject + +class MoreFragment : BaseFragment(), MoreView, MainView.TitledView, MainView.MainChildView { + + @Inject + lateinit var presenter: MorePresenter + + @Inject + lateinit var moreAdapter: FlexibleAdapter> + + companion object { + fun newInstance() = MoreFragment() + } + + override val titleStringId: Int + get() = R.string.more_title + + override val settingsRes: Pair? + get() { + return context?.run { + getString(R.string.settings_title) to + ContextCompat.getDrawable(this, R.drawable.ic_more_settings_24dp) + } + } + + override val aboutRes: Pair? + get() { + return context?.run { + getString(R.string.about_title) to + ContextCompat.getDrawable(this, R.drawable.ic_more_about_24dp) + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_more, container, false) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + presenter.onAttachView(this) + } + + override fun initView() { + moreAdapter.run { setOnItemClickListener { presenter.onItemSelected(getItem(it)) } } + + moreRecycler.apply { + layoutManager = SmoothScrollLinearLayoutManager(context) + adapter = moreAdapter + } + } + + override fun onFragmentReselected() { + presenter.onViewReselected() + } + + override fun updateData(data: List) { + moreAdapter.updateDataSet(data) + } + + override fun openSettingsView() { + (activity as? MainActivity)?.pushView(SettingsFragment.newInstance()) + } + + override fun openAboutView() { + (activity as? MainActivity)?.pushView(AboutFragment.newInstance()) + } + + override fun popView() { + (activity as? MainActivity)?.popView() + } + + override fun onDestroyView() { + presenter.onDetachView() + super.onDestroyView() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/more/MoreItem.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/more/MoreItem.kt new file mode 100644 index 00000000..20bad835 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/more/MoreItem.kt @@ -0,0 +1,51 @@ +package io.github.wulkanowy.ui.modules.more + +import android.graphics.drawable.Drawable +import android.view.View +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import eu.davidea.flexibleadapter.items.IFlexible +import eu.davidea.viewholders.FlexibleViewHolder +import io.github.wulkanowy.R +import kotlinx.android.extensions.LayoutContainer +import kotlinx.android.synthetic.main.item_more.* + +class MoreItem(val title: String, private val drawable: Drawable?) + : AbstractFlexibleItem() { + + override fun getLayoutRes() = R.layout.item_more + + override fun createViewHolder(view: View?, adapter: FlexibleAdapter>?): ViewHolder { + return ViewHolder(view, adapter) + } + + override fun bindViewHolder(adapter: FlexibleAdapter>?, holder: ViewHolder?, + position: Int, payloads: MutableList?) { + holder?.apply { + moreItemTitle.text = title + moreItemImage.setImageDrawable(drawable) + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as MoreItem + + if (title != other.title) return false + + return true + } + + override fun hashCode(): Int { + return title.hashCode() + } + + class ViewHolder(view: View?, adapter: FlexibleAdapter<*>?) + : FlexibleViewHolder(view, adapter), LayoutContainer { + + override val containerView: View? + get() = contentView + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/more/MorePresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/more/MorePresenter.kt new file mode 100644 index 00000000..8da65f64 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/more/MorePresenter.kt @@ -0,0 +1,39 @@ +package io.github.wulkanowy.ui.modules.more + +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import io.github.wulkanowy.data.ErrorHandler +import io.github.wulkanowy.ui.base.BasePresenter +import javax.inject.Inject + +class MorePresenter @Inject constructor(errorHandler: ErrorHandler) + : BasePresenter(errorHandler) { + + override fun onAttachView(view: MoreView) { + super.onAttachView(view) + view.initView() + loadData() + } + + fun onItemSelected(item: AbstractFlexibleItem<*>?) { + if (item is MoreItem) { + view?.run { + when (item.title) { + settingsRes?.first -> openSettingsView() + aboutRes?.first -> openAboutView() + } + } + } + } + + fun onViewReselected() { + view?.popView() + } + + private fun loadData() { + view?.run { + updateData(listOfNotNull( + settingsRes?.let { MoreItem(it.first, it.second) }, + aboutRes?.let { MoreItem(it.first, it.second) })) + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/more/MoreView.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/more/MoreView.kt new file mode 100644 index 00000000..273c6b03 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/more/MoreView.kt @@ -0,0 +1,21 @@ +package io.github.wulkanowy.ui.modules.more + +import android.graphics.drawable.Drawable +import io.github.wulkanowy.ui.base.BaseView + +interface MoreView : BaseView { + + val settingsRes: Pair? + + val aboutRes: Pair? + + fun initView() + + fun updateData(data: List) + + fun openSettingsView() + + fun openAboutView() + + fun popView() +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/settings/SettingsFragment.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/settings/SettingsFragment.kt new file mode 100644 index 00000000..7a24a10d --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/settings/SettingsFragment.kt @@ -0,0 +1,70 @@ +package io.github.wulkanowy.ui.modules.settings + +import android.content.Context +import android.content.SharedPreferences +import android.os.Bundle +import android.widget.Toast +import androidx.appcompat.app.AppCompatDelegate +import com.takisoft.preferencex.PreferenceFragmentCompat +import dagger.android.support.AndroidSupportInjection +import io.github.wulkanowy.R +import io.github.wulkanowy.ui.modules.main.MainView +import javax.inject.Inject + +class SettingsFragment : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener, + MainView.TitledView, SettingsView { + + @Inject + lateinit var presenter: SettingsPresenter + + companion object { + fun newInstance() = SettingsFragment() + } + + override val titleStringId: Int + get() = R.string.settings_title + + override fun onAttach(context: Context) { + AndroidSupportInjection.inject(this) + super.onAttach(context) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + presenter.onAttachView(this) + } + + override fun onCreatePreferencesFix(savedInstanceState: Bundle?, rootKey: String?) { + addPreferencesFromResource(R.xml.scheme_preferences) + } + + override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { + presenter.onSharedPreferenceChanged(key) + } + + override fun setTheme(theme: Int) { + AppCompatDelegate.setDefaultNightMode(theme) + activity?.recreate() + } + + override fun setServicesSuspended(serviceEnablesKey: String, isHolidays: Boolean) { + findPreference(serviceEnablesKey).run { + summary = if (isHolidays) getString(R.string.pref_services_suspended) else "" + isEnabled = !isHolidays + } + } + + override fun showMessage(text: String) { + Toast.makeText(context, text, Toast.LENGTH_SHORT).show() + } + + override fun onResume() { + super.onResume() + preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this) + } + + override fun onPause() { + super.onPause() + preferenceScreen.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/settings/SettingsPresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/settings/SettingsPresenter.kt new file mode 100644 index 00000000..25e48f87 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/settings/SettingsPresenter.kt @@ -0,0 +1,43 @@ +package io.github.wulkanowy.ui.modules.settings + +import io.github.wulkanowy.data.ErrorHandler +import io.github.wulkanowy.data.repositories.PreferencesRepository +import io.github.wulkanowy.services.job.ServiceHelper +import io.github.wulkanowy.ui.base.BasePresenter +import io.github.wulkanowy.utils.isHolidays +import io.github.wulkanowy.utils.logEvent +import org.threeten.bp.LocalDate.now +import javax.inject.Inject + +class SettingsPresenter @Inject constructor( + errorHandler: ErrorHandler, + private val preferencesRepository: PreferencesRepository, + private val serviceHelper: ServiceHelper +) : BasePresenter(errorHandler) { + + override fun onAttachView(view: SettingsView) { + super.onAttachView(view) + + view.run { + setServicesSuspended(preferencesRepository.serviceEnablesKey, now().isHolidays) + } + } + + fun onSharedPreferenceChanged(key: String) { + when (key) { + preferencesRepository.serviceEnablesKey -> { + if (preferencesRepository.serviceEnabled) serviceHelper.startFullSyncService() + else serviceHelper.stopFullSyncService() + } + preferencesRepository.servicesIntervalKey, + preferencesRepository.servicesOnlyWifiKey -> { + serviceHelper.reloadFullSyncService() + } + preferencesRepository.currentThemeKey -> { + view?.setTheme(preferencesRepository.currentTheme) + } + } + + logEvent("Setting changed", mapOf("name" to key)) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/settings/SettingsView.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/settings/SettingsView.kt new file mode 100644 index 00000000..0b3c2f70 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/settings/SettingsView.kt @@ -0,0 +1,10 @@ +package io.github.wulkanowy.ui.modules.settings + +import io.github.wulkanowy.ui.base.BaseView + +interface SettingsView : BaseView { + + fun setTheme(theme: Int) + + fun setServicesSuspended(serviceEnablesKey: String, isHolidays: Boolean) +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/splash/SplashActivity.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/splash/SplashActivity.kt new file mode 100644 index 00000000..0b6e86bb --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/splash/SplashActivity.kt @@ -0,0 +1,39 @@ +package io.github.wulkanowy.ui.modules.splash + +import android.os.Bundle +import io.github.wulkanowy.services.notification.GradeNotification +import io.github.wulkanowy.ui.base.BaseActivity +import io.github.wulkanowy.ui.modules.login.LoginActivity +import io.github.wulkanowy.ui.modules.main.MainActivity +import javax.inject.Inject +import androidx.appcompat.app.AppCompatDelegate + +class SplashActivity : BaseActivity(), SplashView { + + @Inject + lateinit var presenter: SplashPresenter + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + presenter.onAttachView(this) + } + + override fun openLoginView() { + startActivity(LoginActivity.getStartIntent(this)) + finish() + } + + override fun openMainView() { + startActivity(MainActivity.getStartIntent(this)) + finish() + } + + override fun setCurrentThemeMode(mode: Int) { + AppCompatDelegate.setDefaultNightMode(mode) + } + + override fun onDestroy() { + presenter.onDetachView() + super.onDestroy() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/splash/SplashPresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/splash/SplashPresenter.kt new file mode 100644 index 00000000..d9dd9b9e --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/splash/SplashPresenter.kt @@ -0,0 +1,26 @@ +package io.github.wulkanowy.ui.modules.splash + +import io.github.wulkanowy.data.ErrorHandler +import io.github.wulkanowy.data.repositories.PreferencesRepository +import io.github.wulkanowy.data.repositories.SessionRepository +import io.github.wulkanowy.ui.base.BasePresenter +import io.github.wulkanowy.utils.logLogin +import javax.inject.Inject + +class SplashPresenter @Inject constructor( + private val sessionRepository: SessionRepository, + private val preferencesRepository: PreferencesRepository, + errorHandler: ErrorHandler +) : BasePresenter(errorHandler) { + + override fun onAttachView(view: SplashView) { + super.onAttachView(view) + view.run { + setCurrentThemeMode(preferencesRepository.currentTheme) + if (sessionRepository.isSessionSaved) { + logLogin("Open app") + openMainView() + } else openLoginView() + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/splash/SplashView.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/splash/SplashView.kt new file mode 100644 index 00000000..0a68c4e4 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/splash/SplashView.kt @@ -0,0 +1,12 @@ +package io.github.wulkanowy.ui.modules.splash + +import io.github.wulkanowy.ui.base.BaseView + +interface SplashView : BaseView { + + fun openLoginView() + + fun openMainView() + + fun setCurrentThemeMode(mode: Int) +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetableDialog.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetableDialog.kt new file mode 100644 index 00000000..743f37e5 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetableDialog.kt @@ -0,0 +1,78 @@ +package io.github.wulkanowy.ui.modules.timetable + +import android.annotation.SuppressLint +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.View.GONE +import android.view.ViewGroup +import androidx.fragment.app.DialogFragment +import io.github.wulkanowy.R +import io.github.wulkanowy.data.db.entities.Timetable +import io.github.wulkanowy.utils.toFormattedString +import kotlinx.android.synthetic.main.dialog_timetable.* + +class TimetableDialog : DialogFragment() { + + private lateinit var lesson: Timetable + + companion object { + private const val ARGUMENT_KEY = "Item" + + fun newInstance(exam: Timetable): TimetableDialog { + return TimetableDialog().apply { + arguments = Bundle().apply { putSerializable(ARGUMENT_KEY, exam) } + } + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setStyle(STYLE_NO_TITLE, 0) + arguments?.run { + lesson = getSerializable(ARGUMENT_KEY) as Timetable + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.dialog_timetable, container, false) + } + + @SuppressLint("SetTextI18n") + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + + timetableDialogSubject.text = lesson.subject + timetableDialogTime.text = "${lesson.start.toFormattedString("HH:mm")} - ${lesson.end.toFormattedString("HH:mm")}" + + lesson.group.let { + if (it.isBlank()) { + timetableDialogGroupTitle.visibility = GONE + timetableDialogGroup.visibility = GONE + } else timetableDialogGroup.text = it + } + + lesson.room.let { + if (it.isBlank()) { + timetableDialogRoomTitle.visibility = GONE + timetableDialogRoom.visibility = GONE + } else timetableDialogRoom.text = it + } + + lesson.teacher.let { + if (it.isBlank()) { + timetableDialogTeacherTitle.visibility = GONE + timetableDialogTeacher.visibility = GONE + } else timetableDialogTeacher.text = it + } + + lesson.info.let { + if (it.isBlank()) { + timetableDialogChangesTitle.visibility = GONE + timetableDialogChanges.visibility = GONE + } else timetableDialogChanges.text = it + } + + timetableDialogClose.setOnClickListener { dismiss() } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetableFragment.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetableFragment.kt new file mode 100644 index 00000000..dbd0ac3f --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetableFragment.kt @@ -0,0 +1,117 @@ +package io.github.wulkanowy.ui.modules.timetable + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import io.github.wulkanowy.R +import io.github.wulkanowy.data.db.entities.Timetable +import io.github.wulkanowy.ui.base.BaseFragment +import io.github.wulkanowy.ui.modules.main.MainView +import io.github.wulkanowy.utils.setOnItemClickListener +import kotlinx.android.synthetic.main.fragment_timetable.* +import javax.inject.Inject + +class TimetableFragment : BaseFragment(), TimetableView, MainView.MainChildView, MainView.TitledView { + + @Inject + lateinit var presenter: TimetablePresenter + + @Inject + lateinit var timetableAdapter: FlexibleAdapter> + + companion object { + private const val SAVED_DATE_KEY = "CURRENT_DATE" + + fun newInstance() = TimetableFragment() + } + + override val titleStringId: Int + get() = R.string.timetable_title + + override val roomString: String + get() = getString(R.string.timetable_room) + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_timetable, container, false) + } + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + messageContainer = timetableRecycler + presenter.onAttachView(this, savedInstanceState?.getLong(SAVED_DATE_KEY)) + } + + override fun initView() { + timetableAdapter.run { + setOnItemClickListener { presenter.onTimetableItemSelected(getItem(it)) } + } + + timetableRecycler.run { + layoutManager = SmoothScrollLinearLayoutManager(context) + adapter = timetableAdapter + } + timetableSwipe.setOnRefreshListener { presenter.onSwipeRefresh() } + timetablePreviousButton.setOnClickListener { presenter.onPreviousDay() } + timetableNextButton.setOnClickListener { presenter.onNextDay() } + } + + override fun updateData(data: List) { + timetableAdapter.updateDataSet(data, true) + } + + override fun clearData() { + timetableAdapter.clear() + } + + override fun updateNavigationDay(date: String) { + timetableNavDate.text = date + } + + override fun isViewEmpty() = timetableAdapter.isEmpty + + override fun hideRefresh() { + timetableSwipe.isRefreshing = false + } + + override fun onFragmentReselected() { + presenter.onViewReselected() + } + + override fun showEmpty(show: Boolean) { + timetableEmpty.visibility = if (show) View.VISIBLE else View.GONE + } + + override fun showProgress(show: Boolean) { + timetableProgress.visibility = if (show) View.VISIBLE else View.GONE + } + + override fun showContent(show: Boolean) { + timetableRecycler.visibility = if (show) View.VISIBLE else View.GONE + } + + override fun showPreButton(show: Boolean) { + timetablePreviousButton.visibility = if (show) View.VISIBLE else View.INVISIBLE + } + + override fun showNextButton(show: Boolean) { + timetableNextButton.visibility = if (show) View.VISIBLE else View.INVISIBLE + } + + override fun showTimetableDialog(lesson: Timetable) { + TimetableDialog.newInstance(lesson).show(fragmentManager, lesson.toString()) + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putLong(SAVED_DATE_KEY, presenter.currentDate.toEpochDay()) + } + + override fun onDestroyView() { + presenter.onDetachView() + super.onDestroyView() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetableItem.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetableItem.kt new file mode 100644 index 00000000..f37c0f51 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetableItem.kt @@ -0,0 +1,62 @@ +package io.github.wulkanowy.ui.modules.timetable + +import android.annotation.SuppressLint +import android.graphics.Paint +import android.view.View +import android.view.View.GONE +import android.view.View.VISIBLE +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import eu.davidea.flexibleadapter.items.IFlexible +import eu.davidea.viewholders.FlexibleViewHolder +import io.github.wulkanowy.R +import io.github.wulkanowy.data.db.entities.Timetable +import io.github.wulkanowy.utils.toFormattedString +import kotlinx.android.extensions.LayoutContainer +import kotlinx.android.synthetic.main.item_timetable.* + +class TimetableItem(val lesson: Timetable, private val roomText: String) + : AbstractFlexibleItem() { + + override fun getLayoutRes(): Int = R.layout.item_timetable + + override fun createViewHolder(view: View, adapter: FlexibleAdapter>): ViewHolder { + return ViewHolder(view, adapter) + } + + @SuppressLint("SetTextI18n") + override fun bindViewHolder(adapter: FlexibleAdapter>, holder: ViewHolder, + position: Int, payloads: MutableList?) { + holder.apply { + timetableItemNumber.text = lesson.number.toString() + timetableItemSubject.text = lesson.subject + timetableItemRoom.text = if (lesson.room.isNotBlank()) "$roomText ${lesson.room}" else "" + timetableItemTime.text = "${lesson.start.toFormattedString("HH:mm")} - ${lesson.end.toFormattedString("HH:mm")}" + timetableItemAlert.visibility = if (lesson.changes || lesson.canceled) VISIBLE else GONE + timetableItemSubject.paintFlags = + if (lesson.canceled) timetableItemSubject.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG + else timetableItemSubject.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as TimetableItem + + if (lesson != other.lesson) return false + return true + } + + override fun hashCode(): Int { + return lesson.hashCode() + } + + class ViewHolder(val view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter), + LayoutContainer { + + override val containerView: View + get() = contentView + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetablePresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetablePresenter.kt new file mode 100644 index 00000000..1a0eae83 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetablePresenter.kt @@ -0,0 +1,106 @@ +package io.github.wulkanowy.ui.modules.timetable + +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem +import io.github.wulkanowy.data.ErrorHandler +import io.github.wulkanowy.data.repositories.SessionRepository +import io.github.wulkanowy.data.repositories.TimetableRepository +import io.github.wulkanowy.ui.base.BasePresenter +import io.github.wulkanowy.utils.SchedulersProvider +import io.github.wulkanowy.utils.isHolidays +import io.github.wulkanowy.utils.logEvent +import io.github.wulkanowy.utils.nextOrSameSchoolDay +import io.github.wulkanowy.utils.nextSchoolDay +import io.github.wulkanowy.utils.previousSchoolDay +import io.github.wulkanowy.utils.toFormattedString +import org.threeten.bp.LocalDate +import org.threeten.bp.LocalDate.now +import org.threeten.bp.LocalDate.ofEpochDay +import java.util.concurrent.TimeUnit.MILLISECONDS +import javax.inject.Inject + +class TimetablePresenter @Inject constructor( + private val errorHandler: ErrorHandler, + private val schedulers: SchedulersProvider, + private val timetableRepository: TimetableRepository, + private val sessionRepository: SessionRepository +) : BasePresenter(errorHandler) { + + lateinit var currentDate: LocalDate + private set + + fun onAttachView(view: TimetableView, date: Long?) { + super.onAttachView(view) + view.initView() + loadData(ofEpochDay(date ?: now().nextOrSameSchoolDay.toEpochDay())) + reloadView() + } + + fun onPreviousDay() { + loadData(currentDate.previousSchoolDay) + reloadView() + logEvent("Timetable day changed", mapOf("button" to "prev", "date" to currentDate.toFormattedString())) + } + + fun onNextDay() { + loadData(currentDate.nextSchoolDay) + reloadView() + logEvent("Timetable day changed", mapOf("button" to "next", "date" to currentDate.toFormattedString())) + } + + fun onSwipeRefresh() { + loadData(currentDate, true) + } + + fun onViewReselected() { + loadData(now().nextOrSameSchoolDay) + reloadView() + } + + fun onTimetableItemSelected(item: AbstractFlexibleItem<*>?) { + if (item is TimetableItem) view?.showTimetableDialog(item.lesson) + } + + private fun loadData(date: LocalDate, forceRefresh: Boolean = false) { + currentDate = date + disposable.apply { + clear() + add(sessionRepository.getSemesters() + .delay(200, MILLISECONDS) + .map { it.single { semester -> semester.current } } + .flatMap { timetableRepository.getTimetable(it, currentDate, currentDate, forceRefresh) } + .map { items -> items.map { TimetableItem(it, view?.roomString.orEmpty()) } } + .map { items -> items.sortedBy { it.lesson.number } } + .subscribeOn(schedulers.backgroundThread) + .observeOn(schedulers.mainThread) + .doFinally { + view?.run { + hideRefresh() + showProgress(false) + } + } + .subscribe({ + view?.apply { + updateData(it) + showEmpty(it.isEmpty()) + showContent(it.isNotEmpty()) + } + logEvent("Timetable load", mapOf("items" to it.size, "forceRefresh" to forceRefresh, "date" to currentDate.toFormattedString())) + }) { + view?.run { showEmpty(isViewEmpty()) } + errorHandler.proceed(it) + }) + } + } + + private fun reloadView() { + view?.apply { + showProgress(true) + showContent(false) + showEmpty(false) + clearData() + showNextButton(!currentDate.plusDays(1).isHolidays) + showPreButton(!currentDate.minusDays(1).isHolidays) + updateNavigationDay(currentDate.toFormattedString("EEEE \n dd.MM.YYYY").capitalize()) + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetableView.kt b/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetableView.kt new file mode 100644 index 00000000..63ece69f --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetableView.kt @@ -0,0 +1,33 @@ +package io.github.wulkanowy.ui.modules.timetable + +import io.github.wulkanowy.data.db.entities.Timetable +import io.github.wulkanowy.ui.base.BaseView + +interface TimetableView : BaseView { + + val roomString: String + + fun initView() + + fun updateData(data: List) + + fun updateNavigationDay(date: String) + + fun isViewEmpty(): Boolean + + fun clearData() + + fun hideRefresh() + + fun showEmpty(show: Boolean) + + fun showProgress(show: Boolean) + + fun showContent(show: Boolean) + + fun showPreButton(show: Boolean) + + fun showNextButton(show: Boolean) + + fun showTimetableDialog(lesson: Timetable) +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/splash/SplashActivity.java b/app/src/main/java/io/github/wulkanowy/ui/splash/SplashActivity.java deleted file mode 100644 index 21ce8ba5..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/splash/SplashActivity.java +++ /dev/null @@ -1,50 +0,0 @@ -package io.github.wulkanowy.ui.splash; - -import android.os.Bundle; -import android.support.v7.app.AppCompatDelegate; - -import javax.inject.Inject; - -import io.github.wulkanowy.services.notifies.NotificationService; -import io.github.wulkanowy.ui.base.BaseActivity; -import io.github.wulkanowy.ui.login.LoginActivity; -import io.github.wulkanowy.ui.main.MainActivity; - -public class SplashActivity extends BaseActivity implements SplashContract.View { - - @Inject - SplashContract.Presenter presenter; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - presenter.attachView(this); - } - - @Override - protected void onDestroy() { - presenter.detachView(); - super.onDestroy(); - } - - @Override - public void openLoginActivity() { - startActivity(LoginActivity.getStartIntent(this)); - finish(); - } - - @Override - public void openMainActivity() { - startActivity(MainActivity.getStartIntent(this)); - finish(); - } - - public void setCurrentThemeMode(int mode) { - AppCompatDelegate.setDefaultNightMode(mode); - } - - @Override - public void cancelNotifications() { - new NotificationService(getApplicationContext()).cancelAll(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/splash/SplashContract.java b/app/src/main/java/io/github/wulkanowy/ui/splash/SplashContract.java deleted file mode 100644 index a1c5ad72..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/splash/SplashContract.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.github.wulkanowy.ui.splash; - -import io.github.wulkanowy.ui.base.BaseContract; - -public interface SplashContract { - - interface View extends BaseContract.View { - - void openLoginActivity(); - - void openMainActivity(); - - void cancelNotifications(); - - void setCurrentThemeMode(int mode); - } - - interface Presenter extends BaseContract.Presenter { - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/splash/SplashModule.java b/app/src/main/java/io/github/wulkanowy/ui/splash/SplashModule.java deleted file mode 100644 index 838b411d..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/splash/SplashModule.java +++ /dev/null @@ -1,13 +0,0 @@ -package io.github.wulkanowy.ui.splash; - -import dagger.Binds; -import dagger.Module; -import io.github.wulkanowy.di.scopes.PerActivity; - -@Module -public abstract class SplashModule { - - @PerActivity - @Binds - abstract SplashContract.Presenter provideSplashPresenter(SplashPresenter splashPresenter); -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/splash/SplashPresenter.java b/app/src/main/java/io/github/wulkanowy/ui/splash/SplashPresenter.java deleted file mode 100644 index 69423348..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/splash/SplashPresenter.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.github.wulkanowy.ui.splash; - -import android.support.annotation.NonNull; - -import javax.inject.Inject; - -import io.github.wulkanowy.data.RepositoryContract; -import io.github.wulkanowy.ui.base.BasePresenter; - -public class SplashPresenter extends BasePresenter - implements SplashContract.Presenter { - - @Inject - SplashPresenter(RepositoryContract repository) { - super(repository); - } - - @Override - public void attachView(@NonNull SplashContract.View view) { - super.attachView(view); - getView().setCurrentThemeMode(getRepository().getSharedRepo().getCurrentTheme()); - getView().cancelNotifications(); - - if (getRepository().getSharedRepo().isUserLoggedIn()) { - getView().openMainActivity(); - } else { - getView().openLoginActivity(); - } - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/widgets/TimetableWidgetFactory.java b/app/src/main/java/io/github/wulkanowy/ui/widgets/TimetableWidgetFactory.java deleted file mode 100644 index 9e632396..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/widgets/TimetableWidgetFactory.java +++ /dev/null @@ -1,140 +0,0 @@ -package io.github.wulkanowy.ui.widgets; - -import android.content.Context; -import android.content.Intent; -import android.graphics.Paint; -import android.view.View; -import android.widget.AdapterView; -import android.widget.RemoteViews; -import android.widget.RemoteViewsService; - -import org.apache.commons.lang3.StringUtils; - -import java.util.ArrayList; -import java.util.List; - -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.RepositoryContract; -import io.github.wulkanowy.data.db.dao.entities.TimetableLesson; -import io.github.wulkanowy.data.db.dao.entities.Week; - -import static io.github.wulkanowy.utils.TimeUtilsKt.getFirstDayOfCurrentWeek; -import static io.github.wulkanowy.utils.TimeUtilsKt.getTodayOrNextDayOrder; - -public class TimetableWidgetFactory implements RemoteViewsService.RemoteViewsFactory { - - private final Context context; - - private List lessonList = new ArrayList<>(); - - private final RepositoryContract repository; - - public TimetableWidgetFactory(Context context, RepositoryContract repository) { - this.context = context; - this.repository = repository; - } - - - @Override - public void onCreate() { - // do nothing - } - - @Override - public void onDataSetChanged() { - lessonList = new ArrayList<>(); - - if (repository.getSharedRepo().isUserLoggedIn()) { - - Week week = repository.getDbRepo().getWeek(getFirstDayOfCurrentWeek()); - int valueOfDay = getTodayOrNextDayOrder(repository.getSharedRepo().getTimetableWidgetState()); - - if (valueOfDay != 5 && valueOfDay != 6 && week != null) { - week.resetDayList(); - lessonList = week.getDayList().get(valueOfDay).getTimetableLessons(); - } - } - } - - @Override - public void onDestroy() { - // do nothing - } - - @Override - public int getCount() { - return lessonList.size(); - } - - @Override - public RemoteViews getViewAt(int position) { - if (position == AdapterView.INVALID_POSITION) { - return null; - } - - RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.timetable_widget_item); - views.setTextViewText(R.id.timetable_widget_item_subject, getSubjectName(position)); - views.setTextViewText(R.id.timetable_widget_item_time, getTimeText(position)); - views.setTextViewText(R.id.timetable_widget_item_room, getRoomText(position)); - - if (!getDescriptionText(position).isEmpty()) { - views.setViewVisibility(R.id.timetable_widget_item_description, View.VISIBLE); - views.setTextViewText(R.id.timetable_widget_item_description, getDescriptionText(position)); - } else { - views.setViewVisibility(R.id.timetable_widget_item_description, View.GONE); - } - - if (lessonList.get(position).getMovedOrCanceled()) { - views.setInt(R.id.timetable_widget_item_subject, "setPaintFlags", - Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); - } else { - views.setInt(R.id.timetable_widget_item_subject, "setPaintFlags", - Paint.ANTI_ALIAS_FLAG); - } - - views.setOnClickFillInIntent(R.id.timetable_widget_item_container, new Intent()); - return views; - } - - @Override - public RemoteViews getLoadingView() { - return null; - } - - @Override - public int getViewTypeCount() { - return 1; - } - - @Override - public long getItemId(int position) { - return position; - } - - @Override - public boolean hasStableIds() { - return true; - } - - private String getSubjectName(int position) { - return lessonList.get(position).getSubject(); - } - - private String getRoomText(int position) { - TimetableLesson lesson = lessonList.get(position); - if (!lesson.getRoom().isEmpty()) { - return context.getString(R.string.timetable_dialog_room) + " " + lesson.getRoom(); - } - return lesson.getRoom(); - } - - private String getTimeText(int position) { - TimetableLesson lesson = lessonList.get(position); - return lesson.getStartTime() + " - " + lesson.getEndTime(); - } - - private String getDescriptionText(int position) { - return StringUtils.capitalize(lessonList.get(position).getDescription()); - } - -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/widgets/TimetableWidgetProvider.java b/app/src/main/java/io/github/wulkanowy/ui/widgets/TimetableWidgetProvider.java deleted file mode 100644 index aa164e29..00000000 --- a/app/src/main/java/io/github/wulkanowy/ui/widgets/TimetableWidgetProvider.java +++ /dev/null @@ -1,112 +0,0 @@ -package io.github.wulkanowy.ui.widgets; - -import android.app.PendingIntent; -import android.appwidget.AppWidgetManager; -import android.appwidget.AppWidgetProvider; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.support.v4.app.TaskStackBuilder; -import android.widget.RemoteViews; - -import javax.inject.Inject; - -import dagger.android.AndroidInjection; -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.RepositoryContract; -import io.github.wulkanowy.services.widgets.TimetableWidgetServices; -import io.github.wulkanowy.ui.main.MainActivity; - -import static io.github.wulkanowy.utils.TimeUtilsKt.getTodayOrNextDay; - -public class TimetableWidgetProvider extends AppWidgetProvider { - - private static final String ACTION_TIMETABLE_TOGGLE = "timetable_toggle"; - - @Inject - RepositoryContract repository; - - @Override - public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { - inject(context); - - for (int appWidgetId : appWidgetIds) { - RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.timetable_widget); - - setViews(views, context, appWidgetId); - setToggleIntent(views, context); - setTemplateIntent(views, context); - updateWidget(views, appWidgetManager, appWidgetId); - } - super.onUpdate(context, appWidgetManager, appWidgetIds); - } - - @Override - public void onReceive(final Context context, Intent intent) { - super.onReceive(context, intent); - inject(context); - - if (ACTION_TIMETABLE_TOGGLE.equals(intent.getAction())) { - AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); - ComponentName thisWidget = new ComponentName(context.getPackageName(), - TimetableWidgetProvider.class.getName()); - int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget); - - repository.getSharedRepo().setTimetableWidgetState(!repository.getSharedRepo().getTimetableWidgetState()); - onUpdate(context, appWidgetManager, appWidgetIds); - } - } - - @Override - public void onDisabled(Context context) { - super.onDisabled(context); - inject(context); - repository.getSharedRepo().setTimetableWidgetState(false); - } - - private void setToggleIntent(RemoteViews views, Context context) { - Intent refreshIntent = new Intent(context, TimetableWidgetProvider.class); - refreshIntent.setAction(ACTION_TIMETABLE_TOGGLE); - PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, - refreshIntent, PendingIntent.FLAG_UPDATE_CURRENT); - views.setOnClickPendingIntent(R.id.timetable_widget_toggle, pendingIntent); - } - - private void setTemplateIntent(RemoteViews views, Context context) { - Intent intent = MainActivity.getStartIntent(context); - intent.putExtra(MainActivity.EXTRA_CARD_ID_KEY, 3); - - PendingIntent pendingIntent = TaskStackBuilder.create(context) - .addNextIntentWithParentStack(intent) - .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); - - views.setPendingIntentTemplate(R.id.timetable_widget_list, pendingIntent); - } - - private void setViews(RemoteViews views, Context context, int appWidgetId) { - Intent intent = new Intent(context, TimetableWidgetServices.class); - intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); - - views.setRemoteAdapter(appWidgetId, R.id.timetable_widget_list, intent); - views.setEmptyView(R.id.timetable_widget_list, R.id.timetable_widget_empty); - - boolean nextDay = repository.getSharedRepo().getTimetableWidgetState(); - - String toggleText = context.getString(nextDay ? R.string.widget_timetable_tomorrow - : R.string.widget_timetable_today); - - views.setTextViewText(R.id.timetable_widget_toggle, toggleText); - views.setTextViewText(R.id.timetable_widget_date, getTodayOrNextDay(nextDay)); - } - - private void updateWidget(RemoteViews views, AppWidgetManager appWidgetManager, int appWidgetId) { - appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.timetable_widget_list); - appWidgetManager.updateAppWidget(appWidgetId, views); - } - - private void inject(Context context) { - if (repository == null) { - AndroidInjection.inject(this, context); - } - } -} diff --git a/app/src/main/java/io/github/wulkanowy/ui/widgets/timetable/TimetableWidgetFactory.kt b/app/src/main/java/io/github/wulkanowy/ui/widgets/timetable/TimetableWidgetFactory.kt new file mode 100644 index 00000000..6b9868f2 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/widgets/timetable/TimetableWidgetFactory.kt @@ -0,0 +1,93 @@ +package io.github.wulkanowy.ui.widgets.timetable + +import android.content.Context +import android.content.Intent +import android.graphics.Paint.ANTI_ALIAS_FLAG +import android.graphics.Paint.STRIKE_THRU_TEXT_FLAG +import android.view.View.GONE +import android.view.View.VISIBLE +import android.widget.AdapterView.INVALID_POSITION +import android.widget.RemoteViews +import android.widget.RemoteViewsService +import io.github.wulkanowy.R +import io.github.wulkanowy.data.db.SharedPrefHelper +import io.github.wulkanowy.data.db.entities.Timetable +import io.github.wulkanowy.data.repositories.SessionRepository +import io.github.wulkanowy.data.repositories.TimetableRepository +import io.github.wulkanowy.utils.toFormattedString +import io.reactivex.disposables.CompositeDisposable +import org.threeten.bp.LocalDate +import timber.log.Timber + +class TimetableWidgetFactory( + private val timetableRepository: TimetableRepository, + private val sessionRepository: SessionRepository, + private val sharedPref: SharedPrefHelper, + private val context: Context, + private val intent: Intent? +) : RemoteViewsService.RemoteViewsFactory { + + private val disposable: CompositeDisposable = CompositeDisposable() + + private var lessons = emptyList() + + override fun getLoadingView() = null + + override fun hasStableIds() = true + + override fun getCount() = lessons.size + + override fun getViewTypeCount() = 1 + + override fun getItemId(position: Int) = position.toLong() + + override fun onCreate() {} + + override fun onDataSetChanged() { + intent?.action?.let { LocalDate.ofEpochDay(sharedPref.getLong(it, 0)) } + ?.let { date -> + if (sessionRepository.isSessionSaved) { + disposable.add(sessionRepository.getSemesters() + .map { it.single { item -> item.current } } + .flatMap { timetableRepository.getTimetable(it, date, date) } + .map { item -> item.sortedBy { it.number } } + .subscribe({ lessons = it }) + { Timber.e(it, "An error has occurred while downloading data for the widget") }) + } + } + } + + override fun getViewAt(position: Int): RemoteViews? { + if (position == INVALID_POSITION) return null + + return RemoteViews(context.packageName, R.layout.item_widget_timetable).apply { + lessons[position].let { + setTextViewText(R.id.timetableWidgetItemSubject, it.subject) + setTextViewText(R.id.timetableWidgetItemNumber, it.number.toString()) + setTextViewText(R.id.timetableWidgetItemTime, it.start.toFormattedString("HH:mm") + + " - ${it.end.toFormattedString("HH:mm")}") + + if (it.room.isNotBlank()) { + setTextViewText(R.id.timetableWidgetItemRoom, "${context.getString(R.string.timetable_room)} ${it.room}") + } else setTextViewText(R.id.timetableWidgetItemRoom, "") + + if (it.info.isNotBlank()) { + setViewVisibility(R.id.timetableWidgetItemDescription, VISIBLE) + setTextViewText(R.id.timetableWidgetItemDescription, it.info.capitalize()) + } else setViewVisibility(R.id.timetableWidgetItemDescription, GONE) + + if (it.changes) { + setInt(R.id.timetableWidgetItemSubject, "setPaintFlags", + STRIKE_THRU_TEXT_FLAG or ANTI_ALIAS_FLAG) + } else { + setInt(R.id.timetableWidgetItemSubject, "setPaintFlags", ANTI_ALIAS_FLAG) + } + } + setOnClickFillInIntent(R.id.timetableWidgetItemContainer, Intent()) + } + } + + override fun onDestroy() { + disposable.clear() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/widgets/timetable/TimetableWidgetProvider.kt b/app/src/main/java/io/github/wulkanowy/ui/widgets/timetable/TimetableWidgetProvider.kt new file mode 100644 index 00000000..8439aed4 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/widgets/timetable/TimetableWidgetProvider.kt @@ -0,0 +1,123 @@ +package io.github.wulkanowy.ui.widgets.timetable + +import android.app.PendingIntent +import android.app.PendingIntent.FLAG_UPDATE_CURRENT +import android.appwidget.AppWidgetManager +import android.appwidget.AppWidgetManager.ACTION_APPWIDGET_UPDATE +import android.appwidget.AppWidgetManager.EXTRA_APPWIDGET_IDS +import android.appwidget.AppWidgetProvider +import android.content.Context +import android.content.Intent +import android.widget.RemoteViews +import dagger.android.AndroidInjection +import io.github.wulkanowy.R +import io.github.wulkanowy.data.db.SharedPrefHelper +import io.github.wulkanowy.services.widgets.TimetableWidgetService +import io.github.wulkanowy.ui.modules.main.MainActivity +import io.github.wulkanowy.ui.modules.main.MainActivity.Companion.EXTRA_START_MENU_INDEX +import io.github.wulkanowy.utils.logEvent +import io.github.wulkanowy.utils.nextOrSameSchoolDay +import io.github.wulkanowy.utils.nextSchoolDay +import io.github.wulkanowy.utils.previousSchoolDay +import io.github.wulkanowy.utils.toFormattedString +import io.github.wulkanowy.utils.weekDayName +import org.threeten.bp.LocalDate +import javax.inject.Inject + +class TimetableWidgetProvider : AppWidgetProvider() { + + @Inject + lateinit var sharedPref: SharedPrefHelper + + companion object { + const val EXTRA_TOGGLED_WIDGET_ID = "extraToggledWidget" + + const val EXTRA_BUTTON_TYPE = "extraButtonType" + + const val BUTTON_NEXT = "buttonNext" + + const val BUTTON_PREV = "buttonPrev" + + const val BUTTON_RESET = "buttonReset" + } + + override fun onUpdate(context: Context?, appWidgetManager: AppWidgetManager?, appWidgetIds: IntArray?) { + appWidgetIds?.forEach { + val widgetKey = "timetable_widget_$it" + checkSavedWidgetDate(widgetKey) + + val savedDate = LocalDate.ofEpochDay(sharedPref.getLong(widgetKey, 0)) + context?.run { + RemoteViews(packageName, R.layout.widget_timetable).apply { + setTextViewText(R.id.timetableWidgetDay, savedDate.weekDayName.capitalize()) + setTextViewText(R.id.timetableWidgetDate, savedDate.toFormattedString()) + setEmptyView(R.id.timetableWidgetList, R.id.timetableWidgetEmpty) + setRemoteAdapter(R.id.timetableWidgetList, Intent(context, TimetableWidgetService::class.java) + .apply { action = widgetKey }) + setOnClickPendingIntent(R.id.timetableWidgetNext, createNavIntent(context, it, it, appWidgetIds, BUTTON_NEXT)) + setOnClickPendingIntent(R.id.timetableWidgetPrev, createNavIntent(context, -it, it, appWidgetIds, BUTTON_PREV)) + createNavIntent(context, Int.MAX_VALUE, it, appWidgetIds, BUTTON_RESET).let { intent -> + setOnClickPendingIntent(R.id.timetableWidgetDate, intent) + setOnClickPendingIntent(R.id.timetableWidgetDay, intent) + } + setPendingIntentTemplate(R.id.timetableWidgetList, + PendingIntent.getActivity(context, 1, MainActivity.getStartIntent(context).apply { + putExtra(EXTRA_START_MENU_INDEX, 3) + }, FLAG_UPDATE_CURRENT)) + + }.also { view -> + appWidgetManager?.apply { + notifyAppWidgetViewDataChanged(it, R.id.timetableWidgetList) + updateAppWidget(it, view) + } + } + } + } + } + + override fun onReceive(context: Context?, intent: Intent?) { + AndroidInjection.inject(this, context) + intent?.let { + val widgetKey = "timetable_widget_${it.getIntExtra(EXTRA_TOGGLED_WIDGET_ID, 0)}" + it.getStringExtra(EXTRA_BUTTON_TYPE).let { button -> + when (button) { + BUTTON_NEXT -> { + LocalDate.ofEpochDay(sharedPref.getLong(widgetKey, 0)).nextSchoolDay + .let { date -> sharedPref.putLong(widgetKey, date.toEpochDay(), true) } + } + BUTTON_PREV -> { + LocalDate.ofEpochDay(sharedPref.getLong(widgetKey, 0)).previousSchoolDay + .let { date -> sharedPref.putLong(widgetKey, date.toEpochDay(), true) } + } + BUTTON_RESET -> sharedPref.putLong(widgetKey, LocalDate.now().nextOrSameSchoolDay.toEpochDay(), true) + } + button?.also { btn -> if (btn.isNotBlank()) logEvent("Widget day changed", mapOf("button" to button)) } + } + } + super.onReceive(context, intent) + } + + override fun onDeleted(context: Context?, appWidgetIds: IntArray?) { + appWidgetIds?.forEach { + sharedPref.delete("timetable_widget_$it") + } + } + + private fun createNavIntent(context: Context, code: Int, widgetId: Int, widgetIds: IntArray, buttonType: String): PendingIntent { + return PendingIntent.getBroadcast(context, code, + Intent(context, TimetableWidgetProvider::class.java).apply { + action = ACTION_APPWIDGET_UPDATE + putExtra(EXTRA_APPWIDGET_IDS, widgetIds) + putExtra(EXTRA_BUTTON_TYPE, buttonType) + putExtra(EXTRA_TOGGLED_WIDGET_ID, widgetId) + }, FLAG_UPDATE_CURRENT) + } + + private fun checkSavedWidgetDate(widgetKey: String) { + sharedPref.run { + if (getLong(widgetKey, -1) == -1L) { + putLong(widgetKey, LocalDate.now().nextOrSameSchoolDay.toEpochDay(), true) + } + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/utils/ActivityExtension.kt b/app/src/main/java/io/github/wulkanowy/utils/ActivityExtension.kt new file mode 100644 index 00000000..c0314d02 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/utils/ActivityExtension.kt @@ -0,0 +1,18 @@ +package io.github.wulkanowy.utils + +import android.app.Activity +import android.content.Context.INPUT_METHOD_SERVICE +import android.view.inputmethod.InputMethodManager + + +fun Activity.showSoftInput() { + (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager?)?.run { + if (currentFocus != null) showSoftInput(currentFocus, 0) + } +} + +fun Activity.hideSoftInput() { + (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager?)?.run { + hideSoftInputFromWindow(window.decorView.applicationWindowToken, 0) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/utils/AnimationUtils.java b/app/src/main/java/io/github/wulkanowy/utils/AnimationUtils.java deleted file mode 100644 index 04116423..00000000 --- a/app/src/main/java/io/github/wulkanowy/utils/AnimationUtils.java +++ /dev/null @@ -1,40 +0,0 @@ -package io.github.wulkanowy.utils; - -import android.animation.Animator; -import android.animation.AnimatorListenerAdapter; -import android.view.View; - -public final class AnimationUtils { - - public static void slideDown(final View view) { - view.setVisibility(View.VISIBLE); - view.setAlpha(0.f); - - view.setTranslationY(-(view.getHeight() / 2)); - view.animate() - .translationY(0) - .alpha(1.f) - .setListener(new AnimatorListenerAdapter() { - @Override - public void onAnimationEnd(Animator animation) { - view.setVisibility(View.VISIBLE); - view.setAlpha(1.f); - } - }); - } - - public static void slideUp(final View view) { - view.animate() - .translationY(-(view.getHeight() / 2)) - .alpha(0.f) - .setListener(new AnimatorListenerAdapter() { - @Override - public void onAnimationEnd(Animator animation) { - // superfluous restoration - view.setVisibility(View.GONE); - view.setAlpha(1.f); - view.setTranslationY(0.f); - } - }); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/utils/AppConstant.java b/app/src/main/java/io/github/wulkanowy/utils/AppConstant.java deleted file mode 100644 index 2499974d..00000000 --- a/app/src/main/java/io/github/wulkanowy/utils/AppConstant.java +++ /dev/null @@ -1,27 +0,0 @@ -package io.github.wulkanowy.utils; - -public final class AppConstant { - - public static final String APP_NAME = "Wulkanowy"; - - public static final String DATABASE_NAME = "wulkanowy_db"; - - public static final String SHARED_PREFERENCES_NAME = "user_data"; - - - public static final String VULCAN_CREATE_ACCOUNT_URL = - "https://cufs.vulcan.net.pl/Default/AccountManage/CreateAccount"; - - public static final String VULCAN_FORGOT_PASS_URL = - "https://cufs.vulcan.net.pl/Default/AccountManage/UnlockAccount"; - - public static final String DEFAULT_SYMBOL = "Default"; - - public static final String DATE_PATTERN = "yyyy-MM-dd"; - - public static final String REPO_URL = "https://github.com/wulkanowy/wulkanowy"; - - private AppConstant() { - throw new IllegalStateException("Utility class"); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/utils/CommonUtils.java b/app/src/main/java/io/github/wulkanowy/utils/CommonUtils.java deleted file mode 100644 index 9c7b35fb..00000000 --- a/app/src/main/java/io/github/wulkanowy/utils/CommonUtils.java +++ /dev/null @@ -1,54 +0,0 @@ -package io.github.wulkanowy.utils; - -import android.app.Activity; -import android.content.Context; -import android.content.res.TypedArray; -import android.net.Uri; -import android.support.annotation.AttrRes; -import android.support.annotation.ColorInt; -import android.support.customtabs.CustomTabsIntent; - -import io.github.wulkanowy.R; - -public final class CommonUtils { - - private CommonUtils() { - throw new IllegalStateException("Utility class"); - } - - public static void openInternalBrowserViewer(Activity activity, String url) { - CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); - builder.setToolbarColor(activity.getResources().getColor(R.color.colorPrimary)); - CustomTabsIntent customTabsIntent = builder.build(); - customTabsIntent.launchUrl(activity, Uri.parse(url)); - } - - public static int colorHexToColorName(String hexColor) { - switch (hexColor) { - case "000000": - return R.string.color_black_text; - - case "F04C4C": - return R.string.color_red_text; - - case "20A4F7": - return R.string.color_blue_text; - - case "6ECD07": - return R.string.color_green_text; - - default: - return R.string.noColor_text; - } - } - - @ColorInt - public static int getThemeAttrColor(Context context, @AttrRes int colorAttr) { - final TypedArray array = context.obtainStyledAttributes(null, new int[]{colorAttr}); - try { - return array.getColor(0, 0); - } finally { - array.recycle(); - } - } -} diff --git a/app/src/main/java/io/github/wulkanowy/utils/ContextExtension.kt b/app/src/main/java/io/github/wulkanowy/utils/ContextExtension.kt new file mode 100644 index 00000000..e056bf7e --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/utils/ContextExtension.kt @@ -0,0 +1,15 @@ +package io.github.wulkanowy.utils + +import android.content.Context +import androidx.annotation.AttrRes +import androidx.annotation.ColorInt + +@ColorInt +fun Context.getThemeAttrColor(@AttrRes colorAttr: Int): Int { + val array = this.obtainStyledAttributes(null, intArrayOf(colorAttr)) + try { + return array.getColor(0, 0) + } finally { + array.recycle() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/utils/DataObjectConverter.java b/app/src/main/java/io/github/wulkanowy/utils/DataObjectConverter.java deleted file mode 100644 index cd4490d6..00000000 --- a/app/src/main/java/io/github/wulkanowy/utils/DataObjectConverter.java +++ /dev/null @@ -1,202 +0,0 @@ -package io.github.wulkanowy.utils; - - -import java.util.ArrayList; -import java.util.List; - -import io.github.wulkanowy.data.db.dao.entities.AttendanceLesson; -import io.github.wulkanowy.data.db.dao.entities.Day; -import io.github.wulkanowy.data.db.dao.entities.Diary; -import io.github.wulkanowy.data.db.dao.entities.Exam; -import io.github.wulkanowy.data.db.dao.entities.Grade; -import io.github.wulkanowy.data.db.dao.entities.School; -import io.github.wulkanowy.data.db.dao.entities.Semester; -import io.github.wulkanowy.data.db.dao.entities.Student; -import io.github.wulkanowy.data.db.dao.entities.Subject; -import io.github.wulkanowy.data.db.dao.entities.TimetableLesson; -import io.github.wulkanowy.data.db.dao.entities.Week; - -public final class DataObjectConverter { - - private DataObjectConverter() { - throw new IllegalStateException("Utility class"); - } - - public static List schoolsToSchoolsEntities(List schools, Long symbolId) { - List studentList = new ArrayList<>(); - - for (io.github.wulkanowy.api.generic.School school : schools) { - studentList.add(new School() - .setName(school.getName()) - .setCurrent(school.getCurrent()) - .setRealId(school.getId()) - .setSymbolId(symbolId) - ); - } - - return studentList; - } - - public static List studentsToStudentEntities(List students, Long schoolId) { - List studentList = new ArrayList<>(); - - for (io.github.wulkanowy.api.generic.Student student : students) { - studentList.add(new Student() - .setName(student.getName()) - .setCurrent(student.isCurrent()) - .setRealId(student.getId()) - .setSchoolId(schoolId) - ); - } - - return studentList; - } - - public static List diariesToDiaryEntities(List diaryList, Long studentId) { - List diaryEntityList = new ArrayList<>(); - - for (io.github.wulkanowy.api.generic.Diary diary : diaryList) { - diaryEntityList.add(new Diary() - .setStudentId(studentId) - .setValue(diary.getId()) - .setName(diary.getName()) - .setCurrent(diary.isCurrent())); - } - - return diaryEntityList; - } - - public static List semestersToSemesterEntities(List semesters, long diaryId) { - List semesterList = new ArrayList<>(); - - for (io.github.wulkanowy.api.generic.Semester semester : semesters) { - semesterList.add(new Semester() - .setDiaryId(diaryId) - .setName(semester.getName()) - .setCurrent(semester.isCurrent()) - .setValue(semester.getId()) - ); - } - - return semesterList; - } - - public static List subjectsToSubjectEntities(List subjectList, long semesterId) { - List subjectEntityList = new ArrayList<>(); - - for (io.github.wulkanowy.api.grades.Subject subject : subjectList) { - Subject subjectEntity = new Subject() - .setSemesterId(semesterId) - .setName(subject.getName()) - .setPredictedRating(subject.getPredictedRating()) - .setFinalRating(subject.getFinalRating()); - subjectEntityList.add(subjectEntity); - } - - return subjectEntityList; - } - - public static List gradesToGradeEntities(List gradeList, long semesterId) { - List gradeEntityList = new ArrayList<>(); - - for (io.github.wulkanowy.api.grades.Grade grade : gradeList) { - gradeEntityList.add(new Grade() - .setSubject(grade.getSubject()) - .setValue(grade.getValue()) - .setColor(grade.getColor()) - .setSymbol(grade.getSymbol()) - .setDescription(grade.getDescription()) - .setWeight(grade.getWeight()) - .setDate(grade.getDate()) - .setTeacher(grade.getTeacher()) - .setSemesterId(semesterId)); - } - - return gradeEntityList; - } - - public static Week weekToWeekEntity(io.github.wulkanowy.api.generic.Week week) { - return new Week().setStartDayDate(week.getStartDayDate()); - } - - public static Day dayToDayEntity(io.github.wulkanowy.api.generic.Day day) { - return new Day() - .setDate(day.getDate()) - .setDayName(day.getDayName()); - } - - public static Day timetableDayToDayEntity(io.github.wulkanowy.api.timetable.TimetableDay day) { - return new Day() - .setDate(day.getDate()) - .setDayName(day.getDayName()) - .setFreeDay(day.isFreeDay()) - .setFreeDayName(day.getFreeDayName()); - } - - public static List daysToDaysEntities(List dayList) { - List dayEntityList = new ArrayList<>(); - - for (io.github.wulkanowy.api.generic.Day day : dayList) { - dayEntityList.add(dayToDayEntity(day)); - } - return dayEntityList; - } - - public static List lessonsToTimetableLessonsEntities(List lessonList) { - List lessonEntityList = new ArrayList<>(); - - for (io.github.wulkanowy.api.generic.Lesson lesson : lessonList) { - lessonEntityList.add(new TimetableLesson() - .setNumber(lesson.getNumber()) - .setSubject(lesson.getSubject()) - .setTeacher(lesson.getTeacher()) - .setRoom(lesson.getRoom()) - .setDescription(lesson.getDescription()) - .setGroup(lesson.getGroupName()) - .setStartTime(lesson.getStartTime()) - .setEndTime(lesson.getEndTime()) - .setDate(lesson.getDate()) - .setEmpty(lesson.isEmpty()) - .setDivisionIntoGroups(lesson.isDivisionIntoGroups()) - .setPlanning(lesson.isPlanning()) - .setRealized(lesson.isRealized()) - .setMovedOrCanceled(lesson.isMovedOrCanceled()) - .setNewMovedInOrChanged(lesson.isNewMovedInOrChanged())); - } - - return lessonEntityList; - } - - public static List lessonsToAttendanceLessonsEntities(List lessonList) { - List lessonEntityList = new ArrayList<>(); - - for (io.github.wulkanowy.api.generic.Lesson lesson : lessonList) { - lessonEntityList.add(new AttendanceLesson() - .setNumber(lesson.getNumber()) - .setSubject(lesson.getSubject()) - .setDate(lesson.getDate()) - .setPresence(lesson.isPresence()) - .setAbsenceUnexcused(lesson.isAbsenceUnexcused()) - .setAbsenceExcused(lesson.isAbsenceExcused()) - .setUnexcusedLateness(lesson.isUnexcusedLateness()) - .setAbsenceForSchoolReasons(lesson.isAbsenceForSchoolReasons()) - .setExcusedLateness(lesson.isExcusedLateness()) - .setExemption(lesson.isExemption())); - } - return lessonEntityList; - } - - public static List examsToExamsEntity(List examList) { - List examEntityList = new ArrayList<>(); - - for (io.github.wulkanowy.api.exams.Exam exam : examList) { - examEntityList.add(new Exam() - .setDescription(exam.getDescription()) - .setEntryDate(exam.getEntryDate()) - .setSubjectAndGroup(exam.getSubjectAndGroup()) - .setTeacher(exam.getTeacher()) - .setType(exam.getType())); - } - return examEntityList; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/utils/EntitiesCompare.java b/app/src/main/java/io/github/wulkanowy/utils/EntitiesCompare.java deleted file mode 100644 index 5681bad1..00000000 --- a/app/src/main/java/io/github/wulkanowy/utils/EntitiesCompare.java +++ /dev/null @@ -1,42 +0,0 @@ -package io.github.wulkanowy.utils; - -import org.apache.commons.collections4.CollectionUtils; - -import java.util.ArrayList; -import java.util.List; - -import io.github.wulkanowy.data.db.dao.entities.Grade; - -public final class EntitiesCompare { - - private EntitiesCompare() { - throw new IllegalStateException("Utility class"); - } - - public static List compareGradeList(List newList, List oldList) { - - List addedOrUpdatedGradeList = new ArrayList<>(CollectionUtils - .removeAll(newList, oldList)); - List updatedList = new ArrayList<>(CollectionUtils - .removeAll(newList, addedOrUpdatedGradeList)); - List lastList = new ArrayList<>(); - - for (Grade grade : addedOrUpdatedGradeList) { - if (!oldList.isEmpty()) { - grade.setRead(false); - } - grade.setIsNew(true); - updatedList.add(grade); - } - - for (Grade updateGrade : updatedList) { - for (Grade oldGrade : oldList) { - if (updateGrade.equals(oldGrade)) { - updateGrade.setRead(oldGrade.getRead()); - } - } - lastList.add(updateGrade); - } - return lastList; - } -} diff --git a/app/src/main/java/io/github/wulkanowy/utils/FabricUtils.java b/app/src/main/java/io/github/wulkanowy/utils/FabricUtils.java deleted file mode 100644 index 69897caa..00000000 --- a/app/src/main/java/io/github/wulkanowy/utils/FabricUtils.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.github.wulkanowy.utils; - -import com.crashlytics.android.answers.Answers; -import com.crashlytics.android.answers.CustomEvent; -import com.crashlytics.android.answers.LoginEvent; -import com.crashlytics.android.answers.SignUpEvent; - -public final class FabricUtils { - - private FabricUtils() { - throw new IllegalStateException("Utility class"); - } - - public static void logLogin(String method, boolean result) { - Answers.getInstance().logLogin(new LoginEvent() - .putMethod(method) - .putSuccess(result) - ); - } - - public static void logRegister(boolean result, String symbol, String message) { - Answers.getInstance().logSignUp(new SignUpEvent() - .putMethod("Login activity") - .putSuccess(result) - .putCustomAttribute("symbol", symbol) - .putCustomAttribute("message", message) - ); - } - - public static void logRefresh(String name, boolean result, String date) { - Answers.getInstance().logCustom( - new CustomEvent(name + " refresh") - .putCustomAttribute("Success", result ? "true" : "false") - .putCustomAttribute("Date", date) - ); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/utils/FabricUtils.kt b/app/src/main/java/io/github/wulkanowy/utils/FabricUtils.kt new file mode 100644 index 00000000..a82c4f81 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/utils/FabricUtils.kt @@ -0,0 +1,48 @@ +package io.github.wulkanowy.utils + +import com.crashlytics.android.answers.Answers +import com.crashlytics.android.answers.CustomEvent +import com.crashlytics.android.answers.LoginEvent +import com.crashlytics.android.answers.SignUpEvent +import timber.log.Timber + +fun logLogin(method: String) { + try { + Answers.getInstance().logLogin(LoginEvent().putMethod(method)) + } catch (e: Throwable) { + Timber.d(e) + } +} + +fun logRegister(message: String, result: Boolean, symbol: String, endpoint: String) { + try { + Answers.getInstance().logSignUp(SignUpEvent() + .putMethod("Login activity") + .putSuccess(result) + .putCustomAttribute("symbol", symbol) + .putCustomAttribute("message", message) + .putCustomAttribute("endpoint", endpoint) + ) + } catch (e: Throwable) { + Timber.d(e) + } +} + +fun logEvent(name: String, params: Map) { + try { + Answers.getInstance().logCustom(CustomEvent(name) + .apply { + params.forEach { + when { + it.value is String -> putCustomAttribute(it.key, it.value as String) + it.value is Number -> putCustomAttribute(it.key, it.value as Number) + it.value is Boolean -> putCustomAttribute(it.key, if ((it.value as Boolean)) "true" else "false") + else -> Timber.w("logEvent() unknown value type: ${it.value}") + } + } + } + ) + } catch (e: Throwable) { + Timber.d(e) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/utils/FlexibleAdapterExtension.kt b/app/src/main/java/io/github/wulkanowy/utils/FlexibleAdapterExtension.kt new file mode 100644 index 00000000..27b5f94f --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/utils/FlexibleAdapterExtension.kt @@ -0,0 +1,10 @@ +package io.github.wulkanowy.utils + +import eu.davidea.flexibleadapter.FlexibleAdapter + +inline fun FlexibleAdapter<*>.setOnItemClickListener(crossinline listener: (position: Int) -> Unit) { + addListener(FlexibleAdapter.OnItemClickListener { _, position -> + listener(position) + true + }) +} \ No newline at end of file diff --git a/app/src/main/java/io/github/wulkanowy/utils/FragNavControlerExtension.kt b/app/src/main/java/io/github/wulkanowy/utils/FragNavControlerExtension.kt new file mode 100644 index 00000000..dcf47754 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/utils/FragNavControlerExtension.kt @@ -0,0 +1,20 @@ +package io.github.wulkanowy.utils + +import androidx.fragment.app.Fragment +import com.ncapdevi.fragnav.FragNavController + +inline fun FragNavController.setOnViewChangeListener(crossinline listener: (fragment: Fragment?) -> Unit) { + transactionListener = object : FragNavController.TransactionListener { + override fun onFragmentTransaction(fragment: Fragment?, transactionType: FragNavController.TransactionType) { + listener(fragment) + } + + override fun onTabTransaction(fragment: Fragment?, index: Int) { + listener(fragment) + } + } +} + +fun FragNavController.safelyPopFragment() { + if (!isRootFragment) popFragment() +} diff --git a/app/src/main/java/io/github/wulkanowy/utils/GradeExtension.kt b/app/src/main/java/io/github/wulkanowy/utils/GradeExtension.kt new file mode 100644 index 00000000..c9119cc3 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/utils/GradeExtension.kt @@ -0,0 +1,49 @@ +package io.github.wulkanowy.utils + +import io.github.wulkanowy.R +import io.github.wulkanowy.data.db.entities.Grade +import io.github.wulkanowy.data.db.entities.GradeSummary + +fun List.calcAverage(): Double { + var counter = 0.0 + var denominator = 0.0 + + forEach { + counter += (it.value + it.modifier) * it.weightValue + denominator += it.weightValue + } + return if (denominator != 0.0) counter / denominator else 0.0 +} + +@JvmName("calcSummaryAverage") +fun List.calcAverage(): Double { + return asSequence().mapNotNull { + if (it.finalGrade.matches("[0-6]".toRegex())) it.finalGrade.toDouble() else null + }.average().let { if (it.isNaN()) 0.0 else it } +} + +inline val Grade.valueColor: Int + get() { + return when (value) { + 6 -> R.color.grade_six + 5 -> R.color.grade_five + 4 -> R.color.grade_four + 3 -> R.color.grade_three + 2 -> R.color.grade_two + 1 -> R.color.grade_one + else -> R.color.grade_default + } + + } + +inline val Grade.colorStringId: Int + get() { + return when (color) { + "000000" -> R.string.all_black + "F04C4C" -> R.string.all_red + "20A4F7" -> R.string.all_blue + "6ECD07" -> R.string.all_green + "B16CF1" -> R.string.all_purple + else -> R.string.all_empty_color + } + } \ No newline at end of file diff --git a/app/src/main/java/io/github/wulkanowy/utils/GradeUtils.java b/app/src/main/java/io/github/wulkanowy/utils/GradeUtils.java deleted file mode 100644 index 7b6ba193..00000000 --- a/app/src/main/java/io/github/wulkanowy/utils/GradeUtils.java +++ /dev/null @@ -1,172 +0,0 @@ -package io.github.wulkanowy.utils; - -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import io.github.wulkanowy.R; -import io.github.wulkanowy.data.db.dao.entities.Grade; -import io.github.wulkanowy.data.db.dao.entities.Subject; - -public final class GradeUtils { - - private final static Pattern validGradePattern = Pattern.compile("^(\\++|-|--|=)?[0-6](\\++|-|--|=)?$"); - private final static Pattern simpleGradeValuePattern = Pattern.compile("([0-6])"); - - private GradeUtils() { - throw new IllegalStateException("Utility class"); - } - - public static float calculateWeightedAverage(List gradeList) { - - float counter = 0f; - float denominator = 0f; - - for (Grade grade : gradeList) { - int weight = getWeightValue(grade.getWeight()); - float value = getWeightedGradeValue(grade.getValue()); - - if (value != -1.0f) { - counter += value * weight; - denominator += weight; - } - } - - if (counter == 0f) { - return -1.0f; - } - return counter / denominator; - } - - public static float calculateSubjectsAverage(List subjectList, boolean usePredicted) { - return calculateSubjectsAverage(subjectList, usePredicted, false); - } - - public static float calculateDetailedSubjectsAverage(List subjectList) { - return calculateSubjectsAverage(subjectList, false, true); - } - - public static int getValueColor(String value) { - Matcher m1 = validGradePattern.matcher(value); - if (!m1.find()) { - return R.color.grade_default; - } - - Matcher m2 = simpleGradeValuePattern.matcher(m1.group()); - if (!m2.find()) { - return R.color.grade_default; - } - - switch (Integer.parseInt(m2.group())) { - case 6: - return R.color.grade_six; - case 5: - return R.color.grade_five; - case 4: - return R.color.grade_four; - case 3: - return R.color.grade_three; - case 2: - return R.color.grade_two; - case 1: - return R.color.grade_one; - default: - return R.color.grade_default; - } - } - - private static float calculateSubjectsAverage(List subjectList, boolean usePredicted, boolean useSubjectsAverages) { - float counter = 0f; - float denominator = 0f; - - for (Subject subject : subjectList) { - float value; - - if (useSubjectsAverages) { - value = calculateWeightedAverage(subject.getGradeList()); - } else { - value = getGradeValue(usePredicted ? subject.getPredictedRating() : subject.getFinalRating()); - } - - if (value != -1.0f) { - counter += Math.round(value); - denominator++; - } - } - - if (counter == 0) { - return -1.0f; - } - - return counter / denominator; - } - - public static float getGradeValue(String grade) { - if (validGradePattern.matcher(grade).matches()) { - return getWeightedGradeValue(grade); - } - - return getVerbalGradeValue(grade); - } - - private static float getVerbalGradeValue(String grade) { - switch (grade) { - case "celujący": - return 6f; - case "bardzo dobry": - return 5f; - case "dobry": - return 4f; - case "dostateczny": - return 3f; - case "dopuszczający": - return 2f; - case "niedostateczny": - return 1f; - default: - return -1f; - } - } - - public static String getShortGradeValue(String grade) { - switch (grade) { - case "celujący": - return "6"; - case "bardzo dobry": - return "5"; - case "dobry": - return "4"; - case "dostateczny": - return "3"; - case "dopuszczający": - return "2"; - case "niedostateczny": - return "1"; - default: - return grade; - } - } - - private static float getWeightedGradeValue(String value) { - if (validGradePattern.matcher(value).matches()) { - if (value.matches("[-][0-6]") || value.matches("[0-6][-]")) { - String replacedValue = value.replaceAll("[-]", ""); - return Float.valueOf(replacedValue) - 0.33f; - } else if (value.matches("[+][0-6]") || value.matches("[0-6][+]")) { - String replacedValue = value.replaceAll("[+]", ""); - return Float.valueOf((replacedValue)) + 0.33f; - } else if (value.matches("[-|=]{1,2}[0-6]") || value.matches("[0-6][-|=]{1,2}")) { - String replacedValue = value.replaceAll("[-|=]{1,2}", ""); - return Float.valueOf((replacedValue)) - 0.5f; - } else { - return Float.valueOf(value); - } - } else { - return -1; - } - } - - private static int getWeightValue(String weightOfGrade) { - return Integer.valueOf(weightOfGrade.substring(0, weightOfGrade.length() - 3)); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/utils/KeyboardUtils.java b/app/src/main/java/io/github/wulkanowy/utils/KeyboardUtils.java deleted file mode 100644 index 6be1b76f..00000000 --- a/app/src/main/java/io/github/wulkanowy/utils/KeyboardUtils.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.github.wulkanowy.utils; - -import android.app.Activity; -import android.content.Context; -import android.view.inputmethod.InputMethodManager; -import android.widget.EditText; - -public final class KeyboardUtils { - - private KeyboardUtils() { - throw new IllegalStateException("Utility class"); - } - - public static void hideSoftInput(Activity activity) { - InputMethodManager manager = (InputMethodManager) - activity.getSystemService(Context.INPUT_METHOD_SERVICE); - if (manager != null) { - manager.hideSoftInputFromWindow(activity.getWindow() - .getDecorView().getApplicationWindowToken(), 0); - } - } - - public static void showSoftInput(EditText editText, Context context) { - editText.setFocusable(true); - editText.setFocusableInTouchMode(true); - editText.requestFocus(); - InputMethodManager inputMethodManager = (InputMethodManager) context - .getSystemService(Context.INPUT_METHOD_SERVICE); - if (inputMethodManager != null) { - inputMethodManager.showSoftInput(editText, 0); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/io/github/wulkanowy/utils/LibsBuiderExtension.kt b/app/src/main/java/io/github/wulkanowy/utils/LibsBuiderExtension.kt new file mode 100644 index 00000000..d21b998b --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/utils/LibsBuiderExtension.kt @@ -0,0 +1,16 @@ +package io.github.wulkanowy.utils + +import android.view.View +import com.mikepenz.aboutlibraries.Libs +import com.mikepenz.aboutlibraries.LibsBuilder +import com.mikepenz.aboutlibraries.LibsConfiguration + +inline fun LibsBuilder.withOnExtraListener(crossinline listener: (Libs.SpecialButton?) -> Unit): LibsBuilder { + withListener(object : LibsConfiguration.LibsListenerImpl() { + override fun onExtraClicked(v: View?, specialButton: Libs.SpecialButton?): Boolean { + listener(specialButton) + return true + } + }) + return this +} diff --git a/app/src/main/java/io/github/wulkanowy/utils/LoggerUtils.java b/app/src/main/java/io/github/wulkanowy/utils/LoggerUtils.java deleted file mode 100644 index 6e6c701b..00000000 --- a/app/src/main/java/io/github/wulkanowy/utils/LoggerUtils.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.github.wulkanowy.utils; - -import android.os.Build; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.util.Log; - -import com.crashlytics.android.Crashlytics; - -import timber.log.Timber; - -public final class LoggerUtils { - - public static class CrashlyticsTree extends Timber.Tree { - - @Override - protected void log(int priority, @Nullable String tag, @Nullable String message, @Nullable Throwable t) { - Crashlytics.setInt("priority", priority); - Crashlytics.setString("tag", tag); - - if (t == null) { - Crashlytics.log(message); - } else { - Crashlytics.setString("message", message); - Crashlytics.logException(t); - } - } - } - - public static class DebugLogTree extends Timber.DebugTree { - - @Override - protected void log(int priority, String tag, @NonNull String message, Throwable t) { - if ("HUAWEI".equals(Build.MANUFACTURER) || "samsung".equals(Build.MANUFACTURER)) { - if (priority == Log.VERBOSE || priority == Log.DEBUG || priority == Log.INFO) { - priority = Log.ERROR; - } - } - super.log(priority, AppConstant.APP_NAME, message, t); - } - - @Override - protected String createStackElementTag(@NonNull StackTraceElement element) { - return super.createStackElementTag(element) + " - " + element.getLineNumber(); - } - } -} diff --git a/app/src/main/java/io/github/wulkanowy/utils/LoggerUtils.kt b/app/src/main/java/io/github/wulkanowy/utils/LoggerUtils.kt new file mode 100644 index 00000000..56537413 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/utils/LoggerUtils.kt @@ -0,0 +1,22 @@ +package io.github.wulkanowy.utils + +import com.crashlytics.android.Crashlytics +import timber.log.Timber + +class DebugLogTree : Timber.DebugTree() { + + override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { + super.log(priority, "Wulkanowy", message, t) + } +} + +class CrashlyticsTree : Timber.Tree() { + + override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { + Crashlytics.setInt("priority", priority) + Crashlytics.setString("tag", tag) + + if (t == null) Crashlytics.log(message) + else Crashlytics.logException(t) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/utils/NetworkUtils.java b/app/src/main/java/io/github/wulkanowy/utils/NetworkUtils.java deleted file mode 100644 index a1484eb9..00000000 --- a/app/src/main/java/io/github/wulkanowy/utils/NetworkUtils.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.github.wulkanowy.utils; - -import android.content.Context; -import android.net.ConnectivityManager; - -public final class NetworkUtils { - - private NetworkUtils() { - throw new IllegalStateException("Utility class"); - } - - public static boolean isOnline(Context context) { - ConnectivityManager connectivityManager = - (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - return connectivityManager != null && connectivityManager.getActiveNetworkInfo() != null - && connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting(); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/utils/SchedulersProvider.kt b/app/src/main/java/io/github/wulkanowy/utils/SchedulersProvider.kt new file mode 100644 index 00000000..e426d4d5 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/utils/SchedulersProvider.kt @@ -0,0 +1,14 @@ +package io.github.wulkanowy.utils + +import io.reactivex.Scheduler +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.schedulers.Schedulers + +open class SchedulersProvider { + + open val mainThread: Scheduler + get() = AndroidSchedulers.mainThread() + + open val backgroundThread: Scheduler + get() = Schedulers.io() +} diff --git a/app/src/main/java/io/github/wulkanowy/utils/TimeExtension.kt b/app/src/main/java/io/github/wulkanowy/utils/TimeExtension.kt new file mode 100644 index 00000000..0e832f96 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/utils/TimeExtension.kt @@ -0,0 +1,87 @@ +package io.github.wulkanowy.utils + +import org.threeten.bp.DayOfWeek.* +import org.threeten.bp.Instant +import org.threeten.bp.LocalDate +import org.threeten.bp.LocalDateTime +import org.threeten.bp.ZoneId +import org.threeten.bp.format.DateTimeFormatter +import org.threeten.bp.format.DateTimeFormatter.ofPattern +import org.threeten.bp.temporal.TemporalAdjusters.* +import java.util.* + +private const val DATE_PATTERN = "dd.MM.yyyy" + +fun Date.toLocalDate(): LocalDate { + return Instant.ofEpochMilli(this.time).atZone(ZoneId.systemDefault()).toLocalDate() +} + +fun Date.toLocalDateTime(): LocalDateTime { + return Instant.ofEpochMilli(this.time).atZone(ZoneId.systemDefault()).toLocalDateTime() +} + +fun String.toLocalDate(format: String = DATE_PATTERN): LocalDate { + return LocalDate.parse(this, DateTimeFormatter.ofPattern(format)) +} + +fun LocalDate.toFormattedString(format: String = DATE_PATTERN): String = this.format(ofPattern(format)) + +fun LocalDateTime.toFormattedString(format: String = DATE_PATTERN): String = this.format(ofPattern(format)) + +inline val LocalDate.nextSchoolDay: LocalDate + get() { + return when (this.dayOfWeek) { + FRIDAY, SATURDAY, SUNDAY -> this.with(next(MONDAY)) + else -> this.plusDays(1) + } + } + +inline val LocalDate.previousSchoolDay: LocalDate + get() { + return when (this.dayOfWeek) { + SATURDAY, SUNDAY, MONDAY -> this.with(previous(FRIDAY)) + else -> this.minusDays(1) + } + } + +inline val LocalDate.nextOrSameSchoolDay: LocalDate + get() { + return when (this.dayOfWeek) { + SATURDAY, SUNDAY -> this.with(next(MONDAY)) + else -> this + } + } + +inline val LocalDate.previousOrSameSchoolDay: LocalDate + get() { + return when (this.dayOfWeek) { + SATURDAY, SUNDAY -> this.with(previous(FRIDAY)) + else -> this + } + } + +inline val LocalDate.weekDayName: String + get() = this.format(ofPattern("EEEE", Locale.getDefault())) + +inline val LocalDate.monday: LocalDate + get() = this.with(MONDAY) + +inline val LocalDate.friday: LocalDate + get() = this.with(FRIDAY) + +/** + * [Dz.U. 2016 poz. 1335](http://prawo.sejm.gov.pl/isap.nsf/DocDetails.xsp?id=WDU20160001335) + */ +inline val LocalDate.isHolidays: Boolean + get() { + return LocalDate.of(this.year, 9, 1).run { + when (dayOfWeek) { + FRIDAY, SATURDAY, SUNDAY -> with(firstInMonth(MONDAY)) + else -> this + } + }.let { firstSchoolDay -> + LocalDate.of(this.year, 6, 20) + .with(next(FRIDAY)) + .let { lastSchoolDay -> this.isBefore(firstSchoolDay) && this.isAfter(lastSchoolDay) } + } + } diff --git a/app/src/main/java/io/github/wulkanowy/utils/TimeUtils.kt b/app/src/main/java/io/github/wulkanowy/utils/TimeUtils.kt deleted file mode 100644 index c61c7e0d..00000000 --- a/app/src/main/java/io/github/wulkanowy/utils/TimeUtils.kt +++ /dev/null @@ -1,97 +0,0 @@ -package io.github.wulkanowy.utils - -import org.threeten.bp.DayOfWeek.* -import org.threeten.bp.LocalDate -import org.threeten.bp.Year -import org.threeten.bp.format.DateTimeFormatter -import org.threeten.bp.temporal.TemporalAdjusters -import java.util.* - -private val formatter = DateTimeFormatter.ofPattern(AppConstant.DATE_PATTERN) - -fun getParsedDate(dateString: String, dateFormat: String): LocalDate { - return LocalDate.parse(dateString, DateTimeFormatter.ofPattern(dateFormat)) -} - -fun getMondaysFromCurrentSchoolYear() = getMondaysFromCurrentSchoolYear(LocalDate.now()) - -fun getMondaysFromCurrentSchoolYear(date: LocalDate): List { - val startDate = getFirstSchoolDay(getSchoolYearForDate(date)) - ?.with(TemporalAdjusters.previousOrSame(MONDAY)) - val endDate = getFirstSchoolDay(getSchoolYearForDate(date) + 1) - ?.with(TemporalAdjusters.previousOrSame(MONDAY)) - - val dateList = ArrayList() - var monday = startDate as LocalDate - while (monday.isBefore(endDate)) { - dateList.add(monday.format(formatter)) - monday = monday.plusWeeks(1) - } - - return dateList -} - -fun getSchoolYearForDate(date: LocalDate): Int { - return if (date.monthValue <= 8) date.year - 1 else date.year -} - -fun getFirstDayOfCurrentWeek(): String = getFirstDayOfCurrentWeek(LocalDate.now()) - -fun getFirstDayOfCurrentWeek(date: LocalDate): String { - return when (date.dayOfWeek) { - SATURDAY -> date.plusDays(2) - SUNDAY -> date.plusDays(1) - else -> date.with(MONDAY) - }.format(formatter) -} - -fun getTodayOrNextDayOrder(next: Boolean): Int = getTodayOrNextDayOrder(next, LocalDate.now()) - -fun getTodayOrNextDayOrder(next: Boolean, date: LocalDate): Int { - val day = date.dayOfWeek - return if (next) { - if (day == SUNDAY) { - 0 - } else day.value - } else day.value - 1 -} - -fun getTodayOrNextDay(next: Boolean): String? = getTodayOrNextDay(next, LocalDate.now()) - -fun getTodayOrNextDay(next: Boolean, date: LocalDate): String? { - return (if (next) { - date.plusDays(1) - } else date).format(formatter) -} - -fun isDateInWeek(firstWeekDay: LocalDate, date: LocalDate): Boolean { - return date.isAfter(firstWeekDay.minusDays(1)) && date.isBefore(firstWeekDay.plusDays(5)) -} - -/** - * [Dz.U. 2016 poz. 1335](http://prawo.sejm.gov.pl/isap.nsf/DocDetails.xsp?id=WDU20160001335) - */ -fun isHolidays(): Boolean = isHolidays(LocalDate.now(), Year.now().value) - -fun isHolidays(day: LocalDate, year: Int): Boolean { - return day.isAfter(getLastSchoolDay(year)) && day.isBefore(getFirstSchoolDay(year)) -} - -fun getFirstSchoolDay(year: Int): LocalDate? { - val firstSeptember = LocalDate.of(year, 9, 1) - - return when (firstSeptember.dayOfWeek) { - FRIDAY, - SATURDAY, - SUNDAY -> firstSeptember.with(TemporalAdjusters.firstInMonth(MONDAY)) - else -> { - firstSeptember - } - } -} - -fun getLastSchoolDay(year: Int): LocalDate? { - return LocalDate - .of(year, 6, 20) - .with(TemporalAdjusters.next(FRIDAY)) -} diff --git a/app/src/main/java/io/github/wulkanowy/utils/ViewPagerExtension.kt b/app/src/main/java/io/github/wulkanowy/utils/ViewPagerExtension.kt new file mode 100644 index 00000000..6a5ad880 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/utils/ViewPagerExtension.kt @@ -0,0 +1,13 @@ +package io.github.wulkanowy.utils + +import androidx.viewpager.widget.ViewPager + +inline fun ViewPager.setOnSelectPageListener(crossinline selectListener: (position: Int) -> Unit) { + addOnPageChangeListener(object : ViewPager.OnPageChangeListener { + override fun onPageSelected(position: Int) { + selectListener(position) + } + override fun onPageScrollStateChanged(state: Int) {} + override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {} + }) +} diff --git a/app/src/main/java/io/github/wulkanowy/utils/async/AbstractTask.java b/app/src/main/java/io/github/wulkanowy/utils/async/AbstractTask.java deleted file mode 100644 index 44721416..00000000 --- a/app/src/main/java/io/github/wulkanowy/utils/async/AbstractTask.java +++ /dev/null @@ -1,63 +0,0 @@ -package io.github.wulkanowy.utils.async; - -import android.os.AsyncTask; - -import timber.log.Timber; - -public class AbstractTask extends AsyncTask { - - private Exception exception; - - private AsyncListeners.OnRefreshListener onRefreshListener; - - private AsyncListeners.OnFirstLoadingListener onFirstLoadingListener; - - public void setOnFirstLoadingListener(AsyncListeners.OnFirstLoadingListener onFirstLoadingListener) { - this.onFirstLoadingListener = onFirstLoadingListener; - } - - public void setOnRefreshListener(AsyncListeners.OnRefreshListener onRefreshListener) { - this.onRefreshListener = onRefreshListener; - } - - @Override - protected Boolean doInBackground(Void... voids) { - try { - if (onFirstLoadingListener != null) { - onFirstLoadingListener.onDoInBackgroundLoading(); - } else if (onRefreshListener != null) { - onRefreshListener.onDoInBackgroundRefresh(); - } else { - Timber.e("AbstractTask does not have a listener assigned"); - } - return true; - } catch (Exception e) { - exception = e; - return false; - } - } - - @Override - protected void onCancelled() { - super.onCancelled(); - if (onFirstLoadingListener != null) { - onFirstLoadingListener.onCanceledLoadingAsync(); - } else if (onRefreshListener != null) { - onRefreshListener.onCanceledRefreshAsync(); - } else { - Timber.e("AbstractTask does not have a listener assigned"); - } - } - - @Override - protected void onPostExecute(Boolean result) { - super.onPostExecute(result); - if (onFirstLoadingListener != null) { - onFirstLoadingListener.onEndLoadingAsync(result, exception); - } else if (onRefreshListener != null) { - onRefreshListener.onEndRefreshAsync(result, exception); - } else { - Timber.e("AbstractTask does not have a listener assigned"); - } - } -} diff --git a/app/src/main/java/io/github/wulkanowy/utils/async/AsyncListeners.java b/app/src/main/java/io/github/wulkanowy/utils/async/AsyncListeners.java deleted file mode 100644 index 0d33c57c..00000000 --- a/app/src/main/java/io/github/wulkanowy/utils/async/AsyncListeners.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.github.wulkanowy.utils.async; - -public interface AsyncListeners { - - interface OnRefreshListener { - - void onDoInBackgroundRefresh() throws Exception; - - void onCanceledRefreshAsync(); - - void onEndRefreshAsync(boolean result, Exception exception); - - } - - interface OnFirstLoadingListener { - - void onDoInBackgroundLoading() throws Exception; - - void onCanceledLoadingAsync(); - - void onEndLoadingAsync(boolean result, Exception exception); - } -} diff --git a/app/src/main/java/io/github/wulkanowy/utils/security/Scrambler.kt b/app/src/main/java/io/github/wulkanowy/utils/security/Scrambler.kt index 050f474f..6c7f242c 100644 --- a/app/src/main/java/io/github/wulkanowy/utils/security/Scrambler.kt +++ b/app/src/main/java/io/github/wulkanowy/utils/security/Scrambler.kt @@ -11,8 +11,7 @@ import android.security.KeyPairGeneratorSpec import android.security.keystore.KeyGenParameterSpec import android.security.keystore.KeyProperties.* import android.util.Base64 -import android.util.Base64.DEFAULT -import org.apache.commons.lang3.StringUtils +import android.util.Base64.* import timber.log.Timber import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream @@ -21,8 +20,8 @@ import java.nio.charset.Charset import java.security.KeyPairGenerator import java.security.KeyStore import java.security.PrivateKey -import java.security.PublicKey import java.util.* +import java.util.Calendar.YEAR import javax.crypto.Cipher import javax.crypto.Cipher.DECRYPT_MODE import javax.crypto.Cipher.ENCRYPT_MODE @@ -31,142 +30,113 @@ import javax.crypto.CipherOutputStream import javax.security.auth.x500.X500Principal import kotlin.collections.ArrayList -object Scrambler { +private const val KEY_ALIAS = "USER_PASSWORD" - private const val KEY_ALIAS = "USER_PASSWORD" +private const val ALGORITHM_RSA = "RSA" - private const val ALGORITHM_RSA = "RSA" +private const val KEYSTORE_NAME = "AndroidKeyStore" - private const val KEYSTORE_NAME = "AndroidKeyStore" +private const val KEY_TRANSFORMATION_ALGORITHM = "RSA/ECB/PKCS1Padding" - private const val KEY_TRANSFORMATION_ALGORITHM = "RSA/ECB/PKCS1Padding" +private const val KEY_CIPHER_JELLY_PROVIDER = "AndroidOpenSSL" - private const val KEY_CIPHER_JELLY_PROVIDER = "AndroidOpenSSL" +private const val KEY_CIPHER_M_PROVIDER = "AndroidKeyStoreBCWorkaround" - private const val KEY_CIPHER_M_PROVIDER = "AndroidKeyStoreBCWorkaround" +private val KEY_CHARSET = Charset.forName("UTF-8") - private val KEY_CHARSET = Charset.forName("UTF-8") +private val isKeyPairExists: Boolean + get() = keyStore.getKey(KEY_ALIAS, null) != null - @JvmStatic - fun encrypt(plainText: String, context: Context): String { - if (StringUtils.isEmpty(plainText)) { - throw ScramblerException("Text to be encrypted is empty") - } +private val cipher: Cipher + get() { + return if (SDK_INT >= M) Cipher.getInstance(KEY_TRANSFORMATION_ALGORITHM, KEY_CIPHER_M_PROVIDER) + else Cipher.getInstance(KEY_TRANSFORMATION_ALGORITHM, KEY_CIPHER_JELLY_PROVIDER) + } - if (SDK_INT < JELLY_BEAN_MR2) { - return String(Base64.encode(plainText.toByteArray(KEY_CHARSET), DEFAULT), KEY_CHARSET) - } +private val keyStore: KeyStore + get() = KeyStore.getInstance(KEYSTORE_NAME).apply { load(null) } - try { - if (!isKeyPairExist()) { - generateKeyPair(context) +fun encrypt(plainText: String, context: Context): String { + if (plainText.isEmpty()) throw ScramblerException("Text to be encrypted is empty") + + if (SDK_INT < JELLY_BEAN_MR2) { + return String(Base64.encode(plainText.toByteArray(KEY_CHARSET), DEFAULT), KEY_CHARSET) + } + + return try { + if (!isKeyPairExists) generateKeyPair(context) + cipher.let { + it.init(ENCRYPT_MODE, keyStore.getCertificate(KEY_ALIAS).publicKey) + + ByteArrayOutputStream().let { output -> + CipherOutputStream(output, it).apply { + write(plainText.toByteArray(KEY_CHARSET)) + close() + } + encodeToString(output.toByteArray(), DEFAULT) } - - val cipher = getCipher() - cipher.init(ENCRYPT_MODE, getPublicKey()) - - val outputStream = ByteArrayOutputStream() - val cipherOutputStream = CipherOutputStream(outputStream, cipher) - cipherOutputStream.write(plainText.toByteArray(KEY_CHARSET)) - cipherOutputStream.close() - - return Base64.encodeToString(outputStream.toByteArray(), DEFAULT) - } catch (e: Exception) { - throw ScramblerException("An error occurred while encrypting text", e) } - + } catch (exception: Exception) { + Timber.e(exception, "An error occurred while encrypting text") + String(encode(plainText.toByteArray(KEY_CHARSET), DEFAULT), KEY_CHARSET) } - @JvmStatic - fun decrypt(cipherText: String): String { - if (StringUtils.isEmpty(cipherText)) { - throw ScramblerException("Text to be encrypted is empty") - } - - if (SDK_INT < JELLY_BEAN_MR2) { - return String(Base64.decode(cipherText.toByteArray(KEY_CHARSET), DEFAULT), KEY_CHARSET) - } - - if (!isKeyPairExist()) { - throw ScramblerException("KeyPair doesn't exist") - } - - try { - val cipher = getCipher() - cipher.init(DECRYPT_MODE, getPrivateKey()) - - val input = CipherInputStream(ByteArrayInputStream(Base64.decode(cipherText, DEFAULT)), cipher) - val values = ArrayList() - - var nextByte = 0 - while ({ nextByte = input.read(); nextByte }() != -1) { - values.add(nextByte.toByte()) - } - - val bytes = ByteArray(values.size) - for (i in bytes.indices) { - bytes[i] = values[i] - } - return String(bytes, 0, bytes.size, KEY_CHARSET) - } catch (e: Exception) { - throw ScramblerException("An error occurred while decrypting text", e) - } - - } - - private fun getKeyStoreInstance(): KeyStore { - val keyStore = KeyStore.getInstance(KEYSTORE_NAME) - keyStore.load(null) - return keyStore - } - - private fun getPublicKey(): PublicKey = - (getKeyStoreInstance().getEntry(KEY_ALIAS, null) as KeyStore.PrivateKeyEntry) - .certificate.publicKey - - - private fun getPrivateKey(): PrivateKey = - (getKeyStoreInstance().getEntry(KEY_ALIAS, null) as KeyStore.PrivateKeyEntry).privateKey - - - private fun getCipher(): Cipher { - if (SDK_INT >= M) { - return Cipher.getInstance(KEY_TRANSFORMATION_ALGORITHM, KEY_CIPHER_M_PROVIDER) - } - - return Cipher.getInstance(KEY_TRANSFORMATION_ALGORITHM, KEY_CIPHER_JELLY_PROVIDER) - } - - @TargetApi(JELLY_BEAN_MR2) - private fun generateKeyPair(context: Context) { - val spec = if (SDK_INT >= M) { - KeyGenParameterSpec.Builder(KEY_ALIAS, PURPOSE_DECRYPT or PURPOSE_ENCRYPT) - .setDigests(DIGEST_SHA256, DIGEST_SHA512) - .setCertificateSubject(X500Principal("CN=Wulkanowy")) - .setEncryptionPaddings(ENCRYPTION_PADDING_RSA_PKCS1) - .setSignaturePaddings(SIGNATURE_PADDING_RSA_PKCS1) - .setCertificateSerialNumber(BigInteger.TEN) - .build() - } else { - val start = Calendar.getInstance() - val end = Calendar.getInstance() - end.add(Calendar.YEAR, 99) - - KeyPairGeneratorSpec.Builder(context) - .setAlias(KEY_ALIAS) - .setSubject(X500Principal("CN=Wulkanowy")) - .setSerialNumber(BigInteger.TEN) - .setStartDate(start.time) - .setEndDate(end.time) - .build() - } - - val generator = KeyPairGenerator.getInstance(ALGORITHM_RSA, KEYSTORE_NAME) - generator.initialize(spec) - generator.generateKeyPair() - - Timber.i("A new KeyPair has been generated") - } - - private fun isKeyPairExist(): Boolean = getKeyStoreInstance().getKey(KEY_ALIAS, null) != null +} + +fun decrypt(cipherText: String): String { + if (cipherText.isEmpty()) throw ScramblerException("Text to be encrypted is empty") + + if (SDK_INT < JELLY_BEAN_MR2 || cipherText.length < 250) { + return String(decode(cipherText.toByteArray(KEY_CHARSET), DEFAULT), KEY_CHARSET) + } + + if (!isKeyPairExists) throw ScramblerException("KeyPair doesn't exist") + + return try { + cipher.let { + it.init(DECRYPT_MODE, (keyStore.getKey(KEY_ALIAS, null) as PrivateKey)) + + CipherInputStream(ByteArrayInputStream(decode(cipherText, DEFAULT)), it).let { input -> + val values = ArrayList() + var nextByte = 0 + while ({ nextByte = input.read(); nextByte }() != -1) { + values.add(nextByte.toByte()) + } + val bytes = ByteArray(values.size) + for (i in bytes.indices) { + bytes[i] = values[i] + } + String(bytes, 0, bytes.size, KEY_CHARSET) + } + } + } catch (e: Exception) { + throw ScramblerException("An error occurred while decrypting text", e) + } +} + +@TargetApi(JELLY_BEAN_MR2) +private fun generateKeyPair(context: Context) { + (if (SDK_INT >= M) { + KeyGenParameterSpec.Builder(KEY_ALIAS, PURPOSE_DECRYPT or PURPOSE_ENCRYPT) + .setDigests(DIGEST_SHA256, DIGEST_SHA512) + .setCertificateSubject(X500Principal("CN=Wulkanowy")) + .setEncryptionPaddings(ENCRYPTION_PADDING_RSA_PKCS1) + .setSignaturePaddings(SIGNATURE_PADDING_RSA_PKCS1) + .setCertificateSerialNumber(BigInteger.TEN) + .build() + } else { + KeyPairGeneratorSpec.Builder(context) + .setAlias(KEY_ALIAS) + .setSubject(X500Principal("CN=Wulkanowy")) + .setSerialNumber(BigInteger.TEN) + .setStartDate(Calendar.getInstance().time) + .setEndDate(Calendar.getInstance().apply { add(YEAR, 99) }.time) + .build() + }).let { + KeyPairGenerator.getInstance(ALGORITHM_RSA, KEYSTORE_NAME).apply { + initialize(it) + genKeyPair() + } + } + Timber.i("A new KeyPair has been generated") } diff --git a/app/src/main/res/drawable-hdpi/ic_notify_grade.png b/app/src/main/res/drawable-hdpi/ic_stat_notify_grade.png similarity index 100% rename from app/src/main/res/drawable-hdpi/ic_notify_grade.png rename to app/src/main/res/drawable-hdpi/ic_stat_notify_grade.png diff --git a/app/src/main/res/drawable-mdpi/ic_notify_grade.png b/app/src/main/res/drawable-mdpi/ic_stat_notify_grade.png similarity index 100% rename from app/src/main/res/drawable-mdpi/ic_notify_grade.png rename to app/src/main/res/drawable-mdpi/ic_stat_notify_grade.png diff --git a/app/src/main/res/drawable-night/ic_border.xml b/app/src/main/res/drawable-night/ic_all_divider.xml similarity index 100% rename from app/src/main/res/drawable-night/ic_border.xml rename to app/src/main/res/drawable-night/ic_all_divider.xml diff --git a/app/src/main/res/drawable-v23/img_splash_logo.png b/app/src/main/res/drawable-v23/img_splash_logo.png new file mode 100644 index 00000000..249722ba Binary files /dev/null and b/app/src/main/res/drawable-v23/img_splash_logo.png differ diff --git a/app/src/main/res/drawable/splash_background.xml b/app/src/main/res/drawable-v23/layer_splash_background.xml similarity index 53% rename from app/src/main/res/drawable/splash_background.xml rename to app/src/main/res/drawable-v23/layer_splash_background.xml index 0b79b672..ca7afbe1 100644 --- a/app/src/main/res/drawable/splash_background.xml +++ b/app/src/main/res/drawable-v23/layer_splash_background.xml @@ -1,8 +1,12 @@ - + diff --git a/app/src/main/res/drawable-v23/splash_background.xml b/app/src/main/res/drawable-v23/splash_background.xml deleted file mode 100644 index 611bb2a7..00000000 --- a/app/src/main/res/drawable-v23/splash_background.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - diff --git a/app/src/main/res/drawable-xhdpi/ic_notify_grade.png b/app/src/main/res/drawable-xhdpi/ic_stat_notify_grade.png similarity index 100% rename from app/src/main/res/drawable-xhdpi/ic_notify_grade.png rename to app/src/main/res/drawable-xhdpi/ic_stat_notify_grade.png diff --git a/app/src/main/res/drawable-xxhdpi/ic_notify_grade.png b/app/src/main/res/drawable-xxhdpi/ic_stat_notify_grade.png similarity index 100% rename from app/src/main/res/drawable-xxhdpi/ic_notify_grade.png rename to app/src/main/res/drawable-xxhdpi/ic_stat_notify_grade.png diff --git a/app/src/main/res/drawable/ic_border.xml b/app/src/main/res/drawable/ic_all_divider.xml similarity index 100% rename from app/src/main/res/drawable/ic_border.xml rename to app/src/main/res/drawable/ic_all_divider.xml diff --git a/app/src/main/res/drawable/ic_exclamation_24dp.xml b/app/src/main/res/drawable/ic_all_note_24dp.xml similarity index 96% rename from app/src/main/res/drawable/ic_exclamation_24dp.xml rename to app/src/main/res/drawable/ic_all_note_24dp.xml index 14950458..988df22c 100644 --- a/app/src/main/res/drawable/ic_exclamation_24dp.xml +++ b/app/src/main/res/drawable/ic_all_note_24dp.xml @@ -7,4 +7,4 @@ - \ No newline at end of file + diff --git a/app/src/main/res/drawable/ic_alert_24dp.xml b/app/src/main/res/drawable/ic_all_round_note_24dp.xml similarity index 97% rename from app/src/main/res/drawable/ic_alert_24dp.xml rename to app/src/main/res/drawable/ic_all_round_note_24dp.xml index 1c41b556..f4f1f2c5 100644 --- a/app/src/main/res/drawable/ic_alert_24dp.xml +++ b/app/src/main/res/drawable/ic_all_round_note_24dp.xml @@ -7,4 +7,4 @@ android:fillColor="@color/colorPrimary" android:pathData="M13 13h-2V7h2m0 10h-2v-2h2M12 2A10 10 0 0 0 2 12a10 10 0 0 0 10 10 10 10 0 0 0 10-10A10 10 0 0 0 12 2z" /> - \ No newline at end of file + diff --git a/app/src/main/res/drawable/ic_login_person_24px.xml b/app/src/main/res/drawable/ic_login_person_24px.xml new file mode 100644 index 00000000..c300d6e0 --- /dev/null +++ b/app/src/main/res/drawable/ic_login_person_24px.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_action_menu_semester.xml b/app/src/main/res/drawable/ic_menu_grade_semester_24dp.xml similarity index 100% rename from app/src/main/res/drawable/ic_action_menu_semester.xml rename to app/src/main/res/drawable/ic_menu_grade_semester_24dp.xml diff --git a/app/src/main/res/drawable/ic_menu_attendance_24dp.xml b/app/src/main/res/drawable/ic_menu_main_attendance_24dp.xml similarity index 100% rename from app/src/main/res/drawable/ic_menu_attendance_24dp.xml rename to app/src/main/res/drawable/ic_menu_main_attendance_24dp.xml diff --git a/app/src/main/res/drawable/ic_menu_exams_24dp.xml b/app/src/main/res/drawable/ic_menu_main_exam_24dp.xml similarity index 100% rename from app/src/main/res/drawable/ic_menu_exams_24dp.xml rename to app/src/main/res/drawable/ic_menu_main_exam_24dp.xml diff --git a/app/src/main/res/drawable/ic_menu_grade_26dp.xml b/app/src/main/res/drawable/ic_menu_main_grade_26dp.xml similarity index 100% rename from app/src/main/res/drawable/ic_menu_grade_26dp.xml rename to app/src/main/res/drawable/ic_menu_main_grade_26dp.xml diff --git a/app/src/main/res/drawable/ic_menu_main_more_24dp.xml b/app/src/main/res/drawable/ic_menu_main_more_24dp.xml new file mode 100644 index 00000000..26932b2b --- /dev/null +++ b/app/src/main/res/drawable/ic_menu_main_more_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_menu_timetable_24dp.xml b/app/src/main/res/drawable/ic_menu_main_timetable_24dp.xml similarity index 91% rename from app/src/main/res/drawable/ic_menu_timetable_24dp.xml rename to app/src/main/res/drawable/ic_menu_main_timetable_24dp.xml index 63880977..213c7ea7 100644 --- a/app/src/main/res/drawable/ic_menu_timetable_24dp.xml +++ b/app/src/main/res/drawable/ic_menu_main_timetable_24dp.xml @@ -1,4 +1,3 @@ - - - - diff --git a/app/src/main/res/drawable/ic_action_menu_summary.xml b/app/src/main/res/drawable/ic_more_about_24dp.xml similarity index 85% rename from app/src/main/res/drawable/ic_action_menu_summary.xml rename to app/src/main/res/drawable/ic_more_about_24dp.xml index 1b2a93b8..b0f56132 100644 --- a/app/src/main/res/drawable/ic_action_menu_summary.xml +++ b/app/src/main/res/drawable/ic_more_about_24dp.xml @@ -4,10 +4,10 @@ android:viewportHeight="24" android:viewportWidth="24"> diff --git a/app/src/main/res/drawable/ic_more_settings_24dp.xml b/app/src/main/res/drawable/ic_more_settings_24dp.xml new file mode 100644 index 00000000..9e0bd837 --- /dev/null +++ b/app/src/main/res/drawable/ic_more_settings_24dp.xml @@ -0,0 +1,16 @@ + + + diff --git a/app/src/main/res/drawable/ic_swap_30dp.xml b/app/src/main/res/drawable/ic_timetable_swap_30dp.xml similarity index 100% rename from app/src/main/res/drawable/ic_swap_30dp.xml rename to app/src/main/res/drawable/ic_timetable_swap_30dp.xml diff --git a/app/src/main/res/drawable/ic_widget_chevron_24dp.png b/app/src/main/res/drawable/ic_widget_chevron_24dp.png new file mode 100644 index 00000000..34345521 Binary files /dev/null and b/app/src/main/res/drawable/ic_widget_chevron_24dp.png differ diff --git a/app/src/main/res/drawable/img_splash_512px.png b/app/src/main/res/drawable/img_splash_512px.png deleted file mode 100644 index 9d8f403c..00000000 Binary files a/app/src/main/res/drawable/img_splash_512px.png and /dev/null differ diff --git a/app/src/main/res/drawable/img_splash_logo.png b/app/src/main/res/drawable/img_splash_logo.png new file mode 100644 index 00000000..28dbd51d Binary files /dev/null and b/app/src/main/res/drawable/img_splash_logo.png differ diff --git a/app/src/main/res/drawable/img_timetable_widget_preview.png b/app/src/main/res/drawable/img_timetable_widget_preview.png new file mode 100644 index 00000000..60a35ab6 Binary files /dev/null and b/app/src/main/res/drawable/img_timetable_widget_preview.png differ diff --git a/app/src/main/res/drawable-v15/splash_background.xml b/app/src/main/res/drawable/layer_splash_background.xml similarity index 64% rename from app/src/main/res/drawable-v15/splash_background.xml rename to app/src/main/res/drawable/layer_splash_background.xml index c58c374a..6509b2f8 100644 --- a/app/src/main/res/drawable-v15/splash_background.xml +++ b/app/src/main/res/drawable/layer_splash_background.xml @@ -1,14 +1,12 @@ - - + android:gravity="left|right|top|bottom" + android:src="@drawable/img_splash_logo" /> diff --git a/app/src/main/res/drawable/widget_timetable_preview.png b/app/src/main/res/drawable/widget_timetable_preview.png deleted file mode 100644 index d9f3538c..00000000 Binary files a/app/src/main/res/drawable/widget_timetable_preview.png and /dev/null differ diff --git a/app/src/main/res/layout/activity_login.xml b/app/src/main/res/layout/activity_login.xml index 4a6f08b2..1a86fa92 100644 --- a/app/src/main/res/layout/activity_login.xml +++ b/app/src/main/res/layout/activity_login.xml @@ -1,137 +1,10 @@ - + android:layout_height="match_parent"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -