Merge pull request #109 from refilc/dev

dev to master after half a year finally <3
This commit is contained in:
Márton Kiss 2024-05-05 17:35:27 +02:00 committed by GitHub
commit 3db67b2288
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
818 changed files with 55930 additions and 41243 deletions

View File

@ -15,10 +15,10 @@ jobs:
encodedString: ${{ secrets.KEYSTORE_BASE64 }} encodedString: ${{ secrets.KEYSTORE_BASE64 }}
- name: Create key.properties - name: Create key.properties
run: | run: |
echo "storeFile=${{ steps.android_keystore.outputs.filePath }}" > filcnaplo/android/key.properties echo "storeFile=${{ steps.android_keystore.outputs.filePath }}" > refilc/android/key.properties
echo "storePassword=${{ secrets.STORE_PASSWORD }}" >> filcnaplo/android/key.properties echo "storePassword=${{ secrets.STORE_PASSWORD }}" >> refilc/android/key.properties
echo "keyPassword=${{ secrets.KEY_PASSWORD }}" >> filcnaplo/android/key.properties echo "keyPassword=${{ secrets.KEY_PASSWORD }}" >> refilc/android/key.properties
echo "keyAlias=${{ secrets.KEY_ALIAS }}" >> filcnaplo/android/key.properties echo "keyAlias=${{ secrets.KEY_ALIAS }}" >> refilc/android/key.properties
- uses: actions/setup-java@v3 - uses: actions/setup-java@v3
with: with:
distribution: "zulu" distribution: "zulu"
@ -32,7 +32,7 @@ jobs:
- name: Install dependencies - name: Install dependencies
run: ./fix-pub.sh run: ./fix-pub.sh
- name: Build - name: Build
run: cd filcnaplo && ./build.sh run: cd refilc && ./build.sh
- name: Upload Android Release - name: Upload Android Release
uses: actions/upload-artifact@v2 uses: actions/upload-artifact@v2
with: with:

View File

@ -46,7 +46,7 @@ jobs:
# Build and sign the ipa using a single flutter command # Build and sign the ipa using a single flutter command
- name: Building IPA - name: Building IPA
working-directory: filcnaplo working-directory: refilc
run: bash build-ipa.sh run: bash build-ipa.sh
# Collect the file and upload as artifact # Collect the file and upload as artifact
@ -55,7 +55,7 @@ jobs:
with: with:
name: release-ipa name: release-ipa
# Path to the release files # Path to the release files
path: filcnaplo/build/ios/ipa/*.ipa path: refilc/build/ios/ipa/*.ipa
# Important! Cleanup: remove the certificate and provisioning profile from the runner! # Important! Cleanup: remove the certificate and provisioning profile from the runner!
- name: Clean up keychain and provisioning profile - name: Clean up keychain and provisioning profile

71
.gitignore vendored
View File

@ -1,39 +1,56 @@
filcnaplo/.flutter-plugins refilc/.flutter-plugins
filcnaplo/.flutter-plugins-dependencies refilc/.flutter-plugins-dependencies
filcnaplo/pubspec.lock refilc/pubspec.lock
filcnaplo/.dart_tool/ refilc/.dart_tool/
filcnaplo/android/ # refilc/android/
filcnaplo/ios/ # refilc/ios/
filcnaplo/windows/ # refilc/windows/
filcnaplo/linux/ # refilc/linux/
filcnaplo/macos/ # refilc/macos/
filcnaplo/build/ refilc/build/
refilc/android/key.properties
refilc/android/debug.keystore
filcnaplo_desktop_ui/.flutter-plugins refilc_desktop_ui/.flutter-plugins
filcnaplo_desktop_ui/.flutter-plugins-dependencies refilc_desktop_ui/.flutter-plugins-dependencies
filcnaplo_desktop_ui/pubspec.lock refilc_desktop_ui/pubspec.lock
filcnaplo_desktop_ui/.dart_tool/ refilc_desktop_ui/.dart_tool/
filcnaplo_kreta_api/.flutter-plugins refilc_kreta_api/.flutter-plugins
filcnaplo_kreta_api/.flutter-plugins-dependencies refilc_kreta_api/.flutter-plugins-dependencies
filcnaplo_kreta_api/pubspec.lock refilc_kreta_api/pubspec.lock
filcnaplo_kreta_api/.dart_tool/ refilc_kreta_api/.dart_tool/
filcnaplo_mobile_ui/.flutter-plugins refilc_mobile_ui/.flutter-plugins
filcnaplo_mobile_ui/.flutter-plugins-dependencies refilc_mobile_ui/.flutter-plugins-dependencies
filcnaplo_mobile_ui/pubspec.lock refilc_mobile_ui/pubspec.lock
filcnaplo_mobile_ui/.dart_tool/ refilc_mobile_ui/.dart_tool/
filcnaplo_premium/.flutter-plugins # filcnaplo_premium/.flutter-plugins
filcnaplo_premium/.flutter-plugins-dependencies # filcnaplo_premium/.flutter-plugins-dependencies
filcnaplo_premium/pubspec.lock # filcnaplo_premium/pubspec.lock
filcnaplo_premium/.dart_tool/ # filcnaplo_premium/.dart_tool/
.vscode .vscode
.github .github
.idea .idea
.gitmodules .gitmodules
.gradle
filcnaplo/.DS_Store refilc/.DS_Store
.DS_Store .DS_Store
refilc/linux/flutter/
.plugin_symlinks/
refilc/macos/Flutter/
refilc/ios/Flutter/
refilc/ios/Runner/GeneratedPluginRegistrant.h
refilc/ios/Runner/GeneratedPluginRegistrant.m
refilc/android/local.properties
refilc/android/debugkey.properties
refilc/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java
tool_logs/build/*.log
tool_logs/d8dx_fix/*.log
tool_logs/pub_fix/*.log
refilc_mobile_ui/android/local.properties

2
.gitmodules vendored
View File

@ -1,3 +1,3 @@
[submodule "naplo-plus"] [submodule "naplo-plus"]
path = filcnaplo_premium path = refilc_plus
url = git@github.com:refilc/naplo-plus.git url = git@github.com:refilc/naplo-plus.git

View File

@ -11,8 +11,10 @@
### Clone the project ### Clone the project
<em>A teljes source eléréséhez szükséged lesz a naplo-plus repo-ra is, mely biztonsági okokból privát. Írj Discord szerverünkön, hogy kaphass hozzáférést.</em>
```sh ```sh
git clone https://github.com/refilc/naplo git clone --branch dev https://github.com/refilc/naplo --recursive
cd naplo cd naplo
``` ```
@ -23,8 +25,8 @@ Run `fix-pub.sh`
### Run the app ### Run the app
```sh ```sh
cd filcnaplo cd refilc
flutter run flutter run (--release)
``` ```
### Contribution ### Contribution
@ -47,6 +49,4 @@ Az összes (ugyan azon verzióhoz tartozó) contribution meg fog jelenni a relea
**Péter:** video editor **Péter:** video editor
**annon:** a régi Filc Napló fejlesztője (ez az app, ha bár sokban változott, alapjaiban a Filc-re épül) <em>**annon:** a régi Filc Napló fejlesztője (ez az app, ha bár sokban változott, alapjaiban a Filc-re épül)</em>
<sup>Ez a projekt egy fork; az eredeti projektet megtaláljátok itt: [filc/naplo-archive](https://github.com/filc/naplo-archive) (köszi, annon)</sup>

View File

@ -1,13 +0,0 @@
What's new:
- design tweak
- new premium ui
- premium fix
- rounding fix
- graph percentage fix
- fail warning
- Widget
- fix sent messages
- fix ios live activities
- Hibajavítások 🐛
- **Megérkezett a Filc Premium!**

44
filcnaplo/.gitignore vendored
View File

@ -1,44 +0,0 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
.pub-cache/
.pub/
/build/
# Symbolication related
app.*.symbols
# Obfuscation related
app.*.map.json
# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release

View File

@ -1,5 +0,0 @@
-keep class io.flutter.plugin.editing.** { *; }
-keep class androidx.lifecycle.DefaultLifecycleObserver
-keep class com.pauldemarco.flutter_blue.** { *; }
-keep class com.mr.flutter.plugin.filepicker.** { *; }
-keep class com.shockwave.**

View File

@ -1,7 +0,0 @@
package hu.refilc.naplo;
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends FlutterActivity {
}

View File

@ -1,119 +0,0 @@
package hu.refilc.naplo.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.sql.SQLException;
import hu.refilc.naplo.database.SQLiteHelper;
public class DBManager {
private Context context;
private SQLiteDatabase database;
private SQLiteHelper dbHelper;
public DBManager(Context c) {
this.context = c;
}
public DBManager open() throws SQLException {
this.dbHelper = new SQLiteHelper(this.context);
this.database = this.dbHelper.getWritableDatabase();
return this;
}
public void close() {
this.dbHelper.close();
}
public Cursor fetchWidget(int wid) {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_WIDGETS, new String[]{SQLiteHelper._ID, SQLiteHelper.DAY_SEL}, SQLiteHelper._ID + " = " + wid, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public Cursor fetchTimetable() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_USER_DATA, new String[]{SQLiteHelper.TIMETABLE}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public Cursor fetchLastUser() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_SETTINGS, new String[]{SQLiteHelper.LAST_ACCOUNT_ID}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public Cursor fetchTheme() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_SETTINGS, new String[]{SQLiteHelper.THEME, SQLiteHelper.ACCENT_COLOR}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public Cursor fetchPremiumToken() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_SETTINGS, new String[]{SQLiteHelper.PREMIUM_TOKEN}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public Cursor fetchPremiumScopes() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_SETTINGS, new String[]{SQLiteHelper.PREMIUM_SCOPES}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public Cursor fetchLocale() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_SETTINGS, new String[]{SQLiteHelper.LOCALE}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public void deleteWidget(int _id) {
this.database.delete(SQLiteHelper.TABLE_NAME_WIDGETS, "_id=" + _id, null);
}
/*public void changeSettings(int _id, Map<String, String> map) {
ContentValues con = new ContentValues();
for(Map.Entry<String, String> e: map.entrySet()){
con.put(e.getKey(), e.getValue());
}
this.database.update(SQLiteHelper.TABLE_NAME_WIDGETS, con, "_id = " + _id, null);
}
public void insertSettings(int _id, Map<String, String> map) {
ContentValues con = new ContentValues();
for(Map.Entry<String, String> e: map.entrySet()){
con.put(e.getKey(), e.getValue());
//Log.d("Settings added", e.getKey() + " - " + e.getValue());
}
this.database.insert(SQLiteHelper.TABLE_NAME_WIDGETS, null, con);
}*/
public void insertSelDay(int _id, int day_sel) {
ContentValues con = new ContentValues();
con.put(SQLiteHelper._ID, _id);
con.put(SQLiteHelper.DAY_SEL, day_sel);
this.database.insert(SQLiteHelper.TABLE_NAME_WIDGETS, null, con);
}
public int update(int _id, int day_sel) {
ContentValues con = new ContentValues();
con.put(SQLiteHelper.DAY_SEL, day_sel);
return this.database.update(SQLiteHelper.TABLE_NAME_WIDGETS, con, SQLiteHelper._ID + " = " + _id, null);
}
}

View File

@ -1,36 +0,0 @@
package hu.refilc.naplo.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLiteHelper extends SQLiteOpenHelper {
private static final String CREATE_TABLE_WIDGET = " create table widgets ( _id INTEGER NOT NULL, day_sel INTEGER NOT NULL);";
private static final String DB_NAME = "app.db";
private static final int DB_VERSION = 1;
public static final String _ID = "_id";
public static final String DAY_SEL = "day_sel";
public static final String TIMETABLE = "timetable";
public static final String LAST_ACCOUNT_ID = "last_account_id";
public static final String THEME = "theme";
public static final String PREMIUM_TOKEN = "premium_token";
public static final String PREMIUM_SCOPES = "premium_scopes";
public static final String LOCALE = "language";
public static final String ACCENT_COLOR = "accent_color";
public static final String TABLE_NAME_WIDGETS = "widgets";
public static final String TABLE_NAME_USER_DATA = "user_data";
public static final String TABLE_NAME_SETTINGS = "settings";
public SQLiteHelper(Context context) {
super(context, DB_NAME, null, 7);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_WIDGET);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS widgets");
onCreate(db);
}
}

View File

@ -1,36 +0,0 @@
package hu.refilc.naplo.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.util.Calendar;
import java.util.Date;
public class Utils {
public static boolean hasNetwork(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
public static Date getWeekStartDate() {
Calendar calendar = Calendar.getInstance();
while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
calendar.add(Calendar.DATE, -1);
}
return calendar.getTime();
}
public static Date getWeekEndDate() {
Calendar calendar = Calendar.getInstance();
while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
calendar.add(Calendar.DATE, 1);
}
calendar.add(Calendar.DATE, -1);
return calendar.getTime();
}
}

View File

@ -1,65 +0,0 @@
package hu.refilc.naplo.utils;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDate;
public class Week {
private final LocalDate start;
private final LocalDate end;
private Week(LocalDate start, LocalDate end) {
this.start = start;
this.end = end;
}
public static Week current() {
return fromDate(LocalDate.now());
}
public static Week fromId(int id) {
LocalDate _now = getYearStart().plusDays(id * 7L);
return new Week(_now.minusDays(_now.getDayOfWeek().getValue() - 1), _now.plusDays(7 - _now.getDayOfWeek().getValue()));
}
public static Week fromDate(LocalDate date) {
return new Week(date.minusDays(date.getDayOfWeek().getValue() - 1), date.plusDays(7 - date.getDayOfWeek().getValue()));
}
public Week next() {
return Week.fromDate(start.plusDays(8));
}
public int id() {
return (int) Math.ceil(Duration.between(getYearStart().atStartOfDay(), start.atStartOfDay()).toDays() / 7f);
}
private static LocalDate getYearStart() {
LocalDate now = LocalDate.now();
LocalDate start = getYearStart(now.getYear());
return start.isBefore(now) ? start : getYearStart(now.getYear() -1);
}
private static LocalDate getYearStart(int year) {
LocalDate time = LocalDate.of(year, 9, 1);
if (time.getDayOfWeek() == DayOfWeek.SATURDAY)
return time.plusDays(2);
else if (time.getDayOfWeek() == DayOfWeek.SUNDAY)
return time.plusDays(1);
return time;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Week week = (Week) o;
return this.id() == week.id();
}
@Override
public int hashCode() {
return id();
}
}

View File

