From 2213544eecbad546819c8a8227eb2a0e3d3dc807 Mon Sep 17 00:00:00 2001 From: Denny Sheirer Date: Tue, 17 Nov 2026 03:24:29 -0500 Subject: [PATCH] #2676 Alias List optionally tracks radio reference system with optional auto-update for talkgroup alias changes. (#2679) Co-authored-by: denny --- .../alias/AliasListConfiguration.java | 269 +++++++++ .../io/github/dsheirer/alias/AliasModel.java | 123 ++++- .../alias/AliasConfigurationEditor.java | 201 ++++++- .../playlist/radioreference/SiteEditor.java | 116 +++- .../preference/PreferenceEditorFactory.java | 3 + .../gui/preference/PreferenceEditorType.java | 1 + .../gui/preference/UserPreferencesEditor.java | 5 + .../RadioReferencePreferenceEditor.java | 80 +++ .../dsheirer/playlist/PlaylistManager.java | 17 + .../github/dsheirer/playlist/PlaylistV2.java | 16 + .../AliasListUpdateInterval.java | 56 ++ .../RadioReferencePreference.java | 37 ++ .../radioreference/AliasListSynchronizer.java | 510 ++++++++++++++++++ .../CachingRadioReferenceService.java | 11 + .../alias/AliasListConfigurationTest.java | 119 ++++ .../AliasListSynchronizerTest.java | 164 ++++++ 16 files changed, 1724 insertions(+), 4 deletions(-) create mode 100644 src/main/java/io/github/dsheirer/alias/AliasListConfiguration.java create mode 100644 src/main/java/io/github/dsheirer/gui/preference/radioreference/RadioReferencePreferenceEditor.java create mode 100644 src/main/java/io/github/dsheirer/preference/radioreference/AliasListUpdateInterval.java create mode 100644 src/main/java/io/github/dsheirer/service/radioreference/AliasListSynchronizer.java create mode 100644 src/test/java/io/github/dsheirer/alias/AliasListConfigurationTest.java create mode 100644 src/test/java/io/github/dsheirer/service/radioreference/AliasListSynchronizerTest.java diff --git a/src/main/java/io/github/dsheirer/alias/AliasListConfiguration.java b/src/main/java/io/github/dsheirer/alias/AliasListConfiguration.java new file mode 100644 index 00000000..2390d050 --- /dev/null +++ b/src/main/java/io/github/dsheirer/alias/AliasListConfiguration.java @@ -0,0 +1,269 @@ +/* + * ***************************************************************************** + * Copyright (C) 2014-2026 Dennis Sheirer + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see + * **************************************************************************** + */ + +package io.github.dsheirer.alias; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; +import javafx.beans.Observable; +import javafx.beans.property.BooleanProperty; +import javafx.beans.property.IntegerProperty; +import javafx.beans.property.LongProperty; +import javafx.beans.property.SimpleBooleanProperty; +import javafx.beans.property.SimpleIntegerProperty; +import javafx.beans.property.SimpleLongProperty; +import javafx.beans.property.SimpleStringProperty; +import javafx.beans.property.StringProperty; +import javafx.util.Callback; + +/** + * Persisted settings for an alias list. Alias lists are otherwise identified only by the list name that each alias + * carries, so settings that belong to the list itself, like tracking a Radio Reference system, are stored here and + * saved in the playlist. + * + * Radio Reference tracking uses two timestamps from the Radio Reference system's last updated value: the last updated + * value seen by the most recent check, and the last updated value that the aliases were synchronized to. When the + * seen value is newer than the synchronized value, the system changed on Radio Reference and the aliases haven't + * been updated yet. + */ +public class AliasListConfiguration +{ + public static final int NO_SYSTEM = 0; + + private StringProperty mName = new SimpleStringProperty(); + private IntegerProperty mRadioReferenceSystemId = new SimpleIntegerProperty(NO_SYSTEM); + private StringProperty mRadioReferenceSystemName = new SimpleStringProperty(); + private BooleanProperty mAutoUpdate = new SimpleBooleanProperty(); + private LongProperty mRadioReferenceLastUpdated = new SimpleLongProperty(); + private LongProperty mSynchronizedLastUpdated = new SimpleLongProperty(); + private LongProperty mLastChecked = new SimpleLongProperty(); + + /** + * Jackson constructor + */ + public AliasListConfiguration() + { + } + + /** + * Constructs an instance + * @param name of the alias list + */ + public AliasListConfiguration(String name) + { + setName(name); + } + + /** + * Extractor so that observable lists of configurations report changes to the persisted properties. + */ + public static Callback extractor() + { + return (AliasListConfiguration c) -> new Observable[] {c.mName, c.mRadioReferenceSystemId, + c.mRadioReferenceSystemName, c.mAutoUpdate, c.mRadioReferenceLastUpdated, c.mSynchronizedLastUpdated, + c.mLastChecked}; + } + + /** + * Alias list name + */ + @JacksonXmlProperty(isAttribute = true, localName = "name") + public String getName() + { + return mName.get(); + } + + public void setName(String name) + { + mName.set(name); + } + + @JsonIgnore + public StringProperty nameProperty() + { + return mName; + } + + /** + * Indicates if this alias list tracks a Radio Reference system. + */ + @JsonIgnore + public boolean isTrackingRadioReferenceSystem() + { + return getRadioReferenceSystemId() > NO_SYSTEM; + } + + /** + * Indicates if this alias list tracks the specified Radio Reference system. + */ + public boolean isTracking(int systemId) + { + return systemId > NO_SYSTEM && getRadioReferenceSystemId() == systemId; + } + + /** + * Radio Reference system ID tracked by this alias list, or NO_SYSTEM (0). + */ + @JacksonXmlProperty(isAttribute = true, localName = "rr_system_id") + public int getRadioReferenceSystemId() + { + return mRadioReferenceSystemId.get(); + } + + public void setRadioReferenceSystemId(int systemId) + { + mRadioReferenceSystemId.set(systemId); + } + + @JsonIgnore + public IntegerProperty radioReferenceSystemIdProperty() + { + return mRadioReferenceSystemId; + } + + /** + * Radio Reference system name, for display. + */ + @JacksonXmlProperty(isAttribute = true, localName = "rr_system_name") + public String getRadioReferenceSystemName() + { + return mRadioReferenceSystemName.get(); + } + + public void setRadioReferenceSystemName(String name) + { + mRadioReferenceSystemName.set(name); + } + + @JsonIgnore + public StringProperty radioReferenceSystemNameProperty() + { + return mRadioReferenceSystemName; + } + + /** + * Indicates if talkgroups are automatically added or updated as aliases when the system changes on Radio Reference. + */ + @JacksonXmlProperty(isAttribute = true, localName = "rr_auto_update") + public boolean isAutoUpdate() + { + return mAutoUpdate.get(); + } + + public void setAutoUpdate(boolean autoUpdate) + { + mAutoUpdate.set(autoUpdate); + } + + @JsonIgnore + public BooleanProperty autoUpdateProperty() + { + return mAutoUpdate; + } + + /** + * Radio Reference last updated timestamp (ms since epoch) for the system, as seen by the most recent check. + */ + @JacksonXmlProperty(isAttribute = true, localName = "rr_last_updated") + public long getRadioReferenceLastUpdated() + { + return mRadioReferenceLastUpdated.get(); + } + + public void setRadioReferenceLastUpdated(long timestamp) + { + mRadioReferenceLastUpdated.set(timestamp); + } + + @JsonIgnore + public LongProperty radioReferenceLastUpdatedProperty() + { + return mRadioReferenceLastUpdated; + } + + /** + * Radio Reference last updated timestamp (ms since epoch) that the aliases were last synchronized to. + */ + @JacksonXmlProperty(isAttribute = true, localName = "rr_synchronized") + public long getSynchronizedLastUpdated() + { + return mSynchronizedLastUpdated.get(); + } + + public void setSynchronizedLastUpdated(long timestamp) + { + mSynchronizedLastUpdated.set(timestamp); + } + + @JsonIgnore + public LongProperty synchronizedLastUpdatedProperty() + { + return mSynchronizedLastUpdated; + } + + /** + * Time (ms since epoch) of the most recent successful check of the system on Radio Reference. + */ + @JacksonXmlProperty(isAttribute = true, localName = "rr_last_checked") + public long getLastChecked() + { + return mLastChecked.get(); + } + + public void setLastChecked(long timestamp) + { + mLastChecked.set(timestamp); + } + + @JsonIgnore + public LongProperty lastCheckedProperty() + { + return mLastChecked; + } + + /** + * Indicates if the most recent check saw a system change on Radio Reference that the aliases don't include yet. + */ + @JsonIgnore + public boolean isUpdateAvailable() + { + return isTrackingRadioReferenceSystem() && getRadioReferenceLastUpdated() > getSynchronizedLastUpdated(); + } + + /** + * Starts tracking the Radio Reference system. Clears timestamps so that the next refresh synchronizes. + */ + public void track(int systemId, String systemName) + { + setRadioReferenceSystemId(systemId); + setRadioReferenceSystemName(systemName); + setRadioReferenceLastUpdated(0); + setSynchronizedLastUpdated(0); + setLastChecked(0); + } + + /** + * Stops tracking any Radio Reference system. + */ + public void stopTracking() + { + track(NO_SYSTEM, null); + setAutoUpdate(false); + } +} diff --git a/src/main/java/io/github/dsheirer/alias/AliasModel.java b/src/main/java/io/github/dsheirer/alias/AliasModel.java index 1ace3414..a77803c9 100644 --- a/src/main/java/io/github/dsheirer/alias/AliasModel.java +++ b/src/main/java/io/github/dsheirer/alias/AliasModel.java @@ -46,6 +46,8 @@ public class AliasModel private ObservableList mAliases = FXCollections.observableArrayList(Alias.extractor()); private ObservableList mAliasListNames = FXCollections.observableArrayList(); private Map mAliasListMap = new HashMap<>(); + private ObservableList mAliasListConfigurations = + FXCollections.observableArrayList(AliasListConfiguration.extractor()); public AliasModel() { @@ -63,6 +65,99 @@ public class AliasModel return mAliasListNames; } + /** + * Observable list of persisted alias list configurations. Only alias lists with settings, like Radio Reference + * system tracking, have a configuration. + */ + public ObservableList aliasListConfigurations() + { + return mAliasListConfigurations; + } + + /** + * Bulk loading of alias list configurations from a playlist. Ignores configurations without a name and + * duplicates of an earlier configuration's name. + */ + public void addAliasListConfigurations(List configurations) + { + if(configurations != null) + { + for(AliasListConfiguration configuration: configurations) + { + String name = configuration.getName(); + + if(name != null && !name.isEmpty() && getAliasListConfiguration(name) == null) + { + mAliasListConfigurations.add(configuration); + addAliasList(name); + } + } + } + } + + /** + * Configuration for the named alias list. + * @param aliasListName to find + * @return configuration or null if the alias list doesn't have one + */ + public AliasListConfiguration getAliasListConfiguration(String aliasListName) + { + if(aliasListName != null) + { + for(AliasListConfiguration configuration: mAliasListConfigurations) + { + if(aliasListName.equals(configuration.getName())) + { + return configuration; + } + } + } + + return null; + } + + /** + * Configuration for the named alias list, created when the alias list doesn't have one. + * @param aliasListName for the configuration, not null or the (No Alias List) name + * @return configuration + */ + public AliasListConfiguration getOrCreateAliasListConfiguration(String aliasListName) + { + if(aliasListName == null || aliasListName.isEmpty() || aliasListName.equals(NO_ALIAS_LIST)) + { + throw new IllegalArgumentException("Invalid alias list name [" + aliasListName + "]"); + } + + AliasListConfiguration configuration = getAliasListConfiguration(aliasListName); + + if(configuration == null) + { + configuration = new AliasListConfiguration(aliasListName); + mAliasListConfigurations.add(configuration); + addAliasList(aliasListName); + } + + return configuration; + } + + /** + * Name of the first alias list that tracks the Radio Reference system. + * @param systemId of the Radio Reference system + * @return alias list name or null + */ + public String getAliasListNameTracking(int systemId) + { + for(AliasListConfiguration configuration: mAliasListConfigurations) + { + if(configuration.isTracking(systemId)) + { + return configuration.getName(); + } + } + + return null; + } + /** * Clears and reloads the list of alias list names from the current set of aliases. */ @@ -79,6 +174,15 @@ public class AliasModel mAliasListNames.add(aliasListName); } } + + //Alias lists with a configuration exist even before they have any aliases + for(AliasListConfiguration configuration: mAliasListConfigurations) + { + if(!mAliasListNames.contains(configuration.getName())) + { + mAliasListNames.add(configuration.getName()); + } + } } /** @@ -93,7 +197,22 @@ public class AliasModel return; } - mAliases.stream().filter(alias -> alias.getAliasListName().equals(oldName)).forEach(alias -> alias.setAliasListName(newName)); + mAliases.stream().filter(alias -> oldName.equals(alias.getAliasListName())).forEach(alias -> alias.setAliasListName(newName)); + + AliasListConfiguration configuration = getAliasListConfiguration(oldName); + + if(configuration != null) + { + //Merging into an existing list keeps that list's configuration + if(getAliasListConfiguration(newName) == null) + { + configuration.setName(newName); + } + else + { + mAliasListConfigurations.remove(configuration); + } + } } /** @@ -109,6 +228,7 @@ public class AliasModel mAliases.removeIf(alias -> alias.getAliasListName().equals(aliasListName)); mAliasListMap.remove(aliasListName); + mAliasListConfigurations.removeIf(configuration -> aliasListName.equals(configuration.getName())); } /** @@ -146,6 +266,7 @@ public class AliasModel removeAlias(alias); } + mAliasListConfigurations.clear(); mAliasListNames.clear(); } diff --git a/src/main/java/io/github/dsheirer/gui/playlist/alias/AliasConfigurationEditor.java b/src/main/java/io/github/dsheirer/gui/playlist/alias/AliasConfigurationEditor.java index f2e1924b..9fdf7aec 100644 --- a/src/main/java/io/github/dsheirer/gui/playlist/alias/AliasConfigurationEditor.java +++ b/src/main/java/io/github/dsheirer/gui/playlist/alias/AliasConfigurationEditor.java @@ -23,6 +23,7 @@ import com.google.common.eventbus.Subscribe; import io.github.dsheirer.alias.Alias; import io.github.dsheirer.alias.AliasFactory; import io.github.dsheirer.alias.AliasList; +import io.github.dsheirer.alias.AliasListConfiguration; import io.github.dsheirer.alias.AliasModel; import io.github.dsheirer.eventbus.MyEventBus; import io.github.dsheirer.gui.control.MaxLengthUnaryOperator; @@ -33,6 +34,11 @@ import io.github.dsheirer.icon.Icon; import io.github.dsheirer.playlist.PlaylistManager; import io.github.dsheirer.preference.PreferenceType; import io.github.dsheirer.preference.UserPreferences; +import io.github.dsheirer.service.radioreference.AliasListSynchronizer; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -49,6 +55,7 @@ import javafx.geometry.Pos; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; +import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.MenuButton; @@ -62,10 +69,12 @@ import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.TextFormatter; import javafx.scene.control.TextInputDialog; +import javafx.scene.control.Tooltip; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; +import javafx.scene.layout.Region; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; @@ -106,6 +115,13 @@ public class AliasConfigurationEditor extends SplitPane implements IAliasListRef private FilteredList mAliasFilteredList; private SortedList mAliasSortedList; private AliasPredicate mAliasPredicate; + private VBox mRadioReferenceBox; + private Label mRadioReferenceSystemLabel; + private Label mRadioReferenceStatusLabel; + private CheckBox mAutoUpdateCheckBox; + private Button mRefreshAliasListButton; + private boolean mRefreshInProgress; + private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); /** * Constructs an instance @@ -120,7 +136,7 @@ public class AliasConfigurationEditor extends SplitPane implements IAliasListRef VBox leftBox = new VBox(); VBox.setVgrow(getAliasTableView(), Priority.ALWAYS); - leftBox.getChildren().addAll(getSearchAndListSelectionBox(), getAliasTableView()); + leftBox.getChildren().addAll(getSearchAndListSelectionBox(), getRadioReferenceBox(), getAliasTableView()); HBox topBox = new HBox(); HBox.setHgrow(leftBox, Priority.ALWAYS); @@ -130,9 +146,191 @@ public class AliasConfigurationEditor extends SplitPane implements IAliasListRef mCurrentEditor = getAliasItemEditor(); getItems().addAll(topBox, getAliasItemEditor()); + //Configuration changes (e.g. a background Radio Reference check) update the Radio Reference controls + mPlaylistManager.getAliasModel().aliasListConfigurations() + .addListener((ListChangeListener)c -> updateRadioReferenceControls()); + updateRadioReferenceControls(); + MyEventBus.getGlobalEventBus().register(this); } + /** + * Configuration for the alias list selected in the combo box, or null. + */ + private AliasListConfiguration getSelectedConfiguration() + { + String aliasListName = getAliasListNameComboBox().getSelectionModel().getSelectedItem(); + return mPlaylistManager.getAliasModel().getAliasListConfiguration(aliasListName); + } + + /** + * Radio Reference system tracking controls for the selected alias list. Disabled when the alias list doesn't + * track a Radio Reference system. + */ + private VBox getRadioReferenceBox() + { + if(mRadioReferenceBox == null) + { + //Two rows so that a long system name doesn't push the controls and status off the editor + Label label = new Label("Radio Reference:"); + label.setLabelFor(getRadioReferenceSystemLabel()); + label.setMinWidth(Region.USE_PREF_SIZE); + HBox systemRow = new HBox(10, label, getRadioReferenceSystemLabel()); + systemRow.setAlignment(Pos.CENTER_LEFT); + + HBox controlsRow = new HBox(10, getAutoUpdateCheckBox(), getRefreshAliasListButton(), + getRadioReferenceStatusLabel()); + controlsRow.setAlignment(Pos.CENTER_LEFT); + + mRadioReferenceBox = new VBox(5, systemRow, controlsRow); + mRadioReferenceBox.setPadding(new Insets(0, 0, 10, 10)); + } + + return mRadioReferenceBox; + } + + private Label getRadioReferenceSystemLabel() + { + if(mRadioReferenceSystemLabel == null) + { + mRadioReferenceSystemLabel = new Label(); + } + + return mRadioReferenceSystemLabel; + } + + private Label getRadioReferenceStatusLabel() + { + if(mRadioReferenceStatusLabel == null) + { + mRadioReferenceStatusLabel = new Label(); + } + + return mRadioReferenceStatusLabel; + } + + private CheckBox getAutoUpdateCheckBox() + { + if(mAutoUpdateCheckBox == null) + { + mAutoUpdateCheckBox = new CheckBox("Auto-Update Talkgroups"); + mAutoUpdateCheckBox.setTooltip(new Tooltip("Automatically add or update talkgroup aliases when the " + + "system changes on Radio Reference. Set how often to check in User Preferences > Radio Reference > Alias Lists.")); + mAutoUpdateCheckBox.setOnAction(event -> { + AliasListConfiguration configuration = getSelectedConfiguration(); + + if(configuration != null && configuration.isTrackingRadioReferenceSystem()) + { + configuration.setAutoUpdate(getAutoUpdateCheckBox().isSelected()); + } + }); + } + + return mAutoUpdateCheckBox; + } + + private Button getRefreshAliasListButton() + { + if(mRefreshAliasListButton == null) + { + mRefreshAliasListButton = new Button("Refresh Now"); + mRefreshAliasListButton.setTooltip(new Tooltip("Add or update talkgroup aliases from Radio Reference now")); + mRefreshAliasListButton.setOnAction(event -> { + AliasListConfiguration configuration = getSelectedConfiguration(); + + if(configuration == null || !configuration.isTrackingRadioReferenceSystem()) + { + return; + } + + mRefreshInProgress = true; + updateRadioReferenceControls(); + getRadioReferenceStatusLabel().setText("Refreshing from Radio Reference..."); + + mPlaylistManager.getAliasListSynchronizer().refresh(configuration) + .whenComplete((result, throwable) -> Platform.runLater(() -> { + mRefreshInProgress = false; + updateRadioReferenceControls(); + + if(throwable != null) + { + Alert alert = new Alert(Alert.AlertType.ERROR, "Unable to refresh alias list [" + + configuration.getName() + "] from Radio Reference.\n\n" + + AliasListSynchronizer.getMessage(throwable), ButtonType.OK); + alert.setTitle("Refresh Alias List"); + alert.setHeaderText("Radio Reference Refresh Failed"); + alert.initOwner(getRefreshAliasListButton().getScene().getWindow()); + alert.show(); + } + else if(result != null && result.applied() && configuration == getSelectedConfiguration()) + { + getRadioReferenceStatusLabel().setText("Added " + result.added() + ", updated " + + result.updated() + " aliases. " + getStatusText(configuration)); + } + })); + }); + } + + return mRefreshAliasListButton; + } + + /** + * Updates the Radio Reference controls for the currently selected alias list. + */ + private void updateRadioReferenceControls() + { + AliasListConfiguration configuration = getSelectedConfiguration(); + boolean tracking = configuration != null && configuration.isTrackingRadioReferenceSystem(); + + getAutoUpdateCheckBox().setDisable(!tracking); + getAutoUpdateCheckBox().setSelected(tracking && configuration.isAutoUpdate()); + getRefreshAliasListButton().setDisable(!tracking || mRefreshInProgress); + + if(tracking) + { + String name = configuration.getRadioReferenceSystemName(); + getRadioReferenceSystemLabel().setText((name != null && !name.isEmpty() ? name : "System") + " [" + + configuration.getRadioReferenceSystemId() + "]"); + + if(!mRefreshInProgress) + { + getRadioReferenceStatusLabel().setText(getStatusText(configuration)); + } + } + else + { + getRadioReferenceSystemLabel().setText("Not tracking a system"); + getRadioReferenceStatusLabel().setText(null); + } + } + + /** + * Status text for a tracked alias list: Radio Reference last updated and synchronized timestamps. + */ + private static String getStatusText(AliasListConfiguration configuration) + { + StringBuilder sb = new StringBuilder(); + sb.append("Updated on Radio Reference: ").append(format(configuration.getRadioReferenceLastUpdated())); + sb.append(" Synchronized: ").append(format(configuration.getSynchronizedLastUpdated())); + + if(configuration.isUpdateAvailable()) + { + sb.append(" (Update Available)"); + } + + return sb.toString(); + } + + private static String format(long timestamp) + { + if(timestamp <= 0) + { + return "never"; + } + + return DATE_FORMATTER.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault())); + } + /** * Redraws the alias color swatches after a change to the application theme. */ @@ -331,6 +529,7 @@ public class AliasConfigurationEditor extends SplitPane implements IAliasListRef { getNewAliasButton().setDisable(newValue == null || newValue.contentEquals(AliasModel.NO_ALIAS_LIST)); update(); + updateRadioReferenceControls(); }); if(mAliasListNameComboBox.getItems().size() > 1) diff --git a/src/main/java/io/github/dsheirer/gui/playlist/radioreference/SiteEditor.java b/src/main/java/io/github/dsheirer/gui/playlist/radioreference/SiteEditor.java index daa93e3c..1b6d927c 100644 --- a/src/main/java/io/github/dsheirer/gui/playlist/radioreference/SiteEditor.java +++ b/src/main/java/io/github/dsheirer/gui/playlist/radioreference/SiteEditor.java @@ -19,6 +19,7 @@ package io.github.dsheirer.gui.playlist.radioreference; +import io.github.dsheirer.alias.AliasListConfiguration; import io.github.dsheirer.alias.AliasModel; import io.github.dsheirer.controller.channel.Channel; import io.github.dsheirer.eventbus.MyEventBus; @@ -45,6 +46,7 @@ import io.github.dsheirer.rrapi.type.Site; import io.github.dsheirer.rrapi.type.SiteFrequency; import io.github.dsheirer.rrapi.type.System; import io.github.dsheirer.rrapi.type.SystemInformation; +import io.github.dsheirer.service.radioreference.AliasListSynchronizer; import io.github.dsheirer.source.config.SourceConfigTuner; import io.github.dsheirer.source.config.SourceConfigTunerMultipleFrequency; import java.text.DecimalFormat; @@ -55,6 +57,7 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; import javafx.animation.RotateTransition; +import javafx.application.Platform; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.beans.property.SimpleStringProperty; import javafx.beans.value.ObservableValue; @@ -75,6 +78,7 @@ import javafx.scene.control.TextField; import javafx.scene.control.TextFormatter; import javafx.scene.control.TextInputDialog; import javafx.scene.control.ToggleButton; +import javafx.scene.control.Tooltip; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; @@ -120,6 +124,7 @@ public class SiteEditor extends GridPane private SystemInformation mCurrentSystemInformation; private ComboBox mAliasListNameComboBox; private Button mNewAliasListButton; + private Button mNewSystemAliasListButton; private Label mP25ControlLabel; private SegmentedButton mP25ControlSegmentedButton; private ToggleButton mFdmaControlToggleButton; @@ -222,8 +227,12 @@ public class SiteEditor extends GridPane GridPane.setHgrow(getAliasListNameComboBox(), Priority.ALWAYS); getChildren().add(getAliasListNameComboBox()); - GridPane.setConstraints(getNewAliasListButton(), 2, ++row); - getChildren().add(getNewAliasListButton()); + HBox aliasListButtonsBox = new HBox(); + aliasListButtonsBox.setAlignment(Pos.CENTER_LEFT); + aliasListButtonsBox.setSpacing(10); + aliasListButtonsBox.getChildren().addAll(getNewAliasListButton(), getNewSystemAliasListButton()); + GridPane.setConstraints(aliasListButtonsBox, 2, ++row); + getChildren().add(aliasListButtonsBox); HBox createBox = new HBox(); createBox.setAlignment(Pos.CENTER_LEFT); @@ -278,6 +287,18 @@ public class SiteEditor extends GridPane getGoToChannelEditorCheckBox().setDisable(disable || !supported); getAliasListNameComboBox().setDisable(disable || !supported); getNewAliasListButton().setDisable(disable || !supported); + getNewSystemAliasListButton().setDisable(disable || !supported || system == null); + + //Select an alias list that tracks this site's system, if there is one + if(system != null) + { + String trackingAliasList = mPlaylistManager.getAliasModel().getAliasListNameTracking(system.getSystemId()); + + if(trackingAliasList != null) + { + getAliasListNameComboBox().getSelectionModel().select(trackingAliasList); + } + } getCreateChannelConfigurationButton().setVisible(false); getGoToChannelEditorCheckBox().setVisible(false); @@ -878,6 +899,97 @@ public class SiteEditor extends GridPane return mNewAliasListButton; } + /** + * Button to create an alias list that tracks the talkgroups of the current system on Radio Reference. + */ + private Button getNewSystemAliasListButton() + { + if(mNewSystemAliasListButton == null) + { + mNewSystemAliasListButton = new Button("New Alias List For System"); + mNewSystemAliasListButton.setTooltip(new Tooltip("Create an alias list with the system's talkgroups " + + "that tracks the system on Radio Reference and automatically adds or updates talkgroup aliases")); + mNewSystemAliasListButton.setDisable(true); + mNewSystemAliasListButton.setOnAction(event -> createSystemAliasList()); + } + + return mNewSystemAliasListButton; + } + + /** + * Prompts for a name and creates an alias list that tracks the current system, then imports the talkgroups. + */ + private void createSystemAliasList() + { + if(mCurrentSystem == null) + { + return; + } + + String systemName = mCurrentSystem.getName() != null ? mCurrentSystem.getName().trim() : ""; + + if(systemName.length() > 25) + { + systemName = systemName.substring(0, 25).trim(); + } + + TextInputDialog dialog = new TextInputDialog(systemName); + dialog.setTitle("Create New Alias List For System"); + dialog.setHeaderText("Create an alias list that tracks the talkgroups for " + mCurrentSystem.getName() + + ".\nPlease enter an alias list name (max 25 chars)."); + dialog.setContentText("Name:"); + dialog.getEditor().setTextFormatter(new TextFormatter(new MaxLengthUnaryOperator(25))); + dialog.initOwner(getNewSystemAliasListButton().getScene().getWindow()); + Optional result = dialog.showAndWait(); + + if(result.isEmpty() || result.get().trim().isEmpty()) + { + return; + } + + String name = result.get().trim(); + AliasModel aliasModel = mPlaylistManager.getAliasModel(); + + if(name.equals(AliasModel.NO_ALIAS_LIST) || aliasModel.aliasListNames().contains(name)) + { + Alert alert = new Alert(Alert.AlertType.ERROR, "An alias list named [" + name + + "] already exists. Please choose another name.", ButtonType.OK); + alert.setTitle("Create New Alias List For System"); + alert.setHeaderText("Alias List Exists"); + alert.initOwner(getNewSystemAliasListButton().getScene().getWindow()); + alert.showAndWait(); + return; + } + + AliasListConfiguration configuration = aliasModel.getOrCreateAliasListConfiguration(name); + configuration.track(mCurrentSystem.getSystemId(), mCurrentSystem.getName()); + configuration.setAutoUpdate(true); + getAliasListNameComboBox().getSelectionModel().select(name); + + getNewSystemAliasListButton().setDisable(true); + + mPlaylistManager.getAliasListSynchronizer().refresh(configuration) + .whenComplete((syncResult, throwable) -> Platform.runLater(() -> { + getNewSystemAliasListButton().setDisable(mCurrentSystem == null); + + if(throwable != null) + { + Alert alert = new Alert(Alert.AlertType.ERROR, "Alias list [" + name + "] was created, but the " + + "talkgroups couldn't be imported from Radio Reference. Use Refresh Now in the Aliases tab " + + "to try again.\n\n" + AliasListSynchronizer.getMessage(throwable), ButtonType.OK); + alert.setTitle("Create New Alias List For System"); + alert.setHeaderText("Talkgroup Import Failed"); + + if(getScene() != null) + { + alert.initOwner(getScene().getWindow()); + } + + alert.show(); + } + })); + } + private Label getProtocolNotSupportedLabel() { if(mProtocolNotSupportedLabel == null) diff --git a/src/main/java/io/github/dsheirer/gui/preference/PreferenceEditorFactory.java b/src/main/java/io/github/dsheirer/gui/preference/PreferenceEditorFactory.java index 647a5a49..7b6efc81 100644 --- a/src/main/java/io/github/dsheirer/gui/preference/PreferenceEditorFactory.java +++ b/src/main/java/io/github/dsheirer/gui/preference/PreferenceEditorFactory.java @@ -27,6 +27,7 @@ import io.github.dsheirer.gui.preference.decoder.JmbeLibraryPreferenceEditor; import io.github.dsheirer.gui.preference.directory.DirectoryPreferenceEditor; import io.github.dsheirer.gui.preference.mp3.MP3PreferenceEditor; import io.github.dsheirer.gui.preference.playback.PlaybackPreferenceEditor; +import io.github.dsheirer.gui.preference.radioreference.RadioReferencePreferenceEditor; import io.github.dsheirer.gui.preference.record.RecordPreferenceEditor; import io.github.dsheirer.gui.preference.tuner.TunerPreferenceEditor; import io.github.dsheirer.preference.UserPreferences; @@ -59,6 +60,8 @@ public class PreferenceEditorFactory return new DirectoryPreferenceEditor(userPreferences); case JMBE_LIBRARY: return new JmbeLibraryPreferenceEditor(userPreferences); + case RADIO_REFERENCE_ALIAS_LISTS: + return new RadioReferencePreferenceEditor(userPreferences); case SOURCE_TUNERS: return new TunerPreferenceEditor(userPreferences); case TALKGROUP_FORMAT: diff --git a/src/main/java/io/github/dsheirer/gui/preference/PreferenceEditorType.java b/src/main/java/io/github/dsheirer/gui/preference/PreferenceEditorType.java index c28d47a6..612cf398 100644 --- a/src/main/java/io/github/dsheirer/gui/preference/PreferenceEditorType.java +++ b/src/main/java/io/github/dsheirer/gui/preference/PreferenceEditorType.java @@ -29,6 +29,7 @@ public enum PreferenceEditorType CHANNEL_EVENT("Channel Events"), DIRECTORY("Directories"), JMBE_LIBRARY("JMBE Audio Library"), + RADIO_REFERENCE_ALIAS_LISTS("Alias Lists"), AUDIO_MP3("MP3"), AUDIO_RECORD("Record"), AUDIO_OUTPUT("Playback/Tones"), diff --git a/src/main/java/io/github/dsheirer/gui/preference/UserPreferencesEditor.java b/src/main/java/io/github/dsheirer/gui/preference/UserPreferencesEditor.java index f328b7e4..db8cc7ae 100644 --- a/src/main/java/io/github/dsheirer/gui/preference/UserPreferencesEditor.java +++ b/src/main/java/io/github/dsheirer/gui/preference/UserPreferencesEditor.java @@ -200,6 +200,11 @@ public class UserPreferencesEditor extends BorderPane treeRoot.getChildren().add(storageItem); storageItem.setExpanded(true); + TreeItem radioReferenceItem = new TreeItem<>("Radio Reference"); + radioReferenceItem.getChildren().add(new TreeItem(PreferenceEditorType.RADIO_REFERENCE_ALIAS_LISTS)); + treeRoot.getChildren().add(radioReferenceItem); + radioReferenceItem.setExpanded(true); + TreeItem sourceItem = new TreeItem<>("Source"); sourceItem.getChildren().add(new TreeItem(PreferenceEditorType.SOURCE_TUNERS)); treeRoot.getChildren().add(sourceItem); diff --git a/src/main/java/io/github/dsheirer/gui/preference/radioreference/RadioReferencePreferenceEditor.java b/src/main/java/io/github/dsheirer/gui/preference/radioreference/RadioReferencePreferenceEditor.java new file mode 100644 index 00000000..bc87489d --- /dev/null +++ b/src/main/java/io/github/dsheirer/gui/preference/radioreference/RadioReferencePreferenceEditor.java @@ -0,0 +1,80 @@ +/* + * ***************************************************************************** + * Copyright (C) 2014-2026 Dennis Sheirer + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see + * **************************************************************************** + */ + +package io.github.dsheirer.gui.preference.radioreference; + +import io.github.dsheirer.preference.UserPreferences; +import io.github.dsheirer.preference.radioreference.AliasListUpdateInterval; +import io.github.dsheirer.preference.radioreference.RadioReferencePreference; +import javafx.geometry.HPos; +import javafx.geometry.Insets; +import javafx.scene.control.ComboBox; +import javafx.scene.control.Label; +import javafx.scene.layout.GridPane; +import javafx.scene.layout.VBox; + +/** + * Preference settings for alias lists that track a Radio Reference system. + */ +public class RadioReferencePreferenceEditor extends VBox +{ + private RadioReferencePreference mRadioReferencePreference; + private ComboBox mUpdateIntervalComboBox; + + public RadioReferencePreferenceEditor(UserPreferences userPreferences) + { + mRadioReferencePreference = userPreferences.getRadioReferencePreference(); + + setPadding(new Insets(10, 10, 10, 10)); + setSpacing(10); + + GridPane gridPane = new GridPane(); + gridPane.setHgap(10); + gridPane.setVgap(10); + + Label intervalLabel = new Label("Check Tracked Systems For Talkgroup Changes:"); + intervalLabel.setLabelFor(getUpdateIntervalComboBox()); + GridPane.setHalignment(intervalLabel, HPos.RIGHT); + gridPane.add(intervalLabel, 0, 0); + gridPane.add(getUpdateIntervalComboBox(), 1, 0); + + Label help = new Label("Alias lists that track a Radio Reference system check the system on this schedule " + + "while sdrtrunk is running and a Radio Reference login is stored. Alias lists with Auto-Update enabled " + + "add or update talkgroup aliases when the system changed. Use Refresh Now in the playlist editor's " + + "Aliases tab to update an alias list immediately."); + help.setWrapText(true); + help.setMaxWidth(500); + + getChildren().addAll(gridPane, help); + } + + private ComboBox getUpdateIntervalComboBox() + { + if(mUpdateIntervalComboBox == null) + { + mUpdateIntervalComboBox = new ComboBox<>(); + mUpdateIntervalComboBox.getItems().addAll(AliasListUpdateInterval.values()); + mUpdateIntervalComboBox.getSelectionModel().select(mRadioReferencePreference.getAliasListUpdateInterval()); + mUpdateIntervalComboBox.setOnAction(event -> mRadioReferencePreference + .setAliasListUpdateInterval(mUpdateIntervalComboBox.getSelectionModel().getSelectedItem())); + } + + return mUpdateIntervalComboBox; + } +} diff --git a/src/main/java/io/github/dsheirer/playlist/PlaylistManager.java b/src/main/java/io/github/dsheirer/playlist/PlaylistManager.java index 8ecd8404..2b31ceb1 100644 --- a/src/main/java/io/github/dsheirer/playlist/PlaylistManager.java +++ b/src/main/java/io/github/dsheirer/playlist/PlaylistManager.java @@ -24,6 +24,7 @@ import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import io.github.dsheirer.alias.Alias; +import io.github.dsheirer.alias.AliasListConfiguration; import io.github.dsheirer.alias.AliasModel; import io.github.dsheirer.audio.broadcast.BroadcastModel; import io.github.dsheirer.controller.channel.Channel.ChannelType; @@ -39,6 +40,7 @@ import io.github.dsheirer.module.log.EventLogManager; import io.github.dsheirer.preference.UserPreferences; import io.github.dsheirer.preference.playlist.PlaylistPreference; import io.github.dsheirer.sample.Listener; +import io.github.dsheirer.service.radioreference.AliasListSynchronizer; import io.github.dsheirer.service.radioreference.RadioReference; import io.github.dsheirer.source.tuner.manager.TunerManager; import io.github.dsheirer.util.ThreadPool; @@ -76,6 +78,7 @@ public class PlaylistManager implements Listener private TunerManager mTunerManager; private UserPreferences mUserPreferences; private RadioReference mRadioReference; + private AliasListSynchronizer mAliasListSynchronizer; private AtomicBoolean mPlaylistSavePending = new AtomicBoolean(); private ScheduledFuture mPlaylistSaveFuture; private boolean mPlaylistLoading = false; @@ -103,6 +106,7 @@ public class PlaylistManager implements Listener mBroadcastModel = new BroadcastModel(mAliasModel, mIconModel, userPreferences); mRadioReference = new RadioReference(mUserPreferences); + mAliasListSynchronizer = new AliasListSynchronizer(mAliasModel, mRadioReference, mUserPreferences); mChannelModel = new ChannelModel(mAliasModel); mChannelProcessingManager = new ChannelProcessingManager(mChannelMapModel, eventLogManager, mTunerManager, @@ -120,6 +124,8 @@ public class PlaylistManager implements Listener mChannelModel.addListener(this); mAliasModel.aliasList().addListener((ListChangeListener)c -> schedulePlaylistSave()); + mAliasModel.aliasListConfigurations() + .addListener((ListChangeListener)c -> schedulePlaylistSave()); mChannelMapModel.getChannelMaps().addListener((ListChangeListener)c -> schedulePlaylistSave()); @@ -248,6 +254,14 @@ public class PlaylistManager implements Listener return mBroadcastModel; } + /** + * Synchronizer for alias lists that track a Radio Reference system. + */ + public AliasListSynchronizer getAliasListSynchronizer() + { + return mAliasListSynchronizer; + } + /** * Channel Map model managed by this playlist manager */ @@ -264,6 +278,7 @@ public class PlaylistManager implements Listener { PlaylistV2 playlist = load(); transferPlaylistToModels(playlist); + mAliasListSynchronizer.start(); } /** @@ -401,6 +416,7 @@ public class PlaylistManager implements Listener mPlaylistLoading = true; mAliasModel.addAliases(playlist.getAliases()); + mAliasModel.addAliasListConfigurations(playlist.getAliasListConfigurations()); mBroadcastModel.addBroadcastConfigurations(playlist.getBroadcastConfigurations()); @@ -445,6 +461,7 @@ public class PlaylistManager implements Listener PlaylistV2 playlist = new PlaylistV2(); playlist.setAliases(new ArrayList(mAliasModel.getAliases())); + playlist.setAliasListConfigurations(new ArrayList<>(mAliasModel.aliasListConfigurations())); playlist.setBroadcastConfigurations(new ArrayList(mBroadcastModel.getBroadcastConfigurations())); playlist.setChannels(new ArrayList(mChannelModel.getChannels())); playlist.setChannelMaps(new ArrayList(mChannelMapModel.getChannelMaps())); diff --git a/src/main/java/io/github/dsheirer/playlist/PlaylistV2.java b/src/main/java/io/github/dsheirer/playlist/PlaylistV2.java index bef4ddab..61d00bf3 100644 --- a/src/main/java/io/github/dsheirer/playlist/PlaylistV2.java +++ b/src/main/java/io/github/dsheirer/playlist/PlaylistV2.java @@ -24,6 +24,7 @@ package io.github.dsheirer.playlist; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import io.github.dsheirer.alias.Alias; +import io.github.dsheirer.alias.AliasListConfiguration; import io.github.dsheirer.audio.broadcast.BroadcastConfiguration; import io.github.dsheirer.controller.channel.Channel; import io.github.dsheirer.controller.channel.map.ChannelMap; @@ -36,6 +37,7 @@ public class PlaylistV2 { private int mVersion = PlaylistManager.PLAYLIST_CURRENT_VERSION; private List mAliases = new ArrayList<>(); + private List mAliasListConfigurations = new ArrayList<>(); private List mBroadcastConfigurations = new ArrayList<>(); private List mChannels = new ArrayList<>(); private List mChannelMaps = new ArrayList<>(); @@ -72,6 +74,20 @@ public class PlaylistV2 mAliases = aliases; } + /** + * Alias list settings, like Radio Reference system tracking. Older playlists don't have these. + */ + @JacksonXmlProperty(isAttribute = false, localName = "alias_list") + public List getAliasListConfigurations() + { + return mAliasListConfigurations; + } + + public void setAliasListConfigurations(List configurations) + { + mAliasListConfigurations = configurations != null ? configurations : new ArrayList<>(); + } + @JacksonXmlProperty(isAttribute = false, localName = "channel") public List getChannels() { diff --git a/src/main/java/io/github/dsheirer/preference/radioreference/AliasListUpdateInterval.java b/src/main/java/io/github/dsheirer/preference/radioreference/AliasListUpdateInterval.java new file mode 100644 index 00000000..a42fbc28 --- /dev/null +++ b/src/main/java/io/github/dsheirer/preference/radioreference/AliasListUpdateInterval.java @@ -0,0 +1,56 @@ +/* + * ***************************************************************************** + * Copyright (C) 2014-2026 Dennis Sheirer + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see + * **************************************************************************** + */ + +package io.github.dsheirer.preference.radioreference; + +import java.time.Duration; + +/** + * How often alias lists that track a Radio Reference system check the system for changes. + */ +public enum AliasListUpdateInterval +{ + TWELVE_HOURS("Every 12 Hours", Duration.ofHours(12)), + DAILY("Every Day", Duration.ofDays(1)), + WEEKLY("Once a Week", Duration.ofDays(7)), + MONTHLY("Once a Month", Duration.ofDays(30)); + + private final String mLabel; + private final Duration mInterval; + + AliasListUpdateInterval(String label, Duration interval) + { + mLabel = label; + mInterval = interval; + } + + /** + * Time between checks + */ + public Duration getInterval() + { + return mInterval; + } + + @Override + public String toString() + { + return mLabel; + } +} diff --git a/src/main/java/io/github/dsheirer/preference/radioreference/RadioReferencePreference.java b/src/main/java/io/github/dsheirer/preference/radioreference/RadioReferencePreference.java index c2a0e20d..e3457190 100644 --- a/src/main/java/io/github/dsheirer/preference/radioreference/RadioReferencePreference.java +++ b/src/main/java/io/github/dsheirer/preference/radioreference/RadioReferencePreference.java @@ -60,6 +60,7 @@ public class RadioReferencePreference extends Preference private static final String ENCRYPTED_TALKGROUP_DO_NOT_MONITOR = "encrypted.talkgroup.import.do.not.monitor"; private static final String CREATE_AND_SHOW_CHANNEL_EDITOR = "create.and.show.channel.editor"; private static final String LOCATION = "location"; + private static final String ALIAS_LIST_UPDATE_INTERVAL = "alias.list.update.interval"; private static final String LOCATION_LABEL = "location.label"; private String mUserName; @@ -71,6 +72,7 @@ public class RadioReferencePreference extends Preference private Boolean mShowChannelEditorCounty; private Boolean mEncryptedTalkgroupImport; private Boolean mCreateAndShowChannelEditor; + private AliasListUpdateInterval mAliasListUpdateInterval; private int mPreferredCountryId = INVALID_ID; private int mPreferredStateId = INVALID_ID; private int mPreferredCountyId = INVALID_ID; @@ -494,6 +496,41 @@ public class RadioReferencePreference extends Preference } + /** + * How often alias lists that track a Radio Reference system check the system for changes. + */ + public AliasListUpdateInterval getAliasListUpdateInterval() + { + if(mAliasListUpdateInterval == null) + { + String name = mPreferences.get(ALIAS_LIST_UPDATE_INTERVAL, AliasListUpdateInterval.DAILY.name()); + + try + { + mAliasListUpdateInterval = AliasListUpdateInterval.valueOf(name); + } + catch(IllegalArgumentException iae) + { + mAliasListUpdateInterval = AliasListUpdateInterval.DAILY; + } + } + + return mAliasListUpdateInterval; + } + + /** + * Sets how often alias lists that track a Radio Reference system check the system for changes. + */ + public void setAliasListUpdateInterval(AliasListUpdateInterval interval) + { + if(interval != null) + { + mAliasListUpdateInterval = interval; + mPreferences.put(ALIAS_LIST_UPDATE_INTERVAL, interval.name()); + notifyPreferenceUpdated(); + } + } + /** * Indicates if should show channel editor after trunked channel configuration create */ diff --git a/src/main/java/io/github/dsheirer/service/radioreference/AliasListSynchronizer.java b/src/main/java/io/github/dsheirer/service/radioreference/AliasListSynchronizer.java new file mode 100644 index 00000000..9c50c7d7 --- /dev/null +++ b/src/main/java/io/github/dsheirer/service/radioreference/AliasListSynchronizer.java @@ -0,0 +1,510 @@ +/* + * ***************************************************************************** + * Copyright (C) 2014-2026 Dennis Sheirer + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see + * **************************************************************************** + */ + +package io.github.dsheirer.service.radioreference; + +import com.google.common.annotations.VisibleForTesting; +import io.github.dsheirer.alias.Alias; +import io.github.dsheirer.alias.AliasListConfiguration; +import io.github.dsheirer.alias.AliasModel; +import io.github.dsheirer.alias.id.AliasID; +import io.github.dsheirer.gui.playlist.radioreference.RadioReferenceDecoder; +import io.github.dsheirer.gui.playlist.radioreference.TalkgroupEncryption; +import io.github.dsheirer.preference.UserPreferences; +import io.github.dsheirer.preference.radioreference.AliasListUpdateInterval; +import io.github.dsheirer.rrapi.RadioReferenceException; +import io.github.dsheirer.rrapi.RadioReferenceService; +import io.github.dsheirer.rrapi.type.System; +import io.github.dsheirer.rrapi.type.SystemInformation; +import io.github.dsheirer.rrapi.type.Talkgroup; +import io.github.dsheirer.rrapi.type.TalkgroupCategory; +import io.github.dsheirer.util.ThreadPool; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import javafx.application.Platform; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Keeps alias lists that track a Radio Reference system up to date. Checks each tracked system on the interval from + * the user's Radio Reference preferences, records the system's Radio Reference last updated timestamp, and when the + * alias list is set to auto-update and the system changed, adds an alias for each new talkgroup and updates the name + * and group of aliases for talkgroups that changed on Radio Reference since the last synchronization. + * + * Aliases for talkgroups that are removed from Radio Reference are left in place, and alias settings other than the + * name and group (color, icon, priority, record, stream, etc.) are never changed. + */ +public class AliasListSynchronizer +{ + private static final Logger mLog = LoggerFactory.getLogger(AliasListSynchronizer.class); + private static final long CHECK_PERIOD_MINUTES = 30; + private static final long INITIAL_DELAY_MINUTES = 2; + private static final long RETRY_AFTER_FAILURE_MS = TimeUnit.HOURS.toMillis(1); + + private final AliasModel mAliasModel; + private final RadioReference mRadioReference; + private final UserPreferences mUserPreferences; + private final Object mSynchronizationLock = new Object(); + private final Map mFailedAttempts = new HashMap<>(); + private RadioReferenceDecoder mRadioReferenceDecoder; + private ScheduledFuture mScheduledCheck; + + /** + * Constructs an instance + * @param aliasModel containing aliases and alias list configurations + * @param radioReference for access to the web service + * @param userPreferences for the update interval and encrypted talkgroup import preferences + */ + public AliasListSynchronizer(AliasModel aliasModel, RadioReference radioReference, UserPreferences userPreferences) + { + mAliasModel = aliasModel; + mRadioReference = radioReference; + mUserPreferences = userPreferences; + } + + /** + * Starts periodic checks of tracked alias lists. + */ + public synchronized void start() + { + if(mScheduledCheck == null) + { + mScheduledCheck = ThreadPool.SCHEDULED.scheduleAtFixedRate(this::checkDueAliasLists, + INITIAL_DELAY_MINUTES, CHECK_PERIOD_MINUTES, TimeUnit.MINUTES); + } + } + + /** + * Stops periodic checks. + */ + public synchronized void stop() + { + if(mScheduledCheck != null) + { + mScheduledCheck.cancel(false); + mScheduledCheck = null; + } + } + + /** + * Checks each tracked alias list whose last check is older than the preferred update interval. Runs on a + * scheduler thread. + */ + private void checkDueAliasLists() + { + if(!mUserPreferences.getRadioReferencePreference().hasStoredCredentials()) + { + return; + } + + AliasListUpdateInterval interval = mUserPreferences.getRadioReferencePreference().getAliasListUpdateInterval(); + long now = java.lang.System.currentTimeMillis(); + + for(AliasListConfiguration configuration: getTrackedConfigurations()) + { + boolean due = now - configuration.getLastChecked() >= interval.getInterval().toMillis(); + + Long failed; + synchronized(mFailedAttempts) + { + failed = mFailedAttempts.get(configuration.getRadioReferenceSystemId()); + } + + boolean retryWait = failed != null && now - failed < RETRY_AFTER_FAILURE_MS; + + if(due && !retryWait) + { + try + { + synchronize(configuration, false).join(); + } + catch(Exception e) + { + mLog.warn("Unable to check Radio Reference system [" + configuration.getRadioReferenceSystemId() + + "] for alias list [" + configuration.getName() + "] - " + getMessage(e)); + } + } + } + } + + /** + * Snapshot of the alias list configurations that track a Radio Reference system. + */ + private List getTrackedConfigurations() + { + List tracked = new ArrayList<>(); + + //The configuration list is modified on the FX thread, so retry on a concurrent change + for(int attempt = 0; attempt < 3; attempt++) + { + try + { + tracked.clear(); + + for(AliasListConfiguration configuration: new ArrayList<>(mAliasModel.aliasListConfigurations())) + { + if(configuration.isTrackingRadioReferenceSystem()) + { + tracked.add(configuration); + } + } + + return tracked; + } + catch(Exception e) + { + //Try again + } + } + + return tracked; + } + + /** + * Refreshes the alias list now: reads the current system and talkgroups from Radio Reference and adds or updates + * aliases, regardless of the alias list's auto-update setting. + * @param configuration of a tracked alias list + * @return future result, completed after the aliases are updated on the FX thread + */ + public CompletableFuture refresh(AliasListConfiguration configuration) + { + return synchronize(configuration, true); + } + + /** + * Checks the tracked system and, when forced or when the alias list auto-updates and the system changed, + * synchronizes the talkgroup aliases. + * @param configuration of the tracked alias list + * @param force true to synchronize regardless of the auto-update setting or the last updated timestamps + * @return future result + */ + private CompletableFuture synchronize(AliasListConfiguration configuration, boolean force) + { + CompletableFuture future = new CompletableFuture<>(); + + if(configuration == null || !configuration.isTrackingRadioReferenceSystem()) + { + future.completeExceptionally(new IllegalArgumentException("Alias list doesn't track a Radio Reference system")); + return future; + } + + ThreadPool.CACHED.execute(() -> { + //One synchronization at a time so that a manual refresh and a scheduled check can't both add aliases + synchronized(mSynchronizationLock) + { + int systemId = configuration.getRadioReferenceSystemId(); + + try + { + RadioReferenceService service = mRadioReference.getService(); + + if(service instanceof CachingRadioReferenceService caching) + { + caching.invalidateSystem(systemId); + } + + SystemInformation systemInformation = service.getSystemInformation(systemId); + + if(systemInformation == null) + { + throw new RadioReferenceException("Radio Reference didn't provide system [" + systemId + "]"); + } + + long lastUpdated = getTime(systemInformation.getLastUpdated()); + boolean changed = lastUpdated > configuration.getSynchronizedLastUpdated(); + boolean synchronize = force || (configuration.isAutoUpdate() && changed); + + List talkgroups = null; + Map categoryNames = new HashMap<>(); + System system = null; + RadioReferenceDecoder decoder = null; + + if(synchronize) + { + decoder = getRadioReferenceDecoder(); + system = toSystem(systemId, systemInformation); + talkgroups = service.getTalkgroups(systemId); + + List categories = service.getTalkgroupCategories(systemId); + + if(categories != null) + { + for(TalkgroupCategory category: categories) + { + categoryNames.put(category.getTalkgroupCategoryId(), category.getName()); + } + } + } + + synchronized(mFailedAttempts) + { + mFailedAttempts.remove(systemId); + } + + List talkgroupsToApply = talkgroups; + System systemToApply = system; + RadioReferenceDecoder decoderToApply = decoder; + String systemName = systemInformation.getName(); + + runOnFxThread(() -> { + try + { + future.complete(apply(configuration, systemId, systemName, lastUpdated, talkgroupsToApply, + categoryNames, systemToApply, decoderToApply)); + } + catch(Throwable t) + { + future.completeExceptionally(t); + } + }); + } + catch(Throwable t) + { + synchronized(mFailedAttempts) + { + mFailedAttempts.put(systemId, java.lang.System.currentTimeMillis()); + } + + future.completeExceptionally(t); + } + } + }); + + return future; + } + + /** + * Records the check and applies the talkgroups to the alias list. Runs on the FX thread. + * @param talkgroups to apply, or null when only recording the check + */ + @VisibleForTesting + Result apply(AliasListConfiguration configuration, int systemId, String systemName, long lastUpdated, + List talkgroups, Map categoryNames, System system, + RadioReferenceDecoder decoder) + { + //The user may have deleted the alias list or stopped tracking while the request was in progress + if(!mAliasModel.aliasListConfigurations().contains(configuration) || !configuration.isTracking(systemId)) + { + return new Result(false, 0, 0, lastUpdated); + } + + configuration.setLastChecked(java.lang.System.currentTimeMillis()); + configuration.setRadioReferenceLastUpdated(lastUpdated); + + if(systemName != null && !systemName.isEmpty()) + { + configuration.setRadioReferenceSystemName(systemName); + } + + if(talkgroups == null) + { + return new Result(false, 0, 0, lastUpdated); + } + + String aliasListName = configuration.getName(); + long previousSynchronization = configuration.getSynchronizedLastUpdated(); + boolean encryptedDoNotMonitor = mUserPreferences.getRadioReferencePreference().isEncryptedTalkgroupDoNotMonitor(); + + List listAliases = new ArrayList<>(); + + for(Alias alias: mAliasModel.getAliases()) + { + if(aliasListName.equals(alias.getAliasListName())) + { + listAliases.add(alias); + } + } + + List created = new ArrayList<>(); + int updated = 0; + + for(Talkgroup talkgroup: talkgroups) + { + io.github.dsheirer.alias.id.talkgroup.Talkgroup aliasId = decoder.getTalkgroupAliasId(talkgroup, system); + String group = categoryNames.get(talkgroup.getTalkgroupCategoryId()); + List matches = getMatches(listAliases, aliasId); + + if(matches.isEmpty()) + { + Alias alias = decoder.createAlias(talkgroup, system, aliasListName, group); + + if(encryptedDoNotMonitor && + TalkgroupEncryption.lookup(talkgroup.getEncryptionState()) == TalkgroupEncryption.FULL) + { + alias.addAliasID(new io.github.dsheirer.alias.id.priority.Priority( + io.github.dsheirer.alias.id.priority.Priority.DO_NOT_MONITOR)); + } + + created.add(alias); + listAliases.add(alias); + } + //Only update aliases for talkgroups that changed on Radio Reference after the previous synchronization, so + //that the first synchronization and unchanged talkgroups keep any names the user has edited. + else if(previousSynchronization > 0 && getTime(talkgroup.getLastUpdated()) > previousSynchronization) + { + for(Alias alias: matches) + { + boolean aliasUpdated = false; + String name = talkgroup.getAlphaTag(); + + if(name != null && !name.isEmpty() && !Objects.equals(name, alias.getName())) + { + alias.setName(name); + aliasUpdated = true; + } + + if(group != null && !group.isEmpty() && !Objects.equals(group, alias.getGroup())) + { + alias.setGroup(group); + aliasUpdated = true; + } + + if(aliasUpdated) + { + updated++; + } + } + } + } + + if(!created.isEmpty()) + { + mAliasModel.addAliases(created); + } + + configuration.setSynchronizedLastUpdated(lastUpdated); + + mLog.info("Alias list [" + aliasListName + "] synchronized with Radio Reference system [" + + configuration.getRadioReferenceSystemId() + "] - added [" + created.size() + "] updated [" + updated + + "] aliases"); + + return new Result(true, created.size(), updated, lastUpdated); + } + + /** + * Aliases with a talkgroup alias identifier that matches the talkgroup. + */ + private static List getMatches(List aliases, io.github.dsheirer.alias.id.talkgroup.Talkgroup aliasId) + { + List matches = new ArrayList<>(); + + for(Alias alias: aliases) + { + for(AliasID id: alias.getAliasIdentifiers()) + { + if(aliasId.matches(id)) + { + matches.add(alias); + break; + } + } + } + + return matches; + } + + /** + * Decoder for talkgroup values and protocols, created on first use from the cached Radio Reference maps. + */ + private RadioReferenceDecoder getRadioReferenceDecoder() throws RadioReferenceException + { + if(mRadioReferenceDecoder == null) + { + RadioReferenceService service = mRadioReference.getService(); + mRadioReferenceDecoder = new RadioReferenceDecoder(mUserPreferences, service.getTypesMap(), + service.getFlavorsMap(), service.getVoicesMap(), service.getTagsMap()); + } + + return mRadioReferenceDecoder; + } + + /** + * Creates a system from the system information, for the decoder's protocol lookup. + */ + private static System toSystem(int systemId, SystemInformation systemInformation) + { + System system = new System(); + system.setSystemId(systemId); + system.setName(systemInformation.getName()); + system.setTypeId(systemInformation.getTypeId()); + system.setFlavorId(systemInformation.getFlavorId()); + system.setVoiceId(systemInformation.getVoiceId()); + system.setCity(systemInformation.getCity()); + system.setLastUpdated(systemInformation.getLastUpdated()); + return system; + } + + private static long getTime(Date date) + { + return date != null ? date.getTime() : 0; + } + + /** + * Runs on the FX thread, or on this thread when the FX toolkit isn't running (headless). + */ + private static void runOnFxThread(Runnable runnable) + { + if(Platform.isFxApplicationThread()) + { + runnable.run(); + return; + } + + try + { + Platform.runLater(runnable); + } + catch(IllegalStateException ise) + { + runnable.run(); + } + } + + /** + * Message for an exception, unwrapping completion exceptions. + */ + public static String getMessage(Throwable throwable) + { + Throwable cause = throwable; + + while(cause.getCause() != null && (cause instanceof java.util.concurrent.CompletionException || + cause instanceof java.util.concurrent.ExecutionException)) + { + cause = cause.getCause(); + } + + return cause.getMessage() != null ? cause.getMessage() : cause.getClass().getSimpleName(); + } + + /** + * Synchronization result + * @param applied true if the talkgroups were applied to the alias list + * @param added alias count + * @param updated alias count + * @param lastUpdated Radio Reference system last updated timestamp + */ + public record Result(boolean applied, int added, int updated, long lastUpdated) {} +} diff --git a/src/main/java/io/github/dsheirer/service/radioreference/CachingRadioReferenceService.java b/src/main/java/io/github/dsheirer/service/radioreference/CachingRadioReferenceService.java index b54c798a..af61b174 100644 --- a/src/main/java/io/github/dsheirer/service/radioreference/CachingRadioReferenceService.java +++ b/src/main/java/io/github/dsheirer/service/radioreference/CachingRadioReferenceService.java @@ -148,6 +148,17 @@ public class CachingRadioReferenceService extends RadioReferenceService return get(mTalkgroupCache, systemId); } + /** + * Discards the cached system information and talkgroups for the system so that the next request reads current + * values from the web service. + * @param systemId to discard + */ + public void invalidateSystem(int systemId) + { + mSystemInfoCache.invalidate(systemId); + mTalkgroupCache.invalidate(systemId); + } + /** * Loads a value from the web service */ diff --git a/src/test/java/io/github/dsheirer/alias/AliasListConfigurationTest.java b/src/test/java/io/github/dsheirer/alias/AliasListConfigurationTest.java new file mode 100644 index 00000000..282a3151 --- /dev/null +++ b/src/test/java/io/github/dsheirer/alias/AliasListConfigurationTest.java @@ -0,0 +1,119 @@ +/* + * ***************************************************************************** + * Copyright (C) 2014-2026 Dennis Sheirer + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see + * **************************************************************************** + */ + +package io.github.dsheirer.alias; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import io.github.dsheirer.playlist.PlaylistV2; +import java.util.List; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Alias list configuration persistence and alias model rename/delete handling. + */ +public class AliasListConfigurationTest +{ + private static ObjectMapper mapper() + { + JacksonXmlModule xmlModule = new JacksonXmlModule(); + xmlModule.setDefaultUseWrapper(false); + return new XmlMapper(xmlModule).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + } + + @Test + void playlistRoundTrip() throws Exception + { + AliasListConfiguration configuration = new AliasListConfiguration("County P25"); + configuration.track(1234, "County Public Safety"); + configuration.setAutoUpdate(true); + configuration.setRadioReferenceLastUpdated(2000L); + configuration.setSynchronizedLastUpdated(1000L); + configuration.setLastChecked(3000L); + + Alias alias = new Alias("Fire Dispatch"); + alias.setAliasListName("County P25"); + + PlaylistV2 playlist = new PlaylistV2(); + playlist.getAliases().add(alias); + playlist.getAliasListConfigurations().add(configuration); + + String xml = mapper().writeValueAsString(playlist); + PlaylistV2 read = mapper().readValue(xml, PlaylistV2.class); + + assertEquals(1, read.getAliasListConfigurations().size(), xml); + AliasListConfiguration readConfiguration = read.getAliasListConfigurations().get(0); + assertEquals("County P25", readConfiguration.getName()); + assertEquals(1234, readConfiguration.getRadioReferenceSystemId()); + assertEquals("County Public Safety", readConfiguration.getRadioReferenceSystemName()); + assertTrue(readConfiguration.isAutoUpdate()); + assertEquals(2000L, readConfiguration.getRadioReferenceLastUpdated()); + assertEquals(1000L, readConfiguration.getSynchronizedLastUpdated()); + assertEquals(3000L, readConfiguration.getLastChecked()); + assertTrue(readConfiguration.isUpdateAvailable()); + assertEquals(1, read.getAliases().size()); + } + + @Test + void legacyPlaylistWithoutConfigurations() throws Exception + { + String xml = ""; + PlaylistV2 read = mapper().readValue(xml, PlaylistV2.class); + assertTrue(read.getAliasListConfigurations().isEmpty()); + assertEquals(1, read.getAliases().size()); + } + + @Test + void trackingLookupRenameAndDelete() + { + AliasModel model = new AliasModel(); + model.addAliasListConfigurations(List.of(new AliasListConfiguration("Plain"))); + AliasListConfiguration tracked = model.getOrCreateAliasListConfiguration("Tracked"); + tracked.track(42, "System 42"); + + //Configured alias lists are listed before they have any aliases + assertTrue(model.aliasListNames().contains("Tracked")); + assertEquals("Tracked", model.getAliasListNameTracking(42)); + assertNull(model.getAliasListNameTracking(7)); + assertFalse(model.getAliasListConfiguration("Plain").isTrackingRadioReferenceSystem()); + + Alias alias = new Alias("TG 1"); + alias.setAliasListName("Tracked"); + model.addAlias(alias); + + model.renameAliasList("Tracked", "Renamed"); + assertEquals("Renamed", model.getAliasListNameTracking(42)); + assertEquals("Renamed", alias.getAliasListName()); + assertNull(model.getAliasListConfiguration("Tracked")); + + model.refreshAliasListNames(); + assertTrue(model.aliasListNames().contains("Plain")); + + model.deleteAliasList("Renamed"); + assertNull(model.getAliasListNameTracking(42)); + assertTrue(model.getAliases().isEmpty()); + } +} diff --git a/src/test/java/io/github/dsheirer/service/radioreference/AliasListSynchronizerTest.java b/src/test/java/io/github/dsheirer/service/radioreference/AliasListSynchronizerTest.java new file mode 100644 index 00000000..0ac001b8 --- /dev/null +++ b/src/test/java/io/github/dsheirer/service/radioreference/AliasListSynchronizerTest.java @@ -0,0 +1,164 @@ +/* + * ***************************************************************************** + * Copyright (C) 2014-2026 Dennis Sheirer + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see + * **************************************************************************** + */ + +package io.github.dsheirer.service.radioreference; + +import io.github.dsheirer.alias.Alias; +import io.github.dsheirer.alias.AliasListConfiguration; +import io.github.dsheirer.alias.AliasModel; +import io.github.dsheirer.alias.id.AliasIDType; +import io.github.dsheirer.gui.playlist.radioreference.RadioReferenceDecoder; +import io.github.dsheirer.preference.UserPreferences; +import io.github.dsheirer.protocol.Protocol; +import io.github.dsheirer.rrapi.type.System; +import io.github.dsheirer.rrapi.type.Talkgroup; +import io.github.dsheirer.rrapi.type.Type; +import java.util.Date; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Applying Radio Reference talkgroups to a tracked alias list, without the web service. + */ +public class AliasListSynchronizerTest +{ + private static final int SYSTEM_ID = 42; + private static final String LIST = "Tracked"; + + private AliasModel mAliasModel; + private AliasListSynchronizer mSynchronizer; + private RadioReferenceDecoder mDecoder; + private System mSystem; + private AliasListConfiguration mConfiguration; + + @BeforeEach + void setup() + { + UserPreferences userPreferences = new UserPreferences(); + mAliasModel = new AliasModel(); + mSynchronizer = new AliasListSynchronizer(mAliasModel, null, userPreferences); + + Type p25 = new Type(); + p25.setTypeId(1); + p25.setName("Project 25"); + mDecoder = new RadioReferenceDecoder(userPreferences, Map.of(1, p25), Map.of(), Map.of(), Map.of()); + + mSystem = new System(); + mSystem.setSystemId(SYSTEM_ID); + mSystem.setTypeId(1); + + mConfiguration = mAliasModel.getOrCreateAliasListConfiguration(LIST); + mConfiguration.track(SYSTEM_ID, "System"); + } + + private static Talkgroup talkgroup(int value, String alphaTag, int categoryId, long lastUpdated) + { + Talkgroup talkgroup = new Talkgroup(); + talkgroup.setDecimalValue(value); + talkgroup.setAlphaTag(alphaTag); + talkgroup.setTalkgroupCategoryId(categoryId); + talkgroup.setLastUpdated(new Date(lastUpdated)); + return talkgroup; + } + + private AliasListSynchronizer.Result apply(long lastUpdated, List talkgroups) + { + return mSynchronizer.apply(mConfiguration, SYSTEM_ID, "System", lastUpdated, talkgroups, + Map.of(1, "Fire", 2, "Police"), mSystem, mDecoder); + } + + private Alias alias(int value) + { + return mAliasModel.getAliases(LIST, AliasIDType.TALKGROUP).stream() + .filter(a -> a.getAliasIdentifiers().stream().anyMatch(id -> + new io.github.dsheirer.alias.id.talkgroup.Talkgroup(Protocol.APCO25, value).matches(id))) + .findFirst().orElseThrow(); + } + + @Test + void firstSynchronizationAddsMissingAndKeepsExistingNames() + { + //The user already has an alias for talkgroup 100 with their own name + Alias existing = new Alias("My Name"); + existing.setAliasListName(LIST); + existing.addAliasID(new io.github.dsheirer.alias.id.talkgroup.Talkgroup(Protocol.APCO25, 100)); + mAliasModel.addAlias(existing); + + AliasListSynchronizer.Result result = apply(5000, + List.of(talkgroup(100, "FD Dispatch", 1, 4000), talkgroup(200, "PD Main", 2, 4000))); + + assertTrue(result.applied()); + assertEquals(1, result.added()); + assertEquals(0, result.updated()); + assertEquals("My Name", alias(100).getName()); + assertEquals("PD Main", alias(200).getName()); + assertEquals("Police", alias(200).getGroup()); + assertEquals(5000, mConfiguration.getSynchronizedLastUpdated()); + assertEquals(5000, mConfiguration.getRadioReferenceLastUpdated()); + assertTrue(mConfiguration.getLastChecked() > 0); + assertFalse(mConfiguration.isUpdateAvailable()); + } + + @Test + void laterSynchronizationUpdatesOnlyChangedTalkgroups() + { + apply(5000, List.of(talkgroup(100, "FD Dispatch", 1, 4000), talkgroup(200, "PD Main", 2, 4000))); + alias(200).setName("User Edited"); + + //Talkgroup 100 was renamed on Radio Reference after the first synchronization; 200 didn't change + AliasListSynchronizer.Result result = apply(9000, List.of(talkgroup(100, "FD Dispatch 1", 2, 8000), + talkgroup(200, "PD Main", 2, 4000), talkgroup(300, "EMS", 1, 8000))); + + assertEquals(1, result.added()); + assertEquals(1, result.updated()); + assertEquals("FD Dispatch 1", alias(100).getName()); + assertEquals("Police", alias(100).getGroup()); + assertEquals("User Edited", alias(200).getName()); + assertEquals("EMS", alias(300).getName()); + assertEquals(9000, mConfiguration.getSynchronizedLastUpdated()); + } + + @Test + void checkOnlyRecordsTimestamps() + { + AliasListSynchronizer.Result result = apply(7000, null); + + assertFalse(result.applied()); + assertEquals(7000, mConfiguration.getRadioReferenceLastUpdated()); + assertEquals(0, mConfiguration.getSynchronizedLastUpdated()); + assertTrue(mConfiguration.isUpdateAvailable()); + assertTrue(mAliasModel.getAliases().isEmpty()); + } + + @Test + void deletedAliasListIsIgnored() + { + mAliasModel.deleteAliasList(LIST); + AliasListSynchronizer.Result result = apply(5000, List.of(talkgroup(100, "FD Dispatch", 1, 4000))); + + assertFalse(result.applied()); + assertTrue(mAliasModel.getAliases().isEmpty()); + } +}