diff --git a/src/api/account.h b/src/api/account.h index 8a5e1ef17192e35be3e8be83bd0646e99ae8a164..0d11630a9068a1a917f7bb03fc102dd27bdfa2ac 100644 --- a/src/api/account.h +++ b/src/api/account.h @@ -18,16 +18,14 @@ ***************************************************************************/ #pragma once -// Std -#include <string> -#include <memory> - -// Data #include "profile.h" -// old LRC #include "typedefs.h" +#include <memory> + +#include <QString> + namespace lrc { @@ -64,7 +62,7 @@ enum class Status { }; static inline account::Status -to_status(const std::string& type) +to_status(const QString& type) { if (type == "INITIALIZING") return account::Status::INITIALIZING; @@ -95,40 +93,40 @@ enum class TlsMethod { }; struct ConfProperties_t { - std::string mailbox; - std::string dtmfType; + QString mailbox; + QString dtmfType; bool autoAnswer; int activeCallLimit; - std::string hostname; - std::string username; - std::string routeset; - std::string password; - std::string realm; - std::string localInterface; - std::string deviceId; - std::string deviceName; - std::string managerUri; - std::string managerUsername; + QString hostname; + QString username; + QString routeset; + QString password; + QString realm; + QString localInterface; + QString deviceId; + QString deviceName; + QString managerUri; + QString managerUsername; bool publishedSameAsLocal; int localPort; int publishedPort; - std::string publishedAddress; - std::string userAgent; + QString publishedAddress; + QString userAgent; bool upnpEnabled; bool hasCustomUserAgent; bool allowIncoming; - std::string archivePassword; + QString archivePassword; bool archiveHasPassword; - std::string archivePath; - std::string archivePin; + QString archivePath; + QString archivePin; bool proxyEnabled; - std::string proxyServer; - std::string proxyPushToken; + QString proxyServer; + QString proxyPushToken; bool peerDiscovery; bool accountDiscovery; bool accountPublish; int registrationExpire; - std::vector<std::map<std::string, std::string>> credentials; + VectorMapStringString credentials; struct Audio_t { int audioPortMax; int audioPortMin; @@ -139,15 +137,15 @@ struct ConfProperties_t { int videoPortMin; } Video; struct STUN_t { - std::string server; + QString server; bool enable; } STUN; struct TURN_t { - std::string server; + QString server; bool enable; - std::string username; - std::string password; - std::string realm; + QString username; + QString password; + QString realm; } TURN; struct Presence_t { bool presencePublishSupported; @@ -155,7 +153,7 @@ struct ConfProperties_t { bool presenceEnabled; } Presence; struct Ringtone_t { - std::string ringtonePath; + QString ringtonePath; bool ringtoneEnabled; } Ringtone; struct SRTP_t { @@ -167,13 +165,13 @@ struct ConfProperties_t { int listenerPort; bool enable; int port; - std::string certificateListFile; - std::string certificateFile; - std::string privateKeyFile; - std::string password; + QString certificateListFile; + QString certificateFile; + QString privateKeyFile; + QString password; TlsMethod method; - std::string ciphers; - std::string serverName; + QString ciphers; + QString serverName; bool verifyServer; bool verifyClient; bool requireClientCertificate; @@ -185,8 +183,8 @@ struct ConfProperties_t { bool AllowFromTrusted; } DHT; struct RingNS_t { - std::string uri; - std::string account; + QString uri; + QString account; } RingNS; struct Registration_t { int expire; @@ -224,7 +222,7 @@ struct Info { bool freeable = false; bool valid = true; - std::string registeredName; + QString registeredName; Status status = account::Status::INVALID; std::unique_ptr<lrc::api::ContactModel> contactModel; std::unique_ptr<lrc::api::ConversationModel> conversationModel; @@ -235,7 +233,7 @@ struct Info NewAccountModel* accountModel {nullptr}; // daemon config - std::string id; + QString id; profile::Info profileInfo; // contains: type, alias bool enabled; ConfProperties_t confProperties; diff --git a/src/api/avmodel.h b/src/api/avmodel.h index 92449e0d6a7d6c458eb4b03319b854c3a75c53a4..8bce2730741422bf8302baa5f9d0d2937ad01255 100644 --- a/src/api/avmodel.h +++ b/src/api/avmodel.h @@ -82,23 +82,23 @@ public: * Get video devices * @return list of devices */ - std::vector<std::string> getDevices() const; + VectorString getDevices() const; /** * Retrieve current default video device * @return current default video device id */ - std::string getDefaultDevice() const; + QString getDefaultDevice() const; /** * Set new default video device * @param id of the device */ - void setDefaultDevice(const std::string& deviceId); + void setDefaultDevice(const QString& deviceId); /** * Retrieve current framerate/resolution/etc of a device * @param id of the device * @return settings of the device */ - video::Settings getDeviceSettings(const std::string& deviceId) const; + video::Settings getDeviceSettings(const QString& deviceId) const; /** * Set device settings * @param video::Settings @@ -109,58 +109,58 @@ public: * @param id of the device * @return possibilities of the device */ - video::Capabilities getDeviceCapabilities(const std::string& deviceId) const; + video::Capabilities getDeviceCapabilities(const QString& deviceId) const; /** * Get the deviceId corresponding to a given device friendly name * @return deviceId */ - std::string getDeviceIdFromName(const std::string& deviceName) const; + QString getDeviceIdFromName(const QString& deviceName) const; /** * Get supported audio managers * @return supported audio managers */ - std::vector<std::string> getSupportedAudioManagers() const; + VectorString getSupportedAudioManagers() const; /** * Get current audio manager * @return current audio manager */ - std::string getAudioManager() const; + QString getAudioManager() const; /** * Get current audio outputs * @return audio outputs */ - std::vector<std::string> getAudioOutputDevices() const; + VectorString getAudioOutputDevices() const; /** * Get current audio inputs * @return audio inputs */ - std::vector<std::string> getAudioInputDevices() const; + VectorString getAudioInputDevices() const; /** * Get current ringtone device * @return current ringtone device */ - std::string getRingtoneDevice() const; + QString getRingtoneDevice() const; /** * Get current output device * @return current output device */ - std::string getOutputDevice() const; + QString getOutputDevice() const; /** * Get current input device * @return current input device */ - std::string getInputDevice() const; + QString getInputDevice() const; /** * Get current state of the audio meter * @return current state of the audio meter */ - bool isAudioMeterActive(const std::string& id="") const; + bool isAudioMeterActive(const QString& id="") const; /** * Turn on/off the audio metering feature * @param the new state of the meter */ - void setAudioMeterState(bool active, const std::string& id="") const; + void setAudioMeterState(bool active, const QString& id="") const; /** * Starts audio device. Should only be invoked when outside of a call. */ @@ -174,43 +174,43 @@ public: * @param name of the new audio manager * @return if the operation is successful */ - bool setAudioManager(const std::string& name); + bool setAudioManager(const QString& name); /** * Set current ringtone device * @param name of the new ringtone device */ - void setRingtoneDevice(const std::string& name); + void setRingtoneDevice(const QString& name); /** * Set current output device * @param name of the new output device */ - void setOutputDevice(const std::string& name); + void setOutputDevice(const QString& name); /** * Set current input device * @param name of the new input device */ - void setInputDevice(const std::string& name); + void setInputDevice(const QString& name); /** * Stop local record at given path * @param path */ - void stopLocalRecorder(const std::string& path) const; + void stopLocalRecorder(const QString& path) const; /** * Start a local recorder and return it path. * @param audioOnly */ - std::string startLocalRecorder(const bool& audioOnly) const; + QString startLocalRecorder(const bool& audioOnly) const; /** * Get the current recording path * @return recording path */ - std::string getRecordPath() const; + QString getRecordPath() const; /** * Sets the recording path * @param path recording path */ - void setRecordPath(const std::string& path) const; + void setRecordPath(const QString& path) const; /** * Whether or not to record every call * @return always recording @@ -256,7 +256,7 @@ public: * @return the linked renderer * @throw std::out_of_range if not found */ - const video::Renderer& getRenderer(const std::string& id) const; + const video::Renderer& getRenderer(const QString& id) const; /** * Render a file to the call id specified @@ -264,7 +264,7 @@ public: * @param callId * @note callId can be omitted to switch the input of the local recorder */ - void setInputFile(const std::string& uri, const std::string& callId = {}); + void setInputFile(const QString& uri, const QString& callId = {}); /** * Change the current device rendered for the call id specified * @param id of the camera @@ -272,7 +272,7 @@ public: * @note renders a black frame if device not found or empty * @note callId can be omitted to switch the input of the local recorder */ - void switchInputTo(const std::string& id, const std::string& callId = {}); + void switchInputTo(const QString& id, const QString& callId = {}); /** * Render the current display to the call id specified * @param idx of the display @@ -283,13 +283,13 @@ public: * @param callId * @note callId can be omitted to switch the input of the local recorder */ - void setDisplay(int idx, int x, int y, int w, int h, const std::string& callId = {}); + void setDisplay(int idx, int x, int y, int w, int h, const QString& callId = {}); /** * Get informations on the rendered device * @param call_id linked call to the renderer * @return the device rendered */ - video::RenderedDevice getCurrentRenderedDevice(const std::string& call_id) const; + video::RenderedDevice getCurrentRenderedDevice(const QString& call_id) const; /** * set to true to receive AVFrames from render @@ -300,13 +300,13 @@ public: * set current using device * @ param device name */ - void setCurrentVideoCaptureDevice(std::string ¤tVideoCaptureDevice); + void setCurrentVideoCaptureDevice(QString ¤tVideoCaptureDevice); /** * set current using device * @ return current using device name */ - std::string getCurrentVideoCaptureDevice() const; + QString getCurrentVideoCaptureDevice() const; /** * clear current using device @@ -318,17 +318,17 @@ Q_SIGNALS: * Emitted when a renderer is started * @param id of the renderer */ - void rendererStarted(const std::string& id); + void rendererStarted(const QString& id); /** * Emitted when a renderer is stopped * @param id of the renderer */ - void rendererStopped(const std::string& id); + void rendererStopped(const QString& id); /** * Emitted when a new frame is ready * @param id */ - void frameUpdated(const std::string& id); + void frameUpdated(const QString& id); /** * Emitted when a device is plugged or unplugged */ @@ -338,12 +338,12 @@ Q_SIGNALS: * @param id Ringbuffer id * @param level Volume in range [0, 1] */ - void audioMeter(const std::string& id, float level); + void audioMeter(const QString& id, float level); /** * local recorder stopped * @param filePath */ - void recordPlaybackStopped(const std::string& filePath); + void recordPlaybackStopped(const QString& filePath); private: std::unique_ptr<AVModelPimpl> pimpl_; diff --git a/src/api/behaviorcontroller.h b/src/api/behaviorcontroller.h index 2292e246a459543a1d50b4f97c1252ede5441eee..9b2195fa2b7b0f9677eea9e32e06854c95a6fa4d 100644 --- a/src/api/behaviorcontroller.h +++ b/src/api/behaviorcontroller.h @@ -18,14 +18,11 @@ ***************************************************************************/ #pragma once -// Std -#include <memory> +#include "typedefs.h" -// Qt -#include <qobject.h> +#include <QObject> -// Lrc -#include "typedefs.h" +#include <memory> namespace lrc { @@ -61,44 +58,44 @@ Q_SIGNALS: /** * Emitted when the client should open the chat view. */ - void showChatView(const std::string& accountId, const api::conversation::Info& conversationInfo) const; + void showChatView(const QString& accountId, const api::conversation::Info& conversationInfo) const; /** * Emitted when the client should ask the user whether it wants to leave a message after a failed call. */ - void showLeaveMessageView(const std::string& accountId, const api::conversation::Info& conversationInfo) const; + void showLeaveMessageView(const QString& accountId, const api::conversation::Info& conversationInfo) const; /** * Emitted when the client should open the call view. */ - void showCallView(const std::string& accountId, const api::conversation::Info& conversationInfo) const; + void showCallView(const QString& accountId, const api::conversation::Info& conversationInfo) const; /** * Emitted when the client should open the incoming call view. */ - void showIncomingCallView(const std::string& accountId, const api::conversation::Info& conversationInfo) const; + void showIncomingCallView(const QString& accountId, const api::conversation::Info& conversationInfo) const; /** * Emitted when the client receives a new trust request */ - void newTrustRequest(const std::string& accountId, const std::string& contactUri) const; + void newTrustRequest(const QString& accountId, const QString& contactUri) const; /** * Emitted when a trust request has been accepted, refused or blocked */ - void trustRequestTreated(const std::string& accountId, const std::string& contactUri) const; + void trustRequestTreated(const QString& accountId, const QString& contactUri) const; /** * Emitted when the client receives an unread message to display (text or file for now) */ - void newUnreadInteraction(const std::string& accountId, const std::string& conversation, + void newUnreadInteraction(const QString& accountId, const QString& conversation, uint64_t interactionId, const interaction::Info& interaction) const; /** * Emitted when the unread interaction is now read */ - void newReadInteraction(const std::string& accountId, const std::string& conversation, uint64_t interactionId) const; + void newReadInteraction(const QString& accountId, const QString& conversation, uint64_t interactionId) const; /** * Emitted debugMessageReceived */ - void debugMessageReceived(const std::string& message); + void debugMessageReceived(const QString& message); /** * Emitted audioMeter */ - void audioMeter(const std::string& id, float level); + void audioMeter(const QString& id, float level); }; diff --git a/src/api/call.h b/src/api/call.h index bf036765ffe9a28ae03c2ecff2dac65a1b66e513..bda2fb73e5f0257325f1c33e5c431d1f134c05f0 100644 --- a/src/api/call.h +++ b/src/api/call.h @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * + * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * * Author: Nicolas Jäger <nicolas.jager@savoirfairelinux.com> * * Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com> * * * @@ -18,14 +18,14 @@ ***************************************************************************/ #pragma once +// Qt +#include <QObject> + // std #include <string> #include <ctime> #include <chrono> -// Qt -#include <QObject> - namespace lrc { @@ -51,37 +51,37 @@ enum class Status { CONNECTED }; -static inline std::string +static inline QString to_string(const call::Status& status) { switch(status) { case call::Status::PAUSED: - return QObject::tr("Hold").toStdString(); + return QObject::tr("Hold"); case call::Status::IN_PROGRESS: - return QObject::tr("Talking").toStdString(); + return QObject::tr("Talking"); case call::Status::INVALID: - return QObject::tr("ERROR").toStdString(); + return QObject::tr("ERROR"); case call::Status::INCOMING_RINGING: - return QObject::tr("Incoming").toStdString(); + return QObject::tr("Incoming"); case call::Status::OUTGOING_RINGING: - return QObject::tr("Calling").toStdString(); + return QObject::tr("Calling"); case call::Status::CONNECTING: - return QObject::tr("Connecting").toStdString(); + return QObject::tr("Connecting"); case call::Status::SEARCHING: - return QObject::tr("Searching").toStdString(); + return QObject::tr("Searching"); case call::Status::INACTIVE: - return QObject::tr("Inactive").toStdString(); + return QObject::tr("Inactive"); case call::Status::ENDED: - return QObject::tr("Finished").toStdString(); + return QObject::tr("Finished"); case call::Status::TIMEOUT: - return QObject::tr("Timeout").toStdString(); + return QObject::tr("Timeout"); case call::Status::PEER_BUSY: - return QObject::tr("Peer busy").toStdString(); + return QObject::tr("Peer busy"); case call::Status::TERMINATING: - return QObject::tr("Finished").toStdString(); + return QObject::tr("Finished"); case call::Status::CONNECTED: - return QObject::tr("Communication established").toStdString(); + return QObject::tr("Communication established"); default: return ""; // to remove a build warning, should not happen } @@ -94,7 +94,7 @@ to_string(const call::Status& status) * @return */ static inline Status -to_status(const std::string& status) +to_status(const QString& status) { if (status == "INCOMING") return Status::INCOMING_RINGING; @@ -127,11 +127,11 @@ enum class Type { struct Info { - std::string id; + QString id; std::chrono::steady_clock::time_point startTime; Status status = Status::INVALID; Type type = Type::INVALID; - std::string peerUri; + QString peerUri; bool isOutgoing; bool audioMuted = false; bool videoMuted = false; diff --git a/src/api/contact.h b/src/api/contact.h index e2fe54d6f23349a0fdd8216a00ffaa8dd19a04ee..51c67eeae549c5aef2924b5fa2d4b19d19fa9afe 100644 --- a/src/api/contact.h +++ b/src/api/contact.h @@ -18,12 +18,10 @@ ***************************************************************************/ #pragma once -// Std -#include <string> - -// Data #include "profile.h" +#include <QString> + namespace lrc { @@ -43,7 +41,7 @@ namespace contact struct Info { profile::Info profileInfo; - std::string registeredName; + QString registeredName; bool isTrusted = false; bool isPresent = false; bool isBanned = false; diff --git a/src/api/contactmodel.h b/src/api/contactmodel.h index 878eea9a6536e3e56ec56a6f0528c2fd75a17929..ef0134fe82574513c6fde0b57a7ba2d20ec3c8c3 100644 --- a/src/api/contactmodel.h +++ b/src/api/contactmodel.h @@ -18,18 +18,13 @@ ***************************************************************************/ #pragma once -// Std -#include <string> -#include <memory> -#include <map> - -// Qt -#include <qobject.h> - -// LRC #include "typedefs.h" #include "api/behaviorcontroller.h" +#include <QObject> + +#include <memory> + namespace lrc { @@ -52,7 +47,7 @@ class ConversationModel; class LIB_EXPORT ContactModel : public QObject { Q_OBJECT public: - using ContactInfoMap = std::map<std::string, contact::Info>; + using ContactInfoMap = QMap<QString, contact::Info>; const account::Info& owner; @@ -72,19 +67,19 @@ public: * @param contactUri * @param banned */ - void removeContact(const std::string& contactUri, bool banned=false); + void removeContact(const QString& contactUri, bool banned=false); /** * get contact information. * @param contactUri * @return the contact::Info structure for a contact * @throws out_of_range exception if can't find the contact */ - const contact::Info getContact(const std::string& contactUri) const; + const contact::Info getContact(const QString& contactUri) const; /** * get list of banned contacts. * @return list of banned contacts uris as string */ - const std::list<std::string>& getBannedContacts() const; + const QList<QString>& getBannedContacts() const; /** * @return all contacts for this account. */ @@ -101,41 +96,41 @@ public: * Search a SIP or a Ring contact from a query. * @param query */ - void searchContact(const std::string& query); + void searchContact(const QString& query); /** * Send a text interaction to a contact over the Dht. * @param contactUri * @param body * @return id from daemon */ - uint64_t sendDhtMessage(const std::string& uri, const std::string& body) const; + uint64_t sendDhtMessage(const QString& uri, const QString& body) const; Q_SIGNALS: /** * Connect this signal to know when this model was updated. */ - void modelUpdated(const std::string& uri, bool needsSorted=true) const; + void modelUpdated(const QString& uri, bool needsSorted=true) const; /** * Connect this signal to know when a contact was added. * @param contactUri */ - void contactAdded(const std::string& contactUri) const; + void contactAdded(const QString& contactUri) const; /** * Connect this signal to know when a pending contact was accepted. * @param contactUri */ - void pendingContactAccepted(const std::string& contactUri) const; + void pendingContactAccepted(const QString& contactUri) const; /** * Connect this signal to know when an account was removed. * @param contactUri */ - void contactRemoved(const std::string& contactUri) const; + void contactRemoved(const QString& contactUri) const; /** * Connect this signal to know when an incoming call comes from a pending contact. * @param fromId peer profile uri * @param callId incoming call id */ - void incomingCallFromPending(const std::string& from, const std::string& callId) const; + void incomingCallFromPending(const QString& from, const QString& callId) const; /** * Connect this signal to know when a text message arrives for this account * @param accountId @@ -143,10 +138,10 @@ Q_SIGNALS: * @param from peer uri * @param payloads content of the message */ - void newAccountMessage(std::string& accountId, - std::string& msgId, - std::string& from, - std::map<std::string,std::string> payloads) const; + void newAccountMessage(const QString& accountId, + const QString& msgId, + const QString& from, + const MapStringString& payloads) const; /** * Connect this signal to know when a file transfer interaction is incoming * @param dringId Daemon's ID for incoming transfer @@ -158,7 +153,7 @@ Q_SIGNALS: * @param contactUri * @param banned whether contact was banned or unbanned */ - void bannedStatusChanged(const std::string& contactUri, bool banned) const; + void bannedStatusChanged(const QString& contactUri, bool banned) const; private: std::unique_ptr<ContactModelPimpl> pimpl_; diff --git a/src/api/conversation.h b/src/api/conversation.h index c166ecad9f82b70b5506d8dae56dc9538d321986..d44d7bfdb7cbeace50af9f5420796de28efbab46 100644 --- a/src/api/conversation.h +++ b/src/api/conversation.h @@ -18,13 +18,12 @@ ***************************************************************************/ #pragma once -// Std +#include "interaction.h" +#include "typedefs.h" + #include <vector> #include <map> -// Data -#include "interaction.h" - namespace lrc { @@ -36,11 +35,11 @@ namespace conversation struct Info { - std::string uid = ""; - std::string accountId; - std::vector<std::string> participants; - std::string callId; - std::string confId; + QString uid = ""; + QString accountId; + VectorString participants; + QString callId; + QString confId; std::map<uint64_t, interaction::Info> interactions; uint64_t lastMessageUid = 0; unsigned int unreadMessages = 0; diff --git a/src/api/conversationmodel.h b/src/api/conversationmodel.h index 6de4a0e98ea18e842dacda07661d39e06ee6ae15..410e37484c83c4eee2e5007b20af943821e005fd 100644 --- a/src/api/conversationmodel.h +++ b/src/api/conversationmodel.h @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * + * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * * Author: Nicolas Jäger <nicolas.jager@savoirfairelinux.com> * * Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com> * * * @@ -18,23 +18,19 @@ ***************************************************************************/ #pragma once -// Std -#include <memory> -#include <map> -#include <string> -#include <deque> - -// Qt -#include <qobject.h> - -// Lrc #include "typedefs.h" -// Data #include "api/conversation.h" #include "api/profile.h" #include "api/datatransfer.h" +#include <QObject> +#include <QVector> +#include <QMap> + +#include <memory> +#include <deque> + namespace lrc { @@ -59,8 +55,8 @@ enum class ConferenceableItem { struct AccountConversation { - std::string convId; - std::string accountId; + QString convId; + QString accountId; }; /* @@ -69,7 +65,7 @@ struct AccountConversation * for conferences contains multiple entries */ -typedef std::vector<std::vector<AccountConversation>> ConferenceableValue; +typedef QVector<QVector<AccountConversation>> ConferenceableValue; /** * @brief Class that manages conversation informations. @@ -99,7 +95,7 @@ public: * @param conversation id * @return conversations with given id */ - conversation::Info getConversationForUID(const std::string& uid) const; + conversation::Info getConversationForUID(const QString& uid) const; /** * Get conversations that could be added to conference @@ -107,7 +103,7 @@ public: * @param search name filter * @return filtered conversations */ - std::map<ConferenceableItem, ConferenceableValue> getConferenceableConversations(const std::string& convId, const std::string& filter = {}) const; + QMap<ConferenceableItem, ConferenceableValue> getConferenceableConversations(const QString& convId, const QString& filter = {}) const; /** * Get a custom filtered set of conversations * @return conversations filtered @@ -130,39 +126,39 @@ public: * @param uid of the conversation to change. * @exception std::out_of_range if uid doesn't correspond to an existing conversation */ - void makePermanent(const std::string& uid); + void makePermanent(const QString& uid); /** * Remove a conversation and the contact if it's a dialog * @param uid of the conversation * @param banned if we want to ban the contact. */ - void removeConversation(const std::string& uid, bool banned=false); + void removeConversation(const QString& uid, bool banned=false); /** * Get the action wanted by the user when they click on the conversation * @param uid of the conversation */ - void selectConversation(const std::string& uid) const; + void selectConversation(const QString& uid) const; /** * Call contacts linked to this conversation * @param uid of the conversation */ - void placeCall(const std::string& uid); + void placeCall(const QString& uid); /** * Perform an audio call with contacts linked to this conversation * @param uid of the conversation */ - void placeAudioOnlyCall(const std::string& uid); + void placeAudioOnlyCall(const QString& uid); /** * Send a message to the conversation * @param uid of the conversation * @param body of the message */ - void sendMessage(const std::string& uid, const std::string& body); + void sendMessage(const QString& uid, const QString& body); /** * Modify the current filter (will change the result of getFilteredConversations) * @param filter the new filter */ - void setFilter(const std::string& filter); + void setFilter(const QString& filter); /** * Modify the current filter (will change the result of getFilteredConversations) * @param filter the new filter (example: PENDING, RING) @@ -174,23 +170,23 @@ public: * @param uidA uid of the conversation A * @param uidB uid of the conversation B */ - void joinConversations(const std::string& uidA, const std::string& uidB); + void joinConversations(const QString& uidA, const QString& uidB); /** * Clear the history of a conversation * @param uid of the conversation */ - void clearHistory(const std::string& uid); + void clearHistory(const QString& uid); /** * change the status of the interaction from UNREAD to READ * @param convId, id of the conversation * @param msgId, id of the interaction */ - void setInteractionRead(const std::string& convId, const uint64_t& msgId); + void setInteractionRead(const QString& convId, const uint64_t& msgId); /** * Clears the unread text messages of a conversation * @param convId, uid of the conversation */ - void clearUnreadInteractions(const std::string& convId); + void clearUnreadInteractions(const QString& convId); /** * clear all history */ @@ -200,31 +196,31 @@ public: * @param convId * @param interactionId */ - void clearInteractionFromConversation(const std::string& convId, const uint64_t& interactionId); + void clearInteractionFromConversation(const QString& convId, const uint64_t& interactionId); /** * Retry to send a message. In fact, will delete the previous interaction and resend a new one. * @param convId * @param interactionId */ - void retryInteraction(const std::string& convId, const uint64_t& interactionId); + void retryInteraction(const QString& convId, const uint64_t& interactionId); /** * delete obsolete history from the database * @param days, number of days from today. Below this date, interactions will be deleted */ void deleteObsoleteHistory(int date); - void sendFile(const std::string& convUid, const std::string& path, const std::string& filename); + void sendFile(const QString& convUid, const QString& path, const QString& filename); - void acceptTransfer(const std::string& convUid, uint64_t interactionId, const std::string& path); + void acceptTransfer(const QString& convUid, uint64_t interactionId, const QString& path); - void cancelTransfer(const std::string& convUid, uint64_t interactionId); + void cancelTransfer(const QString& convUid, uint64_t interactionId); void getTransferInfo(uint64_t interactionId, api::datatransfer::Info& info); /** * @param convUid, uid of the conversation * @return the number of unread messages for the conversation */ - int getNumberOfUnreadMessagesFor(const std::string& convUid); + int getNumberOfUnreadMessagesFor(const QString& convUid); Q_SIGNALS: /** @@ -233,14 +229,14 @@ Q_SIGNALS: * @param interactionId * @param interactionInfo */ - void newInteraction(const std::string& uid, uint64_t interactionId, const interaction::Info& interactionInfo) const; + void newInteraction(const QString& uid, uint64_t interactionId, const interaction::Info& interactionInfo) const; /** * Emitted when an interaction got a new status * @param convUid conversation which owns the interaction * @param interactionId * @param msg */ - void interactionStatusUpdated(const std::string& convUid, + void interactionStatusUpdated(const QString& convUid, uint64_t interactionId, const api::interaction::Info& msg) const; /** @@ -248,18 +244,18 @@ Q_SIGNALS: * @param convUid conversation which owns the interaction * @param interactionId */ - void interactionRemoved(const std::string& convUid, + void interactionRemoved(const QString& convUid, uint64_t interactionId) const; /** * Emitted when user clear the history of a conversation * @param uid */ - void conversationCleared(const std::string& uid) const; + void conversationCleared(const QString& uid) const; /** * Emitted when conversation's participant has been updated * @param uid */ - void conversationUpdated(const std::string& uid) const; + void conversationUpdated(const QString& uid) const; /** * Emitted when conversations are sorted by last interaction */ @@ -272,12 +268,12 @@ Q_SIGNALS: * Emitted when a conversation has been added * @param uid */ - void newConversation(const std::string& uid) const; + void newConversation(const QString& uid) const; /** * Emitted when a conversation has been removed * @param uid */ - void conversationRemoved(const std::string& uid) const; + void conversationRemoved(const QString& uid) const; /** * Emitted after all history were cleared * @note the client must connect this signal to know when update the view of the list @@ -288,7 +284,7 @@ Q_SIGNALS: * be modified * @param uid */ - void conversationReady(std::string uid) const; + void conversationReady(QString uid) const; private: std::unique_ptr<ConversationModelPimpl> pimpl_; diff --git a/src/api/datatransfer.h b/src/api/datatransfer.h index 4522e4f2e651af8f5888f3da7cf8d2c90c16ae81..5d0dcf8afca081fa1a3701106d543e08527a86eb 100644 --- a/src/api/datatransfer.h +++ b/src/api/datatransfer.h @@ -17,11 +17,13 @@ ***************************************************************************/ #pragma once +// LRC +#include "typedefs.h" + // std #include <ctime> -// LRC -#include "typedefs.h" +#include <QString> namespace lrc { namespace api { @@ -40,7 +42,7 @@ enum class Status { INVALID }; -static inline const std::string +static inline const QString to_string(const Status& status) { switch(status) { @@ -69,7 +71,7 @@ to_string(const Status& status) } static inline Status -to_status(const std::string& status) +to_status(const QString& status) { if (status == "on_connection") return datatransfer::Status::on_connection; @@ -96,15 +98,15 @@ to_status(const std::string& status) struct Info { - std::string uid; ///< long-term and unique identifier (used for historic) + QString uid; ///< long-term and unique identifier (used for historic) Status status; bool isOutgoing; std::size_t totalSize; std::size_t progress; ///< if status >= on_progress, gives number of bytes tx/rx until now - std::string path; - std::string displayName; - std::string accountId; - std::string peerUri; + QString path; + QString displayName; + QString accountId; + QString peerUri; std::time_t timestamp = 0; }; diff --git a/src/api/datatransfermodel.h b/src/api/datatransfermodel.h index a61d214cb9f5e8c6b813408289753658e0bbfc77..2d36c2ebc99cb80a6eb0cbecb6123028da84f992 100644 --- a/src/api/datatransfermodel.h +++ b/src/api/datatransfermodel.h @@ -17,21 +17,17 @@ ***************************************************************************/ #pragma once -// Std -#include <string> -#include <memory> -#include <ios> - -// Qt -#include <qobject.h> - -// Data #include "api/datatransfer.h" #include "api/account.h" -// LRC #include "typedefs.h" +#include <QObject> + +#include <string> +#include <memory> +#include <ios> + namespace lrc { class CallbacksHandler; @@ -55,14 +51,14 @@ public: DataTransferModel(); ~DataTransferModel(); - void sendFile(const std::string& account_id, const std::string& peer_uri, - const std::string& file_path, const std::string& display_name); + void sendFile(const QString& account_id, const QString& peer_uri, + const QString& file_path, const QString& display_name); void transferInfo(long long ringId, datatransfer::Info& lrc_info); void bytesProgress(int interactionId, int64_t& total, int64_t& progress); - void accept(int interactionId, const std::string& file_path, std::size_t offset); + void accept(int interactionId, const QString& file_path, std::size_t offset); void cancel(int interactionId); @@ -76,7 +72,7 @@ public: * Used when images < 20 Mb are automatically accepted and downloaded * Should contains the full directory with the end marker (/ on linux for example) */ - std::string downloadDirectory; + QString downloadDirectory; Q_SIGNALS: /** @@ -89,7 +85,7 @@ Q_SIGNALS: * @param transfer_id unique identification of incoming data transfer. * @param status reported status. */ - void transferStatusChanged(const std::string& uid, datatransfer::Status status); + void transferStatusChanged(const QString& uid, datatransfer::Status status); private: class Impl; diff --git a/src/api/interaction.h b/src/api/interaction.h index fc690ff11bbec412251ba699901c17b24f4ea2db..ebfb9a8cb5ea254f924f31d487a3cc68b6ea4dbf 100644 --- a/src/api/interaction.h +++ b/src/api/interaction.h @@ -18,9 +18,9 @@ ***************************************************************************/ #pragma once -// Std +#include <QString> + #include <ctime> -#include <string> namespace lrc { @@ -40,7 +40,7 @@ enum class Type { COUNT__ }; -static inline const std::string +static inline const QString to_string(const Type& type) { switch(type) { @@ -60,7 +60,7 @@ to_string(const Type& type) } static inline Type -to_type(const std::string& type) +to_type(const QString& type) { if (type == "TEXT") return interaction::Type::TEXT; @@ -93,7 +93,7 @@ enum class Status { COUNT__ }; -static inline const std::string +static inline const QString to_string(const Status& status) { switch(status) { @@ -133,7 +133,7 @@ to_string(const Status& status) } static inline Status -to_status(const std::string& status) +to_status(const QString& status) { if (status == "UNKNOWN") return Status::UNKNOWN; @@ -179,8 +179,8 @@ to_status(const std::string& status) */ struct Info { - std::string authorUri; - std::string body; + QString authorUri; + QString body; std::time_t timestamp = 0; std::time_t duration = 0; Type type = Type::INVALID; @@ -189,7 +189,7 @@ struct Info }; static inline bool isOutgoing(const Info& interaction) { - return interaction.authorUri.empty(); + return interaction.authorUri.isEmpty(); } } // namespace interaction diff --git a/src/api/lrc.h b/src/api/lrc.h index 3f90b3e6bae8d10648457ab2094a2e5030356a8f..58c32de7c270531af5ff7eba1d515413e43c7eda 100644 --- a/src/api/lrc.h +++ b/src/api/lrc.h @@ -18,15 +18,12 @@ ***************************************************************************/ #pragma once -// Std +#include "typedefs.h" + #include <memory> #include <vector> -#include <string> #include <atomic> -// Lrc -#include "typedefs.h" - namespace lrc { @@ -94,22 +91,22 @@ public: /** * Helper: get active call list from daemon */ - static std::vector<std::string> activeCalls(); + static VectorString activeCalls(); /** * Helper: get call list from daemon */ - static std::vector<std::string> getCalls(); + static VectorString getCalls(); /** * Helper: get conference list from daemon */ - static std::vector<std::string> getConferences(); + static VectorString getConferences(); /** * Helper: get subcalls list for a conference from daemon */ - static std::vector<std::string> getConferenceSubcalls(const std::string& id); + static VectorString getConferenceSubcalls(const QString& cid); /** * Preference diff --git a/src/api/newaccountmodel.h b/src/api/newaccountmodel.h index 8b24fc6f847407c3f0f94f0bd3822d035db7be94..133dd016961c08de14361957de1bb9c93d0ddc31 100644 --- a/src/api/newaccountmodel.h +++ b/src/api/newaccountmodel.h @@ -19,7 +19,11 @@ ***************************************************************************/ #pragma once -// std +#include "typedefs.h" +#include "api/account.h" + +#include <QObject> + #include <vector> #include <map> #include <memory> @@ -27,13 +31,6 @@ #include <mutex> #include <condition_variable> -// Qt -#include <qobject.h> - -// Lrc -#include "typedefs.h" -#include "api/account.h" - namespace lrc { @@ -61,43 +58,42 @@ public: ~NewAccountModel(); /** - * get a list of all acountId. - * @return a std::vector<std::string>. + * @return a list of all acountId. */ - std::vector<std::string> getAccountList() const; + QStringList getAccountList() const; /** * get account informations associated to an accountId. * @param accountId. * @return a const account::Info& structure. */ - const account::Info& getAccountInfo(const std::string& accountId) const; + const account::Info& getAccountInfo(const QString& accountId) const; /** * flag account corresponding to passed id as freeable. */ - void flagFreeable(const std::string& accountId) const; + void flagFreeable(const QString& accountId) const; /** * set account enable/disable, save config and do unregister for account * @param accountId. * @param enabled. */ - void setAccountEnabled(const std::string& accountID, bool enabled) const; + void setAccountEnabled(const QString& accountID, bool enabled) const; /** * saves account config to .yml * @param accountId. * @param reference to the confProperties */ - void setAccountConfig(const std::string& accountID, + void setAccountConfig(const QString& accountID, const account::ConfProperties_t& confProperties) const; /** * gets a copy of the accounts config * @param accountId. * @return an account::Info::ConfProperties_t structure. */ - account::ConfProperties_t getAccountConfig(const std::string& accountId) const; + account::ConfProperties_t getAccountConfig(const QString& accountId) const; /** * Call exportToFile from the daemon * @param accountId @@ -105,20 +101,20 @@ public: * @param password * @return if the file is exported with success */ - bool exportToFile(const std::string& accountId, const std::string& path, const std::string& password = {}) const; + bool exportToFile(const QString& accountId, const QString& path, const QString& password = {}) const; /** * Call exportOnRing from the daemon * @param accountId * @param password * @return if the export is initialized */ - bool exportOnRing(const std::string& accountId, const std::string& password) const; + bool exportOnRing(const QString& accountId, const QString& password) const; /** * Call removeAccount from the daemon * @param accountId to remove * @note will emit accountRemoved */ - void removeAccount(const std::string& accountId) const; + void removeAccount(const QString& accountId) const; /** * Call changeAccountPassword from the daemon * @param accountId @@ -126,23 +122,23 @@ public: * @param newPassword * @return if the password has been changed */ - bool changeAccountPassword(const std::string& accountId, - const std::string& currentPassword, - const std::string& newPassword) const; + bool changeAccountPassword(const QString& accountId, + const QString& currentPassword, + const QString& newPassword) const; /** * Change the avatar of an account * @param accountId * @param avatar * @throws out_of_range exception if account is not found */ - void setAvatar(const std::string& accountId, const std::string& avatar); + void setAvatar(const QString& accountId, const QString& avatar); /** * Change the alias of an account * @param accountId * @param alias * @throws out_of_range exception if account is not found */ - void setAlias(const std::string& accountId, const std::string& alias); + void setAlias(const QString& accountId, const QString& alias); /** * Try to register a name * @param accountId @@ -150,7 +146,7 @@ public: * @param username * @return if operation started */ - bool registerName(const std::string& accountId, const std::string& password, const std::string& username); + bool registerName(const QString& accountId, const QString& password, const QString& username); /** * Connect to JAMS to retrieve the account @@ -159,9 +155,9 @@ public: * @param serverUri * @return the account id */ - static std::string connectToAccountManager(const std::string& username, - const std::string& password, - const std::string& serverUri); + static QString connectToAccountManager(const QString& username, + const QString& password, + const QString& serverUri); /** * Create a new Ring or SIP account @@ -174,51 +170,51 @@ public: * @param uri of the account (for SIP) * @return the created account */ - static std::string createNewAccount(profile::Type type, - const std::string& displayName = "", - const std::string& archivePath = "", - const std::string& password = "", - const std::string& pin = "", - const std::string& uri = ""); + static QString createNewAccount(profile::Type type, + const QString& displayName = "", + const QString& archivePath = "", + const QString& password = "", + const QString& pin = "", + const QString& uri = ""); /** * Set an account to the first position */ - void setTopAccount(const std::string& accountId); + void setTopAccount(const QString& accountId); /** * Get the vCard for an account * @param id * @return vcard of the account */ - std::string accountVCard(const std::string& accountId, bool compressImage = true) const; + QString accountVCard(const QString& accountId, bool compressImage = true) const; Q_SIGNALS: /** * Connect this signal to know when an invalid account is here * @param accountID */ - void invalidAccountDetected(const std::string& accountID); + void invalidAccountDetected(const QString& accountID); /** * Connect this signal to know when the status of an account has changed. * @param accountID */ - void accountStatusChanged(const std::string& accountID); + void accountStatusChanged(const QString& accountID); /** * Connect this signal to know when an account was added. * @param accountID */ - void accountAdded(const std::string& accountID); + void accountAdded(const QString& accountID); /** * Connect this signal to know when an account was removed. * @param accountID */ - void accountRemoved(const std::string& accountID); + void accountRemoved(const QString& accountID); /** * Connect this signal to know when an account was updated. * @param accountID */ - void profileUpdated(const std::string& accountID); + void profileUpdated(const QString& accountID); /** * Connect this signal to know when an account is exported on the DHT @@ -226,7 +222,7 @@ Q_SIGNALS: * @param status * @param pin */ - void exportOnRingEnded(const std::string& accountID, account::ExportOnRingStatus status, const std::string& pin); + void exportOnRingEnded(const QString& accountID, account::ExportOnRingStatus status, const QString& pin); /** * Name registration has ended @@ -234,7 +230,7 @@ Q_SIGNALS: * @param status * @param name */ - void nameRegistrationEnded(const std::string& accountId, account::RegisterNameStatus status, const std::string& name); + void nameRegistrationEnded(const QString& accountId, account::RegisterNameStatus status, const QString& name); /** * Name registration has been found @@ -242,14 +238,14 @@ Q_SIGNALS: * @param status * @param name */ - void registeredNameFound(const std::string& accountId, account::LookupStatus status, const std::string& address, const std::string& name); + void registeredNameFound(const QString& accountId, account::LookupStatus status, const QString& address, const QString& name); /** * Migration has finished * @param accountId * @param ok */ - void migrationEnded(const std::string& accountId, bool ok); + void migrationEnded(const QString& accountId, bool ok); private: std::unique_ptr<NewAccountModelPimpl> pimpl_; diff --git a/src/api/newcallmodel.h b/src/api/newcallmodel.h index 3472dfc82d7ef25df0de74c8a7d214bcca209340..7a9de15450b246d9b0bbe3806fa01ab4710c942a 100644 --- a/src/api/newcallmodel.h +++ b/src/api/newcallmodel.h @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * + * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * * Author: Nicolas Jäger <nicolas.jager@savoirfairelinux.com> * * Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com> * * * @@ -18,21 +18,15 @@ ***************************************************************************/ #pragma once -// Std -#include <memory> -#include <string> -#include <map> - -// Qt -#include <qobject.h> - -// Data #include "api/call.h" #include "api/account.h" - -// LRC #include "typedefs.h" +#include <QObject> + +#include <memory> +#include <map> + namespace Video { class Renderer; } @@ -57,7 +51,7 @@ class LIB_EXPORT NewCallModel : public QObject { Q_OBJECT public: - using CallInfoMap = std::map<std::string, std::shared_ptr<call::Info>>; + using CallInfoMap = std::map<QString, std::shared_ptr<call::Info>>; const account::Info& owner; @@ -76,7 +70,7 @@ public: * @param isAudioOnly, set to false by default * @return the call uid created. Empty string is returned if call couldn't be created. */ - std::string createCall(const std::string& uri, bool isAudioOnly = false); + QString createCall(const QString& uri, bool isAudioOnly = false); /** * Get the call from its call id @@ -84,7 +78,7 @@ public: * @return the callInfo * @throw out_of_range exception if not found */ - const call::Info& getCall(const std::string& uid) const; + const call::Info& getCall(const QString& uid) const; /** * Get the call from the peer uri @@ -93,7 +87,7 @@ public: * @return the callInfo * @throw out_of_range exception if not found */ - const call::Info& getCallFromURI(const std::string& uri, bool notOver = false) const; + const call::Info& getCallFromURI(const QString& uri, bool notOver = false) const; /** * Get conference from a peer uri @@ -101,91 +95,91 @@ public: * @return the callInfo * @throw out_of_range exception if not found */ - const call::Info& getConferenceFromURI(const std::string& uri) const; + const call::Info& getConferenceFromURI(const QString& uri) const; /** * @param callId to test * @return true if callId is presend else false. */ - bool hasCall(const std::string& callId) const; + bool hasCall(const QString& callId) const; /** * Send a text message to a SIP call * @param callId * @param body of the message */ - void sendSipMessage(const std::string& callId, const std::string& body) const; + void sendSipMessage(const QString& callId, const QString& body) const; /** * Accept a call * @param callId */ - void accept(const std::string& callId) const; + void accept(const QString& callId) const; /** * Hang up a call * @param callId */ - void hangUp(const std::string& callId) const; + void hangUp(const QString& callId) const; /** * Refuse a call * @param callId */ - void refuse(const std::string& callId) const; + void refuse(const QString& callId) const; /** * Toggle audio record on a call * @param callId */ - void toggleAudioRecord(const std::string& callId) const; + void toggleAudioRecord(const QString& callId) const; /** * Play DTMF in a call * @param callId * @param value to play */ - void playDTMF(const std::string& callId, const std::string& value) const; + void playDTMF(const QString& callId, const QString& value) const; /** * Toggle pause on a call. * @warn only use this function for SIP calls * @param callId */ - void togglePause(const std::string& callId) const; + void togglePause(const QString& callId) const; /** * Toggle a media on a call * @param callId * @param media {AUDIO, VIDEO} */ - void toggleMedia(const std::string& callId, const NewCallModel::Media media) const; + void toggleMedia(const QString& callId, const NewCallModel::Media media) const; /** * Not implemented yet */ - void setQuality(const std::string& callId, const double quality) const; + void setQuality(const QString& callId, const double quality) const; /** * Blind transfer. Directly transfer a call to a sip number * @param callId: the call to transfer * @param to: the sip number (for example: "sip:1412") */ - void transfer(const std::string& callId, const std::string& to) const; + void transfer(const QString& callId, const QString& to) const; /** * Perform an attended. Transfer a call to another call * @param callIdSrc: the call to transfer * @param callIdDest: the destination's call */ - void transferToCall(const std::string& callIdSrc, const std::string& callIdDest) const; + void transferToCall(const QString& callIdSrc, const QString& callIdDest) const; /** * Create a conference from 2 calls. * @param callIdA uid of the call A * @param callIdB uid of the call B */ - void joinCalls(const std::string& callIdA, const std::string& callIdB) const; + void joinCalls(const QString& callIdA, const QString& callIdB) const; /** * Call a participant and add it to a call @@ -194,25 +188,25 @@ public: * @param audioOnly If the call is audio only * @return id for a new call */ - std::string callAndAddParticipant(const std::string uri, const std::string& callId, bool audioOnly); + QString callAndAddParticipant(const QString uri, const QString& callId, bool audioOnly); /** * Not implemented yet */ - void removeParticipant(const std::string& callId, const std::string& participant) const; + void removeParticipant(const QString& callId, const QString& participant) const; /** * @param callId * @return a human readable call duration (M:ss) */ - std::string getFormattedCallDuration(const std::string& callId) const; + QString getFormattedCallDuration(const QString& callId) const; /** * Get if a call is recording * @param callId * @return true if the call is recording else false */ - bool isRecording(const std::string& callId) const; + bool isRecording(const QString& callId) const; /** * Close all active calls and conferences @@ -224,42 +218,42 @@ public: * @param statusCode * @return status message */ - static std::string getSIPCallStatusString(const short& statusCode); + static QString getSIPCallStatusString(const short& statusCode); /** * Set a call as the current call (hold other calls) */ - void setCurrentCall(const std::string& callId) const; + void setCurrentCall(const QString& callId) const; Q_SIGNALS: /** * Emitted when a call state changes * @param callId */ - void callStatusChanged(const std::string& callId, int code) const; + void callStatusChanged(const QString& callId, int code) const; /** * Emitted when a call starts * @param callId */ - void callStarted(const std::string& callId) const; + void callStarted(const QString& callId) const; /** * Emitted when a call is over * @param callId */ - void callEnded(const std::string& callId) const; + void callEnded(const QString& callId) const; /** * Emitted when a call is incoming * @param callId * @param fromId the peer uri * @param displayname */ - void newIncomingCall(const std::string& fromId, const std::string& callId, const std::string& displayname) const; + void newIncomingCall(const QString& fromId, const QString& callId, const QString& displayname) const; /** * Emitted when a call is added to a conference * @param callId * @param confId */ - void callAddedToConference(const std::string& callId, const std::string& confId) const; + void callAddedToConference(const QString& callId, const QString& confId) const; /** * Emitted when a voice mail notice arrives @@ -268,7 +262,7 @@ Q_SIGNALS: * @param oldCount * @param urgentCount */ - void voiceMailNotify(const std::string& accountId, int newCount, int oldCount, int urgentCount) const; + void voiceMailNotify(const QString& accountId, int newCount, int oldCount, int urgentCount) const; private: std::unique_ptr<NewCallModelPimpl> pimpl_; diff --git a/src/api/newcodecmodel.h b/src/api/newcodecmodel.h index e7c82d93fc0dc7b414294ddbb7ea5b37d72d11a5..02d325a8de1b0114dd978c40745c0948a4955474 100644 --- a/src/api/newcodecmodel.h +++ b/src/api/newcodecmodel.h @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright (C) 2018-2020 Savoir-faire Linux Inc. * + * Copyright (C) 2018-2020 Savoir-faire Linux Inc. * * Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com> * * * * This library is free software; you can redistribute it and/or * @@ -17,18 +17,13 @@ ***************************************************************************/ #pragma once -// Std -#include <memory> -#include <string> -#include <list> +#include "api/account.h" +#include "typedefs.h" -// Qt -#include <qobject.h> #include <QObject> +#include <QList> -// Lrc -#include "api/account.h" -#include "typedefs.h" +#include <memory> namespace lrc { @@ -45,15 +40,15 @@ struct Codec { unsigned int id; bool enabled; - std::string name; - std::string samplerate; - std::string bitrate; - std::string min_bitrate; - std::string max_bitrate; - std::string type; - std::string quality; - std::string min_quality; - std::string max_quality; + QString name; + QString samplerate; + QString bitrate; + QString min_bitrate; + QString max_bitrate; + QString type; + QString quality; + QString min_quality; + QString max_quality; bool auto_quality_enabled; }; @@ -72,11 +67,11 @@ public: /** * @return audio codecs for the account */ - std::list<Codec> getAudioCodecs() const; + QList<Codec> getAudioCodecs() const; /** * @return video codecs for the account */ - std::list<Codec> getVideoCodecs() const; + QList<Codec> getVideoCodecs() const; /** * Set a higher priority to a codec * @param codecId diff --git a/src/api/newdevicemodel.h b/src/api/newdevicemodel.h index e4c6da77b34258a87024d500d3d245a8dee26ac8..feb05232214515a7ba62177297d7af87d1bcf1b5 100644 --- a/src/api/newdevicemodel.h +++ b/src/api/newdevicemodel.h @@ -17,18 +17,14 @@ ***************************************************************************/ #pragma once -// Std -#include <memory> -#include <string> -#include <list> +#include "api/account.h" +#include "typedefs.h" -// Qt -#include <qobject.h> #include <QObject> -// Lrc -#include "api/account.h" -#include "typedefs.h" +#include <memory> +#include <string> +#include <list> namespace lrc { @@ -43,8 +39,8 @@ namespace account { struct Info; } struct Device { - std::string id = ""; - std::string name = ""; + QString id = ""; + QString name = ""; bool isCurrent = false; }; @@ -72,14 +68,14 @@ public: * Get ring devices of an account * @return a copy of current devices */ - std::list<Device> getAllDevices() const; + QList<Device> getAllDevices() const; /** * Retrieve a device by its id * @param id of the device * @return the device if found else a device with a null id */ - Device getDevice(const std::string& id) const; + Device getDevice(const QString& id) const; /** * Revoke a ring device @@ -87,7 +83,7 @@ public: * @param password of the account's archive * @note will emit deviceRevoked when finished */ - void revokeDevice(const std::string& id, const std::string& password); + void revokeDevice(const QString& id, const QString& password); /** * Change the name of the current device @@ -95,25 +91,25 @@ public: * @note will emit deviceUpdated when finished * @note ring can't change the name of another device */ - void setCurrentDeviceName(const std::string& newName); + void setCurrentDeviceName(const QString& newName); Q_SIGNALS: /** * Link to this signal to know when a new device is added * @param id added device */ - void deviceAdded(const std::string& id) const; + void deviceAdded(const QString& id) const; /** * Link to this signal to know when a device is removed * @param id removed device * @param Status (SUCCESS, WRONG_PASSWORD, UNKNOWN_DEVICE) */ - void deviceRevoked(const std::string& id, const Status status) const; + void deviceRevoked(const QString& id, const Status status) const; /** * Link to this signal when a device get a new name * @param id */ - void deviceUpdated(const std::string& id) const; + void deviceUpdated(const QString& id) const; private: std::unique_ptr<NewDeviceModelPimpl> pimpl_; diff --git a/src/api/newvideo.h b/src/api/newvideo.h index 322aa8b1aea28cfde98d6e302fac72dd7003e1f5..2c8b4259d926c47c5fcfea7de43ad79f301d215f 100644 --- a/src/api/newvideo.h +++ b/src/api/newvideo.h @@ -48,12 +48,12 @@ namespace video constexpr static const char PREVIEW_RENDERER_ID[] = "local"; -using Channel = std::string; -using Resolution = std::string; +using Channel = QString; +using Resolution = QString; using Framerate = float; -using FrameratesList = std::vector<Framerate>; -using ResRateList = std::vector<std::pair<Resolution, FrameratesList>>; -using Capabilities = std::map<Channel, ResRateList>; +using FrameratesList = QVector<Framerate>; +using ResRateList = QVector<QPair<Resolution, FrameratesList>>; +using Capabilities = QMap<Channel, ResRateList>; /** * This class is used by Renderer class to expose video data frame @@ -84,7 +84,7 @@ enum DeviceType */ struct RenderedDevice { - std::string name; + QString name; DeviceType type = INVALID; }; @@ -94,8 +94,8 @@ struct RenderedDevice struct Settings { Channel channel = ""; - std::string name = ""; - std::string id = ""; + QString name = ""; + QString id = ""; Framerate rate = 0; Resolution size = ""; }; @@ -103,8 +103,8 @@ struct Settings class LIB_EXPORT Renderer : public QObject { Q_OBJECT public: - Renderer(const std::string& id, Settings videoSettings, - const std::string& shmPath = "", const bool useAVFrame = false); + Renderer(const QString& id, Settings videoSettings, + const QString& shmPath = "", const bool useAVFrame = false); ~Renderer(); /** @@ -116,7 +116,7 @@ public: * @param res new resolution "wxh" * @param shmPath new shmPath */ - void update(const std::string& res, const std::string& shmPath); + void update(const QString& res, const QString& shmPath); /** * Stop renderer and thread */ @@ -130,7 +130,7 @@ public: /** * @return renderer's id */ - std::string getId() const; + QString getId() const; /** * @return current rendered frame */ @@ -167,7 +167,7 @@ Q_SIGNALS: * Emitted when a new frame is ready * @param id */ - void frameUpdated(const std::string& id); + void frameUpdated(const QString& id); private: std::unique_ptr<RendererPimpl> pimpl_; diff --git a/src/api/peerdiscoverymodel.h b/src/api/peerdiscoverymodel.h index 382c9e43a430e49f84fc00da550da1f289c72b16..38cf150c88adb5c4d5983ac5084c471ed6ba887b 100644 --- a/src/api/peerdiscoverymodel.h +++ b/src/api/peerdiscoverymodel.h @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright (C) 2019-2020 Savoir-faire Linux Inc. * + * Copyright (C) 2019-2020 Savoir-faire Linux Inc. * * Author: Mingrui Zhang <mingrui.zhang@savoirfairelinux.com> * * * * This library is free software; you can redistribute it and/or * @@ -18,17 +18,16 @@ #pragma once +// Lrc +#include "typedefs.h" + +// Qt +#include <QObject> + // std #include <vector> #include <map> #include <memory> -#include <string> - -// Qt -#include <qobject.h> - -// Lrc -#include "typedefs.h" namespace lrc { @@ -51,7 +50,6 @@ enum class PeerModelChanged REMOVE }; - /** * @brief Class that manages local peer discovery info */ @@ -59,7 +57,7 @@ class LIB_EXPORT PeerDiscoveryModel : public QObject { Q_OBJECT public: - PeerDiscoveryModel(const CallbacksHandler& callbackHandler, const std::string& accountID); + PeerDiscoveryModel(const CallbacksHandler& callbackHandler, const QString& accountID); ~PeerDiscoveryModel(); /** * get a map of discovered peers account @@ -71,7 +69,7 @@ Q_SIGNALS: /** * Connect this signal to know when the status of local peer discovery map changed. */ - void modelChanged(const std::string& contactUri, PeerModelChanged state, const std::string& displayname); + void modelChanged(const QString& contactUri, PeerModelChanged state, const QString& displayname); private: std::unique_ptr<PeerDiscoveryModelPimpl> pimpl_; diff --git a/src/api/profile.h b/src/api/profile.h index 68b8e72cfb15da3355e71605bed8027f21ae4c94..681220d385178e9c346b347dba8401f0f13803dc 100644 --- a/src/api/profile.h +++ b/src/api/profile.h @@ -18,8 +18,7 @@ ***************************************************************************/ #pragma once -// Std -#include <string> +#include <QString> namespace lrc { @@ -39,7 +38,7 @@ enum class Type { COUNT__ }; -static inline const std::string +static inline const QString to_string(const Type& type) { switch(type) { @@ -59,7 +58,7 @@ to_string(const Type& type) } static inline Type -to_type(const std::string& type) +to_type(const QString& type) { if (type == "PENDING") return Type::PENDING; @@ -81,9 +80,9 @@ to_type(const std::string& type) */ struct Info { - std::string uri = ""; - std::string avatar = ""; - std::string alias = ""; + QString uri = ""; + QString avatar = ""; + QString alias = ""; Type type = Type::INVALID; }; diff --git a/src/authority/daemon.cpp b/src/authority/daemon.cpp index 2d4dc6dc88a8fbec0434847a58a0be1b139145b2..d16aba9f2def288044ca6f64494aed56ebe28873 100644 --- a/src/authority/daemon.cpp +++ b/src/authority/daemon.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * + * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * * Author: Nicolas Jäger <nicolas.jager@savoirfairelinux.com> * * Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com> * * * @@ -29,40 +29,33 @@ namespace daemon { void -addContact(const api::account::Info& owner, const std::string& contactUri) +addContact(const api::account::Info& owner, const QString& contactUri) { - ConfigurationManager::instance().addContact(QString(owner.id.c_str()), - QString(contactUri.c_str())); + ConfigurationManager::instance().addContact(owner.id, contactUri); } void addContact(const api::account::Info& owner, const api::contact::Info& contactInfo) { - ConfigurationManager::instance().addContact(QString(owner.id.c_str()), - QString(contactInfo.profileInfo.uri.c_str())); + ConfigurationManager::instance().addContact(owner.id, contactInfo.profileInfo.uri); } void -removeContact(const api::account::Info& owner, const std::string& contactUri, bool banned) +removeContact(const api::account::Info& owner, const QString& contactUri, bool banned) { - ConfigurationManager::instance().removeContact(QString(owner.id.c_str()), - QString(contactUri.c_str()), banned); + ConfigurationManager::instance().removeContact(owner.id, contactUri, banned); } bool -addContactFromPending(const api::account::Info& owner, const std::string& contactUri) +addContactFromPending(const api::account::Info& owner, const QString& contactUri) { - return ConfigurationManager::instance().acceptTrustRequest(QString(owner.id.c_str()), - QString(contactUri.c_str())); + return ConfigurationManager::instance().acceptTrustRequest(owner.id, contactUri); } bool -discardFromPending(const api::account::Info& owner, const std::string& contactUri) +discardFromPending(const api::account::Info& owner, const QString& contactUri) { - return ConfigurationManager::instance().discardTrustRequest( - QString(owner.id.c_str()), - QString(contactUri.c_str()) - ); + return ConfigurationManager::instance().discardTrustRequest(owner.id, contactUri); } } // namespace daemon diff --git a/src/authority/daemon.h b/src/authority/daemon.h index 2fad74dc23543baa92d3a596bdce93f22a9a573b..fbe84249bcb1bd33db5d96b2e29d7943c3d86547 100644 --- a/src/authority/daemon.h +++ b/src/authority/daemon.h @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * + * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * * Author: Nicolas Jäger <nicolas.jager@savoirfairelinux.com> * * Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com> * * * @@ -36,7 +36,7 @@ namespace daemon * @param owner * @param contactUri */ -void addContact(const api::account::Info& owner, const std::string& contactUri); +void addContact(const api::account::Info& owner, const QString& contactUri); /** * Ask the daemon to add contact to the daemon. * @param owner @@ -49,21 +49,21 @@ void addContact(const api::account::Info& owner, const api::contact::Info& conta * @param contactInfo * @param banned */ -void removeContact(const api::account::Info& owner, const std::string& contactUri, bool banned); +void removeContact(const api::account::Info& owner, const QString& contactUri, bool banned); /** * Ask the daemon to add a contact from the pending list. * @param owner * @param contactUri * @return if operation succeed */ -bool addContactFromPending(const api::account::Info& owner, const std::string& contactUri); +bool addContactFromPending(const api::account::Info& owner, const QString& contactUri); /** * Ask the daemon to discard a pending. * @param owner * @param contactUri * @return if operation succeed */ -bool discardFromPending(const api::account::Info& owner, const std::string& contactUri); +bool discardFromPending(const api::account::Info& owner, const QString& contactUri); } // namespace daemon diff --git a/src/authority/storagehelper.cpp b/src/authority/storagehelper.cpp index b4de3e8a05fcc54cf0d28988400018e329565d16..99a9c7ac1f7c75f768fb26dd3526c40ad7047e71 100644 --- a/src/authority/storagehelper.cpp +++ b/src/authority/storagehelper.cpp @@ -21,6 +21,7 @@ #include "storagehelper.h" #include "api/profile.h" +#include "api/conversation.h" #include "api/datatransfer.h" #include "uri.h" #include "vcard.h" @@ -56,18 +57,16 @@ QString getPath() return dataDir.absolutePath() + "/jami/"; } -std::string -prepareUri(const std::string& uri, api::profile::Type type) +QString +prepareUri(const QString& uri, api::profile::Type type) { - URI uriObject(QString::fromStdString(uri)); + URI uriObject(uri); switch (type) { case api::profile::Type::SIP: - return uriObject.format(URI::Section::USER_INFO | URI::Section::HOSTNAME) - .toStdString(); + return uriObject.format(URI::Section::USER_INFO | URI::Section::HOSTNAME); break; case api::profile::Type::RING: - return uriObject.format(URI::Section::USER_INFO) - .toStdString(); + return uriObject.format(URI::Section::USER_INFO); break; case api::profile::Type::INVALID: case api::profile::Type::PENDING: @@ -78,7 +77,7 @@ prepareUri(const std::string& uri, api::profile::Type type) } } -std::string +QString getFormattedCallDuration(const std::time_t duration) { if (duration == 0) return {}; @@ -95,47 +94,47 @@ getFormattedCallDuration(const std::time_t duration) } if (seconds < 10) formattedString += "0"; formattedString += std::to_string(seconds); - return formattedString; + return QString::fromStdString(formattedString); } -std::string -getCallInteractionString(const std::string& authorUri, +QString +getCallInteractionString(const QString& authorUri, const std::time_t& duration) { if (duration < 0) { - if (authorUri.empty()) { - return "📞 " + QObject::tr("Outgoing call").toStdString(); + if (authorUri.isEmpty()) { + return "📞 " + QObject::tr("Outgoing call"); } else { - return "📞 " + QObject::tr("Incoming call").toStdString(); + return "📞 " + QObject::tr("Incoming call"); } - } else if (authorUri.empty()) { + } else if (authorUri.isEmpty()) { if (duration) { - return "📞 " + QObject::tr("Outgoing call").toStdString() + return "📞 " + QObject::tr("Outgoing call") + " - " + getFormattedCallDuration(duration); } else { - return "🕽 " + QObject::tr("Missed outgoing call").toStdString(); + return "🕽 " + QObject::tr("Missed outgoing call"); } } else { if (duration) { - return "📞 " + QObject::tr("Incoming call").toStdString() + return "📞 " + QObject::tr("Incoming call") + " - " + getFormattedCallDuration(duration); } else { - return "🕽 " + QObject::tr("Missed incoming call").toStdString(); + return "🕽 " + QObject::tr("Missed incoming call"); } } } -std::string -getContactInteractionString(const std::string& authorUri, +QString +getContactInteractionString(const QString& authorUri, const api::interaction::Status& status) { - if (authorUri.empty()) { - return QObject::tr("Contact added").toStdString(); + if (authorUri.isEmpty()) { + return QObject::tr("Contact added"); } else { if (status == api::interaction::Status::UNKNOWN) { - return QObject::tr("Invitation received").toStdString(); + return QObject::tr("Invitation received"); } else if (status == api::interaction::Status::SUCCESS) { - return QObject::tr("Invitation accepted").toStdString(); + return QObject::tr("Invitation accepted"); } } return {}; @@ -143,17 +142,16 @@ getContactInteractionString(const std::string& authorUri, namespace vcard { -std::string compressedAvatar(const std::string& image); -void setProfile(const std::string& accountId, +QString compressedAvatar(const QString& image); +void setProfile(const QString& accountId, const api::profile::Info& profileInfo, - const bool overwrite, const bool isPeer); -std::string -compressedAvatar(const std::string& image) +QString +compressedAvatar(const QString& image) { QImage qimage; - const bool ret = qimage.loadFromData(QByteArray::fromBase64(image.c_str()), 0); + const bool ret = qimage.loadFromData(QByteArray::fromBase64(image.toUtf8()), 0); if (!ret) { qDebug() << "vCard image loading failed"; return image; @@ -163,19 +161,20 @@ compressedAvatar(const std::string& image) buffer.open(QIODevice::WriteOnly); qimage.scaled({ 128,128 }).save(&buffer, "JPEG", 90); auto b64Img = bArray.toBase64().trimmed(); - return std::string(b64Img.constData(), b64Img.length()); + return QString::fromLocal8Bit(b64Img.constData(), b64Img.length()); } -std::string +QString profileToVcard(const api::profile::Info& profileInfo, bool compressImage) { using namespace api; - bool compressedImage = std::strncmp(profileInfo.avatar.c_str(), "/9j/", 4) == 0; + bool compressedImage = std::strncmp( + profileInfo.avatar.toStdString().c_str(), "/9j/", 4) == 0; if (compressedImage && !compressImage) { compressImage = false; } - std::string vCardStr = vCard::Delimiter::BEGIN_TOKEN; + QString vCardStr = vCard::Delimiter::BEGIN_TOKEN; vCardStr += vCard::Delimiter::END_LINE_TOKEN; vCardStr += vCard::Property::VERSION; vCardStr += ":2.1"; @@ -215,17 +214,17 @@ profileToVcard(const api::profile::Info& profileInfo, } void -setProfile(const std::string& accountId, +setProfile(const QString& accountId, const api::profile::Info& profileInfo, const bool isPeer) { auto vcard = vcard::profileToVcard(profileInfo); - auto accountLocalPath = getPath() + QString::fromStdString(accountId) + "/"; + auto accountLocalPath = getPath() + accountId + "/"; QString filePath; QFile file; if (isPeer) { filePath = accountLocalPath + "profiles/" + - QString(QByteArray::fromStdString(profileInfo.uri).toBase64()) + ".vcf"; + QString(profileInfo.uri.toUtf8().toBase64()) + ".vcf"; file.setFileName(filePath); } else { filePath = accountLocalPath + "profile" + ".vcf"; @@ -237,12 +236,12 @@ setProfile(const std::string& accountId, } QTextStream in(&file); in.setCodec("UTF-8"); - in << QString::fromStdString(vcard); + in << vcard; } } // namespace vcard -std::vector<std::string> -getConversationsWithPeer(Database& db, const std::string& participant_uri) +VectorString +getConversationsWithPeer(Database& db, const QString& participant_uri) { return db.select("id", "conversations", @@ -250,8 +249,8 @@ getConversationsWithPeer(Database& db, const std::string& participant_uri) {{":participant", participant_uri}}).payloads; } -std::vector<std::string> -getPeerParticipantsForConversation(Database& db, const std::string& conversationId) +VectorString +getPeerParticipantsForConversation(Database& db, const QString& conversationId) { return db.select("participant", "conversations", @@ -260,24 +259,24 @@ getPeerParticipantsForConversation(Database& db, const std::string& conversation } void -createOrUpdateProfile(const std::string & accountId, +createOrUpdateProfile(const QString & accountId, const api::profile::Info & profileInfo, const bool isPeer) { if (isPeer) { auto contact = storage::buildContactFromProfile(accountId, profileInfo.uri, profileInfo.type); - if (!profileInfo.alias.empty()) contact.profileInfo.alias = profileInfo.alias; - if (!profileInfo.avatar.empty()) contact.profileInfo.avatar = profileInfo.avatar; + if (!profileInfo.alias.isEmpty()) contact.profileInfo.alias = profileInfo.alias; + if (!profileInfo.avatar.isEmpty()) contact.profileInfo.avatar = profileInfo.avatar; vcard::setProfile(accountId, contact.profileInfo, isPeer); return; } vcard::setProfile(accountId, profileInfo, isPeer); } -std::string -getAccountAvatar(const std::string& accountId) +QString +getAccountAvatar(const QString& accountId) { - auto accountLocalPath = getPath() + QString::fromStdString(accountId) + "/"; + auto accountLocalPath = getPath() + accountId + "/"; QString filePath; filePath = accountLocalPath + "profile.vcf"; QFile file(filePath); @@ -290,24 +289,24 @@ getAccountAvatar(const std::string& accountId) const auto vCard = lrc::vCard::utils::toHashMap(in.readAll().toUtf8()); const auto photo = (vCard.find(vCard::Property::PHOTO_PNG) == vCard.end()) ? vCard[vCard::Property::PHOTO_JPEG] : vCard[vCard::Property::PHOTO_PNG]; - return photo.toStdString(); + return photo; } api::contact::Info -buildContactFromProfile(const std::string & accountId, - const std::string& peer_uri, +buildContactFromProfile(const QString & accountId, + const QString& peer_uri, const api::profile::Type& type) { lrc::api::profile::Info profileInfo; profileInfo.uri = peer_uri; profileInfo.type = type; - auto accountLocalPath = getPath() + QString::fromStdString(accountId) + "/"; + auto accountLocalPath = getPath() + accountId + "/"; QString b64filePath; - b64filePath = accountLocalPath + "profiles/" + QString(QByteArray::fromStdString(peer_uri).toBase64()) + ".vcf"; + b64filePath = accountLocalPath + "profiles/" + QString(peer_uri.toUtf8().toBase64()) + ".vcf"; QFile file(b64filePath); if (!file.open(QIODevice::ReadOnly)) { // try non-base64 path - QString filePath = accountLocalPath + "profiles/" + QString::fromStdString(peer_uri) + ".vcf"; + QString filePath = accountLocalPath + "profiles/" + peer_uri + ".vcf"; file.setFileName(filePath); if (!file.open(QIODevice::ReadOnly)) { qWarning().noquote() << "Can't open file: " << filePath; @@ -330,24 +329,24 @@ buildContactFromProfile(const std::string & accountId, const auto photo = (vCard.find(vCard::Property::PHOTO_PNG) == vCard.end()) ? vCard[vCard::Property::PHOTO_JPEG] : vCard[vCard::Property::PHOTO_PNG]; - profileInfo.avatar = photo.toStdString(); - profileInfo.alias = alias.toStdString(); + profileInfo.avatar = photo; + profileInfo.alias = alias; return { profileInfo, "", true, false }; } -std::vector<std::string> getAllConversations(Database & db) +VectorString getAllConversations(Database & db) { return db.select("id", "conversations", {}, {}).payloads; } -std::vector<std::string> -getConversationsBetween(Database& db, const std::string& peer1_uri, const std::string& peer2_uri) +VectorString +getConversationsBetween(Database& db, const QString& peer1_uri, const QString& peer2_uri) { auto conversationsForPeer1 = getConversationsWithPeer(db, peer1_uri); std::sort(conversationsForPeer1.begin(), conversationsForPeer1.end()); auto conversationsForPeer2 = getConversationsWithPeer(db, peer2_uri); std::sort(conversationsForPeer2.begin(), conversationsForPeer2.end()); - std::vector<std::string> common; + VectorString common; std::set_intersection(conversationsForPeer1.begin(), conversationsForPeer1.end(), conversationsForPeer2.begin(), conversationsForPeer2.end(), @@ -355,8 +354,8 @@ getConversationsBetween(Database& db, const std::string& peer1_uri, const std::s return common; } -std::string -beginConversationWithPeer(Database& db, const std::string& peer_uri, const bool isOutgoing) +QString +beginConversationWithPeer(Database& db, const QString& peer_uri, const bool isOutgoing) { // Add conversation between account and profile auto newConversationsId = db.select("IFNULL(MAX(id), 0) + 1", @@ -391,15 +390,16 @@ getHistory(Database& db, api::conversation::Info& conversation) if (interactionsResult.nbrOfCols == nCols) { auto payloads = interactionsResult.payloads; for (decltype(payloads.size()) i = 0; i < payloads.size(); i += nCols) { - std::string durationString; - auto extra_data_str = QString::fromStdString(payloads[i + 7]); + QString durationString; + auto extra_data_str = payloads[i + 7]; if (!extra_data_str.isEmpty()) { auto jsonData = JSONFromString(extra_data_str); - durationString = readJSONValue(jsonData, "duration").toStdString(); + durationString = readJSONValue(jsonData, "duration"); } auto body = payloads[i + 2]; auto type = api::interaction::to_type(payloads[i + 4]); - std::time_t duration = durationString.empty() ? 0 : std::stoi(durationString); + std::time_t duration = durationString.isEmpty() ? + 0 : std::stoi(durationString.toStdString()); auto status = api::interaction::to_status(payloads[i + 5]); if (type == api::interaction::Type::CALL) { body = getCallInteractionString(payloads[i + 1], duration); @@ -409,21 +409,21 @@ getHistory(Database& db, api::conversation::Info& conversation) auto msg = api::interaction::Info({ payloads[i + 1], body, - std::stoi(payloads[i + 3]), + std::stoi(payloads[i + 3].toStdString()), duration, type, status, (payloads[i + 6] == "1" ? true : false) }); - conversation.interactions.emplace(std::stoull(payloads[i]), std::move(msg)); - conversation.lastMessageUid = std::stoull(payloads[i]); + conversation.interactions.emplace(std::stoull(payloads[i].toStdString()), std::move(msg)); + conversation.lastMessageUid = std::stoull(payloads[i].toStdString()); } } } int addMessageToConversation(Database& db, - const std::string& conversationId, + const QString& conversationId, const api::interaction::Info& msg) { return db.insertInto("interactions", { @@ -437,7 +437,7 @@ addMessageToConversation(Database& db, }, { { ":author", msg.authorUri}, { ":conversation", conversationId}, - { ":timestamp", std::to_string(msg.timestamp)}, + { ":timestamp", toQString(msg.timestamp)}, { ":body", msg.body}, { ":type", to_string(msg.type)}, { ":status", to_string(msg.status)}, @@ -447,9 +447,9 @@ addMessageToConversation(Database& db, int addOrUpdateMessage(Database& db, - const std::string& conversationId, + const QString& conversationId, const api::interaction::Info& msg, - const std::string& daemonId) + const QString& daemonId) { // Check if profile is already present. auto msgAlreadyExists = db.select("id", @@ -467,37 +467,37 @@ addOrUpdateMessage(Database& db, {":status", "status"}, {":daemon_id", "daemon_id"} }, { - {":author", msg.authorUri.empty() ? "" : msg.authorUri}, + {":author", msg.authorUri.isEmpty() ? "" : msg.authorUri}, {":conversation", conversationId}, - {":timestamp", std::to_string(msg.timestamp)}, - {msg.body.empty() ? "" : ":body", msg.body}, + {":timestamp", toQString(msg.timestamp)}, + {msg.body.isEmpty() ? "" : ":body", msg.body}, {":type", to_string(msg.type)}, - {daemonId.empty() ? "" : ":daemon_id", daemonId}, + {daemonId.isEmpty() ? "" : ":daemon_id", daemonId}, {":status", to_string(msg.status)} }); } else { // already exists @ id(msgAlreadyExists[0]) auto id = msgAlreadyExists[0]; - std::string extra_data; + QString extra_data; if (msg.type == api::interaction::Type::CALL) { auto duration = std::max(msg.duration, static_cast<std::time_t>(0)); auto extra_data_str = getInteractionExtraDataById(db, id); - auto extra_data_JSON = JSONFromString(QString::fromStdString(extra_data_str)); + auto extra_data_JSON = JSONFromString(extra_data_str); writeJSONValue(extra_data_JSON, "duration", QString::number(duration)); - extra_data = stringFromJSON(extra_data_JSON).toStdString(); + extra_data = stringFromJSON(extra_data_JSON); } db.update("interactions", { "body=:body, extra_data=:extra_data" }, - { {msg.body.empty() ? "" : ":body", msg.body}, - { extra_data.empty() ? "" : ":extra_data", extra_data } }, + { {msg.body.isEmpty() ? "" : ":body", msg.body}, + { extra_data.isEmpty() ? "" : ":extra_data", extra_data } }, "id=:id", { {":id", id} }); - return std::stoi(id); + return std::stoi(id.toStdString()); } } int addDataTransferToConversation(Database& db, - const std::string& conversationId, + const QString& conversationId, const api::datatransfer::Info& infoFromDaemon) { return db.insertInto("interactions", { @@ -511,7 +511,7 @@ addDataTransferToConversation(Database& db, }, { {":author", infoFromDaemon.isOutgoing ? "" : infoFromDaemon.peerUri}, {":conversation", conversationId}, - {":timestamp", std::to_string(std::time(nullptr))}, + {":timestamp", toQString(std::time(nullptr))}, {":body", infoFromDaemon.path}, {":type", infoFromDaemon.isOutgoing ? "DATA_TRANSFER" : @@ -522,8 +522,8 @@ addDataTransferToConversation(Database& db, } void addDaemonMsgId(Database& db, - const std::string& interactionId, - const std::string& daemonId) + const QString& interactionId, + const QString& daemonId) { db.update("interactions", "daemon_id=:daemon_id", @@ -531,7 +531,7 @@ void addDaemonMsgId(Database& db, "id=:id", {{":id", interactionId}}); } -std::string getDaemonIdByInteractionId(Database& db, const std::string& id) +QString getDaemonIdByInteractionId(Database& db, const QString& id) { auto ids = db.select("daemon_id", "interactions", @@ -540,7 +540,7 @@ std::string getDaemonIdByInteractionId(Database& db, const std::string& id) return ids.empty() ? "" : ids[0]; } -std::string getInteractionIdByDaemonId(Database& db, const std::string& daemon_id) +QString getInteractionIdByDaemonId(Database& db, const QString& daemon_id) { auto ids = db.select("id", "interactions", @@ -549,31 +549,29 @@ std::string getInteractionIdByDaemonId(Database& db, const std::string& daemon_i return ids.empty() ? "" : ids[0]; } -std::string getInteractionExtraDataById(Database& db, const std::string& id, - const std::string& key) +QString getInteractionExtraDataById(Database& db, const QString& id, + const QString& key) { auto extra_datas = db.select("extra_data", "interactions", "id=:id", { {":id", id} }).payloads; - if (key.empty()) { + if (key.isEmpty()) { return extra_datas.empty() ? "" : extra_datas[0]; } - std::string value; - auto extra_data_str = QString::fromStdString(extra_datas[0]); - if (!extra_data_str.isEmpty()) { - value = readJSONValue(JSONFromString(extra_data_str), QString::fromStdString(key)) - .toStdString(); + QString value; + if (!extra_datas[0].isEmpty()) { + value = readJSONValue(JSONFromString(extra_datas[0]), key); } return value; } void updateInteractionBody(Database& db, unsigned int id, - const std::string& newBody) + const QString& newBody) { db.update("interactions", "body=:body", {{":body", newBody}}, - "id=:id", {{":id", std::to_string(id)}}); + "id=:id", {{":id", toQString(id)}}); } void updateInteractionStatus(Database& db, unsigned int id, @@ -582,7 +580,7 @@ void updateInteractionStatus(Database& db, unsigned int id, db.update("interactions", { "status=:status" }, {{":status", api::interaction::to_string(newStatus)}}, - "id=:id", {{":id", std::to_string(id)}}); + "id=:id", {{":id", toQString(id)}}); } void setInteractionRead(Database& db, unsigned int id) @@ -590,16 +588,16 @@ void setInteractionRead(Database& db, unsigned int id) db.update("interactions", { "is_read=:is_read" }, { {":is_read", "1"} }, - "id=:id", { {":id", std::to_string(id)} }); + "id=:id", { {":id", toQString(id)} }); } -std::string +QString conversationIdFromInteractionId(Database& db, unsigned int interactionId) { auto result = db.select("conversation", "interactions", "id=:id", - {{":id", std::to_string(interactionId)}}); + {{":id", toQString(interactionId)}}); if (result.nbrOfCols == 1 && result.payloads.size()) { return result.payloads[0]; } @@ -607,28 +605,28 @@ conversationIdFromInteractionId(Database& db, unsigned int interactionId) } void clearHistory(Database& db, - const std::string& conversationId) + const QString& conversationId) { try { db.deleteFrom("interactions", "conversation=:conversation", {{":conversation", conversationId}}); } catch (Database::QueryDeleteError& e) { - qWarning() << "deleteFrom error: " << e.details().c_str(); + qWarning() << "deleteFrom error: " << e.details(); } } void clearInteractionFromConversation(Database& db, - const std::string& conversationId, + const QString& conversationId, const uint64_t& interactionId) { try { db.deleteFrom("interactions", "conversation=:conversation AND id=:id", {{":conversation", conversationId}, - {":id", std::to_string(interactionId)}}); + {":id", toQString(interactionId)}}); } catch (Database::QueryDeleteError& e) { - qWarning() << "deleteFrom error: " << e.details().c_str(); + qWarning() << "deleteFrom error: " << e.details(); } } @@ -639,7 +637,7 @@ void clearAllHistory(Database& db) "1=1", {}); } catch (Database::QueryDeleteError& e) { - qWarning() << "deleteFrom error: " << e.details().c_str(); + qWarning() << "deleteFrom error: " << e.details(); } } @@ -647,14 +645,14 @@ void deleteObsoleteHistory(Database& db, long int date) { try { - db.deleteFrom("interactions", "timestamp<=:date", { {":date", std::to_string(date)} }); + db.deleteFrom("interactions", "timestamp<=:date", { {":date", toQString(date)} }); } catch (Database::QueryDeleteError& e) { - qWarning() << "deleteFrom error: " << e.details().c_str(); + qWarning() << "deleteFrom error: " << e.details(); } } void -removeContact(Database& db, const std::string& contactUri) +removeContact(Database& db, const QString& contactUri) { // Get common conversations auto conversations = getConversationsWithPeer(db, contactUri); @@ -667,12 +665,12 @@ removeContact(Database& db, const std::string& contactUri) db.deleteFrom("interactions", "conversation=:id", {{":id", conversationId}}); } } catch (Database::QueryDeleteError& e) { - qWarning() << "deleteFrom error: " << e.details().c_str(); + qWarning() << "deleteFrom error: " << e.details(); } } int -countUnreadFromInteractions(Database& db, const std::string& conversationId) +countUnreadFromInteractions(Database& db, const QString& conversationId) { return db.count("is_read", "interactions", @@ -686,8 +684,8 @@ getLastTimestamp(Database& db) auto timestamps = db.select("MAX(timestamp)", "interactions", "1=1", {}).payloads; auto result = std::time(nullptr); try { - if (!timestamps.empty() && !timestamps[0].empty()) { - result = std::stoull(timestamps[0]); + if (!timestamps.empty() && !timestamps[0].isEmpty()) { + result = std::stoull(timestamps[0].toStdString()); } } catch (const std::out_of_range& e) { qDebug() << "storage::getLastTimestamp, stoull throws an out_of_range exception: " << e.what(); @@ -776,13 +774,13 @@ enum class msgFlag { IS_TEXT }; -std::string profileToVcard(const lrc::api::profile::Info&, const std::string&); -uint64_t getTimeFromTimeStr(const std::string&) noexcept; -std::pair<msgFlag, uint64_t> migrateMessageBody(const std::string&, +QString profileToVcard(const lrc::api::profile::Info&, const QString&); +uint64_t getTimeFromTimeStr(const QString&) noexcept; +std::pair<msgFlag, uint64_t> migrateMessageBody(const QString&, const lrc::api::interaction::Type&); -std::vector<std::string> getPeerParticipantsForConversationId(lrc::Database&, - const std::string&, - const std::string&); +VectorString getPeerParticipantsForConversationId(lrc::Database&, + const QString&, + const QString&); void migrateAccountDb(const QString&, std::shared_ptr<lrc::Database>, std::shared_ptr<lrc::Database>); @@ -790,7 +788,7 @@ void migrateAccountDb(const QString&, namespace interaction { static inline api::interaction::Type -to_type(const std::string& type) +to_type(const QString& type) { if (type == "TEXT") return api::interaction::Type::TEXT; @@ -806,8 +804,8 @@ to_type(const std::string& type) return api::interaction::Type::INVALID; } -static inline std::string -to_migrated_status_string(const std::string& status) +static inline QString +to_migrated_status_string(const QString& status) { if (status == "FAILED") return "FAILURE"; @@ -824,18 +822,19 @@ to_migrated_status_string(const std::string& status) } // namespace interaction -std::string +QString profileToVcard(const api::profile::Info& profileInfo, - const std::string& accountId = {}) + const QString& accountId = {}) { using namespace api; - bool compressedImage = std::strncmp(profileInfo.avatar.c_str(), "/9g=", 4) == 0;; - std::string vCardStr = vCard::Delimiter::BEGIN_TOKEN; + bool compressedImage = std::strncmp( + profileInfo.avatar.toStdString().c_str(), "/9g=", 4) == 0;; + QString vCardStr = vCard::Delimiter::BEGIN_TOKEN; vCardStr += vCard::Delimiter::END_LINE_TOKEN; vCardStr += vCard::Property::VERSION; vCardStr += ":2.1"; vCardStr += vCard::Delimiter::END_LINE_TOKEN; - if (!accountId.empty()) { + if (!accountId.isEmpty()) { vCardStr += vCard::Property::UID; vCardStr += ":"; vCardStr += accountId; @@ -869,14 +868,15 @@ profileToVcard(const api::profile::Info& profileInfo, } uint64_t -getTimeFromTimeStr(const std::string& str) noexcept +getTimeFromTimeStr(const QString& str) noexcept { uint64_t minutes = 0, seconds = 0; - std::size_t delimiterPos = str.find(":"); + std::string timeStr = str.toStdString(); + std::size_t delimiterPos = timeStr.find(":"); if (delimiterPos != std::string::npos) { try { - minutes = std::stoull(str.substr(0, delimiterPos)); - seconds = std::stoull(str.substr(delimiterPos + 1)); + minutes = std::stoull(timeStr.substr(0, delimiterPos)); + seconds = std::stoull(timeStr.substr(delimiterPos + 1)); } catch (const std::exception&) { return 0; } @@ -885,7 +885,7 @@ getTimeFromTimeStr(const std::string& str) noexcept } std::pair<msgFlag, uint64_t> -migrateMessageBody(const std::string& body, const api::interaction::Type& type) +migrateMessageBody(const QString& body, const api::interaction::Type& type) { uint64_t duration{ 0 }; // check in english and local to determine the direction of the call @@ -899,29 +899,29 @@ migrateMessageBody(const std::string& body, const api::interaction::Type& type) static QString lir = QObject::tr("Invitation received"); static QString eia = "Invitation accepted"; static QString lia = QObject::tr("Invitation accepted"); - auto qstrBody = QString::fromStdString(body); + auto strBody = body.toStdString(); switch (type) { case api::interaction::Type::CALL: { - bool en_missedOut = qstrBody.contains(emo); - bool en_out = qstrBody.contains(eo); - bool loc_missedOut = qstrBody.contains(lmo); - bool loc_out = qstrBody.contains(lo); + bool en_missedOut = body.contains(emo); + bool en_out = body.contains(eo); + bool loc_missedOut = body.contains(lmo); + bool loc_out = body.contains(lo); bool outgoingCall = en_missedOut || en_out || loc_missedOut || loc_out; - std::size_t dashPos = body.find("-"); + std::size_t dashPos = strBody.find("-"); if (dashPos != std::string::npos) { - duration = getTimeFromTimeStr(body.substr(dashPos + 2)); + duration = getTimeFromTimeStr(toQString(strBody.substr(dashPos + 2))); } return std::make_pair(msgFlag(outgoingCall), duration); } break; case api::interaction::Type::CONTACT: - if (qstrBody.contains(eca) || qstrBody.contains(lca)) { + if (body.contains(eca) || body.contains(lca)) { return std::make_pair(msgFlag::IS_CONTACT_ADDED, 0); - } else if (qstrBody.contains(eir) || qstrBody.contains(lir)) { + } else if (body.contains(eir) || body.contains(lir)) { return std::make_pair(msgFlag::IS_INVITATION_RECEIVED, 0); - } else if (qstrBody.contains(eia) || qstrBody.contains(lia)) { + } else if (body.contains(eia) || body.contains(lia)) { return std::make_pair(msgFlag::IS_INVITATION_ACCEPTED, 0); } break; @@ -935,8 +935,8 @@ migrateMessageBody(const std::string& body, const api::interaction::Type& type) return std::make_pair(msgFlag::IS_OUTGOING, 0); } -std::vector<std::string> -getPeerParticipantsForConversationId(Database& db, const std::string& profileId, const std::string& conversationId) +VectorString +getPeerParticipantsForConversationId(Database& db, const QString& profileId, const QString& conversationId) { return db.select("participant_id", "conversations", @@ -958,25 +958,25 @@ migrateAccountDb(const QString& accountId, MapStringString accountDetails = ConfigurationManager::instance(). getAccountDetails(accountId.toStdString().c_str()); bool isRingAccount = accountDetails[ConfProperties::TYPE] == "RING"; - std::map<std::string, std::string> profileIdUriMap; - std::map<std::string, std::string> convIdPeerUriMap; - std::string accountProfileId; + std::map<QString, QString> profileIdUriMap; + std::map<QString, QString> convIdPeerUriMap; + QString accountProfileId; // 1. profiles_accounts // migrate account's avatar/alias from profiles table to {data_dir}/profile.vcf - std::string accountUri; + QString accountUri; if (isRingAccount) { accountUri = accountDetails[DRing::Account::ConfProperties::USERNAME].contains("ring:") ? - accountDetails[DRing::Account::ConfProperties::USERNAME].toStdString().substr(std::string("ring:").size()) : - accountDetails[DRing::Account::ConfProperties::USERNAME].toStdString(); + QString(accountDetails[DRing::Account::ConfProperties::USERNAME]).remove(QString("ring:")) : + accountDetails[DRing::Account::ConfProperties::USERNAME]; } else { - accountUri = accountDetails[DRing::Account::ConfProperties::USERNAME].toStdString(); + accountUri = accountDetails[DRing::Account::ConfProperties::USERNAME]; } auto accountProfileIds = legacyDb->select( "profile_id", "profiles_accounts", "account_id=:account_id AND is_account=:is_account", - { {":account_id", accountId.toStdString()}, + { {":account_id", accountId}, {":is_account", "true"} }).payloads; if (accountProfileIds.size() != 1) { return; @@ -994,13 +994,13 @@ migrateAccountDb(const QString& accountId, accountProfileInfo = { accountUri, accountProfile[0], accountProfile[1], isRingAccount ? profile::Type::RING : profile::Type::SIP }; } - auto accountVcard = profileToVcard(accountProfileInfo, accountId.toStdString()); + auto accountVcard = profileToVcard(accountProfileInfo, accountId); auto profileFilePath = accountLocalPath + "profile" + ".vcf"; QFile file(profileFilePath); if (!file.open(QIODevice::WriteOnly)) { throw std::runtime_error("Can't open file: " + profileFilePath.toStdString()); } - QTextStream(&file) << QString::fromStdString(accountVcard); + QTextStream(&file) << accountVcard; // 2. profiles // migrate profiles from profiles table to {data_dir}/{uri}.vcf @@ -1013,7 +1013,7 @@ migrateAccountDb(const QString& accountId, auto profileIds = legacyDb->select( "profile_id", "profiles_accounts", "account_id=:account_id AND is_account=:is_account", - { {":account_id", accountId.toStdString()}, + { {":account_id", accountId}, {":is_account", "false"} }).payloads; for (const auto& profileId : profileIds) { auto profile = legacyDb->select( @@ -1024,13 +1024,13 @@ migrateAccountDb(const QString& accountId, continue; } profile::Info profileInfo{ profile[0], profile[2], profile[1] }; - auto uri = URI(QString::fromStdString(profile[0])); + auto uri = URI(profile[0]); auto profileUri = uri.userinfo(); if (!isRingAccount && uri.hasHostname()) { profileUri += "@" + uri.hostname(); } // insert into map for use during the conversations table migration - profileIdUriMap.insert(std::make_pair(profileId, profileUri.toStdString())); + profileIdUriMap.insert(std::make_pair(profileId, profileUri)); auto vcard = profileToVcard(profileInfo); // make sure the directory exists QDir dir(accountLocalPath + "profiles"); @@ -1048,7 +1048,7 @@ migrateAccountDb(const QString& accountId, qWarning() << "Can't open file: " << profileFilePath; continue; } - QTextStream(&file) << QString::fromStdString(vcard); + QTextStream(&file) << vcard; } // 3. conversations @@ -1110,7 +1110,8 @@ migrateAccountDb(const QString& accountId, } // migrate body+type ==> msgFlag+duration auto migratedMsg = migrateMessageBody(body, type); - auto profileUri = it == profileIdUriMap.end() ? "" : it->second; + QString profileUri = it == profileIdUriMap.end() ? + "" : it->second; // clear author uri if outgoing switch (migratedMsg.first) { case msgFlag::IS_OUTGOING: @@ -1143,12 +1144,11 @@ migrateAccountDb(const QString& accountId, if (migratedMsg.first == msgFlag::IS_INVITATION_RECEIVED) { statusStr = "UNKNOWN"; } - std::string extra_data = migratedMsg.second == 0 ? "" : + QString extra_data = migratedMsg.second == 0 ? "" : JSONStringFromInitList({ qMakePair(QString("duration"), QJsonValue(QString::number(migratedMsg.second))) - }) - .toStdString(); + }); if (accountUri == profileUri) profileUri.clear(); auto typeStr = api::interaction::to_string(type); @@ -1171,8 +1171,8 @@ migrateAccountDb(const QString& accountId, {":type", api::interaction::to_string(type)}, {":status", interaction::to_migrated_status_string(statusStr)}, {":is_read", is_read ? "1" : "0" }, - {daemonId.empty() ? "" : ":daemon_id", daemonId}, - {extra_data.empty() ? "" : ":extra_data", extra_data } + {daemonId.isEmpty() ? "" : ":daemon_id", daemonId}, + {extra_data.isEmpty() ? "" : ":extra_data", extra_data } }); } catch (const std::runtime_error& e) { qWarning() << e.what(); diff --git a/src/authority/storagehelper.h b/src/authority/storagehelper.h index 9567e58fa7da4b8ee6992239f0db3f33852a5a52..5db65ee69aa5d6faa8275090a4f0b54cf746f257 100644 --- a/src/authority/storagehelper.h +++ b/src/authority/storagehelper.h @@ -53,7 +53,8 @@ QString getPath(); * @param type of account for which to transform the uri * @return formatted uri */ -std::string prepareUri(const std::string& uri, api::profile::Type type); +QString +prepareUri(const QString& uri, api::profile::Type type); /** * Get a formatted string for a call interaction's body @@ -61,8 +62,8 @@ std::string prepareUri(const std::string& uri, api::profile::Type type); * @param duration of the call * @return the formatted and translated call message string */ -std::string -getCallInteractionString(const std::string& authorUri, +QString +getCallInteractionString(const QString& authorUri, const std::time_t& duration); /** @@ -71,8 +72,8 @@ getCallInteractionString(const std::string& authorUri, * @param status * @return the formatted and translated call message string */ -std::string -getContactInteractionString(const std::string& authorUri, +QString +getContactInteractionString(const QString& authorUri, const api::interaction::Status& status); namespace vcard @@ -84,8 +85,9 @@ namespace vcard * @param compressImage * @return vcard string of the profile */ -std::string profileToVcard(const api::profile::Info& profileInfo, - bool compressImage = false); +QString +profileToVcard(const api::profile::Info& profileInfo, + bool compressImage = false); } // namespace vcard @@ -93,23 +95,26 @@ std::string profileToVcard(const api::profile::Info& profileInfo, * @param duration * @return a human readable call duration (M:ss) */ -std::string getFormattedCallDuration(const std::time_t duration); +QString +getFormattedCallDuration(const std::time_t duration); /** * Get all conversations with a given participant's URI * @param db * @param participant_uri */ -std::vector<std::string> getConversationsWithPeer(Database& db, - const std::string& participant_uri); +VectorString +getConversationsWithPeer(Database& db, + const QString& participant_uri); /** * Get all peer participant(s) URIs for a given conversation id * @param db * @param conversationId */ -std::vector<std::string> getPeerParticipantsForConversation(Database& db, - const std::string& conversationId); +VectorString +getPeerParticipantsForConversation(Database& db, + const QString& conversationId); /** * Creates or updates a contact or account vCard file with profile data. @@ -117,7 +122,7 @@ std::vector<std::string> getPeerParticipantsForConversation(Database& db, * @param profileInfo the contact info containing peer profile information * @param isPeer indicates that a the profileInfo is that of a peer */ -void createOrUpdateProfile(const std::string& accountId, +void createOrUpdateProfile(const QString& accountId, const api::profile::Info& profileInfo, const bool isPeer = false); @@ -126,8 +131,8 @@ void createOrUpdateProfile(const std::string& accountId, * @param accountId * @return the account's base64 avatar */ -std::string -getAccountAvatar(const std::string& accountId); +QString +getAccountAvatar(const QString& accountId); /** * Build a contact info struct from a vCard @@ -136,8 +141,8 @@ getAccountAvatar(const std::string& accountId); * @param type of contact to build * @return the contact info containing peer profile information */ -api::contact::Info buildContactFromProfile(const std::string & accountId, - const std::string& peer_uri, +api::contact::Info buildContactFromProfile(const QString& accountId, + const QString& peer_uri, const api::profile::Type& type); /** @@ -145,7 +150,7 @@ api::contact::Info buildContactFromProfile(const std::string & accountId, * @param db * @return conversations id for all conversations */ -std::vector<std::string> getAllConversations(Database& db); +VectorString getAllConversations(Database& db); /** * Get conversations shared between an account and a contact. @@ -154,9 +159,9 @@ std::vector<std::string> getAllConversations(Database& db); * @param contactProfile the id of the contact in the database * @return conversations id for conversations between account and contact */ -std::vector<std::string> getConversationsBetween(Database& db, - const std::string& accountProfile, - const std::string& contactProfile); +VectorString getConversationsBetween(Database& db, + const QString& accountProfile, + const QString& contactProfile); /** * Start a conversation between account and contact. Creates an entry in the conversations table @@ -166,9 +171,9 @@ std::vector<std::string> getConversationsBetween(Database& db, * @param isOutgoing * @return conversation_id of the new conversation. */ -std::string beginConversationWithPeer(Database& db, - const std::string& peer_uri, - const bool isOutgoing = true); +QString beginConversationWithPeer(Database& db, + const QString& peer_uri, + const bool isOutgoing = true); /** * Return interactions from a conversation @@ -185,7 +190,7 @@ void getHistory(Database& db, api::conversation::Info& conversation); * @return the id of the inserted interaction */ int addMessageToConversation(Database& db, - const std::string& conversationId, + const QString& conversationId, const api::interaction::Info& msg); /** @@ -197,9 +202,9 @@ int addMessageToConversation(Database& db, * @return the id of the inserted interaction */ int addOrUpdateMessage(Database& db, - const std::string& conversationId, + const QString& conversationId, const api::interaction::Info& msg, - const std::string& daemonId); + const QString& daemonId); /** * Add a data transfer entry into interactions linked to a conversation. @@ -209,7 +214,7 @@ int addOrUpdateMessage(Database& db, * @return the id of the inserted interaction */ int addDataTransferToConversation(Database& db, - const std::string& conversationId, + const QString& conversationId, const api::datatransfer::Info& infoFromDaemon); /** @@ -219,15 +224,15 @@ int addDataTransferToConversation(Database& db, * @param daemonId */ void addDaemonMsgId(Database& db, - const std::string& interactionId, - const std::string& daemonId); + const QString& interactionId, + const QString& daemonId); /** * @param db * @param id * @return the daemon id for an interaction else an empty string */ -std::string getDaemonIdByInteractionId(Database& db, const std::string& id); +QString getDaemonIdByInteractionId(Database& db, const QString& id); /** * Obtain the id of an interaction of a given daemon_id @@ -235,7 +240,7 @@ std::string getDaemonIdByInteractionId(Database& db, const std::string& id); * @param id * @return the interaction id for a daemon id else an empty string */ -std::string getInteractionIdByDaemonId(Database& db, const std::string& daemon_id); +QString getInteractionIdByDaemonId(Database& db, const QString& daemon_id); /** * Obtain the extra_data column of an interaction of a given id @@ -244,8 +249,8 @@ std::string getInteractionIdByDaemonId(Database& db, const std::string& daemon_i * @param id * @param key */ -std::string getInteractionExtraDataById(Database& db, const std::string& id, - const std::string& key = {}); +QString getInteractionExtraDataById(Database& db, const QString& id, + const QString& key = {}); /** * Change the body of an interaction @@ -254,7 +259,7 @@ std::string getInteractionExtraDataById(Database& db, const std::string& id, * @param newBody */ void updateInteractionBody(Database& db, unsigned int id, - const std::string& newBody); + const QString& newBody); /** * Change the status of an interaction @@ -279,7 +284,7 @@ void setInteractionRead(Database& db, unsigned int id); * @param conversationId */ void clearHistory(Database& db, - const std::string& conversationId); + const QString& conversationId); /** * Clear interaction from history @@ -288,7 +293,7 @@ void clearHistory(Database& db, * @param interactionId */ void clearInteractionFromConversation(Database& db, - const std::string& conversationId, + const QString& conversationId, const uint64_t& interactionId); /** @@ -310,21 +315,21 @@ void deleteObsoleteHistory(Database& db, long int date); * @param db * @param contactUri */ -void removeContact(Database& db, const std::string& contactUri); +void removeContact(Database& db, const QString& contactUri); /** * count number of 'UNREAD' from 'interactions' table. * @param db * @param conversationId */ -int countUnreadFromInteractions(Database& db, const std::string& conversationId); +int countUnreadFromInteractions(Database& db, const QString& conversationId); /** * Retrieve an interaction's conversation id * @param db * @param conversationId */ -std::string conversationIdFromInteractionId(Database& db, unsigned int interactionId); +QString conversationIdFromInteractionId(Database& db, unsigned int interactionId); /** * Retrieve the last timestamp from the interactions table diff --git a/src/avmodel.cpp b/src/avmodel.cpp index 1bb30628098f14468756bf6e4940548c6f107fbc..ba5f34548b0a3b408f0914e58286714ffa075e66 100644 --- a/src/avmodel.cpp +++ b/src/avmodel.cpp @@ -57,16 +57,16 @@ public: AVModelPimpl(AVModel& linked, const CallbacksHandler& callbacksHandler); const CallbacksHandler& callbacksHandler; - std::string getRecordingPath() const; - static const std::string recorderSavesSubdir; + QString getRecordingPath() const; + static const QString recorderSavesSubdir; AVModel& linked_; std::mutex renderers_mtx_; - std::map<std::string, std::unique_ptr<video::Renderer>> renderers_; + std::map<QString, std::unique_ptr<video::Renderer>> renderers_; // store if a renderers is for a finished call - std::map<std::string, bool> finishedRenderers_; + std::map<QString, bool> finishedRenderers_; bool useAVFrame_ = false; - std::string currentVideoCaptureDevice_ {}; + QString currentVideoCaptureDevice_ {}; #ifndef ENABLE_LIBWRAP // TODO: Init Video Renderers from daemon (see: https://git.jami.net/savoirfairelinux/ring-daemon/issues/59) @@ -79,7 +79,7 @@ public: * @param type * @return the device name */ - std::string getDevice(int type) const; + QString getDevice(int type) const; public Q_SLOTS: /** @@ -89,25 +89,25 @@ public Q_SLOTS: * @param width * @param height */ - void startedDecoding(const std::string& id, const std::string& shmPath, int width, int height); + void startedDecoding(const QString& id, const QString& shmPath, int width, int height); /** * Listen from CallbacksHandler when a renderer stops * @param id * @param shmPath */ - void stoppedDecoding(const std::string& id, const std::string& shmPath); + void stoppedDecoding(const QString& id, const QString& shmPath); /** * Listen from CallbacksHandler when a call got a new state * @param id * @param state the new state * @param code unused */ - void slotCallStateChanged(const std::string& id, const std::string &state, int code); + void slotCallStateChanged(const QString& id, const QString &state, int code); /** * Detect when the current frame is updated * @param id */ - void slotFrameUpdated(const std::string& id); + void slotFrameUpdated(const QString& id); /** * Detect when a device is plugged or unplugged */ @@ -117,16 +117,16 @@ public Q_SLOTS: * @param id Ringbuffer id * @param level Volume in range [0, 1] */ - void slotAudioMeter(const std::string& id, float level); + void slotAudioMeter(const QString& id, float level); /** * Listen from CallbacksHandler when a recorder stopped notice is incoming * @param filePath */ - void slotRecordPlaybackStopped(const std::string& filePath); + void slotRecordPlaybackStopped(const QString& filePath); }; -const std::string AVModelPimpl::recorderSavesSubdir = "sent_data"; +const QString AVModelPimpl::recorderSavesSubdir = "sent_data"; #ifndef ENABLE_LIBWRAP uint32_t AVModelPimpl::SIZE_RENDERER = 0; #endif @@ -190,57 +190,56 @@ AVModel::setHardwareAcceleration(bool accelerate) setEncodingAccelerated(accelerate); } -std::vector<std::string> +VectorString AVModel::getDevices() const { QStringList devices = VideoManager::instance() .getDeviceList(); - std::vector<std::string> result; - for (const auto& manager : devices) { - result.emplace_back(manager.toStdString()); + VectorString result; + for (const auto& device : devices) { + result.push_back(device); } return result; } -std::string +QString AVModel::getDefaultDevice() const { - QString name = VideoManager::instance().getDefaultDevice(); - return name.toStdString(); + return VideoManager::instance().getDefaultDevice(); } void -AVModel::setDefaultDevice(const std::string& deviceId) +AVModel::setDefaultDevice(const QString& deviceId) { - VideoManager::instance().setDefaultDevice(deviceId.c_str()); + VideoManager::instance().setDefaultDevice(deviceId); } video::Settings -AVModel::getDeviceSettings(const std::string& deviceId) const +AVModel::getDeviceSettings(const QString& deviceId) const { - if (deviceId.empty()) { + if (deviceId.isEmpty()) { return video::Settings(); } MapStringString settings = VideoManager::instance() - .getSettings(deviceId.c_str()); - if (settings["id"].toStdString() != deviceId) { - throw std::out_of_range("Device '" + deviceId + "' not found"); + .getSettings(deviceId); + if (settings["id"] != deviceId) { + throw std::out_of_range("Device '" + deviceId.toStdString() + "' not found"); } video::Settings result; - result.name = settings["name"].toStdString(); - result.id = settings["id"].toStdString(); - result.channel = settings["channel"].toStdString(); - result.size = settings["size"].toStdString(); + result.name = settings["name"]; + result.id = settings["id"]; + result.channel = settings["channel"]; + result.size = settings["size"]; result.rate = settings["rate"].toFloat(); return result; } video::Capabilities -AVModel::getDeviceCapabilities(const std::string& deviceId) const +AVModel::getDeviceCapabilities(const QString& deviceId) const { // Channel x Resolution x Framerate QMap<QString, QMap<QString, QVector<QString>>> capabilites = - VideoManager::instance().getCapabilities(deviceId.c_str()); + VideoManager::instance().getCapabilities(deviceId); video::Capabilities result; for (auto& channel : capabilites.toStdMap()) { video::ResRateList channelCapabilities; @@ -248,22 +247,20 @@ AVModel::getDeviceCapabilities(const std::string& deviceId) const video::FrameratesList rates; QVectorIterator<QString> itRates(resToRates.second); while (itRates.hasNext()) { - rates.emplace_back(itRates.next().toFloat()); + rates.push_back(itRates.next().toFloat()); } std::sort(rates.begin(), rates.end(), std::greater<int>()); - channelCapabilities.emplace_back( - std::make_pair(resToRates.first.toStdString(), rates)); + channelCapabilities.push_back(qMakePair(resToRates.first, rates)); } // sort by resolution widths std::sort(channelCapabilities.begin(), channelCapabilities.end(), - [](const std::pair<video::Resolution, video::FrameratesList>& lhs, - const std::pair<video::Resolution, video::FrameratesList>& rhs) { - auto lhsWidth = stoull(lhs.first.substr(0, lhs.first.find("x"))); - auto rhsWidth = stoull(rhs.first.substr(0, rhs.first.find("x"))); + [](const QPair<video::Resolution, video::FrameratesList>& lhs, + const QPair<video::Resolution, video::FrameratesList>& rhs) { + auto lhsWidth = lhs.first.left(lhs.first.indexOf("x")).toLongLong(); + auto rhsWidth = rhs.first.left(rhs.first.indexOf("x")).toLongLong(); return lhsWidth > rhsWidth; }); - result.insert( - std::make_pair(channel.first.toStdString(), channelCapabilities)); + result.insert(channel.first, channelCapabilities); } return result; } @@ -274,12 +271,12 @@ AVModel::setDeviceSettings(video::Settings& settings) MapStringString newSettings; auto rate = QString::number(settings.rate, 'f', 7); rate = rate.left(rate.length() - 1); - newSettings["channel"] = settings.channel.c_str(); - newSettings["name"] = settings.name.c_str(); - newSettings["id"] = settings.id.c_str(); + newSettings["channel"] = settings.channel; + newSettings["name"] = settings.name; + newSettings["id"] = settings.id; newSettings["rate"] = rate; - newSettings["size"] = settings.size.c_str(); - VideoManager::instance().applySettings(settings.id.c_str(), newSettings); + newSettings["size"] = settings.size; + VideoManager::instance().applySettings(settings.id, newSettings); // If the preview is running, reload it // doing this during a call will cause re-invite, this is unwanted @@ -292,42 +289,41 @@ AVModel::setDeviceSettings(video::Settings& settings) } } -std::string -AVModel::getDeviceIdFromName(const std::string& deviceName) const +QString +AVModel::getDeviceIdFromName(const QString& deviceName) const { auto devices = getDevices(); auto iter = std::find_if(devices.begin(), devices.end(), - [this, deviceName](const std::string& d) { + [this, deviceName](const QString& d) { auto settings = getDeviceSettings(d); return settings.name == deviceName; }); if (iter == devices.end()) { - qWarning() << "Couldn't find device: " << deviceName.c_str(); + qWarning() << "Couldn't find device: " << deviceName; return {}; } return *iter; } -std::vector<std::string> +VectorString AVModel::getSupportedAudioManagers() const { QStringList managers = ConfigurationManager::instance() .getSupportedAudioManagers(); - std::vector<std::string> result; + VectorString result; for (const auto& manager : managers) { - result.emplace_back(manager.toStdString()); + result.push_back(manager); } return result; } -std::string +QString AVModel::getAudioManager() const { - QString manager = ConfigurationManager::instance().getAudioManager(); - return manager.toStdString(); + return ConfigurationManager::instance().getAudioManager(); } -std::vector<std::string> +VectorString AVModel::getAudioOutputDevices() const { QStringList devices = ConfigurationManager::instance() @@ -341,14 +337,14 @@ AVModel::getAudioOutputDevices() const } } - std::vector<std::string> result; + VectorString result; for (const auto& device : devices) { - result.emplace_back(device.toStdString()); + result.push_back(device); } return result; } -std::vector<std::string> +VectorString AVModel::getAudioInputDevices() const { QStringList devices = ConfigurationManager::instance() @@ -362,28 +358,28 @@ AVModel::getAudioInputDevices() const } } - std::vector<std::string> result; + VectorString result; for (const auto& device : devices) { - result.emplace_back(device.toStdString()); + result.push_back(device); } return result; } -std::string +QString AVModel::getRingtoneDevice() const { const int RINGTONE_IDX = 2; return pimpl_->getDevice(RINGTONE_IDX); } -std::string +QString AVModel::getOutputDevice() const { const int OUTPUT_IDX = 0; return pimpl_->getDevice(OUTPUT_IDX); } -std::string +QString AVModel::getInputDevice() const { const int INPUT_IDX = 1; @@ -391,15 +387,15 @@ AVModel::getInputDevice() const } bool -AVModel::isAudioMeterActive(const std::string& id) const +AVModel::isAudioMeterActive(const QString& id) const { - return ConfigurationManager::instance().isAudioMeterActive(id.c_str()); + return ConfigurationManager::instance().isAudioMeterActive(id); } void -AVModel::setAudioMeterState(bool active, const std::string& id) const +AVModel::setAudioMeterState(bool active, const QString& id) const { - ConfigurationManager::instance().setAudioMeterState(id.c_str(), active); + ConfigurationManager::instance().setAudioMeterState(id, active); } void @@ -415,65 +411,61 @@ AVModel::stopAudioDevice() const } bool -AVModel::setAudioManager(const std::string& name) +AVModel::setAudioManager(const QString& name) { - return ConfigurationManager::instance().setAudioManager(name.c_str()); + return ConfigurationManager::instance().setAudioManager(name); } void -AVModel::setRingtoneDevice(const std::string& name) +AVModel::setRingtoneDevice(const QString& name) { - int idx = ConfigurationManager::instance() - .getAudioOutputDeviceIndex(name.c_str()); + int idx = ConfigurationManager::instance().getAudioOutputDeviceIndex(name); ConfigurationManager::instance().setAudioRingtoneDevice(idx); } void -AVModel::setOutputDevice(const std::string& name) +AVModel::setOutputDevice(const QString& name) { - int idx = ConfigurationManager::instance() - .getAudioOutputDeviceIndex(name.c_str()); + int idx = ConfigurationManager::instance().getAudioOutputDeviceIndex(name); ConfigurationManager::instance().setAudioOutputDevice(idx); } void -AVModel::setInputDevice(const std::string& name) +AVModel::setInputDevice(const QString& name) { - int idx = ConfigurationManager::instance() - .getAudioInputDeviceIndex(name.c_str()); + int idx = ConfigurationManager::instance().getAudioInputDeviceIndex(name); ConfigurationManager::instance().setAudioInputDevice(idx); } void -AVModel::stopLocalRecorder(const std::string& path) const +AVModel::stopLocalRecorder(const QString& path) const { - if (path.empty()) { + if (path.isEmpty()) { qWarning("stopLocalRecorder: can't stop non existing recording"); return; } - VideoManager::instance().stopLocalRecorder(QString::fromStdString(path)); + VideoManager::instance().stopLocalRecorder(path); } -std::string +QString AVModel::startLocalRecorder(const bool& audioOnly) const { - const QString path = QString::fromStdString(pimpl_->getRecordingPath()); + const QString path = pimpl_->getRecordingPath(); const QString finalPath = VideoManager::instance().startLocalRecorder(audioOnly, path); - return finalPath.toStdString(); + return finalPath; } -std::string +QString AVModel::getRecordPath() const { - QString path = ConfigurationManager::instance().getRecordPath(); - return path.toStdString(); + return ConfigurationManager::instance().getRecordPath(); } void -AVModel::setRecordPath(const std::string& path) const +AVModel::setRecordPath(const QString& path) const { - ConfigurationManager::instance().setRecordPath(QString::fromStdString(path).toUtf8()); + ConfigurationManager::instance().setRecordPath(path.toUtf8()); } bool @@ -558,38 +550,38 @@ AVModel::stopPreview() } const video::Renderer& -AVModel::getRenderer(const std::string& id) const +AVModel::getRenderer(const QString& id) const { std::lock_guard<std::mutex> lk(pimpl_->renderers_mtx_); auto search = pimpl_->renderers_.find(id); if (search == pimpl_->renderers_.end() || !pimpl_->renderers_[id]) { - throw std::out_of_range("Can't find renderer " + id); + throw std::out_of_range("Can't find renderer " + id.toStdString()); } return *pimpl_->renderers_[id]; } void -AVModel::setInputFile(const std::string& uri, - const std::string& callId) +AVModel::setInputFile(const QString& uri, + const QString& callId) { QString sep = DRing::Media::VideoProtocolPrefix::SEPARATOR; - auto resource = !uri.empty() ? QString("%1%2%3") + auto resource = !uri.isEmpty() ? QString("%1%2%3") .arg(DRing::Media::VideoProtocolPrefix::FILE) .arg(sep) - .arg(QUrl(uri.c_str()).toLocalFile()) + .arg(QUrl(uri).toLocalFile()) : DRing::Media::VideoProtocolPrefix::NONE; - if (callId.empty()) { + if (callId.isEmpty()) { VideoManager::instance().switchInput(resource); } else { CallManager::instance() - .switchInput(QString::fromStdString(callId), resource); + .switchInput(callId, resource); } } void AVModel::setDisplay(int idx, int x, int y, int w, int h, - const std::string& callId) + const QString& callId) { QString sep = DRing::Media::VideoProtocolPrefix::SEPARATOR; auto resource = QString("%1%2:%3+%4,%5 %6x%7") @@ -600,18 +592,18 @@ AVModel::setDisplay(int idx, int x, int y, int w, int h, .arg(y) .arg(w) .arg(h); - if (callId.empty()) { + if (callId.isEmpty()) { VideoManager::instance().switchInput(resource); } else { CallManager::instance() - .switchInput(QString::fromStdString(callId), resource); + .switchInput(callId, resource); } } void -AVModel::switchInputTo(const std::string& id, - const std::string& callId) +AVModel::switchInputTo(const QString& id, + const QString& callId) { QString resource; auto devices = getDevices(); @@ -622,28 +614,28 @@ AVModel::switchInputTo(const std::string& id, resource = QString("%1%2%3") .arg(DRing::Media::VideoProtocolPrefix::CAMERA) .arg(sep) - .arg(id.c_str()); + .arg(id); } else { resource = QString(DRing::Media::VideoProtocolPrefix::NONE); } - if (callId.empty()) { + if (callId.isEmpty()) { VideoManager::instance().switchInput(resource); } else { CallManager::instance() - .switchInput(QString::fromStdString(callId), resource); + .switchInput(callId, resource); } } video::RenderedDevice -AVModel::getCurrentRenderedDevice(const std::string& call_id) const +AVModel::getCurrentRenderedDevice(const QString& call_id) const { video::RenderedDevice result; MapStringString callDetails; QStringList conferences = CallManager::instance().getConferenceList(); - if (conferences.indexOf(call_id.c_str()) != -1) { - callDetails = CallManager::instance().getConferenceDetails(call_id.c_str()); + if (conferences.indexOf(call_id) != -1) { + callDetails = CallManager::instance().getConferenceDetails(call_id); } else { - callDetails = CallManager::instance().getCallDetails(call_id.c_str()); + callDetails = CallManager::instance().getCallDetails(call_id); } if (!callDetails.contains("VIDEO_SOURCE")) { return result; @@ -653,26 +645,26 @@ AVModel::getCurrentRenderedDevice(const std::string& call_id) const if (source.startsWith("camera://")) { result.type = video::DeviceType::CAMERA; result.name = source - .right(sourceSize - std::string("camera://").size()).toStdString(); + .right(sourceSize - QString("camera://").size()); } else if (source.startsWith("file://")) { result.type = video::DeviceType::FILE; result.name = source - .right(sourceSize -std::string("file://").size()).toStdString(); + .right(sourceSize -QString("file://").size()); } else if (source.startsWith("display://")) { result.type = video::DeviceType::DISPLAY; result.name = source - .right(sourceSize - std::string("display://").size()).toStdString(); + .right(sourceSize - QString("display://").size()); } return result; } void -AVModel::setCurrentVideoCaptureDevice(std::string ¤tVideoCaptureDevice) +AVModel::setCurrentVideoCaptureDevice(QString ¤tVideoCaptureDevice) { pimpl_->currentVideoCaptureDevice_ = currentVideoCaptureDevice; } -std::string +QString AVModel::getCurrentVideoCaptureDevice() const { return pimpl_->currentVideoCaptureDevice_; @@ -723,12 +715,12 @@ AVModelPimpl::AVModelPimpl(AVModel& linked, const CallbacksHandler& callbacksHan { MapStringString rendererInfos = VideoManager::instance(). getRenderer(callId); - auto shmPath = rendererInfos[DRing::Media::Details::SHM_PATH].toStdString(); + auto shmPath = rendererInfos[DRing::Media::Details::SHM_PATH]; auto width = rendererInfos[DRing::Media::Details::WIDTH].toInt(); auto height = rendererInfos[DRing::Media::Details::HEIGHT].toInt(); if (width > 0 && height > 0) { startedPreview = true; - startedDecoding(callId.toStdString(), shmPath, width, height); + startedDecoding(callId, shmPath, width, height); } } }; @@ -738,13 +730,13 @@ AVModelPimpl::AVModelPimpl(AVModel& linked, const CallbacksHandler& callbacksHan restartRenderers({"local"}); } -std::string +QString AVModelPimpl::getRecordingPath() const { #if defined(_WIN32) || defined(__APPLE__) - const QDir dir = QString::fromStdString(linked_.getRecordPath()) + "/" + recorderSavesSubdir.c_str(); + const QDir dir = linked_.getRecordPath() + "/" + recorderSavesSubdir; #else - const QDir dir = authority::storage::getPath() + "/" + recorderSavesSubdir.c_str(); + const QDir dir = authority::storage::getPath() + "/" + recorderSavesSubdir; #endif dir.mkpath("."); @@ -762,13 +754,13 @@ AVModelPimpl::getRecordingPath() const QDir file_path(ss.str().c_str()); - return file_path.path().toStdString(); + return file_path.path(); } void -AVModelPimpl::startedDecoding(const std::string& id, const std::string& shmPath, int width, int height) +AVModelPimpl::startedDecoding(const QString& id, const QString& shmPath, int width, int height) { - const std::string res = std::to_string(width) + "x" + std::to_string(height); + const QString res = toQString(width) + "x" + toQString(height); { std::lock_guard<std::mutex> lk(renderers_mtx_); auto search = renderers_.find(id); @@ -777,7 +769,7 @@ AVModelPimpl::startedDecoding(const std::string& id, const std::string& shmPath, video::Settings settings; settings.size = res; renderers_.insert(std::make_pair(id, - std::make_unique<video::Renderer>(id.c_str(), settings, shmPath, useAVFrame_))); + std::make_unique<video::Renderer>(id, settings, shmPath, useAVFrame_))); finishedRenderers_.insert(std::make_pair(id, false)); #ifndef ENABLE_LIBWRAP SIZE_RENDERER = renderers_.size(); @@ -794,24 +786,24 @@ AVModelPimpl::startedDecoding(const std::string& id, const std::string& shmPath, } void -AVModelPimpl::stoppedDecoding(const std::string& id, const std::string& shmPath) +AVModelPimpl::stoppedDecoding(const QString& id, const QString& shmPath) { Q_UNUSED(shmPath) { std::lock_guard<std::mutex> lk(renderers_mtx_); auto search = renderers_.find(id); if (search == renderers_.end()) { - qWarning() << "Cannot stop decoding, renderer " << id.c_str() << "not found"; + qWarning() << "Cannot stop decoding, renderer " << id << "not found"; return; // nothing to do } (*search).second->stopRendering(); - qDebug() << "Video stopped for call" << id.c_str(); + qDebug() << "Video stopped for call" << id; (*search).second->quit(); if (id != video::PREVIEW_RENDERER_ID) { auto searchFinished = finishedRenderers_.find(id); if (searchFinished == finishedRenderers_.end()) { - qWarning() << "Finished flag: " << id.c_str() << " not found"; + qWarning() << "Finished flag: " << id << " not found"; return; // nothing to do } if (searchFinished->second) { @@ -829,7 +821,7 @@ AVModelPimpl::stoppedDecoding(const std::string& id, const std::string& shmPath) } void -AVModelPimpl::slotCallStateChanged(const std::string& id, const std::string &state, int code) +AVModelPimpl::slotCallStateChanged(const QString& id, const QString &state, int code) { Q_UNUSED(code) if (call::to_status(state) != call::Status::ENDED) @@ -839,7 +831,7 @@ AVModelPimpl::slotCallStateChanged(const std::string& id, const std::string &sta auto searchFinished = finishedRenderers_.find(id); if (search == renderers_.end() || searchFinished == finishedRenderers_.end()) { - qWarning() << "Renderer " << id.c_str() << "not found"; + qWarning() << "Renderer " << id << "not found"; return; // nothing to do } if (!(*search).second->isRendering()) { @@ -872,12 +864,12 @@ AVModelPimpl::stopCameraAndQuit(int) #endif -std::string +QString AVModelPimpl::getDevice(int type) const { if (type < 0 || type > 2) return {}; // No device - std::string result = ""; - std::vector<std::string> devices; + QString result = ""; + VectorString devices; switch (type) { case 1: // INPUT devices = linked_.getAudioInputDevices(); @@ -901,11 +893,11 @@ AVModelPimpl::getDevice(int type) const uint32_t idx; switch (type) { case 1: // INPUT - idx = ConfigurationManager::instance().getAudioInputDeviceIndex(dev.c_str()); + idx = ConfigurationManager::instance().getAudioInputDeviceIndex(dev); break; case 0: // OUTPUT case 2: // RINGTONE - idx = ConfigurationManager::instance().getAudioOutputDeviceIndex(dev.c_str()); + idx = ConfigurationManager::instance().getAudioOutputDeviceIndex(dev); break; default: break; @@ -923,7 +915,7 @@ AVModelPimpl::getDevice(int type) const } void -AVModelPimpl::slotFrameUpdated(const std::string& id) +AVModelPimpl::slotFrameUpdated(const QString& id) { emit linked_.frameUpdated(id); } @@ -935,13 +927,13 @@ AVModelPimpl::slotDeviceEvent() } void -AVModelPimpl::slotAudioMeter(const std::string& id, float level) +AVModelPimpl::slotAudioMeter(const QString& id, float level) { emit linked_.audioMeter(id, level); } void -AVModelPimpl::slotRecordPlaybackStopped(const std::string &filePath) +AVModelPimpl::slotRecordPlaybackStopped(const QString &filePath) { emit linked_.recordPlaybackStopped(filePath); } diff --git a/src/behaviorcontroller.cpp b/src/behaviorcontroller.cpp index da76188565ba72f85ed92b74d7cc45876cc1a1b4..3da29ea533593fd36fb3ee5110aded59277fad73 100644 --- a/src/behaviorcontroller.cpp +++ b/src/behaviorcontroller.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * + * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * * Author: Nicolas Jäger <nicolas.jager@savoirfairelinux.com> * * Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com> * * * diff --git a/src/callbackshandler.cpp b/src/callbackshandler.cpp index a12a11cd012b67aba85ce5ed23de47c97b326f84..dbcc80131b5993837f72b8afaaa30e42f09a0cd7 100644 --- a/src/callbackshandler.cpp +++ b/src/callbackshandler.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * + * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * * Author: Nicolas Jäger <nicolas.jager@savoirfairelinux.com> * * Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com> * * * @@ -248,19 +248,10 @@ void CallbacksHandler::slotNewAccountMessage(const QString& accountId, const QString& msgId, const QString& from, - const QMap<QString,QString>& payloads) + const MapStringString& payloads) { - std::map<std::string,std::string> stdPayloads; - - for (auto item : payloads.keys()) { - stdPayloads[item.toStdString()] = payloads.value(item).toStdString(); - } - - auto accountId2 = accountId.toStdString(); - auto from2 = QString(from).replace("@ring.dht", "").toStdString(); - auto msgId2 = QString(msgId).toStdString(); - - emit newAccountMessage(accountId2, msgId2, from2, stdPayloads); + auto from2 = QString(from).replace("@ring.dht", ""); + emit newAccountMessage(accountId, msgId, from2, payloads); } void @@ -272,7 +263,7 @@ CallbacksHandler::slotNewBuddySubscription(const QString& accountId, Q_UNUSED(accountId) Q_UNUSED(status) Q_UNUSED(message) - emit newBuddySubscription(uri.toStdString(), status); + emit newBuddySubscription(uri, status); } void @@ -281,19 +272,19 @@ CallbacksHandler::slotNearbyPeerSubscription(const QString& accountId, int state, const QString& displayname) { - emit newPeerSubscription(accountId.toStdString(), contactUri.toStdString(), state, displayname.toStdString()); + emit newPeerSubscription(accountId, contactUri, state, displayname); } void CallbacksHandler::slotVoiceMailNotify(const QString& accountId, int newCount, int oldCount, int urgentCount) { - emit voiceMailNotify(accountId.toStdString(), newCount, oldCount, urgentCount); + emit voiceMailNotify(accountId, newCount, oldCount, urgentCount); } void CallbacksHandler::slotRecordPlaybackStopped(const QString& filePath) { - emit recordPlaybackStopped(filePath.toStdString()); + emit recordPlaybackStopped(filePath); } void @@ -301,7 +292,7 @@ CallbacksHandler::slotContactAdded(const QString& accountId, const QString& contactUri, bool confirmed) { - emit contactAdded(accountId.toStdString(), contactUri.toStdString(), confirmed); + emit contactAdded(accountId, contactUri, confirmed); } void @@ -309,7 +300,7 @@ CallbacksHandler::slotContactRemoved(const QString& accountId, const QString& contactUri, bool banned) { - emit contactRemoved(accountId.toStdString(), contactUri.toStdString(), banned); + emit contactRemoved(accountId, contactUri, banned); } void @@ -319,49 +310,48 @@ CallbacksHandler::slotIncomingContactRequest(const QString& accountId, time_t time) { Q_UNUSED(time) - emit incomingContactRequest(accountId.toStdString(), ringId.toStdString(), payload.toStdString()); + emit incomingContactRequest(accountId, ringId, payload); } void CallbacksHandler::slotIncomingCall(const QString &accountId, const QString &callId, const QString &fromUri) { - std::string displayname; + QString displayname; + QString fromQString; if (fromUri.contains("ring.dht")) { auto qDisplayname = fromUri.left(fromUri.indexOf("<") + 1); if (qDisplayname.size() > 2) { - displayname = qDisplayname.left(qDisplayname.indexOf("<") - 1).toStdString(); + displayname = qDisplayname.left(qDisplayname.indexOf("<") - 1); } - auto fromQString = fromUri.right(50); + fromQString = fromUri.right(50); fromQString = fromQString.left(40); - emit incomingCall(accountId.toStdString(), callId.toStdString(), fromQString.toStdString(), displayname); } else { auto left = fromUri.indexOf("<") + 1; auto right = fromUri.indexOf("@"); - auto fromQString = fromUri.mid(left, right-left); - displayname = fromUri.left(fromUri.indexOf("<") - 1).toStdString(); - - emit incomingCall(accountId.toStdString(), callId.toStdString(), fromQString.toStdString(), displayname); + fromQString = fromUri.mid(left, right-left); + displayname = fromUri.left(fromUri.indexOf("<") - 1); } + emit incomingCall(accountId, callId, fromQString, displayname); } void CallbacksHandler::slotCallStateChanged(const QString& callId, const QString& state, int code) { - emit callStateChanged(callId.toStdString(), state.toStdString(), code); + emit callStateChanged(callId, state, code); } void CallbacksHandler::slotAccountDetailsChanged(const QString& accountId, const MapStringString& details) { - emit accountDetailsChanged(accountId.toStdString(), convertMap(details)); + emit accountDetailsChanged(accountId, details); } void CallbacksHandler::slotVolatileAccountDetailsChanged(const QString& accountId, const MapStringString& details) { - emit volatileAccountDetailsChanged(accountId.toStdString(), convertMap(details)); + emit volatileAccountDetailsChanged(accountId, details); } void @@ -378,21 +368,21 @@ CallbacksHandler::slotRegistrationStateChanged(const QString& accountId, { (void) detail_code; (void) detail_str; - emit accountStatusChanged(accountId.toStdString(), lrc::api::account::to_status(registration_state.toStdString())); + emit accountStatusChanged(accountId, lrc::api::account::to_status(registration_state)); } void CallbacksHandler::slotIncomingMessage(const QString& callId, const QString& from, - const QMap<QString,QString>& interaction) + const MapStringString& interaction) { - std::string from2; + QString from2; if (from.contains("@ring.dht")) { - from2 = QString(from).replace("@ring.dht", "").toStdString(); + from2 = QString(from).replace("@ring.dht", ""); } else { auto left = from.indexOf(":")+1; auto right = from.indexOf("@"); - from2 = from.mid(left, right-left).toStdString(); + from2 = from.mid(left, right-left); } for (auto& e : interaction.toStdMap()) { @@ -401,13 +391,13 @@ CallbacksHandler::slotIncomingMessage(const QString& callId, auto pieces1 = pieces0[1].split( "," ); auto pieces2 = pieces1[1].split( "=" ); auto pieces3 = pieces1[2].split( "=" ); - emit incomingVCardChunk(callId.toStdString(), + emit incomingVCardChunk(callId, from2, pieces2[1].toInt(), pieces3[1].toInt(), - e.second.toStdString()); + e.second); } else { // we consider it as an usual message interaction - emit incomingCallMessage(callId.toStdString(), from2, e.second.toStdString()); + emit incomingCallMessage(callId, from2, e.second); } } } @@ -415,7 +405,7 @@ CallbacksHandler::slotIncomingMessage(const QString& callId, void CallbacksHandler::slotConferenceCreated(const QString& callId) { - emit conferenceCreated(callId.toStdString()); + emit conferenceCreated(callId); } void @@ -427,7 +417,7 @@ CallbacksHandler::slotConferenceChanged(const QString& callId, const QString& st void CallbacksHandler::slotConferenceRemoved(const QString& callId) { - emit conferenceRemoved(callId.toStdString()); + emit conferenceRemoved(callId); } void @@ -435,8 +425,8 @@ CallbacksHandler::slotAccountMessageStatusChanged(const QString& accountId, const uint64_t id, const QString& to, int status) { - emit accountMessageStatusChanged(accountId.toStdString(), id, - to.toStdString(), status); + emit accountMessageStatusChanged(accountId, id, + to, status); } void @@ -488,13 +478,9 @@ CallbacksHandler::slotDataTransferEvent(qulonglong dringId, uint codeStatus) void CallbacksHandler::slotKnownDevicesChanged(const QString& accountId, - const QMap<QString, QString>& devices) + const MapStringString& devices) { - std::map<std::string, std::string> stdDevices; - for (auto item : devices.keys()) - stdDevices[item.toStdString()] = devices.value(item).toStdString(); - auto accountId2 = accountId.toStdString(); - emit knownDevicesChanged(accountId2, stdDevices); + emit knownDevicesChanged(accountId, devices); } void @@ -502,57 +488,49 @@ CallbacksHandler::slotDeviceRevokationEnded(const QString& accountId, const QString& deviceId, const int status) { - emit deviceRevocationEnded(accountId.toStdString(), deviceId.toStdString(), status); + emit deviceRevocationEnded(accountId, deviceId, status); } void CallbacksHandler::slotExportOnRingEnded(const QString& accountId, int status, const QString& pin) { - emit exportOnRingEnded(accountId.toStdString(), status, pin.toStdString()); + emit exportOnRingEnded(accountId, status, pin); } void CallbacksHandler::slotNameRegistrationEnded(const QString& accountId, int status, const QString& name) { - emit nameRegistrationEnded(accountId.toStdString(), status, name.toStdString()); + emit nameRegistrationEnded(accountId, status, name); } void CallbacksHandler::slotRegisteredNameFound(const QString& accountId, int status, const QString& address, const QString& name) { - emit registeredNameFound(accountId.toStdString(), status, address.toStdString(), name.toStdString()); + emit registeredNameFound(accountId, status, address, name); } void CallbacksHandler::slotMigrationEnded(const QString& accountId, const QString& status) { - emit migrationEnded(accountId.toStdString(), status == "SUCCESS"); + emit migrationEnded(accountId, status == "SUCCESS"); } -#ifdef ENABLE_LIBWRAP -void -CallbacksHandler::slotDebugMessageReceived(const std::string& message) -{ - emit parent.getBehaviorController().debugMessageReceived(message); -} -#else void CallbacksHandler::slotDebugMessageReceived(const QString& message) { - emit parent.getBehaviorController().debugMessageReceived(message.toStdString()); + emit parent.getBehaviorController().debugMessageReceived(message); } -#endif void CallbacksHandler::slotStartedDecoding(const QString& id, const QString& shmPath, int width, int height) { - emit startedDecoding(id.toStdString(), shmPath.toStdString(), width, height); + emit startedDecoding(id, shmPath, width, height); } void CallbacksHandler::slotStoppedDecoding(const QString& id, const QString& shmPath) { - emit stoppedDecoding(id.toStdString(), shmPath.toStdString()); + emit stoppedDecoding(id, shmPath); } void @@ -564,7 +542,7 @@ CallbacksHandler::slotDeviceEvent() void CallbacksHandler::slotAudioMeterReceived(const QString& id, float level) { - emit audioMeter(id.toStdString(), level); + emit audioMeter(id, level); } } // namespace lrc diff --git a/src/callbackshandler.h b/src/callbackshandler.h index 9b724d76d94ad453c54e87f52711e65158b73dc6..13bac0d288dfdc8083717fe05e4b50731f83bfbb 100644 --- a/src/callbackshandler.h +++ b/src/callbackshandler.h @@ -18,19 +18,14 @@ ***************************************************************************/ #pragma once -// Std -#include <memory> -#include <string> -#include <map> - -// Qt -#include <qobject.h> - -// Lrc #include "typedefs.h" #include "api/datatransfer.h" #include "qtwrapper/conversions_wrap.hpp" +#include <QObject> + +#include <memory> + namespace lrc { @@ -63,43 +58,43 @@ Q_SIGNALS: * @param from interaction sender. * @param payloads. */ - void newAccountMessage(std::string& accountId, - std::string& msgId, - std::string& from, - std::map<std::string,std::string> payloads); + void newAccountMessage(const QString& accountId, + const QString& msgId, + const QString& from, + const MapStringString& payloads); /** * Connect this signal to get information when a peer is online. * @param contactUri the peer. * @param present if the peer is online. */ - void newBuddySubscription(const std::string& contactUri, bool present); + void newBuddySubscription(const QString& contactUri, bool present); /** * Connect this signal to get information when peer discovery changes. * @param contactUri the peer. * @param state is 0 if the peer is added. */ - void newPeerSubscription(const std::string& accountId, const std::string& contactUri, int state, const std::string& displayname); + void newPeerSubscription(const QString& accountId, const QString& contactUri, int state, const QString& displayname); /** * Connect this signal to know when a contact is removed by the daemon. * @param accountId the one who lost a contact. * @param contactUri the contact removed. * @param banned if the contact was banned */ - void contactRemoved(const std::string& accountId, const std::string& contactUri, bool banned); + void contactRemoved(const QString& accountId, const QString& contactUri, bool banned); /** * Connect this signal to know when a contact is added by the daemon. * @param accountId the one who got a new contact. * @param contactUri the new contact. * @param confirmed if the contact is trusted. */ - void contactAdded(const std::string& accountId, const std::string& contactUri, bool confirmed); + void contactAdded(const QString& accountId, const QString& contactUri, bool confirmed); /** * Connect this signal to know when an incoming request is added by the daemon * @param accountId the one who got the request * @param ringId the peer contact * @param payload the VCard */ - void incomingContactRequest(const std::string& accountId, const std::string& ringId, const std::string& payload); + void incomingContactRequest(const QString& accountId, const QString& ringId, const QString& payload); /** * Connect this signal to know when a call arrives * @param accountId the one who receives the call @@ -107,31 +102,31 @@ Q_SIGNALS: * @param fromUri the caller uri * @param displayName the display name of incoming call */ - void incomingCall(const std::string& accountId, - const std::string& callId, - const std::string& fromUri, - const std::string& displayName); + void incomingCall(const QString& accountId, + const QString& callId, + const QString& fromUri, + const QString& displayName); /** * Connect this signal to know when a call is updated * @param callId the call id * @param state the new state * @param code */ - void callStateChanged(const std::string& callId, const std::string &state, int code); + void callStateChanged(const QString& callId, const QString& state, int code); /** * Connect this signal to know when the account details have changed * @param accountId the one who changes * @param details the new details */ - void accountDetailsChanged(const std::string& accountId, - const std::map<std::string,std::string>& details); + void accountDetailsChanged(const QString& accountId, + const MapStringString& details); /** * Connect this signal to know when the volatile account details have changed * @param accountId the one who changes * @param details the new details */ - void volatileAccountDetailsChanged(const std::string& accountId, - const std::map<std::string,std::string>& details); + void volatileAccountDetailsChanged(const QString& accountId, + const MapStringString& details); /** * Connect this signal to know when the accounts list changed */ @@ -141,7 +136,7 @@ Q_SIGNALS: * @param accountId the one who changes * @param status the new status */ - void accountStatusChanged(const std::string& accountId, const api::account::Status status); + void accountStatusChanged(const QString& accountId, const api::account::Status status); /** * Connect this signal to know where a VCard is incoming * @param callId the call linked to this VCard @@ -150,31 +145,30 @@ Q_SIGNALS: * @param numberOfParts of the VCard * @param payload content of the VCard */ - void incomingVCardChunk(const std::string& callId, - const std::string& from, + void incomingVCardChunk(const QString& callId, + const QString& from, int part, int numberOfParts, - const std::string& payload); + const QString& payload); /** * Connect this signal to get incoming text interaction from SIP. * @param callId the call linked. * @param from interaction sender. * @param body the text received. */ - void incomingCallMessage(const std::string& callId, - const std::string& from, - - const std::string& body) const; + void incomingCallMessage(const QString& callId, + const QString& from, + const QString& body) const; /** * Connect this signal to know when a new conference is created * @param callId of the conference */ - void conferenceCreated(const std::string& callId); + void conferenceCreated(const QString& callId); /** * Connect this signal to know when a conference is removed * @param callId of the conference */ - void conferenceRemoved(const std::string& callId); + void conferenceRemoved(const QString& callId); /** * Connect this signal to know when a message sent get a new status * @param accountId, account linked @@ -182,9 +176,9 @@ Q_SIGNALS: * @param to, peer uri * @param status, new status for this message */ - void accountMessageStatusChanged(const std::string& accountId, + void accountMessageStatusChanged(const QString& accountId, const uint64_t id, - const std::string& to, int status); + const QString& to, int status); void transferStatusCreated(long long dringId, api::datatransfer::Info info); void transferStatusCanceled(long long dringId, api::datatransfer::Info info); @@ -201,8 +195,8 @@ Q_SIGNALS: * @param accountId interaction receiver. * @param devices A map of device IDs with corresponding labels. */ - void knownDevicesChanged(std::string& accountId, - std::map<std::string,std::string> devices); + void knownDevicesChanged(const QString& accountId, + const MapStringString& devices); /** * Emit deviceRevocationEnded @@ -210,8 +204,8 @@ Q_SIGNALS: * @param deviceId * @param status SUCCESS = 0, WRONG_PASSWORD = 1, UNKNOWN_DEVICE = 2 */ - void deviceRevocationEnded(const std::string& accountId, - const std::string& deviceId, + void deviceRevocationEnded(const QString& accountId, + const QString& deviceId, const int status); /** @@ -220,7 +214,7 @@ Q_SIGNALS: * @param status SUCCESS = 0, WRONG_PASSWORD = 1, NETWORK_ERROR = 2 * @param pin */ - void exportOnRingEnded(const std::string& accountId, int status, const std::string& pin); + void exportOnRingEnded(const QString& accountId, int status, const QString& pin); /** * Name registration has ended @@ -228,7 +222,7 @@ Q_SIGNALS: * @param status * @param name */ - void nameRegistrationEnded(const std::string& accountId, int status, const std::string& name); + void nameRegistrationEnded(const QString& accountId, int status, const QString& name); /** * Name registration has been found @@ -236,20 +230,20 @@ Q_SIGNALS: * @param status * @param name */ - void registeredNameFound(const std::string& accountId, int status, const std::string& address, const std::string& name); + void registeredNameFound(const QString& accountId, int status, const QString& address, const QString& name); /** * Migration ended * @param accountId * @param ok if migration succeed */ - void migrationEnded(const std::string& accountId, bool ok); + void migrationEnded(const QString& accountId, bool ok); /** * Debug message received * @param message */ - void debugMessageReceived(const std::string& message); + void debugMessageReceived(const QString& message); /** * Renderer is started @@ -258,14 +252,14 @@ Q_SIGNALS: * @param width * @param height */ - void startedDecoding(const std::string& id, const std::string& shmPath, int width, int height); + void startedDecoding(const QString& id, const QString& shmPath, int width, int height); /** * Renderer is stopped * @param id * @param shmrenderer */ - void stoppedDecoding(const std::string& id, const std::string& shmPath); + void stoppedDecoding(const QString& id, const QString& shmPath); /** * Emitted when a device is plugged or unplugged @@ -277,13 +271,13 @@ Q_SIGNALS: * @param id of the ringbuffer level * @param level */ - void audioMeter(const std::string& id, float level); + void audioMeter(const QString& id, float level); /** * Emitted when an local recorder is finished * @param filePath */ - void recordPlaybackStopped(const std::string& filePath); + void recordPlaybackStopped(const QString& filePath); /** * Emitted when an audio level is received @@ -292,7 +286,7 @@ Q_SIGNALS: * @param oldCount * @param urgentCount */ - void voiceMailNotify(const std::string& accountId, int newCount, int oldCount, int urgentCount); + void voiceMailNotify(const QString& accountId, int newCount, int oldCount, int urgentCount); private Q_SLOTS: /** @@ -430,7 +424,7 @@ private Q_SLOTS: * @param devices A map of device IDs and corresponding labels */ void slotKnownDevicesChanged(const QString& accountId, - const QMap<QString, QString>& devices); + const MapStringString& devices); /** * Emit deviceRevocationEnded @@ -477,11 +471,7 @@ private Q_SLOTS: * emit debugMessageReceived * @param message */ -#ifdef ENABLE_LIBWRAP - void slotDebugMessageReceived(const std::string& message); -#else void slotDebugMessageReceived(const QString& message); -#endif /** * Renderer is started diff --git a/src/contactmodel.cpp b/src/contactmodel.cpp index 0e9bb5c846bbb1b08368c6e044a800ec33e553bf..59b4e5eb50e22bfa53404027ff9a46295398f6f8 100644 --- a/src/contactmodel.cpp +++ b/src/contactmodel.cpp @@ -85,7 +85,7 @@ public: * @param displayName * @param banned whether contact is banned or not */ - void addToContacts(const std::string& contactId, const profile::Type& type, const std::string& displayName = "", bool banned = false); + void addToContacts(const QString& contactId, const profile::Type& type, const QString& displayName = "", bool banned = false); /** * Helpers for searchContact. Search for a given RING or SIP contact. */ @@ -94,12 +94,12 @@ public: /** * Update temporary item to display a given message about a given uri. */ - void updateTemporaryMessage(const std::string& mes, const std::string& uri); + void updateTemporaryMessage(const QString& mes, const QString& uri); /** * Check if equivalent uri exist in contact */ - std::string sipUriReceivedFilter(const std::string& uri); + QString sipUriReceivedFilter(const QString& uri); // Helpers const BehaviorController& behaviorController; @@ -109,7 +109,7 @@ public: // Containers ContactModel::ContactInfoMap contacts; - std::list<std::string> bannedContacts; + QList<QString> bannedContacts; std::mutex contactsMtx_; std::mutex bannedContactsMtx_; @@ -119,7 +119,7 @@ public Q_SLOTS: * @param contactUri * @param status */ - void slotNewBuddySubscription(const std::string& uri, bool status); + void slotNewBuddySubscription(const QString& uri, bool status); /** * Listen CallbacksHandler when a contact is added @@ -127,7 +127,7 @@ public Q_SLOTS: * @param contactUri * @param confirmed */ - void slotContactAdded(const std::string& accountId, const std::string& contactUri, bool confirmed); + void slotContactAdded(const QString& accountId, const QString& contactUri, bool confirmed); /** * Listen CallbacksHandler when a contact is removed @@ -135,7 +135,7 @@ public Q_SLOTS: * @param contactUri * @param banned */ - void slotContactRemoved(const std::string& accountId, const std::string& contactUri, bool banned); + void slotContactRemoved(const QString& accountId, const QString& contactUri, bool banned); /** * Listen CallbacksHandler when a registeredName is found @@ -144,7 +144,7 @@ public Q_SLOTS: * @param uri of the contact found * @param registeredName of the contact found */ - void slotRegisteredNameFound(const std::string& accountId, int status, const std::string& uri, const std::string& registeredName); + void slotRegisteredNameFound(const QString& accountId, int status, const QString& uri, const QString& registeredName); /** * Listen CallbacksHandler when an incoming request arrives @@ -152,16 +152,16 @@ public Q_SLOTS: * @param contactUri * @param payload VCard of the contact */ - void slotIncomingContactRequest(const std::string& accountId, - const std::string& contactUri, - const std::string& payload); + void slotIncomingContactRequest(const QString& accountId, + const QString& contactUri, + const QString& payload); /** * Listen from callModel when an incoming call arrives. * @param fromId * @param callId * @param displayName */ - void slotIncomingCall(const std::string& fromId, const std::string& callId, const std::string& displayname); + void slotIncomingCall(const QString& fromId, const QString& callId, const QString& displayname); /** * Listen from callbacksHandler for new account interaction and add pending contact if not present @@ -170,10 +170,10 @@ public Q_SLOTS: * @param from * @param payloads */ - void slotNewAccountMessage(std::string& accountId, - std::string& msgId, - std::string& from, - std::map<std::string,std::string> payloads); + void slotNewAccountMessage(const QString& accountId, + const QString& msgId, + const QString& from, + const MapStringString& payloads); /** * Listen from callbacksHandler to know when a file transfer interaction is incoming @@ -218,8 +218,8 @@ ContactModel::pendingRequestCount() const int pendingRequestCount = 0; std::for_each(pimpl_->contacts.begin(), pimpl_->contacts.end(), [&pendingRequestCount] (const auto& c) { - if (!c.second.isBanned) - pendingRequestCount += static_cast<int>(c.second.profileInfo.type == profile::Type::PENDING); + if (!c.isBanned) + pendingRequestCount += static_cast<int>(c.profileInfo.type == profile::Type::PENDING); }); return pendingRequestCount; } @@ -232,8 +232,8 @@ ContactModel::addContact(contact::Info contactInfo) // If passed contact is a banned contact, call the daemon to unban it auto it = std::find(pimpl_->bannedContacts.begin(), pimpl_->bannedContacts.end(), profile.uri); if (it != pimpl_->bannedContacts.end()) { - qDebug("Unban-ing contact %s", profile.uri.c_str()); - ConfigurationManager::instance().addContact(owner.id.c_str(), profile.uri.c_str()); + qDebug() << QString("Unban-ing contact %s").arg(profile.uri); + ConfigurationManager::instance().addContact(owner.id, profile.uri); // bannedContacts will be updated in slotContactAdded return; } @@ -245,7 +245,7 @@ ContactModel::addContact(contact::Info contactInfo) } MapStringString details = ConfigurationManager::instance().getContactDetails( - owner.id.c_str(), contactInfo.profileInfo.uri.c_str()); + owner.id, contactInfo.profileInfo.uri); // if contactInfo is already a contact for the daemon, type should be equals to RING // if the user add a temporary item for a SIP account, should be directly transformed @@ -254,11 +254,11 @@ ContactModel::addContact(contact::Info contactInfo) && owner.profileInfo.type == profile::Type::SIP)) profile.type = owner.profileInfo.type; - QByteArray vCard = owner.accountModel->accountVCard(owner.id).c_str(); + QByteArray vCard = owner.accountModel->accountVCard(owner.id).toUtf8(); switch (profile.type) { case profile::Type::TEMPORARY: - ConfigurationManager::instance().addContact(owner.id.c_str(), profile.uri.c_str()); - ConfigurationManager::instance().sendTrustRequest(owner.id.c_str(), profile.uri.c_str(), vCard); + ConfigurationManager::instance().addContact(owner.id, profile.uri); + ConfigurationManager::instance().sendTrustRequest(owner.id, profile.uri, vCard); break; case profile::Type::PENDING: if (daemon::addContactFromPending(owner, profile.uri)) { @@ -283,13 +283,13 @@ ContactModel::addContact(contact::Info contactInfo) std::lock_guard<std::mutex> lk(pimpl_->contactsMtx_); auto iter = pimpl_->contacts.find(contactInfo.profileInfo.uri); if (iter == pimpl_->contacts.end()) - pimpl_->contacts.emplace_hint(iter, contactInfo.profileInfo.uri, contactInfo); + pimpl_->contacts.insert(iter, contactInfo.profileInfo.uri, contactInfo); else { // On non-DBus platform, contactInfo.profileInfo.type may be wrong as the contact // may be trusted already. We must use Profile::Type from pimpl_->contacts // and not from contactInfo so we cannot revert a contact back to PENDING. - contactInfo.profileInfo.type = iter->second.profileInfo.type; - iter->second.profileInfo = contactInfo.profileInfo; + contactInfo.profileInfo.type = iter->profileInfo.type; + iter->profileInfo = contactInfo.profileInfo; } } if (profile.type == profile::Type::TEMPORARY) @@ -298,26 +298,26 @@ ContactModel::addContact(contact::Info contactInfo) } void -ContactModel::removeContact(const std::string& contactUri, bool banned) +ContactModel::removeContact(const QString& contactUri, bool banned) { bool emitContactRemoved = false; { std::lock_guard<std::mutex> lk(pimpl_->contactsMtx_); auto contact = pimpl_->contacts.find(contactUri); if (!banned && contact != pimpl_->contacts.end() - && contact->second.profileInfo.type == profile::Type::PENDING) { + && contact->profileInfo.type == profile::Type::PENDING) { // Discard the pending request and remove profile from db if necessary if(!daemon::discardFromPending(owner, contactUri)) { - qDebug() << "Discard request for account " << owner.id.c_str() << " failed (" << contactUri.c_str() << ")"; + qDebug() << "Discard request for account " << owner.id << " failed (" << contactUri << ")"; return; } - pimpl_->contacts.erase(contactUri); + pimpl_->contacts.remove(contactUri); storage::removeContact(pimpl_->db, contactUri); emitContactRemoved = true; } else if (owner.profileInfo.type == profile::Type::SIP) { // Remove contact from db - pimpl_->contacts.erase(contactUri); + pimpl_->contacts.remove(contactUri); storage::removeContact(pimpl_->db, contactUri); emitContactRemoved = true; } @@ -337,25 +337,28 @@ ContactModel::removeContact(const std::string& contactUri, bool banned) } const contact::Info -ContactModel::getContact(const std::string& contactUri) const +ContactModel::getContact(const QString& contactUri) const { std::lock_guard<std::mutex> lk(pimpl_->contactsMtx_); - return pimpl_->contacts.at(contactUri); + if (!pimpl_->contacts.contains(contactUri)) { + throw std::out_of_range("Contact out of range"); + } + return pimpl_->contacts.value(contactUri); } -const std::list<std::string>& +const QList<QString>& ContactModel::getBannedContacts() const { return pimpl_->bannedContacts; } void -ContactModel::searchContact(const std::string& query) +ContactModel::searchContact(const QString& query) { // always reset temporary contact pimpl_->contacts[""] = {}; - auto uri = URI(QString(query.c_str())); + auto uri = URI(query); auto uriScheme = uri.schemeType(); if (uri.schemeType() == URI::SchemeType::NONE) { @@ -372,12 +375,12 @@ ContactModel::searchContact(const std::string& query) } else if (uriScheme == URI::SchemeType::RING && owner.profileInfo.type == profile::Type::RING) { pimpl_->searchRingContact(uri); } else { - pimpl_->updateTemporaryMessage(tr("Bad URI scheme").toStdString(), uri.full().toStdString()); + pimpl_->updateTemporaryMessage(tr("Bad URI scheme"), uri.full()); } } void -ContactModelPimpl::updateTemporaryMessage(const std::string& mes, const std::string& uri) +ContactModelPimpl::updateTemporaryMessage(const QString& mes, const QString& uri) { std::lock_guard<std::mutex> lk(contactsMtx_); auto& temporaryContact = contacts[""]; @@ -389,7 +392,7 @@ ContactModelPimpl::updateTemporaryMessage(const std::string& mes, const std::str void ContactModelPimpl::searchRingContact(const URI& query) { - std::string uriID = query.format(URI::Section::USER_INFO | URI::Section::HOSTNAME | URI::Section::PORT).toStdString(); + QString uriID = query.format(URI::Section::USER_INFO | URI::Section::HOSTNAME | URI::Section::PORT); if (query.isEmpty()) { // This will remove the temporary item emit linked.modelUpdated(uriID); @@ -399,7 +402,7 @@ ContactModelPimpl::searchRingContact(const URI& query) if (query.protocolHint() == URI::ProtocolHint::RING) { // no lookup, this is a ring infoHash for (auto &i : contacts) { - if (i.second.profileInfo.uri == uriID) { + if (i.profileInfo.uri == uriID) { return; } } @@ -408,10 +411,10 @@ ContactModelPimpl::searchRingContact(const URI& query) temporaryContact.profileInfo.alias = uriID; temporaryContact.profileInfo.type = profile::Type::TEMPORARY; } else { - updateTemporaryMessage(tr("Searching…").toStdString(), uriID); + updateTemporaryMessage(tr("Searching…"), uriID); // Default searching - ConfigurationManager::instance().lookupName(QString::fromStdString(linked.owner.id), "", QString::fromStdString(uriID)); + ConfigurationManager::instance().lookupName(linked.owner.id, "", uriID); } emit linked.modelUpdated(uriID); } @@ -419,7 +422,7 @@ ContactModelPimpl::searchRingContact(const URI& query) void ContactModelPimpl::searchSipContact(const URI& query) { - std::string uriID = query.format(URI::Section::USER_INFO | URI::Section::HOSTNAME | URI::Section::PORT).toStdString(); + QString uriID = query.format(URI::Section::USER_INFO | URI::Section::HOSTNAME | URI::Section::PORT); if (query.isEmpty()) { // This will remove the temporary item emit linked.modelUpdated(uriID); @@ -439,13 +442,13 @@ ContactModelPimpl::searchSipContact(const URI& query) } uint64_t -ContactModel::sendDhtMessage(const std::string& contactUri, const std::string& body) const +ContactModel::sendDhtMessage(const QString& contactUri, const QString& body) const { // Send interaction QMap<QString, QString> payloads; - payloads["text/plain"] = body.c_str(); - auto msgId = ConfigurationManager::instance().sendTextMessage(QString(owner.id.c_str()), - QString(contactUri.c_str()), + payloads["text/plain"] = body; + auto msgId = ConfigurationManager::instance().sendTextMessage(QString(owner.id), + QString(contactUri), payloads); // NOTE: ConversationModel should store the interaction into the database return msgId; @@ -518,7 +521,7 @@ ContactModelPimpl::fillWithSIPContacts() profile::Type::SIP); { std::lock_guard<std::mutex> lk(contactsMtx_); - contacts.emplace(contactInfo.profileInfo.uri, contactInfo); + contacts.insert(contactInfo.profileInfo.uri, contactInfo); } } } @@ -530,24 +533,22 @@ bool ContactModelPimpl::fillWithJamiContacts() { // Add contacts from daemon - const VectorMapStringString& contacts_vector = ConfigurationManager::instance().getContacts(linked.owner.id.c_str()); + const VectorMapStringString& contacts_vector = ConfigurationManager::instance().getContacts(linked.owner.id); for (auto contact_info : contacts_vector) { std::lock_guard<std::mutex> lk(contactsMtx_); bool banned = contact_info["banned"] == "true" ? true : false; - addToContacts(contact_info["id"].toStdString(), linked.owner.profileInfo.type, "", banned); + addToContacts(contact_info["id"], linked.owner.profileInfo.type, "", banned); } // Add pending contacts - const VectorMapStringString& pending_tr {ConfigurationManager::instance().getTrustRequests(linked.owner.id.c_str())}; + const VectorMapStringString& pending_tr {ConfigurationManager::instance().getTrustRequests(linked.owner.id)}; for (const auto& tr_info : pending_tr) { // Get pending requests. auto payload = tr_info[DRing::Account::TrustRequest::PAYLOAD].toUtf8(); auto contactUri = tr_info[DRing::Account::TrustRequest::FROM]; - auto contactInfo = storage::buildContactFromProfile(linked.owner.id, - contactUri.toStdString(), - profile::Type::PENDING); + auto contactInfo = storage::buildContactFromProfile(linked.owner.id, contactUri, profile::Type::PENDING); const auto vCard = lrc::vCard::utils::toHashMap(payload); const auto alias = vCard["FN"]; @@ -563,7 +564,7 @@ ContactModelPimpl::fillWithJamiContacts() { { std::lock_guard<std::mutex> lk(contactsMtx_); - contacts.emplace(contactUri.toStdString(), contactInfo); + contacts.insert(contactUri, contactInfo); } // create profile vcard for contact @@ -573,21 +574,21 @@ ContactModelPimpl::fillWithJamiContacts() { // Update presence // TODO fix this map. This is dumb for now. The map contains values as keys, and empty values. const VectorMapStringString& subscriptions { - PresenceManager::instance().getSubscriptions(linked.owner.id.c_str()) + PresenceManager::instance().getSubscriptions(linked.owner.id) }; for (const auto& subscription : subscriptions) { auto first = true; - std::string uri = ""; + QString uri = ""; for (const auto& key : subscription) { if (first) { first = false; - uri = key.toStdString(); + uri = key; } else { { std::lock_guard<std::mutex> lk(contactsMtx_); auto it = contacts.find(uri); if (it != contacts.end()) { - it->second.isPresent = key == "Online"; + it->isPresent = key == "Online"; linked.modelUpdated(uri, false); } } @@ -599,13 +600,13 @@ ContactModelPimpl::fillWithJamiContacts() { } void -ContactModelPimpl::slotNewBuddySubscription(const std::string& contactUri, bool status) +ContactModelPimpl::slotNewBuddySubscription(const QString& contactUri, bool status) { { std::lock_guard<std::mutex> lk(contactsMtx_); auto it = contacts.find(contactUri); if (it != contacts.end()) { - it->second.isPresent = status; + it->isPresent = status; } else return; } @@ -613,13 +614,13 @@ ContactModelPimpl::slotNewBuddySubscription(const std::string& contactUri, bool } void -ContactModelPimpl::slotContactAdded(const std::string& accountId, const std::string& contactUri, bool confirmed) +ContactModelPimpl::slotContactAdded(const QString& accountId, const QString& contactUri, bool confirmed) { Q_UNUSED(confirmed) if (accountId != linked.owner.id) return; auto contact = contacts.find(contactUri); - if (contact->second.profileInfo.type == profile::Type::PENDING) { + if (contact->profileInfo.type == profile::Type::PENDING) { emit behaviorController.trustRequestTreated(linked.owner.id, contactUri); } @@ -632,7 +633,7 @@ ContactModelPimpl::slotContactAdded(const std::string& accountId, const std::str { // Check whether contact is banned or not std::lock_guard<std::mutex> lk(bannedContactsMtx_); - auto it = std::find(bannedContacts.begin(), bannedContacts.end(), contact->second.profileInfo.uri); + auto it = std::find(bannedContacts.begin(), bannedContacts.end(), contact->profileInfo.uri); isBanned = (it != bannedContacts.end()); @@ -655,7 +656,7 @@ ContactModelPimpl::slotContactAdded(const std::string& accountId, const std::str } void -ContactModelPimpl::slotContactRemoved(const std::string& accountId, const std::string& contactUri, bool banned) +ContactModelPimpl::slotContactRemoved(const QString& accountId, const QString& contactUri, bool banned) { if (accountId != linked.owner.id) return; @@ -667,22 +668,22 @@ ContactModelPimpl::slotContactRemoved(const std::string& accountId, const std::s auto contact = contacts.find(contactUri); if (contact == contacts.end()) return; - if (contact->second.profileInfo.type == profile::Type::PENDING) { + if (contact->profileInfo.type == profile::Type::PENDING) { emit behaviorController.trustRequestTreated(linked.owner.id, contactUri); } - if (contact->second.profileInfo.type != profile::Type::SIP) - PresenceManager::instance().subscribeBuddy(linked.owner.id.c_str(), contactUri.c_str(), false); + if (contact->profileInfo.type != profile::Type::SIP) + PresenceManager::instance().subscribeBuddy(linked.owner.id, contactUri, false); if (banned) { - contact->second.isBanned = true; + contact->isBanned = true; // Update bannedContacts index - bannedContacts.emplace_back(contact->second.profileInfo.uri); + bannedContacts.append(contact->profileInfo.uri); } else { - if (contact->second.isBanned) { + if (contact->isBanned) { // Contact was banned, update bannedContacts std::lock_guard<std::mutex> lk(bannedContactsMtx_); - auto it = std::find(bannedContacts.begin(), bannedContacts.end(), contact->second.profileInfo.uri); + auto it = std::find(bannedContacts.begin(), bannedContacts.end(), contact->profileInfo.uri); if (it == bannedContacts.end()) { // should not happen qDebug("ContactModel::slotContactsRemoved(): Contact is banned but not present in bannedContacts. This is most likely the result of an earlier bug."); @@ -691,7 +692,7 @@ ContactModelPimpl::slotContactRemoved(const std::string& accountId, const std::s } } storage::removeContact(db, contactUri); - contacts.erase(contactUri); + contacts.remove(contactUri); } } @@ -705,7 +706,7 @@ ContactModelPimpl::slotContactRemoved(const std::string& accountId, const std::s } void -ContactModelPimpl::addToContacts(const std::string& contactUri, const profile::Type& type, const std::string& displayName, bool banned) +ContactModelPimpl::addToContacts(const QString& contactUri, const profile::Type& type, const QString& displayName, bool banned) { // create a vcard if necessary profile::Info profileInfo{ contactUri, displayName, {}, linked.owner.profileInfo.type }; @@ -716,9 +717,8 @@ ContactModelPimpl::addToContacts(const std::string& contactUri, const profile::T // lookup address in case of RING contact if (type == profile::Type::RING) { - ConfigurationManager::instance().lookupAddress(QString::fromStdString(linked.owner.id), - "", QString::fromStdString(contactUri)); - PresenceManager::instance().subscribeBuddy(linked.owner.id.c_str(), contactUri.c_str(), !banned); + ConfigurationManager::instance().lookupAddress(linked.owner.id, "", contactUri); + PresenceManager::instance().subscribeBuddy(linked.owner.id, contactUri, !banned); } else { contactInfo.profileInfo.alias = displayName; } @@ -726,22 +726,22 @@ ContactModelPimpl::addToContacts(const std::string& contactUri, const profile::T contactInfo.profileInfo.type = type; // Because PENDING should not be stored in the database auto iter = contacts.find(contactInfo.profileInfo.uri); if (iter != contacts.end()) { - auto info = iter->second; + auto info = iter.value(); contactInfo.registeredName = info.registeredName; - iter->second = contactInfo; + iter.value() = contactInfo; } else - contacts.emplace_hint(iter, contactInfo.profileInfo.uri, contactInfo); + contacts.insert(iter, contactInfo.profileInfo.uri, contactInfo); if (banned) { - bannedContacts.emplace_back(contactUri); + bannedContacts.append(contactUri); } } void -ContactModelPimpl::slotRegisteredNameFound(const std::string& accountId, +ContactModelPimpl::slotRegisteredNameFound(const QString& accountId, int status, - const std::string& uri, - const std::string& registeredName) + const QString& uri, + const QString& registeredName) { if (accountId != linked.owner.id) return; @@ -771,13 +771,13 @@ ContactModelPimpl::slotRegisteredNameFound(const std::string& accountId, switch (status) { case 1 /* INVALID */: - updateTemporaryMessage(tr("Invalid ID").toStdString(), registeredName); + updateTemporaryMessage(tr("Invalid ID"), registeredName); break; case 2 /* NOT FOUND */: - updateTemporaryMessage(tr("Registered name not found").toStdString(), registeredName); + updateTemporaryMessage(tr("Registered name not found"), registeredName); break; case 3 /* ERROR */: - updateTemporaryMessage(tr("Couldn't lookup…").toStdString(), registeredName); + updateTemporaryMessage(tr("Couldn't lookup…"), registeredName); break; } } @@ -786,9 +786,9 @@ ContactModelPimpl::slotRegisteredNameFound(const std::string& accountId, } void -ContactModelPimpl::slotIncomingContactRequest(const std::string& accountId, - const std::string& contactUri, - const std::string& payload) +ContactModelPimpl::slotIncomingContactRequest(const QString& accountId, + const QString& contactUri, + const QString& payload) { if (linked.owner.id != accountId) return; @@ -797,14 +797,14 @@ ContactModelPimpl::slotIncomingContactRequest(const std::string& accountId, { std::lock_guard<std::mutex> lk(contactsMtx_); if (contacts.find(contactUri) == contacts.end()) { - const auto vCard = lrc::vCard::utils::toHashMap(payload.c_str()); + const auto vCard = lrc::vCard::utils::toHashMap(payload.toUtf8()); const auto alias = vCard["FN"]; const auto photo = (vCard.find("PHOTO;ENCODING=BASE64;TYPE=PNG") == vCard.end()) ? vCard["PHOTO;ENCODING=BASE64;TYPE=JPEG"] : vCard["PHOTO;ENCODING=BASE64;TYPE=PNG"]; - auto profileInfo = profile::Info {contactUri, photo.toStdString(), alias.toStdString(), profile::Type::PENDING}; + auto profileInfo = profile::Info {contactUri, photo, alias, profile::Type::PENDING}; auto contactInfo = contact::Info {profileInfo, "", false, false, false}; - contacts.emplace(contactUri, contactInfo); + contacts.insert(contactUri, contactInfo); emitTrust = true; storage::createOrUpdateProfile(accountId, profileInfo, true); } @@ -817,7 +817,7 @@ ContactModelPimpl::slotIncomingContactRequest(const std::string& accountId, } void -ContactModelPimpl::slotIncomingCall(const std::string& fromId, const std::string& callId, const std::string& displayname) +ContactModelPimpl::slotIncomingCall(const QString& fromId, const QString& callId, const QString& displayname) { bool emitContactAdded = false; { @@ -831,9 +831,9 @@ ContactModelPimpl::slotIncomingCall(const std::string& fromId, const std::string emitContactAdded = true; } else { // Update the display name - if (!displayname.empty()) { - it->second.profileInfo.alias = displayname; - storage::createOrUpdateProfile(linked.owner.id, it->second.profileInfo, true); + if (!displayname.isEmpty()) { + it->profileInfo.alias = displayname; + storage::createOrUpdateProfile(linked.owner.id, it->profileInfo, true); } } } @@ -848,12 +848,15 @@ ContactModelPimpl::slotIncomingCall(const std::string& fromId, const std::string } void -ContactModelPimpl::slotNewAccountMessage(std::string& accountId, - std::string& msgId, - std::string& from, - std::map<std::string,std::string> payloads) +ContactModelPimpl::slotNewAccountMessage(const QString& accountId, + const QString& msgId, + const QString& from, + const MapStringString& payloads) { - if (accountId != linked.owner.id) return; + if (accountId != linked.owner.id) + return; + + QString from2(from); auto emitNewTrust = false; { @@ -863,12 +866,12 @@ ContactModelPimpl::slotNewAccountMessage(std::string& accountId, // The conversation model will create an entry and link the incomingCall. if (linked.owner.profileInfo.type == profile::Type::SIP) { - std::string potentialContact = sipUriReceivedFilter(from); - if (potentialContact.empty()) { + QString potentialContact = sipUriReceivedFilter(from); + if (potentialContact.isEmpty()) { addToContacts(from, profile::Type::SIP, "", false); } else { // equivalent uri exist, use that uri - from = potentialContact; + from2 = potentialContact; } } else { addToContacts(from, profile::Type::PENDING, "", false); @@ -879,18 +882,18 @@ ContactModelPimpl::slotNewAccountMessage(std::string& accountId, if (emitNewTrust) { emit behaviorController.newTrustRequest(linked.owner.id, from); } - emit linked.newAccountMessage(accountId, msgId, from, payloads); + emit linked.newAccountMessage(accountId, msgId, from2, payloads); } -std::string -ContactModelPimpl::sipUriReceivedFilter(const std::string& uri) +QString +ContactModelPimpl::sipUriReceivedFilter(const QString& uri) { // this function serves when the uri is not found in the contact list // return "" means need to add new contact, else means equivalent uri exist - std::string uriCopy = uri; + std::string uriCopy = uri.toStdString(); auto pos = uriCopy.find("@"); - auto ownerHostName = linked.owner.confProperties.hostname; + auto ownerHostName = linked.owner.confProperties.hostname.toStdString(); if (pos != std::string::npos) { // "@" is found, separate username and hostname @@ -899,15 +902,15 @@ ContactModelPimpl::sipUriReceivedFilter(const std::string& uri) std::string remoteUser = std::move(uriCopy); if (hostName.compare(ownerHostName) == 0) { - - if (contacts.find(remoteUser) != contacts.end()) { - return remoteUser; + auto remoteUserQStr = QString::fromStdString(remoteUser); + if (contacts.find(remoteUserQStr) != contacts.end()) { + return remoteUserQStr; } if (remoteUser.at(0) == '+') { // "+" - country dial-in codes // maximum 3 digits for (int i = 2; i <= 4; i++) { - std::string tempUserName = remoteUser.substr(i); + QString tempUserName = QString::fromStdString(remoteUser.substr(i)); if (contacts.find(tempUserName) != contacts.end()) { return tempUserName; } @@ -916,12 +919,11 @@ ContactModelPimpl::sipUriReceivedFilter(const std::string& uri) } else { // if not "+" from incoming // sub "+" char from contacts to see if user exit - for (auto& i : contacts) { - if (!i.first.empty()) { + for (auto& contactUri : contacts.keys()) { + if (!contactUri.isEmpty()) { for (int j = 2; j <= 4; j++) { - std::string tempUserName = i.first.substr(j); - if (tempUserName == remoteUser) { - return i.first; + if (QString(contactUri).remove(0, j) == remoteUserQStr) { + return contactUri; } } } diff --git a/src/conversationmodel.cpp b/src/conversationmodel.cpp index 1d0cbea50a57dd0fd1cdfc444843a124b8a35d07..60711e494eb660bfa78f42c08ea99646325c563a 100644 --- a/src/conversationmodel.cpp +++ b/src/conversationmodel.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * + * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * * Author: Nicolas Jäger <nicolas.jager@savoirfairelinux.com> * * Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com> * * Author: Guillaume Roguez <guillaume.roguez@savoirfairelinux.com> * @@ -20,21 +20,7 @@ ***************************************************************************/ #include "api/conversationmodel.h" -//Qt -#include <QtCore/QTimer> -#include <QFileInfo> - -// daemon -#include <account_const.h> -#include <datatransfer_interface.h> - -// std -#include <algorithm> -#include <mutex> -#include <regex> -#include <fstream> - -// LRC + // LRC #include "api/lrc.h" #include "api/behaviorcontroller.h" #include "api/contactmodel.h" @@ -46,13 +32,26 @@ #include "api/datatransfermodel.h" #include "callbackshandler.h" #include "authority/storagehelper.h" - #include "uri.h" // Dbus #include "dbus/configurationmanager.h" #include "dbus/callmanager.h" +// daemon +#include <account_const.h> +#include <datatransfer_interface.h> + +//Qt +#include <QtCore/QTimer> +#include <QFileInfo> + +// std +#include <algorithm> +#include <mutex> +#include <regex> +#include <fstream> + namespace lrc { @@ -76,13 +75,13 @@ public: * @param uid of the contact to search. * @return an int. */ - int indexOf(const std::string& uid) const; + int indexOf(const QString& uid) const; /** * return a conversation index from conversations or -1 if no index is found. * @param uri of the contact to search. * @return an int. */ - int indexOfContact(const std::string& uri) const; + int indexOfContact(const QString& uri) const; /** * Initialize conversations_ and filteredConversations_ */ @@ -95,20 +94,20 @@ public: * Call contactModel.addContact if necessary * @param contactUri */ - void sendContactRequest(const std::string& contactUri); + void sendContactRequest(const QString& contactUri); /** * Add a conversation with contactUri * @param convId * @param contactUri */ - void addConversationWith(const std::string& convId, const std::string& contactUri); + void addConversationWith(const QString& convId, const QString& contactUri); /** * Add call interaction for conversation with callId * @param callId * @param duration */ - void addOrUpdateCallMessage(const std::string& callId, - const std::string& from = {}, + void addOrUpdateCallMessage(const QString& callId, + const QString& from = {}, const std::time_t& duration = -1); /** * Add a new message from a peer in the database @@ -117,8 +116,8 @@ public: * @param timestamp the timestamp of the message * @return msgId generated (in db) */ - int addIncomingMessage(const std::string& from, - const std::string& body, + int addIncomingMessage(const QString& from, + const QString& body, const uint64_t& timestamp = 0); /** * Change the status of an interaction. Listen from callbacksHandler @@ -127,30 +126,30 @@ public: * @param to, peer uri * @param status, new status for this interaction */ - void slotUpdateInteractionStatus(const std::string& accountId, + void slotUpdateInteractionStatus(const QString& accountId, const uint64_t id, - const std::string& to, int status); + const QString& to, int status); /** * place a call * @param uid, conversation id * @param isAudioOnly, allow to specify if the call is only audio. Set to false by default. */ - void placeCall(const std::string& uid, bool isAudioOnly = false); + void placeCall(const QString& uid, bool isAudioOnly = false); /** * get number of unread messages */ - int getNumberOfUnreadMessagesFor(const std::string& uid); + int getNumberOfUnreadMessagesFor(const QString& uid); /** * Handle data transfer progression */ - void updateTransfer(QTimer* timer, const std::string& conversation, int conversationIdx, + void updateTransfer(QTimer* timer, const QString& conversation, int conversationIdx, int interactionId); bool usefulDataFromDataTransfer(long long dringId, const datatransfer::Info& info, - int& interactionId, std::string& convId); + int& interactionId, QString& convId); /** * accept a file transfer @@ -158,7 +157,7 @@ public: * @param interactionId * @param final name of the file */ - void acceptTransfer(const std::string& convUid, uint64_t interactionId, const std::string& path); + void acceptTransfer(const QString& convUid, uint64_t interactionId, const QString& path); const ConversationModel& linked; Lrc& lrc; @@ -169,53 +168,53 @@ public: ConversationModel::ConversationQueue conversations; ///< non-filtered conversations ConversationModel::ConversationQueue filteredConversations; ConversationModel::ConversationQueue customFilteredConversations; - std::string filter; + QString filter; profile::Type typeFilter; profile::Type customTypeFilter; std::pair<bool, bool> dirtyConversations {true, true}; ///< true if filteredConversations/customFilteredConversations must be regenerated - std::map<std::string, std::mutex> interactionsLocks; ///< {convId, mutex} + std::map<QString, std::mutex> interactionsLocks; ///< {convId, mutex} public Q_SLOTS: /** * Listen from contactModel when updated (like new alias, avatar, etc.) */ - void slotContactModelUpdated(const std::string& uri, bool needsSorted); + void slotContactModelUpdated(const QString& uri, bool needsSorted); /** * Listen from contactModel when a new contact is added * @param uri */ - void slotContactAdded(const std::string& contactUri); + void slotContactAdded(const QString& contactUri); /** * Listen from contactModel when a pending contact is accepted * @param uri */ - void slotPendingContactAccepted(const std::string& uri); + void slotPendingContactAccepted(const QString& uri); /** * Listen from contactModel when aa new contact is removed * @param uri */ - void slotContactRemoved(const std::string& uri); + void slotContactRemoved(const QString& uri); /** * Listen from callmodel for new calls. * @param fromId caller uri * @param callId */ - void slotIncomingCall(const std::string& fromId, const std::string& callId); + void slotIncomingCall(const QString& fromId, const QString& callId); /** * Listen from callmodel for calls status changed. * @param callId */ - void slotCallStatusChanged(const std::string& callId, int code); + void slotCallStatusChanged(const QString& callId, int code); /** * Listen from callmodel for writing "Call started" * @param callId */ - void slotCallStarted(const std::string& callId); + void slotCallStarted(const QString& callId); /** * Listen from callmodel for writing "Call ended" * @param callId */ - void slotCallEnded(const std::string& callId); + void slotCallEnded(const QString& callId); /** * Listen from CallbacksHandler for new incoming interactions; * @param accountId @@ -223,28 +222,28 @@ public Q_SLOTS: * @param from uri * @param payloads body */ - void slotNewAccountMessage(std::string& accountId, - std::string& msgId, - std::string& from, - std::map<std::string,std::string> payloads); + void slotNewAccountMessage(const QString& accountId, + const QString& msgId, + const QString& from, + const MapStringString& payloads); /** * Listen from CallbacksHandler for new messages in a SIP call * @param callId call linked to the interaction * @param from author uri * @param body of the message */ - void slotIncomingCallMessage(const std::string& callId, const std::string& from, const std::string& body); + void slotIncomingCallMessage(const QString& callId, const QString& from, const QString& body); /** * Listen from CallModel when a call is added to a conference * @param callId * @param confId */ - void slotCallAddedToConference(const std::string& callId, const std::string& confId); + void slotCallAddedToConference(const QString& callId, const QString& confId); /** * Listen from CallbacksHandler when a conference is deleted. * @param confId */ - void slotConferenceRemoved(const std::string& confId); + void slotConferenceRemoved(const QString& confId); void slotTransferStatusCreated(long long dringId, api::datatransfer::Info info); void slotTransferStatusCanceled(long long dringId, api::datatransfer::Info info); @@ -291,14 +290,14 @@ ConversationModel::allFilteredConversations() const auto contactInfo = owner.contactModel->getContact(entry.participants.front()); auto filter = pimpl_->filter; - auto uri = URI(QString(filter.c_str())); + auto uri = URI(filter); bool stripScheme = (uri.schemeType() < URI::SchemeType::COUNT__); FlagPack<URI::Section> flags = URI::Section::USER_INFO | URI::Section::HOSTNAME | URI::Section::PORT; if (!stripScheme) { flags |= URI::Section::SCHEME; } - filter = uri.format(flags).toStdString(); + filter = uri.format(flags); /* Check contact */ // If contact is banned, only match if filter is a perfect match @@ -312,18 +311,18 @@ ConversationModel::allFilteredConversations() const std::regex regexFilter; auto isValidReFilter = true; try { - regexFilter = std::regex(filter, std::regex_constants::icase); + regexFilter = std::regex(filter.toStdString(), std::regex_constants::icase); } catch(std::regex_error&) { isValidReFilter = false; } auto filterUriAndReg = [regexFilter, isValidReFilter](auto contact, auto filter) { - auto result = contact.profileInfo.uri.find(filter) != std::string::npos - || contact.registeredName.find(filter) != std::string::npos; + auto result = contact.profileInfo.uri.contains(filter) + || contact.registeredName.contains(filter); if (!result) { - auto regexFound = isValidReFilter? (!contact.profileInfo.uri.empty() - && std::regex_search(contact.profileInfo.uri, regexFilter)) - || std::regex_search(contact.registeredName, regexFilter) : false; + auto regexFound = isValidReFilter? (!contact.profileInfo.uri.isEmpty() + && std::regex_search(contact.profileInfo.uri.toStdString(), regexFilter)) + || std::regex_search(contact.registeredName.toStdString(), regexFilter) : false; result |= regexFound; } return result; @@ -350,9 +349,11 @@ ConversationModel::allFilteredConversations() const } // Otherwise perform usual regex search - bool result = contactInfo.profileInfo.alias.find(filter) != std::string::npos; - if (!result && isValidReFilter) result |= std::regex_search(contactInfo.profileInfo.alias, regexFilter); - if (!result) result |= filterUriAndReg(contactInfo, filter); + bool result = contactInfo.profileInfo.alias.contains(filter); + if (!result && isValidReFilter) + result |= std::regex_search(contactInfo.profileInfo.alias.toStdString(), regexFilter); + if (!result) + result |= filterUriAndReg(contactInfo, filter); return result; } catch (std::out_of_range&) { // getContact() failed @@ -364,14 +365,14 @@ ConversationModel::allFilteredConversations() const return pimpl_->filteredConversations; } -std::map<ConferenceableItem, ConferenceableValue> -ConversationModel::getConferenceableConversations(const std::string& convId, const std::string& filter) const +QMap<ConferenceableItem, ConferenceableValue> +ConversationModel::getConferenceableConversations(const QString& convId, const QString& filter) const { auto conversationIdx = pimpl_->indexOf(convId); if (conversationIdx == -1 || !owner.enabled) { return {}; } - std::map<ConferenceableItem, ConferenceableValue> result; + QMap<ConferenceableItem, ConferenceableValue> result; ConferenceableValue callsVector, contactsVector; auto currentConfId = pimpl_->conversations.at(conversationIdx).confId; @@ -383,36 +384,36 @@ ConversationModel::getConferenceableConversations(const std::string& convId, con //add contacts for current account for (const auto &conv : conversations) { // conversations with calls will be added in call section - if(!conv.callId.empty() || !conv.confId.empty()) { + if(!conv.callId.isEmpty() || !conv.confId.isEmpty()) { continue; } auto contact = owner.contactModel->getContact(conv.participants.front()); if(contact.isBanned || contact.profileInfo.type == profile::Type::PENDING) { continue; } - std::vector<AccountConversation> cv; + QVector<AccountConversation> cv; AccountConversation accConv = {conv.uid, currentAccountID}; - cv.emplace_back(accConv); - if (filter.empty()) { - contactsVector.emplace_back(cv); + cv.push_back(accConv); + if (filter.isEmpty()) { + contactsVector.push_back(cv); continue; } - bool result = contact.profileInfo.alias.find(filter) != std::string::npos || - contact.profileInfo.uri.find(filter) != std::string::npos || - contact.registeredName.find(filter) != std::string::npos; + bool result = contact.profileInfo.alias.contains(filter) || + contact.profileInfo.uri.contains(filter) || + contact.registeredName.contains(filter); if (result) { - contactsVector.emplace_back(cv); + contactsVector.push_back(cv); } } if (calls.empty() && conferences.empty()) { - result.insert(std::pair<ConferenceableItem, ConferenceableValue>(ConferenceableItem::CONTACT, contactsVector)); + result.insert(ConferenceableItem::CONTACT, contactsVector); return result; } //filter out calls from conference for (const auto& c : conferences) { - for (const std::string subcal : pimpl_->lrc.getConferenceSubcalls(c)) { + for (const auto& subcal : pimpl_->lrc.getConferenceSubcalls(c)) { auto position = std::find(calls.begin(), calls.end(), subcal); if (position != calls.end()) { calls.erase(position); @@ -421,15 +422,15 @@ ConversationModel::getConferenceableConversations(const std::string& convId, con } //found conversations and account for calls and conferences - std::map<std::string, std::vector<AccountConversation>> tempConferences; + QMap<QString, QVector<AccountConversation>> tempConferences; for (const auto &account_id : pimpl_->lrc.getAccountModel().getAccountList()) { try { auto &accountInfo = pimpl_->lrc.getAccountModel().getAccountInfo(account_id); auto accountConv = accountInfo.conversationModel->getFilteredConversations(accountInfo.profileInfo.type); for (const auto &conv : accountConv) { - bool confFilterPredicate = !conv.confId.empty() && conv.confId != currentConfId && + bool confFilterPredicate = !conv.confId.isEmpty() && conv.confId != currentConfId && std::find(conferences.begin(), conferences.end(), conv.confId) != conferences.end(); - bool callFilterPredicate = !conv.callId.empty() && conv.callId != currentCallId && + bool callFilterPredicate = !conv.callId.isEmpty() && conv.callId != currentCallId && std::find(calls.begin(), calls.end(), conv.callId) != calls.end(); if (!confFilterPredicate && !callFilterPredicate) { @@ -438,11 +439,11 @@ ConversationModel::getConferenceableConversations(const std::string& convId, con // vector of conversationID accountID pair // for call has only one entry, for conference multyple - std::vector<AccountConversation> cv; + QVector<AccountConversation> cv; AccountConversation accConv = {conv.uid, account_id}; - cv.emplace_back(accConv); + cv.push_back(accConv); - bool isConference = !conv.confId.empty(); + bool isConference = !conv.confId.isEmpty(); //call could be added if it is not conference and in active state bool shouldAddCall = false; if (!isConference && accountInfo.callModel->hasCall(conv.callId)) { @@ -453,26 +454,26 @@ ConversationModel::getConferenceableConversations(const std::string& convId, con auto contact = accountInfo.contactModel->getContact(conv.participants.front()); //check if contact satisfy filter - bool result = (filter.empty() || isConference) ? true : - (contact.profileInfo.alias.find(filter) != std::string::npos || - contact.profileInfo.uri.find(filter) != std::string::npos || - contact.registeredName.find(filter) != std::string::npos); + bool result = (filter.isEmpty() || isConference) ? true : + (contact.profileInfo.alias.contains(filter) || + contact.profileInfo.uri.contains(filter) || + contact.registeredName.contains(filter)); if (!result) { continue; } if (isConference && tempConferences.count(conv.confId)) { - tempConferences.find(conv.confId)->second.emplace_back(accConv); + tempConferences.find(conv.confId).value().push_back(accConv); } else if (isConference) { - tempConferences.insert(std::pair<std::string, std::vector<AccountConversation>>(conv.confId, cv)); + tempConferences.insert(conv.confId, cv); } else if (shouldAddCall) { - callsVector.emplace_back(cv); + callsVector.push_back(cv); } } } catch (...) {} } - for(auto it : tempConferences) { - if (filter.empty()) { - callsVector.emplace_back(it.second); + for(auto it : tempConferences.toStdMap()) { + if (filter.isEmpty()) { + callsVector.push_back(it.second); continue; } for(AccountConversation accConv : it.second) { @@ -480,17 +481,17 @@ ConversationModel::getConferenceableConversations(const std::string& convId, con auto &account = pimpl_->lrc.getAccountModel().getAccountInfo(accConv.accountId); auto conv = account.conversationModel->getConversationForUID(accConv.convId); auto cont = account.contactModel->getContact(conv.participants.front()); - if (cont.profileInfo.alias.find(filter) != std::string::npos || - cont.profileInfo.uri.find(filter) != std::string::npos || - cont.registeredName.find(filter) != std::string::npos) { - callsVector.emplace_back(it.second); + if ( cont.profileInfo.alias.contains(filter) || + cont.profileInfo.uri.contains(filter) || + cont.registeredName.contains(filter)) { + callsVector.push_back(it.second); continue; } } catch (...) {} } } - result.insert(std::pair<ConferenceableItem, ConferenceableValue>(ConferenceableItem::CALL, callsVector)); - result.insert(std::pair<ConferenceableItem, ConferenceableValue>(ConferenceableItem::CONTACT, contactsVector)); + result.insert(ConferenceableItem::CALL, callsVector); + result.insert(ConferenceableItem::CONTACT, contactsVector); return result; } @@ -517,7 +518,7 @@ ConversationModel::getFilteredConversations(const profile::Type& filter, bool fo } conversation::Info -ConversationModel::getConversationForUID(const std::string& uid) const +ConversationModel::getConversationForUID(const QString& uid) const { auto conversationIdx = pimpl_->indexOf(uid); if (conversationIdx == -1 || !owner.enabled) { @@ -543,7 +544,7 @@ ConversationModel::filteredConversation(const unsigned int row) const } void -ConversationModel::makePermanent(const std::string& uid) +ConversationModel::makePermanent(const QString& uid) { auto conversationIdx = pimpl_->indexOf(uid); if (conversationIdx == -1 || !owner.enabled) @@ -561,7 +562,7 @@ ConversationModel::makePermanent(const std::string& uid) } void -ConversationModel::selectConversation(const std::string& uid) const +ConversationModel::selectConversation(const QString& uid) const { // Get conversation auto conversationIdx = pimpl_->indexOf(uid); @@ -569,21 +570,21 @@ ConversationModel::selectConversation(const std::string& uid) const if (conversationIdx == -1) return; - if (uid.empty() && owner.contactModel->getContact("").profileInfo.uri.empty()) { + if (uid.isEmpty() && owner.contactModel->getContact("").profileInfo.uri.isEmpty()) { // if we select the temporary contact, check if its a valid contact. return; } auto& conversation = pimpl_->conversations.at(conversationIdx); bool callEnded = true; - if (!conversation.callId.empty()) { + if (!conversation.callId.isEmpty()) { try { auto call = owner.callModel->getCall(conversation.callId); callEnded = call.status == call::Status::ENDED; } catch (...) {} } - if (not callEnded and not conversation.confId.empty()) { + if (not callEnded and not conversation.confId.isEmpty()) { emit pimpl_->behaviorController.showCallView(owner.id, conversation); } else if (callEnded) { emit pimpl_->behaviorController.showChatView(owner.id, conversation); @@ -627,7 +628,7 @@ ConversationModel::selectConversation(const std::string& uid) const } void -ConversationModel::removeConversation(const std::string& uid, bool banned) +ConversationModel::removeConversation(const QString& uid, bool banned) { // Get conversation auto conversationIdx = pimpl_->indexOf(uid); @@ -660,7 +661,7 @@ ConversationModel::deleteObsoleteHistory(int days) } void -ConversationModelPimpl::placeCall(const std::string& uid, bool isAudioOnly) +ConversationModelPimpl::placeCall(const QString& uid, bool isAudioOnly) { auto conversationIdx = indexOf(uid); @@ -675,7 +676,7 @@ ConversationModelPimpl::placeCall(const std::string& uid, bool isAudioOnly) } // Disallow multiple call - if (!conversation.callId.empty()) { + if (!conversation.callId.isEmpty()) { try { auto call = linked.owner.callModel->getCall(conversation.callId); switch (call.status) { @@ -703,11 +704,11 @@ ConversationModelPimpl::placeCall(const std::string& uid, bool isAudioOnly) auto convId = uid; auto participant = conversation.participants.front(); - bool isTemporary = participant.empty(); + bool isTemporary = participant.isEmpty(); auto contactInfo = linked.owner.contactModel->getContact(participant); auto uri = contactInfo.profileInfo.uri; - if (uri.empty()) + if (uri.isEmpty()) return; // Incorrect item // Don't call banned contact @@ -720,8 +721,8 @@ ConversationModelPimpl::placeCall(const std::string& uid, bool isAudioOnly) uri = "ring:" + uri; // Add the ring: before or it will fail. } - auto cb = std::function<void(std::string)>( - [this, isTemporary, uri, isAudioOnly, &conversation](std::string convId) { + auto cb = std::function<void(QString)>( + [this, isTemporary, uri, isAudioOnly, &conversation](QString convId) { int contactIndex; if (isTemporary && (contactIndex = indexOfContact(convId)) < 0) { qDebug() << "Can't place call: Other participant is not a contact (removed while placing call ?)"; @@ -732,7 +733,7 @@ ConversationModelPimpl::placeCall(const std::string& uid, bool isAudioOnly) convId = newConv.uid; newConv.callId = linked.owner.callModel->createCall(uri, isAudioOnly); - if (newConv.callId.empty()) { + if (newConv.callId.isEmpty()) { qDebug() << "Can't place call (daemon side failure ?)"; return; } @@ -744,7 +745,7 @@ ConversationModelPimpl::placeCall(const std::string& uid, bool isAudioOnly) if (isTemporary) { QMetaObject::Connection* const connection = new QMetaObject::Connection; *connection = connect(&this->linked, &ConversationModel::conversationReady, - [cb, connection](std::string convId) { + [cb, connection](QString convId) { cb(convId); QObject::disconnect(*connection); if (connection) { @@ -761,19 +762,19 @@ ConversationModelPimpl::placeCall(const std::string& uid, bool isAudioOnly) } void -ConversationModel::placeAudioOnlyCall(const std::string& uid) +ConversationModel::placeAudioOnlyCall(const QString& uid) { pimpl_->placeCall(uid, true); } void -ConversationModel::placeCall(const std::string& uid) +ConversationModel::placeCall(const QString& uid) { pimpl_->placeCall(uid); } void -ConversationModel::sendMessage(const std::string& uid, const std::string& body) +ConversationModel::sendMessage(const QString& uid, const QString& body) { // FIXME potential race condition between index check and at() call auto conversationIdx = pimpl_->indexOf(uid); @@ -795,8 +796,8 @@ ConversationModel::sendMessage(const std::string& uid, const std::string& body) it might me destroyed while we are reading it */ const auto participants = conversation.participants; - auto cb = std::function<void(std::string)>( - [this, isTemporary, body, &conversation](std::string convId) { + auto cb = std::function<void(QString)>( + [this, isTemporary, body, &conversation](QString convId) { /* Now we should be able to retrieve the final conversation, in case the previous one was temporary */ // FIXME potential race condition between index check and at() call @@ -819,10 +820,10 @@ ConversationModel::sendMessage(const std::string& uid, const std::string& body) QStringList callLists = CallManager::instance().getCallList(); // no auto // workaround: sometimes, it may happen that the daemon delete a call, but lrc don't. We check if the call is // still valid every time the user want to send a message. - if (not newConv.callId.empty() and not callLists.contains(newConv.callId.c_str())) + if (not newConv.callId.isEmpty() and not callLists.contains(newConv.callId)) newConv.callId.clear(); - if (not newConv.callId.empty() + if (not newConv.callId.isEmpty() and call::canSendSIPMessage(owner.callModel->getCall(newConv.callId))) { status = interaction::Status::UNKNOWN; owner.callModel->sendSipMessage(newConv.callId, body); @@ -847,7 +848,7 @@ ConversationModel::sendMessage(const std::string& uid, const std::string& body) // Update conversation if (status == interaction::Status::SENDING) { // Because the daemon already give an id for the message, we need to store it. - storage::addDaemonMsgId(pimpl_->db, std::to_string(msgId), std::to_string(daemonMsgId)); + storage::addDaemonMsgId(pimpl_->db, toQString(msgId), toQString(daemonMsgId)); } bool ret = false; @@ -875,7 +876,7 @@ ConversationModel::sendMessage(const std::string& uid, const std::string& body) if (isTemporary) { QMetaObject::Connection* const connection = new QMetaObject::Connection; *connection = connect(this, &ConversationModel::conversationReady, - [cb, connection](std::string convId) { + [cb, connection](QString convId) { cb(convId); QObject::disconnect(*connection); if (connection) { @@ -910,7 +911,7 @@ ConversationModel::refreshFilter() } void -ConversationModel::setFilter(const std::string& filter) +ConversationModel::setFilter(const QString& filter) { pimpl_->filter = filter; pimpl_->dirtyConversations = {true, true}; @@ -929,7 +930,7 @@ ConversationModel::setFilter(const profile::Type& filter) } void -ConversationModel::joinConversations(const std::string& uidA, const std::string& uidB) +ConversationModel::joinConversations(const QString& uidA, const QString& uidB) { auto conversationAIdx = pimpl_->indexOf(uidA); auto conversationBIdx = pimpl_->indexOf(uidB); @@ -938,18 +939,18 @@ ConversationModel::joinConversations(const std::string& uidA, const std::string& auto& conversationA = pimpl_->conversations[conversationAIdx]; auto& conversationB = pimpl_->conversations[conversationBIdx]; - if (conversationA.callId.empty() || conversationB.callId.empty()) + if (conversationA.callId.isEmpty() || conversationB.callId.isEmpty()) return; - if (conversationA.confId.empty()) { - if(conversationB.confId.empty()){ + if (conversationA.confId.isEmpty()) { + if(conversationB.confId.isEmpty()){ owner.callModel->joinCalls(conversationA.callId, conversationB.callId); }else{ owner.callModel->joinCalls(conversationA.callId, conversationB.confId); conversationA.confId = conversationB.confId; } } else { - if(conversationB.confId.empty()){ + if(conversationB.confId.isEmpty()){ owner.callModel->joinCalls(conversationA.confId, conversationB.callId); conversationB.confId = conversationA.confId; }else{ @@ -960,7 +961,7 @@ ConversationModel::joinConversations(const std::string& uidA, const std::string& } void -ConversationModel::clearHistory(const std::string& uid) +ConversationModel::clearHistory(const QString& uid) { auto conversationIdx = pimpl_->indexOf(uid); if (conversationIdx == -1) @@ -981,7 +982,7 @@ ConversationModel::clearHistory(const std::string& uid) } void -ConversationModel::clearInteractionFromConversation(const std::string& convId, const uint64_t& interactionId) +ConversationModel::clearInteractionFromConversation(const QString& convId, const uint64_t& interactionId) { auto conversationIdx = pimpl_->indexOf(convId); if (conversationIdx == -1) @@ -1022,14 +1023,14 @@ ConversationModel::clearInteractionFromConversation(const std::string& convId, c } void -ConversationModel::retryInteraction(const std::string& convId, const uint64_t& interactionId) +ConversationModel::retryInteraction(const QString& convId, const uint64_t& interactionId) { auto conversationIdx = pimpl_->indexOf(convId); if (conversationIdx == -1) return; auto interactionType = interaction::Type::INVALID; - auto body = std::string(); + QString body = {}; { std::lock_guard<std::mutex> lk(pimpl_->interactionsLocks[convId]); try { @@ -1043,9 +1044,9 @@ ConversationModel::retryInteraction(const std::string& convId, const uint64_t& i if (!interaction::isOutgoing(it->second)) return; // Do not retry non outgoing info - if (it->second.type == interaction::Type::TEXT - || (it->second.type == interaction::Type::DATA_TRANSFER - && interaction::isOutgoing(it->second))) { + if (it->second.type == interaction::Type::TEXT || + (it->second.type == interaction::Type::DATA_TRANSFER && + interaction::isOutgoing(it->second))) { body = it->second.body; interactionType = it->second.type; } else @@ -1065,8 +1066,8 @@ ConversationModel::retryInteraction(const std::string& convId, const uint64_t& i sendMessage(convId, body); } else { // send file - QFileInfo f(body.c_str()); - sendFile(convId, body, f.fileName().toStdString()); + QFileInfo f(body); + sendFile(convId, body, f.fileName()); } } @@ -1087,7 +1088,7 @@ ConversationModel::clearAllHistory() } void -ConversationModel::setInteractionRead(const std::string& convId, +ConversationModel::setInteractionRead(const QString& convId, const uint64_t& interactionId) { auto conversationIdx = pimpl_->indexOf(convId); @@ -1120,7 +1121,7 @@ ConversationModel::setInteractionRead(const std::string& convId, } void -ConversationModel::clearUnreadInteractions(const std::string& convId) { +ConversationModel::clearUnreadInteractions(const QString& convId) { auto conversationIdx = pimpl_->indexOf(convId); if (conversationIdx == -1) { return; @@ -1302,18 +1303,18 @@ ConversationModelPimpl::~ConversationModelPimpl() void ConversationModelPimpl::initConversations() { - const MapStringString accountDetails = ConfigurationManager::instance().getAccountDetails(linked.owner.id.c_str()); + const MapStringString accountDetails = ConfigurationManager::instance().getAccountDetails(linked.owner.id); if (accountDetails.empty()) return; // Fill conversations - for (auto const& c : linked.owner.contactModel->getAllContacts()) + for (auto const& c : linked.owner.contactModel->getAllContacts().toStdMap()) { auto conv = storage::getConversationsWithPeer(db, c.second.profileInfo.uri); if (conv.empty()) { // Can't find a conversation with this contact. Start it. auto newConversationsId = storage::beginConversationWithPeer(db, c.second.profileInfo.uri, c.second.isTrusted); - conv.emplace_back(std::move(newConversationsId)); + conv.push_back(std::move(newConversationsId)); } addConversationWith(conv[0], c.first); @@ -1342,7 +1343,7 @@ ConversationModelPimpl::initConversations() // Load all non treated messages for this account QVector<Message> messages = ConfigurationManager::instance().getLastMessages( - linked.owner.id.c_str(), + linked.owner.id, storage::getLastTimestamp(db) ); for (const auto& message : messages) { @@ -1350,8 +1351,8 @@ ConversationModelPimpl::initConversations() try { timestamp = static_cast<uint64_t>(message.received); } catch (...) {} - addIncomingMessage(message.from.toStdString(), - message.payloads["text/plain"].toStdString(), + addIncomingMessage(message.from, + message.payloads["text/plain"], timestamp); } } @@ -1364,8 +1365,8 @@ ConversationModelPimpl::sortConversations() [this](const auto& conversationA, const auto& conversationB) { // A or B is a temporary contact - if (conversationA.participants.empty()) return true; - if (conversationB.participants.empty()) return false; + if (conversationA.participants.isEmpty()) return true; + if (conversationB.participants.isEmpty()) return false; if (conversationA.uid == conversationB.uid) return false; @@ -1377,8 +1378,11 @@ ConversationModelPimpl::sortConversations() auto historyA = conversationA.interactions; auto historyB = conversationB.interactions; + // A or B is a new conversation (without CONTACT interaction) - if (conversationA.uid.empty() || conversationB.uid.empty()) return conversationA.uid.empty(); + if (conversationA.uid.isEmpty() || conversationB.uid.isEmpty()) + return conversationA.uid.isEmpty(); + if (historyA.empty() && historyB.empty()) { // If no information to compare, sort by Ring ID return conversationA.participants.front() > conversationB.participants.front(); @@ -1402,7 +1406,7 @@ ConversationModelPimpl::sortConversations() } void -ConversationModelPimpl::sendContactRequest(const std::string& contactUri) +ConversationModelPimpl::sendContactRequest(const QString& contactUri) { auto contact = linked.owner.contactModel->getContact(contactUri); auto isNotUsed = contact.profileInfo.type == profile::Type::TEMPORARY @@ -1411,7 +1415,7 @@ ConversationModelPimpl::sendContactRequest(const std::string& contactUri) } void -ConversationModelPimpl::slotContactAdded(const std::string& contactUri) +ConversationModelPimpl::slotContactAdded(const QString& contactUri) { auto type = linked.owner.profileInfo.type; profile::Info profileInfo{ contactUri, {}, {}, type }; @@ -1424,7 +1428,7 @@ ConversationModelPimpl::slotContactAdded(const std::string& contactUri) auto conv = storage::getConversationsWithPeer(db, profileInfo.uri); if (conv.empty()) { // pass conversation UID through only element - conv.emplace_back(storage::beginConversationWithPeer(db, profileInfo.uri)); + conv.push_back(storage::beginConversationWithPeer(db, profileInfo.uri)); } // Add the conversation if not already here if (indexOf(conv[0]) == -1) { @@ -1443,7 +1447,7 @@ ConversationModelPimpl::slotContactAdded(const std::string& contactUri) } void -ConversationModelPimpl::slotPendingContactAccepted(const std::string& uri) +ConversationModelPimpl::slotPendingContactAccepted(const QString& uri) { auto type = linked.owner.profileInfo.type; try { @@ -1453,7 +1457,7 @@ ConversationModelPimpl::slotPendingContactAccepted(const std::string& uri) storage::createOrUpdateProfile(linked.owner.id, profileInfo, true); auto convs = storage::getConversationsWithPeer(db, uri); if (convs.empty()) { - convs.emplace_back(storage::beginConversationWithPeer(db, uri)); + convs.push_back(storage::beginConversationWithPeer(db, uri)); } else { try { auto contact = linked.owner.contactModel->getContact(uri); @@ -1480,7 +1484,7 @@ ConversationModelPimpl::slotPendingContactAccepted(const std::string& uri) } void -ConversationModelPimpl::slotContactRemoved(const std::string& uri) +ConversationModelPimpl::slotContactRemoved(const QString& uri) { auto conversationIdx = indexOfContact(uri); if (conversationIdx == -1) { @@ -1495,33 +1499,33 @@ ConversationModelPimpl::slotContactRemoved(const std::string& uri) } void -ConversationModelPimpl::slotContactModelUpdated(const std::string& uri, bool needsSorted) +ConversationModelPimpl::slotContactModelUpdated(const QString& uri, bool needsSorted) { // We don't create newConversationItem if we already filter on pending conversation::Info newConversationItem; - if (!filter.empty()) { + if (!filter.isEmpty()) { // Create a conversation with the temporary item conversation::Info conversationInfo; auto& temporaryContact = linked.owner.contactModel->getContact(""); conversationInfo.uid = temporaryContact.profileInfo.uri; - conversationInfo.participants.emplace_back(""); + conversationInfo.participants.push_back(""); conversationInfo.accountId = linked.owner.id; // if temporary contact is already present, its alias is not empty (namely "Searching ..."), // or its registeredName is set because it was found on the nameservice. - if (not temporaryContact.profileInfo.alias.empty() || not temporaryContact.registeredName.empty()) { + if (not temporaryContact.profileInfo.alias.isEmpty() || not temporaryContact.registeredName.isEmpty()) { if (!conversations.empty()) { auto firstContactUri = conversations.front().participants.front(); //if first conversation has uri it is already a contact // then we must add temporary item - if (not firstContactUri.empty()) { + if (not firstContactUri.isEmpty()) { conversations.emplace_front(conversationInfo); - } else if (not conversationInfo.uid.empty()) { + } else if (not conversationInfo.uid.isEmpty()) { // If firstContactUri is empty it means that we have to update // this element as it is the temporary. // Only when we have found an uri. conversations.front() = conversationInfo; - } else if (not conversations.front().uid.empty()) { + } else if (not conversations.front().uid.isEmpty()) { //update conversation when uri not found //but conversation have uri from previous search conversations.front() = conversationInfo; @@ -1543,7 +1547,7 @@ ConversationModelPimpl::slotContactModelUpdated(const std::string& uri, bool nee if (!conversations.empty()) { auto firstContactUri = conversations.front().participants.front(); - if (firstContactUri.empty() && needsSorted) { + if (firstContactUri.isEmpty() && needsSorted) { conversations.pop_front(); dirtyConversations = {true, true}; emit linked.modelSorted(); @@ -1556,7 +1560,7 @@ ConversationModelPimpl::slotContactModelUpdated(const std::string& uri, bool nee dirtyConversations = {true, true}; int index = indexOfContact(uri); if (index != -1) { - if (!conversations.empty() && conversations.front().participants.front().empty() && + if (!conversations.empty() && conversations.front().participants.front().isEmpty() && needsSorted) { // In this case, contact is present in list, so temporary item does not longer exists emit linked.modelSorted(); @@ -1568,8 +1572,8 @@ ConversationModelPimpl::slotContactModelUpdated(const std::string& uri, bool nee } void -ConversationModelPimpl::addConversationWith(const std::string& convId, - const std::string& contactUri) +ConversationModelPimpl::addConversationWith(const QString& convId, + const QString& contactUri) { conversation::Info conversation; conversation.uid = convId; @@ -1594,13 +1598,13 @@ ConversationModelPimpl::addConversationWith(const std::string& convId, continue; } // Get the message status from daemon, else unknown - auto id = storage::getDaemonIdByInteractionId(db, std::to_string(interaction.first)); + auto id = storage::getDaemonIdByInteractionId(db, toQString(interaction.first)); int status = 0; - if (id.empty()) { + if (id.isEmpty()) { continue; } try { - auto msgId = std::stoull(id); + auto msgId = std::stoull(id.toStdString()); status = ConfigurationManager::instance().getMessageStatus(msgId); updateSlots.emplace_back( [this, msgId, contactUri, status]() -> void { @@ -1620,7 +1624,7 @@ ConversationModelPimpl::addConversationWith(const std::string& convId, } int -ConversationModelPimpl::indexOf(const std::string& uid) const +ConversationModelPimpl::indexOf(const QString& uid) const { for (unsigned int i = 0; i < conversations.size(); ++i) { if (conversations.at(i).uid == uid) return i; @@ -1629,7 +1633,7 @@ ConversationModelPimpl::indexOf(const std::string& uid) const } int -ConversationModelPimpl::indexOfContact(const std::string& uri) const +ConversationModelPimpl::indexOfContact(const QString& uri) const { for (unsigned int i = 0; i < conversations.size(); ++i) { if (conversations.at(i).participants.front() == uri) return i; @@ -1638,7 +1642,7 @@ ConversationModelPimpl::indexOfContact(const std::string& uri) const } void -ConversationModelPimpl::slotIncomingCall(const std::string& fromId, const std::string& callId) +ConversationModelPimpl::slotIncomingCall(const QString& fromId, const QString& callId) { auto conversationIdx = indexOfContact(fromId); @@ -1649,14 +1653,14 @@ ConversationModelPimpl::slotIncomingCall(const std::string& fromId, const std::s auto& conversation = conversations.at(conversationIdx); - qDebug() << "Add call to conversation with " << fromId.c_str(); + qDebug() << "Add call to conversation with " << fromId; conversation.callId = callId; dirtyConversations = {true, true}; emit behaviorController.showIncomingCallView(linked.owner.id, conversation); } void -ConversationModelPimpl::slotCallStatusChanged(const std::string& callId, int code) +ConversationModelPimpl::slotCallStatusChanged(const QString& callId, int code) { Q_UNUSED(code) // Get conversation @@ -1689,7 +1693,7 @@ ConversationModelPimpl::slotCallStatusChanged(const std::string& callId, int cod } void -ConversationModelPimpl::slotCallStarted(const std::string& callId) +ConversationModelPimpl::slotCallStarted(const QString& callId) { try { @@ -1701,7 +1705,7 @@ ConversationModelPimpl::slotCallStarted(const std::string& callId) } void -ConversationModelPimpl::slotCallEnded(const std::string& callId) +ConversationModelPimpl::slotCallEnded(const QString& callId) { try { auto call = linked.owner.callModel->getCall(callId); @@ -1728,8 +1732,8 @@ ConversationModelPimpl::slotCallEnded(const std::string& callId) } void -ConversationModelPimpl::addOrUpdateCallMessage(const std::string& callId, - const std::string& from, +ConversationModelPimpl::addOrUpdateCallMessage(const QString& callId, + const QString& from, const std::time_t& duration) { // Get conversation @@ -1741,7 +1745,7 @@ ConversationModelPimpl::addOrUpdateCallMessage(const std::string& callId, return; } auto uid = conv_it->uid; - std::string uriString = storage::prepareUri(from, linked.owner.profileInfo.type); + auto uriString = storage::prepareUri(from, linked.owner.profileInfo.type); auto msg = interaction::Info { uriString, {}, std::time(nullptr), duration, interaction::Type::CALL, interaction::Status::SUCCESS, true }; // update the db @@ -1767,24 +1771,24 @@ ConversationModelPimpl::addOrUpdateCallMessage(const std::string& callId, } void -ConversationModelPimpl::slotNewAccountMessage(std::string& accountId, - std::string& msgId, - std::string& from, - std::map<std::string,std::string> payloads) +ConversationModelPimpl::slotNewAccountMessage(const QString& accountId, + const QString& msgId, + const QString& from, + const MapStringString& payloads) { if (accountId != linked.owner.id) return; - for (const auto &payload : payloads) { - if (payload.first.find("text/plain") != std::string::npos) { - auto dbId = addIncomingMessage(from, payload.second); - storage::addDaemonMsgId(db, std::to_string(dbId), msgId); + for (const auto &payload : payloads.keys()) { + if (payload.contains("text/plain")) { + auto dbId = addIncomingMessage(from, payloads.value(payload)); + storage::addDaemonMsgId(db, QString::number(dbId), msgId); } } } void -ConversationModelPimpl::slotIncomingCallMessage(const std::string& callId, const std::string& from, const std::string& body) +ConversationModelPimpl::slotIncomingCallMessage(const QString& callId, const QString& from, const QString& body) { if (not linked.owner.callModel->hasCall(callId)) return; @@ -1807,13 +1811,13 @@ ConversationModelPimpl::slotIncomingCallMessage(const std::string& callId, const } int -ConversationModelPimpl::addIncomingMessage(const std::string& from, - const std::string& body, +ConversationModelPimpl::addIncomingMessage(const QString& from, + const QString& body, const uint64_t& timestamp) { auto convIds = storage::getConversationsWithPeer(db, from); if (convIds.empty()) { - convIds.emplace_back(storage::beginConversationWithPeer(db, from, false)); + convIds.push_back(storage::beginConversationWithPeer(db, from, false)); } auto msg = interaction::Info { from, body, timestamp == 0 ? std::time(nullptr) : static_cast<time_t>(timestamp), 0, @@ -1841,7 +1845,7 @@ ConversationModelPimpl::addIncomingMessage(const std::string& from, } void -ConversationModelPimpl::slotCallAddedToConference(const std::string& callId, const std::string& confId) +ConversationModelPimpl::slotCallAddedToConference(const QString& callId, const QString& confId) { for (auto& conversation: conversations) { if (conversation.callId == callId || conversation.confId == confId) { @@ -1853,9 +1857,9 @@ ConversationModelPimpl::slotCallAddedToConference(const std::string& callId, con } void -ConversationModelPimpl::slotUpdateInteractionStatus(const std::string& accountId, +ConversationModelPimpl::slotUpdateInteractionStatus(const QString& accountId, const uint64_t daemon_id, - const std::string& peer_uri, + const QString& peer_uri, int status) { if (accountId != linked.owner.id) { @@ -1883,11 +1887,11 @@ ConversationModelPimpl::slotUpdateInteractionStatus(const std::string& accountId break; } // Update database - auto interactionId = storage::getInteractionIdByDaemonId(db, std::to_string(daemon_id)); - if (interactionId.empty()) { + auto interactionId = storage::getInteractionIdByDaemonId(db, toQString(daemon_id)); + if (interactionId.isEmpty()) { return; } - auto msgId = std::stoull(interactionId); + auto msgId = std::stoull(interactionId.toStdString()); storage::updateInteractionStatus(db, msgId, newStatus); // Update conversations auto convIds = storage::getConversationsWithPeer(db, peer_uri); @@ -1913,7 +1917,7 @@ ConversationModelPimpl::slotUpdateInteractionStatus(const std::string& accountId } void -ConversationModelPimpl::slotConferenceRemoved(const std::string& confId) +ConversationModelPimpl::slotConferenceRemoved(const QString& confId) { // Get conversation for(auto& i : conversations) { @@ -1924,22 +1928,22 @@ ConversationModelPimpl::slotConferenceRemoved(const std::string& confId) } int -ConversationModelPimpl::getNumberOfUnreadMessagesFor(const std::string& uid) +ConversationModelPimpl::getNumberOfUnreadMessagesFor(const QString& uid) { return storage::countUnreadFromInteractions(db, uid); } void -ConversationModel::sendFile(const std::string& convUid, - const std::string& path, - const std::string& filename) +ConversationModel::sendFile(const QString& convUid, + const QString& path, + const QString& filename) { auto conversationIdx = pimpl_->indexOf(convUid); if (conversationIdx == -1 || !owner.enabled) return; const auto peerUri = pimpl_->conversations[conversationIdx].participants.front(); - bool isTemporary = peerUri.empty(); + bool isTemporary = peerUri.isEmpty(); /* It is necessary to make a copy of convUid since it may very well point to a field in the temporary conversation, which is going to be destroyed by @@ -1949,8 +1953,8 @@ ConversationModel::sendFile(const std::string& convUid, pimpl_->sendContactRequest(peerUri); - auto cb = std::function<void(std::string)>( - [this, isTemporary, peerUri, path, filename](std::string convId) { + auto cb = std::function<void(QString)>( + [this, isTemporary, peerUri, path, filename](QString convId) { int contactIndex; if (isTemporary && (contactIndex = pimpl_->indexOfContact(convId)) < 0) { qDebug() << "Can't send file: Other participant is not a contact (removed while sending file ?)"; @@ -1966,16 +1970,16 @@ ConversationModel::sendFile(const std::string& convUid, return; } - pimpl_->lrc.getDataTransferModel().sendFile(owner.id.c_str(), - newPeerUri.c_str(), - path.c_str(), - filename.c_str()); + pimpl_->lrc.getDataTransferModel().sendFile(owner.id, + newPeerUri, + path, + filename); }); if (isTemporary) { QMetaObject::Connection* const connection = new QMetaObject::Connection; *connection = connect(this, &ConversationModel::conversationReady, - [cb, connection](std::string convId) { + [cb, connection](QString convId) { cb(convId); QObject::disconnect(*connection); if (connection) { @@ -1988,13 +1992,13 @@ ConversationModel::sendFile(const std::string& convUid, } void -ConversationModel::acceptTransfer(const std::string& convUid, uint64_t interactionId, const std::string& path) +ConversationModel::acceptTransfer(const QString& convUid, uint64_t interactionId, const QString& path) { pimpl_->acceptTransfer(convUid, interactionId, path); } void -ConversationModel::cancelTransfer(const std::string& convUid, uint64_t interactionId) +ConversationModel::cancelTransfer(const QString& convUid, uint64_t interactionId) { // For this action, we change interaction status before effective canceling as daemon will // emit Finished event code immediately (before leaving this method) in non-DBus mode. @@ -2035,14 +2039,14 @@ ConversationModel::getTransferInfo(uint64_t interactionId, datatransfer::Info& i } int -ConversationModel::getNumberOfUnreadMessagesFor(const std::string& convUid) +ConversationModel::getNumberOfUnreadMessagesFor(const QString& convUid) { return pimpl_->getNumberOfUnreadMessagesFor(convUid); } bool ConversationModelPimpl::usefulDataFromDataTransfer(long long dringId, const datatransfer::Info&, - int& interactionId, std::string& convId) + int& interactionId, QString& convId) { try { interactionId = lrc.getDataTransferModel().getInteractionIdFromDringId(dringId); @@ -2061,13 +2065,13 @@ ConversationModelPimpl::slotTransferStatusCreated(long long dringId, datatransfe // check if transfer is for the current account if (info.accountId != linked.owner.id) return; - const MapStringString accountDetails = ConfigurationManager::instance().getAccountDetails(linked.owner.id.c_str()); + const MapStringString accountDetails = ConfigurationManager::instance().getAccountDetails(linked.owner.id); if (accountDetails.empty()) return; // create a new conversation if needed auto convIds = storage::getConversationsWithPeer(db, info.peerUri); if (convIds.empty()) { - convIds.emplace_back(storage::beginConversationWithPeer(db, info.peerUri, false)); + convIds.push_back(storage::beginConversationWithPeer(db, info.peerUri, false)); } // add interaction to the db @@ -2113,7 +2117,7 @@ void ConversationModelPimpl::slotTransferStatusAwaitingHost(long long dringId, datatransfer::Info info) { int interactionId; - std::string convId; + QString convId; if (not usefulDataFromDataTransfer(dringId, info, interactionId, convId)) return; @@ -2138,9 +2142,13 @@ ConversationModelPimpl::slotTransferStatusAwaitingHost(long long dringId, datatr dirtyConversations = {true, true}; emit linked.interactionStatusUpdated(convId, interactionId, itCopy); // If it's an accepted file type and less than 20 MB, accept transfer. - auto extensionIdx = info.displayName.find_last_of("."); - if (extensionIdx == std::string::npos) return; - auto extension = info.displayName.substr(extensionIdx); + + // TODO: Use Qt functions + + auto extensionIdx = info.displayName.toStdString().find_last_of("."); + if (extensionIdx == std::string::npos) + return; + auto extension = QString(info.displayName).remove(0, extensionIdx); try { auto contactInfo = linked.owner.contactModel->getContact(conversations[conversationIdx].participants.front()); // Only accept if contact is added @@ -2148,14 +2156,14 @@ ConversationModelPimpl::slotTransferStatusAwaitingHost(long long dringId, datatr } catch (...) { return; } - std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower); auto destinationDir = lrc.getDataTransferModel().downloadDirectory; - if (info.totalSize < 20 * 1024 * 1024 && !destinationDir.empty()) { + if (info.totalSize < 20 * 1024 * 1024 && !destinationDir.isEmpty()) { auto wantedFilename = destinationDir + info.displayName; auto duplicate = 0; - while (std::ifstream(wantedFilename).good()) { + while (std::ifstream(wantedFilename.toStdString()).good()) { ++duplicate; - wantedFilename = destinationDir + info.displayName.substr(0, extensionIdx) + " (" + std::to_string(duplicate) + ")" + extension; + wantedFilename = destinationDir + info.displayName.left(extensionIdx) + + " (" + toQString(duplicate) + ")" + extension.toLower(); } acceptTransfer(convId, interactionId, wantedFilename); } @@ -2164,7 +2172,7 @@ ConversationModelPimpl::slotTransferStatusAwaitingHost(long long dringId, datatr } void -ConversationModelPimpl::acceptTransfer(const std::string& convUid, uint64_t interactionId, const std::string& path) +ConversationModelPimpl::acceptTransfer(const QString& convUid, uint64_t interactionId, const QString& path) { lrc.getDataTransferModel().accept(interactionId, path, 0); storage::updateInteractionBody(db, interactionId, path); @@ -2197,7 +2205,7 @@ void ConversationModelPimpl::slotTransferStatusOngoing(long long dringId, datatransfer::Info info) { int interactionId; - std::string convId; + QString convId; if (not usefulDataFromDataTransfer(dringId, info, interactionId, convId)) return; @@ -2233,7 +2241,7 @@ void ConversationModelPimpl::slotTransferStatusFinished(long long dringId, datatransfer::Info info) { int interactionId; - std::string convId; + QString convId; if (not usefulDataFromDataTransfer(dringId, info, interactionId, convId)) return; @@ -2292,7 +2300,7 @@ void ConversationModelPimpl::updateTransferStatus(long long dringId, datatransfer::Info info, interaction::Status newStatus) { int interactionId; - std::string convId; + QString convId; if (not usefulDataFromDataTransfer(dringId, info, interactionId, convId)) return; @@ -2322,7 +2330,7 @@ ConversationModelPimpl::updateTransferStatus(long long dringId, datatransfer::In } void -ConversationModelPimpl::updateTransfer(QTimer* timer, const std::string& conversation, +ConversationModelPimpl::updateTransfer(QTimer* timer, const QString& conversation, int conversationIdx, int interactionId) { try { diff --git a/src/database.cpp b/src/database.cpp index c47ee726ec3f81946bf106150c2ecc5ccc301e9a..481dd6b84d14c52a17c3d78f4d9b8c65e6f42231 100644 --- a/src/database.cpp +++ b/src/database.cpp @@ -21,10 +21,15 @@ ***************************************************************************/ #include "database.h" -// daemon +#include "api/interaction.h" + +#include <account_const.h> + +// Lrc for migrations +#include "dbus/configurationmanager.h" +#include "vcard.h" #include <account_const.h> -// Qt #include <QObject> #include <QtCore/QDir> #include <QtCore/QDebug> @@ -37,17 +42,10 @@ #include <QtSql/QSqlRecord> #include <QtCore/QVariant> #include <QDir> +#include <QTextStream> -// Std #include <sstream> - -// Data -#include "api/interaction.h" - -// Lrc for migrations -#include "dbus/configurationmanager.h" -#include "vcard.h" -#include <account_const.h> +#include <stdexcept> namespace lrc { @@ -217,28 +215,28 @@ Database::getVersion() } int -Database::insertInto(const std::string& table, // "tests" - const std::map<std::string, std::string>& bindCol, // {{":id", "id"}, {":forename", "colforname"}, {":name", "colname"}} - const std::map<std::string, std::string>& bindsSet) // {{":id", "7"}, {":forename", "alice"}, {":name", "cooper"}} +Database::insertInto(const QString& table, // "tests" + const MapStringString& bindCol, // {{":id", "id"}, {":forename", "colforname"}, {":name", "colname"}} + const MapStringString& bindsSet) // {{":id", "7"}, {":forename", "alice"}, {":name", "cooper"}} { QSqlQuery query(db_); - std::string columns; - std::string binds; + QString columns; + QString binds; - for (const auto& entry : bindCol) { + for (const auto& entry : bindCol.toStdMap()) { columns += entry.second + ","; binds += entry.first + ","; } // remove the last ',' - columns.pop_back(); - binds.pop_back(); + columns.chop(1); + binds.chop(1); - auto prepareStr = std::string("INSERT INTO " + table + " (" + columns + ") VALUES (" + binds + ")"); - query.prepare(prepareStr.c_str()); + auto prepareStr = "INSERT INTO " + table + " (" + columns + ") VALUES (" + binds + ")"; + query.prepare(prepareStr); - for (const auto& entry : bindsSet) - query.bindValue(entry.first.c_str(), entry.second.c_str()); + for (const auto& entry : bindsSet.toStdMap()) + query.bindValue(entry.first, entry.second); if (not query.exec()) throw QueryInsertError(query, table, bindCol, bindsSet); @@ -253,72 +251,72 @@ Database::insertInto(const std::string& table, // "t } void -Database::update(const std::string& table, // "tests" - const std::string& set, // "location=:place, phone:=nmbr" - const std::map<std::string, std::string>& bindsSet, // {{":place", "montreal"}, {":nmbr", "514"}} - const std::string& where, // "contact=:name AND id=:id - const std::map<std::string, std::string>& bindsWhere) // {{":name", "toto"}, {":id", "65"}} +Database::update(const QString& table, // "tests" + const QString& set, // "location=:place, phone:=nmbr" + const MapStringString& bindsSet, // {{":place", "montreal"}, {":nmbr", "514"}} + const QString& where, // "contact=:name AND id=:id + const MapStringString& bindsWhere) // {{":name", "toto"}, {":id", "65"}} { QSqlQuery query(db_); - auto prepareStr = std::string("UPDATE " + table + " SET " + set + " WHERE " + where); - query.prepare(prepareStr.c_str()); + auto prepareStr = QString("UPDATE " + table + " SET " + set + " WHERE " + where); + query.prepare(prepareStr); - for (const auto& entry : bindsSet) - query.bindValue(entry.first.c_str(), entry.second.c_str()); + for (const auto& entry : bindsSet.toStdMap()) + query.bindValue(entry.first, entry.second); - for (const auto& entry : bindsWhere) - query.bindValue(entry.first.c_str(), entry.second.c_str()); + for (const auto& entry : bindsWhere.toStdMap()) + query.bindValue(entry.first, entry.second); if (not query.exec()) throw QueryUpdateError(query, table, set, bindsSet, where, bindsWhere); } Database::Result -Database::select(const std::string& select, // "id", "body", ... - const std::string& table, // "tests" - const std::string& where, // "contact=:name AND id=:id - const std::map<std::string, std::string>& bindsWhere) // {{":name", "toto"}, {":id", "65"}} +Database::select(const QString& select, // "id", "body", ... + const QString& table, // "tests" + const QString& where, // "contact=:name AND id=:id + const MapStringString& bindsWhere) // {{":name", "toto"}, {":id", "65"}} { QSqlQuery query(db_); - std::string columnsSelect; + QString columnsSelect; - auto prepareStr = std::string("SELECT " + select + " FROM " + table + - (where.empty() ? "" : (" WHERE " + where))); - query.prepare(prepareStr.c_str()); + auto prepareStr = QString("SELECT " + select + " FROM " + table + + (where.isEmpty() ? "" : (" WHERE " + where))); + query.prepare(prepareStr); - for (const auto& entry : bindsWhere) - query.bindValue(entry.first.c_str(), entry.second.c_str()); + for (const auto& entry : bindsWhere.toStdMap()) + query.bindValue(entry.first, entry.second); if (not query.exec()) throw QuerySelectError(query, select, table, where, bindsWhere); QSqlRecord rec = query.record(); const auto col_num = rec.count(); - Database::Result result = {col_num, std::vector<std::string>()}; + Database::Result result = {col_num, {}}; // for each row while (query.next()) { for (int i = 0 ; i < col_num ; i++) - result.payloads.emplace_back(query.value(i).toString().toStdString()); + result.payloads.push_back(query.value(i).toString()); } return result; } int -Database::count(const std::string& count, // "id", "body", ... - const std::string& table, // "tests" - const std::string& where, // "contact=:name AND id=:id" - const std::map<std::string, std::string>& bindsWhere) // {{":name", "toto"}, {":id", "65"}} +Database::count(const QString& count, // "id", "body", ... + const QString& table, // "tests" + const QString& where, // "contact=:name AND id=:id" + const MapStringString& bindsWhere) // {{":name", "toto"}, {":id", "65"}} { QSqlQuery query(db_); - std::string columnsSelect; - auto prepareStr = std::string("SELECT count(" + count + ") FROM " + table + " WHERE " + where); - query.prepare(prepareStr.c_str()); + QString columnsSelect; + auto prepareStr = QString("SELECT count(" + count + ") FROM " + table + " WHERE " + where); + query.prepare(prepareStr); - for (const auto& entry : bindsWhere) - query.bindValue(entry.first.c_str(), entry.second.c_str()); + for (const auto& entry : bindsWhere.toStdMap()) + query.bindValue(entry.first, entry.second); if (not query.exec()) throw QueryError(query); @@ -328,17 +326,17 @@ Database::count(const std::string& count, // "id", "body", ... } void -Database::deleteFrom(const std::string& table, // "tests" - const std::string& where, // "contact=:name AND id=:id - const std::map<std::string, std::string>& bindsWhere) // {{":name", "toto"}, {":id", "65"}} +Database::deleteFrom(const QString& table, // "tests" + const QString& where, // "contact=:name AND id=:id + const MapStringString& bindsWhere) // {{":name", "toto"}, {":id", "65"}} { QSqlQuery query(db_); - auto prepareStr = std::string("DELETE FROM " + table + " WHERE " + where); - query.prepare(prepareStr.c_str()); + auto prepareStr = QString("DELETE FROM " + table + " WHERE " + where); + query.prepare(prepareStr); - for (const auto& entry : bindsWhere) - query.bindValue(entry.first.c_str(), entry.second.c_str()); + for (const auto& entry : bindsWhere.toStdMap()) + query.bindValue(entry.first, entry.second); if(not query.exec()) throw QueryDeleteError(query, table, where, bindsWhere); @@ -350,110 +348,110 @@ Database::QueryError::QueryError(const QSqlQuery& query) {} Database::QueryInsertError::QueryInsertError(const QSqlQuery& query, - const std::string& table, - const std::map<std::string, std::string>& bindCol, - const std::map<std::string, std::string>& bindsSet) + const QString& table, + const MapStringString& bindCol, + const MapStringString& bindsSet) : QueryError(query) , table(table), bindCol(bindCol), bindsSet(bindsSet) {} -std::string +QString Database::QueryInsertError::details() { - std::ostringstream oss; - oss << "paramaters sent :"; - oss << "table = " << table.c_str(); - for (auto& b : bindCol) - oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; - for (auto& b : bindsSet) - oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; - return oss.str(); + QTextStream qts; + qts << "paramaters sent :"; + qts << "table = " << table; + for (auto& b : bindCol.toStdMap()) + qts << " {" << b.first << "}, {" << b.second <<"}"; + for (auto& b : bindsSet.toStdMap()) + qts << " {" << b.first << "}, {" << b.second <<"}"; + return qts.readAll(); } Database::QueryUpdateError::QueryUpdateError(const QSqlQuery& query, - const std::string& table, - const std::string& set, - const std::map<std::string, std::string>& bindsSet, - const std::string& where, - const std::map<std::string, std::string>& bindsWhere) + const QString& table, + const QString& set, + const MapStringString& bindsSet, + const QString& where, + const MapStringString& bindsWhere) : QueryError(query) , table(table), set(set), bindsSet(bindsSet), where(where), bindsWhere(bindsWhere) {} -std::string +QString Database::QueryUpdateError::details() { - std::ostringstream oss; - oss << "paramaters sent :"; - oss << "table = " << table.c_str(); - oss << "set = " << set.c_str(); - oss << "bindsSet :"; - for (auto& b : bindsSet) - oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; - oss << "where = " << where.c_str(); - oss << "bindsWhere :"; - for (auto& b : bindsWhere) - oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; - return oss.str(); + QTextStream qts; + qts << "paramaters sent :"; + qts << "table = " << table; + qts << "set = " << set; + qts << "bindsSet :"; + for (auto& b : bindsSet.toStdMap()) + qts << " {" << b.first << "}, {" << b.second <<"}"; + qts << "where = " << where; + qts << "bindsWhere :"; + for (auto& b : bindsWhere.toStdMap()) + qts << " {" << b.first << "}, {" << b.second <<"}"; + return qts.readAll(); } Database::QuerySelectError::QuerySelectError(const QSqlQuery& query, - const std::string& select, - const std::string& table, - const std::string& where, - const std::map<std::string, std::string>& bindsWhere) + const QString& select, + const QString& table, + const QString& where, + const MapStringString& bindsWhere) : QueryError(query) , select(select), table(table), where(where), bindsWhere(bindsWhere) {} -std::string +QString Database::QuerySelectError::details() { - std::ostringstream oss; - oss << "paramaters sent :"; - oss << "select = " << select.c_str(); - oss << "table = " << table.c_str(); - oss << "where = " << where.c_str(); - oss << "bindsWhere :"; - for (auto& b : bindsWhere) - oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; - return oss.str(); + QTextStream qts; + qts << "paramaters sent :"; + qts << "select = " << select; + qts << "table = " << table; + qts << "where = " << where; + qts << "bindsWhere :"; + for (auto& b : bindsWhere.toStdMap()) + qts << " {" << b.first << "}, {" << b.second << "}"; + return qts.readAll(); } Database::QueryDeleteError::QueryDeleteError(const QSqlQuery& query, - const std::string& table, - const std::string& where, - const std::map<std::string, std::string>& bindsWhere) + const QString& table, + const QString& where, + const MapStringString& bindsWhere) : QueryError(query) , table(table), where(where), bindsWhere(bindsWhere) {} -std::string +QString Database::QueryDeleteError::details() { - std::ostringstream oss; - oss << "paramaters sent :"; - oss << "table = " << table.c_str(); - oss << "where = " << where.c_str(); - oss << "bindsWhere :"; - for (auto& b : bindsWhere) - oss << " {" << b.first.c_str() << "}, {" << b.second.c_str() <<"}"; - return oss.str(); + QTextStream qts; + qts << "paramaters sent :"; + qts << "table = " << table; + qts << "where = " << where; + qts << "bindsWhere :"; + for (auto& b : bindsWhere.toStdMap()) + qts << " {" << b.first << "}, {" << b.second <<"}"; + return qts.readAll(); } Database::QueryTruncateError::QueryTruncateError(const QSqlQuery& query, - const std::string& table) + const QString& table) : QueryError(query) , table(table) {} -std::string +QString Database::QueryTruncateError::details() { - std::ostringstream oss; - oss << "paramaters sent :"; - oss << "table = " << table.c_str(); - return oss.str(); + QTextStream qts; + qts << "paramaters sent :"; + qts << "table = " << table; + return qts.readAll(); } /***************************************************************************** @@ -614,29 +612,28 @@ LegacyDatabase::migrateLocalProfiles() auto type = account[DRing::Account::ConfProperties::TYPE] == "SIP"? "SIP" : "RING"; auto uri = account[DRing::Account::ConfProperties::USERNAME].contains("ring:") ? - account[DRing::Account::ConfProperties::USERNAME] - .toStdString().substr(std::string("ring:").size()) : - account[DRing::Account::ConfProperties::USERNAME].toStdString(); + QString(account[DRing::Account::ConfProperties::USERNAME]).remove(0, QString("ring:").size()) : + account[DRing::Account::ConfProperties::USERNAME]; if (select("id", "profiles","uri=:uri", {{":uri", uri}}).payloads.empty()) { insertInto("profiles", {{":uri", "uri"}, {":alias", "alias"}, {":photo", "photo"}, {":type", "type"}, {":status", "status"}}, - {{":uri", uri}, {":alias", alias.toStdString()}, - {":photo", avatar.toStdString()}, {":type", type}, + {{":uri", uri}, {":alias", alias}, + {":photo", avatar}, {":type", type}, {":status", "TRUSTED"}}); auto profileIds = select("id", "profiles","uri=:uri", {{":uri", uri}}).payloads; if (!profileIds.empty() && select("profile_id", "profiles_accounts", "account_id=:account_id AND is_account=:is_account", - {{":account_id", accountId.toStdString()}, + {{":account_id", accountId}, {":is_account", "true"}}).payloads.empty()) { insertInto("profiles_accounts", {{":profile_id", "profile_id"}, {":account_id", "account_id"}, {":is_account", "is_account"}}, {{":profile_id", profileIds[0]}, - {":account_id", accountId.toStdString()}, + {":account_id", accountId}, {":is_account", "true"}}); } } @@ -667,17 +664,17 @@ LegacyDatabase::migratePeerProfiles() auto uri = vCard["TEL;other"]; const auto alias = vCard["FN"]; const auto avatar = vCard["PHOTO;ENCODING=BASE64;TYPE=PNG"]; - const std::string type = uri.startsWith("ring:") ? "RING" : "SIP"; + const QString type = uri.startsWith("ring:") ? "RING" : "SIP"; if (uri.startsWith("ring:")) { - uri = uri.mid(std::string("ring:").size()); + uri = uri.mid(QString("ring:").size()); } - if (select("id", "profiles","uri=:uri", {{":uri", uri.toStdString()}}).payloads.empty()) { + if (select("id", "profiles","uri=:uri", {{":uri", uri}}).payloads.empty()) { insertInto("profiles", {{":uri", "uri"}, {":alias", "alias"}, {":photo", "photo"}, {":type", "type"}, {":status", "status"}}, - {{":uri", uri.toStdString()}, {":alias", alias.toStdString()}, - {":photo", avatar.toStdString()}, {":type", type}, + {{":uri", uri}, {":alias", alias}, + {":photo", avatar}, {":type", type}, {":status", "TRUSTED"}}); } @@ -711,26 +708,29 @@ LegacyDatabase::migrateTextHistory() QJsonParseError err; auto loadDoc = QJsonDocument::fromJson(content.toUtf8(), &err).object(); - if (loadDoc.find("peers") == loadDoc.end()) continue; - if (loadDoc.find("groups") == loadDoc.end()) continue; + if (loadDoc.find("peers") == loadDoc.end()) + continue; + if (loadDoc.find("groups") == loadDoc.end()) + continue; // Load account auto peersObject = loadDoc["peers"].toArray()[0].toObject(); MapStringString details = ConfigurationManager::instance().getAccountDetails(peersObject["accountId"].toString()); - if (!details.contains(DRing::Account::ConfProperties::USERNAME)) continue; + if (!details.contains(DRing::Account::ConfProperties::USERNAME)) + continue; auto accountUri = details[DRing::Account::ConfProperties::USERNAME]; auto isARingContact = accountUri.startsWith("ring:"); if (isARingContact) { accountUri = accountUri.mid(QString("ring:").length()); } - auto accountIds = select("id", "profiles","uri=:uri", {{":uri", accountUri.toStdString()}}).payloads; - auto contactIds = select("id", "profiles","uri=:uri", {{":uri", peersObject["uri"].toString().toStdString()}}).payloads; + auto accountIds = select("id", "profiles","uri=:uri", {{":uri", accountUri}}).payloads; + auto contactIds = select("id", "profiles","uri=:uri", {{":uri", peersObject["uri"].toString()}}).payloads; if (contactIds.empty()) { insertInto("profiles", {{":uri", "uri"}, {":alias", "alias"}, {":photo", "photo"}, {":type", "type"}, {":status", "status"}}, - {{":uri", peersObject["uri"].toString().toStdString()}, {":alias", ""}, + {{":uri", peersObject["uri"].toString()}, {":alias", ""}, {":photo", ""}, {":type", "RING"}, {":status", "TRUSTED"}}); // NOTE: this profile is in a case where it's not a contact for the daemon but a conversation with an account. @@ -741,7 +741,7 @@ LegacyDatabase::migrateTextHistory() peersObject["uri"].toString() ); } - contactIds = select("id", "profiles","uri=:uri", {{":uri", peersObject["uri"].toString().toStdString()}}).payloads; + contactIds = select("id", "profiles","uri=:uri", {{":uri", peersObject["uri"].toString()}}).payloads; } if (accountIds.empty()) { qDebug() << "Can't find profile for URI: " << peersObject["accountId"].toString() << ". Ignore this file."; @@ -755,7 +755,7 @@ LegacyDatabase::migrateTextHistory() account_id=:account_id AND \ is_account=:is_account", {{":profile_id", contactId}, - {":account_id", peersObject["accountId"].toString().toStdString()}, + {":account_id", peersObject["accountId"].toString()}, {":is_account", "false"}}) .payloads; @@ -765,7 +765,7 @@ LegacyDatabase::migrateTextHistory() {":account_id", "account_id"}, {":is_account", "is_account"}}, {{":profile_id", contactId}, - {":account_id", peersObject["accountId"].toString().toStdString()}, + {":account_id", peersObject["accountId"].toString()}, {":is_account", "false"}}); } auto accountId = accountIds[0]; @@ -784,7 +784,7 @@ LegacyDatabase::migrateTextHistory() {{":id", newConversationsId}, {":participant_id", contactId}}); QSqlDatabase::database().commit(); } catch (QueryInsertError& e) { - qDebug() << e.details().c_str(); + qDebug() << e.details(); QSqlDatabase::database().rollback(); } @@ -803,8 +803,8 @@ LegacyDatabase::migrateTextHistory() {":status", "status"}}, {{":account_id", accountId}, {":author_id", direction ? accountId : contactId}, {":conversation_id", newConversationsId}, - {":timestamp", std::to_string(messageObject["timestamp"].toInt())}, - {":body", body.toStdString()}, {":type", "TEXT"}, + {":timestamp", messageObject["timestamp"].toString()}, + {":body", body}, {":type", "TEXT"}, {":status", direction ? "SUCCEED" : "READ"}}); } } @@ -856,9 +856,8 @@ LegacyDatabase::linkRingProfilesWithAccounts(bool contactsOnly) MapStringString account = ConfigurationManager::instance(). getAccountDetails(accountId.toStdString().c_str()); auto accountURI = account[DRing::Account::ConfProperties::USERNAME].contains("ring:") ? - account[DRing::Account::ConfProperties::USERNAME] - .toStdString().substr(std::string("ring:").size()) : - account[DRing::Account::ConfProperties::USERNAME].toStdString(); + QString(account[DRing::Account::ConfProperties::USERNAME]).remove(0, QString("ring:").size()) : + account[DRing::Account::ConfProperties::USERNAME]; auto profileIds = select("id", "profiles","uri=:uri", {{":uri", accountURI}}).payloads; if(profileIds.empty()) { continue; @@ -867,12 +866,12 @@ LegacyDatabase::linkRingProfilesWithAccounts(bool contactsOnly) //if is_account is true we should have only one profile id for account id if (select("profile_id", "profiles_accounts", "account_id=:account_id AND is_account=:is_account", - {{":account_id", accountId.toStdString()}, + {{":account_id", accountId}, {":is_account", "true"}}).payloads.empty()) { insertInto("profiles_accounts", {{":profile_id", "profile_id"}, {":account_id", "account_id"}, {":is_account", "is_account"}}, - {{":profile_id", profileIds[0]}, {":account_id", accountId.toStdString()}, + {{":profile_id", profileIds[0]}, {":account_id", accountId}, {":is_account", "true"}}); } } @@ -885,14 +884,14 @@ LegacyDatabase::linkRingProfilesWithAccounts(bool contactsOnly) //update contacts profiles for (auto contact_info : contacts_vector) { auto contactURI = contact_info["id"]; - updateProfileAccountForContact(contactURI.toStdString(), accountId.toStdString()); + updateProfileAccountForContact(contactURI, accountId); } //update pending contacts profiles const VectorMapStringString& pending_tr = ConfigurationManager::instance() .getTrustRequests(accountId.toStdString().c_str()); for (auto tr_info : pending_tr) { auto contactURI = tr_info[DRing::Account::TrustRequest::FROM]; - updateProfileAccountForContact(contactURI.toStdString(), accountId.toStdString()); + updateProfileAccountForContact(contactURI, accountId); } } else if (account[DRing::Account::ConfProperties::TYPE] == DRing::Account::ProtocolNames::SIP) { // update SIP contacts @@ -910,13 +909,13 @@ LegacyDatabase::linkRingProfilesWithAccounts(bool contactsOnly) account_id=:account_id AND \ is_account=:is_account", {{":profile_id", participant}, - {":account_id", accountId.toStdString()}, + {":account_id", accountId}, {":is_account", "false"}}).payloads; if (rows.empty()) { insertInto("profiles_accounts", {{":profile_id", "profile_id"}, {":account_id", "account_id"}, {":is_account", "is_account"}}, - {{":profile_id", participant}, {":account_id", accountId.toStdString()}, + {{":profile_id", participant}, {":account_id", accountId}, {":is_account", "false"}}); } } @@ -926,8 +925,8 @@ LegacyDatabase::linkRingProfilesWithAccounts(bool contactsOnly) } void -LegacyDatabase::updateProfileAccountForContact(const std::string& contactURI, - const std::string& accountId) +LegacyDatabase::updateProfileAccountForContact(const QString& contactURI, + const QString& accountId) { auto profileIds = select("id", "profiles", "uri=:uri", { {":uri", contactURI} }) diff --git a/src/database.h b/src/database.h index f467416de9891c03c6683a801224e2232bf5b235..284e0261e1da3f1242ba99342ad2f75657bfb241 100644 --- a/src/database.h +++ b/src/database.h @@ -21,6 +21,8 @@ ***************************************************************************/ #pragma once +#include "typedefs.h" + // Qt #include <QObject> #include <QtCore/QDir> @@ -69,7 +71,7 @@ public: * if nbrOfCols equals three and if the size of payloads equals six, * means two rows of data over three columns. */ - std::vector<std::string> payloads; ///< store the values. + VectorString payloads; ///< store the values. }; /** @@ -79,7 +81,7 @@ public: class QueryError : public std::runtime_error { public: explicit QueryError(const QSqlQuery& query); - virtual std::string details() { return {}; } + virtual QString details() { return {}; } const QSqlQuery query; }; @@ -91,14 +93,14 @@ public: class QueryInsertError final : public QueryError { public: explicit QueryInsertError(const QSqlQuery& query, - const std::string& table, - const std::map<std::string, std::string>& bindCol, - const std::map<std::string, std::string>& bindsSet); - std::string details() override; - - const std::string table; - const std::map<std::string, std::string> bindCol; - const std::map<std::string, std::string> bindsSet; + const QString& table, + const MapStringString& bindCol, + const MapStringString& bindsSet); + QString details() override; + + const QString table; + const MapStringString bindCol; + const MapStringString bindsSet; }; /** @@ -108,18 +110,18 @@ public: class QueryUpdateError final : public QueryError { public: explicit QueryUpdateError(const QSqlQuery& query, - const std::string& table, - const std::string& set, - const std::map<std::string, std::string>& bindsSet, - const std::string& where, - const std::map<std::string, std::string>& bindsWhere); - std::string details() override; - - const std::string table; - const std::string set; - const std::map<std::string, std::string> bindsSet; - const std::string where; - const std::map<std::string, std::string> bindsWhere; + const QString& table, + const QString& set, + const MapStringString& bindsSet, + const QString& where, + const MapStringString& bindsWhere); + QString details() override; + + const QString table; + const QString set; + const MapStringString bindsSet; + const QString where; + const MapStringString bindsWhere; }; /** @@ -129,16 +131,16 @@ public: class QuerySelectError final : public QueryError { public: explicit QuerySelectError(const QSqlQuery& query, - const std::string& select, - const std::string& table, - const std::string& where, - const std::map<std::string, std::string>& bindsWhere); - std::string details() override; - - const std::string select; - const std::string table; - const std::string where; - const std::map<std::string, std::string> bindsWhere; + const QString& select, + const QString& table, + const QString& where, + const MapStringString& bindsWhere); + QString details() override; + + const QString select; + const QString table; + const QString where; + const MapStringString bindsWhere; }; /** @@ -148,14 +150,14 @@ public: class QueryDeleteError final : public QueryError { public: explicit QueryDeleteError(const QSqlQuery& query, - const std::string& table, - const std::string& where, - const std::map<std::string, std::string>& bindsWhere); - std::string details() override; - - const std::string table; - const std::string where; - const std::map<std::string, std::string> bindsWhere; + const QString& table, + const QString& where, + const MapStringString& bindsWhere); + QString details() override; + + const QString table; + const QString where; + const MapStringString bindsWhere; }; /** @@ -165,10 +167,10 @@ public: class QueryTruncateError final : public QueryError { public: explicit QueryTruncateError(const QSqlQuery& query, - const std::string& table); - std::string details() override; + const QString& table); + QString details() override; - const std::string table; + const QString table; }; /** @@ -183,9 +185,9 @@ public: * * @note usually the identifiers has to be the same between bindCol and bindsSet */ - int insertInto(const std::string& table, - const std::map<std::string, std::string>& bindCol, - const std::map<std::string, std::string>& bindsSet); + int insertInto(const QString& table, + const MapStringString& bindCol, + const MapStringString& bindsSet); /** * Update value(s) inside a table. * @param table where to perfom the action on. @@ -199,11 +201,11 @@ public: * * @note usually, identifiers between set and bindsSet, are equals. The same goes between where and bindsWhere. */ - void update(const std::string& table, - const std::string& set, - const std::map<std::string, std::string>& bindsSet, - const std::string& where, - const std::map<std::string, std::string>& bindsWhere); + void update(const QString& table, + const QString& set, + const MapStringString& bindsSet, + const QString& where, + const MapStringString& bindsWhere); /** * Delete rows from a table. * @param table where to perfom the action on. @@ -214,9 +216,9 @@ public: * * @note usually, identifiers between where and bindsWhere, are equals. */ - void deleteFrom(const std::string& table, - const std::string& where, - const std::map<std::string, std::string>& bindsWhere); + void deleteFrom(const QString& table, + const QString& where, + const MapStringString& bindsWhere); /** * Select data from table. * @param select column(s) to select.e @@ -229,10 +231,10 @@ public: * * @note usually, identifiers between where and bindsWhere, are equals. */ - Database::Result select(const std::string& select, - const std::string& table, - const std::string& where, - const std::map<std::string, std::string>& bindsWhere); + Database::Result select(const QString& select, + const QString& table, + const QString& where, + const MapStringString& bindsWhere); /** * Returns the count of an expression. @@ -242,8 +244,10 @@ public: * @param bindsWhere specifies the value(s) to test using the identifier(s). The key is the identifier, it should * begin by ':'. The value is the value to test. */ - int count(const std::string& count, const std::string& table, - const std::string& where, const std::map<std::string, std::string>& bindsWhere); + int count(const QString& count, + const QString& table, + const QString& where, + const MapStringString& bindsWhere); QString basePath_; @@ -301,8 +305,8 @@ private: */ void migrateSchemaFromVersion1(); void linkRingProfilesWithAccounts(bool contactsOnly); - void updateProfileAccountForContact(const std::string& contactURI, - const std::string& accountID); + void updateProfileAccountForContact(const QString& contactURI, + const QString& accountID); }; namespace DatabaseFactory diff --git a/src/datatransfermodel.cpp b/src/datatransfermodel.cpp index 3456e99b891eb7b7febbedc2f394fe41315600ed..4c05ac4cbb8ad9a2c49214e669146f30baed3dff 100644 --- a/src/datatransfermodel.cpp +++ b/src/datatransfermodel.cpp @@ -64,8 +64,6 @@ class DataTransferModel::Impl : public QObject public: Impl(DataTransferModel& up_link); - std::vector<std::string> transferIdList() const; - DataTransferModel& upLink; std::map<long long, int> dring2lrcIdMap; std::map<int, long long> lrc2dringIdMap; // stricly the reverse map of dring2lrcIdMap @@ -91,21 +89,6 @@ DataTransferModel::DataTransferModel() DataTransferModel::~DataTransferModel() = default; -std::vector<std::string> -DataTransferModel::Impl::transferIdList() const -{ - VectorULongLong dring_list = ConfigurationManager::instance().dataTransferList(); - //~ for (auto dring_id : dring_list) { - //~ pimpl_->registerTransferId(dring_id); - //~ } - std::vector<std::string> result; - //~ result.reserve(dring_list.size()); - //~ for (auto& item : pimpl_->lrc2dringIdMap) { - //~ result.push_back(item.first); - //~ } - return result; -} - void DataTransferModel::transferInfo(long long ringId, datatransfer::Info& lrc_info) { @@ -116,10 +99,10 @@ DataTransferModel::transferInfo(long long ringId, datatransfer::Info& lrc_info) lrc_info.isOutgoing = !(infoFromDaemon.flags & (1 << uint32_t(DRing::DataTransferFlags::direction))); lrc_info.totalSize = infoFromDaemon.totalSize; lrc_info.progress = infoFromDaemon.bytesProgress; - lrc_info.path = infoFromDaemon.path.toStdString(); - lrc_info.displayName = infoFromDaemon.displayName.toStdString(); - lrc_info.accountId = infoFromDaemon.accountId.toStdString(); - lrc_info.peerUri = infoFromDaemon.peer.toStdString(); + lrc_info.path = infoFromDaemon.path; + lrc_info.displayName = infoFromDaemon.displayName; + lrc_info.accountId = infoFromDaemon.accountId; + lrc_info.peerUri = infoFromDaemon.peer; //lrc_info.timestamp = ? return; } @@ -128,15 +111,15 @@ DataTransferModel::transferInfo(long long ringId, datatransfer::Info& lrc_info) } void -DataTransferModel::sendFile(const std::string& account_id, const std::string& peer_uri, - const std::string& file_path, const std::string& display_name) +DataTransferModel::sendFile(const QString& account_id, const QString& peer_uri, + const QString& file_path, const QString& display_name) { DataTransferInfo info; qulonglong id; - info.accountId = QString::fromStdString(account_id); - info.peer = QString::fromStdString(peer_uri); - info.path = QString::fromStdString(file_path); - info.displayName = QString::fromStdString(display_name); + info.accountId = account_id; + info.peer = peer_uri; + info.path = file_path; + info.displayName = display_name; info.bytesProgress = 0; if (ConfigurationManager::instance().sendFile(info, id) != 0) { qDebug() << "DataTransferModel::sendFile(), error"; @@ -154,11 +137,11 @@ DataTransferModel::bytesProgress(int interactionId, int64_t& total, int64_t& pro void DataTransferModel::accept(int interactionId, - const std::string& file_path, + const QString& file_path, std::size_t offset) { auto dring_id = pimpl_->lrc2dringIdMap.at(interactionId); - ConfigurationManager::instance().acceptFileTransfer(dring_id, QString::fromStdString(file_path), offset); + ConfigurationManager::instance().acceptFileTransfer(dring_id, file_path, offset); } void diff --git a/src/dbus/configurationmanager.h b/src/dbus/configurationmanager.h index 630c099f7f671cdc5a4ccfc087c69a19bbf955b4..63c2fe91c5368c61c76915f699eac3ec0b7df5cb 100644 --- a/src/dbus/configurationmanager.h +++ b/src/dbus/configurationmanager.h @@ -26,6 +26,7 @@ #else #include "configurationmanager_dbus_interface.h" #include <QDBusPendingReply> + #include "../qtwrapper/conversions_wrap.hpp" #endif #endif #include <typedefs.h> diff --git a/src/directrenderer.cpp b/src/directrenderer.cpp index 3791ada8d804858a29becdc5c5023fd4cfb5f979..8f674737cb87eb6cfb7c50d705151af5e5829872 100644 --- a/src/directrenderer.cpp +++ b/src/directrenderer.cpp @@ -77,8 +77,8 @@ avframe{nullptr, AVFrameDeleter} } ///Constructor -Video::DirectRenderer::DirectRenderer(const QByteArray& id, const QSize& res, bool useAVFrame) : -Renderer(id, res), +Video::DirectRenderer::DirectRenderer(const QString& id, const QSize& res, bool useAVFrame) + : Renderer(id, res), d_ptr(std::make_unique<DirectRendererPrivate>(this, useAVFrame)) { setObjectName("Video::DirectRenderer:"+id); diff --git a/src/directrenderer.h b/src/directrenderer.h index 6bca16c3b89eb22e0baf76b93a193822c9b4b88c..aee01ffb5e058015fda427c74b16819d9687cd73 100644 --- a/src/directrenderer.h +++ b/src/directrenderer.h @@ -43,7 +43,7 @@ class LIB_EXPORT DirectRenderer final : public Renderer { public: //Constructor - DirectRenderer (const QByteArray& id, const QSize& res, bool useAVFrame); + DirectRenderer (const QString& id, const QSize& res, bool useAVFrame); virtual ~DirectRenderer(); //Getter diff --git a/src/lrc.cpp b/src/lrc.cpp index dd683ab7d88845cdadf54fe6633131ff77584e7f..26556e660b8d1f3ad1d4614210a7f0416755c4cd 100644 --- a/src/lrc.cpp +++ b/src/lrc.cpp @@ -144,52 +144,52 @@ Lrc::subscribeToDebugReceived() lrcPimpl_->callbackHandler->subscribeToDebugReceived(); } -std::vector<std::string> +VectorString Lrc::activeCalls() { QStringList callLists = CallManager::instance().getCallList(); - std::vector<std::string> result; + VectorString result; result.reserve(callLists.size()); for (const auto &call : callLists) { MapStringString callDetails = CallManager::instance().getCallDetails(call); if(!isFinished(callDetails[QString(DRing::Call::Details::CALL_STATE)])) - result.emplace_back(call.toStdString()); + result.push_back(call); } return result; } -std::vector<std::string> +VectorString Lrc::getCalls() { QStringList callLists = CallManager::instance().getCallList(); - std::vector<std::string> result; + VectorString result; result.reserve(callLists.size()); for (const auto &call : callLists) { - result.emplace_back(call.toStdString()); + result.push_back(call); } return result; } -std::vector<std::string> +VectorString Lrc::getConferences() { QStringList conferencesList = CallManager::instance().getConferenceList(); - std::vector<std::string> result; + VectorString result; result.reserve(conferencesList.size()); for (const auto &conf : conferencesList) { - result.emplace_back(conf.toStdString()); + result.push_back(conf); } return result; } -std::vector<std::string> -Lrc::getConferenceSubcalls(const std::string& cid) +VectorString +Lrc::getConferenceSubcalls(const QString& cid) { - QStringList callList = CallManager::instance().getParticipantList(cid.c_str()); - std::vector<std::string> result; + QStringList callList = CallManager::instance().getParticipantList(cid); + VectorString result; result.reserve(callList.size()); foreach(const auto& callId, callList) { - result.emplace_back(callId.toStdString()); + result.push_back(callId); } return result; } diff --git a/src/newaccountmodel.cpp b/src/newaccountmodel.cpp index f248e4be2660313cba847197117ee0298f2730ee..45d3adb8fe4679c2663a899dc7aae1d5b7337914 100644 --- a/src/newaccountmodel.cpp +++ b/src/newaccountmodel.cpp @@ -20,14 +20,6 @@ ***************************************************************************/ #include "api/newaccountmodel.h" -// daemon -#include <account_const.h> - -//qt -#include <QtGui/QPixmap> -#include <QtGui/QImage> -#include <QtCore/QBuffer> - // new LRC #include "api/lrc.h" #include "api/contactmodel.h" @@ -49,6 +41,14 @@ // Dbus #include "dbus/configurationmanager.h" +// daemon +#include <account_const.h> + +//qt +#include <QtGui/QPixmap> +#include <QtGui/QImage> +#include <QtCore/QBuffer> + #include <atomic> namespace lrc @@ -68,7 +68,7 @@ public: MigrationCb& didMigrateCb); ~NewAccountModelPimpl(); - using AccountInfoDbMap = std::map<std::string, + using AccountInfoDbMap = std::map<QString, std::pair<account::Info, std::shared_ptr<Database>>>; NewAccountModel& linked; @@ -82,7 +82,7 @@ public: std::mutex m_mutex_account_removal; std::condition_variable m_condVar_account_removal; std::atomic_bool username_changed; - std::string new_username; + QString new_username; /** * Add the profile information from an account to the db then add it to accounts. @@ -90,13 +90,13 @@ public: * @param db an optional migrated database object * @note this method get details for an account from the daemon. */ - void addToAccounts(const std::string& accountId, std::shared_ptr<Database> db = nullptr); + void addToAccounts(const QString& accountId, std::shared_ptr<Database> db = nullptr); /** * Remove account from accounts list. Emit accountRemoved. * @param accountId */ - void removeFromAccounts(const std::string& accountId); + void removeFromAccounts(const QString& accountId); /** * Sync changes to the accounts list with the lrc. @@ -110,7 +110,7 @@ public Q_SLOTS: * @param accountId * @param status */ - void slotAccountStatusChanged(const std::string& accountID, const api::account::Status status); + void slotAccountStatusChanged(const QString& accountID, const api::account::Status status); /** * Emit exportOnRingEnded. @@ -118,19 +118,19 @@ public Q_SLOTS: * @param status * @param pin */ - void slotExportOnRingEnded(const std::string& accountID, int status, const std::string& pin); + void slotExportOnRingEnded(const QString& accountID, int status, const QString& pin); /** * @param accountId * @param details */ - void slotAccountDetailsChanged(const std::string& accountID, const std::map<std::string, std::string>& details); + void slotAccountDetailsChanged(const QString& accountID, const MapStringString& details); /** * @param accountId * @param details */ - void slotVolatileAccountDetailsChanged(const std::string& accountID, const std::map<std::string, std::string>& details); + void slotVolatileAccountDetailsChanged(const QString& accountID, const MapStringString& details); /** * Emit nameRegistrationEnded @@ -138,7 +138,7 @@ public Q_SLOTS: * @param status * @param name */ - void slotNameRegistrationEnded(const std::string& accountId, int status, const std::string& name); + void slotNameRegistrationEnded(const QString& accountId, int status, const QString& name); /** * Emit registeredNameFound @@ -147,14 +147,14 @@ public Q_SLOTS: * @param address * @param name */ - void slotRegisteredNameFound(const std::string& accountId, int status, const std::string& address, const std::string& name); + void slotRegisteredNameFound(const QString& accountId, int status, const QString& address, const QString& name); /** * Emit migrationEnded * @param accountId * @param ok */ - void slotMigrationEnded(const std::string& accountId, bool ok); + void slotMigrationEnded(const QString& accountId, bool ok); }; NewAccountModel::NewAccountModel(Lrc& lrc, @@ -172,41 +172,41 @@ NewAccountModel::~NewAccountModel() { } -std::vector<std::string> +QStringList NewAccountModel::getAccountList() const { - std::vector<std::string> accountsId; + QStringList filteredAccountIds; const QStringList accountIds = ConfigurationManager::instance().getAccountList(); for (auto const& id : accountIds) { - auto account = pimpl_->accounts.find(id.toStdString()); + auto account = pimpl_->accounts.find(id); // Do not include accounts flagged for removal if (account != pimpl_->accounts.end() && account->second.first.valid) - accountsId.emplace_back(id.toStdString()); + filteredAccountIds.push_back(id); } - return accountsId; + return filteredAccountIds; } void -NewAccountModel::setAccountEnabled(const std::string& accountId, bool enabled) const +NewAccountModel::setAccountEnabled(const QString& accountId, bool enabled) const { auto account = pimpl_->accounts.find(accountId); if (account == pimpl_->accounts.end()) { - throw std::out_of_range("NewAccountModel::getAccountConfig, can't find " + accountId); + throw std::out_of_range("NewAccountModel::getAccountConfig, can't find " + accountId.toStdString()); } auto& accountInfo = account->second.first; accountInfo.enabled = enabled; - ConfigurationManager::instance().sendRegister(QString::fromStdString(accountId), enabled); + ConfigurationManager::instance().sendRegister(accountId, enabled); } void -NewAccountModel::setAccountConfig(const std::string& accountId, +NewAccountModel::setAccountConfig(const QString& accountId, const account::ConfProperties_t& confProperties) const { auto account = pimpl_->accounts.find(accountId); if (account == pimpl_->accounts.end()) { - throw std::out_of_range("NewAccountModel::save, can't find " + accountId); + throw std::out_of_range("NewAccountModel::save, can't find " + accountId.toStdString()); } auto& accountInfo = account->second.first; auto& configurationManager = ConfigurationManager::instance(); @@ -215,54 +215,54 @@ NewAccountModel::setAccountConfig(const std::string& accountId, // TODO: move these into the ConfProperties_t struct ? using namespace DRing::Account; qDebug("UPNP_ENABLED: %s\n", details[ConfProperties::UPNP_ENABLED].toStdString().c_str()); - details[ConfProperties::ENABLED] = toQString(accountInfo.enabled); - details[ConfProperties::ALIAS] = toQString(accountInfo.profileInfo.alias); - details[ConfProperties::DISPLAYNAME] = toQString(accountInfo.profileInfo.alias); + details[ConfProperties::ENABLED] = accountInfo.enabled ? QString("true") : QString ("false"); + details[ConfProperties::ALIAS] = accountInfo.profileInfo.alias; + details[ConfProperties::DISPLAYNAME] = accountInfo.profileInfo.alias; details[ConfProperties::TYPE] = (accountInfo.profileInfo.type == profile::Type::RING) ? QString(ProtocolNames::RING) : QString(ProtocolNames::SIP); if (accountInfo.profileInfo.type == profile::Type::RING) { - details[ConfProperties::USERNAME] = toQString(accountInfo.profileInfo.uri).prepend((accountInfo.profileInfo.type == profile::Type::RING) ? "ring:" : ""); + details[ConfProperties::USERNAME] = accountInfo.profileInfo.uri.prepend((accountInfo.profileInfo.type == profile::Type::RING) ? "ring:" : ""); } else if (accountInfo.profileInfo.type == profile::Type::SIP) { VectorMapStringString finalCred; - std::map<std::string, std::string> credentials; + MapStringString credentials; credentials[ConfProperties::USERNAME] = confProperties.username; credentials[ConfProperties::PASSWORD] = confProperties.password; - credentials[ConfProperties::REALM] = confProperties.realm.empty() ? "*" : confProperties.realm; + credentials[ConfProperties::REALM] = confProperties.realm.isEmpty() ? "*" : confProperties.realm; auto credentialsVec = confProperties.credentials; credentialsVec[0] = credentials; for (auto const &i : credentialsVec) { QMap<QString, QString> credMap; - for (auto const &j : i) { - credMap[j.first.c_str()] = j.second.c_str(); + for (auto const &j : i.toStdMap()) { + credMap[j.first] = j.second; } finalCred.append(credMap); } - ConfigurationManager::instance().setCredentials(accountId.c_str(), finalCred); - details[ConfProperties::USERNAME] = toQString(confProperties.username); + ConfigurationManager::instance().setCredentials(accountId, finalCred); + details[ConfProperties::USERNAME] = confProperties.username; accountInfo.confProperties.credentials.swap(credentialsVec); } - configurationManager.setAccountDetails(QString::fromStdString(accountId), details); + configurationManager.setAccountDetails(accountId, details); } account::ConfProperties_t -NewAccountModel::getAccountConfig(const std::string& accountId) const +NewAccountModel::getAccountConfig(const QString& accountId) const { auto account = pimpl_->accounts.find(accountId); if (account == pimpl_->accounts.end()) { - throw std::out_of_range("NewAccountModel::getAccountConfig, can't find " + accountId); + throw std::out_of_range("NewAccountModel::getAccountConfig, can't find " + accountId.toStdString()); } auto& accountInfo = account->second.first; return accountInfo.confProperties; } void -NewAccountModel::setAlias(const std::string& accountId, const std::string& alias) +NewAccountModel::setAlias(const QString& accountId, const QString& alias) { auto account = pimpl_->accounts.find(accountId); if (account == pimpl_->accounts.end()) { - throw std::out_of_range("NewAccountModel::setAlias, can't find " + accountId); + throw std::out_of_range("NewAccountModel::setAlias, can't find " + accountId.toStdString()); } auto& accountInfo = account->second.first; accountInfo.profileInfo.alias = alias; @@ -273,11 +273,11 @@ NewAccountModel::setAlias(const std::string& accountId, const std::string& alias } void -NewAccountModel::setAvatar(const std::string& accountId, const std::string& avatar) +NewAccountModel::setAvatar(const QString& accountId, const QString& avatar) { auto account = pimpl_->accounts.find(accountId); if (account == pimpl_->accounts.end()) { - throw std::out_of_range("NewAccountModel::setAvatar, can't find " + accountId); + throw std::out_of_range("NewAccountModel::setAvatar, can't find " + accountId.toStdString()); } auto& accountInfo = account->second.first; accountInfo.profileInfo.avatar = avatar; @@ -288,44 +288,44 @@ NewAccountModel::setAvatar(const std::string& accountId, const std::string& avat } bool -NewAccountModel::registerName(const std::string& accountId, const std::string& password, const std::string& username) +NewAccountModel::registerName(const QString& accountId, const QString& password, const QString& username) { - return ConfigurationManager::instance().registerName(accountId.c_str(), password.c_str(), username.c_str()); + return ConfigurationManager::instance().registerName(accountId, password, username); } bool -NewAccountModel::exportToFile(const std::string& accountId, const std::string& path, const std::string& password) const +NewAccountModel::exportToFile(const QString& accountId, const QString& path, const QString& password) const { - return ConfigurationManager::instance().exportToFile(accountId.c_str(), path.c_str(), password.c_str()); + return ConfigurationManager::instance().exportToFile(accountId, path, password); } bool -NewAccountModel::exportOnRing(const std::string& accountId, const std::string& password) const +NewAccountModel::exportOnRing(const QString& accountId, const QString& password) const { - return ConfigurationManager::instance().exportOnRing(accountId.c_str(), password.c_str()); + return ConfigurationManager::instance().exportOnRing(accountId, password); } void -NewAccountModel::removeAccount(const std::string& accountId) const +NewAccountModel::removeAccount(const QString& accountId) const { - ConfigurationManager::instance().removeAccount(accountId.c_str()); + ConfigurationManager::instance().removeAccount(accountId); } bool -NewAccountModel::changeAccountPassword(const std::string& accountId, - const std::string& currentPassword, - const std::string& newPassword) const +NewAccountModel::changeAccountPassword(const QString& accountId, + const QString& currentPassword, + const QString& newPassword) const { return ConfigurationManager::instance() - .changeAccountPassword(accountId.c_str(), currentPassword.c_str(), newPassword.c_str()); + .changeAccountPassword(accountId, currentPassword, newPassword); } void -NewAccountModel::flagFreeable(const std::string& accountId) const +NewAccountModel::flagFreeable(const QString& accountId) const { auto account = pimpl_->accounts.find(accountId); if (account == pimpl_->accounts.end()) - throw std::out_of_range("NewAccountModel::flagFreeable, can't find " + accountId); + throw std::out_of_range("NewAccountModel::flagFreeable, can't find " + accountId.toStdString()); { std::lock_guard<std::mutex> lock(pimpl_->m_mutex_account_removal); @@ -335,11 +335,11 @@ NewAccountModel::flagFreeable(const std::string& accountId) const } const account::Info& -NewAccountModel::getAccountInfo(const std::string& accountId) const +NewAccountModel::getAccountInfo(const QString& accountId) const { auto accountInfo = pimpl_->accounts.find(accountId); if (accountInfo == pimpl_->accounts.end()) - throw std::out_of_range("NewAccountModel::getAccountInfo, can't find " + accountId); + throw std::out_of_range("NewAccountModel::getAccountInfo, can't find " + accountId.toStdString()); return accountInfo->second.first; } @@ -369,7 +369,7 @@ NewAccountModelPimpl::NewAccountModelPimpl(NewAccountModel& linked, auto accountDbs = authority::storage::migrateIfNeeded(accountIds, willMigrateCb, didMigrateCb); for (const auto& id : accountIds) { - addToAccounts(id.toStdString(), accountDbs.at(accountIds.indexOf(id))); + addToAccounts(id, accountDbs.at(accountIds.indexOf(id))); } connect(&callbacksHandler, &CallbacksHandler::accountsChanged, this, &NewAccountModelPimpl::updateAccounts); @@ -394,11 +394,11 @@ NewAccountModelPimpl::updateAccounts() QStringList accountIds = configurationManager.getAccountList(); // Detect removed accounts - std::list<std::string> toBeRemoved; + QStringList toBeRemoved; for (auto& it : accounts) { auto& accountInfo = it.second.first; - if (!accountIds.contains(QString::fromStdString(accountInfo.id))) { - qDebug("detected account removal %s", accountInfo.id.c_str()); + if (!accountIds.contains(accountInfo.id)) { + qDebug() << QString("detected account removal %s").arg(accountInfo.id); toBeRemoved.push_back(accountInfo.id); } } @@ -409,14 +409,14 @@ NewAccountModelPimpl::updateAccounts() // Detect new accounts for (auto& id : accountIds) { - auto account = accounts.find(id.toStdString()); + auto account = accounts.find(id); // NOTE: If the daemon is down, but dbus answered, id can contains // "Remote peer disconnected", "The name is not activable", etc. // So avoid to create useless directories. if (account == accounts.end() && id.indexOf(" ") == -1) { - qDebug("detected new account %s", id.toStdString().c_str()); - addToAccounts(id.toStdString()); - auto updatedAccount = accounts.find(id.toStdString()); + qDebug() << QString("detected new account %s").arg(id); + addToAccounts(id); + auto updatedAccount = accounts.find(id); if (updatedAccount == accounts.end()) { return; } @@ -424,14 +424,14 @@ NewAccountModelPimpl::updateAccounts() // NOTE: At this point, a SIP account is ready, but not a Ring // account. Indeed, the keys are not generated at this point. // See slotAccountStatusChanged for more details. - emit linked.accountAdded(id.toStdString()); + emit linked.accountAdded(id); } } } } void -NewAccountModelPimpl::slotAccountStatusChanged(const std::string& accountID, const api::account::Status status) +NewAccountModelPimpl::slotAccountStatusChanged(const QString& accountID, const api::account::Status status) { if (status == api::account::Status::INVALID) { emit linked.invalidAccountDetected(accountID); @@ -455,7 +455,7 @@ NewAccountModelPimpl::slotAccountStatusChanged(const std::string& accountID, con accounts.erase(accountID); addToAccounts(accountID); emit linked.accountAdded(accountID); - } else if (!accountInfo.profileInfo.uri.empty()) { + } else if (!accountInfo.profileInfo.uri.isEmpty()) { accountInfo.status = status; emit linked.accountStatusChanged(accountID); } @@ -466,14 +466,14 @@ NewAccountModelPimpl::slotAccountStatusChanged(const std::string& accountID, con } void -NewAccountModelPimpl::slotAccountDetailsChanged(const std::string& accountId, const std::map<std::string, std::string>& details) +NewAccountModelPimpl::slotAccountDetailsChanged(const QString& accountId, const MapStringString& details) { auto account = accounts.find(accountId); if (account == accounts.end()) { - throw std::out_of_range("NewAccountModelPimpl::slotAccountDetailsChanged, can't find " + accountId); + throw std::out_of_range("NewAccountModelPimpl::slotAccountDetailsChanged, can't find " + accountId.toStdString()); } auto& accountInfo = account->second.first; - accountInfo.fromDetails(convertMap(details)); + accountInfo.fromDetails(details); if (username_changed) { username_changed = false; accountInfo.registeredName = new_username; @@ -483,11 +483,11 @@ NewAccountModelPimpl::slotAccountDetailsChanged(const std::string& accountId, co } void -NewAccountModelPimpl::slotVolatileAccountDetailsChanged(const std::string& accountId, const std::map<std::string, std::string>& details) +NewAccountModelPimpl::slotVolatileAccountDetailsChanged(const QString& accountId, const MapStringString& details) { auto account = accounts.find(accountId); if (account == accounts.end()) { - qWarning() << "NewAccountModelPimpl::slotVolatileAccountDetailsChanged, can't find " << accountId.c_str(); + qWarning() << "NewAccountModelPimpl::slotVolatileAccountDetailsChanged, can't find " << accountId; return; } auto& accountInfo = account->second.first; @@ -495,12 +495,12 @@ NewAccountModelPimpl::slotVolatileAccountDetailsChanged(const std::string& accou auto new_usernameIt = details.find(DRing::Account::VolatileProperties::REGISTERED_NAME); if (new_usernameIt == details.end()) return; - accountInfo.registeredName = new_usernameIt->second; + accountInfo.registeredName = new_usernameIt.value(); emit linked.profileUpdated(accountId); } void -NewAccountModelPimpl::slotExportOnRingEnded(const std::string& accountID, int status, const std::string& pin) +NewAccountModelPimpl::slotExportOnRingEnded(const QString& accountID, int status, const QString& pin) { account::ExportOnRingStatus convertedStatus = account::ExportOnRingStatus::INVALID; switch (status) { @@ -520,7 +520,7 @@ NewAccountModelPimpl::slotExportOnRingEnded(const std::string& accountID, int st } void -NewAccountModelPimpl::slotNameRegistrationEnded(const std::string& accountId, int status, const std::string& name) +NewAccountModelPimpl::slotNameRegistrationEnded(const QString& accountId, int status, const QString& name) { account::RegisterNameStatus convertedStatus = account::RegisterNameStatus::INVALID; switch (status) @@ -528,7 +528,7 @@ NewAccountModelPimpl::slotNameRegistrationEnded(const std::string& accountId, in case 0: { convertedStatus = account::RegisterNameStatus::SUCCESS; auto account = accounts.find(accountId); - if (account != accounts.end() && account->second.first.registeredName.empty()) { + if (account != accounts.end() && account->second.first.registeredName.isEmpty()) { auto conf = linked.getAccountConfig(accountId); username_changed = true; new_username = name; @@ -555,7 +555,7 @@ NewAccountModelPimpl::slotNameRegistrationEnded(const std::string& accountId, in } void -NewAccountModelPimpl::slotRegisteredNameFound(const std::string& accountId, int status, const std::string& address, const std::string& name) +NewAccountModelPimpl::slotRegisteredNameFound(const QString& accountId, int status, const QString& address, const QString& name) { account::LookupStatus convertedStatus = account::LookupStatus::INVALID; switch (status) @@ -579,7 +579,7 @@ NewAccountModelPimpl::slotRegisteredNameFound(const std::string& accountId, int } void -NewAccountModelPimpl::slotMigrationEnded(const std::string& accountId, bool ok) +NewAccountModelPimpl::slotMigrationEnded(const QString& accountId, bool ok) { if (ok) { auto it = accounts.find(accountId); @@ -588,26 +588,26 @@ NewAccountModelPimpl::slotMigrationEnded(const std::string& accountId, bool ok) return; } auto& accountInfo = it->second.first; - MapStringString details = ConfigurationManager::instance().getAccountDetails(accountId.c_str()); + MapStringString details = ConfigurationManager::instance().getAccountDetails(accountId); accountInfo.fromDetails(details); - MapStringString volatileDetails = ConfigurationManager::instance().getVolatileAccountDetails(accountId.c_str()); - std::string daemonStatus = volatileDetails[DRing::Account::ConfProperties::Registration::STATUS].toStdString(); + MapStringString volatileDetails = ConfigurationManager::instance().getVolatileAccountDetails(accountId); + QString daemonStatus = volatileDetails[DRing::Account::ConfProperties::Registration::STATUS]; accountInfo.status = lrc::api::account::to_status(daemonStatus); } emit linked.migrationEnded(accountId, ok); } void -NewAccountModelPimpl::addToAccounts(const std::string& accountId, +NewAccountModelPimpl::addToAccounts(const QString& accountId, std::shared_ptr<Database> db) { if (db == nullptr) { try { auto appPath = authority::storage::getPath(); - auto dbName = QString::fromStdString(accountId + "/history"); + auto dbName = accountId + "/history"; db = DatabaseFactory::create<Database>(dbName, appPath); // create the profiles path if necessary - QDir profilesDir(appPath + QString::fromStdString(accountId) + "/profiles"); + QDir profilesDir(appPath + accountId + "/profiles"); if (!profilesDir.exists()) { profilesDir.mkpath("."); } @@ -630,18 +630,18 @@ NewAccountModelPimpl::addToAccounts(const std::string& accountId, newAccInfo.profileInfo.avatar = authority::storage::getAccountAvatar(accountId); // Fill account::Info struct with details from daemon - MapStringString details = ConfigurationManager::instance().getAccountDetails(accountId.c_str()); + MapStringString details = ConfigurationManager::instance().getAccountDetails(accountId); newAccInfo.fromDetails(details); // Fill account::Info::confProperties credentials - VectorMapStringString credGet = ConfigurationManager::instance().getCredentials(accountId.c_str()); - std::vector<std::map<std::string, std::string>> credToStore; + VectorMapStringString credGet = ConfigurationManager::instance().getCredentials(accountId); + VectorMapStringString credToStore; for (auto const &i : credGet.toStdVector()) { - std::map<std::string, std::string> credMap; + MapStringString credMap; for (auto const &j : i.toStdMap()) { - credMap[j.first.toStdString()] = j.second.toStdString(); + credMap[j.first] = j.second; } - credToStore.emplace_back(credMap); + credToStore.push_back(credMap); } newAccInfo.confProperties.credentials.swap(credToStore); @@ -655,13 +655,13 @@ NewAccountModelPimpl::addToAccounts(const std::string& accountId, newAccInfo.deviceModel = std::make_unique<NewDeviceModel>(newAccInfo, callbacksHandler); newAccInfo.codecModel = std::make_unique<NewCodecModel>(newAccInfo, callbacksHandler); - MapStringString volatileDetails = ConfigurationManager::instance().getVolatileAccountDetails(accountId.c_str()); - std::string daemonStatus = volatileDetails[DRing::Account::ConfProperties::Registration::STATUS].toStdString(); + MapStringString volatileDetails = ConfigurationManager::instance().getVolatileAccountDetails(accountId); + auto daemonStatus = volatileDetails[DRing::Account::ConfProperties::Registration::STATUS]; newAccInfo.status = lrc::api::account::to_status(daemonStatus); } void -NewAccountModelPimpl::removeFromAccounts(const std::string& accountId) +NewAccountModelPimpl::removeFromAccounts(const QString& accountId) { /* Update db before waiting for the client to stop using the structs is fine as long as we don't free anything */ @@ -691,46 +691,46 @@ void account::Info::fromDetails(const MapStringString& details) { using namespace DRing::Account; - const MapStringString volatileDetails = ConfigurationManager::instance().getVolatileAccountDetails(id.c_str()); + const MapStringString volatileDetails = ConfigurationManager::instance().getVolatileAccountDetails(id); // General if (details[ConfProperties::TYPE] != "") profileInfo.type = details[ConfProperties::TYPE] == QString(ProtocolNames::RING) ? profile::Type::RING : profile::Type::SIP; - registeredName = profileInfo.type == profile::Type::RING ? volatileDetails[VolatileProperties::REGISTERED_NAME].toStdString() : ""; - profileInfo.alias = toStdString(details[ConfProperties::DISPLAYNAME]); + registeredName = profileInfo.type == profile::Type::RING ? volatileDetails[VolatileProperties::REGISTERED_NAME] : ""; + profileInfo.alias = details[ConfProperties::DISPLAYNAME]; enabled = toBool(details[ConfProperties::ENABLED]); - confProperties.mailbox = toStdString(details[ConfProperties::MAILBOX]); - confProperties.dtmfType = toStdString(details[ConfProperties::DTMF_TYPE]); + confProperties.mailbox = details[ConfProperties::MAILBOX]; + confProperties.dtmfType = details[ConfProperties::DTMF_TYPE]; confProperties.autoAnswer = toBool(details[ConfProperties::AUTOANSWER]); confProperties.activeCallLimit = toInt(details[ConfProperties::ACTIVE_CALL_LIMIT]); - confProperties.hostname = toStdString(details[ConfProperties::HOSTNAME]); + confProperties.hostname = details[ConfProperties::HOSTNAME]; profileInfo.uri = (profileInfo.type == profile::Type::RING and details[ConfProperties::USERNAME].contains("ring:")) - ? details[ConfProperties::USERNAME].toStdString().substr(std::string("ring:").size()) - : details[ConfProperties::USERNAME].toStdString(); - confProperties.username = toStdString(details[ConfProperties::USERNAME]); - confProperties.routeset = toStdString(details[ConfProperties::ROUTE]); - confProperties.password = toStdString(details[ConfProperties::PASSWORD]); - confProperties.realm = toStdString(details[ConfProperties::REALM]); - confProperties.localInterface = toStdString(details[ConfProperties::LOCAL_INTERFACE]); - confProperties.deviceId = toStdString(details[ConfProperties::RING_DEVICE_ID]); - confProperties.deviceName = toStdString(details[ConfProperties::RING_DEVICE_NAME]); + ? QString(details[ConfProperties::USERNAME]).remove(QString("ring:")) + : details[ConfProperties::USERNAME]; + confProperties.username = details[ConfProperties::USERNAME]; + confProperties.routeset = details[ConfProperties::ROUTE]; + confProperties.password = details[ConfProperties::PASSWORD]; + confProperties.realm = details[ConfProperties::REALM]; + confProperties.localInterface = details[ConfProperties::LOCAL_INTERFACE]; + confProperties.deviceId = details[ConfProperties::RING_DEVICE_ID]; + confProperties.deviceName = details[ConfProperties::RING_DEVICE_NAME]; confProperties.publishedSameAsLocal = toBool(details[ConfProperties::PUBLISHED_SAMEAS_LOCAL]); confProperties.localPort = toInt(details[ConfProperties::LOCAL_PORT]); confProperties.publishedPort = toInt(details[ConfProperties::PUBLISHED_PORT]); - confProperties.publishedAddress = toStdString(details[ConfProperties::PUBLISHED_ADDRESS]); - confProperties.userAgent = toStdString(details[ConfProperties::USER_AGENT]); + confProperties.publishedAddress = details[ConfProperties::PUBLISHED_ADDRESS]; + confProperties.userAgent = details[ConfProperties::USER_AGENT]; confProperties.upnpEnabled = toBool(details[ConfProperties::UPNP_ENABLED]); confProperties.hasCustomUserAgent = toBool(details[ConfProperties::HAS_CUSTOM_USER_AGENT]); confProperties.allowIncoming = toBool(details[ConfProperties::ALLOW_CERT_FROM_HISTORY]) | toBool(details[ConfProperties::ALLOW_CERT_FROM_CONTACT]) | toBool(details[ConfProperties::ALLOW_CERT_FROM_TRUSTED]); - confProperties.archivePassword = toStdString(details[ConfProperties::ARCHIVE_PASSWORD]); + confProperties.archivePassword = details[ConfProperties::ARCHIVE_PASSWORD]; confProperties.archiveHasPassword = toBool(details[ConfProperties::ARCHIVE_HAS_PASSWORD]); - confProperties.archivePath = toStdString(details[ConfProperties::ARCHIVE_PATH]); - confProperties.archivePin = toStdString(details[ConfProperties::ARCHIVE_PIN]); + confProperties.archivePath = details[ConfProperties::ARCHIVE_PATH]; + confProperties.archivePin = details[ConfProperties::ARCHIVE_PIN]; confProperties.proxyEnabled = toBool(details[ConfProperties::PROXY_ENABLED]); - confProperties.proxyServer = toStdString(details[ConfProperties::PROXY_SERVER]); - confProperties.proxyPushToken = toStdString(details[ConfProperties::PROXY_PUSH_TOKEN]); + confProperties.proxyServer = details[ConfProperties::PROXY_SERVER]; + confProperties.proxyPushToken = details[ConfProperties::PROXY_PUSH_TOKEN]; confProperties.peerDiscovery = toBool(details[ConfProperties::DHT_PEER_DISCOVERY]); confProperties.accountDiscovery = toBool(details[ConfProperties::ACCOUNT_PEER_DISCOVERY]); confProperties.accountPublish = toBool(details[ConfProperties::ACCOUNT_PUBLISH]); @@ -742,33 +742,33 @@ account::Info::fromDetails(const MapStringString& details) confProperties.Video.videoPortMax = toInt(details[ConfProperties::Video::PORT_MAX]); confProperties.Video.videoPortMin = toInt(details[ConfProperties::Video::PORT_MIN]); // STUN - confProperties.STUN.server = toStdString(details[ConfProperties::STUN::SERVER]); + confProperties.STUN.server = details[ConfProperties::STUN::SERVER]; confProperties.STUN.enable = toBool(details[ConfProperties::STUN::ENABLED]); // TURN - confProperties.TURN.server = toStdString(details[ConfProperties::TURN::SERVER]); + confProperties.TURN.server = details[ConfProperties::TURN::SERVER]; confProperties.TURN.enable = toBool(details[ConfProperties::TURN::ENABLED]); - confProperties.TURN.username = toStdString(details[ConfProperties::TURN::SERVER_UNAME]); - confProperties.TURN.password = toStdString(details[ConfProperties::TURN::SERVER_PWD]); - confProperties.TURN.realm = toStdString(details[ConfProperties::TURN::SERVER_REALM]); + confProperties.TURN.username = details[ConfProperties::TURN::SERVER_UNAME]; + confProperties.TURN.password = details[ConfProperties::TURN::SERVER_PWD]; + confProperties.TURN.realm = details[ConfProperties::TURN::SERVER_REALM]; // Presence confProperties.Presence.presencePublishSupported = toBool(details[ConfProperties::Presence::SUPPORT_PUBLISH]); confProperties.Presence.presenceSubscribeSupported = toBool(details[ConfProperties::Presence::SUPPORT_SUBSCRIBE]); confProperties.Presence.presenceEnabled = toBool(details[ConfProperties::Presence::ENABLED]); // Ringtone - confProperties.Ringtone.ringtonePath = toStdString(details[ConfProperties::Ringtone::PATH]); + confProperties.Ringtone.ringtonePath = details[ConfProperties::Ringtone::PATH]; confProperties.Ringtone.ringtoneEnabled = toBool(details[ConfProperties::Ringtone::ENABLED]); // SRTP - confProperties.SRTP.keyExchange = toStdString(details[ConfProperties::SRTP::KEY_EXCHANGE]).empty()? account::KeyExchangeProtocol::NONE : account::KeyExchangeProtocol::SDES; + confProperties.SRTP.keyExchange = details[ConfProperties::SRTP::KEY_EXCHANGE].isEmpty()? account::KeyExchangeProtocol::NONE : account::KeyExchangeProtocol::SDES; confProperties.SRTP.enable = toBool(details[ConfProperties::SRTP::ENABLED]); confProperties.SRTP.rtpFallback = toBool(details[ConfProperties::SRTP::RTP_FALLBACK]); // TLS confProperties.TLS.listenerPort = toInt(details[ConfProperties::TLS::LISTENER_PORT]); confProperties.TLS.enable = details[ConfProperties::TYPE] == QString(ProtocolNames::RING)? true : toBool(details[ConfProperties::TLS::ENABLED]); confProperties.TLS.port = toInt(details[ConfProperties::TLS::PORT]); - confProperties.TLS.certificateListFile = toStdString(details[ConfProperties::TLS::CA_LIST_FILE]); - confProperties.TLS.certificateFile = toStdString(details[ConfProperties::TLS::CERTIFICATE_FILE]); - confProperties.TLS.privateKeyFile = toStdString(details[ConfProperties::TLS::PRIVATE_KEY_FILE]); - confProperties.TLS.password = toStdString(details[ConfProperties::TLS::PASSWORD]); + confProperties.TLS.certificateListFile = details[ConfProperties::TLS::CA_LIST_FILE]; + confProperties.TLS.certificateFile = details[ConfProperties::TLS::CERTIFICATE_FILE]; + confProperties.TLS.privateKeyFile = details[ConfProperties::TLS::PRIVATE_KEY_FILE]; + confProperties.TLS.password = details[ConfProperties::TLS::PASSWORD]; auto method = toStdString(details[ConfProperties::TLS::METHOD]); if (method == "TLSv1") { confProperties.TLS.method = account::TlsMethod::TLSv1; @@ -779,8 +779,8 @@ account::Info::fromDetails(const MapStringString& details) } else { confProperties.TLS.method = account::TlsMethod::DEFAULT; } - confProperties.TLS.ciphers = toStdString(details[ConfProperties::TLS::CIPHERS]); - confProperties.TLS.serverName = toStdString(details[ConfProperties::TLS::SERVER_NAME]); + confProperties.TLS.ciphers = details[ConfProperties::TLS::CIPHERS]; + confProperties.TLS.serverName = details[ConfProperties::TLS::SERVER_NAME]; confProperties.TLS.verifyServer = toBool(details[ConfProperties::TLS::VERIFY_SERVER]); confProperties.TLS.verifyClient = toBool(details[ConfProperties::TLS::VERIFY_CLIENT]); confProperties.TLS.requireClientCertificate = toBool(details[ConfProperties::TLS::REQUIRE_CLIENT_CERTIFICATE]); @@ -790,13 +790,13 @@ account::Info::fromDetails(const MapStringString& details) confProperties.DHT.PublicInCalls = toBool(details[ConfProperties::DHT::PUBLIC_IN_CALLS]); confProperties.DHT.AllowFromTrusted = toBool(details[ConfProperties::DHT::ALLOW_FROM_TRUSTED]); // RingNS - confProperties.RingNS.uri = toStdString(details[ConfProperties::RingNS::URI]); - confProperties.RingNS.account = toStdString(details[ConfProperties::RingNS::ACCOUNT]); + confProperties.RingNS.uri = details[ConfProperties::RingNS::URI]; + confProperties.RingNS.account = details[ConfProperties::RingNS::ACCOUNT]; // Registration confProperties.Registration.expire = toInt(details[ConfProperties::Registration::EXPIRE]); // Jams - confProperties.managerUri = toStdString(details[ConfProperties::MANAGER_URI]); - confProperties.managerUsername = toStdString(details[ConfProperties::MANAGER_USERNAME]); + confProperties.managerUri = details[ConfProperties::MANAGER_URI]; + confProperties.managerUsername = details[ConfProperties::MANAGER_USERNAME]; } MapStringString @@ -805,35 +805,35 @@ account::ConfProperties_t::toDetails() const using namespace DRing::Account; MapStringString details; // General - details[ConfProperties::MAILBOX] = toQString(this->mailbox); - details[ConfProperties::DTMF_TYPE] = toQString(this->dtmfType); + details[ConfProperties::MAILBOX] = this->mailbox; + details[ConfProperties::DTMF_TYPE] = this->dtmfType; details[ConfProperties::AUTOANSWER] = toQString(this->autoAnswer); details[ConfProperties::ACTIVE_CALL_LIMIT] = toQString(this->activeCallLimit); - details[ConfProperties::HOSTNAME] = toQString(this->hostname); - details[ConfProperties::ROUTE] = toQString(this->routeset); - details[ConfProperties::PASSWORD] = toQString(this->password); - details[ConfProperties::REALM] = toQString(this->realm); - details[ConfProperties::RING_DEVICE_ID] = toQString(this->deviceId); - details[ConfProperties::RING_DEVICE_NAME] = toQString(this->deviceName); - details[ConfProperties::LOCAL_INTERFACE] = toQString(this->localInterface); + details[ConfProperties::HOSTNAME] = this->hostname; + details[ConfProperties::ROUTE] = this->routeset; + details[ConfProperties::PASSWORD] = this->password; + details[ConfProperties::REALM] = this->realm; + details[ConfProperties::RING_DEVICE_ID] = this->deviceId; + details[ConfProperties::RING_DEVICE_NAME] = this->deviceName; + details[ConfProperties::LOCAL_INTERFACE] = this->localInterface; details[ConfProperties::PUBLISHED_SAMEAS_LOCAL] = toQString(this->publishedSameAsLocal); details[ConfProperties::LOCAL_PORT] = toQString(this->localPort); details[ConfProperties::PUBLISHED_PORT] = toQString(this->publishedPort); - details[ConfProperties::PUBLISHED_ADDRESS] = toQString(this->publishedAddress); - details[ConfProperties::USER_AGENT] = toQString(this->userAgent); + details[ConfProperties::PUBLISHED_ADDRESS] = this->publishedAddress; + details[ConfProperties::USER_AGENT] = this->userAgent; details[ConfProperties::UPNP_ENABLED] = toQString(this->upnpEnabled); details[ConfProperties::HAS_CUSTOM_USER_AGENT] = toQString(this->hasCustomUserAgent); details[ConfProperties::ALLOW_CERT_FROM_HISTORY] = toQString(this->allowIncoming); details[ConfProperties::ALLOW_CERT_FROM_CONTACT] = toQString(this->allowIncoming); details[ConfProperties::ALLOW_CERT_FROM_TRUSTED] = toQString(this->allowIncoming); - details[ConfProperties::ARCHIVE_PASSWORD] = toQString(this->archivePassword); + details[ConfProperties::ARCHIVE_PASSWORD] = this->archivePassword; details[ConfProperties::ARCHIVE_HAS_PASSWORD] = toQString(this->archiveHasPassword); - details[ConfProperties::ARCHIVE_PATH] = toQString(this->archivePath); - details[ConfProperties::ARCHIVE_PIN] = toQString(this->archivePin); + details[ConfProperties::ARCHIVE_PATH] = this->archivePath; + details[ConfProperties::ARCHIVE_PIN] = this->archivePin; // ConfProperties::DEVICE_NAME name is set with NewDeviceModel interface details[ConfProperties::PROXY_ENABLED] = toQString(this->proxyEnabled); - details[ConfProperties::PROXY_SERVER] = toQString(this->proxyServer); - details[ConfProperties::PROXY_PUSH_TOKEN] = toQString(this->proxyPushToken); + details[ConfProperties::PROXY_SERVER] = this->proxyServer; + details[ConfProperties::PROXY_PUSH_TOKEN] = this->proxyPushToken; details[ConfProperties::DHT_PEER_DISCOVERY] = toQString(this->peerDiscovery); details[ConfProperties::ACCOUNT_PEER_DISCOVERY] = toQString(this->accountDiscovery); details[ConfProperties::ACCOUNT_PUBLISH] = toQString(this->accountPublish); @@ -845,20 +845,20 @@ account::ConfProperties_t::toDetails() const details[ConfProperties::Video::PORT_MAX] = toQString(this->Video.videoPortMax); details[ConfProperties::Video::PORT_MIN] = toQString(this->Video.videoPortMin); // STUN - details[ConfProperties::STUN::SERVER] = toQString(this->STUN.server); + details[ConfProperties::STUN::SERVER] = this->STUN.server; details[ConfProperties::STUN::ENABLED] = toQString(this->STUN.enable); // TURN - details[ConfProperties::TURN::SERVER] = toQString(this->TURN.server); + details[ConfProperties::TURN::SERVER] = this->TURN.server; details[ConfProperties::TURN::ENABLED] = toQString(this->TURN.enable); - details[ConfProperties::TURN::SERVER_UNAME] = toQString(this->TURN.username); - details[ConfProperties::TURN::SERVER_PWD] = toQString(this->TURN.password); - details[ConfProperties::TURN::SERVER_REALM] = toQString(this->TURN.realm); + details[ConfProperties::TURN::SERVER_UNAME] = this->TURN.username; + details[ConfProperties::TURN::SERVER_PWD] = this->TURN.password; + details[ConfProperties::TURN::SERVER_REALM] = this->TURN.realm; // Presence details[ConfProperties::Presence::SUPPORT_PUBLISH] = toQString(this->Presence.presencePublishSupported); details[ConfProperties::Presence::SUPPORT_SUBSCRIBE] = toQString(this->Presence.presenceSubscribeSupported); details[ConfProperties::Presence::ENABLED] = toQString(this->Presence.presenceEnabled); // Ringtone - details[ConfProperties::Ringtone::PATH] = toQString(this->Ringtone.ringtonePath); + details[ConfProperties::Ringtone::PATH] = this->Ringtone.ringtonePath; details[ConfProperties::Ringtone::ENABLED] = toQString(this->Ringtone.ringtoneEnabled); // SRTP details[ConfProperties::SRTP::KEY_EXCHANGE] = this->SRTP.keyExchange == account::KeyExchangeProtocol::NONE? "" : "sdes"; @@ -868,10 +868,10 @@ account::ConfProperties_t::toDetails() const details[ConfProperties::TLS::LISTENER_PORT] = toQString(this->TLS.listenerPort); details[ConfProperties::TLS::ENABLED] = toQString(this->TLS.enable); details[ConfProperties::TLS::PORT] = toQString(this->TLS.port); - details[ConfProperties::TLS::CA_LIST_FILE] = toQString(this->TLS.certificateListFile); - details[ConfProperties::TLS::CERTIFICATE_FILE] = toQString(this->TLS.certificateFile); - details[ConfProperties::TLS::PRIVATE_KEY_FILE] = toQString(this->TLS.privateKeyFile); - details[ConfProperties::TLS::PASSWORD] = toQString(this->TLS.password); + details[ConfProperties::TLS::CA_LIST_FILE] = this->TLS.certificateListFile; + details[ConfProperties::TLS::CERTIFICATE_FILE] = this->TLS.certificateFile; + details[ConfProperties::TLS::PRIVATE_KEY_FILE] = this->TLS.privateKeyFile; + details[ConfProperties::TLS::PASSWORD] = this->TLS.password; switch (this->TLS.method) { case account::TlsMethod::TLSv1: details[ConfProperties::TLS::METHOD] = "TLSv1"; @@ -887,8 +887,8 @@ account::ConfProperties_t::toDetails() const details[ConfProperties::TLS::METHOD] = "Default"; break; } - details[ConfProperties::TLS::CIPHERS] = toQString(this->TLS.ciphers); - details[ConfProperties::TLS::SERVER_NAME] = toQString(this->TLS.serverName); + details[ConfProperties::TLS::CIPHERS] = this->TLS.ciphers; + details[ConfProperties::TLS::SERVER_NAME] = this->TLS.serverName; details[ConfProperties::TLS::VERIFY_SERVER] = toQString(this->TLS.verifyServer); details[ConfProperties::TLS::VERIFY_CLIENT] = toQString(this->TLS.verifyClient); details[ConfProperties::TLS::REQUIRE_CLIENT_CERTIFICATE] = toQString(this->TLS.requireClientCertificate); @@ -898,24 +898,24 @@ account::ConfProperties_t::toDetails() const details[ConfProperties::DHT::PUBLIC_IN_CALLS] = toQString(this->DHT.PublicInCalls); details[ConfProperties::DHT::ALLOW_FROM_TRUSTED] = toQString(this->DHT.AllowFromTrusted); // RingNS - details[ConfProperties::RingNS::URI] = toQString(this->RingNS.uri); - details[ConfProperties::RingNS::ACCOUNT] = toQString(this->RingNS.account); + details[ConfProperties::RingNS::URI] = this->RingNS.uri; + details[ConfProperties::RingNS::ACCOUNT] = this->RingNS.account; // Registration details[ConfProperties::Registration::EXPIRE] = toQString(this->Registration.expire); // Manager - details[ConfProperties::MANAGER_URI] = toQString(this->managerUri); - details[ConfProperties::MANAGER_USERNAME] = toQString(this->managerUsername); + details[ConfProperties::MANAGER_URI] = this->managerUri; + details[ConfProperties::MANAGER_USERNAME] = this->managerUsername; return details; } -std::string +QString NewAccountModel::createNewAccount(profile::Type type, - const std::string& displayName, - const std::string& archivePath, - const std::string& password, - const std::string& pin, - const std::string& uri) + const QString& displayName, + const QString& archivePath, + const QString& password, + const QString& pin, + const QString& uri) { MapStringString details = type == profile::Type::SIP? @@ -923,61 +923,59 @@ NewAccountModel::createNewAccount(profile::Type type, ConfigurationManager::instance().getAccountTemplate("RING"); using namespace DRing::Account; details[ConfProperties::TYPE] = type == profile::Type::SIP? "SIP" : "RING"; - details[ConfProperties::DISPLAYNAME] = displayName.c_str(); - details[ConfProperties::ALIAS] = displayName.c_str(); + details[ConfProperties::DISPLAYNAME] = displayName; + details[ConfProperties::ALIAS] = displayName; details[ConfProperties::UPNP_ENABLED] = "true"; - details[ConfProperties::ARCHIVE_PASSWORD] = password.c_str(); - details[ConfProperties::ARCHIVE_PIN] = pin.c_str(); - details[ConfProperties::ARCHIVE_PATH] = archivePath.c_str(); + details[ConfProperties::ARCHIVE_PASSWORD] = password; + details[ConfProperties::ARCHIVE_PIN] = pin; + details[ConfProperties::ARCHIVE_PATH] = archivePath; if (type == profile::Type::SIP) { - details[ConfProperties::USERNAME] = uri.c_str(); + details[ConfProperties::USERNAME] = uri; } QString accountId = ConfigurationManager::instance().addAccount(details); - return accountId.toStdString(); + return accountId; } - - -std::string -NewAccountModel::connectToAccountManager(const std::string& username, - const std::string& password, - const std::string& serverUri) +QString +NewAccountModel::connectToAccountManager(const QString& username, + const QString& password, + const QString& serverUri) { MapStringString details = ConfigurationManager::instance().getAccountTemplate("RING"); using namespace DRing::Account; details[ConfProperties::TYPE] = "RING"; - details[ConfProperties::MANAGER_URI] = serverUri.c_str(); - details[ConfProperties::MANAGER_USERNAME] = username.c_str(); - details[ConfProperties::ARCHIVE_PASSWORD] = password.c_str(); + details[ConfProperties::MANAGER_URI] = serverUri; + details[ConfProperties::MANAGER_USERNAME] = username; + details[ConfProperties::ARCHIVE_PASSWORD] = password; QString accountId = ConfigurationManager::instance().addAccount(details); - return accountId.toStdString(); + return accountId; } void -NewAccountModel::setTopAccount(const std::string& accountId) +NewAccountModel::setTopAccount(const QString& accountId) { bool found = false; - std::string order = {}; + QString order = {}; const QStringList accountIds = ConfigurationManager::instance().getAccountList(); for (auto& id : accountIds) { - if (id.toStdString() == accountId) { + if (id == accountId) { found = true; } else { - order += id.toStdString() + "/"; + order += id + "/"; } } if (found) { order = accountId + "/" + order; } - ConfigurationManager::instance().setAccountsOrder(order.c_str()); + ConfigurationManager::instance().setAccountsOrder(order); } -std::string -NewAccountModel::accountVCard(const std::string& accountId, bool compressImage) const +QString +NewAccountModel::accountVCard(const QString& accountId, bool compressImage) const { auto account = pimpl_->accounts.find(accountId); if (account == pimpl_->accounts.end()) { diff --git a/src/newcallmodel.cpp b/src/newcallmodel.cpp index c1e640d4737832598b193d43877de01db0c38cc4..d2c7c43abda997b0aeb3ec2779d71b3634427890 100644 --- a/src/newcallmodel.cpp +++ b/src/newcallmodel.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * + * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * * Author : Nicolas Jäger <nicolas.jager@savoirfairelinux.com> * * Author : Sébastien Blin <sebastien.blin@savoirfairelinux.com> * * * @@ -44,63 +44,63 @@ #include <QString> static std::uniform_int_distribution<int> dis{ 0, std::numeric_limits<int>::max() }; -static const std::map<short, std::string> sip_call_status_code_map { - {0, QObject::tr("Null").toStdString()}, - {100, QObject::tr("Trying").toStdString()}, - {180, QObject::tr("Ringing").toStdString()}, - {181, QObject::tr("Being Forwarded").toStdString()}, - {182, QObject::tr("Queued").toStdString()}, - {183, QObject::tr("Progress").toStdString()}, - {200, QObject::tr("OK").toStdString()}, - {202, QObject::tr("Accepted").toStdString()}, - {300, QObject::tr("Multiple Choices").toStdString()}, - {301, QObject::tr("Moved Permanently").toStdString()}, - {302, QObject::tr("Moved Temporarily").toStdString()}, - {305, QObject::tr("Use Proxy").toStdString()}, - {380, QObject::tr("Alternative Service").toStdString()}, - {400, QObject::tr("Bad Request").toStdString()}, - {401, QObject::tr("Unauthorized").toStdString()}, - {402, QObject::tr("Payment Required").toStdString()}, - {403, QObject::tr("Forbidden").toStdString()}, - {404, QObject::tr("Not Found").toStdString()}, - {405, QObject::tr("Method Not Allowed").toStdString()}, - {406, QObject::tr("Not Acceptable").toStdString()}, - {407, QObject::tr("Proxy Authentication Required").toStdString()}, - {408, QObject::tr("Request Timeout").toStdString()}, - {410, QObject::tr("Gone").toStdString()}, - {413, QObject::tr("Request Entity Too Large").toStdString()}, - {414, QObject::tr("Request URI Too Long").toStdString()}, - {415, QObject::tr("Unsupported Media Type").toStdString()}, - {416, QObject::tr("Unsupported URI Scheme").toStdString()}, - {420, QObject::tr("Bad Extension").toStdString()}, - {421, QObject::tr("Extension Required").toStdString()}, - {422, QObject::tr("Session Timer Too Small").toStdString()}, - {423, QObject::tr("Interval Too Brief").toStdString()}, - {480, QObject::tr("Temporarily Unavailable").toStdString()}, - {481, QObject::tr("Call TSX Does Not Exist").toStdString()}, - {482, QObject::tr("Loop Detected").toStdString()}, - {483, QObject::tr("Too Many Hops").toStdString()}, - {484, QObject::tr("Address Incomplete").toStdString()}, - {485, QObject::tr("Ambiguous").toStdString()}, - {486, QObject::tr("Busy").toStdString()}, - {487, QObject::tr("Request Terminated").toStdString()}, - {488, QObject::tr("Not Acceptable").toStdString()}, - {489, QObject::tr("Bad Event").toStdString()}, - {490, QObject::tr("Request Updated").toStdString()}, - {491, QObject::tr("Request Pending").toStdString()}, - {493, QObject::tr("Undecipherable").toStdString()}, - {500, QObject::tr("Internal Server Error").toStdString()}, - {501, QObject::tr("Not Implemented").toStdString()}, - {502, QObject::tr("Bad Gateway").toStdString()}, - {503, QObject::tr("Service Unavailable").toStdString()}, - {504, QObject::tr("Server Timeout").toStdString()}, - {505, QObject::tr("Version Not Supported").toStdString()}, - {513, QObject::tr("Message Too Large").toStdString()}, - {580, QObject::tr("Precondition Failure").toStdString()}, - {600, QObject::tr("Busy Everywhere").toStdString()} , - {603, QObject::tr("Call Refused").toStdString()}, - {604, QObject::tr("Does Not Exist Anywhere").toStdString()}, - {606, QObject::tr("Not Acceptable Anywhere").toStdString()} +static const std::map<short, QString> sip_call_status_code_map { + {0, QObject::tr("Null")}, + {100, QObject::tr("Trying")}, + {180, QObject::tr("Ringing")}, + {181, QObject::tr("Being Forwarded")}, + {182, QObject::tr("Queued")}, + {183, QObject::tr("Progress")}, + {200, QObject::tr("OK")}, + {202, QObject::tr("Accepted")}, + {300, QObject::tr("Multiple Choices")}, + {301, QObject::tr("Moved Permanently")}, + {302, QObject::tr("Moved Temporarily")}, + {305, QObject::tr("Use Proxy")}, + {380, QObject::tr("Alternative Service")}, + {400, QObject::tr("Bad Request")}, + {401, QObject::tr("Unauthorized")}, + {402, QObject::tr("Payment Required")}, + {403, QObject::tr("Forbidden")}, + {404, QObject::tr("Not Found")}, + {405, QObject::tr("Method Not Allowed")}, + {406, QObject::tr("Not Acceptable")}, + {407, QObject::tr("Proxy Authentication Required")}, + {408, QObject::tr("Request Timeout")}, + {410, QObject::tr("Gone")}, + {413, QObject::tr("Request Entity Too Large")}, + {414, QObject::tr("Request URI Too Long")}, + {415, QObject::tr("Unsupported Media Type")}, + {416, QObject::tr("Unsupported URI Scheme")}, + {420, QObject::tr("Bad Extension")}, + {421, QObject::tr("Extension Required")}, + {422, QObject::tr("Session Timer Too Small")}, + {423, QObject::tr("Interval Too Brief")}, + {480, QObject::tr("Temporarily Unavailable")}, + {481, QObject::tr("Call TSX Does Not Exist")}, + {482, QObject::tr("Loop Detected")}, + {483, QObject::tr("Too Many Hops")}, + {484, QObject::tr("Address Incomplete")}, + {485, QObject::tr("Ambiguous")}, + {486, QObject::tr("Busy")}, + {487, QObject::tr("Request Terminated")}, + {488, QObject::tr("Not Acceptable")}, + {489, QObject::tr("Bad Event")}, + {490, QObject::tr("Request Updated")}, + {491, QObject::tr("Request Pending")}, + {493, QObject::tr("Undecipherable")}, + {500, QObject::tr("Internal Server Error")}, + {501, QObject::tr("Not Implemented")}, + {502, QObject::tr("Bad Gateway")}, + {503, QObject::tr("Service Unavailable")}, + {504, QObject::tr("Server Timeout")}, + {505, QObject::tr("Version Not Supported")}, + {513, QObject::tr("Message Too Large")}, + {580, QObject::tr("Precondition Failure")}, + {600, QObject::tr("Busy Everywhere")} , + {603, QObject::tr("Call Refused")}, + {604, QObject::tr("Does Not Exist Anywhere")}, + {606, QObject::tr("Not Acceptable Anywhere")} }; namespace lrc @@ -118,7 +118,7 @@ public: * Send the profile VCard into a call * @param callId */ - void sendProfile(const std::string& callId); + void sendProfile(const QString& callId); NewCallModel::CallInfoMap calls; const CallbacksHandler& callbacksHandler; @@ -129,7 +129,7 @@ public: * vector = chunks * @note chunks are counted from 1 to number of parts. We use 0 to store the actual number of parts stored */ - std::map<std::string, std::vector<std::string>> vcardsChunks; + std::map<QString, VectorString> vcardsChunks; /** * Retrieve active calls from the daemon and init the model @@ -140,9 +140,9 @@ public: */ void initConferencesFromDaemon(); bool manageCurrentCall_ {true}; - std::string currentCall_ {}; + QString currentCall_ {}; - std::map<std::string, std::string> pendingConferences_; + std::map<QString, QString> pendingConferences_; public Q_SLOTS: /** * Listen from CallbacksHandler when a call is incoming @@ -151,14 +151,14 @@ public Q_SLOTS: * @param fromId peer uri * @param displayname */ - void slotIncomingCall(const std::string& accountId, const std::string& callId, const std::string& fromId, const std::string& displayname); + void slotIncomingCall(const QString& accountId, const QString& callId, const QString& fromId, const QString& displayname); /** * Listen from CallbacksHandler when a call got a new state * @param callId * @param state the new state * @param code unused */ - void slotCallStateChanged(const std::string& callId, const std::string &state, int code); + void slotCallStateChanged(const QString& callId, const QString &state, int code); /** * Listen from CallbacksHandler when a VCard chunk is incoming * @param callId @@ -167,12 +167,12 @@ public Q_SLOTS: * @param numberOfParts * @param payload */ - void slotincomingVCardChunk(const std::string& callId, const std::string& from, int part, int numberOfParts, const std::string& payload); + void slotincomingVCardChunk(const QString& callId, const QString& from, int part, int numberOfParts, const QString& payload); /** * Listen from CallbacksHandler when a conference is created. * @param callId */ - void slotConferenceCreated(const std::string& callId); + void slotConferenceCreated(const QString& callId); /** * Listen from CallbacksHandler when a voice mail notice is incoming * @param accountId @@ -180,7 +180,7 @@ public Q_SLOTS: * @param oldCount * @param urgentCount */ - void slotVoiceMailNotify(const std::string& accountId, int newCount, int oldCount, int urgentCount); + void slotVoiceMailNotify(const QString& accountId, int newCount, int oldCount, int urgentCount); }; NewCallModel::NewCallModel(const account::Info& owner, const CallbacksHandler& callbacksHandler) @@ -194,95 +194,91 @@ NewCallModel::~NewCallModel() } const call::Info& -NewCallModel::getCallFromURI(const std::string& uri, bool notOver) const +NewCallModel::getCallFromURI(const QString& uri, bool notOver) const { // peer url = ring:uri or sip number - auto url = (owner.profileInfo.type != profile::Type::SIP && uri.find("ring:") == std::string::npos) ? "ring:" + uri : uri; + auto url = (owner.profileInfo.type != profile::Type::SIP && !uri.contains("ring:")) ? "ring:" + uri : uri; for (const auto& call: pimpl_->calls) { if (call.second->peerUri == url) { if (!notOver || !call::isTerminating(call.second->status)) return *call.second; } } - throw std::out_of_range("No call at URI " + uri); + throw std::out_of_range("No call at URI " + uri.toStdString()); } const call::Info& -NewCallModel::getConferenceFromURI(const std::string& uri) const +NewCallModel::getConferenceFromURI(const QString& uri) const { for (const auto& call: pimpl_->calls) { if (call.second->type == call::Type::CONFERENCE) { - QStringList callList = CallManager::instance().getParticipantList(call.first.c_str()); + QStringList callList = CallManager::instance().getParticipantList(call.first); foreach(const auto& callId, callList) { try { - if (pimpl_->calls.find(callId.toStdString()) != pimpl_->calls.end() - && pimpl_->calls[callId.toStdString()]->peerUri == uri) { + if (pimpl_->calls.find(callId) != pimpl_->calls.end() + && pimpl_->calls[callId]->peerUri == uri) { return *call.second; } } catch (...) {} } } } - throw std::out_of_range("No call at URI " + uri); + throw std::out_of_range("No call at URI " + uri.toStdString()); } const call::Info& -NewCallModel::getCall(const std::string& uid) const +NewCallModel::getCall(const QString& uid) const { return *pimpl_->calls.at(uid); } -std::string -NewCallModel::createCall(const std::string& uri, bool isAudioOnly) +QString +NewCallModel::createCall(const QString& uri, bool isAudioOnly) { #ifdef ENABLE_LIBWRAP - auto callId = isAudioOnly ? CallManager::instance().placeCall(owner.id.c_str(), - uri.c_str(), - {{"AUDIO_ONLY", "true"}}) - : CallManager::instance().placeCall(owner.id.c_str(), uri.c_str()); + auto callId = isAudioOnly ? CallManager::instance().placeCall(owner.id, uri, {{"AUDIO_ONLY", "true"}}) + : CallManager::instance().placeCall(owner.id, uri); #else // dbus // do not use auto here (QDBusPendingReply<QString>) - QString callId = isAudioOnly ? CallManager::instance().placeCallWithDetails(owner.id.c_str(), - uri.c_str(), - {{"AUDIO_ONLY", "true"}}) - : CallManager::instance().placeCall(owner.id.c_str(), uri.c_str()); + QString callId = isAudioOnly ? CallManager::instance().placeCallWithDetails(owner.id, uri, {{"AUDIO_ONLY", "true"}}) + : CallManager::instance().placeCall(owner.id, uri); #endif // ENABLE_LIBWRAP if (callId.isEmpty()) { - qDebug() << "no call placed between (account: " << owner.id.c_str() << ", contact: " << uri.c_str() << ")"; + qDebug() << "no call placed between (account: " << owner.id << ", contact: " << uri << ")"; return ""; } auto callInfo = std::make_shared<call::Info>(); - callInfo->id = callId.toStdString(); + callInfo->id = callId; callInfo->peerUri = uri; callInfo->isOutgoing = true; callInfo->status = call::Status::SEARCHING; callInfo->type = call::Type::DIALOG; callInfo->isAudioOnly = isAudioOnly; - pimpl_->calls.emplace(callId.toStdString(), std::move(callInfo)); + pimpl_->calls.emplace(callId, std::move(callInfo)); - return callId.toStdString(); + return callId; } void -NewCallModel::accept(const std::string& callId) const +NewCallModel::accept(const QString& callId) const { - CallManager::instance().accept(callId.c_str()); + CallManager::instance().accept(callId); } void -NewCallModel::hangUp(const std::string& callId) const +NewCallModel::hangUp(const QString& callId) const { if (!hasCall(callId)) return; auto& call = pimpl_->calls[callId]; switch(call->type) { case call::Type::DIALOG: - CallManager::instance().hangUp(callId.c_str()); + CallManager::instance().hangUp(callId); break; case call::Type::CONFERENCE: - CallManager::instance().hangUpConference(callId.c_str()); + CallManager::instance().hangUpConference(callId); break; case call::Type::INVALID: default: @@ -291,64 +287,64 @@ NewCallModel::hangUp(const std::string& callId) const } void -NewCallModel::refuse(const std::string& callId) const +NewCallModel::refuse(const QString& callId) const { if (!hasCall(callId)) return; - CallManager::instance().refuse(callId.c_str()); + CallManager::instance().refuse(callId); } void -NewCallModel::toggleAudioRecord(const std::string& callId) const +NewCallModel::toggleAudioRecord(const QString& callId) const { - CallManager::instance().toggleRecording(callId.c_str()); + CallManager::instance().toggleRecording(callId); } void -NewCallModel::playDTMF(const std::string& callId, const std::string& value) const +NewCallModel::playDTMF(const QString& callId, const QString& value) const { if (!hasCall(callId)) return; if (pimpl_->calls[callId]->status != call::Status::IN_PROGRESS) return; - CallManager::instance().playDTMF(value.c_str()); + CallManager::instance().playDTMF(value); } void -NewCallModel::togglePause(const std::string& callId) const +NewCallModel::togglePause(const QString& callId) const { if (!hasCall(callId)) return; auto& call = pimpl_->calls[callId]; if (call->status == call::Status::PAUSED) { if (call->type == call::Type::DIALOG) { - CallManager::instance().unhold(callId.c_str()); + CallManager::instance().unhold(callId); setCurrentCall(callId); } else { - CallManager::instance().unholdConference(callId.c_str()); + CallManager::instance().unholdConference(callId); } } else if (call->status == call::Status::IN_PROGRESS) { if (call->type == call::Type::DIALOG) - CallManager::instance().hold(callId.c_str()); + CallManager::instance().hold(callId); else { - CallManager::instance().holdConference(callId.c_str()); + CallManager::instance().holdConference(callId); } } } void -NewCallModel::toggleMedia(const std::string& callId, const NewCallModel::Media media) const +NewCallModel::toggleMedia(const QString& callId, const NewCallModel::Media media) const { if (!hasCall(callId)) return; auto& call = pimpl_->calls[callId]; switch(media) { case NewCallModel::Media::AUDIO: - CallManager::instance().muteLocalMedia(callId.c_str(), + CallManager::instance().muteLocalMedia(callId, DRing::Media::Details::MEDIA_TYPE_AUDIO, !call->audioMuted); call->audioMuted = !call->audioMuted; break; case NewCallModel::Media::VIDEO: - CallManager::instance().muteLocalMedia(callId.c_str(), + CallManager::instance().muteLocalMedia(callId, DRing::Media::Details::MEDIA_TYPE_VIDEO, !call->videoMuted); call->videoMuted = !call->videoMuted; @@ -361,7 +357,7 @@ NewCallModel::toggleMedia(const std::string& callId, const NewCallModel::Media m } void -NewCallModel::setQuality(const std::string& callId, const double quality) const +NewCallModel::setQuality(const QString& callId, const double quality) const { Q_UNUSED(callId) Q_UNUSED(quality) @@ -369,23 +365,23 @@ NewCallModel::setQuality(const std::string& callId, const double quality) const } void -NewCallModel::transfer(const std::string& callId, const std::string& to) const +NewCallModel::transfer(const QString& callId, const QString& to) const { - CallManager::instance().transfer(callId.c_str(), to.c_str()); + CallManager::instance().transfer(callId, to); } void -NewCallModel::transferToCall(const std::string& callId, const std::string& callIdDest) const +NewCallModel::transferToCall(const QString& callId, const QString& callIdDest) const { - CallManager::instance().attendedTransfer(callId.c_str(), callIdDest.c_str()); + CallManager::instance().attendedTransfer(callId, callIdDest); } void -NewCallModel::joinCalls(const std::string& callIdA, const std::string& callIdB) const +NewCallModel::joinCalls(const QString& callIdA, const QString& callIdB) const { // Get call informations call::Info call1, call2; - std::string accountIdCall1 = {}, accountIdCall2 = {}; + QString accountIdCall1 = {}, accountIdCall2 = {}; for (const auto &account_id : owner.accountModel->getAccountList()) { try { auto &accountInfo = owner.accountModel->getAccountInfo(account_id); @@ -397,19 +393,19 @@ NewCallModel::joinCalls(const std::string& callIdA, const std::string& callIdB) call2 = accountInfo.callModel->getCall(callIdB); accountIdCall2 = account_id; } - if (!accountIdCall1.empty() && !accountIdCall2.empty()) break; + if (!accountIdCall1.isEmpty() && !accountIdCall2.isEmpty()) break; } catch (...) {} } - if (accountIdCall1.empty() || accountIdCall2.empty()) { + if (accountIdCall1.isEmpty() || accountIdCall2.isEmpty()) { qWarning() << "Can't join inexistent calls."; return; } if (call1.type == call::Type::CONFERENCE && call2.type == call::Type::CONFERENCE) { - bool joined = CallManager::instance().joinConference(callIdA.c_str(), callIdB.c_str()); + bool joined = CallManager::instance().joinConference(callIdA, callIdB); if (!joined) { - qWarning() << "Conference: " << callIdA.c_str() << " couldn't join conference " << callIdB.c_str(); + qWarning() << "Conference: " << callIdA << " couldn't join conference " << callIdB; return; } if (accountIdCall1 != owner.id) { @@ -427,11 +423,11 @@ NewCallModel::joinCalls(const std::string& callIdA, const std::string& callIdB) auto call = call1.type == call::Type::CONFERENCE ? callIdB : callIdA; auto conf = call1.type == call::Type::CONFERENCE ? callIdA : callIdB; // Unpause conference if conference was not active - CallManager::instance().unholdConference(conf.c_str()); + CallManager::instance().unholdConference(conf); auto accountCall = call1.type == call::Type::CONFERENCE ? accountIdCall2 : accountIdCall1; - bool joined = CallManager::instance().addParticipant(call.c_str(), conf.c_str()); + bool joined = CallManager::instance().addParticipant(call, conf); if (!joined) { - qWarning() << "Call: " << call.c_str() << " couldn't join conference " << conf.c_str(); + qWarning() << "Call: " << call << " couldn't join conference " << conf; return; } if (accountCall != owner.id) { @@ -446,13 +442,13 @@ NewCallModel::joinCalls(const std::string& callIdA, const std::string& callIdB) emit callAddedToConference(call, conf); } else { - CallManager::instance().joinParticipant(callIdA.c_str(), callIdB.c_str()); + CallManager::instance().joinParticipant(callIdA, callIdB); // NOTE: This will trigger slotConferenceCreated. } } -std::string -NewCallModel::callAndAddParticipant(const std::string uri, const std::string& callId, bool audioOnly) +QString +NewCallModel::callAndAddParticipant(const QString uri, const QString& callId, bool audioOnly) { auto newCallId = createCall(uri, audioOnly); pimpl_->pendingConferences_.insert({newCallId, callId}); @@ -460,15 +456,15 @@ NewCallModel::callAndAddParticipant(const std::string uri, const std::string& ca } void -NewCallModel::removeParticipant(const std::string& callId, const std::string& participant) const +NewCallModel::removeParticipant(const QString& callId, const QString& participant) const { Q_UNUSED(callId) Q_UNUSED(participant) qDebug() << "removeParticipant() isn't implemented yet"; } -std::string -NewCallModel::getFormattedCallDuration(const std::string& callId) const +QString +NewCallModel::getFormattedCallDuration(const QString& callId) const { if (!hasCall(callId)) return "00:00"; auto& startTime = pimpl_->calls[callId]->startTime; @@ -480,13 +476,13 @@ NewCallModel::getFormattedCallDuration(const std::string& callId) const } bool -NewCallModel::isRecording(const std::string& callId) const +NewCallModel::isRecording(const QString& callId) const { if (!hasCall(callId)) return false; - return CallManager::instance().getIsRecording(callId.c_str()); + return CallManager::instance().getIsRecording(callId); } -std::string +QString NewCallModel::getSIPCallStatusString(const short& statusCode) { auto element = sip_call_status_code_map.find(statusCode); @@ -525,24 +521,24 @@ NewCallModelPimpl::initCallFromDaemon() for (const auto& callId : callList) { MapStringString details = CallManager::instance().getCallDetails(callId); - auto accountId = details["ACCOUNTID"].toStdString(); + auto accountId = details["ACCOUNTID"]; if (accountId == linked.owner.id) { auto callInfo = std::make_shared<call::Info>(); - callInfo->id = callId.toStdString(); + callInfo->id = callId; auto now = std::chrono::steady_clock::now(); auto system_now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); auto diff = static_cast<int64_t>(system_now) - std::stol(details["TIMESTAMP_START"].toStdString()); callInfo->startTime = now - std::chrono::seconds(diff); - callInfo->status = call::to_status(details["CALL_STATE"].toStdString()); + callInfo->status = call::to_status(details["CALL_STATE"]); auto endId = details["PEER_NUMBER"].indexOf("@"); - callInfo->peerUri = details["PEER_NUMBER"].left(endId).toStdString(); + callInfo->peerUri = details["PEER_NUMBER"].left(endId); if (linked.owner.profileInfo.type == lrc::api::profile::Type::RING) { callInfo->peerUri = "ring:" + callInfo->peerUri; } callInfo->videoMuted = details["VIDEO_MUTED"] == "true"; callInfo->audioMuted = details["AUDIO_MUTED"] == "true"; callInfo->type = call::Type::DIALOG; - calls.emplace(callId.toStdString(), std::move(callInfo)); + calls.emplace(callId, std::move(callInfo)); // NOTE/BUG: the videorenderer can't know that the client has restarted // So, for now, a user will have to manually restart the medias until // this renderer is not redesigned. @@ -558,28 +554,28 @@ NewCallModelPimpl::initConferencesFromDaemon() { QMap<QString, QString> details = CallManager::instance().getConferenceDetails(callId); auto callInfo = std::make_shared<call::Info>(); - callInfo->id = callId.toStdString(); + callInfo->id = callId; QStringList callList = CallManager::instance().getParticipantList(callId); auto isForThisAccount = true; foreach(const auto& call, callList) { MapStringString callDetails = CallManager::instance().getCallDetails(call); - isForThisAccount = callDetails["ACCOUNTID"].toStdString() == linked.owner.id; + isForThisAccount = callDetails["ACCOUNTID"] == linked.owner.id; if (!isForThisAccount) break; auto now = std::chrono::steady_clock::now(); auto system_now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); auto diff = static_cast<int64_t>(system_now) - std::stol(callDetails["TIMESTAMP_START"].toStdString()); callInfo->status = details["CONF_STATE"] == "ACTIVE_ATTACHED"? call::Status::IN_PROGRESS : call::Status::PAUSED; callInfo->startTime = now - std::chrono::seconds(diff); - emit linked.callAddedToConference(call.toStdString(), callId.toStdString()); + emit linked.callAddedToConference(call, callId); } if (!isForThisAccount) break; callInfo->type = call::Type::CONFERENCE; - calls.emplace(callId.toStdString(), std::move(callInfo)); + calls.emplace(callId, std::move(callInfo)); } } void -NewCallModel::setCurrentCall(const std::string& callId) const +NewCallModel::setCurrentCall(const QString& callId) const { if (!pimpl_->manageCurrentCall_) return; auto it = pimpl_->pendingConferences_.find(callId); @@ -588,7 +584,6 @@ NewCallModel::setCurrentCall(const std::string& callId) const if (it != pimpl_->pendingConferences_.end()) return; if (!hasCall(callId)) return; - // The client should be able to set the current call multiple times if (pimpl_->currentCall_ == callId) return; pimpl_->currentCall_ = callId; @@ -598,42 +593,42 @@ NewCallModel::setCurrentCall(const std::string& callId) const if (call->status == call::Status::PAUSED) { auto& call = pimpl_->calls[callId]; if (call->type == call::Type::DIALOG) { - CallManager::instance().unhold(callId.c_str()); + CallManager::instance().unhold(callId); } else { - CallManager::instance().unholdConference(callId.c_str()); + CallManager::instance().unholdConference(callId); } } - std::vector<std::string> filterCalls; + VectorString filterCalls; QStringList conferences = CallManager::instance().getConferenceList(); for (const auto& confId : conferences) { QStringList callList = CallManager::instance().getParticipantList(confId); foreach(const auto& cid, callList) { - filterCalls.emplace_back(cid.toStdString()); + filterCalls.push_back(cid); } } for (const auto& cid : Lrc::activeCalls()) { auto filtered = std::find(filterCalls.begin(), filterCalls.end(), cid) != filterCalls.end(); if (cid != callId && !filtered) { - CallManager::instance().hold(cid.c_str()); + CallManager::instance().hold(cid); } } if (!lrc::api::Lrc::holdConferences) { return; } for (const auto& confId : conferences) { - if (callId != confId.toStdString()) + if (callId != confId) CallManager::instance().holdConference(confId); } } void -NewCallModel::sendSipMessage(const std::string& callId, const std::string& body) const +NewCallModel::sendSipMessage(const QString& callId, const QString& body) const { - QMap<QString, QString> payloads; - payloads["text/plain"] = body.c_str(); + MapStringString payloads; + payloads["text/plain"] = body; - CallManager::instance().sendTextMessage(callId.c_str(), payloads, true /* not used */); + CallManager::instance().sendTextMessage(callId, payloads, true /* not used */); } void @@ -650,19 +645,19 @@ NewCallModel::hangupCallsAndConferences() } void -NewCallModelPimpl::slotIncomingCall(const std::string& accountId, const std::string& callId, const std::string& fromId, const std::string& displayname) +NewCallModelPimpl::slotIncomingCall(const QString& accountId, const QString& callId, const QString& fromId, const QString& displayname) { if (linked.owner.id != accountId) { return; } // do not use auto here (QDBusPendingReply<MapStringString>) - MapStringString callDetails = CallManager::instance().getCallDetails(callId.c_str()); + MapStringString callDetails = CallManager::instance().getCallDetails(callId); auto callInfo = std::make_shared<call::Info>(); callInfo->id = callId; // peer uri = ring:<jami_id> or sip number - auto uri = (linked.owner.profileInfo.type != profile::Type::SIP && fromId.find("ring:") == std::string::npos) ? "ring:" + fromId : fromId; + auto uri = (linked.owner.profileInfo.type != profile::Type::SIP && !fromId.contains("ring:")) ? "ring:" + fromId : fromId; callInfo->peerUri = uri; callInfo->isOutgoing = false; callInfo->status = call::Status::INCOMING_RINGING; @@ -684,7 +679,7 @@ NewCallModelPimpl::slotIncomingCall(const std::string& accountId, const std::str } void -NewCallModelPimpl::slotCallStateChanged(const std::string& callId, const std::string& state, int code) +NewCallModelPimpl::slotCallStateChanged(const QString& callId, const QString& state, int code) { if (!linked.hasCall(callId)) return; @@ -705,8 +700,10 @@ NewCallModelPimpl::slotCallStateChanged(const std::string& callId, const std::st return; } - qDebug("slotCallStateChanged (call: %s), from %s to %s", callId.c_str(), - call::to_string(previousStatus).c_str(), call::to_string(status).c_str()); + qDebug() << QString("slotCallStateChanged (call: %s), from %s to %s") + .arg(callId) + .arg(call::to_string(previousStatus)) + .arg(call::to_string(status)); // NOTE: signal emission order matters, always emit CallStatusChanged before CallEnded emit linked.callStatusChanged(callId, code); @@ -737,11 +734,11 @@ NewCallModelPimpl::slotCallStateChanged(const std::string& callId, const std::st } void -NewCallModelPimpl::slotincomingVCardChunk(const std::string& callId, - const std::string& from, +NewCallModelPimpl::slotincomingVCardChunk(const QString& callId, + const QString& from, int part, int numberOfParts, - const std::string& payload) + const QString& payload) { if (!linked.hasCall(callId)) return; @@ -750,22 +747,22 @@ NewCallModelPimpl::slotincomingVCardChunk(const std::string& callId, vcardsChunks[from][part-1] = payload; if ( not std::any_of(vcardsChunks[from].begin(), vcardsChunks[from].end(), - [](const auto& s) { return s.empty(); }) ) { + [](const auto& s) { return s.isEmpty(); }) ) { profile::Info profileInfo; profileInfo.uri = from; profileInfo.type = profile::Type::RING; - std::string vcardPhoto; + QString vcardPhoto; for (auto& chunk : vcardsChunks[from]) vcardPhoto += chunk; - for (auto& e : QString(vcardPhoto.c_str()).split( "\n" )) + for (auto& e : QString(vcardPhoto).split( "\n" )) if (e.contains("PHOTO")) - profileInfo.avatar = e.split( ":" )[1].toStdString(); + profileInfo.avatar = e.split( ":" )[1]; else if (e.contains("FN")) - profileInfo.alias = e.split( ":" )[1].toStdString(); + profileInfo.alias = e.split( ":" )[1]; contact::Info contactInfo; contactInfo.profileInfo = profileInfo; @@ -774,25 +771,25 @@ NewCallModelPimpl::slotincomingVCardChunk(const std::string& callId, vcardsChunks.erase(from); // Transfer is finish, we don't want to reuse this entry. } } else { - vcardsChunks[from] = std::vector<std::string>(numberOfParts); + vcardsChunks[from] = VectorString(numberOfParts); vcardsChunks[from][part-1] = payload; } } void -NewCallModelPimpl::slotVoiceMailNotify(const std::string & accountId, int newCount, int oldCount, int urgentCount) +NewCallModelPimpl::slotVoiceMailNotify(const QString& accountId, int newCount, int oldCount, int urgentCount) { emit linked.voiceMailNotify(accountId, newCount, oldCount, urgentCount); } bool -NewCallModel::hasCall(const std::string& callId) const +NewCallModel::hasCall(const QString& callId) const { return pimpl_->calls.find(callId) != pimpl_->calls.end(); } void -NewCallModelPimpl::slotConferenceCreated(const std::string& confId) +NewCallModelPimpl::slotConferenceCreated(const QString& confId) { auto callInfo = std::make_shared<call::Info>(); callInfo->id = confId; @@ -800,14 +797,14 @@ NewCallModelPimpl::slotConferenceCreated(const std::string& confId) callInfo->type = call::Type::CONFERENCE; callInfo->startTime = std::chrono::steady_clock::now(); calls[confId] = callInfo; - QStringList callList = CallManager::instance().getParticipantList(confId.c_str()); + QStringList callList = CallManager::instance().getParticipantList(confId); foreach(const auto& call, callList) { - emit linked.callAddedToConference(call.toStdString(), confId); + emit linked.callAddedToConference(call, confId); } } void -NewCallModelPimpl::sendProfile(const std::string& callId) +NewCallModelPimpl::sendProfile(const QString& callId) { auto vCard = linked.owner.accountModel->accountVCard(linked.owner.id); @@ -824,10 +821,10 @@ NewCallModelPimpl::sendProfile(const std::string& callId) .arg( key.c_str() ) .arg( QString::number( i+1 ) ) .arg( QString::number( total ) ) - ] = vCard.substr(0, sizeLimit).c_str(); - vCard = vCard.substr(sizeLimit); + ] = vCard.left(sizeLimit); + vCard.remove(0, sizeLimit); ++i; - CallManager::instance().sendTextMessage(callId.c_str(), chunk, false); + CallManager::instance().sendTextMessage(callId, chunk, false); } } diff --git a/src/newcodecmodel.cpp b/src/newcodecmodel.cpp index 8098a191755a373169ac3460c4ce2ffaf2f29c37..54fd24ab5e218474069662b00bf9d8d340ced55c 100644 --- a/src/newcodecmodel.cpp +++ b/src/newcodecmodel.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * + * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * * Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com> * * * * This library is free software; you can redistribute it and/or * @@ -17,10 +17,6 @@ ***************************************************************************/ #include "api/newcodecmodel.h" -// std -#include <list> -#include <mutex> - // LRC #include "callbackshandler.h" #include "dbus/configurationmanager.h" @@ -30,11 +26,14 @@ // Qt #include <QObject> +#include <QList> + +// std +#include <mutex> namespace lrc { - using namespace api; class NewCodecModelPimpl: public QObject @@ -47,9 +46,9 @@ public: void loadFromDaemon(); QVector<unsigned int> codecsList_; - std::list<Codec> videoCodecs; + QList<Codec> videoCodecs; std::mutex audioCodecsMtx; - std::list<Codec> audioCodecs; + QList<Codec> audioCodecs; std::mutex videoCodecsMtx; const CallbacksHandler& callbacksHandler; @@ -69,13 +68,13 @@ NewCodecModel::NewCodecModel(const account::Info& owner, const CallbacksHandler& NewCodecModel::~NewCodecModel() {} -std::list<Codec> +QList<Codec> NewCodecModel::getAudioCodecs() const { return pimpl_->audioCodecs; } -std::list<Codec> +QList<Codec> NewCodecModel::getVideoCodecs() const { return pimpl_->videoCodecs; @@ -112,7 +111,8 @@ NewCodecModel::decreasePriority(const unsigned int& codecId, bool isVideo) { std::unique_lock<std::mutex> lock(mutex); auto it = codecs.begin(); - if (codecs.rbegin()->id == codecId) { + if ( codecs.size() > 0 && + (codecs.end() - 1)->id == codecId) { // Already at bottom, abort return; } @@ -204,7 +204,7 @@ void NewCodecModel::quality(const unsigned int& codecId, double quality) { auto isAudio = true; - auto qualityStr = std::to_string(static_cast<int>(quality)); + auto qualityStr = toQString(static_cast<int>(quality)); Codec finalCodec; { std::unique_lock<std::mutex> lock(pimpl_->videoCodecsMtx); @@ -236,7 +236,7 @@ void NewCodecModel::bitrate(const unsigned int& codecId, double bitrate) { auto isAudio = true; - auto bitrateStr = std::to_string(static_cast<int>(bitrate)); + auto bitrateStr = toQString(static_cast<int>(bitrate)); Codec finalCodec; { std::unique_lock<std::mutex> lock(pimpl_->videoCodecsMtx); @@ -288,7 +288,7 @@ NewCodecModelPimpl::loadFromDaemon() std::unique_lock<std::mutex> lock(videoCodecsMtx); videoCodecs.clear(); } - QVector<unsigned int> activeCodecs = ConfigurationManager::instance().getActiveCodecList(linked.owner.id.c_str()); + QVector<unsigned int> activeCodecs = ConfigurationManager::instance().getActiveCodecList(linked.owner.id); for (const auto& id : activeCodecs) { addCodec(id, activeCodecs); } @@ -318,7 +318,7 @@ NewCodecModelPimpl::setActiveCodecs() } } } - ConfigurationManager::instance().setActiveCodecList(linked.owner.id.c_str(), enabledCodecs); + ConfigurationManager::instance().setActiveCodecList(linked.owner.id, enabledCodecs); // Refresh list from daemon loadFromDaemon(); } @@ -326,26 +326,26 @@ NewCodecModelPimpl::setActiveCodecs() void NewCodecModelPimpl::addCodec(const unsigned int& id, const QVector<unsigned int>& activeCodecs) { - MapStringString details = ConfigurationManager::instance().getCodecDetails(linked.owner.id.c_str(), id); + MapStringString details = ConfigurationManager::instance().getCodecDetails(linked.owner.id, id); Codec codec; codec.id = id; codec.enabled = activeCodecs.indexOf(id) != -1; - codec.name = details[DRing::Account::ConfProperties::CodecInfo::NAME].toStdString(); - codec.samplerate = details[DRing::Account::ConfProperties::CodecInfo::SAMPLE_RATE].toStdString(); - codec.bitrate = details[DRing::Account::ConfProperties::CodecInfo::BITRATE].toStdString(); - codec.min_bitrate = details[DRing::Account::ConfProperties::CodecInfo::MIN_BITRATE].toStdString(); - codec.max_bitrate = details[DRing::Account::ConfProperties::CodecInfo::MAX_BITRATE].toStdString(); - codec.type = details[DRing::Account::ConfProperties::CodecInfo::TYPE].toStdString(); - codec.quality = details[DRing::Account::ConfProperties::CodecInfo::QUALITY].toStdString(); - codec.min_quality = details[DRing::Account::ConfProperties::CodecInfo::MIN_QUALITY].toStdString(); - codec.max_quality = details[DRing::Account::ConfProperties::CodecInfo::MAX_QUALITY].toStdString(); - codec.auto_quality_enabled = details[DRing::Account::ConfProperties::CodecInfo::AUTO_QUALITY_ENABLED].toStdString() == "true"; + codec.name = details[DRing::Account::ConfProperties::CodecInfo::NAME]; + codec.samplerate = details[DRing::Account::ConfProperties::CodecInfo::SAMPLE_RATE]; + codec.bitrate = details[DRing::Account::ConfProperties::CodecInfo::BITRATE]; + codec.min_bitrate = details[DRing::Account::ConfProperties::CodecInfo::MIN_BITRATE]; + codec.max_bitrate = details[DRing::Account::ConfProperties::CodecInfo::MAX_BITRATE]; + codec.type = details[DRing::Account::ConfProperties::CodecInfo::TYPE]; + codec.quality = details[DRing::Account::ConfProperties::CodecInfo::QUALITY]; + codec.min_quality = details[DRing::Account::ConfProperties::CodecInfo::MIN_QUALITY]; + codec.max_quality = details[DRing::Account::ConfProperties::CodecInfo::MAX_QUALITY]; + codec.auto_quality_enabled = details[DRing::Account::ConfProperties::CodecInfo::AUTO_QUALITY_ENABLED] == "true"; if (codec.type == "AUDIO") { std::unique_lock<std::mutex> lock(audioCodecsMtx); - audioCodecs.emplace_back(codec); + audioCodecs.push_back(codec); } else { std::unique_lock<std::mutex> lock(videoCodecsMtx); - videoCodecs.emplace_back(codec); + videoCodecs.push_back(codec); } } @@ -353,17 +353,17 @@ void NewCodecModelPimpl::setCodecDetails(const Codec& codec, bool isAudio) { MapStringString details; - details[ DRing::Account::ConfProperties::CodecInfo::NAME ] = codec.name.c_str(); - details[ DRing::Account::ConfProperties::CodecInfo::SAMPLE_RATE ] = codec.samplerate.c_str(); - details[ DRing::Account::ConfProperties::CodecInfo::BITRATE ] = codec.bitrate.c_str(); - details[ DRing::Account::ConfProperties::CodecInfo::MIN_BITRATE ] = codec.min_bitrate.c_str(); - details[ DRing::Account::ConfProperties::CodecInfo::MAX_BITRATE ] = codec.max_bitrate.c_str(); + details[ DRing::Account::ConfProperties::CodecInfo::NAME ] = codec.name; + details[ DRing::Account::ConfProperties::CodecInfo::SAMPLE_RATE ] = codec.samplerate; + details[ DRing::Account::ConfProperties::CodecInfo::BITRATE ] = codec.bitrate; + details[ DRing::Account::ConfProperties::CodecInfo::MIN_BITRATE ] = codec.min_bitrate; + details[ DRing::Account::ConfProperties::CodecInfo::MAX_BITRATE ] = codec.max_bitrate; details[ DRing::Account::ConfProperties::CodecInfo::TYPE ] = isAudio? "AUDIO" : "VIDEO"; - details[ DRing::Account::ConfProperties::CodecInfo::QUALITY ] = codec.quality.c_str(); - details[ DRing::Account::ConfProperties::CodecInfo::MIN_QUALITY ] = codec.min_quality.c_str(); - details[ DRing::Account::ConfProperties::CodecInfo::MAX_QUALITY ] = codec.max_quality.c_str(); + details[ DRing::Account::ConfProperties::CodecInfo::QUALITY ] = codec.quality; + details[ DRing::Account::ConfProperties::CodecInfo::MIN_QUALITY ] = codec.min_quality; + details[ DRing::Account::ConfProperties::CodecInfo::MAX_QUALITY ] = codec.max_quality; details[ DRing::Account::ConfProperties::CodecInfo::AUTO_QUALITY_ENABLED] = codec.auto_quality_enabled? "true" : "false"; - ConfigurationManager::instance().setCodecDetails(linked.owner.id.c_str(), codec.id, details); + ConfigurationManager::instance().setCodecDetails(linked.owner.id, codec.id, details); } } // namespace lrc diff --git a/src/newdevicemodel.cpp b/src/newdevicemodel.cpp index 4ab13eeac6ac1e972cfbb332966719272331237e..bc50e2a97c9ef7daccf84c05ccd52488d6b1f7a2 100644 --- a/src/newdevicemodel.cpp +++ b/src/newdevicemodel.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * + * Copyright (C) 2017-2020 Savoir-faire Linux Inc. * * Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com> * * * * This library is free software; you can redistribute it and/or * @@ -17,25 +17,20 @@ ***************************************************************************/ #include "api/newdevicemodel.h" -// std -#include <list> -#include <mutex> - -// LRC #include "api/newaccountmodel.h" #include "callbackshandler.h" #include "dbus/configurationmanager.h" -// Daemon #include <account_const.h> -// Qt #include <QObject> +#include <list> +#include <mutex> + namespace lrc { - using namespace api; class NewDeviceModelPimpl: public QObject @@ -49,16 +44,16 @@ public: const NewDeviceModel& linked; std::mutex devicesMtx_; - std::string currentDeviceId_; - std::list<Device> devices_; + QString currentDeviceId_; + QList<Device> devices_; public Q_SLOTS: /** * Listen from CallbacksHandler to get when a device name changed or a device is added * @param accountId interaction receiver. * @param devices A map of device IDs with corresponding labels. */ - void slotKnownDevicesChanged(const std::string& accountId, - const std::map<std::string, std::string> devices); + void slotKnownDevicesChanged(const QString& accountId, + const MapStringString devices); /** * update devices_ when a device is revoked @@ -66,8 +61,8 @@ public Q_SLOTS: * @param deviceId * @param status SUCCESS = 0, WRONG_PASSWORD = 1, UNKNOWN_DEVICE = 2 */ - void slotDeviceRevocationEnded(const std::string& accountId, - const std::string& deviceId, + void slotDeviceRevocationEnded(const QString& accountId, + const QString& deviceId, const int status); }; @@ -78,14 +73,14 @@ NewDeviceModel::NewDeviceModel(const account::Info& owner, const CallbacksHandle NewDeviceModel::~NewDeviceModel() {} -std::list<Device> +QList<Device> NewDeviceModel::getAllDevices() const { return pimpl_->devices_; } Device -NewDeviceModel::getDevice(const std::string& id) const +NewDeviceModel::getDevice(const QString& id) const { std::lock_guard<std::mutex> lock(pimpl_->devicesMtx_); auto i = std::find_if( @@ -100,13 +95,13 @@ NewDeviceModel::getDevice(const std::string& id) const } void -NewDeviceModel::revokeDevice(const std::string& id, const std::string& password) +NewDeviceModel::revokeDevice(const QString& id, const QString& password) { - ConfigurationManager::instance().revokeDevice(owner.id.c_str(), password.c_str(), id.c_str()); + ConfigurationManager::instance().revokeDevice(owner.id, password, id); } void -NewDeviceModel::setCurrentDeviceName(const std::string& newName) +NewDeviceModel::setCurrentDeviceName(const QString& newName) { // Update deamon config auto config = owner.accountModel->getAccountConfig(owner.id); @@ -126,22 +121,22 @@ NewDeviceModelPimpl::NewDeviceModelPimpl(const NewDeviceModel& linked, const Cal , callbacksHandler(callbacksHandler) , devices_({}) { - const MapStringString aDetails = ConfigurationManager::instance().getAccountDetails(linked.owner.id.c_str()); - currentDeviceId_ = aDetails.value(DRing::Account::ConfProperties::RING_DEVICE_ID).toStdString(); - const MapStringString accountDevices = ConfigurationManager::instance().getKnownRingDevices(linked.owner.id.c_str()); + const MapStringString aDetails = ConfigurationManager::instance().getAccountDetails(linked.owner.id); + currentDeviceId_ = aDetails.value(DRing::Account::ConfProperties::RING_DEVICE_ID); + const MapStringString accountDevices = ConfigurationManager::instance().getKnownRingDevices(linked.owner.id); auto it = accountDevices.begin(); while (it != accountDevices.end()) { { std::lock_guard<std::mutex> lock(devicesMtx_); auto device = Device { - /* id= */it.key().toStdString(), - /* name= */it.value().toStdString(), - /* isCurrent= */it.key().toStdString() == currentDeviceId_ + /* id= */it.key(), + /* name= */it.value(), + /* isCurrent= */it.key() == currentDeviceId_ }; if (device.isCurrent) { - devices_.emplace_front(device); + devices_.push_back(device); } else { - devices_.emplace_back(device); + devices_.push_back(device); } } ++it; @@ -162,22 +157,22 @@ NewDeviceModelPimpl::~NewDeviceModelPimpl() } void -NewDeviceModelPimpl::slotKnownDevicesChanged(const std::string& accountId, - const std::map<std::string, std::string> devices) +NewDeviceModelPimpl::slotKnownDevicesChanged(const QString& accountId, + const MapStringString devices) { if (accountId != linked.owner.id) return; auto devicesMap = devices; // Update current devices - std::list<std::string> updatedDevices; + QStringList updatedDevices; { std::lock_guard<std::mutex> lock(devicesMtx_); for (auto& device : devices_) { if (devicesMap.find(device.id) != devicesMap.end()) { if (device.name != devicesMap[device.id]) { - updatedDevices.emplace_back(device.id); + updatedDevices.push_back(device.id); device.name = devicesMap[device.id]; } - devicesMap.erase(device.id); + devicesMap.remove(device.id); } } } @@ -185,17 +180,17 @@ NewDeviceModelPimpl::slotKnownDevicesChanged(const std::string& accountId, emit linked.deviceUpdated(device); // Add new devices - std::list<std::string> addedDevices; + QStringList addedDevices; { std::lock_guard<std::mutex> lock(devicesMtx_); auto it = devicesMap.begin(); while (it != devicesMap.end()) { - devices_.emplace_back(Device { - /* id= */it->first, - /* name= */it->second, + devices_.push_back(Device { + /* id= */it.key(), + /* name= */it.value(), /* isCurrent= */false }); - addedDevices.emplace_back(it->first); + addedDevices.push_back(it.key()); ++it; } } @@ -203,10 +198,9 @@ NewDeviceModelPimpl::slotKnownDevicesChanged(const std::string& accountId, emit linked.deviceAdded(device); } - void -NewDeviceModelPimpl::slotDeviceRevocationEnded(const std::string& accountId, - const std::string& deviceId, +NewDeviceModelPimpl::slotDeviceRevocationEnded(const QString& accountId, + const QString& deviceId, const int status) { if (accountId != linked.owner.id) return; diff --git a/src/newvideo.cpp b/src/newvideo.cpp index 7d29994f5538282bab53e7147553e219dfb02e21..e779ed076e12210080ec1a40db99433d6a49cd50 100644 --- a/src/newvideo.cpp +++ b/src/newvideo.cpp @@ -39,14 +39,14 @@ using namespace api::video; class RendererPimpl: public QObject { public: - RendererPimpl(Renderer& linked, const std::string& id, - Settings videoSettings, const std::string& shmPath, + RendererPimpl(Renderer& linked, const QString& id, + Settings videoSettings, const QString& shmPath, const bool useAVFrame); ~RendererPimpl(); Renderer& linked; - std::string id_; + QString id_; Settings videoSettings_; QThread thread_; bool usingAVFrame_; @@ -56,7 +56,7 @@ public: * @param res the string to convert * @return the QSize object */ - static QSize stringToQSize(const std::string& res); + static QSize stringToQSize(const QString& res); std::mutex rendering_mtx_; @@ -79,8 +79,8 @@ namespace api namespace video { -Renderer::Renderer(const std::string& id, Settings videoSettings, - const std::string& shmPath, const bool useAVFrame) +Renderer::Renderer(const QString& id, Settings videoSettings, + const QString& shmPath, const bool useAVFrame) : pimpl_(std::make_unique<RendererPimpl>(*this, id, videoSettings, shmPath, useAVFrame)) {} @@ -96,9 +96,9 @@ Renderer::initThread() return; #ifdef ENABLE_LIBWRAP if(pimpl_->usingAVFrame_) { - VideoManager::instance().registerAVSinkTarget(pimpl_->id_.c_str(), pimpl_->renderer->avTarget()); + VideoManager::instance().registerAVSinkTarget(pimpl_->id_, pimpl_->renderer->avTarget()); } else { - VideoManager::instance().registerSinkTarget(pimpl_->id_.c_str(), pimpl_->renderer->target()); + VideoManager::instance().registerSinkTarget(pimpl_->id_, pimpl_->renderer->target()); } #endif if (!pimpl_->thread_.isRunning()) @@ -106,7 +106,7 @@ Renderer::initThread() } void -Renderer::update(const std::string& res, const std::string& shmPath) +Renderer::update(const QString& res, const QString& shmPath) { if (!pimpl_->thread_.isRunning()) pimpl_->thread_.start(); @@ -117,12 +117,12 @@ Renderer::update(const std::string& res, const std::string& shmPath) #ifdef ENABLE_LIBWRAP if(pimpl_->usingAVFrame_) { - VideoManager::instance().registerAVSinkTarget(pimpl_->id_.c_str(), pimpl_->renderer->avTarget()); + VideoManager::instance().registerAVSinkTarget(pimpl_->id_, pimpl_->renderer->avTarget()); } else { - VideoManager::instance().registerSinkTarget(pimpl_->id_.c_str(), pimpl_->renderer->target()); + VideoManager::instance().registerSinkTarget(pimpl_->id_, pimpl_->renderer->target()); } #else //ENABLE_LIBWRAP - pimpl_->renderer->setShmPath(shmPath.c_str()); + pimpl_->renderer->setShmPath(shmPath); #endif } @@ -143,7 +143,7 @@ Renderer::useAVFrame(bool useAVFrame) { #endif } -std::string +QString Renderer::getId() const { return pimpl_->id_; @@ -208,8 +208,8 @@ Renderer::stopRendering() }} // end of api::video -RendererPimpl::RendererPimpl(Renderer& linked, const std::string& id, - Settings videoSettings, const std::string& shmPath, bool useAVFrame) +RendererPimpl::RendererPimpl(Renderer& linked, const QString& id, + Settings videoSettings, const QString& shmPath, bool useAVFrame) : linked(linked) , id_(id) , videoSettings_(videoSettings) @@ -217,14 +217,14 @@ RendererPimpl::RendererPimpl(Renderer& linked, const std::string& id, { QSize size = stringToQSize(videoSettings.size); #ifdef ENABLE_LIBWRAP - renderer = std::make_unique<Video::DirectRenderer>(id.c_str(), size, usingAVFrame_); + renderer = std::make_unique<Video::DirectRenderer>(id, size, usingAVFrame_); #else // ENABLE_LIBWRAP - renderer = std::make_unique<Video::ShmRenderer>(id.c_str(), shmPath.c_str(), size); + renderer = std::make_unique<Video::ShmRenderer>(id, shmPath, size); #endif renderer->moveToThread(&thread_); connect(&*renderer, &Video::Renderer::frameUpdated, - this, &RendererPimpl::slotFrameUpdated); + this, &RendererPimpl::slotFrameUpdated); } RendererPimpl::~RendererPimpl() @@ -233,9 +233,9 @@ RendererPimpl::~RendererPimpl() } QSize -RendererPimpl::stringToQSize(const std::string& res) +RendererPimpl::stringToQSize(const QString& res) { - QString sizeStr = res.c_str(); + QString sizeStr = res; auto sizeSplited = sizeStr.split('x'); if (sizeSplited.size() != 2) return {}; auto width = sizeSplited.at(0).toInt(); diff --git a/src/peerdiscoverymodel.cpp b/src/peerdiscoverymodel.cpp index 949b0de030be1c61a5eed91a48d6869682df2dfc..2c19b26e1cf7c2743495d9048e189b8054d7f0a4 100644 --- a/src/peerdiscoverymodel.cpp +++ b/src/peerdiscoverymodel.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright (C) 2019-2020 Savoir-faire Linux Inc. * + * Copyright (C) 2019-2020 Savoir-faire Linux Inc. * * Author: Mingrui Zhang <mingrui.zhang@savoirfairelinux.com> * * * * This library is free software; you can redistribute it and/or * @@ -34,12 +34,12 @@ class PeerDiscoveryModelPimpl: public QObject public: PeerDiscoveryModelPimpl(PeerDiscoveryModel& linked, const CallbacksHandler& callbackHandler, - const std::string& accountID); + const QString& accountID); ~PeerDiscoveryModelPimpl(); PeerDiscoveryModel& linked_; const CallbacksHandler& callbacksHandler_; - const std::string accountID_; + const QString accountID_; public Q_SLOTS: @@ -48,10 +48,10 @@ public Q_SLOTS: * @param accountId * @param status */ - void slotPeerMapStatusChanged(const std::string& accountID, const std::string& contactUri, int state, const std::string& displayname); + void slotPeerMapStatusChanged(const QString& accountID, const QString& contactUri, int state, const QString& displayname); }; -PeerDiscoveryModel::PeerDiscoveryModel(const CallbacksHandler& callbacksHandler, const std::string& accountID) +PeerDiscoveryModel::PeerDiscoveryModel(const CallbacksHandler& callbacksHandler, const QString& accountID) : QObject() , pimpl_(std::make_unique<PeerDiscoveryModelPimpl>(*this, callbacksHandler, accountID)) { @@ -63,7 +63,7 @@ PeerDiscoveryModel::~PeerDiscoveryModel() PeerDiscoveryModelPimpl::PeerDiscoveryModelPimpl(PeerDiscoveryModel& linked, const CallbacksHandler& callbacksHandler, - const std::string& accountID) + const QString& accountID) : linked_(linked) , callbacksHandler_(callbacksHandler) , accountID_(accountID) @@ -77,11 +77,11 @@ PeerDiscoveryModelPimpl::~PeerDiscoveryModelPimpl() } void -PeerDiscoveryModelPimpl::slotPeerMapStatusChanged(const std::string& accountID, const std::string& contactUri, int state, const std::string& displayname) +PeerDiscoveryModelPimpl::slotPeerMapStatusChanged(const QString& accountID, const QString& contactUri, int state, const QString& displayname) { if(accountID != accountID_){ return; - } + } emit linked_.modelChanged(contactUri,state == 0 ? PeerModelChanged::INSERT : PeerModelChanged::REMOVE,displayname); } @@ -90,7 +90,7 @@ std::vector<PeerContact> PeerDiscoveryModel::getNearbyPeers() const { std::vector<PeerContact> result; - const MapStringString nearbyPeers = ConfigurationManager::instance().getNearbyPeers(QString::fromStdString(pimpl_->accountID_)); + const MapStringString nearbyPeers = ConfigurationManager::instance().getNearbyPeers(pimpl_->accountID_); result.reserve(nearbyPeers.size()); QMap<QString, QString>::const_iterator i = nearbyPeers.constBegin(); diff --git a/src/qtwrapper/configurationmanager_wrap.h b/src/qtwrapper/configurationmanager_wrap.h index f384bed4c6054ca9552268f155074c4e21b8c87d..a2795e12bd6630179988419ad01fc9bb4e054434 100644 --- a/src/qtwrapper/configurationmanager_wrap.h +++ b/src/qtwrapper/configurationmanager_wrap.h @@ -170,7 +170,7 @@ public: }), exportable_callback<DebugSignal::MessageSend>( [this](const std::string& message) { - Q_EMIT this->debugMessageReceived(message); + Q_EMIT this->debugMessageReceived(QString(message.c_str())); }), }; @@ -521,12 +521,12 @@ public Q_SLOTS: // METHODS DRing::setNoiseSuppressState(state); } - bool isAudioMeterActive(const std::string& id) { - return DRing::isAudioMeterActive(id); + bool isAudioMeterActive(const QString& id) { + return DRing::isAudioMeterActive(id.toStdString()); } - void setAudioMeterState(const std::string& id, bool state) { - DRing::setAudioMeterState(id, state); + void setAudioMeterState(const QString& id, bool state) { + DRing::setAudioMeterState(id.toStdString(), state); } void setRecordPath(const QString& rec) { @@ -734,7 +734,7 @@ Q_SIGNALS: // SIGNALS void contactRemoved(const QString &accountID, const QString &uri, bool banned); void dataTransferEvent(qulonglong transfer_id, uint code); void deviceRevocationEnded(const QString& accountId, const QString& deviceId, int status); - void debugMessageReceived(const std::string& message); + void debugMessageReceived(const QString& message); }; namespace org { namespace ring { namespace Ring { diff --git a/src/qtwrapper/conversions_wrap.hpp b/src/qtwrapper/conversions_wrap.hpp index 1fc63e178a7ce271bf4610ff4270a1985bec817e..e96b6fd63bd64fd6f92422bec5d999fe265d24e1 100644 --- a/src/qtwrapper/conversions_wrap.hpp +++ b/src/qtwrapper/conversions_wrap.hpp @@ -21,6 +21,7 @@ #include <map> #include <string> #include <vector> +#include <ctime> #include "../typedefs.h" @@ -124,6 +125,18 @@ toQString(int i) noexcept return QString::number(i); } +static inline QString +toQString(unsigned int i) noexcept +{ + return QString::number(i); +} + +static inline QString +toQString(uint64_t i) noexcept +{ + return QString::number(i); +} + static inline bool toBool(QString qs) noexcept { @@ -142,4 +155,10 @@ toStdString(QString qs) noexcept return qs.toStdString(); } +static inline QString +toQString(const std::time_t& t) noexcept +{ + return QString::fromStdString(std::to_string(t)); +} + #endif //CONVERSIONS_WRAP_H diff --git a/src/shmrenderer.cpp b/src/shmrenderer.cpp index fa121219ec859c48b8eafbe1e04986bd5c990683..d2e431e1847d19760eafb7c519d8aa716e5e764d 100644 --- a/src/shmrenderer.cpp +++ b/src/shmrenderer.cpp @@ -77,7 +77,6 @@ class ShmRendererPrivate final : public QObject public: ShmRendererPrivate(ShmRenderer* parent); - //Types using TimePoint = std::chrono::time_point<std::chrono::system_clock>; @@ -125,7 +124,7 @@ ShmRendererPrivate::ShmRendererPrivate(ShmRenderer* parent) } /// Constructor -ShmRenderer::ShmRenderer(const QByteArray& id, const QString& shmPath, const QSize& res) +ShmRenderer::ShmRenderer(const QString& id, const QString& shmPath, const QSize& res) : Renderer(id, res) , d_ptr(std::make_unique<ShmRendererPrivate>(this)) { diff --git a/src/shmrenderer.h b/src/shmrenderer.h index 3ba7e6e40dddfad94048c31a5ccbdcf37f4f631e..44e5221269c25999a5e93b33410e8dbd1e61f0dd 100644 --- a/src/shmrenderer.h +++ b/src/shmrenderer.h @@ -44,7 +44,7 @@ class LIB_EXPORT ShmRenderer final : public Renderer { public: //Constructor - ShmRenderer (const QByteArray& id, const QString& shmPath, const QSize& res); + ShmRenderer (const QString& id, const QString& shmPath, const QSize& res); virtual ~ShmRenderer(); //Mutators diff --git a/src/video/renderer.cpp b/src/video/renderer.cpp index 8bc114058c22a45a8f9720a39f561ce4dde1f2e4..b6e66f15de58309abfa557af5b94d89df47ffc60 100644 --- a/src/video/renderer.cpp +++ b/src/video/renderer.cpp @@ -31,7 +31,8 @@ Video::RendererPrivate::RendererPrivate(Video::Renderer* parent) { } -Video::Renderer::Renderer(const QByteArray& id, const QSize& res) : d_ptr(new RendererPrivate(this)) +Video::Renderer::Renderer(const QString& id, const QSize& res) + : d_ptr(new RendererPrivate(this)) { setObjectName("Renderer:"+id); d_ptr->m_pSize = res; diff --git a/src/video/renderer.h b/src/video/renderer.h index cb764e6131c2b52f7b6abfadeabe87fafdf1e5dc..758b3253c9d96d5bfab0d7d9300792d9d3b7c7e3 100644 --- a/src/video/renderer.h +++ b/src/video/renderer.h @@ -17,7 +17,6 @@ ***************************************************************************/ #pragma once - //Base #include <QtCore/QObject> #include "api/newvideo.h" @@ -32,7 +31,6 @@ class QMutex; struct AVFrame; - namespace Video { class RendererPrivate; @@ -89,7 +87,7 @@ public: }; //Constructor - Renderer (const QByteArray& id, const QSize& res); + Renderer (const QString& id, const QSize& res); virtual ~Renderer(); //Getters