@ -1,392 +0,0 @@
package hu.refilc.naplo.widget_timetable;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.time.DayOfWeek;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.HashMap;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import hu.refilc.naplo.database.DBManager;
import hu.refilc.naplo.MainActivity;
import hu.refilc.naplo.R;
import hu.refilc.naplo.utils.Week;
import static android.app.PendingIntent.FLAG_UPDATE_CURRENT;
import es.antonborri.home_widget.HomeWidgetBackgroundIntent;
import es.antonborri.home_widget.HomeWidgetLaunchIntent;
import es.antonborri.home_widget.HomeWidgetProvider;
public class WidgetTimetable extends HomeWidgetProvider {
private static final String ACTION_WIDGET_CLICK_NAV_LEFT = "list_widget.ACTION_WIDGET_CLICK_NAV_LEFT";
private static final String ACTION_WIDGET_CLICK_NAV_RIGHT = "list_widget.ACTION_WIDGET_CLICK_NAV_RIGHT";
private static final String ACTION_WIDGET_CLICK_NAV_TODAY = "list_widget.ACTION_WIDGET_CLICK_NAV_TODAY";
private static final String ACTION_WIDGET_CLICK_NAV_REFRESH = "list_widget.ACTION_WIDGET_CLICK_NAV_REFRESH";
private static final String ACTION_WIDGET_CLICK_BUY_PREMIUM = "list_widget.ACTION_WIDGET_CLICK_BUY_PREMIUM";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, SharedPreferences widgetData) {
for (int i = 0; i < appWidgetIds.length; i++) {
RemoteViews views = generateView(context, appWidgetIds[i]);
if(premiumEnabled(context) && userLoggedIn(context)) {
int rday = selectDay(context, appWidgetIds[i], 0, true);
views.setTextViewText(R.id.nav_current, convertDayOfWeek(context, rday));
}
pushUpdate(context, views, appWidgetIds[i]);
}
}
public static void pushUpdate(Context context, RemoteViews remoteViews, int appWidgetSingleId) {
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(appWidgetSingleId, remoteViews);
manager.notifyAppWidgetViewDataChanged(appWidgetSingleId, R.id.widget_list);
}
public static RemoteViews generateView(Context context, int appId) {
Intent serviceIntent = new Intent(context, WidgetTimetableService.class);
serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appId);
serviceIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_timetable);
views.setViewVisibility(R.id.need_premium, View.GONE);
views.setViewVisibility(R.id.need_login, View.GONE);
views.setViewVisibility(R.id.tt_grid_cont, View.GONE);
if(!userLoggedIn(context)) {
views.setViewVisibility(R.id.need_login, View.VISIBLE);
views.setOnClickPendingIntent(R.id.open_login, makePending(context, ACTION_WIDGET_CLICK_BUY_PREMIUM, appId));
} else if(premiumEnabled(context)) {
views.setViewVisibility(R.id.tt_grid_cont, View.VISIBLE);
views.setOnClickPendingIntent(R.id.nav_to_left, makePending(context, ACTION_WIDGET_CLICK_NAV_LEFT, appId));
views.setOnClickPendingIntent(R.id.nav_to_right, makePending(context, ACTION_WIDGET_CLICK_NAV_RIGHT, appId));
views.setOnClickPendingIntent(R.id.nav_current, makePending(context, ACTION_WIDGET_CLICK_NAV_TODAY, appId));
views.setOnClickPendingIntent(R.id.nav_refresh, makePending(context, ACTION_WIDGET_CLICK_NAV_REFRESH, appId));
views.setRemoteAdapter(R.id.widget_list, serviceIntent);
views.setEmptyView(R.id.widget_list, R.id.empty_view);
} else {
views.setViewVisibility(R.id.need_premium, View.VISIBLE);
views.setOnClickPendingIntent(R.id.buy_premium, makePending(context, ACTION_WIDGET_CLICK_BUY_PREMIUM, appId));
}
return views;
}
static PendingIntent makePending(Context context, String action, int appWidgetId) {
Intent activebtnnext = new Intent(context, WidgetTimetable.class);
activebtnnext.setAction(action);
activebtnnext.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
return PendingIntent.getBroadcast(context, appWidgetId, activebtnnext , PendingIntent.FLAG_IMMUTABLE);
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
int appId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
RemoteViews views = generateView(context, appId);
try {
if(premiumEnabled(context) && userLoggedIn(context)) {
if (intent.getAction().equals(ACTION_WIDGET_CLICK_NAV_LEFT)) {
int rday = selectDay(context, appId, -1, false);
views.setTextViewText(R.id.nav_current, convertDayOfWeek(context, rday));
pushUpdate(context, views, appId);
} else if (intent.getAction().equals(ACTION_WIDGET_CLICK_NAV_RIGHT)) {
int rday = selectDay(context, appId, 1, false);
views.setTextViewText(R.id.nav_current, convertDayOfWeek(context, rday));
pushUpdate(context, views, appId);
} else if (intent.getAction().equals(ACTION_WIDGET_CLICK_NAV_TODAY)) {
int rday = getToday(context);
setSelectedDay(context, appId, rday);
views.setTextViewText(R.id.nav_current, convertDayOfWeek(context, rday));
pushUpdate(context, views, appId);
} else if (intent.getAction().equals(ACTION_WIDGET_CLICK_NAV_REFRESH)) {
PendingIntent pendingIntent = HomeWidgetLaunchIntent.INSTANCE.getActivity(context, MainActivity.class, Uri.parse("timetable://refresh"));
pendingIntent.send();
} else if (intent.getAction().equals("android.appwidget.action.APPWIDGET_DELETED")) {
DBManager dbManager = new DBManager(context.getApplicationContext());
try {
dbManager.open();
dbManager.deleteWidget(appId);
dbManager.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
if(intent.getAction().equals(ACTION_WIDGET_CLICK_BUY_PREMIUM)) {
PendingIntent pendingIntent = HomeWidgetLaunchIntent.INSTANCE.getActivity(context, MainActivity.class, Uri.parse("settings://premium"));
pendingIntent.send();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public static String convertDayOfWeek(Context context, int rday) {
/*if(rday == -1) return DayOfWeek.of(1).getDisplayName(TextStyle.FULL, new Locale("hu", "HU"));
String dayOfWeek = DayOfWeek.of(rday + 1).getDisplayName(TextStyle.FULL, new Locale("hu", "HU"));*/
String dayOfWeek = "Unknown";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Locale loc = getLocale(context);
if (rday == -1)
return DayOfWeek.of(1).getDisplayName(TextStyle.FULL, loc);
dayOfWeek = DayOfWeek.of(rday + 1).getDisplayName(TextStyle.FULL, loc);
}
return dayOfWeek.substring(0, 1).toUpperCase() + dayOfWeek.substring(1).toLowerCase();
}
public static void setSelectedDay(Context context, int wid, int day) {
DBManager dbManager = new DBManager(context.getApplicationContext());
try {
dbManager.open();
dbManager.update(wid, day);
dbManager.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static int getToday(Context context) {
int rday = new DateTime().getDayOfWeek() - 1;
List<JSONArray> s = genJsonDays(context);
try {
if(checkIsAfter(s, rday)) rday += 1;
} catch (Exception e) {
e.printStackTrace();
}
return retDay(rday, s.size());
}
public static int selectDay(Context context, int wid, int add, Boolean afterSubjects) {
DBManager dbManager = new DBManager(context.getApplicationContext());
try {
dbManager.open();
Cursor cursor = dbManager.fetchWidget(wid);
List<JSONArray> s = genJsonDays(context);
int retday = new DateTime().getDayOfWeek() - 1;
if(cursor.getCount() != 0) retday = retDay(cursor.getInt(1) + add, s.size());
if(afterSubjects) if(checkIsAfter(s, retday)) retday += 1;
retday = retDay(retday, s.size());
if(cursor.getCount() == 0) dbManager.insertSelDay(wid, retday);
else dbManager.update(wid, retday);
dbManager.close();
return retday;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public static Boolean checkIsAfter(List<JSONArray> s, int retday) throws Exception {
retday = retDay(retday, s.size());
String vegIdopont = s.get(retday).getJSONObject(s.get(retday).length() - 1).getString("VegIdopont");
return new DateTime().isAfter(new DateTime(vegIdopont));
}
public static int retDay(int retday, int size) {
if (retday < 0) retday = size - 1;
else if (retday > size - 1) retday = 0;
return retday;
}
public static List<JSONArray> genJsonDays(Context context) {
List<JSONArray> genDays = new ArrayList<>();
Map<String, JSONArray> dayMap = new HashMap<>();
DBManager dbManager = new DBManager(context.getApplicationContext());
try {
dbManager.open();
Cursor ct = dbManager.fetchTimetable();
if (ct.getCount() == 0) {
return genDays;
}
JSONObject fetchedTimetable = new JSONObject(ct.getString(0));
String currentWeek = String.valueOf(Week.current().id());
JSONArray week = fetchedTimetable.getJSONArray(currentWeek);
// Organize lessons into dates
for (int i = 0; i < week.length(); i++) {
try {
JSONObject entry = week.getJSONObject(i);
String date = entry.getString("Datum");
dayMap.computeIfAbsent(date, k -> new JSONArray()).put(entry);
} catch (JSONException e) {
e.printStackTrace();
}
}
genDays.addAll(dayMap.values());
// Sort the 'genDays' list of JSON based on the start time of the first entry
genDays.sort((day1, day2) -> {
try {
// Extract the start time of the first entry in each day's JSON
String startTime1 = day1.getJSONObject(0).getString("KezdetIdopont");
String startTime2 = day2.getJSONObject(0).getString("KezdetIdopont");
// Compare the start times and return the result for sorting
return startTime1.compareTo(startTime2);
} catch (JSONException e) {
e.printStackTrace();
return 0;
}
});
} catch (Exception e) {
e.printStackTrace();
} finally {
dbManager.close();
}
return genDays;
}
public static String zeroPad(int value, int padding){
StringBuilder b = new StringBuilder();
b.append(value);
while(b.length() < padding){
b.insert(0,"0");
}
return b.toString();
}
public static Locale getLocale(Context context) {
DBManager dbManager = new DBManager(context.getApplicationContext());
try {
dbManager.open();
String loc = dbManager.fetchLocale().getString(0);
dbManager.close();
if(loc.equals("hu") || loc.equals("de")) {
return new Locale(loc, loc.toUpperCase());
}
} catch (Exception e) {
e.printStackTrace();
}
return new Locale("en", "GB");
}
public static boolean premiumEnabled(Context context) {
DBManager dbManager = new DBManager(context.getApplicationContext());
try {
dbManager.open();
String premium_token = dbManager.fetchPremiumToken().getString(0);
String premium_scopes_raw = dbManager.fetchPremiumScopes().getString(0);
dbManager.close();
JSONArray arr = new JSONArray(premium_scopes_raw);
List<String> premium_scopes = new ArrayList<>();
for(int i = 0; i < arr.length(); i++){
String scope = arr.getString(i);
premium_scopes.add(scope.substring(scope.lastIndexOf('.') + 1));
}
if(!premium_token.equals("") && (premium_scopes.contains("*") || premium_scopes.contains("TIMETALBE_WIDGET"))) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean userLoggedIn(Context context) {
return !lastUserId(context).equals("");
}
public static String lastUserId(Context context) {
DBManager dbManager = new DBManager(context.getApplicationContext());
try {
dbManager.open();
Cursor cursor = dbManager.fetchLastUser();
dbManager.close();
if(cursor != null && !cursor.getString(0).equals("")) {
String last_user = cursor.getString(0);
return last_user;
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
@Override
public void onEnabled(Context context) {
}
@Override
public void onDisabled(Context context) {
}
}

View File

@ -1,356 +0,0 @@
package hu.refilc.naplo.widget_timetable;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import hu.refilc.naplo.database.DBManager;
import hu.refilc.naplo.R;
public class WidgetTimetableDataProvider implements RemoteViewsService.RemoteViewsFactory {
private Context context;
private int appWidgetId;
private int rday = 0;
private int theme;
private Integer[] colorValues;
List<Lesson> day_subjects = new ArrayList<>();
List<Integer> lessonIndexes = new ArrayList<>();
Item witem;
/* Default values */
static class Item {
int Layout;
int NumVisibility;
int NameVisibility;
int NameNodescVisibility;
int DescVisibility;
int RoomVisibility;
int TimeVisibility;
int NumColor;
int NameColor;
int NameNodescColor;
int DescColor;
Integer[] NameNodescPadding = {0, 0, 0, 0};
public Item(int Layout, int NumVisibility,int NameVisibility,int NameNodescVisibility,int DescVisibility,int RoomVisibility,int TimeVisibility,int NumColor,int NameColor,int NameNodescColor,int DescColor) {
this.Layout = Layout;
this.NumVisibility = NumVisibility;
this.NameVisibility = NameVisibility;
this.NameNodescVisibility = NameNodescVisibility;
this.DescVisibility = DescVisibility;
this.RoomVisibility = RoomVisibility;
this.TimeVisibility = TimeVisibility;
this.NumColor = NumColor;
this.NameColor = NameColor;
this.NameNodescColor = NameNodescColor;
this.DescColor = DescColor;
}
}
static class Lesson {
String status;
String lessonIndex;
String lessonName;
String lessonTopic;
String lessonRoom;
long lessonStart;
long lessonEnd;
String substituteTeacher;
public Lesson(String status, String lessonIndex,String lessonName,String lessonTopic, String lessonRoom,long lessonStart,long lessonEnd,String substituteTeacher) {
this.status = status;
this.lessonIndex = lessonIndex;
this.lessonName = lessonName;
this.lessonTopic = lessonTopic;
this.lessonRoom = lessonRoom;
this.lessonStart = lessonStart;
this.lessonEnd = lessonEnd;
this.substituteTeacher = substituteTeacher;
}
}
Integer[] itemNameNodescPadding = {0, 0, 0, 0};
public WidgetTimetableDataProvider(Context context, Intent intent) {
this.context = context;
this.appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
this.theme = getThemeAccent(context);
this.colorValues = new Integer[]{R.color.filc,
R.color.blue_shade300,
R.color.green_shade300,
R.color.lime_shade300,
R.color.yellow_shade300,
R.color.orange_shade300,
R.color.red_shade300,
R.color.pink_shade300,
R.color.purple_shade300};
}
@Override
public void onCreate() {
initData();
}
@Override
public void onDataSetChanged() {
initData();
}
@Override
public void onDestroy() {
}
@Override
public int getCount() {
return day_subjects.size();
}
public void setLayout(final RemoteViews view) {
/* Visibilities */
view.setViewVisibility(R.id.tt_item_num, witem.NumVisibility);
view.setViewVisibility(R.id.tt_item_name, witem.NameVisibility);
view.setViewVisibility(R.id.tt_item_name_nodesc, witem.NameNodescVisibility);
view.setViewVisibility(R.id.tt_item_desc, witem.DescVisibility);
view.setViewVisibility(R.id.tt_item_room, witem.RoomVisibility);
view.setViewVisibility(R.id.tt_item_time, witem.TimeVisibility);
/* backgroundResources */
view.setInt(R.id.main_lay, "setBackgroundResource", witem.Layout);
/* Paddings */
view.setViewPadding(R.id.tt_item_name_nodesc, witem.NameNodescPadding[0], witem.NameNodescPadding[1], witem.NameNodescPadding[2], witem.NameNodescPadding[3]);
/* Text Colors */
view.setInt(R.id.tt_item_num, "setTextColor", getColor(context, witem.NumColor));
view.setInt(R.id.tt_item_name, "setTextColor", getColor(context, witem.NameColor));
view.setInt(R.id.tt_item_name_nodesc, "setTextColor", getColor(context, witem.NameNodescColor));
view.setInt(R.id.tt_item_desc, "setTextColor", getColor(context, witem.DescColor));
}
public int getColor(Context context, int color) {
return context.getResources().getColor(color);
}
@Override
public RemoteViews getViewAt(int position) {
RemoteViews view = new RemoteViews(context.getPackageName(), R.layout.timetable_item);
witem = defaultItem(theme);
Lesson curr_subject = day_subjects.get(position);
if (curr_subject.status.equals("empty")) {
witem.NumColor = R.color.text_miss_num;
witem.TimeVisibility = View.GONE;
witem.RoomVisibility = View.GONE;
witem.NameNodescColor = R.color.text_miss;
}
if (!curr_subject.substituteTeacher.equals("null")) {
witem.NumColor = R.color.yellow;
witem.Layout = R.drawable.card_layout_tile_helyetesitett;
}
if (curr_subject.status.equals("Elmaradt")) {
witem.NumColor = R.color.red;
witem.Layout = R.drawable.card_layout_tile_elmarad;
} else if (curr_subject.status.equals("TanevRendjeEsemeny")) {
witem.NumVisibility = View.GONE;
witem.TimeVisibility = View.GONE;
witem.RoomVisibility = View.GONE;
witem.NameNodescPadding[0] = 50;
witem.NameNodescPadding[2] = 50;
witem.NameNodescColor = R.color.text_miss;
}
if (curr_subject.lessonTopic.equals("null")) {
witem.DescVisibility = View.GONE;
witem.NameVisibility = View.GONE;
witem.NameNodescVisibility = View.VISIBLE;
}
setLayout(view);
String lessonIndexTrailing = curr_subject.lessonIndex.equals("+") ? "" : ".";
view.setTextViewText(R.id.tt_item_num, curr_subject.lessonIndex + lessonIndexTrailing);
view.setTextViewText(R.id.tt_item_name, curr_subject.lessonName);
view.setTextViewText(R.id.tt_item_name_nodesc, curr_subject.lessonName);
view.setTextViewText(R.id.tt_item_desc, curr_subject.lessonTopic);
view.setTextViewText(R.id.tt_item_room, curr_subject.lessonRoom);
if(curr_subject.lessonStart != 0 && curr_subject.lessonEnd != 0)
view.setTextViewText(R.id.tt_item_time, WidgetTimetable.zeroPad(new DateTime(curr_subject.lessonStart).getHourOfDay(), 2) + ":" + WidgetTimetable.zeroPad(new DateTime(curr_subject.lessonStart).getMinuteOfHour(), 2) +
"\n" + WidgetTimetable.zeroPad(new DateTime(curr_subject.lessonEnd).getHourOfDay(), 2) + ":" + WidgetTimetable.zeroPad(new DateTime(curr_subject.lessonEnd).getMinuteOfHour(),2));
return view;
}
@Override
public RemoteViews getLoadingView() {
return null;
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public boolean hasStableIds() {
return true;
}
private void initData() {
theme = getThemeAccent(context);
rday = WidgetTimetable.selectDay(context, appWidgetId, 0, false);
day_subjects.clear();
lessonIndexes.clear();
try {
List<JSONArray> arr = WidgetTimetable.genJsonDays(context);
if(arr.isEmpty()) {
return;
}
JSONArray arr_lessons = WidgetTimetable.genJsonDays(context).get(rday);
for (int i = 0; i < arr_lessons.length(); i++) {
JSONObject obj_lessons = arr_lessons.getJSONObject(i);
day_subjects.add(jsonToLesson(obj_lessons));
}
} catch (JSONException e) {
e.printStackTrace();
}
if(day_subjects.size() > 0) {
Collections.sort(day_subjects, new Comparator<Lesson>() {
public int compare(Lesson o1, Lesson o2) {
return new DateTime(o1.lessonStart).compareTo(new DateTime(o2.lessonStart));
}
});
for (int i = 0; i < day_subjects.size(); i++) {
if(!day_subjects.get(i).lessonIndex.equals("+")) {
lessonIndexes.add(Integer.valueOf(day_subjects.get(i).lessonIndex));
}
}
if(lessonIndexes.size() > 0) {
int lessonsChecked = Collections.min(lessonIndexes);
int i = 0;
while(lessonsChecked < Collections.max(lessonIndexes)) {
if(!lessonIndexes.contains(lessonsChecked)) {
day_subjects.add(i, emptyLesson(lessonsChecked));
}
lessonsChecked++;
i++;
}
}
}
}
public static Integer getThemeAccent(Context context) {
DBManager dbManager = new DBManager(context.getApplicationContext());
try {
dbManager.open();
Cursor cursor = dbManager.fetchTheme();
dbManager.close();
return cursor.getInt(1);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public Item defaultItem(int theme) {
return new Item(
R.drawable.card_layout_tile,
View.VISIBLE,
View.VISIBLE,
View.INVISIBLE,
View.VISIBLE,
View.VISIBLE,
View.VISIBLE,
colorValues[theme >= colorValues.length ? 0 : theme],
R.color.text,
R.color.text,
R.color.text_desc
);
}
public Lesson emptyLesson(int lessonIndex) {
return new Lesson("empty", String.valueOf(lessonIndex), "Lyukasóra", "null", "null", 0, 0, "null");
}
public Lesson jsonToLesson(JSONObject json) {
try {
String name = json.getString("Nev");
name = name.substring(0, 1).toUpperCase() + name.substring(1); // Capitalize name
return new Lesson(
json.getJSONObject("Allapot").getString("Nev"),
!json.getString("Oraszam").equals("null") ? json.getString("Oraszam") : "+",
name,
json.getString("Tema"),
json.getString("TeremNeve"),
new DateTime(json.getString("KezdetIdopont")).getMillis(),
new DateTime(json.getString("VegIdopont")).getMillis(),
json.getString("HelyettesTanarNeve")
);
}catch (Exception e) {
Log.d("Filc", "exception: " + e);
};
return null;
}
}

View File

@ -1,12 +0,0 @@
package hu.refilc.naplo.widget_timetable;
import android.content.Intent;
import android.os.Build;
import android.widget.RemoteViewsService;
public class WidgetTimetableService extends RemoteViewsService {
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return new WidgetTimetableDataProvider(getApplicationContext(), intent);
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

View File

@ -1,11 +0,0 @@
include ':app'
def localPropertiesFile = new File(rootProject.projectDir, "local.properties")
def properties = new Properties()
assert localPropertiesFile.exists()
localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }
def flutterSdkPath = properties.getProperty("flutter.sdk")
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 735 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 145 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 133 KiB

View File

@ -1,25 +0,0 @@
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
// here, Without this code the task will not work.
//SwiftFlutterForegroundTaskPlugin.setPluginRegistrantCallback(registerPlugins)
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
// here
func registerPlugins(registry: FlutterPluginRegistry) {
GeneratedPluginRegistrant.register(with: registry)
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

View File

@ -1,31 +0,0 @@
import Foundation
class LessonData {
var color: String
var icon: String
var index: String
var title: String
var subtitle: String
var description: String
var startDate: Date
var endDate: Date
var date: ClosedRange<Date>
var nextSubject: String
var nextRoom: String
init?() {
let sharedDefault = UserDefaults(suiteName: "group.refilc2.livecard")!
self.color = sharedDefault.string(forKey: "color")!
self.icon = sharedDefault.string(forKey: "icon")!
self.index = sharedDefault.string(forKey: "index")!
self.title = sharedDefault.string(forKey: "title")!
self.subtitle = sharedDefault.string(forKey: "subtitle")!
self.description = sharedDefault.string(forKey: "description")!
self.startDate = Date(timeIntervalSince1970: Double(sharedDefault.string(forKey: "startDate")!)! / 1000)
self.endDate = Date(timeIntervalSince1970: Double(sharedDefault.string(forKey: "endDate")!)! / 1000)
date = self.startDate...self.endDate
self.nextSubject = sharedDefault.string(forKey: "nextSubject")!
self.nextRoom = sharedDefault.string(forKey: "nextRoom")!
}
}

View File

@ -1,205 +0,0 @@
import ActivityKit
import WidgetKit
import SwiftUI
@main
struct Widgets: WidgetBundle {
var body: some Widget {
if #available(iOS 16.1, *) {
LiveCardWidget()
}
}
}
// Color Converter
extension Color {
init(hex: String, alpha: Double = 1.0) {
var hexValue = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if hexValue.hasPrefix("#") {
hexValue.remove(at: hexValue.startIndex)
}
var rgbValue: UInt64 = 0
Scanner(string: hexValue).scanHexInt64(&rgbValue)
let red = Double((rgbValue & 0xFF0000) >> 16) / 255.0
let green = Double((rgbValue & 0x00FF00) >> 8) / 255.0
let blue = Double(rgbValue & 0x0000FF) / 255.0
self.init(
.sRGB,
red: red,
green: green,
blue: blue,
opacity: alpha
)
}
}
// We need to redefined live activities pipe
struct LiveActivitiesAppAttributes: ActivityAttributes, Identifiable {
public struct ContentState: Codable, Hashable { }
var id = UUID()
}
struct LockScreenLiveActivityView: View {
let context: ActivityViewContext<LiveActivitiesAppAttributes>
let lesson = LessonData()
var body: some View {
HStack(alignment: .center) {
Image(systemName: lesson!.icon)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: CGFloat(30), height: CGFloat(30))
.padding(.leading, CGFloat(24))
VStack(alignment: .leading) {
HStack(alignment: .center) {
Text(lesson!.index + lesson!.title)
.font(.title3)
.bold()
Text(lesson!.subtitle)
.font(.subheadline)
.padding(.trailing, 12)
}
if (lesson!.description != "") {
Text(lesson!.description)
.font(.subheadline)
}
HStack {
Image(systemName: "arrow.right")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: CGFloat(8), height: CGFloat(8))
Text(lesson!.nextSubject)
.font(.caption)
Text(lesson!.nextRoom)
.font(.caption2)
}
}.padding(15)
Spacer()
Text(timerInterval: lesson!.date, countsDown: true)
.multilineTextAlignment(.center)
.frame(width: 85)
.font(.title2)
.monospacedDigit()
.padding(.trailing, CGFloat(24))
}
.activityBackgroundTint(
lesson!.color != "#676767"
? Color(hex: lesson!.color)
// Ha nem megy hat nem megy
: Color.clear
)
}
}
@available(iOSApplicationExtension 16.1, *)
struct LiveCardWidget: Widget {
var body: some WidgetConfiguration {
/// Live Activity Notification
ActivityConfiguration(for: LiveActivitiesAppAttributes.self) { context in
LockScreenLiveActivityView(context: context)
/// Dynamic Island
} dynamicIsland: { context in
let lesson = LessonData()
/// Expanded
return DynamicIsland {
DynamicIslandExpandedRegion(.leading) {
VStack {
Spacer()
ProgressView(
timerInterval: lesson!.date,
countsDown: true,
label: {
Image(systemName: lesson!.icon)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: CGFloat(32), height: CGFloat(32))
},
currentValueLabel: {
Image(systemName: lesson!.icon)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: CGFloat(32), height: CGFloat(32))
}
).progressViewStyle(.circular)
}
}
DynamicIslandExpandedRegion(.center) {
VStack(alignment: .leading) {
Text(lesson!.index + lesson!.title)
.lineLimit(1)
.font(.title3)
.bold()
Text(lesson!.description)
.lineLimit(2)
.font(.caption)
}.padding(EdgeInsets(top: 0.0, leading: 5.0, bottom: 0.0, trailing: 0.0))
}
DynamicIslandExpandedRegion(.trailing) {
VStack {
Spacer()
Text(lesson!.subtitle)
.lineLimit(1)
.font(.subheadline)
Spacer()
}
}
/// Compact
} compactLeading: {
Label {
Text(lesson!.title)
} icon: {
Image(systemName: lesson!.icon)
}
.font(.caption2)
}
compactTrailing: {
Text(timerInterval: lesson!.date, countsDown: true)
.multilineTextAlignment(.center)
.frame(width: 40)
.font(.caption2)
/// Collapsed
} minimal: {
VStack(alignment: .center, content: {
ProgressView(
timerInterval: lesson!.date,
countsDown: true,
label: {
Image(systemName: lesson!.icon)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: CGFloat(12), height: CGFloat(12))
},
currentValueLabel: {
Image(systemName: lesson!.icon)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: CGFloat(12), height: CGFloat(12))
}
).progressViewStyle(.circular)
})
}
.keylineTint(
lesson!.color != "#676767"
? Color(hex: lesson!.color)
: Color.clear
)
}
}
}

View File

@ -1,191 +0,0 @@
// ignore_for_file: avoid_print, use_build_context_synchronously
import 'package:filcnaplo/utils/jwt.dart';
import 'package:filcnaplo_kreta_api/models/school.dart';
import 'package:filcnaplo_kreta_api/providers/absence_provider.dart';
import 'package:filcnaplo_kreta_api/providers/event_provider.dart';
import 'package:filcnaplo_kreta_api/providers/exam_provider.dart';
import 'package:filcnaplo_kreta_api/providers/grade_provider.dart';
import 'package:filcnaplo_kreta_api/providers/homework_provider.dart';
import 'package:filcnaplo_kreta_api/providers/message_provider.dart';
import 'package:filcnaplo_kreta_api/providers/note_provider.dart';
import 'package:filcnaplo_kreta_api/providers/timetable_provider.dart';
import 'package:filcnaplo/api/providers/user_provider.dart';
import 'package:filcnaplo/api/providers/database_provider.dart';
import 'package:filcnaplo/models/settings.dart';
import 'package:filcnaplo/models/user.dart';
import 'package:filcnaplo_kreta_api/client/api.dart';
import 'package:filcnaplo_kreta_api/client/client.dart';
import 'package:filcnaplo_kreta_api/models/student.dart';
import 'package:filcnaplo_kreta_api/models/week.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:filcnaplo/api/nonce.dart';
import 'package:uuid/uuid.dart';
enum LoginState {
missingFields,
invalidGrant,
failed,
normal,
inProgress,
success,
}
Nonce getNonce(String nonce, String username, String instituteCode) {
Nonce nonceEncoder = Nonce(
key: [98, 97, 83, 115, 120, 79, 119, 108, 85, 49, 106, 77], nonce: nonce);
nonceEncoder
.encode(instituteCode.toUpperCase() + nonce + username.toUpperCase());
return nonceEncoder;
}
Future loginAPI({
required String username,
required String password,
required String instituteCode,
required BuildContext context,
void Function(User)? onLogin,
void Function()? onSuccess,
}) async {
Future testLogin(School school) async {
var user = User(
username: username,
password: password,
instituteCode: instituteCode,
name: 'Teszt Lajos',
student: Student(
birth: DateTime.now(),
id: const Uuid().v4(),
name: 'Teszt Lajos',
school: school,
yearId: '1',
parents: ['Teszt András', 'Teszt Linda'],
json: {"a": "b"},
address: '1117 Budapest, Gábor Dénes utca 4.',
),
role: Role.parent,
);
if (onLogin != null) onLogin(user);
// store test user in db
await Provider.of<DatabaseProvider>(context, listen: false)
.store
.storeUser(user);
Provider.of<UserProvider>(context, listen: false).addUser(user);
Provider.of<UserProvider>(context, listen: false).setUser(user.id);
if (onSuccess != null) onSuccess();
return LoginState.success;
}
// if institute matches one of test things do test login
if (instituteCode == 'refilc-test-sweden') {
School school = School(
city: "Stockholm",
instituteCode: "refilc-test-sweden",
name: "reFilc Test SE - Leo Ekström High School",
);
await testLogin(school);
} else if (instituteCode == 'refilc-test-spain') {
School school = School(
city: "Madrid",
instituteCode: "refilc-test-spain",
name: "reFilc Test ES - Emilio Obrero University",
);
await testLogin(school);
} else {
// normal login from here
Provider.of<KretaClient>(context, listen: false).userAgent =
Provider.of<SettingsProvider>(context, listen: false).config.userAgent;
Map<String, String> headers = {
"content-type": "application/x-www-form-urlencoded",
};
String nonceStr = await Provider.of<KretaClient>(context, listen: false)
.getAPI(KretaAPI.nonce, json: false);
Nonce nonce = getNonce(nonceStr, username, instituteCode);
headers.addAll(nonce.header());
Map? res = await Provider.of<KretaClient>(context, listen: false)
.postAPI(KretaAPI.login,
headers: headers,
body: User.loginBody(
username: username,
password: password,
instituteCode: instituteCode,
));
if (res != null) {
if (res.containsKey("error")) {
if (res["error"] == "invalid_grant") {
return LoginState.invalidGrant;
}
} else {
if (res.containsKey("access_token")) {
try {
Provider.of<KretaClient>(context, listen: false).accessToken =
res["access_token"];
Map? studentJson =
await Provider.of<KretaClient>(context, listen: false)
.getAPI(KretaAPI.student(instituteCode));
Student student = Student.fromJson(studentJson!);
var user = User(
username: username,
password: password,
instituteCode: instituteCode,
name: student.name,
student: student,
role: JwtUtils.getRoleFromJWT(res["access_token"])!,
);
if (onLogin != null) onLogin(user);
// Store User in the database
await Provider.of<DatabaseProvider>(context, listen: false)
.store
.storeUser(user);
Provider.of<UserProvider>(context, listen: false).addUser(user);
Provider.of<UserProvider>(context, listen: false).setUser(user.id);
// Get user data
try {
await Future.wait([
Provider.of<GradeProvider>(context, listen: false).fetch(),
Provider.of<TimetableProvider>(context, listen: false)
.fetch(week: Week.current()),
Provider.of<ExamProvider>(context, listen: false).fetch(),
Provider.of<HomeworkProvider>(context, listen: false).fetch(),
Provider.of<MessageProvider>(context, listen: false).fetchAll(),
Provider.of<MessageProvider>(context, listen: false)
.fetchAllRecipients(),
Provider.of<NoteProvider>(context, listen: false).fetch(),
Provider.of<EventProvider>(context, listen: false).fetch(),
Provider.of<AbsenceProvider>(context, listen: false).fetch(),
]);
} catch (error) {
print("WARNING: failed to fetch user data: $error");
}
if (onSuccess != null) onSuccess();
return LoginState.success;
} catch (error) {
print("ERROR: loginAPI: $error");
// maybe check debug mode
// ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("ERROR: $error")));
return LoginState.failed;
}
}
}
}
}
return LoginState.failed;
}

View File

@ -1,294 +0,0 @@
// ignore_for_file: no_leading_underscores_for_local_identifiers
import 'dart:async';
import 'dart:io';
import 'package:filcnaplo/helpers/subject.dart';
import 'package:filcnaplo/models/settings.dart';
import 'package:filcnaplo_kreta_api/models/lesson.dart';
import 'package:filcnaplo_kreta_api/models/week.dart';
import 'package:filcnaplo/utils/format.dart';
import 'package:filcnaplo_kreta_api/providers/timetable_provider.dart';
import 'package:flutter/foundation.dart';
import 'package:live_activities/live_activities.dart';
import 'package:filcnaplo_mobile_ui/pages/home/live_card/live_card.i18n.dart';
enum LiveCardState {
empty,
duringLesson,
duringBreak,
morning,
afternoon,
night,
summary
}
class LiveCardProvider extends ChangeNotifier {
Lesson? currentLesson;
Lesson? nextLesson;
Lesson? prevLesson;
List<Lesson>? nextLessons;
LiveCardState currentState = LiveCardState.empty;
late Timer _timer;
late final TimetableProvider _timetable;
late final SettingsProvider _settings;
late Duration _delay;
final _liveActivitiesPlugin = LiveActivities();
String? _latestActivityId;
Map<String, String> _lastActivity = {};
bool _hasCheckedTimetable = false;
LiveCardProvider({
required TimetableProvider timetable,
required SettingsProvider settings,
}) : _timetable = timetable,
_settings = settings {
if (Platform.isIOS) {
_liveActivitiesPlugin.areActivitiesEnabled().then((value) {
// Console log
if (kDebugMode) {
print("iOS LiveActivity enabled: $value");
}
if (value) {
_liveActivitiesPlugin.init(appGroupId: "group.refilc2.livecard");
_liveActivitiesPlugin.getAllActivitiesIds().then((value) {
_latestActivityId = value.isNotEmpty ? value.first : null;
});
}
});
}
_timer = Timer.periodic(const Duration(seconds: 1), (timer) => update());
_delay = settings.bellDelayEnabled
? Duration(seconds: settings.bellDelay)
: Duration.zero;
update();
}
@override
void dispose() {
_timer.cancel();
if (Platform.isIOS) {
_liveActivitiesPlugin.areActivitiesEnabled().then((value) {
if (value) {
if (_latestActivityId != null) {
_liveActivitiesPlugin.endActivity(_latestActivityId!);
}
}
});
}
super.dispose();
}
// Debugging
static DateTime _now() {
// return DateTime(2023, 9, 27, 9, 30);
return DateTime.now();
}
String getFloorDifference() {
final prevFloor = prevLesson!.getFloor();
final nextFloor = nextLesson!.getFloor();
if (prevFloor == null || nextFloor == null || prevFloor == nextFloor) {
return "to room";
}
if (nextFloor == 0) {
return "ground floor";
}
if (nextFloor > prevFloor) {
return "up floor";
} else {
return "down floor";
}
}
Map<String, String> toMap() {
switch (currentState) {
case LiveCardState.duringLesson:
return {
"color":
'#${_settings.liveActivityColor.toString().substring(10, 16)}',
"icon": currentLesson != null
? SubjectIcon.resolveName(subject: currentLesson?.subject)
: "book",
"index":
currentLesson != null ? '${currentLesson!.lessonIndex}. ' : "",
"title": currentLesson != null
? currentLesson?.subject.renamedTo ?? ShortSubject.resolve(subject: currentLesson?.subject).capital()
: "",
"subtitle": currentLesson?.room.replaceAll("_", " ") ?? "",
"description": currentLesson?.description ?? "",
"startDate": ((currentLesson?.start.millisecondsSinceEpoch ?? 0) -
_delay.inMilliseconds)
.toString(),
"endDate": ((currentLesson?.end.millisecondsSinceEpoch ?? 0) -
_delay.inMilliseconds)
.toString(),
"nextSubject": nextLesson != null
? nextLesson?.subject.renamedTo ?? ShortSubject.resolve(subject: nextLesson?.subject).capital()
: "",
"nextRoom": nextLesson?.room.replaceAll("_", " ") ?? "",
};
case LiveCardState.duringBreak:
final iconFloorMap = {
"to room": "chevron.right.2",
"up floor": "arrow.up.right",
"down floor": "arrow.down.left",
"ground floor": "arrow.down.left",
};
final diff = getFloorDifference();
return {
"color":
'#${_settings.liveActivityColor.toString().substring(10, 16)}',
"icon": iconFloorMap[diff] ?? "cup.and.saucer",
"title": "Szünet",
"description": "go $diff".i18n.fill([
diff != "to room" ? (nextLesson!.getFloor() ?? 0) : nextLesson!.room
]),
"startDate": ((prevLesson?.end.millisecondsSinceEpoch ?? 0) -
_delay.inMilliseconds)
.toString(),
"endDate": ((nextLesson?.start.millisecondsSinceEpoch ?? 0) -
_delay.inMilliseconds)
.toString(),
"nextSubject": (nextLesson != null
? nextLesson?.subject.renamedTo ?? ShortSubject.resolve(subject: nextLesson?.subject).capital()
: "")
.capital(),
"nextRoom": nextLesson?.room.replaceAll("_", " ") ?? "",
"index": "",
"subtitle": "",
};
default:
return {};
}
}
void update() async {
if (Platform.isIOS) {
_liveActivitiesPlugin.areActivitiesEnabled().then((value) {
if (value) {
final cmap = toMap();
if (!mapEquals(cmap, _lastActivity)) {
_lastActivity = cmap;
try {
if (_lastActivity.isNotEmpty) {
if (_latestActivityId == null) {
_liveActivitiesPlugin
.createActivity(_lastActivity)
.then((value) => _latestActivityId = value);
} else {
_liveActivitiesPlugin.updateActivity(
_latestActivityId!, _lastActivity);
}
} else {
if (_latestActivityId != null) {
_liveActivitiesPlugin.endActivity(_latestActivityId!);
}
}
} catch (e) {
if (kDebugMode) {
print('ERROR: Unable to create or update iOS LiveActivity!');
}
}
}
}
});
}
List<Lesson> today = _today(_timetable);
if (today.isEmpty && !_hasCheckedTimetable) {
_hasCheckedTimetable = true;
await _timetable.fetch(week: Week.current());
today = _today(_timetable);
}
_delay = _settings.bellDelayEnabled
? Duration(seconds: _settings.bellDelay)
: Duration.zero;
final now = _now().add(_delay);
// Filter cancelled lessons #20
// Filter label lessons #128
today = today
.where((lesson) =>
lesson.status?.name != "Elmaradt" &&
lesson.subject.id != '' &&
!lesson.isEmpty)
.toList();
if (today.isNotEmpty) {
// sort
today.sort((a, b) => a.start.compareTo(b.start));
final _lesson = today.firstWhere(
(l) => l.start.isBefore(now) && l.end.isAfter(now),
orElse: () => Lesson.fromJson({}));
if (_lesson.start.year != 0) {
currentLesson = _lesson;
} else {
currentLesson = null;
}
final _next = today.firstWhere((l) => l.start.isAfter(now),
orElse: () => Lesson.fromJson({}));
nextLessons = today.where((l) => l.start.isAfter(now)).toList();
if (_next.start.year != 0) {
nextLesson = _next;
} else {
nextLesson = null;
}
final _prev = today.lastWhere((l) => l.end.isBefore(now),
orElse: () => Lesson.fromJson({}));
if (_prev.start.year != 0) {
prevLesson = _prev;
} else {
prevLesson = null;
}
}
if (now.isBefore(DateTime(now.year, DateTime.august, 31)) &&
now.isAfter(DateTime(now.year, DateTime.june, 14))) {
currentState = LiveCardState.summary;
} else if (currentLesson != null) {
currentState = LiveCardState.duringLesson;
} else if (nextLesson != null && prevLesson != null) {
currentState = LiveCardState.duringBreak;
} else if (now.hour >= 12 && now.hour < 20) {
currentState = LiveCardState.afternoon;
} else if (now.hour >= 20) {
currentState = LiveCardState.night;
} else if (now.hour >= 5 && now.hour <= 10) {
currentState = LiveCardState.morning;
} else {
currentState = LiveCardState.empty;
}
notifyListeners();
}
bool get show => currentState != LiveCardState.empty;
Duration get delay => _delay;
bool _sameDate(DateTime a, DateTime b) =>
(a.year == b.year && a.month == b.month && a.day == b.day);
List<Lesson> _today(TimetableProvider p) => (p.getWeek(Week.current()) ?? [])
.where((l) => _sameDate(l.date, _now()))
.toList();
}

View File

@ -1,601 +0,0 @@
import 'package:filcnaplo/api/providers/database_provider.dart';
import 'package:filcnaplo/api/providers/status_provider.dart';
import 'package:filcnaplo/api/providers/user_provider.dart';
import 'package:filcnaplo/models/settings.dart';
import 'package:filcnaplo/helpers/notification_helper.i18n.dart';
import 'package:filcnaplo_kreta_api/client/api.dart';
import 'package:filcnaplo_kreta_api/client/client.dart';
import 'package:filcnaplo_kreta_api/models/absence.dart';
import 'package:filcnaplo_kreta_api/models/grade.dart';
import 'package:filcnaplo_kreta_api/models/lesson.dart';
import 'package:filcnaplo_kreta_api/models/week.dart';
import 'package:filcnaplo_kreta_api/providers/grade_provider.dart';
import 'package:filcnaplo_kreta_api/providers/timetable_provider.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart'
hide Message;
import 'package:i18n_extension/i18n_widget.dart';
import 'package:intl/intl.dart';
import 'package:filcnaplo_kreta_api/models/message.dart';
class NotificationsHelper {
late DatabaseProvider database;
late SettingsProvider settingsProvider;
late UserProvider userProvider;
late KretaClient kretaClient;
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
List<T> combineLists<T, K>(
List<T> list1,
List<T> list2,
K Function(T) keyExtractor,
) {
Set<K> uniqueKeys = <K>{};
List<T> combinedList = [];
for (T item in list1) {
K key = keyExtractor(item);
if (!uniqueKeys.contains(key)) {
uniqueKeys.add(key);
combinedList.add(item);
}
}
for (T item in list2) {
K key = keyExtractor(item);
if (!uniqueKeys.contains(key)) {
uniqueKeys.add(key);
combinedList.add(item);
}
}
return combinedList;
}
String dayTitle(DateTime date) {
try {
return DateFormat("EEEE", I18n.locale.languageCode).format(date);
} catch (e) {
return "Unknown";
}
}
@pragma('vm:entry-point')
void backgroundJob() async {
// initialize providers
database = DatabaseProvider();
await database.init();
settingsProvider = await database.query.getSettings(database);
userProvider = await database.query.getUsers(settingsProvider);
if (userProvider.id != null && settingsProvider.notificationsEnabled) {
// refresh kreta login
final status = StatusProvider();
kretaClient = KretaClient(
user: userProvider, settings: settingsProvider, status: status);
kretaClient.refreshLogin();
if (settingsProvider.notificationsGradesEnabled) gradeNotification();
if (settingsProvider.notificationsAbsencesEnabled) absenceNotification();
if (settingsProvider.notificationsMessagesEnabled) messageNotification();
if (settingsProvider.notificationsLessonsEnabled) lessonNotification();
}
}
void gradeNotification() async {
// fetch grades
GradeProvider gradeProvider = GradeProvider(
settings: settingsProvider,
user: userProvider,
database: database,
kreta: kretaClient);
gradeProvider.fetch();
List<Grade> grades =
await database.userQuery.getGrades(userId: userProvider.id ?? "");
DateTime lastSeenGrade =
await database.userQuery.lastSeenGrade(userId: userProvider.id ?? "");
// loop through grades and see which hasn't been seen yet
for (Grade grade in grades) {
// if grade is not a normal grade (1-5), don't show it
if ([1, 2, 3, 4, 5].contains(grade.value.value)) {
// if the grade was added over a week ago, don't show it to avoid notification spam
if (grade.seenDate.isAfter(lastSeenGrade) &&
grade.date.difference(DateTime.now()).inDays * -1 < 7) {
// send notificiation about new grade
AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails(
'GRADES',
'Jegyek',
channelDescription: 'Értesítés jegyek beírásakor',
importance: Importance.max,
priority: Priority.max,
color: settingsProvider.customAccentColor,
ticker: 'Jegyek',
);
NotificationDetails notificationDetails =
NotificationDetails(android: androidNotificationDetails);
if (userProvider.getUsers().length == 1) {
await flutterLocalNotificationsPlugin.show(
grade.id.hashCode,
"title_grade".i18n,
"body_grade".i18n.fill(
[
grade.value.value.toString(),
grade.subject.isRenamed &&
settingsProvider.renamedSubjectsEnabled
? grade.subject.renamedTo!
: grade.subject.name
],
),
notificationDetails,
);
} else {
// multiple users are added, also display student name
await flutterLocalNotificationsPlugin.show(
grade.id.hashCode,
"title_grade".i18n,
"body_grade_multiuser".i18n.fill(
[
userProvider.displayName!,
grade.value.value.toString(),
grade.subject.isRenamed &&
settingsProvider.renamedSubjectsEnabled
? grade.subject.renamedTo!
: grade.subject.name
],
),
notificationDetails,
);
}
}
}
}
// set grade seen status
gradeProvider.seenAll();
}
void absenceNotification() async {
// get absences from api
List? absenceJson = await kretaClient
.getAPI(KretaAPI.absences(userProvider.instituteCode ?? ""));
List<Absence> storedAbsences =
await database.userQuery.getAbsences(userId: userProvider.id!);
if (absenceJson == null) {
return;
}
// format api absences to correct format while preserving isSeen value
List<Absence> absences = absenceJson.map((e) {
Absence apiAbsence = Absence.fromJson(e);
Absence storedAbsence = storedAbsences.firstWhere(
(stored) => stored.id == apiAbsence.id,
orElse: () => apiAbsence);
apiAbsence.isSeen = storedAbsence.isSeen;
return apiAbsence;
}).toList();
List<Absence> modifiedAbsences = [];
if (absences != storedAbsences) {
// remove absences that are not new
absences.removeWhere((element) => storedAbsences.contains(element));
for (Absence absence in absences) {
if (!absence.isSeen) {
absence.isSeen = true;
modifiedAbsences.add(absence);
AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails(
'ABSENCES',
'Hiányzások',
channelDescription: 'Értesítés hiányzások beírásakor',
importance: Importance.max,
priority: Priority.max,
color: settingsProvider.customAccentColor,
ticker: 'Hiányzások',
);
NotificationDetails notificationDetails =
NotificationDetails(android: androidNotificationDetails);
if (userProvider.getUsers().length == 1) {
await flutterLocalNotificationsPlugin.show(
absence.id.hashCode,
"title_absence".i18n, // https://discord.com/channels/1111649116020285532/1153273625206591528
"body_absence".i18n.fill(
[
DateFormat("yyyy-MM-dd").format(absence.date),
absence.subject.isRenamed &&
settingsProvider.renamedSubjectsEnabled
? absence.subject.renamedTo!
: absence.subject.name
],
),
notificationDetails,
);
} else {
await flutterLocalNotificationsPlugin.show(
absence.id.hashCode,
"title_absence".i18n, // https://discord.com/channels/1111649116020285532/1153273625206591528
"body_absence_multiuser".i18n.fill(
[
userProvider.displayName!,
DateFormat("yyyy-MM-dd").format(absence.date),
absence.subject.isRenamed &&
settingsProvider.renamedSubjectsEnabled
? absence.subject.renamedTo!
: absence.subject.name
],
),
notificationDetails,
);
}
}
}
}
// combine modified absences and storedabsences list and save them to the database
List<Absence> combinedAbsences = combineLists(
modifiedAbsences,
storedAbsences,
(Absence absence) => absence.id,
);
await database.userStore
.storeAbsences(combinedAbsences, userId: userProvider.id!);
}
void messageNotification() async {
// get messages from api
List? messageJson =
await kretaClient.getAPI(KretaAPI.messages("beerkezett"));
List<Message> storedmessages =
await database.userQuery.getMessages(userId: userProvider.id!);
if (messageJson == null) {
return;
}
// format api messages to correct format while preserving isSeen value
// Parse messages
List<Message> messages = [];
await Future.wait(List.generate(messageJson.length, (index) {
return () async {
Map message = messageJson.cast<Map>()[index];
Map? innerMessageJson = await kretaClient
.getAPI(KretaAPI.message(message["azonosito"].toString()));
if (innerMessageJson != null) {
messages.add(
Message.fromJson(innerMessageJson, forceType: MessageType.inbox));
}
}();
}));
for (Message message in messages) {
for (Message storedMessage in storedmessages) {
if (message.id == storedMessage.id) {
message.isSeen = storedMessage.isSeen;
}
}
}
List<Message> modifiedmessages = [];
if (messages != storedmessages) {
// remove messages that are not new
messages.removeWhere((element) => storedmessages.contains(element));
for (Message message in messages) {
if (!message.isSeen) {
message.isSeen = true;
modifiedmessages.add(message);
AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails(
'MESSAGES',
'Üzenetek',
channelDescription: 'Értesítés kapott üzenetekkor',
importance: Importance.max,
priority: Priority.max,
color: settingsProvider.customAccentColor,
ticker: 'Üzenetek',
);
NotificationDetails notificationDetails =
NotificationDetails(android: androidNotificationDetails);
if (userProvider.getUsers().length == 1) {
await flutterLocalNotificationsPlugin.show(
message.id.hashCode,
message.author,
message.content.replaceAll(RegExp(r'<[^>]*>'), ''),
notificationDetails,
);
} else {
await flutterLocalNotificationsPlugin.show(
message.id.hashCode,
"(${userProvider.displayName!}) ${message.author}",
message.content.replaceAll(RegExp(r'<[^>]*>'), ''),
notificationDetails,
);
}
}
}
}
// combine modified messages and storedmessages list and save them to the database
List<Message> combinedmessages = combineLists(
modifiedmessages,
storedmessages,
(Message message) => message.id,
);
await database.userStore
.storeMessages(combinedmessages, userId: userProvider.id!);
}
void lessonNotification() async {
// get lesson from api
TimetableProvider timetableProvider = TimetableProvider(
user: userProvider, database: database, kreta: kretaClient);
List<Lesson> storedlessons =
timetableProvider.lessons[Week.current()] ?? [];
List? apilessons = timetableProvider.getWeek(Week.current()) ?? [];
for (Lesson lesson in apilessons) {
for (Lesson storedLesson in storedlessons) {
if (lesson.id == storedLesson.id) {
lesson.isSeen = storedLesson.isSeen;
}
}
}
List<Lesson> modifiedlessons = [];
if (apilessons != storedlessons) {
// remove lessons that are not new
apilessons.removeWhere((element) => storedlessons.contains(element));
for (Lesson lesson in apilessons) {
if (!lesson.isSeen && lesson.isChanged) {
lesson.isSeen = true;
modifiedlessons.add(lesson);
AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails(
'LESSONS',
'Órák',
channelDescription:
'Értesítés órák elmaradásáról, helyettesítésről',
importance: Importance.max,
priority: Priority.max,
color: settingsProvider.customAccentColor,
ticker: 'Órák',
);
NotificationDetails notificationDetails =
NotificationDetails(android: androidNotificationDetails);
if (userProvider.getUsers().length == 1) {
if (lesson.status?.name == "Elmaradt") {
switch (I18n.localeStr) {
case "en_en":
{
await flutterLocalNotificationsPlugin.show(
lesson.id.hashCode,
"title_lesson".i18n,
"body_lesson_canceled".i18n.fill(
[
lesson.lessonIndex,
lesson.name,
dayTitle(lesson.date)
],
),
notificationDetails,
);
break;
}
case "hu_hu":
{
await flutterLocalNotificationsPlugin.show(
lesson.id.hashCode,
"title_lesson".i18n,
"body_lesson_canceled".i18n.fill(
[
dayTitle(lesson.date),
lesson.lessonIndex,
lesson.name
],
),
notificationDetails,
);
break;
}
default:
{
await flutterLocalNotificationsPlugin.show(
lesson.id.hashCode,
"title_lesson".i18n,
"body_lesson_canceled".i18n.fill(
[
lesson.lessonIndex,
lesson.name,
dayTitle(lesson.date)
],
),
notificationDetails,
);
break;
}
}
} else if (lesson.substituteTeacher?.name != "") {
switch (I18n.localeStr) {
case "en_en":
{
await flutterLocalNotificationsPlugin.show(
lesson.id.hashCode,
"title_lesson".i18n,
"body_lesson_substituted".i18n.fill(
[
lesson.lessonIndex,
lesson.name,
dayTitle(lesson.date),
lesson.substituteTeacher!.isRenamed
? lesson.substituteTeacher!.renamedTo!
: lesson.substituteTeacher!.name
],
),
notificationDetails,
);
break;
}
case "hu_hu":
{
await flutterLocalNotificationsPlugin.show(
lesson.id.hashCode,
"title_lesson".i18n,
"body_lesson_substituted".i18n.fill(
[
dayTitle(lesson.date),
lesson.lessonIndex,
lesson.name,
lesson.substituteTeacher!.isRenamed
? lesson.substituteTeacher!.renamedTo!
: lesson.substituteTeacher!.name
],
),
notificationDetails,
);
break;
}
default:
{
await flutterLocalNotificationsPlugin.show(
lesson.id.hashCode,
"title_lesson".i18n,
"body_lesson_substituted".i18n.fill(
[
lesson.lessonIndex,
lesson.name,
dayTitle(lesson.date),
lesson.substituteTeacher!.isRenamed
? lesson.substituteTeacher!.renamedTo!
: lesson.substituteTeacher!.name
],
),
notificationDetails,
);
break;
}
}
}
} else {
if (lesson.status?.name == "Elmaradt") {
switch (I18n.localeStr) {
case "en_en":
{
await flutterLocalNotificationsPlugin.show(
lesson.id.hashCode,
"title_lesson".i18n,
"body_lesson_canceled".i18n.fill(
[
userProvider.displayName!,
lesson.lessonIndex,
lesson.name,
dayTitle(lesson.date)
],
),
notificationDetails,
);
break;
}
case "hu_hu":
{
await flutterLocalNotificationsPlugin.show(
lesson.id.hashCode,
"title_lesson".i18n,
"body_lesson_canceled".i18n.fill(
[
userProvider.displayName!,
dayTitle(lesson.date),
lesson.lessonIndex,
lesson.name
],
),
notificationDetails,
);
break;
}
default:
{
await flutterLocalNotificationsPlugin.show(
lesson.id.hashCode,
"title_lesson".i18n,
"body_lesson_canceled".i18n.fill(
[
userProvider.displayName!,
lesson.lessonIndex,
lesson.name,
dayTitle(lesson.date)
],
),
notificationDetails,
);
break;
}
}
} else if (lesson.substituteTeacher?.name != "") {
switch (I18n.localeStr) {
case "en_en":
{
await flutterLocalNotificationsPlugin.show(
lesson.id.hashCode,
"title_lesson".i18n,
"body_lesson_substituted".i18n.fill(
[
userProvider.displayName!,
lesson.lessonIndex,
lesson.name,
dayTitle(lesson.date),
lesson.substituteTeacher!.isRenamed
? lesson.substituteTeacher!.renamedTo!
: lesson.substituteTeacher!.name
],
),
notificationDetails,
);
break;
}
case "hu_hu":
{
await flutterLocalNotificationsPlugin.show(
lesson.id.hashCode,
"title_lesson".i18n,
"body_lesson_substituted".i18n.fill(
[
userProvider.displayName!,
dayTitle(lesson.date),
lesson.lessonIndex,
lesson.name,
lesson.substituteTeacher!.isRenamed
? lesson.substituteTeacher!.renamedTo!
: lesson.substituteTeacher!.name
],
),
notificationDetails,
);
break;
}
default:
{
await flutterLocalNotificationsPlugin.show(
lesson.id.hashCode,
"title_lesson".i18n,
"body_lesson_substituted".i18n.fill(
[
userProvider.displayName!,
lesson.lessonIndex,
lesson.name,
dayTitle(lesson.date),
lesson.substituteTeacher!.isRenamed
? lesson.substituteTeacher!.renamedTo!
: lesson.substituteTeacher!.name
],
),
notificationDetails,
);
break;
}
}
}
}
}
}
// combine modified lesson and storedlesson list and save them to the database
List<Lesson> combinedlessons = combineLists(
modifiedlessons,
storedlessons,
(Lesson message) => message.id,
);
Map<Week, List<Lesson>> timetableLessons = timetableProvider.lessons;
timetableLessons[Week.current()] = combinedlessons;
await database.userStore
.storeLessons(timetableLessons, userId: userProvider.id!);
}
}
}

View File

@ -1,15 +0,0 @@
import 'package:filcnaplo/helpers/attachment_helper.dart';
import 'package:filcnaplo_kreta_api/models/attachment.dart';
import 'package:flutter/widgets.dart';
import 'package:share_plus/share_plus.dart';
class ShareHelper {
static Future<void> shareText(String text, {String? subject}) => Share.share(text, subject: subject);
// ignore: deprecated_member_use
static Future<void> shareFile(String path, {String? text, String? subject}) => Share.shareFiles([path], text: text, subject: subject);
static Future<void> shareAttachment(Attachment attachment, {required BuildContext context}) async {
String path = await attachment.download(context);
await shareFile(path);
}
}

View File

@ -1,33 +0,0 @@
import 'package:flutter/material.dart';
enum AccentColor {
filc,
blue,
green,
lime,
yellow,
orange,
red,
pink,
purple,
none,
ogfilc,
adaptive,
custom
}
Map<AccentColor, Color> accentColorMap = {
AccentColor.filc: const Color(0xFF3D7BF4),
AccentColor.blue: Colors.blue.shade300,
AccentColor.green: Colors.green.shade400,
AccentColor.lime: Colors.lightGreen.shade400,
AccentColor.yellow: Colors.orange.shade300,
AccentColor.orange: Colors.deepOrange.shade300,
AccentColor.red: Colors.red.shade300,
AccentColor.pink: Colors.pink.shade300,
AccentColor.purple: Colors.purple.shade300,
//AccentColor.none: Colors.black,
AccentColor.ogfilc: const Color(0xff20AC9B),
AccentColor.adaptive: const Color(0xFF3D7BF4),
AccentColor.custom: const Color(0xFF3D7BF4),
};

View File

@ -1,160 +0,0 @@
import 'package:filcnaplo/models/settings.dart';
import 'package:filcnaplo/theme/colors/accent.dart';
import 'package:filcnaplo/theme/colors/colors.dart';
import 'package:filcnaplo/theme/observer.dart';
import 'package:flutter/material.dart';
import 'package:material_color_utilities/material_color_utilities.dart';
import 'package:provider/provider.dart';
class AppTheme {
// Dev note: All of these could be constant variables, but this is better for
// development (you don't have to hot-restart)
static const String _fontFamily = "Montserrat";
static Color? _paletteAccentLight(CorePalette? palette) => palette != null ? Color(palette.primary.get(70)) : null;
static Color? _paletteHighlightLight(CorePalette? palette) => palette != null ? Color(palette.neutral.get(100)) : null;
static Color? _paletteBackgroundLight(CorePalette? palette) => palette != null ? Color(palette.neutral.get(95)) : null;
static Color? _paletteAccentDark(CorePalette? palette) => palette != null ? Color(palette.primary.get(80)) : null;
static Color? _paletteBackgroundDark(CorePalette? palette) => palette != null ? Color(palette.neutralVariant.get(10)) : null;
static Color? _paletteHighlightDark(CorePalette? palette) => palette != null ? Color(palette.neutralVariant.get(20)) : null;
// Light Theme
static ThemeData lightTheme(BuildContext context, {CorePalette? palette}) {
var lightColors = AppColors.fromBrightness(Brightness.light);
final settings = Provider.of<SettingsProvider>(context, listen: false);
AccentColor accentColor = settings.accentColor;
final customAccentColor = accentColor == AccentColor.custom ? settings.customAccentColor : null;
Color accent = customAccentColor ?? accentColorMap[accentColor] ?? const Color(0x00000000);
if (accentColor == AccentColor.adaptive) {
if (palette != null) accent = _paletteAccentLight(palette)!;
} else {
palette = null;
}
Color backgroundColor =
(accentColor == AccentColor.custom ? settings.customBackgroundColor : _paletteBackgroundLight(palette)) ?? lightColors.background;
Color highlightColor =
(accentColor == AccentColor.custom ? settings.customHighlightColor : _paletteHighlightLight(palette)) ?? lightColors.highlight;
return ThemeData(
brightness: Brightness.light,
useMaterial3: true,
fontFamily: _fontFamily,
scaffoldBackgroundColor: backgroundColor,
primaryColor: lightColors.filc,
dividerColor: const Color(0x00000000),
colorScheme: ColorScheme(
primary: accent,
onPrimary: (accent.computeLuminance() > 0.5 ? Colors.black : Colors.white).withOpacity(.9),
secondary: accent,
onSecondary: (accent.computeLuminance() > 0.5 ? Colors.black : Colors.white).withOpacity(.9),
background: highlightColor,
onBackground: Colors.black.withOpacity(.9),
brightness: Brightness.light,
error: lightColors.red,
onError: Colors.white.withOpacity(.9),
surface: highlightColor,
onSurface: Colors.black.withOpacity(.9),
),
shadowColor: lightColors.shadow.withOpacity(.5),
appBarTheme: AppBarTheme(backgroundColor: backgroundColor),
indicatorColor: accent,
iconTheme: IconThemeData(color: lightColors.text.withOpacity(.75)),
navigationBarTheme: NavigationBarThemeData(
indicatorColor: accent.withOpacity(accentColor == AccentColor.adaptive ? 0.4 : 0.8),
iconTheme: MaterialStateProperty.all(IconThemeData(color: lightColors.text)),
backgroundColor: highlightColor,
labelTextStyle: MaterialStateProperty.all(TextStyle(
fontSize: 13.0,
fontWeight: FontWeight.w500,
color: lightColors.text.withOpacity(0.8),
)),
labelBehavior: NavigationDestinationLabelBehavior.alwaysShow,
height: 76.0,
),
sliderTheme: SliderThemeData(
inactiveTrackColor: accent.withOpacity(.3),
),
progressIndicatorTheme: ProgressIndicatorThemeData(color: accent),
expansionTileTheme: ExpansionTileThemeData(iconColor: accent),
cardColor: highlightColor,
bottomNavigationBarTheme: BottomNavigationBarThemeData(
backgroundColor: Provider.of<ThemeModeObserver>(context, listen: false).updateNavbarColor ? backgroundColor : null,
),
);
}
// Dark Theme
static ThemeData darkTheme(BuildContext context, {CorePalette? palette}) {
var darkColors = AppColors.fromBrightness(Brightness.dark);
final settings = Provider.of<SettingsProvider>(context, listen: false);
AccentColor accentColor = settings.accentColor;
final customAccentColor = accentColor == AccentColor.custom ? settings.customAccentColor : null;
Color accent = customAccentColor ?? accentColorMap[accentColor] ?? const Color(0x00000000);
if (accentColor == AccentColor.adaptive) {
if (palette != null) accent = _paletteAccentDark(palette)!;
} else {
palette = null;
}
Color backgroundColor =
(accentColor == AccentColor.custom ? settings.customBackgroundColor : _paletteBackgroundDark(palette)) ?? darkColors.background;
Color highlightColor =
(accentColor == AccentColor.custom ? settings.customHighlightColor : _paletteHighlightDark(palette)) ?? darkColors.highlight;
return ThemeData(
brightness: Brightness.dark,
useMaterial3: true,
fontFamily: _fontFamily,
scaffoldBackgroundColor: backgroundColor,
primaryColor: darkColors.filc,
dividerColor: const Color(0x00000000),
colorScheme: ColorScheme(
primary: accent,
onPrimary: (accent.computeLuminance() > 0.5 ? Colors.black : Colors.white).withOpacity(.9),
secondary: accent,
onSecondary: (accent.computeLuminance() > 0.5 ? Colors.black : Colors.white).withOpacity(.9),
background: highlightColor,
onBackground: Colors.white.withOpacity(.9),
brightness: Brightness.dark,
error: darkColors.red,
onError: Colors.black.withOpacity(.9),
surface: highlightColor,
onSurface: Colors.white.withOpacity(.9),
),
shadowColor: highlightColor.withOpacity(.5), //darkColors.shadow,
appBarTheme: AppBarTheme(backgroundColor: backgroundColor),
indicatorColor: accent,
iconTheme: IconThemeData(color: darkColors.text.withOpacity(.75)),
navigationBarTheme: NavigationBarThemeData(
indicatorColor: accent.withOpacity(accentColor == AccentColor.adaptive ? 0.4 : 0.8),
iconTheme: MaterialStateProperty.all(IconThemeData(color: darkColors.text)),
backgroundColor: highlightColor,
labelTextStyle: MaterialStateProperty.all(TextStyle(
fontSize: 13.0,
fontWeight: FontWeight.w500,
color: darkColors.text.withOpacity(0.8),
)),
labelBehavior: NavigationDestinationLabelBehavior.alwaysShow,
height: 76.0,
),
sliderTheme: SliderThemeData(
inactiveTrackColor: accent.withOpacity(.3),
),
progressIndicatorTheme: ProgressIndicatorThemeData(color: accent),
expansionTileTheme: ExpansionTileThemeData(iconColor: accent),
cardColor: highlightColor,
chipTheme: ChipThemeData(
backgroundColor: accent.withOpacity(.2),
elevation: 1,
),
bottomNavigationBarTheme: BottomNavigationBarThemeData(
backgroundColor: Provider.of<ThemeModeObserver>(context, listen: false).updateNavbarColor ? backgroundColor : null,
),
);
}
}

View File

@ -1,15 +0,0 @@
import 'package:filcnaplo/ui/date_widget.dart';
import 'package:filcnaplo_kreta_api/models/absence.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/absence/absence_viewable.dart' as mobile;
List<DateWidget> getWidgets(List<Absence> providerAbsences, {bool noExcused = false}) {
List<DateWidget> items = [];
providerAbsences.where((a) => !noExcused || a.state != Justification.excused).forEach((absence) {
items.add(DateWidget(
key: absence.id,
date: absence.date,
widget: mobile.AbsenceViewable(absence),
));
});
return items;
}

View File

@ -1,41 +0,0 @@
import 'package:filcnaplo/ui/date_widget.dart';
import 'package:filcnaplo/utils/platform.dart';
import 'package:filcnaplo_kreta_api/models/grade.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/grade/grade_viewable.dart' as mobile;
import 'package:filcnaplo_mobile_ui/common/widgets/grade/new_grades.dart' as mobile;
import 'package:filcnaplo_desktop_ui/common/widgets/grade/grade_viewable.dart' as desktop;
List<DateWidget> getWidgets(List<Grade> providerGrades, DateTime? lastSeenDate) {
List<DateWidget> items = [];
for (var grade in providerGrades) {
final surprise = (!(lastSeenDate != null && grade.date.isAfter(lastSeenDate)) || grade.value.value == 0);
if (grade.type == GradeType.midYear && surprise) {
items.add(DateWidget(
key: grade.id,
date: grade.date,
widget: PlatformUtils.isMobile ? mobile.GradeViewable(grade) : desktop.GradeViewable(grade),
));
}
}
return items;
}
List<DateWidget> getNewWidgets(List<Grade> providerGrades, DateTime? lastSeenDate) {
List<DateWidget> items = [];
List<Grade> newGrades = [];
for (var grade in providerGrades) {
final surprise = !(lastSeenDate != null && !grade.date.isAfter(lastSeenDate)) && grade.value.value != 0;
if (grade.type == GradeType.midYear && surprise) {
newGrades.add(grade);
}
}
newGrades.sort((a, b) => a.date.compareTo(b.date));
if (newGrades.isNotEmpty) {
items.add(DateWidget(
key: newGrades.last.id,
date: newGrades.last.date,
widget: mobile.NewGradesSurprise(newGrades),
));
}
return items;
}

View File

@ -1,15 +0,0 @@
import 'package:filcnaplo/ui/date_widget.dart';
import 'package:filcnaplo_kreta_api/models/homework.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/homework/homework_viewable.dart' as mobile;
List<DateWidget> getWidgets(List<Homework> providerHomework) {
List<DateWidget> items = [];
for (var homework in providerHomework) {
items.add(DateWidget(
key: homework.id,
date: homework.deadline.year != 0 ? homework.deadline : homework.date,
widget: mobile.HomeworkViewable(homework),
));
}
return items;
}

View File

@ -1,15 +0,0 @@
import 'package:filcnaplo/ui/date_widget.dart';
import 'package:filcnaplo_kreta_api/models/lesson.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/lesson/changed_lesson_viewable.dart' as mobile;
List<DateWidget> getWidgets(List<Lesson> providerLessons) {
List<DateWidget> items = [];
providerLessons.where((l) => l.isChanged && l.start.isAfter(DateTime.now())).forEach((lesson) {
items.add(DateWidget(
key: lesson.id,
date: DateTime(lesson.date.year, lesson.date.month, lesson.date.day, lesson.start.hour, lesson.start.minute),
widget: mobile.ChangedLessonViewable(lesson),
));
});
return items;
}

View File

@ -1,23 +0,0 @@
import 'package:filcnaplo/ui/date_widget.dart';
import 'package:filcnaplo/ui/filter/widgets/notes.dart' as note_filter;
import 'package:filcnaplo/ui/filter/widgets/events.dart' as event_filter;
import 'package:filcnaplo_kreta_api/models/event.dart';
import 'package:filcnaplo_kreta_api/models/message.dart';
import 'package:filcnaplo_kreta_api/models/note.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/message/message_viewable.dart' as mobile;
List<DateWidget> getWidgets(List<Message> providerMessages, List<Note> providerNotes, List<Event> providerEvents) {
List<DateWidget> items = [];
for (var message in providerMessages) {
if (message.type == MessageType.inbox) {
items.add(DateWidget(
key: "${message.id}",
date: message.date,
widget: mobile.MessageViewable(message),
));
}
}
items.addAll(note_filter.getWidgets(providerNotes));
items.addAll(event_filter.getWidgets(providerEvents));
return items;
}

View File

@ -1,10 +0,0 @@
import 'package:filcnaplo/models/release.dart';
import 'package:filcnaplo/ui/date_widget.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/update/update_viewable.dart' as mobile;
DateWidget getWidget(Release providerRelease) {
return DateWidget(
date: DateTime.now(),
widget: mobile.UpdateViewable(providerRelease),
);
}

View File

@ -1,348 +0,0 @@
import 'package:filcnaplo/models/settings.dart';
import 'package:filcnaplo_kreta_api/providers/exam_provider.dart';
import 'package:filcnaplo_kreta_api/providers/homework_provider.dart';
import 'package:filcnaplo/theme/colors/colors.dart';
import 'package:filcnaplo_kreta_api/models/exam.dart';
import 'package:filcnaplo_kreta_api/models/homework.dart';
import 'package:filcnaplo_kreta_api/models/lesson.dart';
import 'package:filcnaplo/utils/format.dart';
import 'package:filcnaplo_mobile_ui/common/panel/panel.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/exam/exam_view.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/homework/homework_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'lesson_tile.i18n.dart';
class LessonTile extends StatelessWidget {
const LessonTile(this.lesson, {super.key, this.onTap, this.swapDesc = false});
final Lesson lesson;
final bool swapDesc;
final void Function()? onTap;
@override
Widget build(BuildContext context) {
List<Widget> subtiles = [];
Color accent = Theme.of(context).colorScheme.secondary;
bool fill = false;
bool fillLeading = false;
String lessonIndexTrailing = "";
SettingsProvider settingsProvider = Provider.of<SettingsProvider>(context);
// Only put a trailing . if its a digit
if (RegExp(r'\d').hasMatch(lesson.lessonIndex)) lessonIndexTrailing = ".";
var now = DateTime.now();
if (lesson.start.isBefore(now) &&
lesson.end.isAfter(now) &&
lesson.status?.name != "Elmaradt") {
fillLeading = true;
}
if (lesson.substituteTeacher != null &&
lesson.substituteTeacher?.name != "") {
fill = true;
accent = AppColors.of(context).yellow;
}
if (lesson.status?.name == "Elmaradt") {
fill = true;
accent = AppColors.of(context).red;
}
if (lesson.isEmpty) {
accent = AppColors.of(context).text.withOpacity(0.6);
}
if (!lesson.studentPresence) {
subtiles.add(LessonSubtile(
type: LessonSubtileType.absence,
title: "absence".i18n,
));
}
if (lesson.homeworkId != "") {
Homework homework = Provider.of<HomeworkProvider>(context, listen: false)
.homework
.firstWhere((h) => h.id == lesson.homeworkId,
orElse: () => Homework.fromJson({}));
if (homework.id != "") {
subtiles.add(LessonSubtile(
type: LessonSubtileType.homework,
title: homework.content,
onPressed: () => HomeworkView.show(homework, context: context),
));
}
}
if (lesson.exam != "") {
Exam exam = Provider.of<ExamProvider>(context, listen: false)
.exams
.firstWhere((t) => t.id == lesson.exam,
orElse: () => Exam.fromJson({}));
if (exam.id != "") {
subtiles.add(LessonSubtile(
type: LessonSubtileType.exam,
title: exam.description != ""
? exam.description
: exam.mode?.description ?? "exam".i18n,
onPressed: () => ExamView.show(exam, context: context),
));
}
}
String description = '';
String room = '';
final cleanDesc = lesson.description
.specialChars()
.toLowerCase()
.replaceAll(lesson.subject.name.specialChars().toLowerCase(), '');
if (!swapDesc) {
if (cleanDesc != "") {
description = lesson.description;
}
// Changed lesson Description
if (lesson.isChanged) {
if (lesson.status?.name == "Elmaradt") {
description = 'cancelled'.i18n;
} else if (lesson.substituteTeacher?.name != "") {
description = 'substitution'.i18n;
}
}
room = lesson.room.replaceAll("_", " ");
} else {
description = lesson.room.replaceAll("_", " ");
}
return Padding(
padding: const EdgeInsets.only(bottom: 2.0),
child: Material(
color: fill ? accent.withOpacity(.25) : Colors.transparent,
borderRadius: BorderRadius.circular(12.0),
child: Visibility(
visible: lesson.subject.id != '' || lesson.isEmpty,
replacement: Padding(
padding: const EdgeInsets.only(top: 6.0),
child: PanelTitle(title: Text(lesson.name)),
),
child: Padding(
padding: EdgeInsets.only(bottom: subtiles.isEmpty ? 0.0 : 12.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
minVerticalPadding: 12.0,
dense: true,
onTap: onTap,
// onLongPress: kDebugMode ? () => log(jsonEncode(lesson.json)) : null,
visualDensity: VisualDensity.compact,
contentPadding: const EdgeInsets.symmetric(horizontal: 4.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0)),
title: Text(
!lesson.isEmpty
? lesson.subject.renamedTo ??
lesson.subject.name.capital()
: "empty".i18n,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 15.5,
color: AppColors.of(context)
.text
.withOpacity(!lesson.isEmpty ? 1.0 : 0.5),
fontStyle: lesson.subject.isRenamed &&
settingsProvider.renamedSubjectsItalics
? FontStyle.italic
: null),
),
subtitle: description != ""
? Text(
description,
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 14.0,
),
maxLines: 1,
softWrap: false,
overflow: TextOverflow.ellipsis,
)
: null,
minLeadingWidth: 34.0,
leading: AspectRatio(
aspectRatio: 1,
child: Center(
child: Stack(
children: [
Text(
lesson.lessonIndex + lessonIndexTrailing,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.w600,
color: accent,
),
),
// Current lesson indicator
Transform.translate(
offset: const Offset(-12.0, -2.0),
child: Container(
decoration: BoxDecoration(
color: fillLeading
? Theme.of(context)
.colorScheme
.secondary
.withOpacity(.3)
: const Color(0x00000000),
borderRadius: BorderRadius.circular(12.0),
boxShadow: [
if (fillLeading)
BoxShadow(
color: Theme.of(context)
.colorScheme
.secondary
.withOpacity(.25),
blurRadius: 6.0,
)
],
),
margin: const EdgeInsets.symmetric(vertical: 4.0),
width: 4.0,
height: double.infinity,
),
)
],
),
),
),
trailing: !lesson.isEmpty
? Row(
mainAxisSize: MainAxisSize.min,
children: [
if (!swapDesc)
SizedBox(
width: 52.0,
child: Padding(
padding: const EdgeInsets.only(right: 6.0),
child: Text(
room,
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
maxLines: 2,
style: TextStyle(
fontWeight: FontWeight.w500,
color: AppColors.of(context)
.text
.withOpacity(.75),
),
),
),
),
Stack(
alignment: Alignment.center,
children: [
// Fix alignment hack
const Opacity(opacity: 0, child: Text("EE:EE")),
Text(
"${DateFormat("H:mm").format(lesson.start)}\n${DateFormat("H:mm").format(lesson.end)}",
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.w500,
color: AppColors.of(context)
.text
.withOpacity(.9),
),
),
],
),
],
)
: null,
),
// Homework & Exams
...subtiles,
],
),
),
),
),
);
}
}
enum LessonSubtileType { homework, exam, absence }
class LessonSubtile extends StatelessWidget {
const LessonSubtile(
{super.key, this.onPressed, required this.title, required this.type});
final Function()? onPressed;
final String title;
final LessonSubtileType type;
@override
Widget build(BuildContext context) {
IconData icon;
Color iconColor = AppColors.of(context).text;
switch (type) {
case LessonSubtileType.absence:
icon = FeatherIcons.slash;
iconColor = AppColors.of(context).red;
break;
case LessonSubtileType.exam:
icon = FeatherIcons.file;
break;
case LessonSubtileType.homework:
icon = FeatherIcons.home;
break;
}
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: InkWell(
onTap: onPressed,
borderRadius: BorderRadius.circular(8.0),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0),
child: Row(
children: [
Center(
child: SizedBox(
width: 30.0,
child:
Icon(icon, color: iconColor.withOpacity(.75), size: 20.0),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Text(
title.escapeHtml(),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontWeight: FontWeight.w500,
color: AppColors.of(context).text.withOpacity(.65)),
),
),
),
],
),
),
),
);
}
}

