Skip to content

Commit

Permalink
Add management of the dates of validity of the schedules
Browse files Browse the repository at this point in the history
  • Loading branch information
burgyl committed Sep 7, 2020
1 parent c435f28 commit b096fb6
Show file tree
Hide file tree
Showing 10 changed files with 161 additions and 34 deletions.
6 changes: 3 additions & 3 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ android {
applicationId "ch.lburgy.heiafrschedule"
minSdkVersion 18
targetSdkVersion 29
versionCode 2
versionName "1.0.1"
versionCode 3
versionName "1.0.2"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
Expand All @@ -29,7 +29,7 @@ dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])

implementation group: 'org.apache.httpcomponents', name: 'httpclient-android', version: '4.3.5.1'
implementation 'com.google.android.material:material:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'com.squareup.okhttp3:okhttp:4.6.0'
implementation 'com.squareup.moshi:moshi:1.9.3'
implementation 'com.squareup.okio:okio:2.8.0'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,18 +138,18 @@ public void run() {
}).start();

if (savedInstanceState == null) {
getLessonsAndShowThem(false);
getLessonsAndShowThem(false, true);
} else {
lessonsCompletesByDay = (HashMap<Integer, ArrayList<LessonOfClassComplete>>)
savedInstanceState.getSerializable(KEY_SAVED_LESSONS);
if (savedInstanceState.getBoolean(KEY_SAVED_THREAD_ALIVE, false)) {
threadType = (ThreadType) savedInstanceState.getSerializable(KEY_SAVED_THREAD_TYPE);
switch (threadType) {
case getLessons:
getLessonsAndShowThem(false);
getLessonsAndShowThem(false, false);
break;
case getLessonsFromInternet:
getLessonsAndShowThem(true);
getLessonsAndShowThem(true, false);
break;
}
} else {
Expand All @@ -158,17 +158,57 @@ public void run() {
}
}

private void getLessonsAndShowThem(final boolean forceFromInternet) {
private boolean isNewer(boolean showToast) throws HttpBasicClient.HttpException, InterruptedIOException, HttpBasicClient.NoInternetConnectionException, UnknownHostException {
if (!httpBasicClient.isConnectedToInternet()) return false;
Date[] dates = httpBasicClient.getScheduleDates();

if (dates != null && dates.length == 2 && dates[0] != null && dates[1] != null) {
Date[] scheduleDates = prefManager.getScheduleDates();
if (scheduleDates[1] == null || scheduleDates[1].compareTo(dates[0]) < 0) {
// Delete data
lessonDao.deleteLessons();
roomHEIAFRDao.deleteRooms();
teacherDao.deleteTeachers();
prefManager.setLastUpdateRoomsLessons(null);
// Set the new schedule dates
prefManager.setScheduleDates(dates);
if (showToast) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, R.string.new_schedules, Toast.LENGTH_LONG).show();
}
});
}
return true;
}
}
return false;
}

