Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion bin/pala.dart
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,8 @@ void main(List<String> arguments) async {

if (argResults['daemon']) {
await app.runDaemon();
exit(0);
// A failed login sets exitCode, so a scheduled run shows up as failed.
exit(exitCode);
}

if (argResults['demo']) {
Expand Down
4 changes: 4 additions & 0 deletions docs/USER.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ A főmenü "Beállítások" opciójában az alábbi funkciók érhetők el:
- Git-alapú jegytörténet: Lokális Git tárolóba mentés (`Pala_Jegyek_Git`).
- **Profilkezelés**: Váltás a mentett fiókok között.
- **Háttér-értesítések**: Windowson a Feladatütemezőbe kerül (`PalaDaemon`): a háttérben óránként és bejelentkezéskor ellenőrzi az új jegyeket, majd értesítést küld. Linuxon és macOS-en a `pala --daemon` parancsot magad ütemezheted (például cronnal), az értesítést a rendszer saját értesítési rendszere jeleníti meg.
- **Slack-értesítések**: a `pala --daemon` minden értesítést egy Slack csatornába is elküld, ha megadsz egy Incoming Webhook címet. Tedd a `PALA_SLACK_WEBHOOK` környezeti változóba, vagy írd a `~/.config/pala/slack_webhook` fájlba (`chmod 600`). Csak `https://hooks.slack.com/services/...` címet fogad el. Értesít az új jegyekről (tantárggyal és értékkel), az új házi feladatokról, minden új számonkérésről egyszer, a holnapi számonkérésről egyszer, valamint az elmaradt és helyettesített órákról. Az első futás csak megjegyzi a meglévő dolgozatokat, nem küldi el őket. Egy futás összes értesítése egyetlen Slack üzenetben érkezik.
- **Gemini összefoglaló**: ha megadsz egy Gemini API kulcsot (`PALA_GEMINI_API_KEY` vagy `~/.config/pala/gemini_key`), az új adatot tartalmazó Slack üzenet végére rövid magyar összefoglaló kerül. Új adat nélkül nincs üzenet és nincs API hívás. A modell a `PALA_GEMINI_MODEL` változóval állítható. A kérés csak a tantárgyakat, jegyeket, témákat, dátumokat, valamint a Moodle kurzusok és határidők nevét tartalmazza. A helyettesítő tanár neve és a Moodle értesítések szövege csak a Slack üzenetbe kerül, a Geminihez nem. Az ingyenes szint tartalmát a Google felhasználhatja a termékei fejlesztéséhez.
- **Moodle**: ha a `PALA_MOODLE_URL` be van állítva (például `https://moodle.iskolam.hu`), a futás az olvasatlan Moodle értesítéseket és a következő 14 nap határidejeit is ellenőrzi. Az első futás a `PALA_MOODLE_USER` és `PALA_MOODLE_PASSWORD` értékkel belép, és csak a tokent menti el. Csak jelszavas belépéssel működik (SSO nélkül), és a Moodle mobil szolgáltatásnak engedélyezettnek kell lennie.
- **Futtatás számítógép nélkül**: a `pala --daemon` egyetlen ellenőrzés után kilép, ezért ütemezett feladatból futtatható, például GitHub Actionsből. Sikertelen Kréta belépésnél Slack hibaüzenetet küld, és hibakóddal lép ki.

## 4. Komponensek, Rendszerintegráció & Eltávolítás
A Pala teljes komponenskezelési támogatással rendelkezik a parancssorból és a grafikus beállításokból is:
Expand Down
175 changes: 175 additions & 0 deletions lib/api/moodle_client.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:pala/utils/logger.dart';

/// One unread Moodle notification (grade posted, forum post, assignment
/// change, message).
class MoodleNotification {
final int id;
final String subject;
final DateTime? time;

const MoodleNotification({required this.id, required this.subject, this.time});
}

/// One upcoming Moodle deadline or calendar event.
class MoodleEvent {
final int id;
final String name;
final String? course;
final DateTime? due;

const MoodleEvent({required this.id, required this.name, this.course, this.due});
}

class MoodleLoginException implements Exception {
final String reason;
const MoodleLoginException(this.reason);
@override
String toString() => 'Moodle bejelentkezés sikertelen: $reason';
}

/// Read-only client for the Moodle mobile web service.
///
/// Login uses `login/token.php` with the `moodle_mobile_app` service. The
/// password is only sent to that endpoint, once, and the returned token is
/// kept instead. The school site must keep the mobile service enabled and use
/// plain username and password login (no SSO), otherwise [login] throws.
class MoodleClient {
final Uri baseUri;
final http.Client _client;
String? token;
int? userId;

MoodleClient(String baseUrl, {this.token, http.Client? client})
: baseUri = Uri.parse(baseUrl),
_client = client ?? http.Client();

/// The base url must be https and have a host, so a typo cannot send the
/// password over plain http or to a path-less value.
static bool isValidBaseUrl(String? url) {
if (url == null) return false;
final uri = Uri.tryParse(url);
return uri != null && uri.scheme == 'https' && uri.host.isNotEmpty;
}

Uri _endpoint(String path, [Map<String, String>? query]) {
final basePath = baseUri.path.endsWith('/') ? baseUri.path : '${baseUri.path}/';
return baseUri.replace(path: '$basePath$path', queryParameters: query);
}

Future<void> login(String username, String password) async {
// POST body, so the password never lands in a URL or in server logs.
final response = await _client
.post(
_endpoint('login/token.php'),
body: {'username': username, 'password': password, 'service': 'moodle_mobile_app'},
)
.timeout(const Duration(seconds: 20));
if (response.statusCode != 200) {
throw MoodleLoginException('HTTP ${response.statusCode}');
}
final data = jsonDecode(response.body);
if (data is Map && data['token'] is String) {
token = data['token'] as String;
return;
}
final reason = data is Map ? (data['error'] ?? data['errorcode'] ?? 'ismeretlen hiba') : 'ismeretlen válasz';
throw MoodleLoginException(reason.toString());
}

Future<dynamic> _call(String function, Map<String, String> params) async {
final response = await _client
.post(
_endpoint('webservice/rest/server.php'),
body: {
'wstoken': token ?? '',
'wsfunction': function,
'moodlewsrestformat': 'json',
...params,
},
)
.timeout(const Duration(seconds: 20));
if (response.statusCode != 200) {
PalaLogger.debug('Moodle $function: HTTP ${response.statusCode}');
return null;
}
final data = jsonDecode(response.body);
if (data is Map && data.containsKey('exception')) {
PalaLogger.debug('Moodle $function: ${data['errorcode']}');
// An invalid token means the caller has to log in again.
if (data['errorcode'] == 'invalidtoken') throw const MoodleLoginException('lejárt token');
return null;
}
return data;
}

Future<int?> getUserId() async {
if (userId != null) return userId;
final data = await _call('core_webservice_get_site_info', {});
if (data is Map && data['userid'] is int) {
userId = data['userid'] as int;
}
return userId;
}

/// Unread notifications of the logged-in user, newest first.
Future<List<MoodleNotification>?> getNotifications({int limit = 30}) async {
final uid = await getUserId();
if (uid == null) return null;
final data = await _call('message_popup_get_popup_notifications', {
'useridto': '$uid',
'limit': '$limit',
'offset': '0',
});
return parseNotifications(data);
}

static List<MoodleNotification>? parseNotifications(dynamic data) {
if (data is! Map || data['notifications'] is! List) return null;
final result = <MoodleNotification>[];
for (final n in data['notifications'] as List) {
if (n is! Map || n['id'] is! int) continue;
final read = n['read'] == true;
if (read) continue;
final created = n['timecreated'];
result.add(MoodleNotification(
id: n['id'] as int,
subject: (n['subject'] ?? n['shortenedsubject'] ?? '').toString(),
time: created is int ? DateTime.fromMillisecondsSinceEpoch(created * 1000) : null,
));
}
return result;
}

/// Deadlines and action events from now to [days] days ahead.
Future<List<MoodleEvent>?> getUpcomingEvents({int days = 14, DateTime? now}) async {
final from = (now ?? DateTime.now()).millisecondsSinceEpoch ~/ 1000;
final to = from + days * 86400;
final data = await _call('core_calendar_get_action_events_by_timesort', {
'timesortfrom': '$from',
'timesortto': '$to',
'limitnum': '50',
});
return parseEvents(data);
}

static List<MoodleEvent>? parseEvents(dynamic data) {
if (data is! Map || data['events'] is! List) return null;
final result = <MoodleEvent>[];
for (final e in data['events'] as List) {
if (e is! Map || e['id'] is! int) continue;
final sort = e['timesort'];
final course = e['course'];
result.add(MoodleEvent(
id: e['id'] as int,
name: (e['name'] ?? '').toString(),
course: course is Map ? course['fullname']?.toString() : null,
due: sort is int ? DateTime.fromMillisecondsSinceEpoch(sort * 1000) : null,
));
}
result.sort((a, b) => (a.due ?? DateTime(9999)).compareTo(b.due ?? DateTime(9999)));
return result;
}
}
24 changes: 23 additions & 1 deletion lib/app/cli_app.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import 'package:interact/interact.dart';
import 'package:pala/api/api.dart';
import 'package:pala/api/client.dart';
import 'package:pala/api/demo_client.dart';
import 'package:pala/api/moodle_client.dart';
import 'package:pala/models/models.dart';
import 'package:pala/rules/absence_rules.dart';
import 'package:pala/rules/grade_rules.dart';
Expand All @@ -28,6 +29,8 @@ import 'package:pala/app/tui/screen_buffer.dart';
import 'package:pala/app/tui/tui_state.dart';
import 'package:pala/app/tui/tui_views.dart';
import 'package:pala/utils/logger.dart';
import 'package:pala/utils/gemini_summarizer.dart';
import 'package:pala/utils/slack_notifier.dart';
import 'package:pala/utils/win32_console.dart';
import 'package:pala/version.dart';
import 'package:path/path.dart' as p;
Expand Down Expand Up @@ -63,6 +66,12 @@ class PalaApp {
}

KretaClient? _client;

/// Alert lines of the current daemon run. While it is non-null, Slack gets
/// one combined message at the end (with the optional Gemini summary)
/// instead of one message per alert. [gemini] is the same alert without
/// names or free text, the only form that goes to the Gemini prompt.
List<({String slack, String gemini})>? _runAlerts;
String? studentUid;

File _getAuthFile() {
Expand Down Expand Up @@ -144,9 +153,22 @@ class PalaApp {

Future<void> runDaemon() async {
if (!await _tryAutoLogin()) {
// A scheduled run has no one watching it, so say on Slack that the
// login failed instead of failing silently.
await SlackNotifier.fromConfig(AppState.instance.configDir)
.send('Pala (hiba)', 'A Kréta bejelentkezés nem sikerült. Jelentkezz be újra a Palában.');
exitCode = 1;
return;
}
await _checkNewItems();
_runAlerts = [];
try {
await _checkNewItems();
await _checkMoodle();
} finally {
final alerts = _runAlerts!;
_runAlerts = null;
await _flushAlertsToSlack(alerts);
}
}

void _showBanner() {
Expand Down
Loading
Loading