View File

@ -1,38 +0,0 @@
import 'dart:developer';
import 'package:filcnaplo_kreta_api/models/absence.dart';
import 'package:filcnaplo_kreta_api/models/lesson.dart';
import 'package:filcnaplo_kreta_api/models/week.dart';
import 'package:filcnaplo_kreta_api/providers/timetable_provider.dart';
import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';
class ReverseSearch {
static Future<Lesson?> getLessonByAbsence(Absence absence, BuildContext context) async {
final timetableProvider = Provider.of<TimetableProvider>(context, listen: false);
List<Lesson> lessons = [];
final week = Week.fromDate(absence.date);
try {
await timetableProvider.fetch(week: week);
} catch (e) {
log("[ERROR] getLessonByAbsence: $e");
}
lessons = timetableProvider.getWeek(week) ?? [];
// Find absence lesson in timetable
Lesson lesson = lessons.firstWhere(
(l) => _sameDate(l.date, absence.date) && l.subject.id == absence.subject.id && l.lessonIndex == absence.lessonIndex.toString(),
orElse: () => Lesson.fromJson({'isEmpty': true}),
);
if (lesson.isEmpty) {
return null;
} else {
return lesson;
}
}
// difference.inDays is not reliable
static bool _sameDate(DateTime a, DateTime b) => (a.year == b.year && a.month == b.month && a.day == b.day);
}

View File

@ -1,14 +0,0 @@
import 'package:flutter/material.dart';
import 'package:filcnaplo_kreta_api/models/grade.dart';
import 'package:filcnaplo/ui/widgets/grade/grade_tile.dart';
class GradeViewable extends StatelessWidget {
const GradeViewable(this.grade, {Key? key}) : super(key: key);
final Grade grade;
@override
Widget build(BuildContext context) {
return GradeTile(grade);
}
}

View File

@ -1,25 +0,0 @@
import 'package:flutter/material.dart';
import 'package:filcnaplo_kreta_api/models/grade.dart';
import 'package:filcnaplo_desktop_ui/pages/grades/grades_count_item.dart';
import 'package:collection/collection.dart';
class GradesCount extends StatelessWidget {
const GradesCount({Key? key, required this.grades}) : super(key: key);
final List<Grade> grades;
@override
Widget build(BuildContext context) {
List<int> gradesCount = List.generate(5, (int index) => grades.where((e) => e.value.value == index + 1).length);
return Container(
width: 75,
padding: const EdgeInsets.only(bottom: 6.0, top: 6.0, left: 12.0, right: 0.0),
margin: const EdgeInsets.symmetric(horizontal: 12.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: gradesCount.mapIndexed((index, e) => GradesCountItem(count: e, value: index + 1)).toList(),
),
);
}
}

