Search in sources :

Example 6 with PacketCollection

use of me.retrodaredevil.solarthing.packets.collection.PacketCollection in project solarthing by wildmountainfarms.

the class CommandManager method makeCreator.

/**
 * @param instanceTargetPacket The {@link InstanceTargetPacket} to indicate which fragments to target or null. If null, it is not added to the packet collection
 * @param commandOpenPacket The command packet
 * @return A creator to make a packet collection. When supplied with an {@link Instant} representing now, a packet collection is created.
 */
public PacketCollectionCreator makeCreator(String sourceId, ZoneId zoneId, @Nullable InstanceTargetPacket instanceTargetPacket, CommandOpenPacket commandOpenPacket, PacketCollectionIdGenerator packetCollectionIdGenerator) {
    // instanceTargetPacket may be null
    KeyPair keyPair = getKeyPair();
    InstanceSourcePacket instanceSourcePacket = InstanceSourcePackets.create(sourceId);
    // ----
    return now -> {
        PacketCollection packetCollectionToNestAndEncrypt = PacketCollections.create(now, instanceTargetPacket == null ? Arrays.asList(commandOpenPacket, instanceSourcePacket) : Arrays.asList(commandOpenPacket, instanceSourcePacket, instanceTargetPacket), "unused document ID that does not get serialized");
        // Note, on packetCollectionToNestAndEncrypt, _id is not serialized, so the generator and zoneId used above do NOT affect anything
        final String payload;
        try {
            payload = MAPPER.writeValueAsString(packetCollectionToNestAndEncrypt);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        String hashString = Long.toHexString(now.toEpochMilli()) + "," + HashUtil.encodedHash(payload);
        final String encrypted;
        try {
            synchronized (CIPHER) {
                // It's possible we could be in a multi-threaded environment, and you cannot have multiple threads using a single cipher at once
                encrypted = Encrypt.encrypt(CIPHER, keyPair.getPrivate(), hashString);
            }
        } catch (InvalidKeyException | EncryptException e) {
            throw new RuntimeException(e);
        }
        List<Packet> packets = new ArrayList<>(Arrays.asList(new ImmutableLargeIntegrityPacket(sender, encrypted, payload), instanceSourcePacket));
        if (instanceTargetPacket != null) {
            packets.add(instanceTargetPacket);
        }
        return PacketCollections.createFromPackets(now, packets, packetCollectionIdGenerator, zoneId);
    };
}
Also used : Packet(me.retrodaredevil.solarthing.packets.Packet) KeyPair(java.security.KeyPair) NoSuchFileException(java.nio.file.NoSuchFileException) Arrays(java.util.Arrays) me.retrodaredevil.solarthing.packets.security.crypto(me.retrodaredevil.solarthing.packets.security.crypto) LoggerFactory(org.slf4j.LoggerFactory) ImmutableLargeIntegrityPacket(me.retrodaredevil.solarthing.packets.security.ImmutableLargeIntegrityPacket) Cipher(javax.crypto.Cipher) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) Nullable(me.retrodaredevil.solarthing.annotations.Nullable) InstanceSourcePacket(me.retrodaredevil.solarthing.packets.instance.InstanceSourcePacket) Objects.requireNonNull(java.util.Objects.requireNonNull) JacksonUtil(me.retrodaredevil.solarthing.util.JacksonUtil) Logger(org.slf4j.Logger) PacketCollectionCreator(me.retrodaredevil.solarthing.packets.collection.PacketCollectionCreator) Files(java.nio.file.Files) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) StandardOpenOption(java.nio.file.StandardOpenOption) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) PublicKey(java.security.PublicKey) Instant(java.time.Instant) PacketCollectionIdGenerator(me.retrodaredevil.solarthing.packets.collection.PacketCollectionIdGenerator) File(java.io.File) ZoneId(java.time.ZoneId) PacketCollections(me.retrodaredevil.solarthing.packets.collection.PacketCollections) InstanceSourcePackets(me.retrodaredevil.solarthing.packets.instance.InstanceSourcePackets) List(java.util.List) PrivateKey(java.security.PrivateKey) PacketCollection(me.retrodaredevil.solarthing.packets.collection.PacketCollection) InstanceTargetPacket(me.retrodaredevil.solarthing.packets.instance.InstanceTargetPacket) CommandOpenPacket(me.retrodaredevil.solarthing.commands.packets.open.CommandOpenPacket) KeyPair(java.security.KeyPair) PacketCollection(me.retrodaredevil.solarthing.packets.collection.PacketCollection) InstanceSourcePacket(me.retrodaredevil.solarthing.packets.instance.InstanceSourcePacket) ArrayList(java.util.ArrayList) List(java.util.List) ImmutableLargeIntegrityPacket(me.retrodaredevil.solarthing.packets.security.ImmutableLargeIntegrityPacket) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 7 with PacketCollection

use of me.retrodaredevil.solarthing.packets.collection.PacketCollection in project solarthing by wildmountainfarms.

the class PacketListReceiverHandler method uploadSimple.

/**
 * This method is used to be able to upload packets in a simple way without dealing with {@link PacketListReceiver}s.
 * <p>
 * If {@code packets} is empty, this method does nothing. If not empty, it may add additional packets, turn into a {@link PacketCollection},
 * then "handles" the {@link PacketCollection}, which usually means to persist the {@link PacketCollection} in a database.
 * @param packets The packets to upload
 */
public void uploadSimple(Instant now, List<? extends Packet> packets) {
    List<Packet> mutablePackets = new ArrayList<>(packets);
    if (mutablePackets.isEmpty()) {
        return;
    }
    // this call may mutate mutablePackets, which is why we need it in the first place
    packetListReceiver.receive(mutablePackets);
    PacketCollection packetCollection = PacketCollections.createFromPackets(now, mutablePackets, idGenerator, zoneId);
    handleSinglePacketCollection(packetCollection);
}
Also used : Packet(me.retrodaredevil.solarthing.packets.Packet) PacketCollection(me.retrodaredevil.solarthing.packets.collection.PacketCollection) ArrayList(java.util.ArrayList)

Example 8 with PacketCollection

use of me.retrodaredevil.solarthing.packets.collection.PacketCollection in project solarthing by wildmountainfarms.

the class PacketListReceiverHandler method pack.

public void pack() {
    if (packetList.isEmpty()) {
        return;
    }
    packetListReceiver.receive(packetList);
    Instant now = Instant.now();
    PacketCollection packetCollection = PacketCollections.createFromPackets(now, packetList, idGenerator, zoneId);
    packetList.clear();
    packetCollectionList.add(packetCollection);
}
Also used : PacketCollection(me.retrodaredevil.solarthing.packets.collection.PacketCollection) Instant(java.time.Instant)

Example 9 with PacketCollection

use of me.retrodaredevil.solarthing.packets.collection.PacketCollection in project solarthing by wildmountainfarms.

the class FlagCommandChatBotHandler method clearFlag.

