From a90d5cb9c35b2bfe60d1f64687c99c934107dd3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=C5=82=20Borcz?= Date: Wed, 22 Aug 2018 22:31:17 +0200 Subject: [PATCH] Refactor login module (#151) --- .circleci/config.yml | 3 +- .../java/io/github/wulkanowy/api/Client.java | 17 + .../java/io/github/wulkanowy/api/Vulcan.java | 9 + .../io/github/wulkanowy/api/login/Login.java | 26 +- .../github/wulkanowy/api/login/LoginTest.java | 9 +- app/build.gradle | 30 +- app/proguard-multidex-rules.pro | 3 + .../data/db/dao/entities/AccountTest.java | 18 - .../db/dao/entities/AttendanceLessonTest.java | 25 -- .../data/db/dao/entities/DayTest.java | 19 - .../data/db/dao/entities/DiaryTest.java | 19 - .../data/db/dao/entities/ExamTest.java | 18 - .../data/db/dao/entities/GradeTest.java | 20 -- .../data/db/dao/entities/SchoolTest.java | 22 -- .../data/db/dao/entities/SemesterTest.java | 21 -- .../data/db/dao/entities/StudentTest.java | 21 -- .../data/db/dao/entities/SubjectTest.java | 18 - .../data/db/dao/entities/SymbolTest.java | 21 -- .../db/dao/entities/TimetableLessonTest.java | 24 -- .../data/db/dao/entities/WeekTest.java | 18 - .../repositories/local/StudentLocalTest.kt | 49 +++ app/src/main/AndroidManifest.xml | 2 +- .../java/io/github/wulkanowy/WulkanowyApp.kt | 32 +- .../io/github/wulkanowy/data/ErrorHandler.kt | 31 ++ .../io/github/wulkanowy/data/Repository.java | 56 --- .../wulkanowy/data/RepositoryContract.java | 22 -- .../github/wulkanowy/data/RepositoryModule.kt | 44 +++ .../github/wulkanowy/data/db/AppDatabase.kt | 18 + .../wulkanowy/data/db/SharedPrefHelper.kt | 17 + .../wulkanowy/data/db/dao/DbContract.java | 37 -- .../wulkanowy/data/db/dao/DbHelper.java | 102 ------ .../wulkanowy/data/db/dao/DbRepository.java | 132 ------- .../wulkanowy/data/db/dao/StudentDao.kt | 18 + .../data/db/dao/entities/Account.java | 153 -------- .../db/dao/entities/AttendanceLesson.java | 254 -------------- .../wulkanowy/data/db/dao/entities/Day.java | 263 -------------- .../wulkanowy/data/db/dao/entities/Diary.java | 177 ---------- .../wulkanowy/data/db/dao/entities/Exam.java | 177 ---------- .../wulkanowy/data/db/dao/entities/Grade.java | 293 ---------------- .../data/db/dao/entities/School.java | 179 ---------- .../data/db/dao/entities/Semester.java | 208 ----------- .../data/db/dao/entities/Student.java | 178 ---------- .../data/db/dao/entities/Subject.java | 176 ---------- .../data/db/dao/entities/Symbol.java | 175 --------- .../data/db/dao/entities/TimetableLesson.java | 332 ------------------ .../wulkanowy/data/db/dao/entities/Week.java | 194 ---------- .../data/db/dao/migrations/Migration23.java | 114 ------ .../data/db/dao/migrations/Migration26.java | 20 -- .../data/db/dao/migrations/Migration27.java | 24 -- .../data/db/dao/migrations/Migration28.java | 20 -- .../data/db/dao/migrations/Migration29.kt | 60 ---- .../wulkanowy/data/db/entities/Student.kt | 32 ++ .../data/db/resources/ResourcesContract.java | 17 - .../db/resources/ResourcesRepository.java | 84 ----- .../data/db/shared/SharedPrefContract.java | 35 -- .../data/db/shared/SharedPrefRepository.java | 102 ------ .../data/repositories/StudentRepository.kt | 43 +++ .../data/repositories/local/StudentLocal.kt | 35 ++ .../data/repositories/remote/StudentRemote.kt | 55 +++ .../wulkanowy/data/sync/AccountSync.java | 197 ----------- .../wulkanowy/data/sync/AttendanceSync.java | 140 -------- .../github/wulkanowy/data/sync/ExamsSync.java | 135 ------- .../github/wulkanowy/data/sync/GradeSync.java | 81 ----- .../data/sync/NotRegisteredUserException.java | 8 - .../wulkanowy/data/sync/SubjectSync.java | 66 ---- .../wulkanowy/data/sync/SyncContract.java | 41 --- .../wulkanowy/data/sync/SyncRepository.java | 123 ------- .../wulkanowy/data/sync/TimetableSync.java | 161 --------- .../io/github/wulkanowy/di/AppComponent.java | 20 -- .../io/github/wulkanowy/di/AppComponent.kt | 19 + .../io/github/wulkanowy/di/AppModule.java | 78 ---- .../java/io/github/wulkanowy/di/AppModule.kt | 22 ++ .../io/github/wulkanowy/di/BuilderModule.java | 39 -- .../io/github/wulkanowy/di/BuilderModule.kt | 25 ++ .../wulkanowy/di/scopes/PerActivity.java | 11 - .../github/wulkanowy/di/scopes/PerActivity.kt | 7 + .../wulkanowy/di/scopes/PerChildFragment.java | 11 - .../wulkanowy/di/scopes/PerChildFragment.kt | 7 + .../wulkanowy/di/scopes/PerFragment.java | 11 - .../github/wulkanowy/di/scopes/PerFragment.kt | 7 + .../wulkanowy/services/jobs/SyncJob.java | 148 -------- .../services/notifies/GradeNotify.java | 36 -- .../notifies/NotificationService.java | 57 --- .../widgets/TimetableWidgetServices.java | 22 -- .../wulkanowy/ui/base/BaseActivity.java | 59 ---- .../github/wulkanowy/ui/base/BaseActivity.kt | 33 ++ .../wulkanowy/ui/base/BaseContract.java | 22 -- .../wulkanowy/ui/base/BaseFragment.java | 56 --- .../github/wulkanowy/ui/base/BaseFragment.kt | 24 ++ .../wulkanowy/ui/base/BasePagerAdapter.java | 47 --- .../wulkanowy/ui/base/BasePagerAdapter.kt | 30 ++ .../wulkanowy/ui/base/BasePresenter.java | 41 --- .../github/wulkanowy/ui/base/BasePresenter.kt | 25 ++ .../io/github/wulkanowy/ui/base/BaseView.kt | 8 + .../wulkanowy/ui/login/LoginActivity.java | 236 ------------- .../wulkanowy/ui/login/LoginActivity.kt | 70 ++++ .../wulkanowy/ui/login/LoginContract.java | 54 --- .../wulkanowy/ui/login/LoginErrorHandler.kt | 23 ++ .../wulkanowy/ui/login/LoginModule.java | 13 - .../github/wulkanowy/ui/login/LoginModule.kt | 39 ++ .../wulkanowy/ui/login/LoginPresenter.java | 178 ---------- .../wulkanowy/ui/login/LoginPresenter.kt | 34 ++ .../wulkanowy/ui/login/LoginSwitchListener.kt | 6 + .../github/wulkanowy/ui/login/LoginTask.java | 60 ---- .../io/github/wulkanowy/ui/login/LoginView.kt | 16 + .../ui/login/form/LoginFormFragment.kt | 139 ++++++++ .../ui/login/form/LoginFormPresenter.kt | 88 +++++ .../wulkanowy/ui/login/form/LoginFormView.kt | 34 ++ .../ui/login/options/LoginOptionsFragment.kt | 67 ++++ .../ui/login/options/LoginOptionsItem.kt | 54 +++ .../ui/login/options/LoginOptionsModule.kt | 14 + .../ui/login/options/LoginOptionsPresenter.kt | 45 +++ .../ui/login/options/LoginOptionsView.kt | 16 + .../wulkanowy/ui/main/MainActivity.java | 170 --------- .../github/wulkanowy/ui/main/MainActivity.kt | 13 + .../wulkanowy/ui/main/MainContract.java | 34 -- .../github/wulkanowy/ui/main/MainModule.java | 50 --- .../wulkanowy/ui/main/MainPresenter.java | 63 ---- .../ui/main/OnFragmentIsReadyListener.java | 6 - .../main/attendance/AttendanceContract.java | 33 -- .../attendance/AttendanceDialogFragment.java | 91 ----- .../main/attendance/AttendanceFragment.java | 102 ------ .../ui/main/attendance/AttendanceModule.java | 32 -- .../main/attendance/AttendancePresenter.java | 108 ------ .../main/attendance/tab/AttendanceHeader.java | 151 -------- .../attendance/tab/AttendanceSubItem.java | 122 ------- .../attendance/tab/AttendanceTabContract.java | 30 -- .../attendance/tab/AttendanceTabFragment.java | 129 ------- .../attendance/tab/AttendanceTabModule.java | 21 -- .../tab/AttendanceTabPresenter.java | 194 ---------- .../ui/main/exams/ExamsContract.java | 33 -- .../ui/main/exams/ExamsDialogFragment.java | 81 ----- .../ui/main/exams/ExamsFragment.java | 100 ------ .../wulkanowy/ui/main/exams/ExamsModule.java | 32 -- .../ui/main/exams/ExamsPresenter.java | 107 ------ .../ui/main/exams/tab/ExamsHeader.java | 82 ----- .../ui/main/exams/tab/ExamsSubItem.java | 109 ------ .../ui/main/exams/tab/ExamsTabContract.java | 30 -- .../ui/main/exams/tab/ExamsTabFragment.java | 126 ------- .../ui/main/exams/tab/ExamsTabModule.java | 21 -- .../ui/main/exams/tab/ExamsTabPresenter.java | 167 --------- .../ui/main/grades/GradesContract.java | 49 --- .../ui/main/grades/GradesDialogFragment.java | 117 ------ .../ui/main/grades/GradesFragment.java | 213 ----------- .../ui/main/grades/GradesHeader.java | 199 ----------- .../ui/main/grades/GradesModule.java | 23 -- .../ui/main/grades/GradesPresenter.java | 230 ------------ .../ui/main/grades/GradesSubItem.java | 162 --------- .../ui/main/grades/GradesSummaryHeader.java | 87 ----- .../ui/main/grades/GradesSummarySubItem.java | 84 ----- .../ui/main/settings/SettingsFragment.java | 181 ---------- .../ui/main/timetable/TimetableContract.java | 33 -- .../timetable/TimetableDialogFragment.java | 127 ------- .../ui/main/timetable/TimetableFragment.java | 101 ------ .../ui/main/timetable/TimetableModule.java | 32 -- .../ui/main/timetable/TimetablePresenter.java | 107 ------ .../main/timetable/tab/TimetableHeader.java | 136 ------- .../main/timetable/tab/TimetableSubItem.java | 144 -------- .../timetable/tab/TimetableTabContract.java | 34 -- .../timetable/tab/TimetableTabFragment.java | 143 -------- .../timetable/tab/TimetableTabModule.java | 21 -- .../timetable/tab/TimetableTabPresenter.java | 200 ----------- .../wulkanowy/ui/splash/SplashActivity.java | 50 --- .../wulkanowy/ui/splash/SplashActivity.kt | 32 ++ .../wulkanowy/ui/splash/SplashContract.java | 20 -- .../wulkanowy/ui/splash/SplashModule.java | 13 - .../wulkanowy/ui/splash/SplashPresenter.java | 30 -- .../wulkanowy/ui/splash/SplashPresenter.kt | 16 + .../github/wulkanowy/ui/splash/SplashView.kt | 10 + .../ui/widgets/TimetableWidgetFactory.java | 140 -------- .../ui/widgets/TimetableWidgetProvider.java | 112 ------ .../github/wulkanowy/utils/AppConstant.java | 27 -- .../io/github/wulkanowy/utils/AppConstant.kt | 11 + .../github/wulkanowy/utils/CommonUtils.java | 10 - .../wulkanowy/utils/DataObjectConverter.java | 202 ----------- .../wulkanowy/utils/EntitiesCompare.java | 42 --- .../io/github/wulkanowy/utils/GradeUtils.java | 10 +- .../github/wulkanowy/utils/KeyboardUtils.java | 33 -- .../github/wulkanowy/utils/LoggerUtils.java | 2 +- .../github/wulkanowy/utils/NetworkUtils.java | 18 - .../io/github/wulkanowy/utils/TimeUtils.kt | 2 +- .../wulkanowy/utils/async/AbstractTask.java | 63 ---- .../wulkanowy/utils/async/AsyncListeners.java | 23 -- .../utils/extension/ActivityExtension.kt | 18 + .../extension/FlexibleAdapterExtension.kt | 11 + .../utils/extension/ViewPagerExtension.kt | 14 + .../utils/schedulers/SchedulersManager.kt | 10 + .../utils/schedulers/SchedulersProvider.kt | 12 + .../wulkanowy/utils/security/Scrambler.kt | 35 +- .../res/drawable/ic_login_person_24px.xml | 9 + app/src/main/res/layout/activity_login.xml | 138 +------- .../main/res/layout/fragment_login_form.xml | 129 +++++++ .../res/layout/fragment_login_opions_item.xml | 50 +++ .../res/layout/fragment_login_options.xml | 37 ++ app/src/main/res/values-pl/strings.xml | 5 +- app/src/main/res/values/strings.xml | 9 +- .../io/github/wulkanowy/TestSchedulers.kt | 13 + .../data/db/dao/entities/GradeTest.java | 36 -- .../repositories/remote/StudentRemoteTest.kt | 64 ++++ .../wulkanowy/ui/login/LoginPresenterTest.kt | 66 ++++ .../ui/login/form/LoginFormPresenterTest.kt | 152 ++++++++ .../options/LoginOptionsPresenterTest.kt | 78 ++++ .../ui/splash/SplashPresenterTest.kt | 44 +++ .../utils/DataObjectConverterTest.java | 80 ----- .../wulkanowy/utils/EntitiesCompareTest.java | 105 ------ .../wulkanowy/utils/GradeUtilsTest.java | 85 ----- .../wulkanowy/utils/NetworkUtilsTest.java | 42 --- build.gradle | 7 +- 208 files changed, 2101 insertions(+), 11998 deletions(-) create mode 100644 app/proguard-multidex-rules.pro delete mode 100644 app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/AccountTest.java delete mode 100644 app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/AttendanceLessonTest.java delete mode 100644 app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/DayTest.java delete mode 100644 app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/DiaryTest.java delete mode 100644 app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/ExamTest.java delete mode 100644 app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/GradeTest.java delete mode 100644 app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SchoolTest.java delete mode 100644 app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SemesterTest.java delete mode 100644 app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/StudentTest.java delete mode 100644 app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SubjectTest.java delete mode 100644 app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/SymbolTest.java delete mode 100644 app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/TimetableLessonTest.java delete mode 100644 app/src/androidTest/java/io/github/wulkanowy/data/db/dao/entities/WeekTest.java create mode 100644 app/src/androidTest/java/io/github/wulkanowy/data/repositories/local/StudentLocalTest.kt create mode 100644 app/src/main/java/io/github/wulkanowy/data/ErrorHandler.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/data/Repository.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/RepositoryContract.java create mode 100644 app/src/main/java/io/github/wulkanowy/data/RepositoryModule.kt create mode 100644 app/src/main/java/io/github/wulkanowy/data/db/AppDatabase.kt create mode 100644 app/src/main/java/io/github/wulkanowy/data/db/SharedPrefHelper.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/DbContract.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/DbHelper.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/DbRepository.java create mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/StudentDao.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Account.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/entities/AttendanceLesson.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Day.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Diary.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Exam.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Grade.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/entities/School.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Semester.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Student.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Subject.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Symbol.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/entities/TimetableLesson.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/entities/Week.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration23.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration26.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration27.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration28.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/dao/migrations/Migration29.kt create mode 100644 app/src/main/java/io/github/wulkanowy/data/db/entities/Student.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/resources/ResourcesContract.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/resources/ResourcesRepository.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/shared/SharedPrefContract.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/db/shared/SharedPrefRepository.java create mode 100644 app/src/main/java/io/github/wulkanowy/data/repositories/StudentRepository.kt create mode 100644 app/src/main/java/io/github/wulkanowy/data/repositories/local/StudentLocal.kt create mode 100644 app/src/main/java/io/github/wulkanowy/data/repositories/remote/StudentRemote.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/data/sync/AccountSync.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/sync/AttendanceSync.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/sync/ExamsSync.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/sync/GradeSync.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/sync/NotRegisteredUserException.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/sync/SubjectSync.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/sync/SyncContract.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/sync/SyncRepository.java delete mode 100644 app/src/main/java/io/github/wulkanowy/data/sync/TimetableSync.java delete mode 100644 app/src/main/java/io/github/wulkanowy/di/AppComponent.java create mode 100644 app/src/main/java/io/github/wulkanowy/di/AppComponent.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/di/AppModule.java create mode 100644 app/src/main/java/io/github/wulkanowy/di/AppModule.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/di/BuilderModule.java create mode 100644 app/src/main/java/io/github/wulkanowy/di/BuilderModule.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/di/scopes/PerActivity.java create mode 100644 app/src/main/java/io/github/wulkanowy/di/scopes/PerActivity.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/di/scopes/PerChildFragment.java create mode 100644 app/src/main/java/io/github/wulkanowy/di/scopes/PerChildFragment.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/di/scopes/PerFragment.java create mode 100644 app/src/main/java/io/github/wulkanowy/di/scopes/PerFragment.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/services/jobs/SyncJob.java delete mode 100644 app/src/main/java/io/github/wulkanowy/services/notifies/GradeNotify.java delete mode 100644 app/src/main/java/io/github/wulkanowy/services/notifies/NotificationService.java delete mode 100644 app/src/main/java/io/github/wulkanowy/services/widgets/TimetableWidgetServices.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/base/BaseActivity.java create mode 100644 app/src/main/java/io/github/wulkanowy/ui/base/BaseActivity.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/base/BaseContract.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/base/BaseFragment.java create mode 100644 app/src/main/java/io/github/wulkanowy/ui/base/BaseFragment.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/base/BasePagerAdapter.java create mode 100644 app/src/main/java/io/github/wulkanowy/ui/base/BasePagerAdapter.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/base/BasePresenter.java create mode 100644 app/src/main/java/io/github/wulkanowy/ui/base/BasePresenter.kt create mode 100644 app/src/main/java/io/github/wulkanowy/ui/base/BaseView.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/LoginActivity.java create mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/LoginActivity.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/LoginContract.java create mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/LoginErrorHandler.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/LoginModule.java create mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/LoginModule.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/LoginPresenter.java create mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/LoginPresenter.kt create mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/LoginSwitchListener.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/LoginTask.java create mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/LoginView.kt create mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/form/LoginFormFragment.kt create mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/form/LoginFormPresenter.kt create mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/form/LoginFormView.kt create mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsFragment.kt create mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsItem.kt create mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsModule.kt create mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsPresenter.kt create mode 100644 app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsView.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/MainActivity.java create mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/MainActivity.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/MainContract.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/MainModule.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/MainPresenter.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/OnFragmentIsReadyListener.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendanceContract.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendanceDialogFragment.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendanceFragment.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendanceModule.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/attendance/AttendancePresenter.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceHeader.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceSubItem.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceTabContract.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceTabFragment.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceTabModule.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/attendance/tab/AttendanceTabPresenter.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsContract.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsDialogFragment.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsFragment.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsModule.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/exams/ExamsPresenter.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsHeader.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsSubItem.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsTabContract.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsTabFragment.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsTabModule.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/exams/tab/ExamsTabPresenter.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesContract.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesDialogFragment.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesFragment.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesHeader.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesModule.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesPresenter.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesSubItem.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesSummaryHeader.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/grades/GradesSummarySubItem.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/settings/SettingsFragment.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetableContract.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetableDialogFragment.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetableFragment.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetableModule.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/timetable/TimetablePresenter.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableHeader.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableSubItem.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableTabContract.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableTabFragment.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableTabModule.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/main/timetable/tab/TimetableTabPresenter.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/splash/SplashActivity.java create mode 100644 app/src/main/java/io/github/wulkanowy/ui/splash/SplashActivity.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/splash/SplashContract.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/splash/SplashModule.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/splash/SplashPresenter.java create mode 100644 app/src/main/java/io/github/wulkanowy/ui/splash/SplashPresenter.kt create mode 100644 app/src/main/java/io/github/wulkanowy/ui/splash/SplashView.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/widgets/TimetableWidgetFactory.java delete mode 100644 app/src/main/java/io/github/wulkanowy/ui/widgets/TimetableWidgetProvider.java delete mode 100644 app/src/main/java/io/github/wulkanowy/utils/AppConstant.java create mode 100644 app/src/main/java/io/github/wulkanowy/utils/AppConstant.kt delete mode 100644 app/src/main/java/io/github/wulkanowy/utils/DataObjectConverter.java delete mode 100644 app/src/main/java/io/github/wulkanowy/utils/EntitiesCompare.java delete mode 100644 app/src/main/java/io/github/wulkanowy/utils/KeyboardUtils.java delete mode 100644 app/src/main/java/io/github/wulkanowy/utils/NetworkUtils.java delete mode 100644 app/src/main/java/io/github/wulkanowy/utils/async/AbstractTask.java delete mode 100644 app/src/main/java/io/github/wulkanowy/utils/async/AsyncListeners.java create mode 100644 app/src/main/java/io/github/wulkanowy/utils/extension/ActivityExtension.kt create mode 100644 app/src/main/java/io/github/wulkanowy/utils/extension/FlexibleAdapterExtension.kt create mode 100644 app/src/main/java/io/github/wulkanowy/utils/extension/ViewPagerExtension.kt create mode 100644 app/src/main/java/io/github/wulkanowy/utils/schedulers/SchedulersManager.kt create mode 100644 app/src/main/java/io/github/wulkanowy/utils/schedulers/SchedulersProvider.kt create mode 100644 app/src/main/res/drawable/ic_login_person_24px.xml create mode 100644 app/src/main/res/layout/fragment_login_form.xml create mode 100644 app/src/main/res/layout/fragment_login_opions_item.xml create mode 100644 app/src/main/res/layout/fragment_login_options.xml create mode 100644 app/src/test/java/io/github/wulkanowy/TestSchedulers.kt delete mode 100644 app/src/test/java/io/github/wulkanowy/data/db/dao/entities/GradeTest.java create mode 100644 app/src/test/java/io/github/wulkanowy/data/repositories/remote/StudentRemoteTest.kt create mode 100644 app/src/test/java/io/github/wulkanowy/ui/login/LoginPresenterTest.kt create mode 100644 app/src/test/java/io/github/wulkanowy/ui/login/form/LoginFormPresenterTest.kt create mode 100644 app/src/test/java/io/github/wulkanowy/ui/login/options/LoginOptionsPresenterTest.kt create mode 100644 app/src/test/java/io/github/wulkanowy/ui/splash/SplashPresenterTest.kt delete mode 100644 app/src/test/java/io/github/wulkanowy/utils/DataObjectConverterTest.java delete mode 100644 app/src/test/java/io/github/wulkanowy/utils/EntitiesCompareTest.java delete mode 100644 app/src/test/java/io/github/wulkanowy/utils/GradeUtilsTest.java delete mode 100644 app/src/test/java/io/github/wulkanowy/utils/NetworkUtilsTest.java diff --git a/.circleci/config.yml b/.circleci/config.yml index c807f018..460a6607 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -139,6 +139,7 @@ jobs: - 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 @@ -230,4 +231,4 @@ workflows: tags: only: /\d+\.\d+\.\d+/ branches: - ignore: /.*/ + ignore: /.*/ \ No newline at end of file diff --git a/api/src/main/java/io/github/wulkanowy/api/Client.java b/api/src/main/java/io/github/wulkanowy/api/Client.java index c6360d04..6997322e 100644 --- a/api/src/main/java/io/github/wulkanowy/api/Client.java +++ b/api/src/main/java/io/github/wulkanowy/api/Client.java @@ -13,6 +13,7 @@ import java.util.Map; import java.util.concurrent.TimeUnit; import io.github.wulkanowy.api.generic.School; +import io.github.wulkanowy.api.login.AccountPermissionException; import io.github.wulkanowy.api.login.Login; public class Client { @@ -31,6 +32,8 @@ public class Client { private List schools; + private List symbols; + private Date lastSuccessRequest; private Cookies cookies = new Cookies(); @@ -117,6 +120,20 @@ public class Client { return schools; } + public void setSymbols(List symbols) { + this.symbols = symbols; + } + + public List getSymbols() throws IOException, VulcanException { + try { + login(); + } catch (AccountPermissionException e) { + // logger.error(e.getMessage(), e); + } + + return symbols; + } + public String getSchoolId() throws IOException, VulcanException { return schoolId != null ? schoolId : getSchools().get(0).getId(); } diff --git a/api/src/main/java/io/github/wulkanowy/api/Vulcan.java b/api/src/main/java/io/github/wulkanowy/api/Vulcan.java index 70cf382e..adaeda65 100644 --- a/api/src/main/java/io/github/wulkanowy/api/Vulcan.java +++ b/api/src/main/java/io/github/wulkanowy/api/Vulcan.java @@ -72,6 +72,10 @@ public class Vulcan { return getClient().getSchools(); } + public List getSymbols() throws VulcanException, IOException { + return getClient().getSymbols(); + } + public SnP getStudentAndParent() throws VulcanException, IOException { if (null != this.snp) { return this.snp; @@ -83,6 +87,11 @@ public class Vulcan { return this.snp; } + public void logout() { + client = null; + snp = null; + } + public List getAttendance(String dateStart) throws VulcanException, IOException { return new Attendance(getStudentAndParent()).getAttendance(dateStart); } diff --git a/api/src/main/java/io/github/wulkanowy/api/login/Login.java b/api/src/main/java/io/github/wulkanowy/api/login/Login.java index 443a9387..722a182d 100644 --- a/api/src/main/java/io/github/wulkanowy/api/login/Login.java +++ b/api/src/main/java/io/github/wulkanowy/api/login/Login.java @@ -1,5 +1,6 @@ package io.github.wulkanowy.api.login; +import org.apache.commons.lang3.StringUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; @@ -9,6 +10,8 @@ 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.Client; import io.github.wulkanowy.api.NotLoggedInErrorException; @@ -121,26 +124,39 @@ public class Login { } private String findSymbol(String symbol, String certificate) throws AccountPermissionException { + List symbols = getSymbolsFromCertificate(certificate); + client.setSymbols(symbols); + if ("Default".equals(symbol)) { - return findSymbolInCertificate(certificate); + return getLastSymbol(symbols); } return symbol; } - String findSymbolInCertificate(String certificate) throws AccountPermissionException { + List getSymbolsFromCertificate(String certificate) { Elements instances = Jsoup .parse(certificate.replaceAll(":", ""), "", Parser.xmlParser()) .select("[AttributeName=\"UserInstance\"] samlAttributeValue"); - if (instances.isEmpty()) { // on adfs login + List symbols = new ArrayList<>(); + + for (Element e : instances) { + symbols.add(e.text()); + } + + return symbols; + } + + String getLastSymbol(List symbols) throws AccountPermissionException { + if (symbols.isEmpty()) { // on adfs login return ""; } - if (instances.size() < 2) { // 1st index is always `Default` + if (symbols.size() < 2) { // 1st index is always `Default` throw new AccountPermissionException("First login detected, specify symbol"); } - return instances.get(1).text(); + return StringUtils.stripAccents(symbols.get(1).replaceAll("\\s", "")); } } diff --git a/api/src/test/java/io/github/wulkanowy/api/login/LoginTest.java b/api/src/test/java/io/github/wulkanowy/api/login/LoginTest.java index 86a3ef40..3f16c819 100644 --- a/api/src/test/java/io/github/wulkanowy/api/login/LoginTest.java +++ b/api/src/test/java/io/github/wulkanowy/api/login/LoginTest.java @@ -6,6 +6,8 @@ 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; @@ -118,14 +120,17 @@ public class LoginTest { Login login = new Login(getClient("Logowanie-certyfikat.html")); String certificate = getFixtureAsString("cert-stock.xml"); + List symbols = login.getSymbolsFromCertificate(certificate); - Assert.assertEquals("demo12345", login.findSymbolInCertificate(certificate)); + Assert.assertEquals("demo12345", login.getLastSymbol(symbols)); } @Test(expected = AccountPermissionException.class) public void findSymbolInCertificateWithoutSecondInstanceTest() throws Exception { Login login = new Login(getClient("Logowanie-certyfikat.html")); - login.findSymbolInCertificate(getFixtureAsString("cert-no-symbols.xml")); + List symbols = login.getSymbolsFromCertificate(getFixtureAsString("cert-no-symbols.xml")); + + login.getLastSymbol(symbols); } } diff --git a/app/build.gradle b/app/build.gradle index 7d5ec8a3..5c373f22 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,7 +1,7 @@ -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'// sync warning probably caused by bug https://issuetracker.google.com/issues/74537216 +apply plugin: 'kotlin-android-extensions' apply plugin: 'io.fabric' apply from: 'jacoco.gradle' apply from: 'android-sonarqube.gradle' @@ -16,7 +16,6 @@ buildscript { } 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" @@ -45,6 +44,7 @@ android { targetSdkVersion 27 versionCode 16 versionName "0.5.2" + multiDexEnabled true testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" vectorDrawables.useSupportLibrary = true playAccountConfig = playAccountConfigs.defaultAccountConfig @@ -73,6 +73,7 @@ android { versionNameSuffix "-dev" testCoverageEnabled = true ext.enableCrashlytics = false + multiDexKeepProguard file('proguard-multidex-rules.pro') } } @@ -87,34 +88,31 @@ android { } } +androidExtensions { + experimental = true +} + play { track = 'alpha' uploadImages = true } -greendao { - schemaVersion 29 - generateTests = true -} - configurations.all { resolutionStrategy.force "com.android.support:support-annotations:$supportVersion" } dependencies { implementation project(':api') - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-stdlib:$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" @@ -122,6 +120,12 @@ dependencies { implementation "com.google.android.gms:play-services-oss-licenses:$ossLicenses" implementation "com.jakewharton.timber:timber:$timber" implementation "at.favre.lib:slf4j-timber:$slf4jTimber" + implementation "android.arch.persistence.room:runtime:1.1.1" + implementation 'io.reactivex.rxjava2:rxandroid:2.0.2' + implementation "io.reactivex.rxjava2:rxjava:2.2.0" + implementation 'com.android.support:multidex:1.0.3' + implementation "android.arch.persistence.room:rxjava2:1.1.1" + implementation 'com.github.pwittchen:reactivenetwork-rx2:2.1.0' implementation("com.crashlytics.sdk.android:crashlytics:$crashlyticsSdk@aar") { transitive = true @@ -133,11 +137,13 @@ dependencies { kapt "com.google.dagger:dagger-compiler:$dagger2" kapt "com.google.dagger:dagger-android-processor:$dagger2" kapt "com.jakewharton:butterknife-compiler:$butterknife" + kapt "android.arch.persistence.room:compiler:1.1.1" debugImplementation "com.amitshekhar.android:debug-db:$debugDb" testImplementation "junit:junit:$junit" - testImplementation "org.mockito:mockito-core:$mockito" + testImplementation "org.mockito:mockito-inline:$mockito" + testImplementation "org.jsoup:jsoup:$jsoup" androidTestImplementation "com.android.support.test:runner:$testRunner" androidTestImplementation "org.mockito:mockito-android:$mockito" 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/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/StudentLocalTest.kt b/app/src/androidTest/java/io/github/wulkanowy/data/repositories/local/StudentLocalTest.kt new file mode 100644 index 00000000..e4e9e1df --- /dev/null +++ b/app/src/androidTest/java/io/github/wulkanowy/data/repositories/local/StudentLocalTest.kt @@ -0,0 +1,49 @@ +package io.github.wulkanowy.data.repositories.local + +import android.arch.persistence.room.Room +import android.content.Context +import android.support.test.InstrumentationRegistry +import android.support.test.runner.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 StudentLocalTest { + + private lateinit var studentLocal: StudentLocal + + private lateinit var testDb: AppDatabase + + private lateinit var sharedHelper: SharedPrefHelper + + @Before + fun createDb() { + val context = InstrumentationRegistry.getContext() + testDb = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java) + .build() + sharedHelper = SharedPrefHelper(context.getSharedPreferences("TEST", Context.MODE_PRIVATE)) + studentLocal = StudentLocal(testDb.studentDao(), sharedHelper, context) + } + + @After + fun closeDb() { + testDb.close() + } + + @Test + fun saveAndReadTest() { + studentLocal.save(Student(email = "test", password = "test123", schoolId = "23")) + assert(sharedHelper.getLong(StudentLocal.CURRENT_USER_KEY, 0) == 1L) + + assert(studentLocal.isStudentLoggedIn) + + val student = studentLocal.getCurrentStudent().blockingGet() + assertEquals("23", student.schoolId) + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 59963c45..5013dbc5 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -28,7 +28,7 @@ Unit = {} + + open fun proceed(error: Throwable) { + Timber.i(error, "An exception occurred while the Wulkanowy was running") + + showErrorMessage((when (error) { + is UnknownHostException -> resources.getString(R.string.noInternet_text) + is SocketTimeoutException -> resources.getString(R.string.generic_timeout_error) + is NotLoggedInErrorException, is IOException -> resources.getString(R.string.login_failed_text) + 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..6cacc01e --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/RepositoryModule.kt @@ -0,0 +1,44 @@ +package io.github.wulkanowy.data + +import android.arch.persistence.room.Room +import android.content.Context +import android.content.SharedPreferences +import android.support.v7.preference.PreferenceManager +import com.github.pwittchen.reactivenetwork.library.rx2.internet.observing.InternetObservingSettings +import dagger.Module +import dagger.Provides +import io.github.wulkanowy.api.Vulcan +import io.github.wulkanowy.data.db.AppDatabase +import io.github.wulkanowy.utils.DATABASE_NAME +import javax.inject.Singleton + +@Module +internal class RepositoryModule { + + @Singleton + @Provides + fun provideInternetObservingSettings(): InternetObservingSettings { + return InternetObservingSettings.create() + } + + @Singleton + @Provides + fun provideVulcanApi() = Vulcan() + + @Singleton + @Provides + fun provideDatabase(context: Context): AppDatabase { + return Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME) + .build() + } + + @Singleton + @Provides + fun provideSharedPref(context: Context): SharedPreferences { + return PreferenceManager.getDefaultSharedPreferences(context) + } + + @Singleton + @Provides + fun provideStudentDao(database: AppDatabase) = database.studentDao() +} \ No newline at end of file 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..ffb02591 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/AppDatabase.kt @@ -0,0 +1,18 @@ +package io.github.wulkanowy.data.db + +import android.arch.persistence.room.Database +import android.arch.persistence.room.RoomDatabase +import io.github.wulkanowy.data.db.dao.StudentDao +import io.github.wulkanowy.data.db.entities.Student +import javax.inject.Singleton + +@Singleton +@Database( + entities = [Student::class], + version = 1, + exportSchema = false +) +abstract class AppDatabase : RoomDatabase() { + + abstract fun studentDao(): StudentDao +} \ No newline at end of file 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..6adb79eb --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/SharedPrefHelper.kt @@ -0,0 +1,17 @@ +package io.github.wulkanowy.data.db + +import android.content.SharedPreferences +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class SharedPrefHelper @Inject constructor(private val sharedPref: SharedPreferences) { + + fun putLong(key: String, value: Long) { + sharedPref.edit().putLong(key, value).apply() + } + + fun getLong(key: String, defaultValue: Long): Long { + return sharedPref.getLong(key, defaultValue) + } +} \ No newline at end of file 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/StudentDao.kt b/app/src/main/java/io/github/wulkanowy/data/db/dao/StudentDao.kt new file mode 100644 index 00000000..fb3cb4e7 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/dao/StudentDao.kt @@ -0,0 +1,18 @@ +package io.github.wulkanowy.data.db.dao + +import android.arch.persistence.room.Dao +import android.arch.persistence.room.Insert +import android.arch.persistence.room.OnConflictStrategy.REPLACE +import android.arch.persistence.room.Query +import io.github.wulkanowy.data.db.entities.Student +import io.reactivex.Single + +@Dao +interface StudentDao { + + @Insert(onConflict = REPLACE) + fun insert(student: Student): Long + + @Query("SELECT * FROM Students WHERE id = :id") + fun load(id: Long): Single +} 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/Student.kt b/app/src/main/java/io/github/wulkanowy/data/db/entities/Student.kt new file mode 100644 index 00000000..e3829e87 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/db/entities/Student.kt @@ -0,0 +1,32 @@ +package io.github.wulkanowy.data.db.entities + +import android.arch.persistence.room.ColumnInfo +import android.arch.persistence.room.Entity +import android.arch.persistence.room.Index +import android.arch.persistence.room.PrimaryKey + +@Entity(tableName = "Students", + indices = [Index(value = ["student_id", "student_name"], unique = true)]) +data class Student( + + @PrimaryKey(autoGenerate = true) + var id: Long = 0, + + var email: String, + + var password: String, + + var symbol: String = "", + + @ColumnInfo(name = "student_id") + var studentId: String = "", + + @ColumnInfo(name = "student_name") + var studentName: String = "", + + @ColumnInfo(name = "school_id") + var schoolId: String = "", + + @ColumnInfo(name = "school_name") + var schoolName: String = "" +) 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/StudentRepository.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/StudentRepository.kt new file mode 100644 index 00000000..59659ea5 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/StudentRepository.kt @@ -0,0 +1,43 @@ +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.Student +import io.github.wulkanowy.data.repositories.local.StudentLocal +import io.github.wulkanowy.data.repositories.remote.StudentRemote +import io.reactivex.Single +import java.net.UnknownHostException +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class StudentRepository @Inject constructor( + private val local: StudentLocal, + private val remote: StudentRemote, + private val settings: InternetObservingSettings) { + + lateinit var cachedStudents: Single> + private set + + val isStudentLoggedIn: Boolean + get() = local.isStudentLoggedIn + + fun getConnectedStudents(email: String, password: String, symbol: String): Single> { + cachedStudents = ReactiveNetwork.checkInternetConnectivity(settings) + .flatMap { isConnected -> + if (isConnected) remote.getConnectedStudents(email, password, symbol) + else Single.error>(UnknownHostException("No internet connection")) + }.doOnSuccess { cachedStudents = Single.just(it) } + return cachedStudents + } + + fun save(student: Student) { + local.save(student) + } + + fun getCurrentStudent(): Single = local.getCurrentStudent() + + fun clearCache() { + cachedStudents = Single.just(emptyList()) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/local/StudentLocal.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/local/StudentLocal.kt new file mode 100644 index 00000000..6c325f68 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/local/StudentLocal.kt @@ -0,0 +1,35 @@ +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.StudentDao +import io.github.wulkanowy.data.db.entities.Student +import io.github.wulkanowy.utils.security.Scrambler.decrypt +import io.github.wulkanowy.utils.security.Scrambler.encrypt +import io.reactivex.Single +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class StudentLocal @Inject constructor( + private val studentDb: StudentDao, + private val sharedPref: SharedPrefHelper, + private val context: Context) { + + companion object { + const val CURRENT_USER_KEY: String = "current_user_id" + } + + val isStudentLoggedIn: Boolean + get() = sharedPref.getLong(CURRENT_USER_KEY, 0) != 0L + + fun save(student: Student) { + sharedPref.putLong(CURRENT_USER_KEY, studentDb.insert(student.copy( + password = encrypt(student.password, context)))) + } + + fun getCurrentStudent(): Single { + return studentDb.load(sharedPref.getLong(CURRENT_USER_KEY, defaultValue = 0)) + .map { it.apply { password = decrypt(password) } } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/data/repositories/remote/StudentRemote.kt b/app/src/main/java/io/github/wulkanowy/data/repositories/remote/StudentRemote.kt new file mode 100644 index 00000000..491c3fdd --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/data/repositories/remote/StudentRemote.kt @@ -0,0 +1,55 @@ +package io.github.wulkanowy.data.repositories.remote + +import io.github.wulkanowy.api.Vulcan +import io.github.wulkanowy.api.login.AccountPermissionException +import io.github.wulkanowy.data.db.entities.Student +import io.github.wulkanowy.utils.DEFAULT_SYMBOL +import io.reactivex.Single +import org.apache.commons.lang3.StringUtils.stripAccents +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class StudentRemote @Inject constructor(private val api: Vulcan) { + + fun getConnectedStudents(email: String, password: String, symbol: String): Single> { + return Single.fromCallable { + initApi(email, password, symbol) + getSymbols().filterNot { it == DEFAULT_SYMBOL } + .mapNotNull { symbol -> + try { + initApi(email, password, symbol) + api.schools.flatMap { school -> + initApi(email, password, symbol, school.id) + api.studentAndParent.students.map { student -> + Student( + email = email, + password = password, + symbol = symbol, + studentId = student.id, + studentName = student.name, + schoolId = school.id, + schoolName = school.name + ) + } + } + } catch (e: AccountPermissionException) { + null + } + }.flatten() + } + } + + private fun initApi(email: String, password: String, symbol: String, schoolId: String? = null) { + api.apply { + logout() + setCredentials(email, password, symbol, schoolId, null, null) + } + } + + private fun getSymbols(): List { + return api.symbols.map { + stripAccents(it.replace("[\\s \\W]".toRegex(), "")) + } + } +} 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..053e4697 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/di/AppComponent.kt @@ -0,0 +1,19 @@ +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..612f837f --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/di/AppModule.kt @@ -0,0 +1,22 @@ +package io.github.wulkanowy.di + +import android.content.Context +import dagger.Module +import dagger.Provides +import io.github.wulkanowy.WulkanowyApp +import io.github.wulkanowy.data.ErrorHandler +import io.github.wulkanowy.utils.schedulers.SchedulersManager +import io.github.wulkanowy.utils.schedulers.SchedulersProvider + +@Module +internal class AppModule { + + @Provides + fun provideContext(app: WulkanowyApp): Context = app + + @Provides + fun provideSchedulers(): SchedulersManager = SchedulersProvider() + + @Provides + fun provideErrorHandler(context: Context): ErrorHandler = ErrorHandler(context.resources) +} 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..b1886fca --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/di/BuilderModule.kt @@ -0,0 +1,25 @@ +package io.github.wulkanowy.di + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import io.github.wulkanowy.di.scopes.PerActivity +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.splash.SplashActivity + +@Module +internal abstract class BuilderModule { + + @PerActivity + @ContributesAndroidInjector() + abstract fun bindSplashActivity(): SplashActivity + + @PerActivity + @ContributesAndroidInjector(modules = [LoginModule::class]) + abstract fun bindLoginActivity(): LoginActivity + + @PerActivity + @ContributesAndroidInjector() + abstract fun bindMainActivity(): MainActivity +} 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/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/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/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..696834e0 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/base/BaseActivity.kt @@ -0,0 +1,33 @@ +package io.github.wulkanowy.ui.base + +import android.os.Bundle +import android.support.design.widget.Snackbar +import android.support.design.widget.Snackbar.LENGTH_LONG +import android.support.v7.app.AppCompatDelegate +import android.view.View +import dagger.android.support.DaggerAppCompatActivity +import io.github.wulkanowy.R + +abstract class BaseActivity : DaggerAppCompatActivity(), BaseView { + + protected lateinit var messageView: View + + public override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) + } + + override fun showMessage(text: String) { + Snackbar.make(messageView, text, LENGTH_LONG).show() + + } + + override fun showNoNetworkMessage() { + showMessage(getString(R.string.noInternet_text)) + } + + 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..72c21da9 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/base/BaseFragment.kt @@ -0,0 +1,24 @@ +package io.github.wulkanowy.ui.base + +import android.support.annotation.StringRes + +import dagger.android.support.DaggerFragment + +abstract class BaseFragment : DaggerFragment(), BaseView { + + fun setTitle(title: String) { + activity?.title = title + } + + override fun showMessage(text: String) { + (activity as BaseActivity?)?.showMessage(text) + } + + fun showMessage(@StringRes stringId: Int) { + showMessage(getString(stringId)) + } + + override fun showNoNetworkMessage() { + (activity as BaseActivity?)?.showNoNetworkMessage() + } +} 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..8b37da85 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/base/BasePagerAdapter.kt @@ -0,0 +1,30 @@ +package io.github.wulkanowy.ui.base + +import android.support.v4.app.Fragment +import android.support.v4.app.FragmentManager +import android.support.v4.app.FragmentStatePagerAdapter + +class BasePagerAdapter(fragmentManager: FragmentManager) : FragmentStatePagerAdapter(fragmentManager) { + + private val fragmentList = mutableListOf() + + private val titleList = mutableListOf() + + fun addFragment(fragment: Fragment, title: String) { + fragmentList.add(fragment) + titleList.add(title) + } + + fun addFragments(vararg fragments: Fragment) { + fragmentList.addAll(fragments) + } + + override fun getItem(position: Int): Fragment = fragmentList[position] + + override fun getCount(): Int = fragmentList.size + + override fun getPageTitle(position: Int): CharSequence? { + return if (!titleList.isEmpty() && titleList.size == fragmentList.size) titleList[position] + else null + } +} 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..76c8533e --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/base/BasePresenter.kt @@ -0,0 +1,25 @@ +package io.github.wulkanowy.ui.base + +import io.github.wulkanowy.data.ErrorHandler +import io.reactivex.disposables.CompositeDisposable + +open class BasePresenter(private val errorHandler: ErrorHandler) { + + val disposable = CompositeDisposable() + + var view: T? = null + + val isViewAttached: Boolean + get() = view != null + + open fun attachView(view: T) { + this.view = view + errorHandler.showErrorMessage = { view.showMessage(it) } + } + + open fun detachView() { + 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..4c384ab2 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/base/BaseView.kt @@ -0,0 +1,8 @@ +package io.github.wulkanowy.ui.base + +interface BaseView { + + fun showMessage(text: String) + + fun showNoNetworkMessage() +} 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/LoginActivity.kt b/app/src/main/java/io/github/wulkanowy/ui/login/LoginActivity.kt new file mode 100644 index 00000000..0ab172ac --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/login/LoginActivity.kt @@ -0,0 +1,70 @@ +package io.github.wulkanowy.ui.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.login.form.LoginFormFragment +import io.github.wulkanowy.ui.login.options.LoginOptionsFragment +import io.github.wulkanowy.utils.extension.setOnSelectPageListener +import kotlinx.android.synthetic.main.activity_login.* +import javax.inject.Inject +import javax.inject.Named + +class LoginActivity : BaseActivity(), LoginView, LoginSwitchListener { + + @Inject + lateinit var presenter: LoginPresenter + + @Inject + @field:Named("Login") + lateinit var loginAdapter: BasePagerAdapter + + companion object { + fun getStartIntent(context: Context) = Intent(context, LoginActivity::class.java) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_login) + presenter.attachView(this) + messageView = loginContainer + } + + override fun onBackPressed() { + presenter.onBackPressed { super.onBackPressed() } + } + + override fun initAdapter() { + loginAdapter.addFragments(LoginFormFragment(), LoginOptionsFragment()) + 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() + } + + override fun currentViewPosition(): Int = loginViewpager.currentItem + + public override fun 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/LoginErrorHandler.kt b/app/src/main/java/io/github/wulkanowy/ui/login/LoginErrorHandler.kt new file mode 100644 index 00000000..93b66ab1 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/login/LoginErrorHandler.kt @@ -0,0 +1,23 @@ +package io.github.wulkanowy.ui.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/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/LoginModule.kt b/app/src/main/java/io/github/wulkanowy/ui/login/LoginModule.kt new file mode 100644 index 00000000..5d1e4323 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/login/LoginModule.kt @@ -0,0 +1,39 @@ +package io.github.wulkanowy.ui.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.login.form.LoginFormFragment +import io.github.wulkanowy.ui.login.options.LoginOptionsFragment +import io.github.wulkanowy.ui.login.options.LoginOptionsModule +import javax.inject.Named + +@Module +internal abstract class LoginModule { + + @Module + companion object { + + @JvmStatic + @Provides + @Named("Login") + 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(modules = [LoginOptionsModule::class]) + abstract fun bindLoginOptionsFragment(): LoginOptionsFragment +} 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/LoginPresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/login/LoginPresenter.kt new file mode 100644 index 00000000..51114be3 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/login/LoginPresenter.kt @@ -0,0 +1,34 @@ +package io.github.wulkanowy.ui.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 attachView(view: LoginView) { + super.attachView(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 (currentViewPosition() == 1) { + switchView(0) + hideActionBar() + } else default() + } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/login/LoginSwitchListener.kt b/app/src/main/java/io/github/wulkanowy/ui/login/LoginSwitchListener.kt new file mode 100644 index 00000000..c4b57c85 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/login/LoginSwitchListener.kt @@ -0,0 +1,6 @@ +package io.github.wulkanowy.ui.login + +interface LoginSwitchListener { + + fun switchFragment(position: Int) +} \ No newline at end of file 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/login/LoginView.kt b/app/src/main/java/io/github/wulkanowy/ui/login/LoginView.kt new file mode 100644 index 00000000..6e01f51b --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/login/LoginView.kt @@ -0,0 +1,16 @@ +package io.github.wulkanowy.ui.login + +import io.github.wulkanowy.ui.base.BaseView + +interface LoginView : BaseView { + + fun initAdapter() + + fun loadOptionsView(index: Int) + + fun switchView(position: Int) + + fun hideActionBar() + + fun currentViewPosition(): Int +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/login/form/LoginFormFragment.kt b/app/src/main/java/io/github/wulkanowy/ui/login/form/LoginFormFragment.kt new file mode 100644 index 00000000..cf231c3e --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/login/form/LoginFormFragment.kt @@ -0,0 +1,139 @@ +package io.github.wulkanowy.ui.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.login.LoginSwitchListener +import io.github.wulkanowy.utils.extension.hideSoftInput +import io.github.wulkanowy.utils.extension.showSoftInput +import kotlinx.android.synthetic.main.fragment_login_form.* +import javax.inject.Inject + +class LoginFormFragment : BaseFragment(), LoginFormView { + + @Inject + lateinit var presenter: LoginFormPresenter + + 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.attachView(this) + } + + override fun initInputs() { + loginSignButton.setOnClickListener { + presenter.attemptLogin(loginEmailEdit.text.toString(), + loginPassEdit.text.toString(), + loginSymbolEdit.text.toString()) + } + + loginPassEdit.setOnEditorActionListener { _, id, _ -> onEditAction(id) } + + 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_heading_symbol) + loginMainForm.visibility = GONE + loginSymbolInput.visibility = VISIBLE + loginSymbolEdit.requestFocus() + showSoftKeyboard() + } + + override fun switchNextView() { + (activity as LoginSwitchListener?)?.switchFragment(1) + } + + override fun setErrorEmailRequired() { + loginEmailEdit.run { + requestFocus() + error = getString(R.string.error_field_required) + } + } + + override fun setErrorEmailInvalid() { + loginEmailEdit.run { + requestFocus() + error = getString(R.string.error_invalid_email) + } + } + + override fun setErrorPassRequired(focus: Boolean) { + loginPassEdit.run { + if (focus) requestFocus() + error = getString(R.string.error_field_required) + } + } + + override fun setErrorPassInvalid(focus: Boolean) { + loginPassEdit.run { + if (focus) requestFocus() + error = getString(R.string.error_invalid_password) + } + } + + override fun setErrorSymbolRequire() { + loginSymbolEdit.run { + requestFocus() + error = getString(R.string.error_field_required) + } + } + + override fun setErrorPassIncorrect() { + loginPassEdit.run { + requestFocus() + error = getString(R.string.error_incorrect_password) + } + } + + override fun setErrorSymbolIncorrect() { + loginSymbolEdit.run { + requestFocus() + error = getString(R.string.error_incorrect_symbol) + } + } + + override fun resetViewErrors() { + loginEmailEdit.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 onDestroy() { + super.onDestroy() + presenter.detachView() + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/login/form/LoginFormPresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/login/form/LoginFormPresenter.kt new file mode 100644 index 00000000..27ddb540 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/login/form/LoginFormPresenter.kt @@ -0,0 +1,88 @@ +package io.github.wulkanowy.ui.login.form + +import io.github.wulkanowy.data.repositories.StudentRepository +import io.github.wulkanowy.ui.base.BasePresenter +import io.github.wulkanowy.ui.login.LoginErrorHandler +import io.github.wulkanowy.utils.DEFAULT_SYMBOL +import io.github.wulkanowy.utils.schedulers.SchedulersManager +import javax.inject.Inject + +class LoginFormPresenter @Inject constructor( + private val schedulers: SchedulersManager, + private val errorHandler: LoginErrorHandler, + private val studentRepository: StudentRepository) + : BasePresenter(errorHandler) { + + private var wasEmpty = false + + override fun attachView(view: LoginFormView) { + super.attachView(view) + view.initInputs() + } + + fun attemptLogin(email: String, password: String, symbol: String) { + if (!validateCredentials(email, password, symbol)) return + disposable.add(studentRepository.getConnectedStudents(email, password, normalizeSymbol(symbol)) + .observeOn(schedulers.mainThread()) + .subscribeOn(schedulers.backgroundThread()) + .doOnSubscribe { + view?.run { + hideSoftKeyboard() + showLoginProgress(true) + errorHandler.doOnBadCredentials = { + setErrorPassIncorrect() + showSoftKeyboard() + } + } + studentRepository.clearCache() + } + .doFinally { view?.showLoginProgress(false) } + .subscribe({ + view?.run { + if (it.isEmpty() && !wasEmpty) { + showSymbolInput() + wasEmpty = true + } else if (it.isEmpty() && wasEmpty) { + showSymbolInput() + setErrorSymbolIncorrect() + } else { + switchNextView() + } + } + }, { errorHandler.proceed(it) })) + } + + private fun validateCredentials(email: String, password: String, symbol: String): Boolean { + var isCorrect = true + + if (email.isEmpty()) { + view?.setErrorEmailRequired() + isCorrect = false + } + + if (password.isEmpty()) { + view?.setErrorPassRequired(focus = isCorrect) + isCorrect = false + } + + if (symbol.isEmpty() && wasEmpty) { + view?.setErrorSymbolRequire() + isCorrect = false + } + + if (!email.contains("[@]|[\\\\]{4}".toRegex()) && email.isNotEmpty()) { + view?.setErrorEmailInvalid() + isCorrect = false + } + + if (password.length <= 4 && password.isNotEmpty()) { + view?.setErrorPassInvalid(focus = isCorrect) + isCorrect = false + } + return isCorrect + } + + private fun normalizeSymbol(symbol: String): String { + return if (symbol.isEmpty()) DEFAULT_SYMBOL else symbol + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/login/form/LoginFormView.kt b/app/src/main/java/io/github/wulkanowy/ui/login/form/LoginFormView.kt new file mode 100644 index 00000000..d95f352a --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/login/form/LoginFormView.kt @@ -0,0 +1,34 @@ +package io.github.wulkanowy.ui.login.form + +import io.github.wulkanowy.ui.base.BaseView + +interface LoginFormView : BaseView { + + fun initInputs() + + fun setErrorEmailRequired() + + fun setErrorPassRequired(focus: Boolean) + + fun setErrorSymbolRequire() + + fun setErrorEmailInvalid() + + fun setErrorPassInvalid(focus: Boolean) + + fun setErrorPassIncorrect() + + fun setErrorSymbolIncorrect() + + fun resetViewErrors() + + fun showSoftKeyboard() + + fun hideSoftKeyboard() + + fun showLoginProgress(show: Boolean) + + fun showSymbolInput() + + fun switchNextView() +} \ No newline at end of file diff --git a/app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsFragment.kt b/app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsFragment.kt new file mode 100644 index 00000000..99bef1a1 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsFragment.kt @@ -0,0 +1,67 @@ +package io.github.wulkanowy.ui.login.options + +import android.os.Bundle +import android.support.v7.app.AppCompatActivity +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +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.MainActivity +import io.github.wulkanowy.utils.extension.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 + + 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.attachView(this) + } + + override fun initRecycler() { + loginAdapter.setOnItemClickListener { item -> item?.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) + } + } + + override fun openMainView() { + activity?.let { + startActivity(MainActivity.getStartIntent(it)) + it.finish() + } + } + + override fun showLoginProgress(show: Boolean) { + loginOptionsProgressContainer.visibility = if (show) View.GONE else View.VISIBLE + loginOptionsRecycler.visibility = if (show) View.VISIBLE else View.GONE + } + + override fun showActionBar(show: Boolean) { + (activity as AppCompatActivity?)?.supportActionBar?.run { if (show) show() else hide() } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsItem.kt b/app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsItem.kt new file mode 100644 index 00000000..777c7ef4 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsItem.kt @@ -0,0 +1,54 @@ +package io.github.wulkanowy.ui.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.fragment_login_opions_item.view.* + +class LoginOptionsItem(val student: Student) : AbstractFlexibleItem() { + + override fun getLayoutRes(): Int = R.layout.fragment_login_opions_item + + 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/login/options/LoginOptionsModule.kt b/app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsModule.kt new file mode 100644 index 00000000..711db217 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsModule.kt @@ -0,0 +1,14 @@ +package io.github.wulkanowy.ui.login.options + +import dagger.Module +import dagger.Provides +import eu.davidea.flexibleadapter.FlexibleAdapter +import io.github.wulkanowy.di.scopes.PerFragment + +@Module +internal class LoginOptionsModule { + + @Provides + @PerFragment + fun provideLoginOptionsAdapter() = FlexibleAdapter(null) +} \ No newline at end of file diff --git a/app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsPresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsPresenter.kt new file mode 100644 index 00000000..c7a701d7 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsPresenter.kt @@ -0,0 +1,45 @@ +package io.github.wulkanowy.ui.login.options + +import io.github.wulkanowy.data.ErrorHandler +import io.github.wulkanowy.data.db.entities.Student +import io.github.wulkanowy.data.repositories.StudentRepository +import io.github.wulkanowy.ui.base.BasePresenter +import io.github.wulkanowy.utils.schedulers.SchedulersManager +import io.reactivex.Single +import javax.inject.Inject + +class LoginOptionsPresenter @Inject constructor( + private val errorHandler: ErrorHandler, + private val repository: StudentRepository, + private val schedulers: SchedulersManager) + : BasePresenter(errorHandler) { + + override fun attachView(view: LoginOptionsView) { + super.attachView(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(student.let { + Single.fromCallable { repository.save(it) } + .subscribeOn(schedulers.backgroundThread()) + .observeOn(schedulers.mainThread()) + .doOnSubscribe { _ -> view?.showLoginProgress(true) } + .doOnSuccess { _ -> view?.openMainView() } + .subscribe({ _ -> }, { error -> errorHandler.proceed(error) }) + }) + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsView.kt b/app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsView.kt new file mode 100644 index 00000000..9303839f --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/login/options/LoginOptionsView.kt @@ -0,0 +1,16 @@ +package io.github.wulkanowy.ui.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/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/MainActivity.kt b/app/src/main/java/io/github/wulkanowy/ui/main/MainActivity.kt new file mode 100644 index 00000000..c061680d --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/main/MainActivity.kt @@ -0,0 +1,13 @@ +package io.github.wulkanowy.ui.main + +import android.content.Context +import android.content.Intent +import io.github.wulkanowy.ui.base.BaseActivity + +class MainActivity : BaseActivity() { + + companion object { + fun getStartIntent(context: Context) = Intent(context, MainActivity::class.java) + } +} + 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/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/SplashActivity.kt b/app/src/main/java/io/github/wulkanowy/ui/splash/SplashActivity.kt new file mode 100644 index 00000000..a0457855 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/splash/SplashActivity.kt @@ -0,0 +1,32 @@ +package io.github.wulkanowy.ui.splash + +import android.os.Bundle +import io.github.wulkanowy.ui.base.BaseActivity +import io.github.wulkanowy.ui.login.LoginActivity +import javax.inject.Inject + +class SplashActivity : BaseActivity(), SplashView { + + @Inject + lateinit var presenter: SplashPresenter + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + presenter.attachView(this) + } + + override fun onDestroy() { + super.onDestroy() + presenter.detachView() + } + + override fun openLoginActivity() { + startActivity(LoginActivity.getStartIntent(this)) + finish() + } + + override fun openMainActivity() { + //TODO('Not implemented) + finish() + } +} 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/splash/SplashPresenter.kt b/app/src/main/java/io/github/wulkanowy/ui/splash/SplashPresenter.kt new file mode 100644 index 00000000..ba69ecbc --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/splash/SplashPresenter.kt @@ -0,0 +1,16 @@ +package io.github.wulkanowy.ui.splash + +import io.github.wulkanowy.data.ErrorHandler +import io.github.wulkanowy.data.repositories.StudentRepository +import io.github.wulkanowy.ui.base.BasePresenter +import javax.inject.Inject + +class SplashPresenter @Inject constructor(private val studentRepository: StudentRepository, + errorHandler: ErrorHandler) + : BasePresenter(errorHandler) { + + override fun attachView(view: SplashView) { + super.attachView(view) + view.run { if (studentRepository.isStudentLoggedIn) openMainActivity() else openLoginActivity() } + } +} diff --git a/app/src/main/java/io/github/wulkanowy/ui/splash/SplashView.kt b/app/src/main/java/io/github/wulkanowy/ui/splash/SplashView.kt new file mode 100644 index 00000000..7cdde3b3 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/ui/splash/SplashView.kt @@ -0,0 +1,10 @@ +package io.github.wulkanowy.ui.splash + +import io.github.wulkanowy.ui.base.BaseView + +interface SplashView : BaseView { + + fun openLoginActivity() + + fun openMainActivity() +} 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/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/AppConstant.kt b/app/src/main/java/io/github/wulkanowy/utils/AppConstant.kt new file mode 100644 index 00000000..055d7f14 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/utils/AppConstant.kt @@ -0,0 +1,11 @@ +package io.github.wulkanowy.utils + +const val APP_NAME = "Wulkanowy" + +const val DATABASE_NAME = "wulkanowy_db" + +const val DEFAULT_SYMBOL = "Default" + +const val DATE_PATTERN = "yyyy-MM-dd" + +const val REPO_URL = "https://github.com/wulkanowy/wulkanowy" diff --git a/app/src/main/java/io/github/wulkanowy/utils/CommonUtils.java b/app/src/main/java/io/github/wulkanowy/utils/CommonUtils.java index 9c7b35fb..5c94cc57 100644 --- a/app/src/main/java/io/github/wulkanowy/utils/CommonUtils.java +++ b/app/src/main/java/io/github/wulkanowy/utils/CommonUtils.java @@ -1,12 +1,9 @@ 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; @@ -16,13 +13,6 @@ public final class 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": 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/GradeUtils.java b/app/src/main/java/io/github/wulkanowy/utils/GradeUtils.java index 7b6ba193..b45bdcc6 100644 --- a/app/src/main/java/io/github/wulkanowy/utils/GradeUtils.java +++ b/app/src/main/java/io/github/wulkanowy/utils/GradeUtils.java @@ -1,13 +1,7 @@ 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](\\++|-|--|=)?$"); @@ -17,7 +11,7 @@ public final class GradeUtils { throw new IllegalStateException("Utility class"); } - public static float calculateWeightedAverage(List gradeList) { + /*public static float calculateWeightedAverage(List gradeList) { float counter = 0f; float denominator = 0f; @@ -168,5 +162,5 @@ public final class GradeUtils { 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/LoggerUtils.java b/app/src/main/java/io/github/wulkanowy/utils/LoggerUtils.java index 6e6c701b..2b64e14e 100644 --- a/app/src/main/java/io/github/wulkanowy/utils/LoggerUtils.java +++ b/app/src/main/java/io/github/wulkanowy/utils/LoggerUtils.java @@ -36,7 +36,7 @@ public final class LoggerUtils { priority = Log.ERROR; } } - super.log(priority, AppConstant.APP_NAME, message, t); + super.log(priority, AppConstantKt.APP_NAME, message, t); } @Override 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/TimeUtils.kt b/app/src/main/java/io/github/wulkanowy/utils/TimeUtils.kt index c61c7e0d..dc45d87d 100644 --- a/app/src/main/java/io/github/wulkanowy/utils/TimeUtils.kt +++ b/app/src/main/java/io/github/wulkanowy/utils/TimeUtils.kt @@ -7,7 +7,7 @@ import org.threeten.bp.format.DateTimeFormatter import org.threeten.bp.temporal.TemporalAdjusters import java.util.* -private val formatter = DateTimeFormatter.ofPattern(AppConstant.DATE_PATTERN) +private val formatter = DateTimeFormatter.ofPattern(DATE_PATTERN) fun getParsedDate(dateString: String, dateFormat: String): LocalDate { return LocalDate.parse(dateString, DateTimeFormatter.ofPattern(dateFormat)) 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/extension/ActivityExtension.kt b/app/src/main/java/io/github/wulkanowy/utils/extension/ActivityExtension.kt new file mode 100644 index 00000000..1a48c115 --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/utils/extension/ActivityExtension.kt @@ -0,0 +1,18 @@ +package io.github.wulkanowy.utils.extension + +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/extension/FlexibleAdapterExtension.kt b/app/src/main/java/io/github/wulkanowy/utils/extension/FlexibleAdapterExtension.kt new file mode 100644 index 00000000..779a66fd --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/utils/extension/FlexibleAdapterExtension.kt @@ -0,0 +1,11 @@ +package io.github.wulkanowy.utils.extension + +import eu.davidea.flexibleadapter.FlexibleAdapter +import eu.davidea.flexibleadapter.items.AbstractFlexibleItem + +fun , T : FlexibleAdapter> T.setOnItemClickListener(listener: (K?) -> Unit) { + addListener(FlexibleAdapter.OnItemClickListener { _, position -> + listener(getItem(position)) + true + }) +} diff --git a/app/src/main/java/io/github/wulkanowy/utils/extension/ViewPagerExtension.kt b/app/src/main/java/io/github/wulkanowy/utils/extension/ViewPagerExtension.kt new file mode 100644 index 00000000..6d2763dd --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/utils/extension/ViewPagerExtension.kt @@ -0,0 +1,14 @@ +package io.github.wulkanowy.utils.extension + +import android.support.v4.view.ViewPager + +fun ViewPager.setOnSelectPageListener(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/schedulers/SchedulersManager.kt b/app/src/main/java/io/github/wulkanowy/utils/schedulers/SchedulersManager.kt new file mode 100644 index 00000000..ec27fffa --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/utils/schedulers/SchedulersManager.kt @@ -0,0 +1,10 @@ +package io.github.wulkanowy.utils.schedulers + +import io.reactivex.Scheduler + +interface SchedulersManager { + + fun mainThread(): Scheduler + + fun backgroundThread(): Scheduler +} diff --git a/app/src/main/java/io/github/wulkanowy/utils/schedulers/SchedulersProvider.kt b/app/src/main/java/io/github/wulkanowy/utils/schedulers/SchedulersProvider.kt new file mode 100644 index 00000000..8201e85b --- /dev/null +++ b/app/src/main/java/io/github/wulkanowy/utils/schedulers/SchedulersProvider.kt @@ -0,0 +1,12 @@ +package io.github.wulkanowy.utils.schedulers + +import io.reactivex.Scheduler +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.schedulers.Schedulers + +class SchedulersProvider : SchedulersManager { + + override fun mainThread(): Scheduler = AndroidSchedulers.mainThread() + + override fun backgroundThread(): Scheduler = Schedulers.io() +} \ No newline at end of file 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..d3d53c54 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 @@ -49,18 +49,14 @@ object Scrambler { @JvmStatic fun encrypt(plainText: String, context: Context): String { - if (StringUtils.isEmpty(plainText)) { - throw ScramblerException("Text to be encrypted is empty") - } + 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) } - try { - if (!isKeyPairExist()) { - generateKeyPair(context) - } + return try { + if (!isKeyPairExist()) generateKeyPair(context) val cipher = getCipher() cipher.init(ENCRYPT_MODE, getPublicKey()) @@ -70,26 +66,23 @@ object Scrambler { 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) + Base64.encodeToString(outputStream.toByteArray(), DEFAULT) + } catch (exception: Exception) { + Timber.e(exception, "An error occurred while encrypting text") + String(Base64.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 (StringUtils.isEmpty(cipherText)) throw ScramblerException("Text to be encrypted is empty") - if (SDK_INT < JELLY_BEAN_MR2) { + if (SDK_INT < JELLY_BEAN_MR2 || cipherText.length < 250) { return String(Base64.decode(cipherText.toByteArray(KEY_CHARSET), DEFAULT), KEY_CHARSET) } - if (!isKeyPairExist()) { - throw ScramblerException("KeyPair doesn't exist") - } + if (!isKeyPairExist()) throw ScramblerException("KeyPair doesn't exist") try { val cipher = getCipher() @@ -111,7 +104,6 @@ object Scrambler { } catch (e: Exception) { throw ScramblerException("An error occurred while decrypting text", e) } - } private fun getKeyStoreInstance(): KeyStore { @@ -130,11 +122,8 @@ object Scrambler { 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) + return if (SDK_INT >= M) Cipher.getInstance(KEY_TRANSFORMATION_ALGORITHM, KEY_CIPHER_M_PROVIDER) + else Cipher.getInstance(KEY_TRANSFORMATION_ALGORITHM, KEY_CIPHER_JELLY_PROVIDER) } @TargetApi(JELLY_BEAN_MR2) 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/layout/activity_login.xml b/app/src/main/res/layout/activity_login.xml index 4a6f08b2..35a681f0 100644 --- a/app/src/main/res/layout/activity_login.xml +++ b/app/src/main/res/layout/activity_login.xml @@ -1,137 +1,11 @@ - + android:id="@+id/loginContainer"> - - + android:layout_height="match_parent" /> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -