Display the last connection time in dashboard/wivrnctl

This commit is contained in:
Guillaume Meunier
2025-03-25 21:15:01 +01:00
parent e0a1598ac5
commit 57a0cf1d4b
10 changed files with 252 additions and 57 deletions
+27 -4
View File
@@ -1,5 +1,5 @@
pragma ComponentBehavior: Bound pragma ComponentBehavior: Bound
import QtQml
import QtQuick import QtQuick
import QtQuick.Layouts import QtQuick.Layouts
import QtQuick.Controls as Controls import QtQuick.Controls as Controls
@@ -13,6 +13,28 @@ Kirigami.ScrollablePage {
// flickable.interactive: false // flickable.interactive: false
property date now: new Date()
Timer {
interval: 1000
running: true
repeat: true
onTriggered: headsets.now = new Date();
}
function fuzzy_relative_date(then) {
var time_difference = (headsets.now.getTime() - then.getTime()) / 1000;
if (time_difference < 60)
return i18np("Last connection: %1 second ago", "Last connection: %1 seconds ago", Math.round(time_difference));
if (time_difference < 3600)
return i18np("Last connection: %1 minute ago", "Last connection: %1 minutes ago", Math.round(time_difference / 60));
if (time_difference < 86400)
return i18np("Last connection: %1 hour ago", "Last connection: %1 hours ago", Math.round(time_difference / 3600));
return i18np("Last connection: %1 day ago", "Last connection: %1 days ago", Math.round(time_difference / 86400));
}
Kirigami.PromptDialog { Kirigami.PromptDialog {
id: rename_headset id: rename_headset
title: i18n("Rename headset") title: i18n("Rename headset")
@@ -32,7 +54,7 @@ Kirigami.ScrollablePage {
Kirigami.Action { Kirigami.Action {
text: i18n("Cancel") text: i18n("Cancel")
icon.name: "dialog-cancel" icon.name: "dialog-cancel"
onTriggered: rename_headset.close(); onTriggered: rename_headset.close()
} }
] ]
ColumnLayout { ColumnLayout {
@@ -62,6 +84,8 @@ Kirigami.ScrollablePage {
id: headset id: headset
required property string name required property string name
required property string publicKey required property string publicKey
required property bool hasLastConnection
required property date lastConnection
contentItem: GridLayout { contentItem: GridLayout {
id: delegate_layout id: delegate_layout
@@ -83,8 +107,7 @@ Kirigami.ScrollablePage {
Layout.column: 0 Layout.column: 0
Layout.row: 1 Layout.row: 1
wrapMode: Text.WordWrap wrapMode: Text.WordWrap
// text: "Last connection: unknown" text: headset.hasLastConnection ? headsets.fuzzy_relative_date(headset.lastConnection) : ""
text: ""
} }
Controls.Button { Controls.Button {
+7 -2
View File
@@ -348,10 +348,15 @@ void wivrn_server::on_server_properties_changed(const QString & interface_name,
keys.beginStructure(); keys.beginStructure();
QString public_key; QString public_key;
QString name; QString name;
keys >> name >> public_key; qlonglong last_connection_timestamp;
keys >> name >> public_key >> last_connection_timestamp;
keys.endStructure(); keys.endStructure();
m_knownKeys.push_back(headset{name, public_key}); headset h{name, public_key};
if (last_connection_timestamp)
h.setLastConnection(QDateTime::fromSecsSinceEpoch(last_connection_timestamp));
m_knownKeys.push_back(h);
} }
keys.endArray(); keys.endArray();
+22
View File
@@ -20,6 +20,7 @@
#include <QDBusPendingCallWatcher> #include <QDBusPendingCallWatcher>
#include <QDBusServiceWatcher> #include <QDBusServiceWatcher>
#include <QDateTime>
#include <QObject> #include <QObject>
#include <QProcess> #include <QProcess>
#include <QSize> #include <QSize>
@@ -39,9 +40,12 @@ class headset
QML_ELEMENT QML_ELEMENT
Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(QString name READ name WRITE setName)
Q_PROPERTY(QString publicKey READ publicKey WRITE setPublicKey) Q_PROPERTY(QString publicKey READ publicKey WRITE setPublicKey)
Q_PROPERTY(bool hasLastConnection READ hasLastConnection)
Q_PROPERTY(QDateTime lastConnection READ lastConnection WRITE setLastConnection)
QString m_name; QString m_name;
QString m_publicKey; QString m_publicKey;
QDateTime m_lastConnection;
public: public:
headset() = default; headset() = default;
@@ -49,6 +53,9 @@ public:
headset(headset &&) = default; headset(headset &&) = default;
headset & operator=(const headset &) = default; headset & operator=(const headset &) = default;
headset & operator=(headset &&) = default; headset & operator=(headset &&) = default;
headset(QString name, QString publicKey, QDateTime lastConnection) :
m_name(name), m_publicKey(publicKey), m_lastConnection(lastConnection) {}
headset(QString name, QString publicKey) : headset(QString name, QString publicKey) :
m_name(name), m_publicKey(publicKey) {} m_name(name), m_publicKey(publicKey) {}
@@ -62,6 +69,16 @@ public:
return m_publicKey; return m_publicKey;
} }
QDateTime lastConnection() const
{
return m_lastConnection;
}
bool hasLastConnection() const
{
return !m_lastConnection.isNull();
}
void setName(QString value) void setName(QString value)
{ {
m_name = value; m_name = value;
@@ -71,6 +88,11 @@ public:
{ {
m_publicKey = value; m_publicKey = value;
} }
void setLastConnection(QDateTime value)
{
m_lastConnection = value;
}
}; };
class wivrn_server : public QObject class wivrn_server : public QObject
+3 -3
View File
@@ -67,9 +67,9 @@
<property name="SupportedCodecs" type="as" access="read"/> <property name="SupportedCodecs" type="as" access="read"/>
<property name="Pin" type="s" access="read"/> <property name="Pin" type="s" access="read"/>
<property name="KnownKeys" type="a(ss)" access="read"> <property name="KnownKeys" type="a(ssx)" access="read">
<annotation name="org.qtproject.QtDBus.QtTypeName" value="QList&lt;std::pair&lt;QString,QString&gt;&gt;"/> <annotation name="org.qtproject.QtDBus.QtTypeName" value="QList&lt;std::tuple&lt;QString,QString,uint64_t&gt;&gt;"/>
<!-- first: name, second: public key --> <!-- first: name, second: public key, third: last connection timestamp (seconds since epoch, or 0) -->
</property> </property>
<property name="PairingEnabled" type="b" access="read"/> <property name="PairingEnabled" type="b" access="read"/>
<property name="EncryptionEnabled" type="b" access="read"/> <property name="EncryptionEnabled" type="b" access="read"/>
+55 -25
View File
@@ -2,55 +2,56 @@ msgid ""
msgstr "" msgstr ""
"Project-Id-Version: WiVRn-dashboard\n" "Project-Id-Version: WiVRn-dashboard\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2025-02-02 23:45+0100\n" "POT-Creation-Date: 2025-02-03 20:03+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: Guillaume Meunier <guillaume.meunier@centraliens.net>\n" "Last-Translator: Guillaume Meunier <guillaume.meunier@centraliens.net>\n"
"Language: French\n" "Language: French\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n" "Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n" "Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
#: dashboard/apk_installer.cpp:175 #: dashboard/apk_installer.cpp:167
#, kde-format #, kde-format
msgid "Downloading APK: %1 MB / %2 MB" msgid "Downloading APK: %1 MB / %2 MB"
msgstr "Téléchargement de l'APK : %1 MB / %2 MB" msgstr "Téléchargement de l'APK : %1 MB / %2 MB"
#: dashboard/apk_installer.cpp:177 #: dashboard/apk_installer.cpp:169
#, kde-format #, kde-format
msgid "Downloading APK: %1 MB" msgid "Downloading APK: %1 MB"
msgstr "Téléchargement de l'APK : %1 MB" msgstr "Téléchargement de l'APK : %1 MB"
#: dashboard/apk_installer.cpp:186 #: dashboard/apk_installer.cpp:178
#, kde-format #, kde-format
msgid "Download cancelled" msgid "Download cancelled"
msgstr "Téléchargement annulé" msgstr "Téléchargement annulé"
#: dashboard/apk_installer.cpp:202 #: dashboard/apk_installer.cpp:194
#, kde-format #, kde-format
msgid "Cannot download APK: %1" msgid "Cannot download APK: %1"
msgstr "Impossible de télécharger l'APK : %1" msgstr "Impossible de télécharger l'APK : %1"
#: dashboard/apk_installer.cpp:225 #: dashboard/apk_installer.cpp:217
#, kde-format #, kde-format
msgid "Installing APK" msgid "Installing APK"
msgstr "Installation de l'APK" msgstr "Installation de l'APK"
#: dashboard/apk_installer.cpp:229 #: dashboard/apk_installer.cpp:221
#, kde-format #, kde-format
msgid "adb failed to start: %1" msgid "adb failed to start: %1"
msgstr "adb n'a pas pu démarrer : %1" msgstr "adb n'a pas pu démarrer : %1"
#: dashboard/apk_installer.cpp:239 #: dashboard/apk_installer.cpp:231
#, kde-format #, kde-format
msgid "adb exited abnormally: %1" msgid "adb exited abnormally: %1"
msgstr "adb a quitté de façon anormale : %1" msgstr "adb a quitté de façon anormale : %1"
#: dashboard/apk_installer.cpp:247 #: dashboard/apk_installer.cpp:239
#, kde-format #, kde-format
msgid "The 'adb install' command failed: exit code %1" msgid "The 'adb install' command failed: exit code %1"
msgstr "La commande 'adb install' a échoué : code de retour %1" msgstr "La commande 'adb install' a échoué : code de retour %1"
#: dashboard/apk_installer.cpp:252 #: dashboard/apk_installer.cpp:244
#, kde-format #, kde-format
msgid "Installation successful" msgid "Installation successful"
msgstr "Installation réussie" msgstr "Installation réussie"
@@ -93,11 +94,12 @@ msgid ""
"Follow the instructions in the <a href=\"https://github.com/WiVRn/WiVRn/blob/" "Follow the instructions in the <a href=\"https://github.com/WiVRn/WiVRn/blob/"
"master/docs/building.md#client-headset\">documentation</a> to build your own " "master/docs/building.md#client-headset\">documentation</a> to build your own "
"client." "client."
msgstr "Suivez les instructions dans la <a href=\"https://github.com/WiVRn/WiVRn/blob/master/" msgstr ""
"docs/building.md#client-headset\">documentation</a> pour construire votre " "Suivez les instructions dans la <a href=\"https://github.com/WiVRn/WiVRn/"
"propre client." "blob/master/docs/building.md#client-headset\">documentation</a> pour "
"construire votre propre client."
#: dashboard/qml/ApkInstallPage.qml:65 dashboard/qml/HeadsetsPage.qml:160 #: dashboard/qml/ApkInstallPage.qml:65 dashboard/qml/HeadsetsPage.qml:183
#: dashboard/qml/HeadsetStatsPage.qml:36 #: dashboard/qml/HeadsetStatsPage.qml:36
#, kde-format #, kde-format
msgctxt "go back to the home page" msgctxt "go back to the home page"
@@ -129,61 +131,89 @@ msgstr "Installer WiVRn"
msgid "Headsets" msgid "Headsets"
msgstr "Casques" msgstr "Casques"
#: dashboard/qml/HeadsetsPage.qml:18 #: dashboard/qml/HeadsetsPage.qml:29
#, kde-format
msgid "Last connection: %1 second ago"
msgid_plural "Last connection: %1 seconds ago"
msgstr[0] "Dernière connexion : il a y %1 seconde"
msgstr[1] "Dernière connexion : il a y %1 secondes"
#: dashboard/qml/HeadsetsPage.qml:31
#, kde-format
msgid "Last connection: %1 minute ago"
msgid_plural "Last connection: %1 minutes ago"
msgstr[0] "Dernière connexion : il a y %1 minute"
msgstr[1] "Dernière connexion : il a y %1 minutes"
#: dashboard/qml/HeadsetsPage.qml:33
#, kde-format
msgid "Last connection: %1 hour ago"
msgid_plural "Last connection: %1 hours ago"
msgstr[0] "Dernière connexion : il a y %1 heure"
msgstr[1] "Dernière connexion : il a y %1 heures"
#: dashboard/qml/HeadsetsPage.qml:35
#, kde-format
msgid "Last connection: %1 day ago"
msgid_plural "Last connection: %1 days ago"
msgstr[0] "Dernière connexion : il a y %1 jour"
msgstr[1] "Dernière connexion : il a y %1 jours"
#: dashboard/qml/HeadsetsPage.qml:40
#, kde-format #, kde-format
msgid "Rename headset" msgid "Rename headset"
msgstr "Renommer le casque" msgstr "Renommer le casque"
#: dashboard/qml/HeadsetsPage.qml:26 dashboard/qml/HeadsetsPage.qml:93 #: dashboard/qml/HeadsetsPage.qml:48 dashboard/qml/HeadsetsPage.qml:116
#, kde-format #, kde-format
msgid "Rename" msgid "Rename"
msgstr "Renommer" msgstr "Renommer"
#: dashboard/qml/HeadsetsPage.qml:33 dashboard/qml/WizardPage.qml:38 #: dashboard/qml/HeadsetsPage.qml:55 dashboard/qml/WizardPage.qml:38
#: dashboard/qml/WizardPage.qml:88 dashboard/qml/WizardPage.qml:263 #: dashboard/qml/WizardPage.qml:88 dashboard/qml/WizardPage.qml:263
#: dashboard/qml/WizardPage.qml:312 dashboard/qml/WizardPage.qml:396 #: dashboard/qml/WizardPage.qml:312 dashboard/qml/WizardPage.qml:396
#, kde-format #, kde-format
msgid "Cancel" msgid "Cancel"
msgstr "Annuler" msgstr "Annuler"
#: dashboard/qml/HeadsetsPage.qml:42 #: dashboard/qml/HeadsetsPage.qml:64
#, kde-format #, kde-format
msgid "Headset name…" msgid "Headset name…"
msgstr "Nom du casque…" msgstr "Nom du casque…"
#: dashboard/qml/HeadsetsPage.qml:105 #: dashboard/qml/HeadsetsPage.qml:128
#, kde-format #, kde-format
msgid "Remove" msgid "Remove"
msgstr "Enlever" msgstr "Enlever"
#: dashboard/qml/HeadsetsPage.qml:120 #: dashboard/qml/HeadsetsPage.qml:143
#, kde-format #, kde-format
msgid "Pairing enabled, PIN: %1" msgid "Pairing enabled, PIN: %1"
msgstr "Appairage activé, PIN : %1 " msgstr "Appairage activé, PIN : %1 "
#: dashboard/qml/HeadsetsPage.qml:125 #: dashboard/qml/HeadsetsPage.qml:148
#, kde-format #, kde-format
msgid "Disable pairing" msgid "Disable pairing"
msgstr "Désactiver l'appairage" msgstr "Désactiver l'appairage"
#: dashboard/qml/HeadsetsPage.qml:143 #: dashboard/qml/HeadsetsPage.qml:166
#, kde-format #, kde-format
msgid "Start the WiVRn app on your headset and use the PIN: %1" msgid "Start the WiVRn app on your headset and use the PIN: %1"
msgstr "Démarrez l'appli WiVRn sur votre casque et utilisez le PIN : %1" msgstr "Démarrez l'appli WiVRn sur votre casque et utilisez le PIN : %1"
#: dashboard/qml/HeadsetsPage.qml:143 #: dashboard/qml/HeadsetsPage.qml:166
#, kde-format #, kde-format
msgid "Enable pairing to allow your headset to connect to this computer" msgid "Enable pairing to allow your headset to connect to this computer"
msgstr "" msgstr ""
"Activez l'appairage pour autoriser votre casque à se connecter à cet " "Activez l'appairage pour autoriser votre casque à se connecter à cet "
"ordinateur" "ordinateur"
#: dashboard/qml/HeadsetsPage.qml:148 #: dashboard/qml/HeadsetsPage.qml:171
#, kde-format #, kde-format
msgid "Enable pairing" msgid "Enable pairing"
msgstr "Activer l'appairage" msgstr "Activer l'appairage"
#: dashboard/qml/HeadsetsPage.qml:168 #: dashboard/qml/HeadsetsPage.qml:191
#, kde-format #, kde-format
msgid "Pair a new headset" msgid "Pair a new headset"
msgstr "Appairer un nouveau casque" msgstr "Appairer un nouveau casque"
+65 -10
View File
@@ -20,6 +20,8 @@
#define JSON_DISABLE_ENUM_SERIALIZATION 1 #define JSON_DISABLE_ENUM_SERIALIZATION 1
#include <algorithm> #include <algorithm>
#include <chrono>
#include <ctime>
#include <filesystem> #include <filesystem>
#include <fstream> #include <fstream>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
@@ -204,6 +206,36 @@ std::string server_cookie()
} }
} }
std::string to_iso8601(std::chrono::system_clock::time_point timestamp)
{
// Truncate to an integer number of seconds to be parsable by strptime
auto t = std::chrono::time_point_cast<std::chrono::seconds>(timestamp);
#if __cpp_lib_chrono >= 201907L
return std::format("{:%FT%H:%M:%S%z}", std::chrono::zoned_time{std::chrono::current_zone(), t});
#else
return std::format("{:%FT%H:%M:%S%z}", t);
#endif
}
template <typename T>
std::string to_iso8601(std::chrono::zoned_time<T> timestamp)
{
return std::format("{:%FT%H:%M:%S%z}", timestamp);
}
std::optional<std::chrono::system_clock::time_point> from_iso8601(const std::string & timestamp)
{
tm t;
if (strptime(timestamp.c_str(), "%FT%H:%M:%S%z", &t) == nullptr)
return std::nullopt;
// Convert from local time to UTC
t.tm_sec += t.tm_gmtoff;
return std::chrono::system_clock::from_time_t(mktime(&t));
}
std::vector<headset_key> known_keys() std::vector<headset_key> known_keys()
{ {
if (not std::filesystem::exists(known_keys_file)) if (not std::filesystem::exists(known_keys_file))
@@ -217,7 +249,15 @@ std::vector<headset_key> known_keys()
for (const auto & key: json) for (const auto & key: json)
{ {
keys.emplace_back(key["key"], key["name"]); headset_key k{
.public_key = key["key"],
.name = key["name"],
};
if (key.contains("last_connection"))
k.last_connection = from_iso8601(key["last_connection"]);
keys.push_back(k);
} }
return keys; return keys;
@@ -235,10 +275,13 @@ static void save_keys(const std::vector<headset_key> & keys)
for (const auto & key: keys) for (const auto & key: keys)
{ {
nlohmann::json key_json; nlohmann::json json_key;
key_json["key"] = key.public_key; json_key["key"] = key.public_key;
key_json["name"] = key.name; json_key["name"] = key.name;
json.push_back(key_json); if (key.last_connection)
json_key["last_connection"] = to_iso8601(*key.last_connection);
json.push_back(json_key);
} }
std::string json_str = json.dump(); std::string json_str = json.dump();
@@ -260,6 +303,7 @@ void add_known_key(headset_key key)
{ {
std::vector<headset_key> keys = known_keys(); std::vector<headset_key> keys = known_keys();
key.last_connection = std::chrono::system_clock::now();
if (key.name == "") if (key.name == "")
key.name = "Unknown headset"; key.name = "Unknown headset";
@@ -286,13 +330,24 @@ void remove_known_key(const std::string & key)
void rename_known_key(headset_key key) void rename_known_key(headset_key key)
{ {
std::vector<headset_key> keys = known_keys(); std::vector<headset_key> keys = known_keys();
for (headset_key & k: keys)
{ auto key_iter = std::ranges::find(keys, key.public_key, &headset_key::public_key);
if (k.public_key == key.public_key) if (key_iter != keys.end())
k.name = key.name; key_iter->name = key.name;
}
save_keys(keys); save_keys(keys);
} }
void update_last_connection_timestamp(const std::string & key)
{
std::vector<headset_key> keys = known_keys();
auto key_iter = std::ranges::find(keys, key, &headset_key::public_key);
if (key_iter != keys.end())
{
key_iter->last_connection = std::chrono::system_clock::now();
save_keys(keys);
}
}
} // namespace wivrn } // namespace wivrn
+3
View File
@@ -20,6 +20,7 @@
#pragma once #pragma once
#include <array> #include <array>
#include <chrono>
#include <filesystem> #include <filesystem>
#include <map> #include <map>
#include <optional> #include <optional>
@@ -72,11 +73,13 @@ struct headset_key
{ {
std::string public_key; std::string public_key;
std::string name; std::string name;
std::optional<std::chrono::system_clock::time_point> last_connection;
}; };
std::vector<headset_key> known_keys(); std::vector<headset_key> known_keys();
void add_known_key(headset_key key); void add_known_key(headset_key key);
void remove_known_key(const std::string & key); void remove_known_key(const std::string & key);
void rename_known_key(headset_key key); void rename_known_key(headset_key key);
void update_last_connection_timestamp(const std::string & key);
} // namespace wivrn } // namespace wivrn
+2
View File
@@ -275,6 +275,8 @@ void wivrn::wivrn_connection::init(std::stop_token stop_token, std::function<voi
.public_key = clean_key(headset_key.public_key()), .public_key = clean_key(headset_key.public_key()),
.name = crypto_handshake.name, .name = crypto_handshake.name,
}); });
else if (state != encryption_state::disabled)
wivrn::update_last_connection_timestamp(clean_key(headset_key.public_key()));
} }
void wivrn::wivrn_connection::reset(TCP && tcp, std::function<void()> tick) void wivrn::wivrn_connection::reset(TCP && tcp, std::function<void()> tick)
+7 -3
View File
@@ -735,12 +735,16 @@ void on_json_configuration(WivrnServer * server, const GParamSpec * pspec, gpoin
void expose_known_keys_on_dbus() void expose_known_keys_on_dbus()
{ {
GVariantBuilder * builder = g_variant_builder_new(G_VARIANT_TYPE("a(ss)")); GVariantBuilder * builder = g_variant_builder_new(G_VARIANT_TYPE("a(ssx)"));
for (const auto & i: known_keys()) for (const auto & i: known_keys())
{ {
g_variant_builder_add(builder, "(ss)", i.name.c_str(), i.public_key.c_str()); g_variant_builder_add(builder,
"(ssx)",
i.name.c_str(),
i.public_key.c_str(),
i.last_connection ? std::chrono::duration_cast<std::chrono::seconds>((*i.last_connection).time_since_epoch()).count() : 0);
} }
GVariant * value = g_variant_new("a(ss)", builder); GVariant * value = g_variant_new("a(ssx)", builder);
g_variant_builder_unref(builder); g_variant_builder_unref(builder);
wivrn_server_set_known_keys(dbus_server, value); wivrn_server_set_known_keys(dbus_server, value);
} }
+61 -10
View File
@@ -17,6 +17,7 @@
*/ */
#include <CLI/CLI.hpp> #include <CLI/CLI.hpp>
#include <chrono>
#include <format> #include <format>
#include <ranges> #include <ranges>
#include <systemd/sd-bus.h> #include <systemd/sd-bus.h>
@@ -34,6 +35,13 @@ struct deleter
} }
}; };
struct headset
{
std::string name;
std::string public_key;
std::optional<std::chrono::system_clock::time_point> last_connection;
};
using sd_bus_ptr = std::unique_ptr<sd_bus, deleter>; using sd_bus_ptr = std::unique_ptr<sd_bus, deleter>;
using sd_bus_message_ptr = std::unique_ptr<sd_bus_message, deleter>; using sd_bus_message_ptr = std::unique_ptr<sd_bus_message, deleter>;
@@ -135,28 +143,34 @@ void print_table(const std::array<std::string, std::tuple_size_v<value_type>> &
} }
} }
std::vector<std::pair<std::string, std::string>> get_keys(const sd_bus_ptr & bus) std::vector<headset> get_keys(const sd_bus_ptr & bus)
{ {
auto msg = get_property(bus, auto msg = get_property(bus,
"KnownKeys", "KnownKeys",
"a(ss)"); "a(ssx)");
int ret = sd_bus_message_enter_container(msg.get(), 'a', "(ss)"); int ret = sd_bus_message_enter_container(msg.get(), 'a', "(ssx)");
if (ret < 0) if (ret < 0)
throw std::system_error(-ret, std::system_category(), "Failed to get paired headsets"); throw std::system_error(-ret, std::system_category(), "Failed to get paired headsets");
std::vector<std::pair<std::string, std::string>> values; std::vector<headset> values;
while (true) while (true)
{ {
char * name; char * name;
char * key; char * key;
int ret = sd_bus_message_read(msg.get(), "(ss)", &name, &key); int64_t timestamp;
int ret = sd_bus_message_read(msg.get(), "(ssx)", &name, &key, &timestamp);
if (ret == 0) if (ret == 0)
break; break;
if (ret < 0) if (ret < 0)
throw std::system_error(-ret, std::system_category(), "Failed to get paired headset details"); throw std::system_error(-ret, std::system_category(), "Failed to get paired headset details");
values.emplace_back(name, key); std::optional<std::chrono::system_clock::time_point> last_connection;
if (timestamp)
last_connection = std::chrono::system_clock::from_time_t(timestamp);
values.emplace_back(name, key, last_connection);
} }
return values; return values;
@@ -194,7 +208,37 @@ void unpair(size_t headset_id)
if (headset_id < 1 or headset_id > values.size()) if (headset_id < 1 or headset_id > values.size())
throw std::runtime_error(std::format("Invalid headset number: {}", headset_id)); throw std::runtime_error(std::format("Invalid headset number: {}", headset_id));
call_method(bus, "RevokeKey", "s", values.at(headset_id - 1).second.c_str()); call_method(bus, "RevokeKey", "s", values.at(headset_id - 1).public_key.c_str());
}
template <typename T, typename U>
auto member(T U::* x)
{
return std::views::transform([x](const auto & y) { return y.*x; });
}
std::string relative_timestamp(std::optional<std::chrono::system_clock::time_point> t)
{
static const auto now = std::chrono::system_clock::now();
if (!t)
return "Unknown";
auto how_long_ago = std::chrono::duration_cast<std::chrono::seconds>(now - *t).count();
if (how_long_ago < 0)
return std::format("{}", *t);
if (how_long_ago < 2 * 60)
return std::format("{} seconds ago", how_long_ago);
if (how_long_ago < 2 * 3600)
return std::format("{:.0f} minutes ago", how_long_ago / 60.);
if (how_long_ago < 2 * 86400)
return std::format("{:.0f} hours ago", how_long_ago / 3600.);
return std::format("{:.0f} days ago", how_long_ago / 86400.);
} }
void list_paired(bool show_keys) void list_paired(bool show_keys)
@@ -208,9 +252,16 @@ void list_paired(bool show_keys)
else else
{ {
if (show_keys) if (show_keys)
print_table({"", "Headset name", "Public key"}, std::views::zip(std::views::iota(1), values | std::views::elements<0>, values | std::views::elements<1>)); print_table({"", "Headset name", "Last connection", "Public key"},
std::views::zip(std::views::iota(1),
values | member(&headset::name),
values | std::views::transform([](const headset & h) { return relative_timestamp(h.last_connection); }),
values | member(&headset::public_key)));
else else
print_table({"", "Headset name"}, std::views::zip(std::views::iota(1), values | std::views::elements<0>)); print_table({"", "Headset name", "Last connection"},
std::views::zip(std::views::iota(1),
values | member(&headset::name),
values | std::views::transform([](const headset & h) { return relative_timestamp(h.last_connection); })));
} }
} }
@@ -222,7 +273,7 @@ void rename(size_t headset_id, const std::string & headset_name)
if (headset_id < 1 or headset_id > values.size()) if (headset_id < 1 or headset_id > values.size())
throw std::runtime_error(std::format("Invalid headset number: {}", headset_id)); throw std::runtime_error(std::format("Invalid headset number: {}", headset_id));
call_method(bus, "RenameKey", "ss", values.at(headset_id - 1).second.c_str(), headset_name.c_str()); call_method(bus, "RenameKey", "ss", values.at(headset_id - 1).public_key.c_str(), headset_name.c_str());
} }
void stop_server() void stop_server()