View File

@ -1,34 +0,0 @@
name: filcnaplo_desktop_ui
publish_to: "none"
environment:
sdk: ">=2.17.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# Filcnaplo main dep
filcnaplo:
path: ../filcnaplo/
filcnaplo_kreta_api:
path: ../filcnaplo_kreta_api/
cupertino_icons: ^1.0.2
flutter_feather_icons: ^2.0.0+1
provider: ^5.0.0
url_launcher: ^6.0.9
flutter_linkify: ^5.0.2
flutter_markdown: ^0.6.5
animations: ^2.0.1
confetti: ^0.6.0
auto_size_text: ^3.0.0
flutter_acrylic: ^1.1.3
elegant_notification: ^1.6.1
flutter_staggered_grid_view: ^0.7.0
dev_dependencies:
flutter_lints: ^1.0.0
flutter:
uses-material-design: true

View File

@ -1,11 +0,0 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "pub" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "daily"

View File

@ -1,20 +0,0 @@
name: filcnaplo_kreta_api
publish_to: "none"
environment:
sdk: ">=2.17.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
filcnaplo:
path: ../filcnaplo/
http: ^0.13.3
provider: ^5.0.0
file_picker: ^6.1.1
intl: ^0.18.1
i18n_extension: ^10.0.1
uuid: ^4.2.1
dev_dependencies:
flutter_lints: ^3.0.1