private void getLessonsAndShowThem(final boolean forceFromInternet, final boolean firstLaunch) {
if (MainActivity.this.isDestroyed()) return;
String progressTitle = getResources().getString(R.string.progress_refresh_lessons_title);
progressDialog = ProgressDialog.show(this, progressTitle, null, true);
threadType = ThreadType.getLessons;
if (currentThread != null && currentThread.isAlive())
currentThread.interrupt();
currentThread = new Thread(new Runnable() {
@Override
public void run() {
try {
boolean thisForceFromInternet = forceFromInternet;
int httpCode = CODE_NO_PROBLEMS;
if (!forceFromInternet) {
try {
if (firstLaunch && isNewer(true))
thisForceFromInternet = true;
} catch (HttpBasicClient.HttpException e) {
httpCode = e.getCode();
} catch (UnknownHostException | HttpBasicClient.NoInternetConnectionException e) {
httpCode = CODE_NO_CONNECTION;
}

if (!thisForceFromInternet) {
lessonsCompletesByDay = new HashMap<>();
for (int i = 0; i < NB_DAYS; i++)
lessonsCompletesByDay.put(i, new ArrayList<LessonOfClassComplete>());
Expand Down Expand Up @@ -284,6 +324,8 @@ private void refreshLessons() {
String progressTitle = getResources().getString(R.string.progress_refresh_lessons_title);
progressDialog = ProgressDialog.show(this, progressTitle, null, true);
threadType = ThreadType.getLessonsFromInternet;
if (currentThread != null && currentThread.isAlive())
currentThread.interrupt();
currentThread = new Thread(new Runnable() {
@Override
public void run() {
Expand Down Expand Up @@ -327,6 +369,8 @@ private void getLessonsFromInternet(boolean deleteExisting) throws HttpBasicClie
if (deleteExisting) {
lessonClassJoinDao.deleteLessonsFromClass(classHEIAFR.getName());
lessonClassJoinDao.deleteLessonsNoClass();
} else {
isNewer(false);
}

if (roomHEIAFRDao.getNbRoom() == 0) {
Expand All @@ -351,7 +395,7 @@ private void getLessonsFromInternet(boolean deleteExisting) throws HttpBasicClie
try {
lessonClassJoinDao.insertLessonClassJoin(new LessonClassJoin(lesson.getId(), classHEIAFR.getName()));
} catch (SQLiteConstraintException e) {
// do nothing, the association is allready in the DB
// do nothing, the association is already in the DB
}

ArrayList<RoomHEIAFR> rooms = new ArrayList<>();
Expand All @@ -365,7 +409,7 @@ private void getLessonsFromInternet(boolean deleteExisting) throws HttpBasicClie
try {
lessonRoomJoinDao.insertLessonRoomJoin(new LessonRoomJoin(lesson.getId(), roomID));
} catch (SQLiteConstraintException e) {
// do nothing, the association is allready in the DB
// do nothing, the association is already in the DB
}
}

Expand All @@ -390,6 +434,7 @@ private void getLessonsFromInternet(boolean deleteExisting) throws HttpBasicClie
}
classHEIAFR.setLastUpdate(new Date());
classHEIAFRDao.updateClassHEIAFR(classHEIAFR);
prefManager.setScheduleDates(httpBasicClient.getScheduleDates());
}

private void showHttpErrorCode(int httpCode) {
Expand Down Expand Up @@ -460,7 +505,7 @@ public void run() {
});
}
}).start();
getLessonsAndShowThem(false);
getLessonsAndShowThem(false, false);
}
}
if (prefManager.isLaunchWelcome()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@

import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import ch.lburgy.heiafrschedule.R;
import ch.lburgy.heiafrschedule.database.ClassHEIAFR;
Expand Down Expand Up @@ -162,11 +165,18 @@ public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
findPreference(keyTheme9).setVisible(true);
}

Preference btnDeleteDatas = findPreference(getString(R.string.settings_key_delete_datas));
btnDeleteDatas.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
Date[] dates = prefManager.getScheduleDates();
if (dates != null && dates.length == 2 && dates[0] != null && dates[1] != null) {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
Preference preference = findPreference(getString(R.string.settings_key_data_schedule_dates));
preference.setTitle(getResources().getString(R.string.data_schedule_dates, df.format(dates[0]), df.format(dates[1])));
preference.setVisible(true);
}

findPreference(getString(R.string.settings_key_delete_data)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
deleteDatas();
deleteData();
return true;
}
});
Expand Down Expand Up @@ -243,18 +253,20 @@ public void run() {
}).start();
}

