From 4a4ce3e6566afc8b9bb894822d2599c85d8d5198 Mon Sep 17 00:00:00 2001 From: Alberto Moreta Date: Fri, 15 Sep 2023 12:51:58 +0200 Subject: [PATCH] OPPIA-1369, OPPIA-1384: Migrate model package to Kotlin --- app/build.gradle | 5 +- .../oppia/database/DbHelper.java | 12 +- .../digitalcampus/oppia/model/Activity.java | 254 -------------- .../org/digitalcampus/oppia/model/Activity.kt | 128 +++++++ .../oppia/model/ActivityCount.java | 40 --- .../oppia/model/ActivityCount.kt | 30 ++ .../oppia/model/ActivityLogRepository.java | 41 --- .../oppia/model/ActivityLogRepository.kt | 36 ++ .../oppia/model/ActivityType.java | 68 ---- .../digitalcampus/oppia/model/ActivityType.kt | 14 + .../org/digitalcampus/oppia/model/Badge.java | 76 ----- .../org/digitalcampus/oppia/model/Badge.kt | 49 +++ .../oppia/model/CompleteCourse.java | 119 ------- .../oppia/model/CompleteCourse.kt | 73 ++++ .../oppia/model/CompleteCourseProvider.java | 47 --- .../oppia/model/CompleteCourseProvider.kt | 45 +++ .../org/digitalcampus/oppia/model/Course.java | 317 ------------------ .../org/digitalcampus/oppia/model/Course.kt | 168 ++++++++++ .../oppia/model/CourseInstallRepository.java | 25 -- .../oppia/model/CourseInstallRepository.kt | 20 ++ .../oppia/model/CourseInstallViewAdapter.java | 199 ----------- .../oppia/model/CourseInstallViewAdapter.kt | 129 +++++++ .../oppia/model/CourseMetaPage.java | 57 ---- ...ownloadProgress.java => CourseMetaPage.kt} | 42 +-- .../oppia/model/CourseTransferableFile.java | 147 -------- .../oppia/model/CourseTransferableFile.kt | 72 ++++ .../oppia/model/CoursesRepository.java | 36 -- .../oppia/model/CoursesRepository.kt | 31 ++ .../oppia/model/CustomFieldsRepository.java | 25 -- .../oppia/model/CustomFieldsRepository.kt | 22 ++ .../oppia/model/CustomValue.java | 30 -- .../digitalcampus/oppia/model/CustomValue.kt | 17 + .../oppia/model/DownloadProgress.kt | 29 ++ .../oppia/model/GamificationEvent.java | 67 ---- .../oppia/model/GamificationEvent.kt | 55 +++ .../org/digitalcampus/oppia/model/Lang.java | 93 ----- .../org/digitalcampus/oppia/model/Lang.kt | 59 ++++ .../org/digitalcampus/oppia/model/Media.java | 147 -------- .../org/digitalcampus/oppia/model/Media.kt | 84 +++++ .../oppia/model/MultiLangInfoModel.java | 181 ---------- .../oppia/model/MultiLangInfoModel.kt | 184 ++++++++++ .../oppia/model/OfflineCourseFile.java | 67 ---- .../oppia/model/OfflineCourseFile.kt | 50 +++ .../org/digitalcampus/oppia/model/Points.java | 78 ----- .../org/digitalcampus/oppia/model/Points.kt | 49 +++ .../oppia/model/QuizAnswerFeedback.java | 64 ---- .../oppia/model/QuizAnswerFeedback.kt | 30 ++ .../oppia/model/QuizAttempt.java | 239 ------------- .../digitalcampus/oppia/model/QuizAttempt.kt | 93 +++++ .../oppia/model/QuizAttemptRepository.java | 35 -- .../oppia/model/QuizAttemptRepository.kt | 30 ++ .../digitalcampus/oppia/model/QuizStats.java | 93 ----- .../digitalcampus/oppia/model/QuizStats.kt | 54 +++ .../oppia/model/SearchResult.java | 61 ---- .../digitalcampus/oppia/model/SearchResult.kt | 32 ++ .../digitalcampus/oppia/model/Section.java | 125 ------- .../org/digitalcampus/oppia/model/Section.kt | 65 ++++ .../org/digitalcampus/oppia/model/Tag.java | 119 ------- .../java/org/digitalcampus/oppia/model/Tag.kt | 64 ++++ .../oppia/model/TagRepository.java | 122 ------- .../oppia/model/TagRepository.kt | 120 +++++++ .../digitalcampus/oppia/model/TrackerLog.java | 125 ------- .../digitalcampus/oppia/model/TrackerLog.kt | 50 +++ .../oppia/model/TrackerLogRepository.java | 15 - .../oppia/model/TrackerLogRepository.kt | 13 + .../org/digitalcampus/oppia/model/User.java | 295 ---------------- .../org/digitalcampus/oppia/model/User.kt | 158 +++++++++ .../model/coursecomplete/AllActivities.java | 27 -- .../model/coursecomplete/AllActivities.kt | 21 ++ .../model/coursecomplete/AllQuizzes.java | 27 -- .../oppia/model/coursecomplete/AllQuizzes.kt | 21 ++ .../coursecomplete/AllQuizzesPlusPercent.java | 51 --- .../coursecomplete/AllQuizzesPlusPercent.kt | 43 +++ .../oppia/model/coursecomplete/FinalQuiz.java | 23 -- .../oppia/model/coursecomplete/FinalQuiz.kt | 19 ++ .../oppia/model/db_model/Leaderboard.java | 126 ------- .../oppia/model/db_model/Leaderboard.kt | 55 +++ .../oppia/model/db_model/UserCustomField.java | 94 ------ .../oppia/model/db_model/UserCustomField.kt | 28 ++ .../oppia/model/db_model/UserPreference.java | 56 ---- .../oppia/model/db_model/UserPreference.kt | 17 + .../oppia/model/responses/CourseServer.java | 120 ------- .../oppia/model/responses/CourseServer.kt | 22 ++ .../responses/CoursesServerResponse.java | 15 - .../model/responses/CoursesServerResponse.kt | 5 + .../ui/fields/CustomFieldsUIManager.java | 11 +- .../oppia/widgets/FeedbackWidget.java | 2 +- 87 files changed, 2321 insertions(+), 3981 deletions(-) delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/Activity.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/Activity.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/ActivityCount.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/ActivityCount.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/ActivityLogRepository.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/ActivityLogRepository.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/ActivityType.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/ActivityType.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/Badge.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/Badge.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/CompleteCourse.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/CompleteCourse.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/CompleteCourseProvider.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/CompleteCourseProvider.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/Course.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/Course.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/CourseInstallRepository.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/CourseInstallRepository.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/CourseInstallViewAdapter.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/CourseInstallViewAdapter.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/CourseMetaPage.java rename app/src/main/java/org/digitalcampus/oppia/model/{DownloadProgress.java => CourseMetaPage.kt} (55%) delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/CourseTransferableFile.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/CourseTransferableFile.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/CoursesRepository.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/CoursesRepository.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/CustomFieldsRepository.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/CustomFieldsRepository.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/CustomValue.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/CustomValue.kt create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/DownloadProgress.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/GamificationEvent.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/GamificationEvent.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/Lang.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/Lang.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/Media.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/Media.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/MultiLangInfoModel.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/MultiLangInfoModel.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/OfflineCourseFile.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/OfflineCourseFile.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/Points.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/Points.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/QuizAnswerFeedback.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/QuizAnswerFeedback.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/QuizAttempt.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/QuizAttempt.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/QuizAttemptRepository.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/QuizAttemptRepository.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/QuizStats.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/QuizStats.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/SearchResult.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/SearchResult.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/Section.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/Section.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/Tag.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/Tag.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/TagRepository.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/TagRepository.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/TrackerLog.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/TrackerLog.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/TrackerLogRepository.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/TrackerLogRepository.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/User.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/User.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllActivities.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllActivities.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllQuizzes.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllQuizzes.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllQuizzesPlusPercent.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllQuizzesPlusPercent.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/FinalQuiz.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/FinalQuiz.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/db_model/Leaderboard.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/db_model/Leaderboard.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/db_model/UserCustomField.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/db_model/UserCustomField.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/db_model/UserPreference.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/db_model/UserPreference.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/responses/CourseServer.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/responses/CourseServer.kt delete mode 100644 app/src/main/java/org/digitalcampus/oppia/model/responses/CoursesServerResponse.java create mode 100644 app/src/main/java/org/digitalcampus/oppia/model/responses/CoursesServerResponse.kt diff --git a/app/build.gradle b/app/build.gradle index 81f00a903..5ad3731f1 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -4,6 +4,7 @@ apply plugin: 'com.android.application' apply from: '../jacoco.gradle' apply from: '../sonarqube.gradle' apply plugin: 'kotlin-android' +apply plugin: 'kotlin-kapt' repositories { maven { url "https://jitpack.io" } @@ -303,8 +304,8 @@ dependencies { implementation "com.google.dagger:dagger:$daggerVersion" implementation "com.google.dagger:dagger-android:$daggerVersion" implementation "com.google.dagger:dagger-android-support:$daggerVersion" - annotationProcessor "com.google.dagger:dagger-android-processor:$daggerVersion" - annotationProcessor "com.google.dagger:dagger-compiler:$daggerVersion" + kapt "com.google.dagger:dagger-android-processor:$daggerVersion" + kapt "com.google.dagger:dagger-compiler:$daggerVersion" androidTestImplementation 'com.github.fabioCollini.daggermock:daggermock:0.8.5' implementation "com.squareup.inject:assisted-inject-annotations-dagger2:0.8.1" diff --git a/app/src/main/java/org/digitalcampus/oppia/database/DbHelper.java b/app/src/main/java/org/digitalcampus/oppia/database/DbHelper.java index 04a2b140f..ca4a4b866 100644 --- a/app/src/main/java/org/digitalcampus/oppia/database/DbHelper.java +++ b/app/src/main/java/org/digitalcampus/oppia/database/DbHelper.java @@ -39,17 +39,21 @@ import org.digitalcampus.oppia.gamification.Gamification; import org.digitalcampus.oppia.gamification.PointsComparator; import org.digitalcampus.oppia.model.Activity; +import org.digitalcampus.oppia.model.BooleanValue; import org.digitalcampus.oppia.model.CompleteCourse; import org.digitalcampus.oppia.model.Course; import org.digitalcampus.oppia.model.CustomField; import org.digitalcampus.oppia.model.CustomValue; +import org.digitalcampus.oppia.model.FloatValue; import org.digitalcampus.oppia.model.GamificationEvent; +import org.digitalcampus.oppia.model.IntValue; import org.digitalcampus.oppia.model.Media; import org.digitalcampus.oppia.model.Points; import org.digitalcampus.oppia.model.QuizAttempt; import org.digitalcampus.oppia.model.QuizStats; import org.digitalcampus.oppia.model.SearchResult; import org.digitalcampus.oppia.model.Section; +import org.digitalcampus.oppia.model.StringValue; import org.digitalcampus.oppia.model.TrackerLog; import org.digitalcampus.oppia.model.User; import org.digitalcampus.oppia.model.db_model.Leaderboard; @@ -1617,16 +1621,16 @@ private void fetchUserCustomFields(User u) { if (field.isString() || field.isChoices()) { // Internally, we just save the choices key value as a str String value = c.getString(c.getColumnIndex(CF_VALUE_STR)); - u.putCustomField(key, new CustomValue<>(value)); + u.putCustomField(key, new CustomValue(new StringValue(value))); } else if (field.isBoolean()) { boolean value = c.getInt(c.getColumnIndex(CF_VALUE_BOOL)) == 1; - u.putCustomField(key, new CustomValue<>(value)); + u.putCustomField(key, new CustomValue(new BooleanValue(value))); } else if (field.isInteger()) { int value = c.getInt(c.getColumnIndex(CF_VALUE_INT)); - u.putCustomField(key, new CustomValue<>(value)); + u.putCustomField(key, new CustomValue(new IntValue(value))); } else if (field.isFloat()) { float value = c.getFloat(c.getColumnIndex(CF_VALUE_FLOAT)); - u.putCustomField(key, new CustomValue<>(value)); + u.putCustomField(key, new CustomValue(new FloatValue(value))); } } } diff --git a/app/src/main/java/org/digitalcampus/oppia/model/Activity.java b/app/src/main/java/org/digitalcampus/oppia/model/Activity.java deleted file mode 100644 index 433adb82b..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/Activity.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import android.util.Log; - -import java.io.File; -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import org.digitalcampus.mobile.learning.R; -import org.digitalcampus.oppia.analytics.Analytics; -import org.digitalcampus.oppia.exception.GamificationEventNotFound; -import org.digitalcampus.oppia.utils.storage.FileUtils; - - -public class Activity extends MultiLangInfoModel implements Serializable{ - - /** - * - */ - private static final long serialVersionUID = -1548943805902073988L; - - public static final String TAG = Activity.class.getSimpleName(); - - private long courseId; - private int sectionId; - private int actId; - private int dbId; - private String actType; - private List locations = new ArrayList<>(); - private List contents = new ArrayList<>(); - private String digest; - private String imageFile; - private List media = new ArrayList<>(); - private boolean completed = false; - private boolean attempted = false; - private boolean customImage = false; - private String mimeType; - private List gamificationEvents = new ArrayList<>(); - private int wordCount; - - public Activity(){ - // do nothing - } - - public boolean hasCustomImage(){ - return this.customImage; - } - - public String getImageFilePath(String prefix){ - if(!prefix.endsWith(File.separator)){ - prefix += File.separator; - } - return prefix + this.imageFile; - } - - public int getDefaultResourceImage(){ - if(actType.equals("quiz")){ - return R.drawable.default_icon_quiz; - } else if (actType.equals("page") && this.hasMedia()){ - return R.drawable.default_icon_video; - } - return R.drawable.default_icon_activity; - } - - public void setImageFile(String imageFile) { - this.imageFile = imageFile; - this.customImage = true; - } - - public List getMedia() { - return media; - } - - public Media getMedia(String filename){ - for (Media m : getMedia()) { - if (m.getFilename().equals(filename)) { - return m; - } - } - return null; - } - - public void setMedia(List media) { - this.media = media; - } - - public String getDigest() { - return digest; - } - - public void setDigest(String digest) { - this.digest = digest; - } - - public long getCourseId() { - return courseId; - } - - public void setCourseId(long courseId) { - this.courseId = courseId; - } - - public int getSectionId() { - return sectionId; - } - - public void setSectionId(int sectionId) { - this.sectionId = sectionId; - } - - public int getActId() { - return actId; - } - - public void setActId(int actId) { - this.actId = actId; - } - - public String getActType() { - return actType; - } - - public void setActType(String actType) { - this.actType = actType; - } - - public String getLocation(String lang) { - for(Lang l: locations){ - if(l.getLanguage().equalsIgnoreCase(lang)){ - return l.getContent(); - } - } - if(locations.isEmpty()){ - return null; - } else { - return locations.get(0).getContent(); - } - - } - - public void setLocations(List locations) { - this.locations = locations; - } - - public String getContents(String lang) { - for(Lang l: contents){ - if(l.getLanguage().equalsIgnoreCase(lang)){ - return l.getContent(); - } - } - if(contents.isEmpty()) { - return "No content"; - } else { - return contents.get(0).getContent(); - } - - } - - public String getFileContents(String courseLocation, String lang){ - StringBuilder fileContent = new StringBuilder(); - if (getLocation(lang) != null && !getActType().equals("url")) { - String url = courseLocation + getLocation(lang); - try { - fileContent.append(" "); - fileContent.append(FileUtils.readFile(url)); - return fileContent.toString().trim(); - } catch (IOException e) { - Analytics.logException(e); - Log.d(TAG, "IOException:", e); - } - } - return null; - } - - public void setContents(List contents) { - this.contents = contents; - } - - public boolean hasMedia(){ - return !media.isEmpty(); - } - - public void setCompleted(boolean completed){ - this.completed = completed; - } - - public boolean getCompleted(){ - return this.completed; - } - - public String getMimeType() { - return mimeType; - } - - public void setMimeType(String mimeType) { - this.mimeType = mimeType; - } - - public boolean isAttempted() { - return attempted; - } - - public void setAttempted(boolean attempted) { - this.attempted = attempted; - } - - public int getDbId() { - return dbId; - } - - public void setDbId(int dbId) { - this.dbId = dbId; - } - - public void setGamificationEvents(List events){ - gamificationEvents = events; - } - - public GamificationEvent findGamificationEvent(String event) throws GamificationEventNotFound { - for(GamificationEvent ge: gamificationEvents){ - if(ge.getEvent().equals(event)){ - return ge; - } - } - throw new GamificationEventNotFound(event); - } - - public int getWordCount() { - return wordCount; - } - - public void setWordCount(int wordCount) { - this.wordCount = wordCount; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/Activity.kt b/app/src/main/java/org/digitalcampus/oppia/model/Activity.kt new file mode 100644 index 000000000..251d70de6 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/Activity.kt @@ -0,0 +1,128 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import android.util.Log +import org.digitalcampus.mobile.learning.R +import org.digitalcampus.oppia.analytics.Analytics +import org.digitalcampus.oppia.exception.GamificationEventNotFound +import org.digitalcampus.oppia.utils.storage.FileUtils +import java.io.File +import java.io.IOException +import java.io.Serializable + +class Activity : MultiLangInfoModel(), Serializable { + companion object { + private const val serialVersionUID = -1548943805902073988L + @JvmField + val TAG = Activity::class.simpleName + } + + var courseId: Long = 0 + var sectionId = 0 + var actId = 0 + var dbId = 0 + var actType: String? = null + private var locations: List = ArrayList() + private var contents: List = ArrayList() + var digest: String? = null + private var imageFile: String? = null + var media: List = ArrayList() + var completed = false + var isAttempted = false + private var customImage = false + var mimeType: String? = null + private var gamificationEvents: List = ArrayList() + var wordCount = 0 + + fun hasCustomImage(): Boolean { + return customImage + } + + fun getImageFilePath(prefix: String): String { + var prefixedPath = prefix + if (!prefixedPath.endsWith(File.separator)) { + prefixedPath += File.separator + } + return prefixedPath + imageFile + } + + fun getDefaultResourceImage(): Int { + return when(actType) { + "quiz" -> R.drawable.default_icon_quiz + "activity" -> if (hasMedia()) R.drawable.default_icon_video else R.drawable.default_icon_activity + else -> R.drawable.default_icon_activity + } + } + + fun setImageFile(imageFile: String?) { + this.imageFile = imageFile + customImage = true + } + + fun hasMedia(): Boolean { + return media.isNotEmpty() + } + + fun getMedia(filename: String): Media? { + return media.find { it.filename == filename } + } + + fun getLocation(lang: String?): String? { + val matchingLang = locations.find { it.language.equals(lang, ignoreCase = true) } + return matchingLang?.content ?: if (locations.isNotEmpty()) locations[0].content else null + } + + fun setLocations(locations: List) { + this.locations = locations + } + + fun getContents(lang: String?): String { + val matchingLang = contents.find { it.language.equals(lang, ignoreCase = true) } + return matchingLang?.content ?: if (contents.isNotEmpty()) contents[0].content else "No content" + } + + fun getFileContents(courseLocation: String, lang: String?): String? { + val fileContent = StringBuilder() + if (getLocation(lang) != null && actType != "url") { + val url = courseLocation + getLocation(lang) + try { + fileContent.append(" ") + fileContent.append(FileUtils.readFile(url)) + return fileContent.toString().trim() + } catch (e: IOException) { + Analytics.logException(e) + Log.d(TAG, "IOException:", e) + } + } + return null + } + + fun setContents(contents: List) { + this.contents = contents + } + + fun setGamificationEvents(events: List) { + gamificationEvents = events + } + + @Throws(GamificationEventNotFound::class) + fun findGamificationEvent(event: String): GamificationEvent { + return gamificationEvents.find { it.event == event } + ?: throw GamificationEventNotFound(event) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/ActivityCount.java b/app/src/main/java/org/digitalcampus/oppia/model/ActivityCount.java deleted file mode 100644 index 85cb68f67..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/ActivityCount.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.digitalcampus.oppia.model; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -public class ActivityCount { - - private Map typeCount = new LinkedHashMap<>(); - - public static ActivityCount initialize(List activityTypes) { - ActivityCount activityCount = new ActivityCount(); - for (ActivityType activityType : activityTypes) { - activityCount.getTypeCount().put(activityType.getType(), 0); - } - return activityCount; - } - - public Map getTypeCount() { - return typeCount; - } - - public void setTypeCount(Map typeCount) { - this.typeCount = typeCount; - } - - public void incrementNumberActivityType(String type) { - int incrementedActivitiesNumber = typeCount.get(type) + 1; - typeCount.put(type, incrementedActivitiesNumber); - } - - public int getValueForType(String type) { - Integer value = typeCount.get(type); - return value != null ? value : 0; - } - - public boolean hasValidEvent(String event) { - return typeCount.containsKey(event); - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/ActivityCount.kt b/app/src/main/java/org/digitalcampus/oppia/model/ActivityCount.kt new file mode 100644 index 000000000..5e250e6c8 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/ActivityCount.kt @@ -0,0 +1,30 @@ +package org.digitalcampus.oppia.model + +class ActivityCount { + var typeCount: MutableMap = LinkedHashMap() + + companion object { + @JvmStatic + fun initialize(activityTypes: List): ActivityCount { + val activityCount = ActivityCount() + for (activityType in activityTypes) { + activityCount.typeCount[activityType.type] = 0 + } + return activityCount + } + } + + + fun incrementNumberActivityType(type: String) { + typeCount[type] = typeCount.getOrDefault(type, 0) + 1 + } + + fun getValueForType(type: String): Int { + return typeCount[type] ?: 0 + } + + fun hasValidEvent(event: String): Boolean { + return typeCount.containsKey(event) + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/ActivityLogRepository.java b/app/src/main/java/org/digitalcampus/oppia/model/ActivityLogRepository.java deleted file mode 100644 index 494bd6007..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/ActivityLogRepository.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.digitalcampus.oppia.model; - -import android.content.Context; - -import org.digitalcampus.oppia.utils.storage.Storage; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -public class ActivityLogRepository { - - public List getExportedActivityLogs(Context ctx){ - List files = new ArrayList<>(); - File activityFolder = new File(Storage.getActivityPath(ctx)); - if (activityFolder.exists()) { - File[] children = activityFolder.listFiles(); - for (File dirFile : children) { - if (dirFile.isFile()) { - files.add(dirFile); - } - } - } - return files; - } - - public List getArchivedActivityLogs(Context ctx){ - List files = new ArrayList<>(); - File archivedFolder = new File(Storage.getActivityArchivePath(ctx)); - if (archivedFolder.exists()) { - String[] children = archivedFolder.list(); - for (String dirFiles : children) { - File exportedActivity = new File(archivedFolder, dirFiles); - if (exportedActivity.isFile()) { - files.add(exportedActivity); - } - } - } - return files; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/ActivityLogRepository.kt b/app/src/main/java/org/digitalcampus/oppia/model/ActivityLogRepository.kt new file mode 100644 index 000000000..53b4c67c4 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/ActivityLogRepository.kt @@ -0,0 +1,36 @@ +package org.digitalcampus.oppia.model + +import android.content.Context +import org.digitalcampus.oppia.utils.storage.Storage +import java.io.File + +class ActivityLogRepository { + fun getExportedActivityLogs(ctx: Context): List { + val files = ArrayList() + val activityFolder = File(Storage.getActivityPath(ctx)) + if (activityFolder.exists()) { + val children = activityFolder.listFiles() + for (dirFile in children!!) { + if (dirFile.isFile) { + files.add(dirFile) + } + } + } + return files + } + + fun getArchivedActivityLogs(ctx: Context): List { + val files = ArrayList() + val archivedFolder = File(Storage.getActivityArchivePath(ctx)) + if (archivedFolder.exists()) { + val children = archivedFolder.list() + for (dirFiles in children!!) { + val exportedActivity = File(archivedFolder, dirFiles) + if (exportedActivity.isFile) { + files.add(exportedActivity) + } + } + } + return files + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/ActivityType.java b/app/src/main/java/org/digitalcampus/oppia/model/ActivityType.java deleted file mode 100644 index 21bb51048..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/ActivityType.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.digitalcampus.oppia.model; - -import java.util.ArrayList; -import java.util.List; - -public class ActivityType { - - public static final String ALL = "all"; - - private String name; - private String type; - private int color; - private boolean enabled; - - private List values = new ArrayList<>(); - - public ActivityType(String name, String type, int color, boolean enabled) { - this.name = name; - this.type = type; - this.color = color; - this.enabled = enabled; - } - - @Override - public String toString() { - return name; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public int getColor() { - return color; - } - - public void setColor(int color) { - this.color = color; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getValues() { - return values; - } - - public void setValues(List values) { - this.values = values; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/ActivityType.kt b/app/src/main/java/org/digitalcampus/oppia/model/ActivityType.kt new file mode 100644 index 000000000..971411b49 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/ActivityType.kt @@ -0,0 +1,14 @@ +package org.digitalcampus.oppia.model + +class ActivityType(var name: String, var type: String, var color: Int, var isEnabled: Boolean) { + + companion object { + const val ALL = "all" + } + + var values = ArrayList() + + override fun toString(): String { + return name + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/Badge.java b/app/src/main/java/org/digitalcampus/oppia/model/Badge.java deleted file mode 100644 index b2fd8b60e..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/Badge.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import org.digitalcampus.oppia.utils.DateUtils; -import org.joda.time.DateTime; - -public class Badge { - - private DateTime datetime; - private String description; - private String icon; - private String certificatePdf; - - public static final String BADGE_CRITERIA_ALL_ACTIVITIES = "all_activities"; - public static final String BADGE_CRITERIA_ALL_QUIZZES = "all_quizzes"; - public static final String BADGE_CRITERIA_FINAL_QUIZ = "final_quiz"; - public static final String BADGE_CRITERIA_ALL_QUIZZES_PERCENT = "all_quizzes_plus_percent"; - - public Badge(){ - - } - - public Badge(DateTime datetime, String description) { - this.datetime = datetime; - this.description = description; - } - - public String getDateAsString() { - return DateUtils.DATE_FORMAT.print(datetime); - } - - public void setDateTime(String date) { - this.datetime = DateUtils.DATETIME_FORMAT.parseDateTime(date); - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getIcon() { - return icon; - } - - public void setIcon(String icon) { - this.icon = icon; - } - - public String getCertificatePdf() { - return certificatePdf; - } - - public void setCertificatePdf(String certificatePdf) { - this.certificatePdf = certificatePdf; - } - -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/Badge.kt b/app/src/main/java/org/digitalcampus/oppia/model/Badge.kt new file mode 100644 index 000000000..ec7c2eafd --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/Badge.kt @@ -0,0 +1,49 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import org.digitalcampus.oppia.utils.DateUtils +import org.joda.time.DateTime + +class Badge { + private var datetime: DateTime? = null + var description: String? = null + var icon: String? = null + var certificatePdf: String? = null + + companion object { + const val BADGE_CRITERIA_ALL_ACTIVITIES = "all_activities" + const val BADGE_CRITERIA_ALL_QUIZZES = "all_quizzes" + const val BADGE_CRITERIA_FINAL_QUIZ = "final_quiz" + const val BADGE_CRITERIA_ALL_QUIZZES_PERCENT = "all_quizzes_plus_percent" + } + + constructor() {} + constructor(datetime: DateTime?, description: String?) { + this.datetime = datetime + this.description = description + } + + fun getDateAsString(): String? { + return DateUtils.DATE_FORMAT.print(datetime) + } + + fun setDateTime(date: String?) { + datetime = DateUtils.DATETIME_FORMAT.parseDateTime(date) + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/CompleteCourse.java b/app/src/main/java/org/digitalcampus/oppia/model/CompleteCourse.java deleted file mode 100644 index ea4cae807..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/CompleteCourse.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import android.content.Context; - -import org.digitalcampus.oppia.database.DbHelper; -import org.digitalcampus.oppia.application.SessionManager; -import org.digitalcampus.oppia.utils.xmlreaders.IMediaXMLHandler; - -import java.util.ArrayList; -import java.util.List; - -public class CompleteCourse extends Course implements IMediaXMLHandler{ - - private List baseline = new ArrayList<>(); - private List
sections = new ArrayList<>(); - private List gamification = new ArrayList<>(); - - public CompleteCourse(){ - super(""); - } - public CompleteCourse(String root) { - super(root); - } - - public void setBaselineActivities(List baseline) { - this.baseline = baseline; - } - public List getBaselineActivities() { - return baseline; - } - - public void setSections(List
sections) { this.sections = sections; } - public void setGamification(List gamification) { this.gamification = gamification; } - - public List
getSections() { - return sections; - } - - public Section getSection(int order){ - for (Section section : sections){ - if (section.getOrder() == order) return section; - } - return null; - } - - public Activity getActivityByDigest(String digest){ - for (Section section : sections){ - for (Activity act : section.getActivities()) - if (act.getDigest().equals(digest)) - return act; - } - return null; - } - - public Section getSectionByActivityDigest(String digest){ - for (Section section : sections){ - for (Activity act : section.getActivities()) - if (act.getDigest().equals(digest)) - return section; - } - return null; - } - - public List getGamification() { - return gamification; - } - - public void updateCourseActivity(Context ctx){ - - DbHelper db = DbHelper.getInstance(ctx); - long userId = db.getUserId(SessionManager.getUsername(ctx)); - - for (Section section : sections){ - if (section.isProtectedByPassword()){ - section.setUnlocked(db.sectionUnlocked(getCourseId(), section.getOrder(), userId)); - } - for (Activity activity : section.getActivities()){ - activity.setCompleted(db.activityCompleted(getCourseId(), activity.getDigest(), userId)); - } - } - for (Activity activity : baseline){ - activity.setAttempted(db.activityAttempted(getCourseId(), activity.getDigest(), userId)); - } - } - - - public List getActivities(long courseId) { - ArrayList activities = new ArrayList<>(); - for (Section section : sections){ - for (Activity act : section.getActivities()){ - act.setCourseId(courseId); - activities.add(act); - } - } - return activities; - } - - @Override - public List getCourseMedia() { - return getMedia(); - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/CompleteCourse.kt b/app/src/main/java/org/digitalcampus/oppia/model/CompleteCourse.kt new file mode 100644 index 000000000..5234a0b65 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/CompleteCourse.kt @@ -0,0 +1,73 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import android.content.Context +import org.digitalcampus.oppia.application.SessionManager +import org.digitalcampus.oppia.database.DbHelper +import org.digitalcampus.oppia.utils.xmlreaders.IMediaXMLHandler + +class CompleteCourse : Course, IMediaXMLHandler { + var baselineActivities = ArrayList() + var sections = ArrayList
() + var gamification = ArrayList() + + constructor() : super("") {} + constructor(root: String?) : super(root) {} + + fun getSection(order: Int): Section? { + return sections.find { it.order == order } + } + + fun getActivityByDigest(digest: String): Activity? { + return sections.flatMap { it.activities }.find { it.digest == digest } + } + + fun getSectionByActivityDigest(digest: String): Section? { + return sections.find { section -> section.activities.any { it.digest == digest } } + } + + fun updateCourseActivity(ctx: Context?) { + val db = DbHelper.getInstance(ctx) + val userId = db.getUserId(SessionManager.getUsername(ctx)) + for (section in sections) { + if (section.isProtectedByPassword) { + section.isUnlocked = db.sectionUnlocked(courseId.toLong(), section.order, userId) + } + for (activity in section.activities) { + activity.completed = db.activityCompleted(courseId, activity.digest, userId) + } + } + for (activity in baselineActivities) { + activity.isAttempted = db.activityAttempted(courseId.toLong(), activity.digest, userId) + } + } + + fun getActivities(courseId: Long): List { + val activities = ArrayList() + for (section in sections) { + for (act in section.activities) { + act.courseId = courseId + activities.add(act) + } + } + return activities + } + + override val courseMedia: MutableList + get() = media +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/CompleteCourseProvider.java b/app/src/main/java/org/digitalcampus/oppia/model/CompleteCourseProvider.java deleted file mode 100644 index 5fa4a7890..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/CompleteCourseProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.digitalcampus.oppia.model; - -import android.content.Context; -import android.util.Log; - -import org.digitalcampus.mobile.learning.R; -import org.digitalcampus.oppia.activity.CourseIndexActivity; -import org.digitalcampus.oppia.analytics.Analytics; -import org.digitalcampus.oppia.exception.InvalidXMLException; -import org.digitalcampus.oppia.task.ParseCourseXMLTask; -import org.digitalcampus.oppia.utils.UIUtils; -import org.digitalcampus.oppia.utils.xmlreaders.CourseXMLReader; - -import java.util.concurrent.Callable; - - - -public class CompleteCourseProvider { - - public static final String TAG = CompleteCourseProvider.class.getSimpleName(); - - public CompleteCourse getCompleteCourseSync(Context ctx, Course course){ - try { - CourseXMLReader cxr = new CourseXMLReader(course.getCourseXMLLocation(), course.getCourseId(), ctx); - cxr.parse(CourseXMLReader.ParseMode.COMPLETE); - return cxr.getParsedCourse(); - } catch (InvalidXMLException e) { - Analytics.logException(e); - Log.d(TAG, "Error loading course XML: ", e); - showErrorMessage(ctx); - return null; - } - } - - public void getCompleteCourseAsync(Context ctx, Course course){ - ParseCourseXMLTask task = new ParseCourseXMLTask(ctx); - task.setListener((ParseCourseXMLTask.OnParseXmlListener) ctx); - task.execute(course); - } - - private void showErrorMessage(final Context ctx){ - UIUtils.showAlert(ctx, R.string.error, R.string.error_reading_xml, () -> { - ((CourseIndexActivity) ctx).finish(); - return true; - }); - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/CompleteCourseProvider.kt b/app/src/main/java/org/digitalcampus/oppia/model/CompleteCourseProvider.kt new file mode 100644 index 000000000..5df1c4782 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/CompleteCourseProvider.kt @@ -0,0 +1,45 @@ +package org.digitalcampus.oppia.model + +import android.content.Context +import android.util.Log +import org.digitalcampus.mobile.learning.R +import org.digitalcampus.oppia.activity.CourseIndexActivity +import org.digitalcampus.oppia.analytics.Analytics +import org.digitalcampus.oppia.exception.InvalidXMLException +import org.digitalcampus.oppia.task.ParseCourseXMLTask +import org.digitalcampus.oppia.task.ParseCourseXMLTask.OnParseXmlListener +import org.digitalcampus.oppia.utils.UIUtils +import org.digitalcampus.oppia.utils.xmlreaders.CourseXMLReader + +class CompleteCourseProvider { + + companion object { + val TAG = CompleteCourseProvider::class.simpleName + } + + fun getCompleteCourseSync(ctx: Context, course: Course): CompleteCourse? { + return try { + val cxr = CourseXMLReader(course.courseXMLLocation, course.courseId.toLong(), ctx) + cxr.parse(CourseXMLReader.ParseMode.COMPLETE) + cxr.getParsedCourse() + } catch (e: InvalidXMLException) { + Analytics.logException(e) + Log.d(TAG, "Error loading course XML: ", e) + showErrorMessage(ctx) + null + } + } + + fun getCompleteCourseAsync(ctx: Context?, course: Course?) { + val task = ParseCourseXMLTask(ctx) + task.setListener(ctx as OnParseXmlListener?) + task.execute(course) + } + + private fun showErrorMessage(ctx: Context) { + UIUtils.showAlert(ctx, R.string.error, R.string.error_reading_xml) { + (ctx as CourseIndexActivity).finish() + true + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/Course.java b/app/src/main/java/org/digitalcampus/oppia/model/Course.java deleted file mode 100644 index 0a56ea60c..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/Course.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import android.content.Context; - -import org.digitalcampus.oppia.api.Paths; -import org.digitalcampus.oppia.application.App; -import org.digitalcampus.oppia.exception.CourseNotFoundException; -import org.digitalcampus.oppia.exception.GamificationEventNotFound; -import org.digitalcampus.oppia.model.coursecomplete.AllActivities; -import org.digitalcampus.oppia.model.coursecomplete.AllQuizzes; -import org.digitalcampus.oppia.model.coursecomplete.AllQuizzesPlusPercent; -import org.digitalcampus.oppia.model.coursecomplete.FinalQuiz; -import org.digitalcampus.oppia.utils.TextUtilsJava; -import org.digitalcampus.oppia.utils.storage.Storage; - -import java.io.File; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -public class Course extends MultiLangInfoModel implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 4412987572522420704L; - public static final String SEQUENCING_MODE_NONE = "none"; - public static final String SEQUENCING_MODE_SECTION = "section"; - public static final String SEQUENCING_MODE_COURSE = "course"; - - public static final String TAG = Course.class.getSimpleName(); - - public static final String COURSE_COMPLETE_ALL_ACTIVITIES = "all_activities"; - public static final String COURSE_COMPLETE_ALL_QUIZZES = "all_quizzes"; - public static final String COURSE_COMPLETE_FINAL_QUIZ = "final_quiz"; - public static final String COURSE_COMPLETE_ALL_QUIZZES_PLUS_PERCENT = "all_quizzes_plus_percent"; - - public static final String STATUS_LIVE = "live"; - public static final String STATUS_DRAFT = "draft"; - public static final String STATUS_ARCHIVED = "archived"; - public static final String STATUS_NEW_DOWNLOADS_DISABLED = "new_downloads_disabled"; - public static final String STATUS_READ_ONLY = "read_only"; - - public static final String JSON_PROPERTY_DESCRIPTION = "description"; - public static final String JSON_PROPERTY_TITLE = "title"; - public static final String JSON_PROPERTY_SHORTNAME = "shortname"; - public static final String JSON_PROPERTY_VERSION = "version"; - public static final String JSON_PROPERTY_URL = "url"; - public static final String JSON_PROPERTY_AUTHOR = "author"; - public static final String JSON_PROPERTY_USERNAME = "username"; - public static final String JSON_PROPERTY_ORGANISATION = "organisation"; - public static final String JSON_PROPERTY_STATUS = "status"; - public static final String JSON_PROPERTY_RESTRICTED = "restricted"; - public static final String JSON_PROPERTY_RESTRICTED_COHORTS = "cohorts"; - - private int courseId; - private String shortname; - private Double versionId; - private String status = STATUS_LIVE; - private boolean installed; - private boolean toUpdate; - private boolean toDelete; - private String downloadUrl; - private String imageFile; - private List media = new ArrayList<>(); - private List metaPages = new ArrayList<>(); - private int priority = 0; - private int noActivities = 0; - private int noActivitiesCompleted = 0; - private String sequencingMode = SEQUENCING_MODE_NONE; - private List gamificationEvents = new ArrayList<>(); - private boolean restricted = false; - private List restrictedCohorts = new ArrayList<>(); - - private String root; - - public Course() { - } - - public Course(String root) { - this.root = root; - } - - public boolean validate() throws CourseNotFoundException { - File courseXML = new File(this.getCourseXMLLocation()); - if (!courseXML.exists()) { - throw new CourseNotFoundException(); - } else { - return true; - } - } - - public List getMedia() { - return media; - } - - public void setMedia(List media) { - this.media = media; - } - - public String getImageFile() { - return imageFile; - } - - public String getImageFileFromRoot() { - return this.root + File.separator + Storage.APP_COURSES_DIR_NAME + File.separator + this.getShortname() + File.separator + imageFile; - } - - public void setImageFile(String imageFile) { - this.imageFile = imageFile; - } - - public String getDownloadUrl() { - return downloadUrl; - } - - public void setDownloadUrl(String downloadUrl) { - this.downloadUrl = downloadUrl; - } - - public String getTrackerLogUrl() { - return String.format(Paths.COURSE_ACTIVITY_PATH, this.getShortname()); - } - - public Double getVersionId() { - return versionId; - } - - public void setVersionId(Double versionId) { - this.versionId = versionId; - } - - public boolean isInstalled() { - return installed; - } - - public void setInstalled(boolean installed) { - this.installed = installed; - } - - public boolean isToUpdate() { - return toUpdate; - } - - public void setToUpdate(boolean toUpdate) { - this.toUpdate = toUpdate; - } - - public float getProgressPercent() { - // prevent divide by zero errors - if (this.noActivities != 0) { - return (float) this.noActivitiesCompleted * 100 / (float) this.noActivities; - } else { - return 0; - } - } - - public String getShortname() { - return shortname.toLowerCase(Locale.US); - } - - public void setShortname(String shortname) { - this.shortname = shortname.toLowerCase(Locale.US); - } - - public int getCourseId() { - return courseId; - } - - public void setCourseId(int courseId) { - this.courseId = courseId; - } - - public String getLocation() { - return this.root + File.separator + Storage.APP_COURSES_DIR_NAME + File.separator + this.getShortname() + File.separator; - - } - - public String getCourseXMLLocation() { - return this.root + File.separator + Storage.APP_COURSES_DIR_NAME + File.separator + this.getShortname() + File.separator + App.COURSE_XML; - } - - public void setMetaPages(List ammp) { - this.metaPages = ammp; - } - - public List getMetaPages() { - return this.metaPages; - } - - public CourseMetaPage getMetaPage(int id) { - for (CourseMetaPage mmp : this.metaPages) { - if (id == mmp.getId()) { - return mmp; - } - } - return null; - } - - public int getPriority() { - return priority; - } - - public void setPriority(int priority) { - this.priority = priority; - } - - public int getNoActivities() { - return noActivities; - } - - public void setNoActivities(int noActivities) { - this.noActivities = noActivities; - } - - public int getNoActivitiesCompleted() { - return noActivitiesCompleted; - } - - public void setNoActivitiesCompleted(int noActivitiesCompleted) { - this.noActivitiesCompleted = noActivitiesCompleted; - } - - public String getSequencingMode() { - return sequencingMode; - } - - public void setSequencingMode(String sequencingMode) { - this.sequencingMode = sequencingMode; - } - - public static String getLocalFilename(String shortname, Double versionID) { - return shortname + "-" + String.format("%.0f", versionID) + ".zip"; - } - - public void setGamificationEvents(List events) { - gamificationEvents = events; - } - - public GamificationEvent findGamificationEvent(String event) throws GamificationEventNotFound { - for (GamificationEvent ge : gamificationEvents) { - if (ge.getEvent().equals(event)) { - return ge; - } - } - throw new GamificationEventNotFound(event); - } - - public boolean isToDelete() { - return toDelete; - } - - public void setToDelete(boolean toDelete) { - this.toDelete = toDelete; - } - - public boolean isComplete(Context ctx, User user, String criteria, int percent){ - switch (criteria) { - case COURSE_COMPLETE_ALL_ACTIVITIES: - return AllActivities.isComplete(ctx, this.getCourseId(), user); - case COURSE_COMPLETE_ALL_QUIZZES: - return AllQuizzes.isComplete(ctx, this.getCourseId(), user); - case COURSE_COMPLETE_FINAL_QUIZ: - return FinalQuiz.isComplete(ctx, this.getCourseId(), user); - case COURSE_COMPLETE_ALL_QUIZZES_PLUS_PERCENT: - return AllQuizzesPlusPercent.isComplete(ctx, this.getCourseId(), user, percent); - default: - return false; - } - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public boolean hasStatus(String status) { - return TextUtilsJava.equals(this.status, status); - } - - public void setRestricted(boolean restricted) { - this.restricted = restricted; - } - - public boolean isRestricted() { - return restricted; - } - - public void setRestrictedCohorts(List cohorts){ - this.restrictedCohorts = cohorts; - } - - public List getRestrictedCohorts(){ - return restrictedCohorts; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/Course.kt b/app/src/main/java/org/digitalcampus/oppia/model/Course.kt new file mode 100644 index 000000000..e08154981 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/Course.kt @@ -0,0 +1,168 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import android.content.Context +import org.digitalcampus.oppia.api.Paths +import org.digitalcampus.oppia.application.App +import org.digitalcampus.oppia.exception.CourseNotFoundException +import org.digitalcampus.oppia.exception.GamificationEventNotFound +import org.digitalcampus.oppia.model.coursecomplete.AllActivities +import org.digitalcampus.oppia.model.coursecomplete.AllQuizzes +import org.digitalcampus.oppia.model.coursecomplete.AllQuizzesPlusPercent +import org.digitalcampus.oppia.model.coursecomplete.FinalQuiz +import org.digitalcampus.oppia.utils.TextUtilsJava +import org.digitalcampus.oppia.utils.storage.Storage +import java.io.File +import java.io.Serializable + +open class Course : MultiLangInfoModel, Serializable { + + companion object { + @JvmField + val TAG = Course::class.simpleName + private const val serialVersionUID = 4412987572522420704L + + const val SEQUENCING_MODE_NONE = "none" + const val SEQUENCING_MODE_SECTION = "section" + const val SEQUENCING_MODE_COURSE = "course" + + const val COURSE_COMPLETE_ALL_ACTIVITIES = "all_activities" + const val COURSE_COMPLETE_ALL_QUIZZES = "all_quizzes" + const val COURSE_COMPLETE_FINAL_QUIZ = "final_quiz" + const val COURSE_COMPLETE_ALL_QUIZZES_PLUS_PERCENT = "all_quizzes_plus_percent" + + const val STATUS_LIVE = "live" + const val STATUS_DRAFT = "draft" + const val STATUS_ARCHIVED = "archived" + const val STATUS_NEW_DOWNLOADS_DISABLED = "new_downloads_disabled" + const val STATUS_READ_ONLY = "read_only" + + const val JSON_PROPERTY_DESCRIPTION = "description" + const val JSON_PROPERTY_TITLE = "title" + const val JSON_PROPERTY_SHORTNAME = "shortname" + const val JSON_PROPERTY_VERSION = "version" + const val JSON_PROPERTY_URL = "url" + const val JSON_PROPERTY_AUTHOR = "author" + const val JSON_PROPERTY_USERNAME = "username" + const val JSON_PROPERTY_ORGANISATION = "organisation" + const val JSON_PROPERTY_STATUS = "status" + const val JSON_PROPERTY_RESTRICTED = "restricted" + const val JSON_PROPERTY_RESTRICTED_COHORTS = "cohorts" + + @JvmStatic + fun getLocalFilename(shortname: String, versionID: Double?): String { + return shortname + "-" + String.format("%.0f", versionID) + ".zip" + } + } + + var courseId = 0 + private var shortname: String? = null + var versionId: Double = 0.0 + var status = STATUS_LIVE + var isInstalled = false + var isToUpdate = false + var isToDelete = false + var downloadUrl: String? = null + var imageFile: String? = null + var media: MutableList = ArrayList() + var metaPages: List = ArrayList() + var priority = 0 + var noActivities = 0 + var noActivitiesCompleted = 0 + var sequencingMode = SEQUENCING_MODE_NONE + private var gamificationEvents: List = ArrayList() + var isRestricted = false + var restrictedCohorts: List? = ArrayList() + private var root: String? = null + + constructor() {} + constructor(root: String?) { + this.root = root + } + + @Throws(CourseNotFoundException::class) + fun validate(): Boolean { + val courseXML = File(courseXMLLocation) + return if (!courseXML.exists()) { + throw CourseNotFoundException() + } else { + true + } + } + + fun getImageFileFromRoot(): String { + return this.root + File.separator + Storage.APP_COURSES_DIR_NAME + File.separator + getShortname() + File.separator + imageFile + } + + fun getTrackerLogUrl(): String { + return String.format(Paths.COURSE_ACTIVITY_PATH, getShortname()) + } + + // prevent divide by zero errors + fun getProgressPercent(): Float { + // prevent divide by zero errors + return if (noActivities != 0) { + noActivitiesCompleted.toFloat() * 100f / noActivities.toFloat() + } else { + 0f + } + } + + fun getShortname(): String? { + return shortname?.lowercase() + } + + fun setShortname(shortname: String) { + this.shortname = shortname.lowercase() + } + + fun getLocation(): String { + return this.root + File.separator + Storage.APP_COURSES_DIR_NAME + File.separator + getShortname() + File.separator + } + + val courseXMLLocation: String + get() = getLocation() + App.COURSE_XML + + fun getMetaPage(id: Int): CourseMetaPage? { + return metaPages.find { it.id == id } + } + + fun setGamificationEvents(events: List) { + gamificationEvents = events + } + + @Throws(GamificationEventNotFound::class) + fun findGamificationEvent(event: String): GamificationEvent { + return gamificationEvents.find { it.event == event } + ?: throw GamificationEventNotFound(event) + } + + fun isComplete(ctx: Context?, user: User?, criteria: String?, percent: Int): Boolean { + return when (criteria) { + COURSE_COMPLETE_ALL_ACTIVITIES -> AllActivities.isComplete(ctx, courseId, user) + COURSE_COMPLETE_ALL_QUIZZES -> AllQuizzes.isComplete(ctx, courseId, user) + COURSE_COMPLETE_FINAL_QUIZ -> FinalQuiz.isComplete(ctx, courseId, user) + COURSE_COMPLETE_ALL_QUIZZES_PLUS_PERCENT -> AllQuizzesPlusPercent.isComplete(ctx, courseId, user, percent ) + else -> false + } + } + + fun hasStatus(status: String?): Boolean { + return TextUtilsJava.equals(this.status, status) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/CourseInstallRepository.java b/app/src/main/java/org/digitalcampus/oppia/model/CourseInstallRepository.java deleted file mode 100644 index d576b1765..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/CourseInstallRepository.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.digitalcampus.oppia.model; - - -import android.content.Context; - -import org.digitalcampus.oppia.listener.APIRequestListener; -import org.digitalcampus.oppia.task.APIUserRequestTask; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.List; - -public class CourseInstallRepository { - - public void getCourseList(Context ctx, String url) { - APIUserRequestTask task = new APIUserRequestTask(ctx); - task.setAPIRequestListener((APIRequestListener) ctx); - task.execute(url); - } - - public void refreshCourseList(Context ctx, List courses, - JSONObject json, String storage, boolean showUpdatesOnly) throws JSONException{ - courses.addAll(CourseInstallViewAdapter.parseCoursesJSON(ctx, json, storage, showUpdatesOnly)); - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/CourseInstallRepository.kt b/app/src/main/java/org/digitalcampus/oppia/model/CourseInstallRepository.kt new file mode 100644 index 000000000..f87020835 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/CourseInstallRepository.kt @@ -0,0 +1,20 @@ +package org.digitalcampus.oppia.model + +import android.content.Context +import org.digitalcampus.oppia.listener.APIRequestListener +import org.digitalcampus.oppia.task.APIUserRequestTask +import org.json.JSONException +import org.json.JSONObject + +class CourseInstallRepository { + fun getCourseList(ctx: Context?, url: String?) { + val task = APIUserRequestTask(ctx) + task.setAPIRequestListener(ctx as APIRequestListener?) + task.execute(url) + } + + @Throws(JSONException::class) + fun refreshCourseList(ctx: Context?, courses: MutableList, json: JSONObject?, storage: String?, showUpdatesOnly: Boolean) { + courses.addAll(CourseInstallViewAdapter.parseCoursesJSON(ctx, json, storage, showUpdatesOnly)) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/CourseInstallViewAdapter.java b/app/src/main/java/org/digitalcampus/oppia/model/CourseInstallViewAdapter.java deleted file mode 100644 index 6f6efa530..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/CourseInstallViewAdapter.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import android.content.Context; - -import org.digitalcampus.oppia.database.DbHelper; -import org.digitalcampus.oppia.service.courseinstall.CourseInstallerService; -import org.digitalcampus.oppia.utils.CourseUtils; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -public class CourseInstallViewAdapter extends Course { - - private static final long serialVersionUID = -4251898143809197224L; - - public CourseInstallViewAdapter(String root) { - super(root); - } - - //Extension for UI purposes - private boolean downloading; - private boolean installing; - private int progress; - - private String authorUsername; - private String authorName; - private String organisationName; - - public static final String SERVER_COURSES_NAME = "courses"; - - public boolean isDownloading() { - return downloading; - } - - public void setDownloading(boolean downloading) { - this.downloading = downloading; - } - - public boolean isInstalling() { - return installing; - } - - public boolean isToInstall(){ - return !isInstalled() || isToUpdate(); - } - - public boolean isInProgress(){ - return installing || downloading; - } - - public void setInstalling(boolean installing) { - this.installing = installing; - } - - public int getProgress() { - return progress; - } - - public void setProgress(int progress) { - this.progress = progress; - } - - public void setAuthorUsername(String authorUsername) { - this.authorUsername = authorUsername; - } - - public void setAuthorName(String authorName) { - this.authorName = authorName; - } - - public String getDisplayAuthorName() { - if ((authorName == null) && (authorUsername == null)) return null; - - /*** Previous code to display the author like "Name Surname (@username)" - String displayName = authorName == null ? "" : authorName.trim(); - if (authorUsername != null) { - if ( (authorName != null) && (authorName.trim().length() > 0)) - displayName += " (@" + authorUsername + ")"; - else - displayName += authorUsername; - } - return displayName; - */ - return authorName; - } - - - public static List parseCoursesJSON( - Context ctx, JSONObject json, String location, boolean onlyAddUpdates) - throws JSONException { - - ArrayList downloadingCourses = (ArrayList) CourseInstallerService.getTasksDownloading(); - ArrayList courses = new ArrayList<>(); - - JSONArray coursesArray = json.getJSONArray(SERVER_COURSES_NAME); - for (int i = 0; i < coursesArray.length(); i++) { - JSONObject jsonObj = coursesArray.getJSONObject(i); - CourseInstallViewAdapter course = new CourseInstallViewAdapter(location); - - ArrayList titles = new ArrayList<>(); - JSONObject jsonTitles = jsonObj.getJSONObject(JSON_PROPERTY_TITLE); - Iterator keys = jsonTitles.keys(); - while (keys.hasNext()) { - String key = (String) keys.next(); - Lang l = new Lang(key, jsonTitles.getString(key)); - titles.add(l); - } - course.setTitles(titles); - - ArrayList descriptions = new ArrayList<>(); - if (jsonObj.has(JSON_PROPERTY_DESCRIPTION) && !jsonObj.isNull(JSON_PROPERTY_DESCRIPTION)) { - try { - JSONObject jsonDescriptions = jsonObj.getJSONObject(JSON_PROPERTY_DESCRIPTION); - Iterator dkeys = jsonDescriptions.keys(); - while (dkeys.hasNext()) { - String key = (String) dkeys.next(); - if (!jsonDescriptions.isNull(key)) { - Lang l = new Lang(key, jsonDescriptions.getString(key)); - descriptions.add(l); - } - } - course.setDescriptions(descriptions); - } catch (JSONException jsone) { - //do nothing - } - } - - course.setShortname(jsonObj.getString(JSON_PROPERTY_SHORTNAME)); - course.setVersionId(jsonObj.getDouble(JSON_PROPERTY_VERSION)); - course.setDownloadUrl(jsonObj.getString(JSON_PROPERTY_URL)); - - if (jsonObj.has(JSON_PROPERTY_RESTRICTED)){ - boolean courseRestricted = jsonObj.getBoolean(JSON_PROPERTY_RESTRICTED); - course.setRestricted(courseRestricted); - - if (courseRestricted) { - List restrictedCohorts = CourseUtils.parseCourseCohortsFromJSONArray(jsonObj.getJSONArray(JSON_PROPERTY_RESTRICTED_COHORTS)); - course.setRestrictedCohorts(restrictedCohorts); - } - } - - if (jsonObj.has(JSON_PROPERTY_STATUS) && !jsonObj.isNull(JSON_PROPERTY_STATUS)) - course.setStatus(jsonObj.getString(JSON_PROPERTY_STATUS)); - - if (jsonObj.has(JSON_PROPERTY_AUTHOR) && !jsonObj.isNull(JSON_PROPERTY_AUTHOR)) - course.setAuthorName(jsonObj.getString(JSON_PROPERTY_AUTHOR)); - - if (jsonObj.has(JSON_PROPERTY_USERNAME) && !jsonObj.isNull(JSON_PROPERTY_USERNAME)) - course.setAuthorUsername(jsonObj.getString(JSON_PROPERTY_USERNAME)); - - DbHelper db = DbHelper.getInstance(ctx); - course.setInstalled(db.isInstalled(course.getShortname())); - course.setToUpdate(db.toUpdate(course.getShortname(), course.getVersionId())); - - if (jsonObj.has(JSON_PROPERTY_ORGANISATION) && !jsonObj.isNull(JSON_PROPERTY_ORGANISATION)) { - course.setOrganisationName(jsonObj.getString(JSON_PROPERTY_ORGANISATION)); - } - - if (downloadingCourses != null && downloadingCourses.contains(course.getDownloadUrl())) { - course.setDownloading(true); - } - if (!onlyAddUpdates || course.isToUpdate()) { - courses.add(course); - } - - } - - return courses; - } - - public String getOrganisationName() { - return organisationName; - } - - public void setOrganisationName(String organisationName) { - this.organisationName = organisationName; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/CourseInstallViewAdapter.kt b/app/src/main/java/org/digitalcampus/oppia/model/CourseInstallViewAdapter.kt new file mode 100644 index 000000000..2cdbcd64b --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/CourseInstallViewAdapter.kt @@ -0,0 +1,129 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import android.content.Context +import org.digitalcampus.oppia.database.DbHelper +import org.digitalcampus.oppia.service.courseinstall.CourseInstallerService +import org.json.JSONArray +import org.json.JSONException +import org.json.JSONObject + +class CourseInstallViewAdapter(root: String?) : Course(root) { + //Extension for UI purposes + var isDownloading = false + var isInstalling = false + var progress = 0 + private var authorUsername: String? = null + private var authorName: String? = null + var organisationName: String? = null + + val isToInstall: Boolean + get() = !isInstalled || isToUpdate + + val isInProgress: Boolean + get() = isInstalling || isDownloading + + fun setAuthorUsername(authorUsername: String?) { + this.authorUsername = authorUsername + } + + fun setAuthorName(authorName: String?) { + this.authorName = authorName + } + + val displayAuthorName: String? + get() { + return authorName + } + + companion object { + private const val serialVersionUID = -4251898143809197224L + + const val SERVER_COURSES_NAME = "courses" + + + @Throws(JSONException::class) + fun parseCoursesJSON( + ctx: Context?, json: JSONObject?, location: String?, onlyAddUpdates: Boolean + ): List { + val downloadingCourses = CourseInstallerService.getTasksDownloading() as ArrayList + val courses = ArrayList() + json?.getJSONArray(SERVER_COURSES_NAME)?.let { coursesArray -> + for (i in 0 until coursesArray.length()) { + val jsonObj = coursesArray.getJSONObject(i) + val course = CourseInstallViewAdapter(location) + + val titles = jsonObj.getJSONObject(JSON_PROPERTY_TITLE).toLangList() + course.setTitles(titles) + + val descriptions = jsonObj.optJSONObject(JSON_PROPERTY_DESCRIPTION)?.toLangList() + if (descriptions != null) { + course.setDescriptions(descriptions) + } + + course.setShortname(jsonObj.getString(JSON_PROPERTY_SHORTNAME)) + course.versionId = jsonObj.getDouble(JSON_PROPERTY_VERSION) + course.downloadUrl = jsonObj.getString(JSON_PROPERTY_URL) + + jsonObj.optBoolean(JSON_PROPERTY_RESTRICTED).let { courseRestricted -> + course.isRestricted = courseRestricted + if (courseRestricted) { + val restrictedCohorts = jsonObj.getJSONArray(JSON_PROPERTY_RESTRICTED_COHORTS) + .toIntegerList() + course.restrictedCohorts = restrictedCohorts + } + } + + course.status = jsonObj.optString(JSON_PROPERTY_STATUS, "") + course.setAuthorName(jsonObj.optString(JSON_PROPERTY_AUTHOR, "")) + course.setAuthorUsername(jsonObj.optString(JSON_PROPERTY_USERNAME, "")) + + val db = DbHelper.getInstance(ctx) + course.isInstalled = db.isInstalled(course.getShortname()) + course.isToUpdate = db.toUpdate(course.getShortname(), course.versionId) + course.organisationName = jsonObj.optString(JSON_PROPERTY_ORGANISATION, "") + course.isDownloading = downloadingCourses.contains(course.downloadUrl) == true + + if (!onlyAddUpdates || course.isToUpdate) { + courses.add(course) + } + } + } + return courses + } + + private fun JSONObject.toLangList(): MutableList { + val langList = mutableListOf() + keys().forEach { key -> + val value = optString(key) + if (value.isNotEmpty()) { + langList.add(Lang(key, value)) + } + } + return langList + } + + private fun JSONArray.toIntegerList(): MutableList { + val integerList = mutableListOf() + for (i in 0 until length()) { + integerList.add(optInt(i, 0)) + } + return integerList + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/CourseMetaPage.java b/app/src/main/java/org/digitalcampus/oppia/model/CourseMetaPage.java deleted file mode 100644 index b29335c79..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/CourseMetaPage.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import java.io.Serializable; -import java.util.ArrayList; - -public class CourseMetaPage implements Serializable{ - - /** - * - */ - private static final long serialVersionUID = -1597711519611488890L; - public static final String TAG = CourseMetaPage.class.getSimpleName(); - private int id; - private ArrayList langs = new ArrayList<>(); - - public void setId(int id){ - this.id = id; - } - - public int getId(){ - return this.id; - } - - public void addLang(Lang l){ - langs.add(l); - } - - public Lang getLang(String langStr){ - for(Lang l: langs){ - if(l.getLanguage().equalsIgnoreCase(langStr)){ - return l; - } - } - if(langs.isEmpty()){ - return null; - } else { - return langs.get(0); - } - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/DownloadProgress.java b/app/src/main/java/org/digitalcampus/oppia/model/CourseMetaPage.kt similarity index 55% rename from app/src/main/java/org/digitalcampus/oppia/model/DownloadProgress.java rename to app/src/main/java/org/digitalcampus/oppia/model/CourseMetaPage.kt index 72c1f7cf6..fdd7012bd 100644 --- a/app/src/main/java/org/digitalcampus/oppia/model/DownloadProgress.java +++ b/app/src/main/java/org/digitalcampus/oppia/model/CourseMetaPage.kt @@ -14,31 +14,25 @@ * You should have received a copy of the GNU General Public License * along with OppiaMobile. If not, see . */ +package org.digitalcampus.oppia.model -package org.digitalcampus.oppia.model; +import java.io.Serializable -import java.io.Serializable; +class CourseMetaPage : Serializable { + companion object { + private const val serialVersionUID = -1597711519611488890L + @JvmField + val TAG = CourseMetaPage::class.simpleName + } -public class DownloadProgress implements Serializable { + var id = 0 + private val langs = ArrayList() - public static final String TAG = DownloadProgress.class.getSimpleName(); - private static final long serialVersionUID = -1408102165581810183L; - private String message = ""; - private int progress = 0; - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public int getProgress() { - return progress; - } - - public void setProgress(int progress) { - this.progress = progress; - } -} + fun addLang(l: Lang) { + langs.add(l) + } + + fun getLang(langStr: String?): Lang? { + return langs.find { it.language.equals(langStr, ignoreCase = true) } ?: langs.firstOrNull() + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/CourseTransferableFile.java b/app/src/main/java/org/digitalcampus/oppia/model/CourseTransferableFile.java deleted file mode 100644 index 49579277a..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/CourseTransferableFile.java +++ /dev/null @@ -1,147 +0,0 @@ -package org.digitalcampus.oppia.model; - -import org.digitalcampus.oppia.task.ExportActivityTask; -import org.digitalcampus.oppia.utils.DateUtils; -import org.digitalcampus.oppia.utils.storage.FileUtils; -import org.joda.time.DateTime; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; - -import java.io.File; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -public class CourseTransferableFile implements Serializable { - - static final long serialVersionUID = 123456789123456789L; - - public static final String TYPE_COURSE_BACKUP = "backup"; - public static final String TYPE_COURSE_MEDIA = "media"; - public static final String TYPE_ACTIVITY_LOG = "activity"; - - private String title; - private String shortname; - private Double versionId; - private String type = TYPE_COURSE_BACKUP; - private String filename; - private long fileSize; - private File file; - private List relatedMedia; - private long relatedFilesize = 0; - - public List getRelatedMedia() { - return (relatedMedia != null) ? relatedMedia : new ArrayList<>(); - } - - public void setRelatedMedia(List relatedMedia) { - this.relatedMedia = relatedMedia; - } - - - public String getTitle() { - return title.trim(); - } - - public void setTitle(String title) { - this.title = title; - } - - public String getShortname() { - return shortname; - } - - public void setShortname(String shortname) { - this.shortname = shortname; - } - - public Double getVersionId() { - return versionId; - } - - public void setVersionId(Double versionId) { - this.versionId = versionId; - } - - public String getFilename() { - return filename; - } - - public void setFilename(String filename) { - this.filename = filename; - } - - public long getFileSize() { - return fileSize; - } - - public void setFileSize(long fileSize) { - this.fileSize = fileSize; - } - - public String getDisplayFileSize(){ - return FileUtils.readableFileSize(fileSize + relatedFilesize); - } - - public String getDisplayDateTimeFromFilename(){ - DateTimeFormatter f = DateTimeFormat.forPattern(ExportActivityTask.activityTimestampFormat); - DateTime dateTime = f.parseDateTime(filename.substring(filename.lastIndexOf('_')+1, filename.lastIndexOf('.'))); - return DateUtils.DISPLAY_DATETIME_FORMAT.print(dateTime); - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public File getFile() { - return file; - } - - public void setFile(File file) { - this.file = file; - } - - public void setRelatedFilesize(long relatedFilesize) { - this.relatedFilesize = relatedFilesize; - } - - @Override - public boolean equals(Object o){ - if (o instanceof CourseTransferableFile){ - CourseTransferableFile other = (CourseTransferableFile) o; - return other.getFilename().equals(this.filename); - } - return false; - } - - @Override - public int hashCode() { - return filename != null ? filename.hashCode() : 0; - } - - public String getNotificationName() { - if (type.equals(TYPE_COURSE_BACKUP)){ - return getShortname(); - } - else if(type.equals(TYPE_ACTIVITY_LOG)){ - return getActivityLogUsername() + " log"; - } - return null; - } - - public String getActivityLogUsername(){ - return filename.substring(0, filename.indexOf('_')); - } - - public void setTitleFromFilename() { - String filenameTitle = ""; - if (type.equals(TYPE_ACTIVITY_LOG)){ - filenameTitle = getActivityLogUsername(); - } - setTitle(filenameTitle); - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/CourseTransferableFile.kt b/app/src/main/java/org/digitalcampus/oppia/model/CourseTransferableFile.kt new file mode 100644 index 000000000..f92fc55b1 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/CourseTransferableFile.kt @@ -0,0 +1,72 @@ +package org.digitalcampus.oppia.model + +import org.digitalcampus.oppia.task.ExportActivityTask +import org.digitalcampus.oppia.utils.DateUtils +import org.digitalcampus.oppia.utils.storage.FileUtils +import org.joda.time.format.DateTimeFormat +import java.io.File +import java.io.Serializable + +class CourseTransferableFile( + var shortname: String? = null, + var versionId: Double? = null, + var type: String = TYPE_COURSE_BACKUP, + var filename: String? = null, + var fileSize: Long = 0, + var file: File? = null, + var relatedMedia: List = emptyList(), + var relatedFilesize: Long = 0 +) : Serializable { + + companion object { + const val serialVersionUID = 123456789123456789L + const val TYPE_COURSE_BACKUP = "backup" + const val TYPE_COURSE_MEDIA = "media" + const val TYPE_ACTIVITY_LOG = "activity" + } + + var title: String? = null + get() = field?.trim() + + val displayFileSize: String + get() = FileUtils.readableFileSize(fileSize + relatedFilesize) + + val displayDateTimeFromFilename: String + get() { + val f = DateTimeFormat.forPattern(ExportActivityTask.activityTimestampFormat) + val dateTime = f.parseDateTime( + filename?.substringAfterLast('_')?.substringBeforeLast('.') ?: "" + ) + return DateUtils.DISPLAY_DATETIME_FORMAT.print(dateTime) + } + + + override fun equals(other: Any?): Boolean { + if (other is CourseTransferableFile) { + return other.filename == filename + } + return false + } + + override fun hashCode(): Int { + return filename?.hashCode() ?: 0 + } + + val notificationName: String? + get() { + return when(type) { + TYPE_COURSE_BACKUP -> shortname + TYPE_ACTIVITY_LOG -> activityLogUsername + " log" + else -> null + } + } + + private val activityLogUsername: String + get() = filename?.substringBefore('_') ?: "" + + fun setTitleFromFilename() { + if (type == TYPE_ACTIVITY_LOG) { + title = activityLogUsername + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/CoursesRepository.java b/app/src/main/java/org/digitalcampus/oppia/model/CoursesRepository.java deleted file mode 100644 index 3c99f0c3f..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/CoursesRepository.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.digitalcampus.oppia.model; - -import android.content.Context; - -import org.digitalcampus.oppia.database.DbHelper; -import org.digitalcampus.oppia.application.SessionManager; - -import java.util.List; - -public class CoursesRepository { - - public List getCourses(Context ctx){ - DbHelper db = DbHelper.getInstance(ctx); - long userId = db.getUserId(SessionManager.getUsername(ctx)); - return db.getCoursesForUser(userId); - } - - public Activity getActivityByDigest(Context ctx, String digest){ - DbHelper db = DbHelper.getInstance(ctx); - return db.getActivityByDigest(digest); - } - - public Course getCourse(Context ctx, long courseID, long userID){ - DbHelper db = DbHelper.getInstance(ctx); - return db.getCourseWithProgress(courseID, userID); - } - - public Course getCourseByShortname(Context ctx, String shortname, long userID){ - DbHelper db = DbHelper.getInstance(ctx); - long courseId = db.getCourseIdByShortname(shortname, userID); - if (courseId != -1) { - return db.getCourseWithProgress(courseId, userID); - } - return null; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/CoursesRepository.kt b/app/src/main/java/org/digitalcampus/oppia/model/CoursesRepository.kt new file mode 100644 index 000000000..87ef3e552 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/CoursesRepository.kt @@ -0,0 +1,31 @@ +package org.digitalcampus.oppia.model + +import android.content.Context +import org.digitalcampus.oppia.application.SessionManager +import org.digitalcampus.oppia.database.DbHelper + +class CoursesRepository { + fun getCourses(ctx: Context?): List { + val db = DbHelper.getInstance(ctx) + val userId = db.getUserId(SessionManager.getUsername(ctx)) + return db.getCoursesForUser(userId) + } + + fun getActivityByDigest(ctx: Context?, digest: String?): Activity { + val db = DbHelper.getInstance(ctx) + return db.getActivityByDigest(digest) + } + + fun getCourse(ctx: Context?, courseID: Long, userID: Long): Course { + val db = DbHelper.getInstance(ctx) + return db.getCourseWithProgress(courseID, userID) + } + + fun getCourseByShortname(ctx: Context?, shortname: String?, userID: Long): Course? { + val db = DbHelper.getInstance(ctx) + val courseId = db.getCourseIdByShortname(shortname, userID) + return if (courseId != -1L) { + db.getCourseWithProgress(courseId, userID) + } else null + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/CustomFieldsRepository.java b/app/src/main/java/org/digitalcampus/oppia/model/CustomFieldsRepository.java deleted file mode 100644 index 3132f4869..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/CustomFieldsRepository.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.digitalcampus.oppia.model; - -import android.content.Context; - -import org.digitalcampus.oppia.database.DbHelper; -import org.digitalcampus.oppia.utils.storage.StorageUtils; - -import java.util.List; - -public class CustomFieldsRepository { - - public List getAll(Context ctx){ - return DbHelper.getInstance(ctx).getCustomFields(); - } - - public List getRegisterSteps(Context ctx){ - String customFieldsData = StorageUtils.readFileFromAssets(ctx, CustomField.CUSTOMFIELDS_FILE); - return CustomField.parseRegisterSteps(customFieldsData); - } - - public List getRequiredFields(Context ctx){ - String customFieldsData = StorageUtils.readFileFromAssets(ctx, CustomField.CUSTOMFIELDS_FILE); - return CustomField.getRequiredFields(customFieldsData); - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/CustomFieldsRepository.kt b/app/src/main/java/org/digitalcampus/oppia/model/CustomFieldsRepository.kt new file mode 100644 index 000000000..cee71773b --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/CustomFieldsRepository.kt @@ -0,0 +1,22 @@ +package org.digitalcampus.oppia.model + +import android.content.Context +import org.digitalcampus.oppia.database.DbHelper +import org.digitalcampus.oppia.model.CustomField.RegisterFormStep +import org.digitalcampus.oppia.utils.storage.StorageUtils + +class CustomFieldsRepository { + fun getAll(ctx: Context?): List { + return DbHelper.getInstance(ctx).customFields + } + + fun getRegisterSteps(ctx: Context): List { + val customFieldsData = StorageUtils.readFileFromAssets(ctx, CustomField.CUSTOMFIELDS_FILE) + return CustomField.parseRegisterSteps(customFieldsData) + } + + fun getRequiredFields(ctx: Context): List { + val customFieldsData = StorageUtils.readFileFromAssets(ctx, CustomField.CUSTOMFIELDS_FILE) + return CustomField.getRequiredFields(customFieldsData) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/CustomValue.java b/app/src/main/java/org/digitalcampus/oppia/model/CustomValue.java deleted file mode 100644 index 37a99bbaf..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/CustomValue.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.digitalcampus.oppia.model; - -import androidx.annotation.NonNull; - -public class CustomValue { - - private T value; - - public CustomValue(T value) { - setValue(value); - } - - public T getValue() { - return value; - } - - public void setValue(T value) { - if (value instanceof String || value instanceof Boolean || value instanceof Integer || value instanceof Float) { - this.value = value; - } else { - throw new IllegalArgumentException("value must one of these types: String, int, float or boolean"); - } - } - - @NonNull - @Override - public String toString() { - return String.valueOf(value); - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/CustomValue.kt b/app/src/main/java/org/digitalcampus/oppia/model/CustomValue.kt new file mode 100644 index 000000000..c7914fd38 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/CustomValue.kt @@ -0,0 +1,17 @@ +package org.digitalcampus.oppia.model + +sealed class CustomValueType +data class StringValue(val value: String) : CustomValueType() +data class BooleanValue(val value: Boolean) : CustomValueType() +data class IntValue(val value: Int) : CustomValueType() +data class FloatValue(val value: Float) : CustomValueType() + +class CustomValue(private val value: CustomValueType) { + fun getValue(): Any { + return value + } + + override fun toString(): String { + return value.toString() + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/DownloadProgress.kt b/app/src/main/java/org/digitalcampus/oppia/model/DownloadProgress.kt new file mode 100644 index 000000000..cfc7ff673 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/DownloadProgress.kt @@ -0,0 +1,29 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import java.io.Serializable + +class DownloadProgress : Serializable { + var message: String = "" + var progress: Int = 0 + + companion object { + val TAG = DownloadProgress::class.simpleName + private const val serialVersionUID = -1408102165581810183L + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/GamificationEvent.java b/app/src/main/java/org/digitalcampus/oppia/model/GamificationEvent.java deleted file mode 100644 index 7fcc21f26..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/GamificationEvent.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import java.io.Serializable; - -public class GamificationEvent implements Serializable{ - - private static final long serialVersionUID = 3649466060301114481L; - - private String event; - private int points; - private boolean completed; - - public GamificationEvent(){} - - public GamificationEvent(String event, int points){ - this.event = event; - this.points = points; - this.completed = false; - } - - public GamificationEvent(String event, int points, boolean completed){ - this.event = event; - this.points = points; - this.completed = completed; - } - - public String getEvent() { - return event; - } - - public void setEvent(String event) { - this.event = event; - } - - public int getPoints() { - return points; - } - - public void setPoints(int points) { - this.points = points; - } - - public boolean isCompleted() { - return completed; - } - - public void setCompleted(boolean completed) { - this.completed = completed; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/GamificationEvent.kt b/app/src/main/java/org/digitalcampus/oppia/model/GamificationEvent.kt new file mode 100644 index 000000000..b451d2144 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/GamificationEvent.kt @@ -0,0 +1,55 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import java.io.Serializable + +class GamificationEvent : Serializable { + var event: String? = null + var points = 0 + var isCompleted = false + + constructor() {} + constructor(event: String?, points: Int) { + this.event = event + this.points = points + isCompleted = false + } + + constructor(event: String?, points: Int, completed: Boolean) { + this.event = event + this.points = points + isCompleted = completed + } + + companion object { + private const val serialVersionUID = 3649466060301114481L + } +} + +// TODO: Replace with the below class when all the GamificationEvent references are migrated to kotlin +// This is because Java does not allow constructors with default parameter values +//class GamificationEvent( +// var event: String = "", +// var points: Int = 0, +// var isCompleted: Boolean = false +//) : Serializable { +// +// companion object { +// private const val serialVersionUID = 3649466060301114481L +// } +//} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/Lang.java b/app/src/main/java/org/digitalcampus/oppia/model/Lang.java deleted file mode 100644 index f775bcb06..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/Lang.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import androidx.annotation.Nullable; - -import java.io.Serializable; - -public class Lang implements Serializable { - - - /** - * - */ - private static final long serialVersionUID = -8960131611429444591L; - public static final String TAG = Lang.class.getSimpleName(); - private String language; - private String content; - private String location; - - public Lang(String lang, String content){ - this.setLanguage(lang); - this.setContent(content); - } - - - public String getLanguage() { - String[] langCountry = this.language.split("[_-]"); - return langCountry[0]; - } - - public void setLanguage(String lang) { - // only set the first part of the lang - not the full localisation - String[] langCountry = lang.split("[_-]"); - this.language = langCountry[0]; - } - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - - public void setLocation(String location) { - this.location = location; - } - - public String getLocation() { - return location; - } - - @Override - public String toString() { - return "Lang{" + - "language='" + language + '\'' + - ", content='" + content + '\'' + - ", location='" + location + '\'' + - '}'; - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj == null) - return false; - - if (this.getClass() != obj.getClass()) - return false; - - return getLanguage() != null && getLanguage().equalsIgnoreCase(((Lang) obj).getLanguage()); - } - - @Override - public int hashCode() { - return getLanguage() != null ? getLanguage().hashCode() : 0; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/Lang.kt b/app/src/main/java/org/digitalcampus/oppia/model/Lang.kt new file mode 100644 index 000000000..408a79da1 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/Lang.kt @@ -0,0 +1,59 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import java.io.Serializable + +data class Lang( + var language: String, + var content: String +) : Serializable { + + var location: String? = null + + companion object { + private const val serialVersionUID = -8960131611429444591L + val TAG = Lang::class.simpleName + } + + init { + // only set the first part of the lang - not the full localisation + val langCountry = language.split("[_-]") + language = langCountry[0] + } + + override fun toString(): String { + return "Lang{" + + "language='" + language + '\'' + + ", content='" + content + '\'' + + ", location='" + location + '\'' + + '}' + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as Lang + + return language.equals(other.language, ignoreCase = true) + } + + override fun hashCode(): Int { + return language.hashCode() + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/Media.java b/app/src/main/java/org/digitalcampus/oppia/model/Media.java deleted file mode 100644 index 2bb097aee..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/Media.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import android.content.SharedPreferences; -import android.util.Log; - -import org.digitalcampus.oppia.activity.PrefsActivity; -import org.digitalcampus.oppia.application.App; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -public class Media implements Serializable { - - private static final long serialVersionUID = -7381597814535579028L; - - public static final String TAG = Media.class.getSimpleName(); - private String filename; - private String downloadUrl; - private String digest; - private int length; - private double fileSize; - private ArrayList courses; - - private int downloaded; - - public Media() { - courses = new ArrayList<>(); - } - - public Media(String filename, int length) { - this.filename = filename; - this.length = length; - } - - public String getFilename() { - return filename; - } - - public int getLength() { - return length; - } - - public void setLength(int length) { - this.length = length; - } - - public void setFilename(String filename) { - this.filename = filename; - } - - public String getDownloadUrl() { - return downloadUrl; - } - - public void setDownloadUrl(String downloadUrl) { - this.downloadUrl = downloadUrl; - } - - public String getDigest() { - return digest; - } - - public void setDigest(String digest) { - this.digest = digest; - } - - public double getFileSize() { - return fileSize; - } - - public void setFileSize(double fileSize) { - this.fileSize = fileSize; - } - - public int getDownloaded() { - return downloaded; - } - - public List getCourses() { - return courses; - } - - //ONLY FOR UI PURPOSES - private boolean downloading; - private boolean failed; - private int progress; - - public boolean isDownloading() { - return downloading; - } - - public void setDownloading(boolean downloading) { - this.downloading = downloading; - } - - public int getProgress() { - return progress; - } - - public void setProgress(int progress) { - this.progress = progress; - } - - public boolean hasFailed() { - return failed; - } - - public void setFailed(boolean failed) { - this.failed = failed; - } - - public static boolean shouldScanMedia(SharedPreferences prefs) { - long now = System.currentTimeMillis() / 1000; - long lastScan = prefs.getLong(PrefsActivity.PREF_LAST_MEDIA_SCAN, 0); - return (lastScan + App.MEDIA_SCAN_TIME_LIMIT <= now); - } - - public static void resetMediaScan(SharedPreferences prefs) { - Log.d(TAG, "Resetting last media scan"); - prefs.edit().putLong(PrefsActivity.PREF_LAST_MEDIA_SCAN, 0).apply(); - } - - public static void updateMediaScan(SharedPreferences prefs) { - Log.d(TAG, "Updating last media scan to now"); - long now = System.currentTimeMillis() / 1000; - prefs.edit().putLong(PrefsActivity.PREF_LAST_MEDIA_SCAN, now).apply(); - } -} - diff --git a/app/src/main/java/org/digitalcampus/oppia/model/Media.kt b/app/src/main/java/org/digitalcampus/oppia/model/Media.kt new file mode 100644 index 000000000..bb8e43572 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/Media.kt @@ -0,0 +1,84 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import android.content.SharedPreferences +import android.util.Log +import org.digitalcampus.oppia.activity.PrefsActivity +import org.digitalcampus.oppia.application.App +import java.io.Serializable + +class Media : Serializable { + + companion object { + private const val serialVersionUID = -7381597814535579028L + val TAG = Media::class.simpleName + @JvmStatic + fun shouldScanMedia(prefs: SharedPreferences): Boolean { + val now = System.currentTimeMillis() / 1000 + val lastScan = prefs.getLong(PrefsActivity.PREF_LAST_MEDIA_SCAN, 0) + return lastScan + App.MEDIA_SCAN_TIME_LIMIT <= now + } + + @JvmStatic + fun resetMediaScan(prefs: SharedPreferences) { + Log.d(TAG, "Resetting last media scan") + prefs.edit().putLong(PrefsActivity.PREF_LAST_MEDIA_SCAN, 0).apply() + } + + @JvmStatic + fun updateMediaScan(prefs: SharedPreferences) { + Log.d(TAG, "Updating last media scan to now") + val now = System.currentTimeMillis() / 1000 + prefs.edit().putLong(PrefsActivity.PREF_LAST_MEDIA_SCAN, now).apply() + } + } + + var filename: String? = null + var downloadUrl: String? = null + var digest: String? = null + var length = 0 + var fileSize = 0.0 + private var courses: ArrayList? = null + val downloaded = 0 + + constructor() { + courses = ArrayList() + } + + constructor(filename: String?, length: Int) { + this.filename = filename + this.length = length + } + + fun getCourses(): List? { + return courses + } + + //ONLY FOR UI PURPOSES + var isDownloading = false + private var failed = false + var progress = 0 + + fun hasFailed(): Boolean { + return failed + } + + fun setFailed(failed: Boolean) { + this.failed = failed + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/MultiLangInfoModel.java b/app/src/main/java/org/digitalcampus/oppia/model/MultiLangInfoModel.java deleted file mode 100644 index 285628349..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/MultiLangInfoModel.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import android.content.SharedPreferences; -import android.util.Log; - -import org.digitalcampus.oppia.activity.PrefsActivity; -import org.digitalcampus.oppia.analytics.Analytics; -import org.digitalcampus.oppia.utils.TextUtilsJava; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; - - -public class MultiLangInfoModel implements Serializable { - - public static final String TAG = MultiLangInfoModel.class.getSimpleName(); - - private List langs = new ArrayList<>(); - private List titles = new ArrayList<>(); - private List descriptions = new ArrayList<>(); - - public static final String DEFAULT_NOTITLE = "No title set"; - - public String getTitle(String lang) { - String title = getInfo(lang, titles); - return title == null ? DEFAULT_NOTITLE : title.trim(); - } - - public String getTitle(SharedPreferences prefs){ - return this.getTitle(prefs.getString(PrefsActivity.PREF_CONTENT_LANGUAGE, Locale.getDefault().getLanguage())); - } - - public void setTitles(List titles) { - this.titles = titles; - } - - public void setTitlesFromJSONString(String jsonStr) { - setInfoFromJSONString(jsonStr, this.titles, false); - } - - public String getTitleJSONString(){ - return getInfoJSONString(this.titles); - } - - public String getDescription(String lang) { - return getInfo(lang, descriptions); - } - - public String getDescription(SharedPreferences prefs){ - return this.getDescription(prefs.getString(PrefsActivity.PREF_CONTENT_LANGUAGE, Locale.getDefault().getLanguage())); - } - - public void setDescriptions(List descriptions) { - this.descriptions = descriptions; - } - - public void setDescriptionsFromJSONString(String jsonStr) { - setInfoFromJSONString(jsonStr, this.descriptions, false); - } - - public String getDescriptionJSONString(){ - return getInfoJSONString(this.descriptions); - } - - public List getLangs() { - return langs; - } - public void setLangs(List langs) { - this.langs = langs; - } - - public String getLangsJSONString(){ - return getInfoJSONString(this.langs); - } - - public void setLangsFromJSONString(String jsonStr) { - setInfoFromJSONString(jsonStr, this.langs, true); - } - - private String getInfo(String lang, List values){ - for(Lang l: values){ - if(l.getLanguage().equalsIgnoreCase(lang)){ - return l.getContent().trim(); - } - } - if(values.size() > 0){ - return values.get(0).getContent().trim(); - } - - return null; - } - - private String getInfoJSONString(List values){ - JSONArray array = new JSONArray(); - for(Lang l: values){ - JSONObject obj = new JSONObject(); - try { - obj.put(l.getLanguage(), l.getContent()); - } catch (JSONException e) { - Analytics.logException(e); - Log.d(TAG, "JSON error: ", e); - } - array.put(obj); - } - return array.toString(); - } - - private void setInfoFromJSONString(String jsonStr, List values, boolean isLangs){ - try { - JSONArray infoArray = new JSONArray(jsonStr); - for(int i=0; i< infoArray.length(); i++){ - JSONObject infoObj = infoArray.getJSONObject(i); - @SuppressWarnings("unchecked") - Iterator iter = infoObj.keys(); - while(iter.hasNext()){ - String key = iter.next(); - String info = ""; - if(!isLangs) { - info = infoObj.getString(key); - } - Lang l = new Lang(key, info); - values.add(l); - } - } - } catch (JSONException e) { - Analytics.logException(e); - Log.d(TAG, "JSON error: ", e); - } catch (NullPointerException npe){ - Analytics.logException(npe); - Log.d(TAG, "Null pointer error: ", npe); - } - } - - public void setTitlesFromJSONObjectMap(JSONObject jsonObjectMultilang) throws JSONException { - List localLangs = parseLangs(jsonObjectMultilang); - this.titles = localLangs; - } - - public void setDescriptionsFromJSONObjectMap(JSONObject jsonObjectMultilang) throws JSONException { - List localLangs = parseLangs(jsonObjectMultilang); - this.descriptions = localLangs; - } - - private List parseLangs(JSONObject jsonObjectMultilang) throws JSONException { - Iterator keys = jsonObjectMultilang.keys(); - List localLangs = new ArrayList<>(); - - while(keys.hasNext()) { - String key = keys.next(); - String value = jsonObjectMultilang.getString(key); - if (!TextUtilsJava.isEmpty(value) && !TextUtilsJava.equals(value,"null")){ - localLangs.add(new Lang(key, value)); - } - } - - return localLangs; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/MultiLangInfoModel.kt b/app/src/main/java/org/digitalcampus/oppia/model/MultiLangInfoModel.kt new file mode 100644 index 000000000..7adbbd9ba --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/MultiLangInfoModel.kt @@ -0,0 +1,184 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import android.content.SharedPreferences +import android.util.Log +import org.digitalcampus.oppia.activity.PrefsActivity +import org.digitalcampus.oppia.analytics.Analytics +import org.digitalcampus.oppia.utils.TextUtilsJava +import org.json.JSONArray +import org.json.JSONException +import org.json.JSONObject +import java.io.Serializable +import java.util.Locale + +open class MultiLangInfoModel : Serializable { + + companion object { + val TAG = MultiLangInfoModel::class.simpleName + const val DEFAULT_NOTITLE = "No title set" + } + + private var langs: MutableList = ArrayList() + private var titles: MutableList = ArrayList() + private var descriptions: MutableList = ArrayList() + + fun getTitle(lang: String?): String { + val title = getInfo(lang, titles) + return title?.trim() ?: DEFAULT_NOTITLE + } + + fun getTitle(prefs: SharedPreferences): String { + return this.getTitle( + prefs.getString( + PrefsActivity.PREF_CONTENT_LANGUAGE, + Locale.getDefault().language + ) + ) + } + + fun setTitles(titles: MutableList) { + this.titles = titles + } + + fun setTitlesFromJSONString(jsonStr: String) { + setInfoFromJSONString(jsonStr, titles, false) + } + + fun getTitleJSONString(): String { + return getInfoJSONString(titles) + } + + fun getDescription(lang: String?): String? { + return getInfo(lang, descriptions) + } + + fun getDescription(prefs: SharedPreferences): String? { + return this.getDescription( + prefs.getString( + PrefsActivity.PREF_CONTENT_LANGUAGE, + Locale.getDefault().language + ) + ) + } + + fun setDescriptions(descriptions: MutableList) { + this.descriptions = descriptions + } + + fun setDescriptionsFromJSONString(jsonStr: String) { + setInfoFromJSONString(jsonStr, descriptions, false) + } + + fun getDescriptionJSONString(): String { + return getInfoJSONString(descriptions) + } + + fun getLangs(): List { + return langs + } + + fun setLangs(langs: MutableList) { + this.langs = langs + } + + fun getLangsJSONString(): String { + return getInfoJSONString(langs) + } + + fun setLangsFromJSONString(jsonStr: String) { + setInfoFromJSONString(jsonStr, langs, true) + } + + private fun getInfo(lang: String?, values: List): String? { + for ((language, content) in values) { + if (language.equals(lang, ignoreCase = true)) { + return content.trim() + } + } + return if (values.isNotEmpty()) { + values[0].content.trim() + } else null + } + + private fun getInfoJSONString(values: List): String { + val array = JSONArray() + for ((language, content) in values) { + val obj = JSONObject() + try { + obj.put(language, content) + } catch (e: JSONException) { + Analytics.logException(e) + Log.d(TAG, "JSON error: ", e) + } + array.put(obj) + } + return array.toString() + } + + private fun setInfoFromJSONString(jsonStr: String, values: MutableList, isLangs: Boolean) { + try { + val infoArray = JSONArray(jsonStr) + for (i in 0 until infoArray.length()) { + val infoObj = infoArray.getJSONObject(i) + val iter = infoObj.keys() + while (iter.hasNext()) { + val key = iter.next() + var info: String? = "" + if (!isLangs) { + info = infoObj.getString(key) + } + val l = Lang(key, info!!) + values.add(l) + } + } + } catch (e: JSONException) { + Analytics.logException(e) + Log.d(TAG, "JSON error: ", e) + } catch (npe: NullPointerException) { + Analytics.logException(npe) + Log.d(TAG, "Null pointer error: ", npe) + } + } + + @Throws(JSONException::class) + fun setTitlesFromJSONObjectMap(jsonObjectMultilang: JSONObject) { + val localLangs = parseLangs(jsonObjectMultilang) + titles = localLangs + } + + @Throws(JSONException::class) + fun setDescriptionsFromJSONObjectMap(jsonObjectMultilang: JSONObject) { + val localLangs = parseLangs(jsonObjectMultilang) + descriptions = localLangs + } + + @Throws(JSONException::class) + private fun parseLangs(jsonObjectMultilang: JSONObject): MutableList { + val keys = jsonObjectMultilang.keys() + val localLangs: MutableList = ArrayList() + while (keys.hasNext()) { + val key = keys.next() + val value = jsonObjectMultilang.getString(key) + if (!TextUtilsJava.isEmpty(value) && !TextUtilsJava.equals(value, "null")) { + localLangs.add(Lang(key, value)) + } + } + return localLangs + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/OfflineCourseFile.java b/app/src/main/java/org/digitalcampus/oppia/model/OfflineCourseFile.java deleted file mode 100644 index 4b016bd74..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/OfflineCourseFile.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.digitalcampus.oppia.model; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -public class OfflineCourseFile { - - public enum FileType {COURSE, MEDIA, INVALID} - public enum Status {SELECTED, IMPORTING, IMPORTED} - private static final String MODULES_XML_PATH = ".*/module.xml"; - private static final String MEDIA_REGEX = ".*\\.(?:mp4|m4v|mpeg|3gp|3gpp)$"; - - private final File file; - private final FileType type; - private Status status; - - public OfflineCourseFile(File file){ - this.file = file; - this.type = getFileType(file); - this.status = Status.SELECTED; - } - - public FileType getType() { - return type; - } - - public File getFile() { - return file; - } - - public void updateStatus(Status newStatus) { - status = newStatus; - } - - public Status getStatus() { - return status; - } - - private OfflineCourseFile.FileType getFileType(File file){ - OfflineCourseFile.FileType fileType = OfflineCourseFile.FileType.INVALID; - try { - InputStream inputStream = new FileInputStream(file); - ZipInputStream zipInputStream = new ZipInputStream(inputStream); - ZipEntry entry; - while ((entry = zipInputStream.getNextEntry()) != null) { - String name = entry.getName(); - if (name.matches(MODULES_XML_PATH) && !entry.isDirectory()) { - fileType = OfflineCourseFile.FileType.COURSE; - break; - } - - if (name.matches(MEDIA_REGEX) && !entry.isDirectory()) { - fileType = OfflineCourseFile.FileType.MEDIA; - break; - } - } - zipInputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - return fileType; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/OfflineCourseFile.kt b/app/src/main/java/org/digitalcampus/oppia/model/OfflineCourseFile.kt new file mode 100644 index 000000000..8eb76001c --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/OfflineCourseFile.kt @@ -0,0 +1,50 @@ +package org.digitalcampus.oppia.model + +import java.io.File +import java.io.FileInputStream +import java.io.IOException +import java.io.InputStream +import java.util.zip.ZipEntry +import java.util.zip.ZipInputStream + +class OfflineCourseFile(val file: File) { + enum class FileType { COURSE, MEDIA, INVALID } + enum class Status { SELECTED, IMPORTING, IMPORTED } + + companion object { + private const val MODULES_XML_PATH = ".*/module.xml" + private const val MEDIA_REGEX = ".*\\.(?:mp4|m4v|mpeg|3gp|3gpp)$" + } + + val type: FileType = getFileType(file) + var status: Status = Status.SELECTED + private set + + fun updateStatus(newStatus: Status) { + status = newStatus + } + + private fun getFileType(file: File): FileType { + var fileType = FileType.INVALID + try { + val inputStream: InputStream = FileInputStream(file) + val zipInputStream = ZipInputStream(inputStream) + var entry: ZipEntry + while (zipInputStream.nextEntry.also { entry = it } != null) { + val name = entry.name + if (name.matches(MODULES_XML_PATH.toRegex()) && !entry.isDirectory) { + fileType = FileType.COURSE + break + } + if (name.matches(MEDIA_REGEX.toRegex()) && !entry.isDirectory) { + fileType = FileType.MEDIA + break + } + } + zipInputStream.close() + } catch (e: IOException) { + e.printStackTrace() + } + return fileType + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/Points.java b/app/src/main/java/org/digitalcampus/oppia/model/Points.java deleted file mode 100644 index e52ff3c8f..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/Points.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import org.digitalcampus.oppia.utils.DateUtils; -import org.joda.time.DateTime; - -public class Points { - - private DateTime datetime; - private String event; - private String description; - private int pointsAwarded; - - public String getDateDayMonth() { - return DateUtils.DATE_FORMAT_DAY_MONTH.print(datetime); - } - - - public String getTimeHoursMinutes() { - return DateUtils.TIME_FORMAT_HOURS_MINUTES.print(datetime); - } - - public void setDateTime(String date) { - this.datetime = DateUtils.DATETIME_FORMAT.parseDateTime(date); - } - - public DateTime getDateTime() { - return datetime; - } - - public String getEvent() { - return event; - } - - public void setEvent(String event) { - this.event = event; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public int getPointsAwarded() { - return pointsAwarded; - } - - public void setPointsAwarded(int points) { - this.pointsAwarded = points; - } - - public String getDescriptionPrettified() { - return getDescription() == null ? null : capitalize(getDescription()).replace("_", " "); - } - - public String capitalize(String str) { - return str.substring(0, 1).toUpperCase() + str.substring(1); - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/Points.kt b/app/src/main/java/org/digitalcampus/oppia/model/Points.kt new file mode 100644 index 000000000..75dcea0a2 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/Points.kt @@ -0,0 +1,49 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import org.digitalcampus.oppia.utils.DateUtils +import org.joda.time.DateTime +import java.util.Locale + +class Points { + var dateTime: DateTime? = null + private set + var event: String? = null + var description: String? = null + var pointsAwarded = 0 + + fun getDateDayMonth(): String { + return DateUtils.DATE_FORMAT_DAY_MONTH.print(dateTime) + } + + fun getTimeHoursMinutes(): String { + return DateUtils.TIME_FORMAT_HOURS_MINUTES.print(dateTime) + } + + fun setDateTime(date: String?) { + dateTime = DateUtils.DATETIME_FORMAT.parseDateTime(date) + } + + fun getDescriptionPrettified(): String? { + return description?.let { capitalize(it).replace("_", " ") } + } + + private fun capitalize(str: String): String { + return str.substring(0, 1).uppercase(Locale.getDefault()) + str.substring(1) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/QuizAnswerFeedback.java b/app/src/main/java/org/digitalcampus/oppia/model/QuizAnswerFeedback.java deleted file mode 100644 index 49e12c012..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/QuizAnswerFeedback.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import java.util.List; - -public class QuizAnswerFeedback { - - public static final String TAG = QuizAnswerFeedback.class.getSimpleName(); - - private float score; - private String questionText; - private String feedbackText; - private List userResponse; - private boolean isSurvey; - - public float getScore() { - return score; - } - public void setScore(float score) { - this.score = score; - } - public String getQuestionText() { - return questionText; - } - public void setQuestionText(String questionText) { - this.questionText = questionText; - } - public String getFeedbackText() { - return feedbackText; - } - public void setFeedbackText(String feedbackText) { - this.feedbackText = feedbackText; - } - public List getUserResponse() { - return userResponse; - } - public void setUserResponse(List userResponse) { - this.userResponse = userResponse; - } - - public boolean isSurvey() { - return isSurvey; - } - - public void setIsSurvey(boolean survey) { - isSurvey = survey; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/QuizAnswerFeedback.kt b/app/src/main/java/org/digitalcampus/oppia/model/QuizAnswerFeedback.kt new file mode 100644 index 000000000..dc18047f4 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/QuizAnswerFeedback.kt @@ -0,0 +1,30 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +// TODO: Convert to data class when all references are migrated to kotlin +class QuizAnswerFeedback { + var score = 0f + var questionText: String? = null + var feedbackText: String? = null + var userResponse: List? = null + var isSurvey = false + + companion object { + val TAG = QuizAnswerFeedback::class.simpleName + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/QuizAttempt.java b/app/src/main/java/org/digitalcampus/oppia/model/QuizAttempt.java deleted file mode 100644 index 09be750df..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/QuizAttempt.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import android.content.Context; - -import org.digitalcampus.mobile.learning.R; -import org.digitalcampus.oppia.utils.DateUtils; -import org.digitalcampus.oppia.utils.TextUtilsJava; -import org.joda.time.DateTime; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; - -public class QuizAttempt implements Serializable { - - public static final String TAG = QuizAttempt.class.getSimpleName(); - public static final String TYPE_QUIZ = "quiz"; - public static final String TYPE_FEEDBACK = "feedback"; - - private DateTime datetime; - private long id; - private String data; - private String activityDigest; - private boolean sent; - private long courseId; - private long userId; - private float score; - private float maxscore; - private boolean passed; - private User user; - private String event; - private int points; - private long timetaken; - private String type; - - private String courseTitle; - private String quizTitle; - private String sectionTitle; - - public DateTime getDatetime() { - return datetime; - } - - public void setDatetime(DateTime datetime) { - this.datetime = datetime; - } - - public void setDateTimeFromString(String date) { - this.datetime = DateUtils.DATETIME_FORMAT.parseDateTime(date); - } - - public String getDateTimeString() { - return DateUtils.DATETIME_FORMAT.print(datetime); - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getData() { - return data; - } - - public void setData(String data) { - this.data = data; - } - - public String getActivityDigest() { - return activityDigest; - } - - public void setActivityDigest(String activityDigest) { - this.activityDigest = activityDigest; - } - - public boolean isSent() { - return sent; - } - - public void setSent(boolean sent) { - this.sent = sent; - } - - public long getCourseId() { - return courseId; - } - - public void setCourseId(long courseId) { - this.courseId = courseId; - } - - public long getUserId() { - return userId; - } - - public void setUserId(long userId) { - this.userId = userId; - } - - public float getScore() { - return score; - } - - public float getScoreAsPercent(){ - return this.score*100/this.maxscore; - } - - public String getScorePercentLabel(){ - return Math.round(getScoreAsPercent()) + "%"; - } - - public void setScore(float score) { - this.score = score; - } - - public float getMaxscore() { - return maxscore; - } - - public void setMaxscore(float maxscore) { - this.maxscore = maxscore; - } - - public boolean isPassed() { - return passed; - } - - public void setPassed(boolean passed) { - this.passed = passed; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - public static String asJSONCollectionString(Collection quizAttempts){ - - ArrayList jsonQuizAttempts = new ArrayList<>(); - for (QuizAttempt qa : quizAttempts){ - if (qa.getData() != null) { - jsonQuizAttempts.add(qa.getData()); - } - } - return "[" + TextUtilsJava.join(",", jsonQuizAttempts) + "]"; - - } - - public String getEvent() { - return event; - } - - public void setEvent(String event) { - this.event = event; - } - - public int getPoints() { - return points; - } - - public void setPoints(int points) { - this.points = points; - } - - public long getTimetaken() { - return timetaken; - } - - public void setTimetaken(long timetaken) { - this.timetaken = timetaken; - } - - public String getHumanTimetaken(){ - return String.format("%d min %ds", timetaken/60, timetaken % 60 ); - } - - public String getCourseTitle() { - return courseTitle; - } - - public void setCourseTitle(String courseTitle) { - this.courseTitle = courseTitle; - } - - public String getQuizTitle() { - return quizTitle; - } - - public void setQuizTitle(String quizTitle) { - this.quizTitle = quizTitle; - } - - public String getSectionTitle() { - return sectionTitle; - } - - public void setSectionTitle(String sectionTitle) { - this.sectionTitle = sectionTitle; - } - - public String getDisplayTitle(Context ctx){ - if (sectionTitle == null || quizTitle == null){ - return ctx.getString(R.string.quiz_attempts_unknown_quiz); - } - return sectionTitle + " > " + quizTitle; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/QuizAttempt.kt b/app/src/main/java/org/digitalcampus/oppia/model/QuizAttempt.kt new file mode 100644 index 000000000..12b4fa3be --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/QuizAttempt.kt @@ -0,0 +1,93 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import android.content.Context +import org.digitalcampus.mobile.learning.R +import org.digitalcampus.oppia.utils.DateUtils +import org.digitalcampus.oppia.utils.TextUtilsJava +import org.joda.time.DateTime +import java.io.Serializable +import kotlin.math.roundToInt + +class QuizAttempt : Serializable { + var datetime: DateTime? = null + var id: Long = 0 + var data: String? = null + var activityDigest: String? = null + var isSent = false + var courseId: Long = 0 + var userId: Long = 0 + var score = 0f + var maxscore = 0f + var isPassed = false + var user: User? = null + var event: String? = null + var points = 0 + var timetaken: Long = 0 + var type: String? = null + var courseTitle: String? = null + var quizTitle: String? = null + var sectionTitle: String? = null + + companion object { + @JvmField + val TAG = QuizAttempt::class.simpleName + const val TYPE_QUIZ = "quiz" + const val TYPE_FEEDBACK = "feedback" + + @JvmStatic + fun asJSONCollectionString(quizAttempts: Collection): String { + val jsonQuizAttempts = ArrayList() + for (qa in quizAttempts) { + if (qa.data != null) { + jsonQuizAttempts.add(qa.data) + } + } + return "[" + TextUtilsJava.join(",", jsonQuizAttempts) + "]" + } + } + + fun setDateTimeFromString(date: String?) { + datetime = DateUtils.DATETIME_FORMAT.parseDateTime(date) + } + + fun getDateTimeString(): String { + return DateUtils.DATETIME_FORMAT.print(datetime) + } + + fun getScoreAsPercent(): Float { + return score * 100 / maxscore + } + + fun getScorePercentLabel(): String { + return getScoreAsPercent().roundToInt().toString() + "%" + } + + fun getHumanTimetaken(): String { + val minutes = timetaken / 60 + val seconds = timetaken % 60 + return String.format("%d min %ds", minutes, seconds) + } + + fun getDisplayTitle(ctx: Context): String { + return if (sectionTitle == null || quizTitle == null) { + ctx.getString(R.string.quiz_attempts_unknown_quiz) + } else "$sectionTitle > $quizTitle" + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/QuizAttemptRepository.java b/app/src/main/java/org/digitalcampus/oppia/model/QuizAttemptRepository.java deleted file mode 100644 index cc5c3eb20..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/QuizAttemptRepository.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.digitalcampus.oppia.model; - -import android.content.Context; -import android.content.SharedPreferences; -import androidx.preference.PreferenceManager; - -import org.digitalcampus.oppia.activity.PrefsActivity; -import org.digitalcampus.oppia.database.DbHelper; -import org.digitalcampus.oppia.application.SessionManager; - -import java.util.List; -import java.util.Locale; - -public class QuizAttemptRepository { - - public List getQuizAttempts(Context ctx, QuizStats quiz){ - DbHelper db = DbHelper.getInstance(ctx); - long userId = db.getUserId(SessionManager.getUsername(ctx)); - return db.getQuizAttempts(quiz.getDigest(), userId); - } - - public List getGlobalQuizAttempts(Context ctx){ - DbHelper db = DbHelper.getInstance(ctx); - long userId = db.getUserId(SessionManager.getUsername(ctx)); - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); - String lang = prefs.getString(PrefsActivity.PREF_CONTENT_LANGUAGE, Locale.getDefault().getLanguage()); - return db.getGlobalQuizAttempts(userId, lang); - } - - public QuizStats getQuizAttemptStats(Context ctx, int courseId, String digest){ - DbHelper db = DbHelper.getInstance(ctx); - long userId = db.getUserId(SessionManager.getUsername(ctx)); - return db.getQuizAttemptStats(digest, courseId, userId); - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/QuizAttemptRepository.kt b/app/src/main/java/org/digitalcampus/oppia/model/QuizAttemptRepository.kt new file mode 100644 index 000000000..6e51497be --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/QuizAttemptRepository.kt @@ -0,0 +1,30 @@ +package org.digitalcampus.oppia.model + +import android.content.Context +import androidx.preference.PreferenceManager +import org.digitalcampus.oppia.activity.PrefsActivity +import org.digitalcampus.oppia.application.SessionManager +import org.digitalcampus.oppia.database.DbHelper +import java.util.Locale + +class QuizAttemptRepository { + fun getQuizAttempts(ctx: Context?, quiz: QuizStats): List { + val db = DbHelper.getInstance(ctx) + val userId = db.getUserId(SessionManager.getUsername(ctx)) + return db.getQuizAttempts(quiz.digest, userId) + } + + fun getGlobalQuizAttempts(ctx: Context?): List { + val db = DbHelper.getInstance(ctx) + val userId = db.getUserId(SessionManager.getUsername(ctx)) + val prefs = PreferenceManager.getDefaultSharedPreferences(ctx!!) + val lang = prefs.getString(PrefsActivity.PREF_CONTENT_LANGUAGE, Locale.getDefault().language) + return db.getGlobalQuizAttempts(userId, lang) + } + + fun getQuizAttemptStats(ctx: Context?, courseId: Int, digest: String?): QuizStats { + val db = DbHelper.getInstance(ctx) + val userId = db.getUserId(SessionManager.getUsername(ctx)) + return db.getQuizAttemptStats(digest, courseId, userId) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/QuizStats.java b/app/src/main/java/org/digitalcampus/oppia/model/QuizStats.java deleted file mode 100644 index 1c6e4dd44..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/QuizStats.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import android.util.Log; - -import java.io.Serializable; - -public class QuizStats implements Serializable { - - public static final String TAG = QuizStats.class.getSimpleName(); - - private String digest; - private int numAttempts; - private float maxScore = -1; - private float userScore = -1; - private float averageScore = -1; - private boolean passed; - - private String quizTitle; - private String sectionTitle; - - public String getDigest() { return digest; } - public void setDigest(String digest) { this.digest = digest; } - - public float getMaxScore() { - return maxScore; - } - public void setMaxScore(float maxScore) { - this.maxScore = maxScore; - } - - public float getUserScore() { return userScore; } - public void setUserScore(float userScore) { this.userScore = userScore; } - - public void setAverageScore(float averageScore) { - this.averageScore = averageScore; - } - public float getAverageScore(){ return averageScore; } - - public boolean isAttempted(){ return numAttempts > 0; } - - public int getPercent(){ - Log.d(TAG, "userScore:" + userScore); - Log.d(TAG, "maxScore:" + maxScore); - int percent = Math.round(userScore * 100.0f / Math.max(1,maxScore)); - Log.d(TAG, "percent:" + percent); - return percent; - } - - public int getAveragePercent(){ - return Math.round(averageScore * 100.0f / Math.max(1,maxScore)); - } - - public boolean isPassed(){ - return passed; - } - public void setPassed(boolean passed){ this.passed = passed; } - - public int getNumAttempts() { return numAttempts; } - public void setNumAttempts(int numAttempts) { this.numAttempts = numAttempts; } - - public String getQuizTitle() { - return quizTitle; - } - - public void setQuizTitle(String quizTitle) { - this.quizTitle = quizTitle; - } - - public String getSectionTitle() { - return sectionTitle; - } - - public void setSectionTitle(String sectionTitle) { - this.sectionTitle = sectionTitle; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/QuizStats.kt b/app/src/main/java/org/digitalcampus/oppia/model/QuizStats.kt new file mode 100644 index 000000000..39c8e60eb --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/QuizStats.kt @@ -0,0 +1,54 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import android.util.Log +import java.io.Serializable + +// TODO: Convert to data class when all references are migrated to kotlin +class QuizStats : Serializable { + var digest: String? = null + var numAttempts = 0 + var maxScore = -1f + var userScore = -1f + var averageScore = -1f + var isPassed = false + var quizTitle: String? = null + var sectionTitle: String? = null + + companion object { + @JvmField + val TAG = QuizStats::class.simpleName + } + + fun isAttempted(): Boolean { + return numAttempts > 0 + } + + fun getPercent(): Int { + Log.d(TAG, "userScore:$userScore") + Log.d(TAG, "maxScore:$maxScore") + val percent = (userScore * 100.0f / maxScore).toInt() + Log.d(TAG, "percent:$percent") + return percent + } + + fun getAveragePercent(): Int { + return (averageScore * 100.0f / maxScore).toInt() + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/SearchResult.java b/app/src/main/java/org/digitalcampus/oppia/model/SearchResult.java deleted file mode 100644 index 004d4c6b6..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/SearchResult.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import java.io.Serializable; - -public class SearchResult implements Serializable{ - - /** - * - */ - private static final long serialVersionUID = 45066452542727434L; - - public static final String TAG = SearchResult.class.getSimpleName(); - - private Course course; - private Activity activity; - private Section section; - - private float rank; - - public Course getCourse() { - return course; - } - public void setCourse(Course course) { - this.course = course; - } - public Activity getActivity() { - return activity; - } - public void setActivity(Activity activity) { - this.activity = activity; - } - public float getRank() { - return rank; - } - public void setRank(float rank) { - this.rank = rank; - } - public Section getSection() { - return section; - } - public void setSection(Section section) { - this.section = section; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/SearchResult.kt b/app/src/main/java/org/digitalcampus/oppia/model/SearchResult.kt new file mode 100644 index 000000000..886121c12 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/SearchResult.kt @@ -0,0 +1,32 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import java.io.Serializable + +class SearchResult : Serializable { + var course: Course? = null + var activity: Activity? = null + var section: Section? = null + var rank = 0f + + companion object { + private const val serialVersionUID = 45066452542727434L + @JvmField + val TAG = SearchResult::class.simpleName + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/Section.java b/app/src/main/java/org/digitalcampus/oppia/model/Section.java deleted file mode 100644 index 2df4a5b53..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/Section.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import org.digitalcampus.oppia.utils.TextUtilsJava; - -import java.io.File; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - - -public class Section extends MultiLangInfoModel implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 6360494638548755423L; - - public static final String TAG = Section.class.getSimpleName(); - private int order; - private List activities; - private String imageFile; - private String password; - private boolean unlocked = false; - - public String getImageFile() { - return imageFile; - } - - public void setImageFile(String imageFile) { - this.imageFile = imageFile; - } - - public Section(){ - activities = new ArrayList<>(); - } - - public int getOrder() { - return order; - } - - public void setOrder(int order) { - this.order = order; - } - - public List getActivities() { - return activities; - } - - public void addActivity(Activity activity){ - this.activities.add(activity); - } - public void setActivities(List activities) { - this.activities = (List) activities; - } - - public boolean isProtectedByPassword() { - return !TextUtilsJava.isEmpty(password); - } - - public void setPassword(String password) { - this.password = password; - } - - public String getPassword(){ - return password; - } - - public boolean checkPassword(String inputPassword){ - return TextUtilsJava.equals(password, inputPassword); - } - - public boolean isUnlocked() { - return unlocked; - } - - public void setUnlocked(boolean unlocked) { - this.unlocked = unlocked; - } - - public boolean hasCustomImage(){ - return !TextUtilsJava.isEmpty(imageFile); - } - - public String getImageFilePath(String prefix){ - if(!prefix.endsWith(File.separator)){ - prefix += File.separator; - } - return prefix + this.imageFile; - } - - public Activity getActivity(String digest){ - for (Activity activity : this.activities){ - if (digest.equals(activity.getDigest())) - return activity; - } - return null; - } - - public int getCompletedActivities(){ - int completed = 0; - for (Activity activity : this.activities){ - if (activity.getCompleted()) - completed++; - } - return completed; - } - -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/Section.kt b/app/src/main/java/org/digitalcampus/oppia/model/Section.kt new file mode 100644 index 000000000..7560bfcce --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/Section.kt @@ -0,0 +1,65 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import org.digitalcampus.oppia.utils.TextUtilsJava +import java.io.File +import java.io.Serializable + +// TODO: Convert to data class when all references are migrated to kotlin +class Section : MultiLangInfoModel(), Serializable { + var order = 0 + var activities: MutableList = ArrayList() + var imageFile: String? = null + var password: String? = null + var isUnlocked = false + + companion object { + private const val serialVersionUID = 6360494638548755423L + @JvmField + val TAG = Section::class.simpleName + } + + val isProtectedByPassword: Boolean + get() { return !TextUtilsJava.isEmpty(password) } + + fun addActivity(activity: Activity) { + activities.add(activity) + } + + fun checkPassword(inputPassword: String?): Boolean { + return TextUtilsJava.equals(password, inputPassword) + } + + fun hasCustomImage(): Boolean { + return !TextUtilsJava.isEmpty(imageFile) + } + + fun getImageFilePath(prefix: String): String { + val separator = if (!prefix.endsWith(File.separator)) File.separator else "" + return prefix + separator + imageFile + } + + fun getActivity(digest: String): Activity? { + return activities.find { it.digest == digest } + } + + fun getCompletedActivities(): Int { + return activities.count { it.completed } + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/Tag.java b/app/src/main/java/org/digitalcampus/oppia/model/Tag.java deleted file mode 100644 index 80b056299..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/Tag.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -public class Tag implements Serializable{ - - /** - * - */ - private static final long serialVersionUID = 5144400570961137778L; - - public static final String TAG_CLASS = Tag.class.getSimpleName(); - - private String name; - private int count; - private int id; - private String description; - private int orderPriority; - private String icon; - private boolean highlight = false; - private int countNewDownloadEnabled = -1; - private int countAvailable; - - private ArrayList courses = new ArrayList<>(); - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public int getCount() { - // count should not be under 0 - return Math.max(0, count); - } - public void setCount(int count) { - this.count = count; - } - public List getCourses() { - return courses; - } - public void setCourses(List courses) { - this.courses = (ArrayList) courses; - } - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - public int getOrderPriority() { - return orderPriority; - } - public void setOrderPriority(int orderPriority) { - this.orderPriority = orderPriority; - } - public String getIcon() { - return icon; - } - public void setIcon(String icon) { - this.icon = icon; - } - public boolean isHighlight() { - return highlight; - } - public void setHighlight(boolean highlight) { - this.highlight = highlight; - } - - - public int getCountNewDownloadEnabled() { - return countNewDownloadEnabled; - } - - public void setCountNewDownloadEnabled(int countNewDownloadEnabled) { - this.countNewDownloadEnabled = countNewDownloadEnabled; - } - - public int getCountAvailable() { - return countAvailable; - } - - public void setCountAvailable(int countAvailable) { - this.countAvailable = countAvailable; - } - - public void incrementCountAvailable() { - this.countAvailable++; - } - - public void decrementCountAvailable() { - this.countAvailable--; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/Tag.kt b/app/src/main/java/org/digitalcampus/oppia/model/Tag.kt new file mode 100644 index 000000000..21da69c12 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/Tag.kt @@ -0,0 +1,64 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import java.io.Serializable + +open class Tag : Serializable { + + companion object { + private const val serialVersionUID = 5144400570961137778L + val TAG = Tag::class.simpleName + } + + var name: String? = null + private var count = 0 + var id = 0 + var description: String? = null + var orderPriority = 0 + var icon: String? = null + var isHighlight = false + var countNewDownloadEnabled = -1 + var countAvailable = 0 + private val courses = ArrayList() + + fun getCount() : Int { + // count should not be under 0 + return count.coerceAtLeast(0) + } + + fun setCount(count: Int) { + this.count = count + } + + fun getCourses(): List { + return courses + } + + fun setCourses(courses: List) { + this.courses.clear() + this.courses.addAll(courses) + } + + fun incrementCountAvailable() { + countAvailable++ + } + + fun decrementCountAvailable() { + countAvailable-- + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/TagRepository.java b/app/src/main/java/org/digitalcampus/oppia/model/TagRepository.java deleted file mode 100644 index e2fff2029..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/TagRepository.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - - -import android.content.Context; - -import org.digitalcampus.mobile.learning.R; -import org.digitalcampus.oppia.activity.AppActivity; -import org.digitalcampus.oppia.api.ApiEndpoint; -import org.digitalcampus.oppia.api.Paths; -import org.digitalcampus.oppia.listener.APIRequestListener; -import org.digitalcampus.oppia.task.APIUserRequestTask; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.Iterator; -import java.util.List; - -public class TagRepository { - - public static final String TAG = TagRepository.class.getSimpleName(); - - private static final String JSON_PROPERTY_TAGS = "tags"; - private static final String JSON_PROPERTY_NAME = "name"; - private static final String JSON_PROPERTY_ID = "id"; - private static final String JSON_PROPERTY_COUNT = "count"; - private static final String JSON_PROPERTY_DESCRIPTION = "description"; - private static final String JSON_PROPERTY_ICON = "icon"; - private static final String JSON_PROPERTY_HIGHLIGHT = "highlight"; - private static final String JSON_PROPERTY_ORDER_PRIORITY = "order_priority"; - private static final String JSON_PROPERTY_COUNT_NEW_DOWNLOADS_ENABLED = "count_new_downloads_enabled"; - private static final String JSON_PROPERTY_COURSE_STATUSES = "course_statuses"; - - - public void getTagList(Context ctx, ApiEndpoint api) { - - ((AppActivity) ctx).showProgressDialog(ctx.getString(R.string.loading)); - - APIUserRequestTask task = new APIUserRequestTask(ctx, api); - String url = Paths.SERVER_TAG_PATH; - task.setAPIRequestListener((APIRequestListener) ctx); - task.execute(url); - } - - public void refreshTagList(List tags, JSONObject json, List installedCoursesNames) throws JSONException { - - for (int i = 0; i < (json.getJSONArray(JSON_PROPERTY_TAGS).length()); i++) { - JSONObject jsonObj = (JSONObject) json.getJSONArray(JSON_PROPERTY_TAGS).get(i); - Tag t = new Tag(); - t.setName(jsonObj.getString(JSON_PROPERTY_NAME)); - t.setId(jsonObj.getInt(JSON_PROPERTY_ID)); - t.setCount(jsonObj.getInt(JSON_PROPERTY_COUNT)); - // Description - if (jsonObj.has(JSON_PROPERTY_DESCRIPTION) && !jsonObj.isNull(JSON_PROPERTY_DESCRIPTION)) { - t.setDescription(jsonObj.getString(JSON_PROPERTY_DESCRIPTION)); - } - // icon - if (jsonObj.has(JSON_PROPERTY_ICON) && !jsonObj.isNull(JSON_PROPERTY_ICON)) { - t.setIcon(jsonObj.getString(JSON_PROPERTY_ICON)); - } - // highlight - if (jsonObj.has(JSON_PROPERTY_HIGHLIGHT) && !jsonObj.isNull(JSON_PROPERTY_HIGHLIGHT)) { - t.setHighlight(jsonObj.getBoolean(JSON_PROPERTY_HIGHLIGHT)); - } - // order priority - if (jsonObj.has(JSON_PROPERTY_ORDER_PRIORITY) && !jsonObj.isNull(JSON_PROPERTY_ORDER_PRIORITY)) { - t.setOrderPriority(jsonObj.getInt(JSON_PROPERTY_ORDER_PRIORITY)); - } - // Count new downloads enabled - if (jsonObj.has(JSON_PROPERTY_COUNT_NEW_DOWNLOADS_ENABLED) && !jsonObj.isNull(JSON_PROPERTY_COUNT_NEW_DOWNLOADS_ENABLED)) { - t.setCountNewDownloadEnabled(jsonObj.getInt(JSON_PROPERTY_COUNT_NEW_DOWNLOADS_ENABLED)); - } - - if (jsonObj.has(JSON_PROPERTY_COURSE_STATUSES) && !jsonObj.isNull(JSON_PROPERTY_COURSE_STATUSES)) { - t.setCountAvailable(t.getCountNewDownloadEnabled()); - JSONObject jObjCourseStatuses = jsonObj.getJSONObject(JSON_PROPERTY_COURSE_STATUSES); - Iterator keys = jObjCourseStatuses.keys(); - - while (keys.hasNext()) { - String key = keys.next(); - String value = jObjCourseStatuses.getString(key); - - if (isCourseInstalled(key, installedCoursesNames)) { - if(Course.STATUS_NEW_DOWNLOADS_DISABLED.equals(value)){ - t.incrementCountAvailable(); - } - } else { - if(Course.STATUS_READ_ONLY.equals(value)){ - t.decrementCountAvailable(); - } - } - } - } else { - t.setCountAvailable(t.getCountNewDownloadEnabled() > -1 ? t.getCountNewDownloadEnabled() : t.getCount()); - } - - if (t.getCountAvailable() > 0) { - tags.add(t); - } - } - } - - private boolean isCourseInstalled(String name, List installedCoursesNames) { - return installedCoursesNames.contains(name); - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/TagRepository.kt b/app/src/main/java/org/digitalcampus/oppia/model/TagRepository.kt new file mode 100644 index 000000000..2ba045215 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/TagRepository.kt @@ -0,0 +1,120 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import android.content.Context +import org.digitalcampus.mobile.learning.R +import org.digitalcampus.oppia.activity.AppActivity +import org.digitalcampus.oppia.api.ApiEndpoint +import org.digitalcampus.oppia.api.Paths +import org.digitalcampus.oppia.listener.APIRequestListener +import org.digitalcampus.oppia.task.APIUserRequestTask +import org.json.JSONException +import org.json.JSONObject + +class TagRepository { + + companion object { + val TAG = TagRepository::class.simpleName + private const val JSON_PROPERTY_TAGS = "tags" + private const val JSON_PROPERTY_NAME = "name" + private const val JSON_PROPERTY_ID = "id" + private const val JSON_PROPERTY_COUNT = "count" + private const val JSON_PROPERTY_DESCRIPTION = "description" + private const val JSON_PROPERTY_ICON = "icon" + private const val JSON_PROPERTY_HIGHLIGHT = "highlight" + private const val JSON_PROPERTY_ORDER_PRIORITY = "order_priority" + private const val JSON_PROPERTY_COUNT_NEW_DOWNLOADS_ENABLED = "count_new_downloads_enabled" + private const val JSON_PROPERTY_COURSE_STATUSES = "course_statuses" + } + + fun getTagList(ctx: Context, api: ApiEndpoint?) { + (ctx as AppActivity).showProgressDialog(ctx.getString(R.string.loading)) + val task = APIUserRequestTask(ctx, api) + val url = Paths.SERVER_TAG_PATH + task.setAPIRequestListener(ctx as APIRequestListener) + task.execute(url) + } + + @Throws(JSONException::class) + fun refreshTagList( + tags: MutableList, + json: JSONObject, + installedCoursesNames: List + ) { + for (i in 0 until json.getJSONArray(JSON_PROPERTY_TAGS).length()) { + val jsonObj = json.getJSONArray(JSON_PROPERTY_TAGS)[i] as JSONObject + val t = Tag() + t.name = jsonObj.getString(JSON_PROPERTY_NAME) + t.id = jsonObj.getInt(JSON_PROPERTY_ID) + t.setCount(jsonObj.getInt(JSON_PROPERTY_COUNT)) + + // Description + if (jsonObj.has(JSON_PROPERTY_DESCRIPTION) && !jsonObj.isNull(JSON_PROPERTY_DESCRIPTION)) { + t.description = jsonObj.getString(JSON_PROPERTY_DESCRIPTION) + } + + // icon + if (jsonObj.has(JSON_PROPERTY_ICON) && !jsonObj.isNull(JSON_PROPERTY_ICON)) { + t.icon = jsonObj.getString(JSON_PROPERTY_ICON) + } + + // highlight + if (jsonObj.has(JSON_PROPERTY_HIGHLIGHT) && !jsonObj.isNull(JSON_PROPERTY_HIGHLIGHT)) { + t.isHighlight = jsonObj.getBoolean(JSON_PROPERTY_HIGHLIGHT) + } + + // order priority + if (jsonObj.has(JSON_PROPERTY_ORDER_PRIORITY) && !jsonObj.isNull(JSON_PROPERTY_ORDER_PRIORITY)) { + t.orderPriority = jsonObj.getInt(JSON_PROPERTY_ORDER_PRIORITY) + } + + // Count new downloads enabled + if (jsonObj.has(JSON_PROPERTY_COUNT_NEW_DOWNLOADS_ENABLED) && !jsonObj.isNull(JSON_PROPERTY_COUNT_NEW_DOWNLOADS_ENABLED)) { + t.countNewDownloadEnabled = jsonObj.getInt(JSON_PROPERTY_COUNT_NEW_DOWNLOADS_ENABLED) + } + + if (jsonObj.has(JSON_PROPERTY_COURSE_STATUSES) && !jsonObj.isNull(JSON_PROPERTY_COURSE_STATUSES)) { + t.countAvailable = t.countNewDownloadEnabled + val jObjCourseStatuses = jsonObj.getJSONObject(JSON_PROPERTY_COURSE_STATUSES) + val keys = jObjCourseStatuses.keys() + while (keys.hasNext()) { + val key = keys.next() + val value = jObjCourseStatuses.getString(key) + if (isCourseInstalled(key, installedCoursesNames)) { + if (Course.STATUS_NEW_DOWNLOADS_DISABLED == value) { + t.incrementCountAvailable() + } + } else { + if (Course.STATUS_READ_ONLY == value) { + t.decrementCountAvailable() + } + } + } + } else { + t.countAvailable = if (t.countNewDownloadEnabled > -1) t.countNewDownloadEnabled else t.getCount() + } + if (t.countAvailable > 0) { + tags.add(t) + } + } + } + + private fun isCourseInstalled(name: String, installedCoursesNames: List): Boolean { + return installedCoursesNames.contains(name) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/TrackerLog.java b/app/src/main/java/org/digitalcampus/oppia/model/TrackerLog.java deleted file mode 100644 index 015fcf951..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/TrackerLog.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import org.digitalcampus.oppia.utils.DateUtils; -import org.digitalcampus.oppia.utils.TextUtilsJava; -import org.joda.time.DateTime; - -import java.util.Collection; - -public class TrackerLog { - - private DateTime datetime; - private long id; - private String digest; - private String content; - private String type; - private boolean submitted; - private boolean completed; - private long courseId; - private long userId; - private String event; - private int points; - - public long getId() { - return id; - } - public void setId(long id) { - this.id = id; - } - - public DateTime getDatetime() { - return datetime; - } - public void setDatetime(DateTime datetime) { - this.datetime = datetime; - } - public String getDigest() { - return digest; - } - public void setDigest(String digest) { - this.digest = digest; - } - public String getContent() { - return content; - } - public void setContent(String content) { - this.content = content; - } - public boolean isSubmitted() { - return submitted; - } - public void setSubmitted(boolean submitted) { - this.submitted = submitted; - } - - public String getDateTimeString() { - return DateUtils.DATETIME_FORMAT.print(datetime); - } - public boolean isCompleted() { - return completed; - } - public void setCompleted(boolean completed) { - this.completed = completed; - } - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - public long getCourseId() { - return courseId; - } - public void setCourseId(long courseId) { - this.courseId = courseId; - } - public long getUserId() { - return userId; - } - public void setUserId(long userId) { - this.userId = userId; - } - - public String getEvent() { - return event; - } - - public void setEvent(String event) { - this.event = event; - } - - public int getPoints() { - return points; - } - - public void setPoints(int points) { - this.points = points; - } - - @Override - public String toString(){ - return this.content; - } - - public static String asJSONCollectionString(Collection trackerLogs){ - return "[" + TextUtilsJava.join(",", trackerLogs) + "]"; - - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/TrackerLog.kt b/app/src/main/java/org/digitalcampus/oppia/model/TrackerLog.kt new file mode 100644 index 000000000..c2afba06b --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/TrackerLog.kt @@ -0,0 +1,50 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import org.digitalcampus.oppia.utils.DateUtils +import org.digitalcampus.oppia.utils.TextUtilsJava +import org.joda.time.DateTime + +class TrackerLog { + var datetime: DateTime? = null + var id: Long = 0 + var digest: String? = null + var content: String? = null + var type: String? = null + var isSubmitted = false + var isCompleted = false + var courseId: Long = 0 + var userId: Long = 0 + var event: String? = null + var points = 0 + + companion object { + @JvmStatic + fun asJSONCollectionString(trackerLogs: Collection?): String { + return "[" + TextUtilsJava.join(",", trackerLogs) + "]" + } + } + + fun getDateTimeString(): String { + return DateUtils.DATETIME_FORMAT.print(datetime) + } + + override fun toString(): String { + return content!! + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/TrackerLogRepository.java b/app/src/main/java/org/digitalcampus/oppia/model/TrackerLogRepository.java deleted file mode 100644 index ea8063d6a..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/TrackerLogRepository.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.digitalcampus.oppia.model; - -import android.content.Context; - -import org.digitalcampus.oppia.database.DbHelper; - -public class TrackerLogRepository { - - - public String getLastTrackerDatetime(Context context) throws Exception { - DbHelper db = DbHelper.getInstance(context); -// User user = db.getUser(SessionManager.getUsername(context)); #reminders-multi-user - return db.getLastTrackerDatetime(-1/*user.getUserId()*/); - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/TrackerLogRepository.kt b/app/src/main/java/org/digitalcampus/oppia/model/TrackerLogRepository.kt new file mode 100644 index 000000000..7d61d81c2 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/TrackerLogRepository.kt @@ -0,0 +1,13 @@ +package org.digitalcampus.oppia.model + +import android.content.Context +import org.digitalcampus.oppia.database.DbHelper + +class TrackerLogRepository { + + fun getLastTrackerDatetime(context: Context): String { + val db = DbHelper.getInstance(context) + // User user = db.getUser(SessionManager.getUsername(context)); #reminders-multi-user + return db.getLastTrackerDatetime(-1 /*user.getUserId()*/) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/User.java b/app/src/main/java/org/digitalcampus/oppia/model/User.java deleted file mode 100644 index 4d2a67c2d..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/User.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * This file is part of OppiaMobile - https://digital-campus.org/ - * - * OppiaMobile is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * OppiaMobile is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with OppiaMobile. If not, see . - */ - -package org.digitalcampus.oppia.model; - -import android.content.Context; - -import org.digitalcampus.oppia.database.DbHelper; -import org.digitalcampus.oppia.utils.CryptoUtils; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class User { - - public static final String API_KEY = "api_key"; - public static final String FIRST_NAME = "first_name"; - public static final String LAST_NAME = "last_name"; - public static final String EMAIL = "email"; - public static final String ORGANISATION = "organisation"; - public static final String JOB_TITLE = "job_title"; - public static final String SCORING_ENABLED = "scoring"; - public static final String BADGING_ENABLED = "badging"; - public static final String POINTS = "points"; - public static final String BADGES = "badges"; - public static final String COHORTS = "cohorts"; - - private long userId; - private String username; - private String email; - private String password; - private String passwordAgain; - private String firstname; - private String lastname; - private String apiKey; - private String jobTitle; - private String organisation; - private String phoneNo; - private String passwordEncrypted; - private boolean scoringEnabled = true; - private boolean badgingEnabled = true; - private int points = 0; - private int badges = 0; - private boolean offlineRegister = false; - private List cohorts = new ArrayList<>(); - - private Map userCustomFields = new HashMap<>(); - - private boolean localUser; - - public String getUsername() { - return username; - } - public void setUsername(String username) { - this.username = username; - } - public String getEmail() { - return email; - } - public void setEmail(String email) { - this.email = email; - } - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - public String getPasswordAgain() { - return passwordAgain; - } - public void setPasswordAgain(String passwordAgain) { - this.passwordAgain = passwordAgain; - } - public String getFirstname() { - return firstname; - } - public void setFirstname(String firstname) { - this.firstname = firstname; - } - public String getLastname() { - return lastname; - } - public void setLastname(String lastname) { - this.lastname = lastname; - } - public String getApiKey() { - return apiKey; - } - public void setApiKey(String apiKey) { - this.apiKey = apiKey; - } - public String getDisplayName() { - return firstname + " " + lastname; - } - - public int getPoints() { - return points; - } - public void setPoints(int points) { - this.points = points; - } - public int getBadges() { - return badges; - } - public void setBadges(int badges) { - this.badges = badges; - } - public boolean isScoringEnabled() { - return scoringEnabled; - } - public void setScoringEnabled(boolean scoringEnabled) { - this.scoringEnabled = scoringEnabled; - } - - public boolean isBadgingEnabled() { - return badgingEnabled; - } - public void setBadgingEnabled(boolean badgingEnabled) { - this.badgingEnabled = badgingEnabled; - } - - public String getPasswordEncrypted() { - if (this.passwordEncrypted == null){ - this.passwordEncrypted = CryptoUtils.encryptLocalPassword(this.password); - } - return this.passwordEncrypted; - } - - public void setPasswordEncrypted(String pwEncrypted){ - this.passwordEncrypted = pwEncrypted; - } - - public String getPasswordHashed(){ - if (this.password != null){ - return CryptoUtils.encryptExternalPassword(this.password); - } - else return ""; - } - - public long getUserId() { - return userId; - } - public void setUserId(long userId) { - this.userId = userId; - } - public String getJobTitle() { - return jobTitle; - } - public void setJobTitle(String jobTitle) { - this.jobTitle = jobTitle; - } - public String getOrganisation() { - return organisation; - } - public void setOrganisation(String organisation) { - this.organisation = organisation; - } - public String getPhoneNo() { - return phoneNo; - } - public void setPhoneNo(String phoneNo) { - this.phoneNo = phoneNo; - } - - - public boolean isOfflineRegister() { - return offlineRegister; - } - - public void setOfflineRegister(boolean offlineRegister) { - this.offlineRegister = offlineRegister; - } - - public Map getUserCustomFields() { - return userCustomFields; - } - - public CustomValue getCustomField(String key){ - return userCustomFields.get(key); - } - - public void putCustomField(String key, CustomValue value){ - userCustomFields.put(key, value); - } - - public void setUserCustomFields(Map userCustomFields) { - this.userCustomFields = userCustomFields; - } - - private void setCustomFieldsFromJSON(Context ctx, JSONObject json) throws JSONException { - List cFields = DbHelper.getInstance(ctx).getCustomFields(); - for (CustomField field : cFields) { - String key = field.getKey(); - if (json.has(key)) { - if (field.isString()) { - String value = json.getString(key); - this.putCustomField(key, new CustomValue<>(value)); - } else if (field.isBoolean()) { - boolean value = json.getBoolean(key); - this.putCustomField(key, new CustomValue<>(value)); - } else if (field.isInteger()) { - int value = json.getInt(key); - this.putCustomField(key, new CustomValue<>(value)); - } else if (field.isFloat()) { - float value = (float) json.getDouble(key); - this.putCustomField(key, new CustomValue<>(value)); - } - } - } - } - - public void setCohorts(List cohorts) { - this.cohorts = cohorts; - } - - public void setCohortsFromJSONArray(JSONArray cohortsJson) throws JSONException { - List cohorts = new ArrayList<>(); - for (int i = 0; i < cohortsJson.length(); i++) { - cohorts.add(cohortsJson.getInt(i)); - } - this.setCohorts(cohorts); - } - - public void updateFromJSON(Context ctx, JSONObject json) throws JSONException { - - this.setFirstname(json.getString(User.FIRST_NAME)); - this.setLastname(json.getString(User.LAST_NAME)); - if (json.has(User.API_KEY)){ - this.setApiKey(json.getString(User.API_KEY)); - } - if (json.has(User.EMAIL)) { - this.setEmail(json.getString(User.EMAIL)); - } - if (json.has(User.ORGANISATION)) { - this.setOrganisation(json.getString(User.ORGANISATION)); - } - if (json.has(User.JOB_TITLE)) { - this.setJobTitle(json.getString(User.JOB_TITLE)); - } - this.setCustomFieldsFromJSON(ctx, json); - - // Set user cohorts - if (json.has(User.COHORTS)) { - JSONArray cohortsJson = json.getJSONArray(User.COHORTS); - this.setCohortsFromJSONArray(cohortsJson); - } - - // Set badging and scoring data - try { - this.setPoints(json.getInt(User.POINTS)); - this.setBadges(json.getInt(User.BADGES)); - this.setScoringEnabled(json.getBoolean(User.BADGING_ENABLED)); - this.setBadgingEnabled(json.getBoolean(User.BADGING_ENABLED)); - } catch (JSONException e) { - this.setPoints(0); - this.setBadges(0); - this.setScoringEnabled(true); - this.setBadgingEnabled(true); - } - - } - - - public List getCohorts() { - return this.cohorts; - } - - public boolean isLocalUser() { - return localUser; - } - - public void setLocalUser(boolean localUser) { - this.localUser = localUser; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/User.kt b/app/src/main/java/org/digitalcampus/oppia/model/User.kt new file mode 100644 index 000000000..fba3376c8 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/User.kt @@ -0,0 +1,158 @@ +/* + * This file is part of OppiaMobile - https://digital-campus.org/ + * + * OppiaMobile is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * OppiaMobile is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OppiaMobile. If not, see . + */ +package org.digitalcampus.oppia.model + +import android.content.Context +import org.digitalcampus.oppia.database.DbHelper +import org.digitalcampus.oppia.utils.CryptoUtils +import org.json.JSONArray +import org.json.JSONException +import org.json.JSONObject + +open class User { + + companion object { + const val API_KEY = "api_key" + const val FIRST_NAME = "first_name" + const val LAST_NAME = "last_name" + const val EMAIL = "email" + const val ORGANISATION = "organisation" + const val JOB_TITLE = "job_title" + const val SCORING_ENABLED = "scoring" + const val BADGING_ENABLED = "badging" + const val POINTS = "points" + const val BADGES = "badges" + const val COHORTS = "cohorts" + } + + var userId: Long = 0 + var username: String? = null + var email: String? = null + var password: String? = null + var passwordAgain: String? = null + var firstname: String? = null + var lastname: String? = null + var apiKey: String? = null + var jobTitle: String? = null + var organisation: String? = null + var phoneNo: String? = null + private var passwordEncrypted: String? = null + var isScoringEnabled = true + var isBadgingEnabled = true + var points = 0 + var badges = 0 + var isOfflineRegister = false + var cohorts: List = ArrayList() + var userCustomFields: MutableMap = HashMap() + var isLocalUser = false + + fun getDisplayName(): String { + return "$firstname $lastname" + } + + fun getPasswordHashed(): String { + return if (password != null) { + CryptoUtils.encryptExternalPassword(password!!) + } else "" + } + + fun getPasswordEncrypted() : String? { + if (passwordEncrypted == null) { + passwordEncrypted = CryptoUtils.encryptLocalPassword(password!!) + } + return passwordEncrypted + } + + fun setPasswordEncrypted(passwordEncrypted: String?) { + this.passwordEncrypted = passwordEncrypted + } + + fun getCustomField(key: String): CustomValue? { + return userCustomFields[key] + } + + fun putCustomField(key: String, value: CustomValue) { + userCustomFields[key] = value + } + + private fun setCustomFieldsFromJSON(ctx: Context, json: JSONObject) { + val cFields = DbHelper.getInstance(ctx).customFields + for (field in cFields) { + val key = field.key + if (json.has(key)) { + if (field.isString) { + val value = json.getString(key) + putCustomField(key, CustomValue(StringValue(value))) + } else if (field.isBoolean) { + val value = json.getBoolean(key) + putCustomField(key, CustomValue(BooleanValue(value))) + } else if (field.isInteger) { + val value = json.getInt(key) + putCustomField(key, CustomValue(IntValue(value))) + } else if (field.isFloat) { + val value = json.getDouble(key).toFloat() + putCustomField(key, CustomValue(FloatValue(value))) + } + } + } + } + + fun setCohortsFromJSONArray(cohortsJson: JSONArray) { + val cohorts: MutableList = ArrayList() + for (i in 0 until cohortsJson.length()) { + cohorts.add(cohortsJson.getInt(i)) + } + this.cohorts = cohorts + } + + fun updateFromJSON(ctx: Context, json: JSONObject) { + firstname = json.getString(FIRST_NAME) + lastname = json.getString(LAST_NAME) + if (json.has(API_KEY)) { + apiKey = json.getString(API_KEY) + } + if (json.has(EMAIL)) { + email = json.getString(EMAIL) + } + if (json.has(ORGANISATION)) { + organisation = json.getString(ORGANISATION) + } + if (json.has(JOB_TITLE)) { + jobTitle = json.getString(JOB_TITLE) + } + setCustomFieldsFromJSON(ctx, json) + + // Set user cohorts + if (json.has(COHORTS)) { + val cohortsJson = json.getJSONArray(COHORTS) + setCohortsFromJSONArray(cohortsJson) + } + + // Set badging and scoring data + try { + points = json.getInt(POINTS) + badges = json.getInt(BADGES) + isScoringEnabled = json.getBoolean(BADGING_ENABLED) + isBadgingEnabled = json.getBoolean(BADGING_ENABLED) + } catch (e: JSONException) { + points = 0 + badges = 0 + isScoringEnabled = true + isBadgingEnabled = true + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllActivities.java b/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllActivities.java deleted file mode 100644 index 08edc4598..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllActivities.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.digitalcampus.oppia.model.coursecomplete; - -import android.content.Context; - -import org.digitalcampus.oppia.database.DbHelper; -import org.digitalcampus.oppia.model.Activity; -import org.digitalcampus.oppia.model.User; - -import java.util.List; - -public class AllActivities { - - public static boolean isComplete(Context ctx, int courseId, User user){ - - DbHelper db = DbHelper.getInstance(ctx); - // Get all the digests for this course - List activities = db.getCourseActivities(courseId); - - // check that the user has completed every activity - for (Activity activity: activities){ - if (!db.activityCompleted(courseId, activity.getDigest(), user.getUserId())){ - return false; - } - } - return true; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllActivities.kt b/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllActivities.kt new file mode 100644 index 000000000..59bc54b8c --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllActivities.kt @@ -0,0 +1,21 @@ +package org.digitalcampus.oppia.model.coursecomplete + +import android.content.Context +import org.digitalcampus.oppia.database.DbHelper +import org.digitalcampus.oppia.model.User + +object AllActivities { + fun isComplete(ctx: Context?, courseId: Int, user: User?): Boolean { + val db = DbHelper.getInstance(ctx) + // Get all the digests for this course + val activities = db.getCourseActivities(courseId.toLong()) + + // check that the user has completed every activity + for (activity in activities) { + if (!db.activityCompleted(courseId, activity.digest, user!!.userId)) { + return false + } + } + return true + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllQuizzes.java b/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllQuizzes.java deleted file mode 100644 index 9ac053cfd..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllQuizzes.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.digitalcampus.oppia.model.coursecomplete; - -import android.content.Context; - -import org.digitalcampus.oppia.database.DbHelper; -import org.digitalcampus.oppia.model.Activity; -import org.digitalcampus.oppia.model.User; - -import java.util.List; - -public class AllQuizzes { - - public static boolean isComplete(Context ctx, int courseId, User user){ - - DbHelper db = DbHelper.getInstance(ctx); - // Get all the digests for this course - List quizzes = db.getCourseQuizzes(courseId); - - // check that the user has completed every activity - for (Activity activity: quizzes){ - if (!db.activityCompleted(courseId, activity.getDigest(), user.getUserId())){ - return false; - } - } - return true; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllQuizzes.kt b/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllQuizzes.kt new file mode 100644 index 000000000..c76221db4 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllQuizzes.kt @@ -0,0 +1,21 @@ +package org.digitalcampus.oppia.model.coursecomplete + +import android.content.Context +import org.digitalcampus.oppia.database.DbHelper +import org.digitalcampus.oppia.model.User + +object AllQuizzes { + fun isComplete(ctx: Context?, courseId: Int, user: User?): Boolean { + val db = DbHelper.getInstance(ctx) + // Get all the digests for this course + val quizzes = db.getCourseQuizzes(courseId.toLong()) + + // check that the user has completed every activity + for (activity in quizzes) { + if (!db.activityCompleted(courseId, activity.digest, user!!.userId)) { + return false + } + } + return true + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllQuizzesPlusPercent.java b/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllQuizzesPlusPercent.java deleted file mode 100644 index 7fa22f688..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllQuizzesPlusPercent.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.digitalcampus.oppia.model.coursecomplete; - -import android.content.Context; - -import org.digitalcampus.oppia.database.DbHelper; -import org.digitalcampus.oppia.model.Activity; -import org.digitalcampus.oppia.model.User; - -import java.util.List; - -public class AllQuizzesPlusPercent { - - public static final String TAG = AllQuizzesPlusPercent.class.getSimpleName(); - - public static boolean isComplete(Context ctx, int courseId, User user, int percent){ - - DbHelper db = DbHelper.getInstance(ctx); - - // check all the quizzes complete - List quizzes = db.getCourseQuizzes(courseId); - - // check that the user has completed every activity - for (Activity activity: quizzes){ - if (!db.activityCompleted(courseId, activity.getDigest(), user.getUserId())){ - return false; - } - } - - int totalNonQuizActivities = 0; - int activitiesNonQuizCompleted = 0; - - // check no of other activities completed - List activities = db.getCourseActivities(courseId); - for (Activity activity: activities){ - if(activity.getActType().equals("quiz")){ - // skip to next in loop - continue; - } - totalNonQuizActivities++; - if (db.activityCompleted(courseId, activity.getDigest(), user.getUserId())){ - activitiesNonQuizCompleted++; - } - } - - if (totalNonQuizActivities == 0){ - return true; - } - int percentComplete = activitiesNonQuizCompleted * 100 / totalNonQuizActivities; - return percentComplete >= percent; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllQuizzesPlusPercent.kt b/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllQuizzesPlusPercent.kt new file mode 100644 index 000000000..09374515e --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/AllQuizzesPlusPercent.kt @@ -0,0 +1,43 @@ +package org.digitalcampus.oppia.model.coursecomplete + +import android.content.Context +import org.digitalcampus.oppia.database.DbHelper +import org.digitalcampus.oppia.model.User + +object AllQuizzesPlusPercent { + val TAG = AllQuizzesPlusPercent::class.simpleName + + fun isComplete(ctx: Context?, courseId: Int, user: User?, percent: Int): Boolean { + val db = DbHelper.getInstance(ctx) + + // check all the quizzes complete + val quizzes = db.getCourseQuizzes(courseId.toLong()) + + // check that the user has completed every activity + for (activity in quizzes) { + if (!db.activityCompleted(courseId, activity.digest, user!!.userId)) { + return false + } + } + var totalNonQuizActivities = 0 + var activitiesNonQuizCompleted = 0 + + // check no of other activities completed + val activities = db.getCourseActivities(courseId.toLong()) + for (activity in activities) { + if (activity.actType == "quiz") { + // skip to next in loop + continue + } + totalNonQuizActivities++ + if (db.activityCompleted(courseId, activity.digest, user!!.userId)) { + activitiesNonQuizCompleted++ + } + } + if (totalNonQuizActivities == 0) { + return true + } + val percentComplete = activitiesNonQuizCompleted * 100 / totalNonQuizActivities + return percentComplete >= percent + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/FinalQuiz.java b/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/FinalQuiz.java deleted file mode 100644 index 3250b0d80..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/FinalQuiz.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.digitalcampus.oppia.model.coursecomplete; - -import android.content.Context; - -import org.digitalcampus.oppia.database.DbHelper; -import org.digitalcampus.oppia.exception.ActivityNotFoundException; -import org.digitalcampus.oppia.model.User; - - -public class FinalQuiz { - - public static boolean isComplete(Context ctx, int courseId, User user) { - - DbHelper db = DbHelper.getInstance(ctx); - // Get final quiz digest - try { - String digest = db.getCourseFinalQuizDigest(courseId); - return db.activityCompleted(courseId, digest, user.getUserId()); - } catch (ActivityNotFoundException anfe) { - return false; - } - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/FinalQuiz.kt b/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/FinalQuiz.kt new file mode 100644 index 000000000..df8a34eab --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/coursecomplete/FinalQuiz.kt @@ -0,0 +1,19 @@ +package org.digitalcampus.oppia.model.coursecomplete + +import android.content.Context +import org.digitalcampus.oppia.database.DbHelper +import org.digitalcampus.oppia.exception.ActivityNotFoundException +import org.digitalcampus.oppia.model.User + +object FinalQuiz { + fun isComplete(ctx: Context?, courseId: Int, user: User?): Boolean { + val db = DbHelper.getInstance(ctx) + // Get final quiz digest + return try { + val digest = db.getCourseFinalQuizDigest(courseId.toLong()) + db.activityCompleted(courseId, digest, user!!.userId) + } catch (anfe: ActivityNotFoundException) { + false + } + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/db_model/Leaderboard.java b/app/src/main/java/org/digitalcampus/oppia/model/db_model/Leaderboard.java deleted file mode 100644 index 5cb7f1eef..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/db_model/Leaderboard.java +++ /dev/null @@ -1,126 +0,0 @@ -package org.digitalcampus.oppia.model.db_model; - -import androidx.annotation.NonNull; -import androidx.room.ColumnInfo; -import androidx.room.Entity; -import androidx.room.Ignore; -import androidx.room.PrimaryKey; -import androidx.room.TypeConverters; - -import org.digitalcampus.oppia.database.converters.TimestampConverter; -import org.joda.time.DateTime; - -@Entity(tableName = "leaderboard") -public class Leaderboard implements Comparable{ - - @PrimaryKey(autoGenerate = true) - @ColumnInfo(name = "_id") - private long id; - - private String username; - private String fullname; - private Integer points = 0; - private Integer position = 0; - - @TypeConverters(TimestampConverter.class) - private DateTime lastupdate = new DateTime(); - - @Ignore - private boolean isUser; - - - @Ignore - public Leaderboard(@NonNull String username, String fullname, Integer points, DateTime lastupdate, Integer position) { - this.username = username; - this.fullname = fullname; - this.points = points; - this.position = position; - this.lastupdate = lastupdate; - } - - @Ignore - public Leaderboard(@NonNull String username, String fullname, Integer points, String lastupdateStr, Integer position) { - this.username = username; - this.fullname = fullname; - this.points = points; - this.position = position; - setLastupdateStr(lastupdateStr); - } - - public Leaderboard() { - } - - @Override - public int compareTo(@NonNull Leaderboard other) { - if (this.points.equals(other.points)) - return 0; - else if (this.points < other.points) - return 1; - else - return -1; - } - - public void setLastupdateStr(String string) { - setLastupdate(TimestampConverter.fromTimestamp(string)); - } - - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - @NonNull - public String getUsername() { - return username; - } - - public void setUsername(@NonNull String username) { - this.username = username; - } - - public String getFullname() { - return fullname; - } - - public void setFullname(String fullname) { - this.fullname = fullname; - } - - public Integer getPoints() { - return points; - } - - public void setPoints(Integer points) { - this.points = points; - } - - public DateTime getLastupdate() { - return lastupdate; - } - - public void setLastupdate(DateTime lastupdate) { - this.lastupdate = lastupdate; - } - - public boolean isUser() { - return isUser; - } - - public void setUser(boolean user) { - isUser = user; - } - - - public Integer getPosition() { - return position; - } - - public void setPosition(Integer position) { - this.position = position; - } - -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/db_model/Leaderboard.kt b/app/src/main/java/org/digitalcampus/oppia/model/db_model/Leaderboard.kt new file mode 100644 index 000000000..66f68f6c5 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/db_model/Leaderboard.kt @@ -0,0 +1,55 @@ +package org.digitalcampus.oppia.model.db_model + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.Ignore +import androidx.room.PrimaryKey +import androidx.room.TypeConverters +import org.digitalcampus.oppia.database.converters.TimestampConverter +import org.joda.time.DateTime + +@Entity(tableName = "leaderboard") +class Leaderboard : Comparable { + @PrimaryKey(autoGenerate = true) + @ColumnInfo(name = "_id") + var id: Long = 0 + var username: String? = null + var fullname: String? = null + var points = 0 + var position = 0 + + @TypeConverters(TimestampConverter::class) + var lastupdate = DateTime() + + @Ignore + var isUser = false + + @Ignore + constructor(username: String, fullname: String?, points: Int, lastupdate: DateTime, position: Int) { + this.username = username + this.fullname = fullname + this.points = points + this.position = position + this.lastupdate = lastupdate + } + + @Ignore + constructor(username: String, fullname: String?, points: Int, lastupdateStr: String?, position: Int) { + this.username = username + this.fullname = fullname + this.points = points + this.position = position + setLastupdateStr(lastupdateStr) + } + + constructor() {} + + override operator fun compareTo(other: Leaderboard): Int { + return points.compareTo(other.points) + } + + fun setLastupdateStr(string: String?) { + lastupdate = TimestampConverter.fromTimestamp(string) + } + +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/db_model/UserCustomField.java b/app/src/main/java/org/digitalcampus/oppia/model/db_model/UserCustomField.java deleted file mode 100644 index 633c141c7..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/db_model/UserCustomField.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.digitalcampus.oppia.model.db_model; - -import androidx.annotation.NonNull; -import androidx.room.ColumnInfo; -import androidx.room.Entity; -import androidx.room.PrimaryKey; - -@Entity(tableName = "user_custom_field") -public class UserCustomField { - - - @PrimaryKey(autoGenerate = true) - @ColumnInfo(name = "_id") - private @NonNull long id; - private @NonNull String username; - - @ColumnInfo(name = "field_key") - private @NonNull String fieldKey; - - @ColumnInfo(name = "value_str") - private String valueStr; - - @ColumnInfo(name = "value_int") - private Integer valueInt; - - @ColumnInfo(name = "value_bool") - private Boolean valueBool; - - @ColumnInfo(name = "value_float") - private Float valueFloat; - - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - @NonNull - public String getUsername() { - return username; - } - - public void setUsername(@NonNull String username) { - this.username = username; - } - - @NonNull - public String getFieldKey() { - return fieldKey; - } - - public void setFieldKey(@NonNull String fieldKey) { - this.fieldKey = fieldKey; - } - - @NonNull - public String getValueStr() { - return valueStr; - } - - public void setValueStr(@NonNull String valueStr) { - this.valueStr = valueStr; - } - - @NonNull - public Integer getValueInt() { - return valueInt; - } - - public void setValueInt(@NonNull Integer valueInt) { - this.valueInt = valueInt; - } - - @NonNull - public Boolean getValueBool() { - return valueBool; - } - - public void setValueBool(@NonNull Boolean valueBool) { - this.valueBool = valueBool; - } - - @NonNull - public Float getValueFloat() { - return valueFloat; - } - - public void setValueFloat(@NonNull Float valueFloat) { - this.valueFloat = valueFloat; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/db_model/UserCustomField.kt b/app/src/main/java/org/digitalcampus/oppia/model/db_model/UserCustomField.kt new file mode 100644 index 000000000..c4af06460 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/db_model/UserCustomField.kt @@ -0,0 +1,28 @@ +package org.digitalcampus.oppia.model.db_model + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey + +@Entity(tableName = "user_custom_field") +class UserCustomField { + @PrimaryKey(autoGenerate = true) + @ColumnInfo(name = "_id") + var id: Long = 0 + var username: String = "" + + @ColumnInfo(name = "field_key") + var fieldKey: String = "" + + @ColumnInfo(name = "value_str") + var valueStr: String? = null + + @ColumnInfo(name = "value_int") + var valueInt: Int? = null + + @ColumnInfo(name = "value_bool") + var valueBool: Boolean? = null + + @ColumnInfo(name = "value_float") + var valueFloat: Float? = null +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/db_model/UserPreference.java b/app/src/main/java/org/digitalcampus/oppia/model/db_model/UserPreference.java deleted file mode 100644 index b12c75d13..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/db_model/UserPreference.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.digitalcampus.oppia.model.db_model; - -import androidx.annotation.NonNull; -import androidx.room.ColumnInfo; -import androidx.room.Entity; -import androidx.room.Index; -import androidx.room.PrimaryKey; - -@Entity(tableName = "user_preference", indices = {@Index(name = "idx", value = {"username", "preference"}, unique = true)}) -public class UserPreference { - - @PrimaryKey(autoGenerate = true) - @ColumnInfo(name = "_id") - private @NonNull long id; - private @NonNull String username; - private @NonNull String preference; - private String value; - - public UserPreference(@NonNull String username, @NonNull String preference, String value) { - this.username = username; - this.preference = preference; - this.value = value; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPreference() { - return preference; - } - - public void setPreference(String preference) { - this.preference = preference; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/db_model/UserPreference.kt b/app/src/main/java/org/digitalcampus/oppia/model/db_model/UserPreference.kt new file mode 100644 index 000000000..49ca95604 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/db_model/UserPreference.kt @@ -0,0 +1,17 @@ +package org.digitalcampus.oppia.model.db_model + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.Index +import androidx.room.PrimaryKey + +@Entity( + tableName = "user_preference", + indices = [Index(name = "idx", value = ["username", "preference"], unique = true)] +) +class UserPreference(var username: String, var preference: String, var value: String) { + @PrimaryKey(autoGenerate = true) + @ColumnInfo(name = "_id") + var id: Long = 0 + +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/responses/CourseServer.java b/app/src/main/java/org/digitalcampus/oppia/model/responses/CourseServer.java deleted file mode 100644 index 01fd3db38..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/responses/CourseServer.java +++ /dev/null @@ -1,120 +0,0 @@ -package org.digitalcampus.oppia.model.responses; - -import org.digitalcampus.oppia.model.Course; -import org.digitalcampus.oppia.utils.TextUtilsJava; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class CourseServer { - - - private int id; - private String shortname; - private Double version; - private String organisation; - private String author; - private Map title = new HashMap<>(); - private Map description = new HashMap<>(); - - private int priority = 0; - - private String status = Course.STATUS_LIVE; - - private boolean isRestricted = false; - private List cohorts; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getShortname() { - return shortname; - } - - public void setShortname(String shortname) { - this.shortname = shortname; - } - - public Double getVersion() { - return version; - } - - public void setVersion(Double version) { - this.version = version; - } - - public String getOrganisation() { - return organisation; - } - - public void setOrganisation(String organisation) { - this.organisation = organisation; - } - - public String getAuthor() { - return author; - } - - public void setAuthor(String author) { - this.author = author; - } - - public Map getTitle() { - return title; - } - - public void setTitle(Map title) { - this.title = title; - } - - public Map getDescription() { - return description; - } - - public void setDescription(Map description) { - this.description = description; - } - - public int getPriority() { - return priority; - } - - public void setPriority(int priority) { - this.priority = priority; - } - - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public boolean hasStatus(String status) { - return TextUtilsJava.equals(this.status, status); - } - - public boolean isRestricted() { - return isRestricted; - } - - public void setRestricted(boolean isRestricted) { - this.isRestricted = isRestricted; - } - - public List getRestrictedCohorts() { - return cohorts; - } - - public void setRestrictedCohorts(List cohorts) { - this.cohorts = cohorts; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/responses/CourseServer.kt b/app/src/main/java/org/digitalcampus/oppia/model/responses/CourseServer.kt new file mode 100644 index 000000000..5c62efc9c --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/responses/CourseServer.kt @@ -0,0 +1,22 @@ +package org.digitalcampus.oppia.model.responses + +import org.digitalcampus.oppia.model.Course +import org.digitalcampus.oppia.utils.TextUtilsJava + +class CourseServer { + var id = 0 + var shortname: String? = null + var version: Double = 0.0 + var organisation: String? = null + var author: String? = null + var title: Map = HashMap() + var description: Map = HashMap() + var priority = 0 + var status = Course.STATUS_LIVE + var isRestricted = false + var restrictedCohorts: List? = null + + fun hasStatus(status: String?): Boolean { + return TextUtilsJava.equals(this.status, status) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/model/responses/CoursesServerResponse.java b/app/src/main/java/org/digitalcampus/oppia/model/responses/CoursesServerResponse.java deleted file mode 100644 index 650308d5b..000000000 --- a/app/src/main/java/org/digitalcampus/oppia/model/responses/CoursesServerResponse.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.digitalcampus.oppia.model.responses; - -import java.util.List; - -public class CoursesServerResponse { - private List courses; - - public List getCourses() { - return courses; - } - - public void setCourses(List courses) { - this.courses = courses; - } -} diff --git a/app/src/main/java/org/digitalcampus/oppia/model/responses/CoursesServerResponse.kt b/app/src/main/java/org/digitalcampus/oppia/model/responses/CoursesServerResponse.kt new file mode 100644 index 000000000..dadadedd3 --- /dev/null +++ b/app/src/main/java/org/digitalcampus/oppia/model/responses/CoursesServerResponse.kt @@ -0,0 +1,5 @@ +package org.digitalcampus.oppia.model.responses + +class CoursesServerResponse { + var courses: List? = null +} \ No newline at end of file diff --git a/app/src/main/java/org/digitalcampus/oppia/utils/ui/fields/CustomFieldsUIManager.java b/app/src/main/java/org/digitalcampus/oppia/utils/ui/fields/CustomFieldsUIManager.java index ba0b03fb0..edd5c34fe 100644 --- a/app/src/main/java/org/digitalcampus/oppia/utils/ui/fields/CustomFieldsUIManager.java +++ b/app/src/main/java/org/digitalcampus/oppia/utils/ui/fields/CustomFieldsUIManager.java @@ -15,8 +15,11 @@ import org.digitalcampus.mobile.learning.R; import org.digitalcampus.oppia.database.DbHelper; +import org.digitalcampus.oppia.model.BooleanValue; import org.digitalcampus.oppia.model.CustomField; import org.digitalcampus.oppia.model.CustomValue; +import org.digitalcampus.oppia.model.IntValue; +import org.digitalcampus.oppia.model.StringValue; import org.digitalcampus.oppia.model.User; import org.digitalcampus.oppia.utils.TextUtilsJava; @@ -206,13 +209,13 @@ public Map getCustomFieldValues(){ CustomField field = formField.first; if (field.isBoolean()){ ValidableSwitchLayout input = (ValidableSwitchLayout) formField.second; - values.put(field.getKey(), new CustomValue<>(input.isChecked())); + values.put(field.getKey(), new CustomValue(new BooleanValue(input.isChecked()))); } else if (field.isChoices()){ ValidableSpinnerLayout input = (ValidableSpinnerLayout) formField.second; String value = input.getCleanedValue(); if (value != null && !TextUtilsJava.isEmpty(value)){ - values.put(field.getKey(), new CustomValue<>(input.getCleanedValue())); + values.put(field.getKey(), new CustomValue(new StringValue(input.getCleanedValue()))); } } @@ -221,11 +224,11 @@ else if (field.isChoices()){ if (field.isInteger()){ String value = input.getCleanedValue(); if (value != null && !TextUtilsJava.isEmpty(value)){ - values.put(field.getKey(), new CustomValue<>(Integer.parseInt(value))); + values.put(field.getKey(), new CustomValue(new IntValue(Integer.parseInt(value)))); } } else{ - values.put(field.getKey(), new CustomValue<>(input.getCleanedValue())); + values.put(field.getKey(), new CustomValue(new StringValue(input.getCleanedValue()))); } } diff --git a/app/src/main/java/org/digitalcampus/oppia/widgets/FeedbackWidget.java b/app/src/main/java/org/digitalcampus/oppia/widgets/FeedbackWidget.java index 1ada881a2..6c94f26a6 100644 --- a/app/src/main/java/org/digitalcampus/oppia/widgets/FeedbackWidget.java +++ b/app/src/main/java/org/digitalcampus/oppia/widgets/FeedbackWidget.java @@ -127,7 +127,7 @@ void showAnswersFeedback() { for(QuizQuestion q: questions){ if(!(q instanceof Description) && !q.isSkipped()){ QuizAnswerFeedback qf = new QuizAnswerFeedback(); - qf.setIsSurvey(true); + qf.setSurvey(true); qf.setScore(100); qf.setQuestionText(q.getTitle(prefLang)); qf.setUserResponse(q.getUserResponses());