View File

@ -1,11 +0,0 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "pub" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "daily"

View File

@ -1,70 +0,0 @@
import 'package:filcnaplo/theme/colors/colors.dart';
import 'package:flutter/material.dart';
class RoundedBottomSheet extends StatelessWidget {
const RoundedBottomSheet({super.key, this.child, this.borderRadius = 12.0, this.shrink = true, this.showHandle = true});
final Widget? child;
final double borderRadius;
final bool shrink;
final bool showHandle;
@override
Widget build(BuildContext context) {
return AnimatedContainer(
duration: const Duration(milliseconds: 500),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.background,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(borderRadius),
topRight: Radius.circular(borderRadius),
),
),
child: SafeArea(
child: Column(
mainAxisSize: shrink ? MainAxisSize.min : MainAxisSize.max,
children: [
if (showHandle)
Container(
width: 42.0,
height: 4.0,
margin: const EdgeInsets.only(top: 12.0, bottom: 4.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(45.0),
color: AppColors.of(context).text.withOpacity(0.10),
),
),
if (child != null) child!,
SizedBox(height: MediaQuery.of(context).padding.bottom),
],
),
),
);
}
}
Future<T?> showRoundedModalBottomSheet<T>(
BuildContext context, {
required Widget child,
bool rootNavigator = true,
}) async {
return await showModalBottomSheet<T>(
context: context,
backgroundColor: const Color(0x00000000),
elevation: 0,
isDismissible: true,
useRootNavigator: rootNavigator,
builder: (context) => RoundedBottomSheet(child: child));
}
PersistentBottomSheetController<T> showRoundedBottomSheet<T>(
BuildContext context, {
required Widget child,
}) {
return showBottomSheet<T>(
context: context,
backgroundColor: const Color(0x00000000),
elevation: 12.0,
builder: (context) => RoundedBottomSheet(child: child),
);
}

View File

@ -1,136 +0,0 @@
import 'package:filcnaplo/theme/colors/colors.dart';
import 'package:flutter/material.dart';
import 'package:filcnaplo/utils/format.dart';
class HeroScrollView extends StatefulWidget {
const HeroScrollView(
{super.key,
required this.child,
required this.title,
required this.icon,
this.italic = false,
this.navBarItems = const [],
this.onClose,
this.iconSize = 64.0,
this.scrollController});
final Widget child;
final String title;
final IconData? icon;
final List<Widget> navBarItems;
final VoidCallback? onClose;
final double iconSize;
final ScrollController? scrollController;
final bool italic;
@override
HeroScrollViewState createState() => HeroScrollViewState();
}
class HeroScrollViewState extends State<HeroScrollView> {
late ScrollController _scrollController;
bool showBarTitle = false;
@override
void initState() {
super.initState();
_scrollController = widget.scrollController ?? ScrollController();
_scrollController.addListener(() {
if (_scrollController.offset > 42.0) {
if (showBarTitle == false) setState(() => showBarTitle = true);
} else {
if (showBarTitle == true) setState(() => showBarTitle = false);
}
});
}
@override
void dispose() {
super.dispose();
_scrollController.dispose();
}
@override
Widget build(BuildContext context) {
return NestedScrollView(
controller: _scrollController,
physics:
const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()),
headerSliverBuilder: (context, _) => [
SliverAppBar(
pinned: true,
floating: false,
snap: false,
centerTitle: false,
titleSpacing: 0,
surfaceTintColor: Theme.of(context).scaffoldBackgroundColor,
title: AnimatedOpacity(
opacity: showBarTitle ? 1.0 : 0.0,
duration: const Duration(milliseconds: 200),
child: Row(
children: [
Icon(widget.icon,
color: AppColors.of(context).text.withOpacity(.8)),
const SizedBox(width: 8.0),
Expanded(
child: Text(
widget.title.capital(),
overflow: TextOverflow.ellipsis,
maxLines: 2,
style: TextStyle(
color: AppColors.of(context).text,
fontWeight: FontWeight.w500,
fontStyle: widget.italic ? FontStyle.italic : null),
),
),
],
)),
leading: BackButton(
color: AppColors.of(context).text,
onPressed: () {
if (widget.onClose != null) {
widget.onClose!();
} else {
Navigator.of(context).pop();
}
}),
actions: widget.navBarItems,
expandedHeight: 145.69,
stretch: true,
flexibleSpace: FlexibleSpaceBar(
background: Stack(
children: [
Center(
child: Icon(
widget.icon,
size: widget.iconSize,
color: AppColors.of(context).text.withOpacity(.15),
),
),
Container(
alignment: Alignment.center,
margin: const EdgeInsets.only(top: 82),
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: Text(
widget.title.capital(),
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 36.0,
color: AppColors.of(context).text.withOpacity(.9),
fontStyle: widget.italic ? FontStyle.italic : null,
fontWeight: FontWeight.bold),
),
),
],
),
),
),
],
body: widget.child,
);
}
}

View File

@ -1,99 +0,0 @@
import 'package:filcnaplo/helpers/subject.dart';
import 'package:filcnaplo/models/settings.dart';
import 'package:filcnaplo/theme/colors/colors.dart';
import 'package:filcnaplo/utils/format.dart';
import 'package:filcnaplo_kreta_api/models/subject.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/absence/absence_display.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class AbsenceSubjectTile extends StatelessWidget {
const AbsenceSubjectTile(this.subject,
{super.key,
this.percentage = 0.0,
this.excused = 0,
this.unexcused = 0,
this.pending = 0,
this.onTap});
final GradeSubject subject;
final void Function()? onTap;
final double percentage;
final int excused;
final int unexcused;
final int pending;
@override
Widget build(BuildContext context) {
SettingsProvider settingsProvider = Provider.of<SettingsProvider>(context);
return Material(
type: MaterialType.transparency,
child: ListTile(
// minLeadingWidth: 32.0,
dense: true,
contentPadding: const EdgeInsets.only(left: 8.0, right: 6.0),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),
visualDensity: VisualDensity.compact,
onTap: onTap,
leading: Icon(
SubjectIcon.resolveVariant(subject: subject, context: context),
size: 32.0),
title: Text(
subject.renamedTo ?? subject.name.capital(),
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 15.0,
fontStyle:
subject.isRenamed && settingsProvider.renamedSubjectsItalics
? FontStyle.italic
: null),
),
subtitle: AbsenceDisplay(excused, unexcused, pending),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(width: 8.0),
if (percentage >= 0)
Stack(
alignment: Alignment.centerRight,
children: [
const Opacity(
opacity: 0,
child: Text("100%",
style: TextStyle(fontFamily: "monospace"))),
Text(
"${percentage.round()}%",
style: TextStyle(
// fontFamily: "monospace",
color: getColorByPercentage(percentage, context: context),
fontWeight: FontWeight.w700,
fontSize: 24.0,
),
),
],
),
],
),
),
);
}
}
Color getColorByPercentage(double percentage, {required BuildContext context}) {
Color color = AppColors.of(context).text;
percentage = percentage.round().toDouble();
if (percentage > 35) {
color = AppColors.of(context).red;
} else if (percentage > 25) {
color = AppColors.of(context).orange;
} else if (percentage > 15) {
color = AppColors.of(context).yellow;
}
return color.withOpacity(.8);
}

View File

@ -1,46 +0,0 @@
import 'package:filcnaplo_kreta_api/models/event.dart';
import 'package:filcnaplo/utils/format.dart';
import 'package:filcnaplo_mobile_ui/common/profile_image/profile_image.dart';
import 'package:flutter/material.dart';
class EventTile extends StatelessWidget {
const EventTile(this.event, {super.key, this.onTap, this.padding});
final Event event;
final void Function()? onTap;
final EdgeInsetsGeometry? padding;
@override
Widget build(BuildContext context) {
return Material(
color: Theme.of(context).colorScheme.background,
borderRadius: BorderRadius.circular(14.0),
child: Padding(
padding: padding ?? const EdgeInsets.symmetric(horizontal: 8.0),
child: ListTile(
visualDensity: VisualDensity.compact,
contentPadding: const EdgeInsets.only(left: 8.0, right: 12.0),
onTap: onTap,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14.0)),
leading: const ProfileImage(
name: "!",
radius: 22.0,
),
title: Text(
event.title,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontWeight: FontWeight.w600),
),
subtitle: Text(
event.content.escapeHtml().replaceAll('\n', ' '),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontWeight: FontWeight.w500),
),
minLeadingWidth: 0,
),
),
);
}
}

View File

@ -1,64 +0,0 @@
import 'package:filcnaplo/helpers/subject.dart';
import 'package:filcnaplo/theme/colors/colors.dart';
import 'package:filcnaplo_kreta_api/models/exam.dart';
import 'package:flutter/material.dart';
import 'package:filcnaplo/utils/format.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
class ExamTile extends StatelessWidget {
const ExamTile(this.exam, {super.key, this.onTap, this.padding});
final Exam exam;
final void Function()? onTap;
final EdgeInsetsGeometry? padding;
@override
Widget build(BuildContext context) {
return Material(
type: MaterialType.transparency,
child: Padding(
padding: padding ?? const EdgeInsets.symmetric(horizontal: 8.0),
child: ListTile(
visualDensity: VisualDensity.compact,
contentPadding: const EdgeInsets.only(left: 8.0, right: 12.0),
onTap: onTap,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(14.0)),
leading: SizedBox(
width: 44,
height: 44,
child: Padding(
padding: const EdgeInsets.only(top: 2.0),
child: Icon(
SubjectIcon.resolveVariant(
subject: exam.subject, context: context),
size: 28.0,
color: AppColors.of(context).text.withOpacity(.75),
),
)),
title: Text(
exam.description != ""
? exam.description
: (exam.mode?.description ?? "Számonkérés"),
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontWeight: FontWeight.w600),
),
subtitle: Text(
exam.subject.isRenamed
? exam.subject.renamedTo!
: exam.subject.name.capital(),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontWeight: FontWeight.w500),
),
trailing: Icon(
FeatherIcons.edit,
color: AppColors.of(context).text.withOpacity(.75),
),
minLeadingWidth: 0,
),
),
);
}
}

View File

@ -1,20 +0,0 @@
import 'package:filcnaplo_kreta_api/models/exam.dart';
import 'package:filcnaplo_mobile_ui/common/viewable.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/card_handle.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/exam/exam_tile.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/exam/exam_view.dart';
import 'package:flutter/material.dart';
class ExamViewable extends StatelessWidget {
const ExamViewable(this.exam, {super.key});
final Exam exam;
@override
Widget build(BuildContext context) {
return Viewable(
tile: ExamTile(exam),
view: CardHandle(child: ExamView(exam)),
);
}
}

View File

@ -1,115 +0,0 @@
import 'package:filcnaplo/helpers/subject.dart';
import 'package:filcnaplo/models/settings.dart';
import 'package:filcnaplo/theme/colors/colors.dart';
import 'package:filcnaplo_kreta_api/models/homework.dart';
import 'package:filcnaplo/utils/format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:provider/provider.dart';
class HomeworkTile extends StatelessWidget {
const HomeworkTile(this.homework,
{super.key, this.onTap, this.padding, this.censored = false});
final Homework homework;
final void Function()? onTap;
final EdgeInsetsGeometry? padding;
final bool censored;
@override
Widget build(BuildContext context) {
SettingsProvider settingsProvider = Provider.of<SettingsProvider>(context);
return Material(
color: Theme.of(context).colorScheme.background,
borderRadius: BorderRadius.circular(8.0),
child: Padding(
padding: padding ?? const EdgeInsets.symmetric(horizontal: 8.0),
child: ListTile(
visualDensity: VisualDensity.compact,
contentPadding: const EdgeInsets.only(left: 8.0, right: 12.0),
onTap: onTap,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),
leading: SizedBox(
width: 44,
height: 44,
child: censored
? Container(
decoration: BoxDecoration(
color: AppColors.of(context).text.withOpacity(.55),
borderRadius: BorderRadius.circular(60.0),
),
)
: Padding(
padding: const EdgeInsets.only(top: 2.0),
child: Icon(
SubjectIcon.resolveVariant(
subject: homework.subject, context: context),
size: 28.0,
color: AppColors.of(context).text.withOpacity(.75),
),
),
),
title: censored
? Wrap(
children: [
Container(
width: 160,
height: 15,
decoration: BoxDecoration(
color: AppColors.of(context).text.withOpacity(.85),
borderRadius: BorderRadius.circular(8.0),
),
),
],
)
: Text(
homework.subject.renamedTo ?? homework.subject.name.capital(),
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontWeight: FontWeight.w600,
fontStyle: homework.subject.isRenamed &&
settingsProvider.renamedSubjectsItalics
? FontStyle.italic
: null),
),
subtitle: censored
? Wrap(
children: [
Container(
width: 100,
height: 10,
decoration: BoxDecoration(
color: AppColors.of(context).text.withOpacity(.45),
borderRadius: BorderRadius.circular(8.0),
),
),
],
)
: Text(
homework.content.escapeHtml().replaceAll('\n', ' '),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontWeight: FontWeight.w500),
),
trailing: censored
? Container(
width: 15,
height: 15,
decoration: BoxDecoration(
color: AppColors.of(context).text.withOpacity(.45),
borderRadius: BorderRadius.circular(8.0),
),
)
: Icon(
FeatherIcons.home,
color: AppColors.of(context).text.withOpacity(.75),
),
minLeadingWidth: 0,
),
),
);
}
}

View File

@ -1,25 +0,0 @@
import 'package:filcnaplo_kreta_api/models/lesson.dart';
import 'package:filcnaplo_mobile_ui/common/viewable.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/card_handle.dart';
import 'package:filcnaplo/ui/widgets/lesson/lesson_tile.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/lesson/lesson_view.dart';
import 'package:flutter/material.dart';
class LessonViewable extends StatelessWidget {
const LessonViewable(this.lesson, {super.key, this.swapDesc = false});
final Lesson lesson;
final bool swapDesc;
@override
Widget build(BuildContext context) {
final tile = LessonTile(lesson, swapDesc: swapDesc);
if (lesson.subject.id == '' || tile.lesson.isEmpty) return tile;
return Viewable(
tile: tile,
view: CardHandle(child: LessonView(lesson)),
);
}
}

View File

@ -1,128 +0,0 @@
import 'package:filcnaplo/api/providers/user_provider.dart';
import 'package:filcnaplo/utils/color.dart';
import 'package:filcnaplo_kreta_api/models/message.dart';
import 'package:filcnaplo_mobile_ui/common/panel/panel.dart';
import 'package:filcnaplo_mobile_ui/common/profile_image/profile_image.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/message/attachment_tile.dart';
import 'package:flutter/material.dart';
import 'package:filcnaplo/utils/format.dart';
import 'package:flutter_custom_tabs/flutter_custom_tabs.dart';
// import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:flutter_linkify/flutter_linkify.dart';
import 'package:provider/provider.dart';
import 'message_view_tile.i18n.dart';
class MessageViewTile extends StatelessWidget {
const MessageViewTile(this.message, {super.key});
final Message message;
@override
Widget build(BuildContext context) {
UserProvider user = Provider.of<UserProvider>(context, listen: false);
String recipientLabel = "";
if (message.recipients.any((r) => r.name == user.student?.name)) {
recipientLabel = "me".i18n;
}
if (recipientLabel != "" && message.recipients.length > 1) {
recipientLabel += " +";
recipientLabel += message.recipients
.where((r) => r.name != user.student?.name)
.length
.toString();
}
if (recipientLabel == "") {
// note: convertint to set to remove duplicates
recipientLabel +=
message.recipients.map((r) => r.name).toSet().join(", ");
}
List<Widget> attachments = [];
for (var a in message.attachments) {
attachments.add(AttachmentTile(a));
}
return Padding(
padding: const EdgeInsets.symmetric(vertical: 12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Subject
Text(
message.subject,
softWrap: true,
maxLines: 10,
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 24.0,
),
),
// Author
ListTile(
visualDensity: VisualDensity.compact,
contentPadding: EdgeInsets.zero,
leading: ProfileImage(
name: message.author,
backgroundColor: ColorUtils.stringToColor(message.author),
),
title: Text(
message.author,
style: const TextStyle(fontWeight: FontWeight.w600),
overflow: TextOverflow.ellipsis,
maxLines: 2,
),
subtitle: Text(
"${"to".i18n} $recipientLabel",
style: const TextStyle(fontWeight: FontWeight.w500),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
trailing: const Row(
mainAxisSize: MainAxisSize.min,
children: [
// IconButton(
// onPressed: () {},
// icon: Icon(FeatherIcons.cornerUpLeft, color: AppColors.of(context).text),
// splashRadius: 24.0,
// padding: EdgeInsets.zero,
// visualDensity: VisualDensity.compact,
// ),
// IconButton(
// onPressed: () {},
// icon: Icon(FeatherIcons.share2, color: AppColors.of(context).text),
// splashRadius: 24.0,
// padding: EdgeInsets.zero,
// visualDensity: VisualDensity.compact,
// ),
],
),
),
// Content
Panel(
padding: const EdgeInsets.all(12.0),
child: SelectableLinkify(
text: message.content.escapeHtml(),
options: const LinkifyOptions(looseUrl: true, removeWww: true),
onOpen: (link) {
launch(link.url,
customTabsOption: CustomTabsOption(
toolbarColor: Theme.of(context).scaffoldBackgroundColor,
showPageTitle: true,
));
},
style: const TextStyle(fontWeight: FontWeight.w400),
),
),
// Attachments
...attachments,
],
),
);
}
}

