fix duplicate device names

This commit is contained in:
Claudio Maggioni (maggicl) 2020-04-25 22:51:30 +02:00
parent dbf9ef885b
commit be7c9ce99f
3 changed files with 19 additions and 3 deletions

View file

@ -29,7 +29,7 @@ public class BooleanTriggerController {
return booleanTriggerRepository.findAllByAutomationId(automationId);
}
private BooleanTrigger<?> save(BooleanTrigger newRL, BooleanTriggerSaveRequest s) {
private BooleanTrigger<?> save(BooleanTrigger<?> newRL, BooleanTriggerSaveRequest s) {
newRL.setDeviceId(s.getDeviceId());
newRL.setAutomationId(s.getAutomationId());
newRL.setOn(s.isOn());
@ -40,7 +40,7 @@ public class BooleanTriggerController {
@PostMapping
public BooleanTrigger<?> create(
@Valid @RequestBody BooleanTriggerSaveRequest booleanTriggerSaveRequest) {
return save(new BooleanTrigger(), booleanTriggerSaveRequest);
return save(new BooleanTrigger<>(), booleanTriggerSaveRequest);
}
@PutMapping

View file

@ -14,6 +14,10 @@ import org.springframework.data.repository.query.Param;
public interface DeviceRepository<T extends Device> extends CrudRepository<T, Long> {
List<T> findByRoomId(@Param("roomId") long roomId);
@Query(
"SELECT COUNT(d) FROM Device d JOIN d.room r JOIN r.user u WHERE d.name = ?1 AND u.username = ?2")
Integer findDuplicates(String name, String username);
/**
* Finds devices by their id and a username
*

View file

@ -29,7 +29,15 @@ public class DeviceService {
roomRepository.findByIdAndUsername(roomId, username).orElseThrow(NotFoundException::new);
}
public void triggerTriggers(Device device) {
private void renameIfDuplicate(Device toCreate, String username) {
while (deviceRepository.findDuplicates(toCreate.getName(), username)
- (toCreate.getId() <= 0 ? 0 : 1)
> 0) {
toCreate.setName(toCreate.getName() + " (new)");
}
}
private void triggerTriggers(Device device) {
final long deviceId = device.getId();
@ -107,6 +115,8 @@ public class DeviceService {
final User currentUser = userRepository.findByUsername(guestUsername);
final User host = userRepository.findById(hostId).orElseThrow(NotFoundException::new);
if (!host.getGuests().contains(currentUser)) throw new NotFoundException();
renameIfDuplicate(device, host.getUsername());
device = deviceRepository.save(device);
final Set<User> guests = Set.copyOf(host.getGuests());
// We're telling the host that a guest has modified a device. Therefore, fromGuest becomes
@ -145,6 +155,7 @@ public class DeviceService {
public <T extends Device> List<T> saveAllAsOwner(
Iterable<T> devices, String username, boolean fromScene) {
devices.forEach(d -> renameIfDuplicate(d, username));
devices = deviceRepository.saveAll(devices);
devices.forEach((d) -> propagateUpdateAsOwner(d, username));
@ -156,6 +167,7 @@ public class DeviceService {
}
public <T extends Device> T saveAsOwner(T device, String username, boolean fromScene) {
renameIfDuplicate(device, username);
device = deviceRepository.save(device);
propagateUpdateAsOwner(device, username);