private void deleteDatas() {
private void deleteData() {
new Thread(new Runnable() {
@Override
public void run() {
lessonDao.deleteLessons();
roomHEIAFRDao.deleteRooms();
teacherDao.deleteTeachers();
prefManager.setLastUpdateRoomsLessons(null);
prefManager.setScheduleDates(new Date[2]);
classChanged = true;
getActivity().runOnUiThread(new Runnable() {
public void run() {
String message = getResources().getString(R.string.datas_deleted);
findPreference(getString(R.string.settings_key_data_schedule_dates)).setVisible(false);
String message = getResources().getString(R.string.data_deleted);
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,12 @@
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

Expand Down Expand Up @@ -85,11 +89,46 @@ private void initCredentials(String username, String password) {
}
}

public Date[] getScheduleDates() throws HttpException, UnknownHostException, NoInternetConnectionException, InterruptedIOException {
Document doc = getDoc(URL_CLASSES, true);
if (doc == null) return null;

Date[] dates = new Date[2];
Element table = doc.getElementsByTag("table").get(4);
Element script = table.getElementsByTag("script").get(0);
String scriptContent = script.childNode(0).toString();

// Get the HTML from within the script tag
Pattern pattern = Pattern.compile("<.*>");
Matcher matcher = pattern.matcher(scriptContent);
matcher.find();
String datesString = Jsoup.parse(matcher.group(0)).text();

// Get the dates
pattern = Pattern.compile(".*?du (.*?) au (.*)");
matcher = pattern.matcher(datesString);
matcher.find();
String firstDate = matcher.group(1);
String secondDate = matcher.group(2);

// Parse them
SimpleDateFormat parser = new SimpleDateFormat("dd MMM yyyy", Locale.FRENCH);
try {
dates[0] = parser.parse(firstDate);
dates[1] = parser.parse(secondDate);
} catch (ParseException e) {
e.printStackTrace();
return null;
}

return dates;
}

public List<ClassHEIAFR> getClasses() throws HttpException, UnknownHostException, NoInternetConnectionException, InterruptedIOException {
ArrayList<ClassHEIAFR> classes = new ArrayList<>();
Document doc = getDoc(URL_CLASSES, true);
if (doc == null) return null;

ArrayList<ClassHEIAFR> classes = new ArrayList<>();
Element select = doc.getElementsByTag("select").first();
Elements options = select.getElementsByTag("option");
for (Element option : options) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ public class PrefManager {
private static final String KEY_CLASS_ID = "class_id";
private static final String KEY_THEME = "theme";
private static final String KEY_LAST_UPDATE_ROOMS_LESSONS = "last_update_rooms_lessons";
private static final String KEY_SCHEDULE_DATE_1 = "schedule_date_1";
private static final String KEY_SCHEDULE_DATE_2 = "schedule_date_2";

private static final String KEY_IV = "-iv";
private static final String KEY_ENCRYPTED = "encrypted_key";
Expand Down Expand Up @@ -112,6 +114,21 @@ public Date getLastUpdateRoomsLessons() {
return DateConverter.toDate(pref.getLong(KEY_LAST_UPDATE_ROOMS_LESSONS, -1));
}

public void setScheduleDates(Date[] scheduleDates) {
if (scheduleDates != null && scheduleDates.length == 2) {
editor.putLong(KEY_SCHEDULE_DATE_1, DateConverter.fromDate(scheduleDates[0]));
editor.putLong(KEY_SCHEDULE_DATE_2, DateConverter.fromDate(scheduleDates[1]));
editor.commit();
}
}

public Date[] getScheduleDates() {
Date[] scheduleDates = new Date[2];
scheduleDates[0] = DateConverter.toDate(pref.getLong(KEY_SCHEDULE_DATE_1, -1));
scheduleDates[1] = DateConverter.toDate(pref.getLong(KEY_SCHEDULE_DATE_2, -1));
return scheduleDates;
}

public void setTheme(int theme) {
editor.putInt(KEY_THEME, theme);
editor.commit();
Expand Down
8 changes: 5 additions & 3 deletions app/src/main/res/values-de/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
<string name="classes_refreshed">Die Liste der Klassen wurde aktualisiert</string>
<string name="infos_header">Informationen</string>
<string name="display_header">Display</string>
<string name="datas_header">Daten</string>
<string name="data_header">Daten</string>
<string name="theme_title">Design</string>
<string name="classes_dialog_title">Wählen Sie Ihre Klasse</string>
<string name="theme_dialog_title">Design auswählen</string>
Expand All @@ -32,8 +32,8 @@
<string name="action_find_room">Einen Raum finden</string>
<string name="error_end_time_before_start">Die Endzeit muss später als die Startzeit liegen</string>
<string name="progress_search_rooms_title">Räume für Sie suchen …</string>
<string name="delete_datas">Lokale Daten löschen</string>
<string name="datas_deleted">Lokale Daten wurden gelöscht</string>
<string name="delete_data">Lokale Daten löschen</string>
<string name="data_deleted">Lokale Daten wurden gelöscht</string>
<string name="warning_first_search">Da dies das erste Mal ist, dass Sie einen Raum finden wollen, muss die Anwendung alle Unterrichte aller Räume aus dem Internet abrufen, was bis zu 2 oder 3 Minuten dauern kann.</string>
<string name="dialog_downloading_title">Das Update herunterladen …</string>
<string name="dialog_update_title">Möchten Sie die Anwendung aktualisieren ?</string>
Expand All @@ -46,4 +46,6 @@
<string name="about_header">Über</string>
<string name="licenses_header">Lizenzen</string>
<string name="see_github_title">Siehe das Projekt auf GitHub</string>
<string name="data_schedule_dates">Zeitplan vom %1$s bis %2$s</string>
<string name="new_schedules">Neue Zeitpläne sind verfügbar !</string>
</resources>
8 changes: 5 additions & 3 deletions app/src/main/res/values-fr/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
<string name="title_activity_settings">Paramètres</string>
<string name="display_header">Affichage</string>
<string name="infos_header">Informations</string>
<string name="datas_header">Données</string>
<string name="data_header">Données</string>
<string name="theme_title">Thème</string>
<string name="classes_dialog_title">Choisissez votre classe</string>
<string name="classes_title">Classe</string>
Expand All @@ -32,8 +32,8 @@
<string name="action_find_room">Trouver une salle</string>
<string name="error_end_time_before_start">L\'heure de fin doit être postérieure à l\'heure de début</string>
<string name="progress_search_rooms_title">Recherche de salles pour vous …</string>
<string name="delete_datas">Supprimer les données locales</string>
<string name="datas_deleted">Les données locales ont été supprimées</string>
<string name="delete_data">Supprimer les données locales</string>
<string name="data_deleted">Les données locales ont été supprimées</string>
<string name="warning_first_search">Etant donné que c\'est la première fois que vous voulez trouver une salle, l\'application doit obtenir tous les cours de toutes les salles à partir d\'Internet, ce qui peut prendre jusqu\'à 2 ou 3 minutes.</string>
<string name="dialog_update_title">Voulez-vous mettre à jour l\'application ?</string>
<string name="dialog_downloading_title">Téléchargement de la mise à jour …</string>
Expand All @@ -46,4 +46,6 @@
<string name="license_moshi_description">par Square Open Source, sous license Apache 2.0</string>
<string name="license_jsoup_description">par Jonathan Hedley, sous license MIT</string>
<string name="license_httpcomponents_description">par The Apache Software Foundation, sous license Apache 2.0</string>
<string name="data_schedule_dates">Horaires du %1$s au %2$s</string>
<string name="new_schedules">De nouveaux horaires sont disponibles !</string>
</resources>
8 changes: 5 additions & 3 deletions app/src/main/res/values-it/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<string name="title_activity_settings">Impostazioni</string>
<string name="http_error">Errore HTTP</string>
<string name="infos_header">Informazioni</string>
<string name="datas_header">Dati</string>
<string name="data_header">Dati</string>
<string name="theme_title">Tema</string>
<string name="classes_dialog_title">Scelga la vostra classe</string>
<string name="theme_dialog_title">Scelga tema</string>
Expand All @@ -32,8 +32,8 @@
<string name="action_find_room">Trovare una stanza</string>
<string name="error_end_time_before_start">L\'ora della fine deve essere successiva all\'ora del inizio</string>
<string name="progress_search_rooms_title">Ricerca stanze per lei …</string>
<string name="delete_datas">Cancellare i dati locali</string>
<string name="datas_deleted">I dati locali sono stati cancellati</string>
<string name="delete_data">Cancellare i dati locali</string>
<string name="data_deleted">I dati locali sono stati cancellati</string>
<string name="warning_first_search">Poiché è la prima volta che si desidera trovare una stanza, l\'applicazione deve recuperare tutte le lezioni di tutte le stanze da Internet, che può richiedere fino a 2 o 3 minuti.</string>
<string name="dialog_update_title">Vuole aggiornare l\'applicazione ?</string>
<string name="dialog_downloading_title">Il download del aggiornamento …</string>
Expand All @@ -46,4 +46,6 @@
<string name="about_header">About</string>
<string name="licenses_header">Licenze</string>
<string name="see_github_title">Vedi il progetto su GitHub</string>
<string name="data_schedule_dates">Orari dal %1$s al %2$s</string>
<string name="new_schedules">Sono disponibili nuovi orari !</string>
</resources>
Loading

0 comments on commit b096fb6

Please sign in to comment.