View File

@ -1,55 +0,0 @@
import 'package:filcnaplo/utils/color.dart';
import 'package:filcnaplo_kreta_api/models/note.dart';
import 'package:filcnaplo_mobile_ui/common/profile_image/profile_image.dart';
import 'package:flutter/material.dart';
class NoteTile extends StatelessWidget {
const NoteTile(this.note, {super.key, this.onTap, this.padding});
final Note note;
final void Function()? onTap;
final EdgeInsetsGeometry? padding;
@override
Widget build(BuildContext context) {
return Material(
type: MaterialType.transparency,
child: Padding(
padding: padding ?? const EdgeInsets.symmetric(horizontal: 8.0),
child: ListTile(
visualDensity: VisualDensity.compact,
contentPadding: const EdgeInsets.only(left: 8.0, right: 12.0),
onTap: onTap,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(14.0)),
leading: ProfileImage(
name: (note.teacher.isRenamed
? note.teacher.renamedTo
: note.teacher.name) ??
'',
radius: 22.0,
backgroundColor: ColorUtils.stringToColor(
(note.teacher.isRenamed
? note.teacher.renamedTo
: note.teacher.name) ??
'',
),
),
title: Text(
note.title,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontWeight: FontWeight.w600),
),
subtitle: Text(
note.content.replaceAll('\n', ' '),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontWeight: FontWeight.w500),
),
minLeadingWidth: 0,
),
),
);
}
}

View File

@ -1,431 +0,0 @@
// ignore_for_file: no_leading_underscores_for_local_identifiers
import 'dart:math';
import 'package:animations/animations.dart';
import 'package:auto_size_text/auto_size_text.dart';
import 'package:filcnaplo/api/providers/update_provider.dart';
import 'package:filcnaplo/ui/date_widget.dart';
import 'package:filcnaplo_kreta_api/models/absence.dart';
import 'package:filcnaplo_kreta_api/models/lesson.dart';
import 'package:filcnaplo_kreta_api/models/subject.dart';
import 'package:filcnaplo_kreta_api/models/week.dart';
import 'package:filcnaplo_kreta_api/providers/absence_provider.dart';
import 'package:filcnaplo_kreta_api/providers/note_provider.dart';
import 'package:filcnaplo/api/providers/user_provider.dart';
import 'package:filcnaplo/theme/colors/colors.dart';
import 'package:filcnaplo_kreta_api/providers/timetable_provider.dart';
import 'package:filcnaplo_mobile_ui/common/action_button.dart';
import 'package:filcnaplo_mobile_ui/common/empty.dart';
import 'package:filcnaplo_mobile_ui/common/filter_bar.dart';
import 'package:filcnaplo_mobile_ui/common/panel/panel.dart';
import 'package:filcnaplo_mobile_ui/common/profile_image/profile_button.dart';
import 'package:filcnaplo_mobile_ui/common/profile_image/profile_image.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/absence/absence_subject_tile.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/absence/absence_viewable.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/statistics_tile.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/miss_tile.dart';
import 'package:filcnaplo_mobile_ui/pages/absences/absence_subject_view.dart';
import 'package:filcnaplo/ui/filter/sort.dart';
import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:provider/provider.dart';
import 'absences_page.i18n.dart';
enum AbsenceFilter { absences, delays, misses }
class SubjectAbsence {
GradeSubject subject;
List<Absence> absences;
double percentage;
SubjectAbsence(
{required this.subject, this.absences = const [], this.percentage = 0.0});
}
class AbsencesPage extends StatefulWidget {
const AbsencesPage({super.key});
@override
AbsencesPageState createState() => AbsencesPageState();
}
class AbsencesPageState extends State<AbsencesPage>
with TickerProviderStateMixin {
late UserProvider user;
late AbsenceProvider absenceProvider;
late TimetableProvider timetableProvider;
late NoteProvider noteProvider;
late UpdateProvider updateProvider;
late String firstName;
late TabController _tabController;
late List<SubjectAbsence> absences = [];
final Map<GradeSubject, Lesson> _lessonCount = {};
@override
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this);
timetableProvider = Provider.of<TimetableProvider>(context, listen: false);
WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
for (final lesson in timetableProvider.getWeek(Week.current()) ?? []) {
if (!lesson.isEmpty &&
lesson.subject.id != '' &&
lesson.lessonYearIndex != null) {
_lessonCount.update(
lesson.subject,
(value) {
if (lesson.lessonYearIndex! > value.lessonYearIndex!) {
return lesson;
} else {
return value;
}
},
ifAbsent: () => lesson,
);
}
}
setState(() {});
});
}
void buildSubjectAbsences() {
Map<GradeSubject, SubjectAbsence> _absences = {};
for (final absence in absenceProvider.absences) {
if (absence.delay != 0) continue;
if (!_absences.containsKey(absence.subject)) {
_absences[absence.subject] =
SubjectAbsence(subject: absence.subject, absences: [absence]);
} else {
_absences[absence.subject]?.absences.add(absence);
}
}
_absences.forEach((subject, absence) {
final absentLessonsOfSubject = absenceProvider.absences
.where((e) => e.subject == subject && e.delay == 0)
.length;
final totalLessonsOfSubject = _lessonCount[subject]?.lessonYearIndex ?? 0;
double absentLessonsOfSubjectPercentage;
if (absentLessonsOfSubject <= totalLessonsOfSubject) {
absentLessonsOfSubjectPercentage =
absentLessonsOfSubject / totalLessonsOfSubject * 100;
} else {
absentLessonsOfSubjectPercentage = -1;
}
_absences[subject]?.percentage =
absentLessonsOfSubjectPercentage.clamp(-1, 100.0);
});
absences = _absences.values.toList();
absences.sort((a, b) => -a.percentage.compareTo(b.percentage));
}
@override
Widget build(BuildContext context) {
user = Provider.of<UserProvider>(context);
absenceProvider = Provider.of<AbsenceProvider>(context);
noteProvider = Provider.of<NoteProvider>(context);
updateProvider = Provider.of<UpdateProvider>(context);
timetableProvider = Provider.of<TimetableProvider>(context);
List<String> nameParts = user.displayName?.split(" ") ?? ["?"];
firstName = nameParts.length > 1 ? nameParts[1] : nameParts[0];
buildSubjectAbsences();
return Scaffold(
body: Padding(
padding: const EdgeInsets.only(top: 12.0),
child: NestedScrollView(
physics: const BouncingScrollPhysics(
parent: AlwaysScrollableScrollPhysics()),
headerSliverBuilder: (context, _) => [
SliverAppBar(
pinned: true,
floating: false,
snap: false,
centerTitle: false,
surfaceTintColor: Theme.of(context).scaffoldBackgroundColor,
actions: [
// Profile Icon
Padding(
padding: const EdgeInsets.only(right: 24.0),
child: ProfileButton(
child: ProfileImage(
heroTag: "profile",
name: firstName,
backgroundColor: Theme.of(context)
.colorScheme
.primary, //ColorUtils.stringToColor(user.displayName ?? "?"),
badge: updateProvider.available,
role: user.role,
profilePictureString: user.picture,
),
),
),
],
automaticallyImplyLeading: false,
shadowColor: Theme.of(context).shadowColor,
title: Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Text(
"Absences".i18n,
style: TextStyle(
color: AppColors.of(context).text,
fontSize: 32.0,
fontWeight: FontWeight.bold),
),
),
bottom: FilterBar(
items: [
Tab(text: "Absences".i18n),
Tab(text: "Delays".i18n),
Tab(text: "Misses".i18n),
],
controller: _tabController,
disableFading: true,
),
),
],
body: TabBarView(
physics: const BouncingScrollPhysics(),
controller: _tabController,
children: List.generate(
3, (index) => filterViewBuilder(context, index))),
),
),
);
}
List<DateWidget> getFilterWidgets(AbsenceFilter activeData) {
List<DateWidget> items = [];
switch (activeData) {
case AbsenceFilter.absences:
for (var a in absences) {
items.add(DateWidget(
date: DateTime.fromMillisecondsSinceEpoch(0),
widget: AbsenceSubjectTile(
a.subject,
percentage: a.percentage,
excused: a.absences
.where((a) => a.state == Justification.excused)
.length,
unexcused: a.absences
.where((a) => a.state == Justification.unexcused)
.length,
pending: a.absences
.where((a) => a.state == Justification.pending)
.length,
onTap: () => AbsenceSubjectView.show(a.subject, a.absences,
context: context),
),
));
}
break;
case AbsenceFilter.delays:
for (var absence in absenceProvider.absences) {
if (absence.delay != 0) {
items.add(DateWidget(
date: absence.date,
widget: AbsenceViewable(absence, padding: EdgeInsets.zero),
));
}
}
break;
case AbsenceFilter.misses:
for (var note in noteProvider.notes) {
if (note.type?.name == "HaziFeladatHiany" ||
note.type?.name == "Felszereleshiany") {
items.add(DateWidget(
date: note.date,
widget: MissTile(note),
));
}
}
break;
}
return items;
}
Widget filterViewBuilder(context, int activeData) {
List<Widget> filterWidgets = [];
if (activeData > 0) {
filterWidgets = sortDateWidgets(
context,
dateWidgets: getFilterWidgets(AbsenceFilter.values[activeData]),
padding: EdgeInsets.zero,
hasShadow: true,
);
} else {
filterWidgets = [
Padding(
padding: const EdgeInsets.only(bottom: 24.0),
child: Panel(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("Subjects".i18n),
Padding(
padding: const EdgeInsets.only(right: 4.0),
child: IconButton(
onPressed: () {
showDialog(
context: context,
builder: (context) => AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0)),
title: Text("attention".i18n),
content: Text("attention_body".i18n),
actions: [
ActionButton(
label: "Ok",
onTap: () => Navigator.of(context).pop(),
),
],
),
);
},
padding: EdgeInsets.zero,
splashRadius: 24.0,
visualDensity: VisualDensity.compact,
constraints: BoxConstraints.tight(const Size(42.0, 42.0)),
icon: const Icon(FeatherIcons.info),
),
),
],
),
child: PageTransitionSwitcher(
transitionBuilder: (
Widget child,
Animation<double> primaryAnimation,
Animation<double> secondaryAnimation,
) {
return FadeThroughTransition(
animation: primaryAnimation,
secondaryAnimation: secondaryAnimation,
fillColor: Theme.of(context).colorScheme.background,
child: child,
);
},
child: Column(
children: getFilterWidgets(AbsenceFilter.values[activeData])
.map((e) => e.widget)
.cast<Widget>()
.toList(),
),
),
),
)
];
}
return Padding(
padding: const EdgeInsets.only(top: 12.0),
child: RefreshIndicator(
color: Theme.of(context).colorScheme.secondary,
onRefresh: () async {
await absenceProvider.fetch();
await noteProvider.fetch();
},
child: ListView.builder(
padding: EdgeInsets.zero,
physics: const BouncingScrollPhysics(),
itemCount: max(filterWidgets.length + (activeData <= 1 ? 1 : 0), 1),
itemBuilder: (context, index) {
if (filterWidgets.isNotEmpty) {
if ((index == 0 && activeData == 1) ||
(index == 0 && activeData == 0)) {
int value1 = 0;
int value2 = 0;
String title1 = "";
String title2 = "";
String suffix = "";
if (activeData == AbsenceFilter.absences.index) {
value1 = absenceProvider.absences
.where((e) =>
e.delay == 0 && e.state == Justification.excused)
.length;
value2 = absenceProvider.absences
.where((e) =>
e.delay == 0 && e.state == Justification.unexcused)
.length;
title1 = "stat_1".i18n;
title2 = "stat_2".i18n;
suffix = " ${"hr".i18n}";
} else if (activeData == AbsenceFilter.delays.index) {
value1 = absenceProvider.absences
.where((e) =>
e.delay != 0 && e.state == Justification.excused)
.map((e) => e.delay)
.fold(0, (a, b) => a + b);
value2 = absenceProvider.absences
.where((e) =>
e.delay != 0 && e.state == Justification.unexcused)
.map((e) => e.delay)
.fold(0, (a, b) => a + b);
title1 = "stat_3".i18n;
title2 = "stat_4".i18n;
suffix = " ${"min".i18n}";
}
return Padding(
padding: const EdgeInsets.only(
bottom: 24.0, left: 24.0, right: 24.0),
child: Row(children: [
Expanded(
child: StatisticsTile(
title: AutoSizeText(
title1,
textAlign: TextAlign.center,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
valueSuffix: suffix,
value: value1.toDouble(),
decimal: false,
color: AppColors.of(context).green,
),
),
const SizedBox(width: 24.0),
Expanded(
child: StatisticsTile(
title: AutoSizeText(
title2,
textAlign: TextAlign.center,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
valueSuffix: suffix,
value: value2.toDouble(),
decimal: false,
color: AppColors.of(context).red,
),
),
]),
);
}
return Padding(
padding:
const EdgeInsets.symmetric(horizontal: 24.0, vertical: 6.0),
child: filterWidgets[index - (activeData <= 1 ? 1 : 0)],
);
} else {
return Empty(subtitle: "empty".i18n);
}
},
),
),
);
}
}

View File

@ -1,60 +0,0 @@
import 'package:i18n_extension/i18n_extension.dart';
extension ScreensLocalization on String {
static final _t = Translations.byLocale("hu_hu") +
{
"en_en": {
"Absences": "Absences",
"Delays": "Delays",
"Misses": "Misses",
"empty": "You have no absences.",
"stat_1": "Excused Absences",
"stat_2": "Unexcused Absences",
"stat_3": "Excused Delay",
"stat_4": "Unexcused Delay",
"min": "min",
"hr": "hrs",
"Subjects": "Subjects",
"attention": "Attention!",
"attention_body": "Percentage calculations are only an approximation so they may not be accurate.",
"lesson_not_found": "Cannot find lesson",
},
"hu_hu": {
"Absences": "Hiányzások",
"Delays": "Késések",
"Misses": "Hiányok",
"empty": "Nincsenek hiányaid.",
"stat_1": "Igazolt hiányzások",
"stat_2": "Igazolatlan hiányzások",
"stat_3": "Igazolt Késés",
"stat_4": "Igazolatlan Késés",
"min": "perc",
"hr": "óra",
"Subjects": "Tantárgyak",
"attention": "Figyelem!",
"attention_body": "A százalékos számítások csak közelítések, ezért előfordulhat, hogy nem pontosak.",
"lesson_not_found": "Nem található óra",
},
"de_de": {
"Absences": "Fehlen",
"Delays": "Verspätung",
"Misses": "Fehlt",
"empty": "Sie haben keine Fehlen.",
"stat_1": "Entschuldigte Fehlen",
"stat_2": "Unentschuldigte Fehlen",
"stat_3": "Entschuldigte Verspätung",
"stat_4": "Unentschuldigte Verspätung",
"min": "min",
"hr": "hrs",
"Subjects": "Fächer",
"attention": "Achtung!",
"attention_body": "Prozentberechnungen sind nur eine Annäherung und können daher ungenau sein.",
"lesson_not_found": "Lektion kann nicht gefunden werden",
},
};
String get i18n => localize(this, _t);
String fill(List<Object> params) => localizeFill(this, params);
String plural(int value) => localizePlural(value, this, _t);
String version(Object modifier) => localizeVersion(modifier, this, _t);
}

View File