private void clearFlag(MessageSender messageSender, String flagName) {
    List<VersionedPacket<StoredAlterPacket>> packets = getPacketsWithFlagName(flagName);
    if (packets == null) {
        messageSender.sendMessage("Could not get flags. Please try again.");
        return;
    }
    Instant now = Instant.now();
    if (packets.isEmpty()) {
        messageSender.sendMessage("Flag: '" + flagName + "' is not set!");
        return;
    }
    List<VersionedPacket<StoredAlterPacket>> activePackets = packets.stream().filter(versionedPacket -> {
        FlagPacket flagPacket = (FlagPacket) versionedPacket.getPacket().getPacket();
        return flagPacket.getFlagData().getActivePeriod().isActive(now);
    }).collect(Collectors.toList());
    if (activePackets.isEmpty()) {
        messageSender.sendMessage("Flag: '" + flagName + "' is not currently active. In a future update we may allow you to clear inactive flags.");
        return;
    }
    // We know that the user wants this flag cleared, so let's delete all the packets that are active.
    for (VersionedPacket<StoredAlterPacket> packetToRequestDeleteFor : activePackets) {
        DeleteAlterPacket deleteAlterPacket = new ImmutableDeleteAlterPacket(packetToRequestDeleteFor.getPacket().getDbId(), packetToRequestDeleteFor.getUpdateToken());
        PacketCollectionCreator creator = commandHelper.getCommandManager().makeCreator(sourceId, zoneId, null, deleteAlterPacket, PacketCollectionIdGenerator.Defaults.UNIQUE_GENERATOR);
        PacketCollection packetCollection = creator.create(now);
        boolean success = false;
        try {
            database.getOpenDatabase().uploadPacketCollection(packetCollection, null);
            success = true;
        } catch (SolarThingDatabaseException e) {
            LOGGER.error("Could not upload request to delete alter packet for ID: " + packetToRequestDeleteFor.getPacket().getDbId(), e);
        }
        if (success) {
            messageSender.sendMessage("Requested delete for flag: '" + flagName + "' under ID: " + packetToRequestDeleteFor.getPacket().getDbId());
        } else {
            messageSender.sendMessage("Could not request delete for flag: '" + flagName + "' under ID: " + packetToRequestDeleteFor.getPacket().getDbId() + ". See logs for details.");
        }
    }
}
Also used : Arrays(java.util.Arrays) AlterPacketsProvider(me.retrodaredevil.solarthing.AlterPacketsProvider) LoggerFactory(org.slf4j.LoggerFactory) NotNull(me.retrodaredevil.solarthing.annotations.NotNull) MessageSender(me.retrodaredevil.solarthing.message.MessageSender) VersionedPacket(me.retrodaredevil.solarthing.database.VersionedPacket) RequestFlagPacket(me.retrodaredevil.solarthing.commands.packets.open.RequestFlagPacket) FlagData(me.retrodaredevil.solarthing.type.alter.flag.FlagData) Nullable(me.retrodaredevil.solarthing.annotations.Nullable) DeleteAlterPacket(me.retrodaredevil.solarthing.commands.packets.open.DeleteAlterPacket) FlagPacket(me.retrodaredevil.solarthing.type.alter.packets.FlagPacket) ExecutorService(java.util.concurrent.ExecutorService) Logger(org.slf4j.Logger) PacketCollectionCreator(me.retrodaredevil.solarthing.packets.collection.PacketCollectionCreator) SolarThingDatabase(me.retrodaredevil.solarthing.database.SolarThingDatabase) Instant(java.time.Instant) StoredAlterPacket(me.retrodaredevil.solarthing.type.alter.StoredAlterPacket) Collectors(java.util.stream.Collectors) PacketCollectionIdGenerator(me.retrodaredevil.solarthing.packets.collection.PacketCollectionIdGenerator) ZoneId(java.time.ZoneId) Executors(java.util.concurrent.Executors) AlterPacket(me.retrodaredevil.solarthing.type.alter.AlterPacket) List(java.util.List) TimeRange(me.retrodaredevil.solarthing.util.TimeRange) TimeRangeActivePeriod(me.retrodaredevil.solarthing.type.alter.flag.TimeRangeActivePeriod) ImmutableRequestFlagPacket(me.retrodaredevil.solarthing.commands.packets.open.ImmutableRequestFlagPacket) Collections(java.util.Collections) ImmutableDeleteAlterPacket(me.retrodaredevil.solarthing.commands.packets.open.ImmutableDeleteAlterPacket) PacketCollection(me.retrodaredevil.solarthing.packets.collection.PacketCollection) SolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.SolarThingDatabaseException) RequestFlagPacket(me.retrodaredevil.solarthing.commands.packets.open.RequestFlagPacket) FlagPacket(me.retrodaredevil.solarthing.type.alter.packets.FlagPacket) ImmutableRequestFlagPacket(me.retrodaredevil.solarthing.commands.packets.open.ImmutableRequestFlagPacket) StoredAlterPacket(me.retrodaredevil.solarthing.type.alter.StoredAlterPacket) ImmutableDeleteAlterPacket(me.retrodaredevil.solarthing.commands.packets.open.ImmutableDeleteAlterPacket) PacketCollection(me.retrodaredevil.solarthing.packets.collection.PacketCollection) VersionedPacket(me.retrodaredevil.solarthing.database.VersionedPacket) Instant(java.time.Instant) SolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.SolarThingDatabaseException) DeleteAlterPacket(me.retrodaredevil.solarthing.commands.packets.open.DeleteAlterPacket) ImmutableDeleteAlterPacket(me.retrodaredevil.solarthing.commands.packets.open.ImmutableDeleteAlterPacket) PacketCollectionCreator(me.retrodaredevil.solarthing.packets.collection.PacketCollectionCreator)

Example 10 with PacketCollection

use of me.retrodaredevil.solarthing.packets.collection.PacketCollection in project solarthing by wildmountainfarms.

the class CommandUtil method getCommandRequesterHandlerList.

/**
 * Gets packet handlers that will download requested commands
 * @param databaseConfigs The list of database configs
 * @param packetGroupReceiver Receives data that has been downloaded. Note that this may be called in a separate thread, so make sure it is thread safe
 * @param options The options object
 * @return A list of packet handlers that, when called, will possibly download commands and then forward those commands to {@code packetGroupReceiver}
 */
