You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

82 lines
2.7 KiB

#include <db/FSWatcher.h>
#include <fstream>
#include <string>
#include <filesystem>
#include <io/debug.h>
#include <db/db.h>
#include <db/update.h>
#include <util/calendar_parsing.h>
bool is_ics(const std::filesystem::path filepath) {
return filepath.extension() == ".ics";
}
namespace db {
FSWatcher::FSWatcher(sql::Database *db, const std::string &directory) : m_db(db), m_directory(directory) {}
void FSWatcher::run() {
// Parse the directory to watch
std::filesystem::path path(m_directory);
// Set the event handler which will be used to process particular events
auto create_entry = [&](inotify::Notification notification) {
create_event(notification.path);
};
auto modify_entry = [&](inotify::Notification notification) {
modify_event(notification.path);
};
auto remove_entry = [&](inotify::Notification notification) {
delete_event(notification.path);
};
/*
auto handleUnexpectedNotification = [](inotify::Notification notification) {
std::cout << "Event " << notification.event << " on " << notification.path << " at "
<< notification.time.time_since_epoch().count()
<< " was triggered, but was not expected" << std::endl;
};
*/
auto file_creation = { inotify::Event::create };
auto file_deletion = { inotify::Event::remove };
auto file_modification = { inotify::Event::moved_to };
// The notifier is configured to watch the parsed path for the defined events. Particular files
// or paths can be ignored(once).
auto notifier = inotify::BuildNotifier()
.watchPathRecursively(path)
.onEvents(file_creation, create_entry)
.onEvents(file_modification, modify_entry)
.onEvents(file_deletion, remove_entry);
// The event loop is started in a separate thread context.
notifier.run();
}
void FSWatcher::create_event(const std::string event_file) {
if(!is_ics(event_file)) return;
ical::IcalObject* object = new ical::IcalObject();
util::parse_main_component(object, util::parse_ics_file(event_file), event_file);
DEBUG << "Created Event " << event_file;
db::insert_events(m_db, object);
}
void FSWatcher::modify_event(const std::string event_file) {
if(!is_ics(event_file)) return;
ical::IcalObject* object = new ical::IcalObject();
util::parse_main_component(object, util::parse_ics_file(event_file), event_file);
DEBUG << "Modified Event " << event_file;
db::insert_events(m_db, object);
}
void FSWatcher::delete_event(const std::string event_file) {
if(!is_ics(event_file)) return;
DEBUG << "Removing Event " << event_file;
db::remove_events(m_db, event_file);
}
}