@ -1,367 +0,0 @@
import 'dart:math';
import 'package:animations/animations.dart';
import 'package:filcnaplo/api/providers/database_provider.dart';
import 'package:filcnaplo/api/providers/user_provider.dart';
import 'package:filcnaplo/models/settings.dart';
import 'package:filcnaplo/utils/format.dart';
// import 'package:filcnaplo_kreta_api/client/api.dart';
// import 'package:filcnaplo_kreta_api/client/client.dart';
import 'package:filcnaplo_kreta_api/providers/grade_provider.dart';
import 'package:filcnaplo/helpers/average_helper.dart';
import 'package:filcnaplo/helpers/subject.dart';
import 'package:filcnaplo_kreta_api/models/grade.dart';
import 'package:filcnaplo_kreta_api/models/subject.dart';
import 'package:filcnaplo_mobile_ui/common/average_display.dart';
import 'package:filcnaplo_mobile_ui/common/bottom_sheet_menu/rounded_bottom_sheet.dart';
import 'package:filcnaplo_mobile_ui/common/panel/panel.dart';
import 'package:filcnaplo_mobile_ui/common/trend_display.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/cretification/certification_tile.dart';
import 'package:filcnaplo/ui/widgets/grade/grade_tile.dart';
import 'package:filcnaplo_mobile_ui/common/widgets/grade/grade_viewable.dart';
import 'package:filcnaplo_mobile_ui/common/hero_scrollview.dart';
import 'package:filcnaplo_mobile_ui/pages/grades/calculator/grade_calculator.dart';
import 'package:filcnaplo_mobile_ui/pages/grades/calculator/grade_calculator_provider.dart';
import 'package:filcnaplo_mobile_ui/pages/grades/grades_count.dart';
import 'package:filcnaplo_mobile_ui/pages/grades/graph.dart';
import 'package:filcnaplo_mobile_ui/pages/grades/subject_grades_container.dart';
import 'package:filcnaplo_premium/ui/mobile/goal_planner/goal_planner_screen.dart';
import 'package:filcnaplo_premium/models/premium_scopes.dart';
import 'package:filcnaplo_premium/providers/premium_provider.dart';
import 'package:filcnaplo_premium/ui/mobile/goal_planner/goal_state_screen.dart';
import 'package:filcnaplo_premium/ui/mobile/premium/upsell.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_expandable_fab/flutter_expandable_fab.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:provider/provider.dart';
import 'grades_page.i18n.dart';
// import 'package:filcnaplo_premium/ui/mobile/goal_planner/new_goal.dart';
class GradeSubjectView extends StatefulWidget {
const GradeSubjectView(this.subject, {super.key, this.groupAverage = 0.0});
final GradeSubject subject;
final double groupAverage;
void push(BuildContext context, {bool root = false}) {
Navigator.of(context, rootNavigator: root)
.push(CupertinoPageRoute(builder: (context) => this));
}
@override
State<GradeSubjectView> createState() => _GradeSubjectViewState();
}
class _GradeSubjectViewState extends State<GradeSubjectView> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
// Controllers
PersistentBottomSheetController? _sheetController;
final ScrollController _scrollController = ScrollController();
List<Widget> gradeTiles = [];
// Providers
late GradeProvider gradeProvider;
late GradeCalculatorProvider calculatorProvider;
late SettingsProvider settingsProvider;
late DatabaseProvider dbProvider;
late UserProvider user;
late double average;
late Widget gradeGraph;
bool gradeCalcMode = false;
String plan = '';
List<Grade> getSubjectGrades(GradeSubject subject) => !gradeCalcMode
? gradeProvider.grades.where((e) => e.subject == subject).toList()
: calculatorProvider.grades.where((e) => e.subject == subject).toList();
bool showGraph(List<Grade> subjectGrades) {
if (gradeCalcMode) return true;
final gradeDates = subjectGrades.map((e) => e.date.millisecondsSinceEpoch);
final maxGradeDate = gradeDates.fold(0, max);
final minGradeDate = gradeDates.fold(0, min);
if (maxGradeDate - minGradeDate < const Duration(days: 5).inMilliseconds) {
return false; // naplo/#78
}
return subjectGrades.where((e) => e.type == GradeType.midYear).length > 1;
}
void buildTiles(List<Grade> subjectGrades) {
List<Widget> tiles = [];
if (showGraph(subjectGrades)) {
tiles.add(gradeGraph);
} else {
tiles.add(Container(height: 24.0));
}
tiles.add(Padding(
padding: const EdgeInsets.only(bottom: 24.0),
child: Panel(
child: GradesCount(grades: getSubjectGrades(widget.subject).toList()),
),
));
// ignore: no_leading_underscores_for_local_identifiers
List<Widget> _gradeTiles = [];
if (!gradeCalcMode) {
subjectGrades.sort((a, b) => -a.date.compareTo(b.date));
for (var grade in subjectGrades) {
if (grade.type == GradeType.midYear) {
_gradeTiles.add(GradeViewable(grade));
} else {
_gradeTiles.add(CertificationTile(grade, padding: EdgeInsets.zero));
}
}
} else if (subjectGrades.isNotEmpty) {
subjectGrades.sort((a, b) => -a.date.compareTo(b.date));
for (var grade in subjectGrades) {
_gradeTiles.add(GradeTile(grade));
}
}
tiles.add(
PageTransitionSwitcher(
transitionBuilder: (
Widget child,
Animation<double> primaryAnimation,
Animation<double> secondaryAnimation,
) {
return SharedAxisTransition(
animation: primaryAnimation,
secondaryAnimation: secondaryAnimation,
transitionType: SharedAxisTransitionType.vertical,
fillColor: Colors.transparent,
child: child,
);
},
child: _gradeTiles.isNotEmpty
? Panel(
key: ValueKey(gradeCalcMode),
title: Text(
gradeCalcMode ? "Ghost Grades".i18n : "Grades".i18n,
),
child: Column(
children: _gradeTiles,
))
: const SizedBox(),
),
);
tiles.add(Padding(
padding: EdgeInsets.only(bottom: !gradeCalcMode ? 24.0 : 250.0)));
gradeTiles = List.castFrom(tiles);
}
@override
void initState() {
super.initState();
user = Provider.of<UserProvider>(context, listen: false);
dbProvider = Provider.of<DatabaseProvider>(context, listen: false);
}
void fetchGoalPlans() async {
plan = (await dbProvider.userQuery
.subjectGoalPlans(userId: user.id!))[widget.subject.id] ??
'';
setState(() {});
}
@override
Widget build(BuildContext context) {
gradeProvider = Provider.of<GradeProvider>(context);
calculatorProvider = Provider.of<GradeCalculatorProvider>(context);
settingsProvider = Provider.of<SettingsProvider>(context);
List<Grade> subjectGrades = getSubjectGrades(widget.subject).toList();
average = AverageHelper.averageEvals(subjectGrades);
final prevAvg = subjectGrades.isNotEmpty
? AverageHelper.averageEvals(subjectGrades
.where((e) => e.date.isBefore(subjectGrades
.reduce((v, e) => e.date.isAfter(v.date) ? e : v)
.date
.subtract(const Duration(days: 30))))
.toList())
: 0.0;
gradeGraph = Padding(
padding: const EdgeInsets.only(top: 16.0, bottom: 8.0),
child: Panel(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("annual_average".i18n),
if (average != prevAvg)
TrendDisplay(current: average, previous: prevAvg),
],
),
child: Container(
padding: const EdgeInsets.only(top: 16.0, right: 12.0),
child: GradeGraph(subjectGrades,
dayThreshold: 5, classAvg: widget.groupAverage),
),
),
);
if (!gradeCalcMode) {
buildTiles(subjectGrades);
} else {
List<Grade> ghostGrades = calculatorProvider.ghosts
.where((e) => e.subject == widget.subject)
.toList();
buildTiles(ghostGrades);
}
fetchGoalPlans();
return Scaffold(
key: _scaffoldKey,
floatingActionButtonLocation: ExpandableFab.location,
floatingActionButton: Visibility(
visible: !gradeCalcMode &&
subjectGrades
.where((e) => e.type == GradeType.midYear)
.isNotEmpty,
child: ExpandableFab(
type: ExpandableFabType.up,
distance: 50,
childrenOffset: const Offset(-3.8, 0.0),
children: [
FloatingActionButton.small(
heroTag: "btn_ghost_grades",
backgroundColor: Theme.of(context).colorScheme.secondary,
onPressed: () {
gradeCalc(context);
},
child: const Icon(FeatherIcons.plus),
),
FloatingActionButton.small(
heroTag: "btn_goal_planner",
backgroundColor: Theme.of(context).colorScheme.secondary,
onPressed: () {
if (!Provider.of<PremiumProvider>(context, listen: false)
.hasScope(PremiumScopes.goalPlanner)) {
PremiumLockedFeatureUpsell.show(
context: context, feature: PremiumFeature.goalplanner);
return;
}
// ScaffoldMessenger.of(context).showSnackBar(
// const SnackBar(content: Text("Hamarosan...")));
Navigator.of(context).push(CupertinoPageRoute(
builder: (context) =>
GoalPlannerScreen(subject: widget.subject)));
},
child: const Icon(FeatherIcons.flag, size: 20.0),
),
],
),
),
body: RefreshIndicator(
onRefresh: () async {},
color: Theme.of(context).colorScheme.secondary,
child: HeroScrollView(
onClose: () {
if (_sheetController != null && gradeCalcMode) {
_sheetController!.close();
} else {
Navigator.of(context).pop();
}
},
navBarItems: [
const SizedBox(width: 6.0),
if (widget.groupAverage != 0)
Center(
child: AverageDisplay(
average: widget.groupAverage, border: true)),
const SizedBox(width: 6.0),
if (average != 0)
Center(child: AverageDisplay(average: average)),
const SizedBox(width: 6.0),
if (plan != '')
Center(
child: GestureDetector(
onTap: () {
Navigator.of(context).push(CupertinoPageRoute(
builder: (context) =>
GoalStateScreen(subject: widget.subject)));
},
child: Container(
width: 54.0,
padding: const EdgeInsets.symmetric(vertical: 8.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(45.0),
color: Theme.of(context)
.colorScheme
.primary
.withOpacity(.15),
),
child: Icon(
FeatherIcons.flag,
size: 17.0,
weight: 2.5,
color: Theme.of(context).colorScheme.primary,
),
),
),
),
const SizedBox(width: 12.0),
],
icon: SubjectIcon.resolveVariant(
subject: widget.subject, context: context),
scrollController: _scrollController,
title: widget.subject.renamedTo ?? widget.subject.name.capital(),
italic: settingsProvider.renamedSubjectsItalics &&
widget.subject.isRenamed,
child: SubjectGradesContainer(
child: CupertinoScrollbar(
child: ListView.builder(
physics: const BouncingScrollPhysics(),
padding: const EdgeInsets.symmetric(horizontal: 24.0),
shrinkWrap: true,
itemBuilder: (context, index) => gradeTiles[index],
itemCount: gradeTiles.length,
),
),
)),
));
}
void gradeCalc(BuildContext context) {
// Scroll to the top of the page
_scrollController.animateTo(100,
duration: const Duration(milliseconds: 500), curve: Curves.ease);
calculatorProvider.clear();
calculatorProvider.addAllGrades(gradeProvider.grades);
_sheetController = _scaffoldKey.currentState?.showBottomSheet(
(context) => RoundedBottomSheet(
borderRadius: 14.0, child: GradeCalculator(widget.subject)),
backgroundColor: const Color(0x00000000),
elevation: 12.0,
);
// Hide the fab and grades
setState(() {
gradeCalcMode = true;
});
_sheetController!.closed.then((value) {
// Show fab and grades
if (mounted) {
setState(() {
gradeCalcMode = false;
});
}
});
}
}

View File

@ -1,34 +0,0 @@
import 'package:filcnaplo/ui/widgets/grade/grade_tile.dart';
import 'package:filcnaplo_kreta_api/models/grade.dart';
import 'package:flutter/material.dart';
class GradesCountItem extends StatelessWidget {
const GradesCountItem({super.key, required this.count, required this.value});
final int count;
final int value;
@override
Widget build(BuildContext context) {
return Row(
children: [
Text.rich(
TextSpan(children: [
TextSpan(
text: count.toString(),
style: const TextStyle(fontWeight: FontWeight.w600),
),
const TextSpan(
text: "x",
style: TextStyle(fontSize: 13.0),
),
]),
style: const TextStyle(fontSize: 15.0),
),
const SizedBox(width: 5.0),
GradeValueWidget(GradeValue(value, "Value", "Value", 100),
size: 19.0, fill: true, shadow: false),
],
);
}
}

View File

@ -1,297 +0,0 @@
import 'package:animations/animations.dart';
import 'package:filcnaplo/api/providers/user_provider.dart';
import 'package:filcnaplo/helpers/subject.dart';
import 'package:filcnaplo/icons/filc_icons.dart';
import 'package:filcnaplo/models/settings.dart';
import 'package:filcnaplo_mobile_ui/pages/home/live_card/heads_up_countdown.dart';
import 'package:filcnaplo_mobile_ui/screens/summary/summary_screen.dart';
import 'package:flutter/material.dart';
import 'package:filcnaplo/utils/format.dart';
import 'package:filcnaplo/api/providers/live_card_provider.dart';
import 'package:filcnaplo_mobile_ui/pages/home/live_card/live_card_widget.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:i18n_extension/i18n_widget.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'live_card.i18n.dart';
class LiveCard extends StatefulWidget {
const LiveCard({super.key});
@override
LiveCardStateA createState() => LiveCardStateA();
}
class LiveCardStateA extends State<LiveCard> {
late void Function() listener;
late UserProvider _userProvider;
late LiveCardProvider liveCard;
@override
void initState() {
super.initState();
listener = () => setState(() {});
_userProvider = Provider.of<UserProvider>(context, listen: false);
liveCard = Provider.of<LiveCardProvider>(context, listen: false);
_userProvider.addListener(liveCard.update);
}
@override
void dispose() {
_userProvider.removeListener(liveCard.update);
super.dispose();
}
@override
Widget build(BuildContext context) {
liveCard = Provider.of<LiveCardProvider>(context);
SettingsProvider settingsProvider = Provider.of<SettingsProvider>(context);
if (!liveCard.show) return Container();
Widget child;
Duration bellDelay = liveCard.delay;
switch (liveCard.currentState) {
case LiveCardState.summary:
child = LiveCardWidget(
key: const Key('livecard.summary'),
title: 'Vége a tanévnek! 🥳',
icon: FeatherIcons.arrowRight,
description: Text(
'Irány az összefoglaláshoz',
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 18.0,
color: Theme.of(context).textTheme.bodyMedium?.color,
),
),
onTap: () {
// showSlidingBottomSheet(
// context,
// useRootNavigator: true,
// builder: (context) => SlidingSheetDialog(
// color: Colors.black.withOpacity(0.99),
// duration: const Duration(milliseconds: 400),
// scrollSpec: const ScrollSpec.bouncingScroll(),
// snapSpec: const SnapSpec(
// snap: true,
// snappings: [1.0],
// initialSnap: 1.0,
// positioning: SnapPositioning.relativeToAvailableSpace,
// ),
// minHeight: MediaQuery.of(context).size.height,
// cornerRadius: 16,
// cornerRadiusOnFullscreen: 0,
// builder: (context, state) => const Material(
// color: Colors.black,
// child: SummaryScreen(
// currentPage: 'start',
// ),
// ),
// ),
// );
SummaryScreen.show(context: context, currentPage: 'start');
},
);
break;
case LiveCardState.morning:
child = LiveCardWidget(
key: const Key('livecard.morning'),
title: DateFormat("EEEE", I18n.of(context).locale.toString())
.format(DateTime.now())
.capital(),
icon: FeatherIcons.sun,
description: liveCard.nextLesson != null
? Text.rich(
TextSpan(
children: [
TextSpan(text: "first_lesson_1".i18n),
TextSpan(
text: liveCard.nextLesson!.subject.renamedTo ??
liveCard.nextLesson!.subject.name.capital(),
style: TextStyle(
fontWeight: FontWeight.w600,
color: Theme.of(context)
.colorScheme
.secondary
.withOpacity(.85),
fontStyle: liveCard.nextLesson!.subject.isRenamed &&
settingsProvider.renamedSubjectsItalics
? FontStyle.italic
: null),
),
TextSpan(text: "first_lesson_2".i18n),
TextSpan(
text: liveCard.nextLesson!.room.capital(),
style: TextStyle(
fontWeight: FontWeight.w600,
color: Theme.of(context)
.colorScheme
.secondary
.withOpacity(.85),
),
),
TextSpan(text: "first_lesson_3".i18n),
TextSpan(
text: DateFormat('H:mm')
.format(liveCard.nextLesson!.start),
style: TextStyle(
fontWeight: FontWeight.w600,
color: Theme.of(context)
.colorScheme
.secondary
.withOpacity(.85),
),
),
TextSpan(text: "first_lesson_4".i18n),
],
),
)
: null,
);
break;
case LiveCardState.duringLesson:
final elapsedTime = DateTime.now()
.difference(liveCard.currentLesson!.start)
.inSeconds
.toDouble() +
bellDelay.inSeconds;
final maxTime = liveCard.currentLesson!.end
.difference(liveCard.currentLesson!.start)
.inSeconds
.toDouble();
final showMinutes = maxTime - elapsedTime > 60;
child = LiveCardWidget(
key: const Key('livecard.duringLesson'),
leading: liveCard.currentLesson!.lessonIndex +
(RegExp(r'\d').hasMatch(liveCard.currentLesson!.lessonIndex)
? "."
: ""),
title: liveCard.currentLesson!.subject.renamedTo ??
liveCard.currentLesson!.subject.name.capital(),
titleItalic: liveCard.currentLesson!.subject.isRenamed &&
settingsProvider.renamedSubjectsEnabled &&
settingsProvider.renamedSubjectsItalics,
subtitle: liveCard.currentLesson!.room,
icon: SubjectIcon.resolveVariant(
subject: liveCard.currentLesson!.subject, context: context),
description: liveCard.currentLesson!.description != ""
? Text(liveCard.currentLesson!.description)
: null,
nextSubject: liveCard.nextLesson?.subject.renamedTo ??
liveCard.nextLesson?.subject.name.capital(),
nextSubjectItalic: liveCard.nextLesson?.subject.isRenamed == true &&
settingsProvider.renamedSubjectsEnabled &&
settingsProvider.renamedSubjectsItalics,
nextRoom: liveCard.nextLesson?.room,
progressMax: showMinutes ? maxTime / 60 : maxTime,
progressCurrent: showMinutes ? elapsedTime / 60 : elapsedTime,
progressAccuracy:
showMinutes ? ProgressAccuracy.minutes : ProgressAccuracy.seconds,
onProgressTap: () {
showDialog(
barrierColor: Colors.black,
context: context,
builder: (context) =>
HeadsUpCountdown(maxTime: maxTime, elapsedTime: elapsedTime),
);
},
);
break;
case LiveCardState.duringBreak:
final iconFloorMap = {
"to room": FeatherIcons.chevronsRight,
"up floor": FilcIcons.upstairs,
"down floor": FilcIcons.downstairs,
"ground floor": FilcIcons.downstairs,
};
final diff = liveCard.getFloorDifference();
final maxTime = liveCard.nextLesson!.start
.difference(liveCard.prevLesson!.end)
.inSeconds
.toDouble();
final elapsedTime = DateTime.now()
.difference(liveCard.prevLesson!.end)
.inSeconds
.toDouble() +
bellDelay.inSeconds.toDouble();
final showMinutes = maxTime - elapsedTime > 60;
child = LiveCardWidget(
key: const Key('livecard.duringBreak'),
title: "break".i18n,
icon: iconFloorMap[diff],
description: liveCard.nextLesson!.room != liveCard.prevLesson!.room
? Text("go $diff".i18n.fill([
diff != "to room"
? (liveCard.nextLesson!.getFloor() ?? 0)
: liveCard.nextLesson!.room
]))
: Text("stay".i18n),
nextSubject: liveCard.nextLesson?.subject.renamedTo ??
liveCard.nextLesson?.subject.name.capital(),
nextSubjectItalic: liveCard.nextLesson?.subject.isRenamed == true &&
settingsProvider.renamedSubjectsItalics,
nextRoom: diff != "to room" ? liveCard.nextLesson?.room : null,
progressMax: showMinutes ? maxTime / 60 : maxTime,
progressCurrent: showMinutes ? elapsedTime / 60 : elapsedTime,
progressAccuracy:
showMinutes ? ProgressAccuracy.minutes : ProgressAccuracy.seconds,
onProgressTap: () {
showDialog(
barrierColor: Colors.black,
context: context,
builder: (context) => HeadsUpCountdown(
maxTime: maxTime,
elapsedTime: elapsedTime,
),
);
},
);
break;
case LiveCardState.afternoon:
child = LiveCardWidget(
key: const Key('livecard.afternoon'),
title: DateFormat("EEEE", I18n.of(context).locale.toString())
.format(DateTime.now())
.capital(),
icon: FeatherIcons.coffee,
);
break;
case LiveCardState.night:
child = LiveCardWidget(
key: const Key('livecard.night'),
title: DateFormat("EEEE", I18n.of(context).locale.toString())
.format(DateTime.now())
.capital(),
icon: FeatherIcons.moon,
);
break;
default:
child = Container();
}
return PageTransitionSwitcher(
transitionBuilder: (
Widget child,
Animation<double> primaryAnimation,
Animation<double> secondaryAnimation,
) {
return SharedAxisTransition(
animation: primaryAnimation,
secondaryAnimation: secondaryAnimation,
transitionType: SharedAxisTransitionType.horizontal,
fillColor: Theme.of(context).scaffoldBackgroundColor,
child: child,
);
},
child: child,
);
}
}

Some files were not shown because too many files have changed in this diff Show More