public static List<PacketHandler> getCommandRequesterHandlerList(List<DatabaseConfig> databaseConfigs, PacketGroupReceiver packetGroupReceiver, PacketHandlingOption options) {
    // Handlers to request and get new commands to send (This may block the current thread). (This doesn't actually handle packets)
    final List<PacketHandler> commandRequesterHandlerList = new ArrayList<>();
    for (DatabaseConfig config : databaseConfigs) {
        if (CouchDbDatabaseSettings.TYPE.equals(config.getType())) {
            CouchDbDatabaseSettings settings = (CouchDbDatabaseSettings) config.getSettings();
            CouchDbInstance instance = CouchDbUtil.createInstance(settings.getCouchProperties(), settings.getOkHttpProperties());
            SolarThingDatabase database = CouchDbSolarThingDatabase.create(instance);
            IndividualSettings individualSettings = config.getIndividualSettingsOrDefault(Constants.DATABASE_COMMAND_DOWNLOAD_ID, null);
            FrequencySettings frequencySettings = individualSettings != null ? individualSettings.getFrequencySettings() : FrequencySettings.NORMAL_SETTINGS;
            PacketHandler packetHandler = new PacketHandler() {

                private final SecurityPacketReceiver securityPacketReceiver = new SecurityPacketReceiver(DatabaseDocumentKeyMap.createFromDatabase(database), packetGroupReceiver, new SecurityPacketReceiver.InstanceTargetPredicate(options.getSourceId(), options.getFragmentId()), Collections.singleton(CommandOpenPacket.class), System.currentTimeMillis(), options.getFragmentId(), options.getSourceId(), database.getEventDatabase());

                @Override
                public void handle(PacketCollection packetCollection) throws PacketHandleException {
                    final List<StoredPacketGroup> packetGroups;
                    try {
                        packetGroups = database.getOpenDatabase().query(new MillisQueryBuilder().startKey(System.currentTimeMillis() - 5 * 60 * 1000).build());
                    } catch (SolarThingDatabaseException e) {
                        throw new PacketHandleException(e);
                    }
                    securityPacketReceiver.receivePacketGroups(packetGroups);
                }
            };
            commandRequesterHandlerList.add(new ThrottleFactorPacketHandler(new AsyncPacketHandlerWrapper(new PrintPacketHandleExceptionWrapper(packetHandler)), frequencySettings));
        }
    }
    return commandRequesterHandlerList;
}
Also used : PacketCollection(me.retrodaredevil.solarthing.packets.collection.PacketCollection) ArrayList(java.util.ArrayList) MillisQueryBuilder(me.retrodaredevil.solarthing.database.MillisQueryBuilder) SolarThingDatabaseException(me.retrodaredevil.solarthing.database.exception.SolarThingDatabaseException) CouchDbDatabaseSettings(me.retrodaredevil.solarthing.config.databases.implementations.CouchDbDatabaseSettings) StoredPacketGroup(me.retrodaredevil.solarthing.packets.collection.StoredPacketGroup) CouchDbInstance(me.retrodaredevil.couchdbjava.CouchDbInstance) CouchDbSolarThingDatabase(me.retrodaredevil.solarthing.database.couchdb.CouchDbSolarThingDatabase) SolarThingDatabase(me.retrodaredevil.solarthing.database.SolarThingDatabase) IndividualSettings(me.retrodaredevil.solarthing.config.databases.IndividualSettings)

Aggregations

PacketCollection (me.retrodaredevil.solarthing.packets.collection.PacketCollection)11 Instant (java.time.Instant)7 SolarThingDatabaseException (me.retrodaredevil.solarthing.database.exception.SolarThingDatabaseException)7 PacketCollectionCreator (me.retrodaredevil.solarthing.packets.collection.PacketCollectionCreator)7 ArrayList (java.util.ArrayList)3 VersionedPacket (me.retrodaredevil.solarthing.database.VersionedPacket)3 ZoneId (java.time.ZoneId)2 Arrays (java.util.Arrays)2 List (java.util.List)2 Nullable (me.retrodaredevil.solarthing.annotations.Nullable)2 CommandOpenPacket (me.retrodaredevil.solarthing.commands.packets.open.CommandOpenPacket)2 ImmutableDeleteAlterPacket (me.retrodaredevil.solarthing.commands.packets.open.ImmutableDeleteAlterPacket)2 ImmutableRequestCommandPacket (me.retrodaredevil.solarthing.commands.packets.open.ImmutableRequestCommandPacket)2 SolarThingDatabase (me.retrodaredevil.solarthing.database.SolarThingDatabase)2 Packet (me.retrodaredevil.solarthing.packets.Packet)2 PacketCollectionIdGenerator (me.retrodaredevil.solarthing.packets.collection.PacketCollectionIdGenerator)2 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1