package envoy.client.data; import java.io.*; import java.nio.channels.*; import java.nio.file.StandardOpenOption; import java.time.Instant; import java.util.*; import java.util.logging.Level; import envoy.client.event.EnvoyCloseEvent; import envoy.data.*; import envoy.event.*; import envoy.exception.EnvoyException; import envoy.util.*; import dev.kske.eventbus.Event; import dev.kske.eventbus.EventBus; import dev.kske.eventbus.EventListener; /** * Stores information about the current {@link User} and their {@link Chat}s. * For message ID generation a {@link IDGenerator} is stored as well. *

* The managed objects are stored inside a folder in the local file system. *

* Project: envoy-client
* File: LocalDB.java
* Created: 3 Feb 2020
* * @author Kai S. K. Engelbart * @since Envoy Client v0.3-alpha */ public final class LocalDB implements EventListener { // Data private User user; private Map users = Collections.synchronizedMap(new HashMap<>()); private List chats = Collections.synchronizedList(new ArrayList<>()); private IDGenerator idGenerator; private CacheMap cacheMap = new CacheMap(); private String authToken; // State management private Instant lastSync = Instant.EPOCH; // Persistence private File userFile; private FileLock instanceLock; private final File dbDir, idGeneratorFile, lastLoginFile, usersFile; /** * Constructs an empty local database. * * @param dbDir the directory in which to persist data * @throws IOException if {@code dbDir} is a file (and not a directory) * @throws EnvoyException if {@code dbDir} is in use by another Envoy instance * @since Envoy Client v0.2-beta */ public LocalDB(File dbDir) throws IOException, EnvoyException { this.dbDir = dbDir; EventBus.getInstance().registerListener(this); // Ensure that the database directory exists if (!dbDir.exists()) dbDir.mkdirs(); else if (!dbDir.isDirectory()) throw new IOException(String.format("LocalDBDir '%s' is not a directory!", dbDir.getAbsolutePath())); // Lock the directory lock(); // Initialize global files idGeneratorFile = new File(dbDir, "id_gen.db"); lastLoginFile = new File(dbDir, "last_login.db"); usersFile = new File(dbDir, "users.db"); // Load global files loadGlobalData(); // Initialize offline caches cacheMap.put(Message.class, new Cache<>()); cacheMap.put(MessageStatusChange.class, new Cache<>()); } /** * Ensured that only one Envoy instance is using this local database by creating * a lock file. * The lock file is deleted on application exit. * * @throws EnvoyException if the lock cannot by acquired * @since Envoy Client v0.2-beta */ private synchronized void lock() throws EnvoyException { final var file = new File(dbDir, "instance.lock"); try { final var fc = FileChannel.open(file.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); instanceLock = fc.tryLock(); if (instanceLock == null) throw new EnvoyException("Another Envoy instance is using this local database!"); } catch (final IOException e) { throw new EnvoyException("Could not create lock file!", e); } } /** * Loads the local user registry {@code users.db}, the id generator * {@code id_gen.db} and last login file {@code last_login.db}. * * @since Envoy Client v0.2-beta */ private synchronized void loadGlobalData() { try { try (var in = new ObjectInputStream(new FileInputStream(usersFile))) { users = (Map) in.readObject(); } idGenerator = SerializationUtils.read(idGeneratorFile, IDGenerator.class); try (var in = new ObjectInputStream(new FileInputStream(lastLoginFile))) { user = (User) in.readObject(); authToken = (String) in.readObject(); } } catch (IOException | ClassNotFoundException e) {} } /** * Loads all data of the client user. * * @throws ClassNotFoundException if the loading process failed * @throws IOException if the loading process failed * @since Envoy Client v0.3-alpha */ public synchronized void loadUserData() throws ClassNotFoundException, IOException { if (user == null) throw new IllegalStateException("Client user is null, cannot initialize user storage"); userFile = new File(dbDir, user.getID() + ".db"); try (var in = new ObjectInputStream(new FileInputStream(userFile))) { chats = (List) in.readObject(); cacheMap = (CacheMap) in.readObject(); lastSync = (Instant) in.readObject(); } synchronize(); } /** * Synchronizes the contact list of the client user with the chat and user * storage. * * @since Envoy Client v0.1-beta */ private void synchronize() { user.getContacts().stream().filter(u -> u instanceof User && !users.containsKey(u.getName())).forEach(u -> users.put(u.getName(), (User) u)); users.put(user.getName(), user); // Synchronize user status data for (final var contact : users.values()) if (contact instanceof User) getChat(contact.getID()).ifPresent(chat -> { ((User) chat.getRecipient()).setStatus(contact.getStatus()); }); // Create missing chats user.getContacts() .stream() .filter(c -> !c.equals(user) && getChat(c.getID()).isEmpty()) .map(c -> c instanceof User ? new Chat(c) : new GroupChat(user, c)) .forEach(chats::add); } /** * Stores all users. If the client user is specified, their chats will be stored * as well. The message id generator will also be saved if present. * * @throws IOException if the saving process failed * @since Envoy Client v0.3-alpha */ @Event(eventType = EnvoyCloseEvent.class, priority = 1000) private synchronized void save() { EnvoyLog.getLogger(LocalDB.class).log(Level.INFO, "Saving local database..."); // Save users try { SerializationUtils.write(usersFile, users); // Save user data and last sync time stamp if (user != null) SerializationUtils.write(userFile, chats, cacheMap, Context.getInstance().getClient().isOnline() ? Instant.now() : lastSync); // Save last login information if (authToken != null) SerializationUtils.write(lastLoginFile, user, authToken); // Save ID generator if (hasIDGenerator()) SerializationUtils.write(idGeneratorFile, idGenerator); } catch (final IOException e) { EnvoyLog.getLogger(LocalDB.class).log(Level.SEVERE, "Unable to save local database: ", e); } } @Event private void onNewAuthToken(NewAuthToken evt) { authToken = evt.get(); } /** * @return a {@code Map} of all users stored locally with their * user names as keys * @since Envoy Client v0.2-alpha */ public Map getUsers() { return users; } /** * @return all saved {@link Chat} objects that list the client user as the * sender * @since Envoy Client v0.1-alpha **/ public List getChats() { return chats; } /** * @param chats the chats to set */ public void setChats(List chats) { this.chats = chats; } /** * @return the {@link User} who initialized the local database * @since Envoy Client v0.2-alpha */ public User getUser() { return user; } /** * @param user the user to set * @since Envoy Client v0.2-alpha */ public void setUser(User user) { this.user = user; } /** * @return the message ID generator * @since Envoy Client v0.3-alpha */ public IDGenerator getIDGenerator() { return idGenerator; } /** * @param idGenerator the message ID generator to set * @since Envoy Client v0.3-alpha */ public void setIDGenerator(IDGenerator idGenerator) { this.idGenerator = idGenerator; } /** * @return {@code true} if an {@link IDGenerator} is present * @since Envoy Client v0.3-alpha */ public boolean hasIDGenerator() { return idGenerator != null; } /** * @return the cache map for messages and message status changes * @since Envoy Client v0.1-beta */ public CacheMap getCacheMap() { return cacheMap; } /** * @return the time stamp when the database was last saved * @since Envoy Client v0.2-beta */ public Instant getLastSync() { return lastSync; } /** * @return the authentication token of the user * @since Envoy Client v0.2-beta */ public String getAuthToken() { return authToken; } /** * Searches for a message by ID. * * @param id the ID of the message to search for * @return an optional containing the message * @since Envoy Client v0.1-beta */ public Optional getMessage(long id) { return chats.stream().map(Chat::getMessages).flatMap(List::stream).filter(m -> m.getID() == id).findAny(); } /** * Searches for a chat by recipient ID. * * @param recipientID the ID of the chat's recipient * @return an optional containing the chat * @since Envoy Client v0.1-beta */ public Optional getChat(long recipientID) { return chats.stream().filter(c -> c.getRecipient().getID() == recipientID).findAny(); } /** * Performs a contact name change if the corresponding contact is present. * * @param event the {@link NameChange} to process * @since Envoy Client v0.1-beta */ public void replaceContactName(NameChange event) { chats.stream().map(Chat::getRecipient).filter(c -> c.getID() == event.getID()).findAny().ifPresent(c -> c.setName(event.get())); } /** * Performs a group resize operation if the corresponding group is present. * * @param event the {@link GroupResize} to process * @since Envoy Client v0.1-beta */ public void updateGroup(GroupResize event) { chats.stream() .map(Chat::getRecipient) .filter(Group.class::isInstance) .filter(g -> g.getID() == event.getGroupID() && g.getID() != user.getID()) .map(Group.class::cast) .findAny() .ifPresent(group -> { switch (event.getOperation()) { case ADD: group.getContacts().add(event.get()); break; case REMOVE: group.getContacts().remove(event.get()); break; } }); } }