1
0
mirror of https://github.com/qTox/qTox.git synced 2024-03-22 14:00:36 +08:00

feat(toxid): reduce passing Tox IDs around

reasons:
- most of the time we don't even know the Tox ID but only the Public Key
- use well defined objects instead of strings that could be anything
This commit is contained in:
sudden6 2016-12-29 23:14:48 +01:00
parent 2f4e8dc3e8
commit e07d8d358f
No known key found for this signature in database
GPG Key ID: 279509B499E032B9
39 changed files with 357 additions and 396 deletions

View File

@ -276,8 +276,8 @@ void Core::start()
if (!msg.isEmpty()) if (!msg.isEmpty())
emit statusMessageSet(msg); emit statusMessageSet(msg);
QString id = getSelfId().toString(); ToxId id = getSelfId();
if (!id.isEmpty()) if (id.isValid()) // TODO: probably useless check, comes basically directly from toxcore
emit idSet(id); emit idSet(id);
// TODO: This is a backwards compatibility check, // TODO: This is a backwards compatibility check,
@ -424,9 +424,10 @@ void Core::bootstrapDht()
+':'+QString().setNum(dhtServer.port)+" ("+dhtServer.name+')'; +':'+QString().setNum(dhtServer.port)+" ("+dhtServer.name+')';
QByteArray address = dhtServer.address.toLatin1(); QByteArray address = dhtServer.address.toLatin1();
QByteArray pk = ToxId{dhtServer.userId}.getPublicKey(); // TODO: constucting the pk via ToxId is a workaround
ToxPk pk = ToxId{dhtServer.userId}.getPublicKey();
const uint8_t* pkPtr = reinterpret_cast<const uint8_t*>(pk.constData()); const uint8_t* pkPtr = reinterpret_cast<const uint8_t*>(pk.getBytes());
if (!tox_bootstrap(tox, address.constData(), dhtServer.port, pkPtr, nullptr)) if (!tox_bootstrap(tox, address.constData(), dhtServer.port, pkPtr, nullptr))
{ {
@ -446,7 +447,7 @@ void Core::bootstrapDht()
void Core::onFriendRequest(Tox*/* tox*/, const uint8_t* cFriendPk, void Core::onFriendRequest(Tox*/* tox*/, const uint8_t* cFriendPk,
const uint8_t* cMessage, size_t cMessageSize, void* core) const uint8_t* cMessage, size_t cMessageSize, void* core)
{ {
QString friendPk = ToxId(cFriendPk, TOX_PUBLIC_KEY_SIZE).getPublicKeyString(); ToxPk friendPk(cFriendPk);
emit static_cast<Core*>(core)->friendRequestReceived(friendPk, CString::toString(cMessage, cMessageSize)); emit static_cast<Core*>(core)->friendRequestReceived(friendPk, CString::toString(cMessage, cMessageSize));
} }
@ -556,67 +557,81 @@ void Core::onReadReceiptCallback(Tox*, uint32_t friendId, uint32_t receipt, void
emit static_cast<Core*>(core)->receiptRecieved(friendId, receipt); emit static_cast<Core*>(core)->receiptRecieved(friendId, receipt);
} }
void Core::acceptFriendRequest(const QString& userId) void Core::acceptFriendRequest(const ToxPk& friendPk)
{ {
uint32_t friendId = tox_friend_add_norequest(tox, ToxId(userId).getPublicKeyBytes(), nullptr); // TODO: error handling
uint32_t friendId = tox_friend_add_norequest(tox, friendPk.getBytes(), nullptr);
if (friendId == std::numeric_limits<uint32_t>::max()) if (friendId == std::numeric_limits<uint32_t>::max())
{ {
emit failedToAddFriend(userId); emit failedToAddFriend(friendPk);
} }
else else
{ {
profile.saveToxSave(); profile.saveToxSave();
emit friendAdded(friendId, userId); emit friendAdded(friendId, friendPk);
emit friendshipChanged(friendId); emit friendshipChanged(friendId);
} }
} }
void Core::requestFriendship(const QString& friendAddress, const QString& message) void Core::requestFriendship(const ToxId& friendAddress, const QString& message)
{ {
ToxId friendToxId(friendAddress); ToxPk friendPk = friendAddress.getPublicKey();
const QString userId = friendAddress.mid(0, TOX_PUBLIC_KEY_SIZE * 2);
if (!friendToxId.isValid()) if (!friendAddress.isValid())
{ {
emit failedToAddFriend(userId, emit failedToAddFriend(friendPk,
tr("Invalid Tox ID")); tr("Invalid Tox ID"));
} }
else if (message.isEmpty()) else if (message.isEmpty())
{ {
emit failedToAddFriend(userId, tr("You need to write a message with your request")); emit failedToAddFriend(friendPk,
tr("You need to write a message with your request"));
} }
else if (message.size() > TOX_MAX_FRIEND_REQUEST_LENGTH) else if (message.size() > TOX_MAX_FRIEND_REQUEST_LENGTH)
{ {
emit failedToAddFriend(userId, tr("Your message is too long!")); emit failedToAddFriend(friendPk,
tr("Your message is too long!"));
} }
else if (hasFriendWithAddress(userId)) else if (hasFriendWithPublicKey(friendPk))
{ {
emit failedToAddFriend(userId, tr("Friend is already added")); emit failedToAddFriend(friendPk,
tr("Friend is already added"));
} }
else else
{ {
CString cMessage(message); CString cMessage(message);
uint32_t friendId = tox_friend_add(tox, ToxId(friendAddress).getBytes(), uint32_t friendId = tox_friend_add(tox, friendAddress.getBytes(),
cMessage.data(), cMessage.size(), nullptr); cMessage.data(), cMessage.size(), nullptr);
if (friendId == std::numeric_limits<uint32_t>::max()) if (friendId == std::numeric_limits<uint32_t>::max())
{ {
qDebug() << "Failed to request friendship"; qDebug() << "Failed to request friendship";
emit failedToAddFriend(userId); emit failedToAddFriend(friendPk);
} }
else else
{ {
qDebug() << "Requested friendship of "<<friendId; qDebug() << "Requested friendship of " << friendId;
// Update our friendAddresses // Update our friendAddresses
Settings::getInstance().updateFriendAddress(userId); Settings::getInstance().updateFriendAddress(friendAddress.toString());
// TODO: start: this really shouldn't be in Core
QString inviteStr = tr("/me offers friendship."); QString inviteStr = tr("/me offers friendship.");
if (message.length()) if (message.length())
inviteStr = tr("/me offers friendship, \"%1\"").arg(message); inviteStr = tr("/me offers friendship, \"%1\"").arg(message);
Profile* profile = Nexus::getProfile(); Profile* profile = Nexus::getProfile();
if (profile->isHistoryEnabled()) if (profile->isHistoryEnabled())
profile->getHistory()->addNewMessage(userId, inviteStr, getSelfId().getPublicKeyString(), QDateTime::currentDateTime(), true, QString()); {
emit friendAdded(friendId, userId); profile->getHistory()->addNewMessage(friendAddress.toString(),
inviteStr,
getSelfId().getPublicKey().toString(),
QDateTime::currentDateTime(),
true,
QString());
}
// TODO: end
emit friendAdded(friendId, friendAddress.getPublicKey());
emit friendshipChanged(friendId); emit friendshipChanged(friendId);
} }
} }
@ -847,7 +862,7 @@ void Core::setAvatar(const QByteArray& data)
{ {
QPixmap pic; QPixmap pic;
pic.loadFromData(data); pic.loadFromData(data);
profile.saveAvatar(data, getSelfId().getPublicKeyString()); profile.saveAvatar(data, getSelfId().getPublicKey().toString());
emit selfAvatarChanged(pic); emit selfAvatarChanged(pic);
} }
else else
@ -997,7 +1012,7 @@ void Core::loadFriends()
{ {
if (tox_friend_get_public_key(tox, ids[i], friendPk, nullptr)) if (tox_friend_get_public_key(tox, ids[i], friendPk, nullptr))
{ {
emit friendAdded(ids[i], ToxId(friendPk, TOX_PUBLIC_KEY_SIZE).getPublicKeyString()); emit friendAdded(ids[i], ToxPk(friendPk));
const size_t nameSize = tox_friend_get_name_size(tox, ids[i], nullptr); const size_t nameSize = tox_friend_get_name_size(tox, ids[i], nullptr);
if (nameSize && nameSize != SIZE_MAX) if (nameSize && nameSize != SIZE_MAX)
@ -1108,7 +1123,7 @@ QString Core::getGroupPeerName(int groupId, int peerId) const
/** /**
* @brief Get the public key of a peer of a group * @brief Get the public key of a peer of a group
*/ */
ToxId Core::getGroupPeerToxId(int groupId, int peerId) const ToxPk Core::getGroupPeerPk(int groupId, int peerId) const
{ {
uint8_t friendPk[TOX_PUBLIC_KEY_SIZE] = {0x00}; uint8_t friendPk[TOX_PUBLIC_KEY_SIZE] = {0x00};
TOX_ERR_CONFERENCE_PEER_QUERY error; TOX_ERR_CONFERENCE_PEER_QUERY error;
@ -1116,10 +1131,10 @@ ToxId Core::getGroupPeerToxId(int groupId, int peerId) const
if (!parsePeerQueryError(error) || !success) if (!parsePeerQueryError(error) || !success)
{ {
qWarning() << "getGroupPeerToxId: Unknown error"; qWarning() << "getGroupPeerToxId: Unknown error";
return ToxId(); return ToxPk();
} }
return ToxId(friendPk, TOX_PUBLIC_KEY_SIZE); return ToxPk(friendPk);
} }
/** /**
@ -1324,83 +1339,36 @@ bool Core::isFriendOnline(uint32_t friendId) const
return connetion != TOX_CONNECTION_NONE; return connetion != TOX_CONNECTION_NONE;
} }
/**
* @brief Checks if we have a friend by address
*/
bool Core::hasFriendWithAddress(const QString &addr) const
{
// Valid length check
if (addr.length() != (TOX_ADDRESS_SIZE * 2))
{
return false;
}
QString pubkey = addr.left(TOX_PUBLIC_KEY_SIZE * 2);
return hasFriendWithPublicKey(pubkey);
}
/** /**
* @brief Checks if we have a friend by public key * @brief Checks if we have a friend by public key
*/ */
bool Core::hasFriendWithPublicKey(const QString &pubkey) const bool Core::hasFriendWithPublicKey(const ToxPk &publicKey) const
{ {
// Valid length check // Validity check
if (pubkey.length() != (TOX_PUBLIC_KEY_SIZE * 2)) if (publicKey.isEmpty())
return false;
bool found = false;
const size_t friendCount = tox_self_get_friend_list_size(tox);
if (friendCount > 0)
{ {
uint32_t *ids = new uint32_t[friendCount]; return false;
tox_self_get_friend_list(tox, ids);
for (int32_t i = 0; i < static_cast<int32_t>(friendCount); ++i)
{
// getFriendAddress may return either id (public key) or address
QString addrOrId = getFriendAddress(ids[i]);
// Set true if found
if (addrOrId.toUpper().startsWith(pubkey.toUpper()))
{
found = true;
break;
}
}
delete[] ids;
} }
return found; // TODO: error handling
} uint32_t friendId = tox_friend_by_public_key(tox, publicKey.getBytes(), nullptr);
/** return friendId != std::numeric_limits<uint32_t>::max();
* @brief Get the full address if known, or public key of a friend
*/
QString Core::getFriendAddress(uint32_t friendNumber) const
{
QString id = getFriendPublicKey(friendNumber);
QString addr = Settings::getInstance().getFriendAddress(id);
if (addr.size() > id.size())
return addr;
return id;
} }
/** /**
* @brief Get the public key part of the ToxID only * @brief Get the public key part of the ToxID only
*/ */
QString Core::getFriendPublicKey(uint32_t friendNumber) const ToxPk Core::getFriendPublicKey(uint32_t friendNumber) const
{ {
uint8_t rawid[TOX_PUBLIC_KEY_SIZE]; uint8_t rawid[TOX_PUBLIC_KEY_SIZE];
if (!tox_friend_get_public_key(tox, friendNumber, rawid, nullptr)) if (!tox_friend_get_public_key(tox, friendNumber, rawid, nullptr))
{ {
qWarning() << "getFriendPublicKey: Getting public key failed"; qWarning() << "getFriendPublicKey: Getting public key failed";
return QString(); return ToxPk();
} }
QByteArray data((char*)rawid, TOX_PUBLIC_KEY_SIZE);
QString id = data.toHex().toUpper();
return id; return ToxPk(rawid);
} }
/** /**
@ -1450,7 +1418,7 @@ QList<CString> Core::splitMessage(const QString &message, int maxLen)
return splittedMsgs; return splittedMsgs;
} }
QString Core::getPeerName(const ToxId& id) const QString Core::getPeerName(const ToxPk& id) const
{ {
QString name; QString name;
uint32_t friendId = tox_friend_by_public_key(tox, id.getBytes(), nullptr); uint32_t friendId = tox_friend_by_public_key(tox, id.getBytes(), nullptr);
@ -1485,13 +1453,16 @@ bool Core::isReady() const
return av && av->getToxAv() && tox && ready; return av && av->getToxAv() && tox && ready;
} }
/**
* @brief Sets the NoSpam value to prevent friend request spam
* @param nospam an arbitrary which becomes part of the Tox ID
*/
void Core::setNospam(uint32_t nospam) void Core::setNospam(uint32_t nospam)
{ {
uint8_t *nspm = reinterpret_cast<uint8_t*>(&nospam);
std::reverse(nspm, nspm + 4);
tox_self_set_nospam(tox, nospam); tox_self_set_nospam(tox, nospam);
emit idSet(getSelfId().toString()); emit idSet(getSelfId());
} }
/** /**

View File

@ -58,20 +58,18 @@ public:
static QByteArray getSaltFromFile(QString filename); static QByteArray getSaltFromFile(QString filename);
QString getPeerName(const ToxId& id) const; QString getPeerName(const ToxPk& id) const;
QVector<uint32_t> getFriendList() const; QVector<uint32_t> getFriendList() const;
uint32_t getGroupNumberPeers(int groupId) const; uint32_t getGroupNumberPeers(int groupId) const;
QString getGroupPeerName(int groupId, int peerId) const; QString getGroupPeerName(int groupId, int peerId) const;
ToxId getGroupPeerToxId(int groupId, int peerId) const; ToxPk getGroupPeerPk(int groupId, int peerId) const;
QList<QString> getGroupPeerNames(int groupId) const; QList<QString> getGroupPeerNames(int groupId) const;
QString getFriendAddress(uint32_t friendNumber) const; ToxPk getFriendPublicKey(uint32_t friendNumber) const;
QString getFriendPublicKey(uint32_t friendNumber) const;
QString getFriendUsername(uint32_t friendNumber) const; QString getFriendUsername(uint32_t friendNumber) const;
bool isFriendOnline(uint32_t friendId) const; bool isFriendOnline(uint32_t friendId) const;
bool hasFriendWithAddress(const QString &addr) const; bool hasFriendWithPublicKey(const ToxPk &publicKey) const;
bool hasFriendWithPublicKey(const QString &pubkey) const;
uint32_t joinGroupchat(int32_t friendId, uint8_t type, const uint8_t* pubkey,uint16_t length) const; uint32_t joinGroupchat(int32_t friendId, uint8_t type, const uint8_t* pubkey,uint16_t length) const;
void quitGroupChat(int groupId) const; void quitGroupChat(int groupId) const;
@ -99,8 +97,8 @@ public slots:
QByteArray getToxSaveData(); QByteArray getToxSaveData();
void acceptFriendRequest(const QString& userId); void acceptFriendRequest(const ToxPk &friendPk);
void requestFriendship(const QString& friendAddress, const QString& message); void requestFriendship(const ToxId &friendAddress, const QString& message);
void groupInviteFriend(uint32_t friendId, int groupId); void groupInviteFriend(uint32_t friendId, int groupId);
int createGroup(uint8_t type = TOX_CONFERENCE_TYPE_AV); int createGroup(uint8_t type = TOX_CONFERENCE_TYPE_AV);
@ -133,10 +131,10 @@ signals:
void connected(); void connected();
void disconnected(); void disconnected();
void friendRequestReceived(const QString& userId, const QString& message); void friendRequestReceived(const ToxPk& friendPk, const QString& message);
void friendMessageReceived(uint32_t friendId, const QString& message, bool isAction); void friendMessageReceived(uint32_t friendId, const QString& message, bool isAction);
void friendAdded(uint32_t friendId, const QString& userId); void friendAdded(uint32_t friendId, const ToxPk& friendPk);
void friendshipChanged(uint32_t friendId); void friendshipChanged(uint32_t friendId);
void friendStatusChanged(uint32_t friendId, Status status); void friendStatusChanged(uint32_t friendId, Status status);
@ -160,7 +158,7 @@ signals:
void usernameSet(const QString& username); void usernameSet(const QString& username);
void statusMessageSet(const QString& message); void statusMessageSet(const QString& message);
void statusSet(Status status); void statusSet(Status status);
void idSet(const QString& id); void idSet(const ToxId& id);
void selfAvatarChanged(const QPixmap& pic); void selfAvatarChanged(const QPixmap& pic);
void messageSentResult(uint32_t friendId, const QString& message, int messageId); void messageSentResult(uint32_t friendId, const QString& message, int messageId);
@ -169,7 +167,7 @@ signals:
void receiptRecieved(int friedId, int receipt); void receiptRecieved(int friedId, int receipt);
void failedToAddFriend(const QString& userId, const QString& errorInfo = QString()); void failedToAddFriend(const ToxPk& friendPk, const QString& errorInfo = QString());
void failedToRemoveFriend(uint32_t friendId); void failedToRemoveFriend(uint32_t friendId);
void failedToSetUsername(const QString& username); void failedToSetUsername(const QString& username);
void failedToSetStatusMessage(const QString& message); void failedToSetStatusMessage(const QString& message);

View File

@ -52,7 +52,7 @@ unsigned CoreFile::corefileIterationInterval()
/* /*
Sleep at most 1000ms if we have no FT, 10 for user FTs Sleep at most 1000ms if we have no FT, 10 for user FTs
There is no real difference between 10ms sleep and 50ms sleep when it There is no real difference between 10ms sleep and 50ms sleep when it
comes to CPU usage  just keep the CPU usage low when there are no file comes to CPU usage just keep the CPU usage low when there are no file
transfers, and speed things up when there is an ongoing file transfer. transfers, and speed things up when there is an ongoing file transfer.
*/ */
constexpr unsigned fileInterval = 10, constexpr unsigned fileInterval = 10,
@ -311,7 +311,8 @@ void CoreFile::onFileReceiveCallback(Tox*, uint32_t friendId, uint32_t fileId,
if (kind == TOX_FILE_KIND_AVATAR) if (kind == TOX_FILE_KIND_AVATAR)
{ {
QString friendAddr = core->getFriendPublicKey(friendId); // TODO: port this to ToxPk
QString friendAddr = core->getFriendPublicKey(friendId).toString();
if (!filesize) if (!filesize)
{ {
qDebug() << QString("Received empty avatar request %1:%2").arg(friendId).arg(fileId); qDebug() << QString("Received empty avatar request %1:%2").arg(friendId).arg(fileId);
@ -482,7 +483,7 @@ void CoreFile::onFileRecvChunkCallback(Tox *tox, uint32_t friendId,
if (!pic.isNull()) if (!pic.isNull())
{ {
qDebug() << "Got"<<file->avatarData.size()<<"bytes of avatar data from" <<friendId; qDebug() << "Got"<<file->avatarData.size()<<"bytes of avatar data from" <<friendId;
core->profile.saveAvatar(file->avatarData, core->getFriendPublicKey(friendId)); core->profile.saveAvatar(file->avatarData, core->getFriendPublicKey(friendId).toString());
emit core->friendAvatarChanged(friendId, pic); emit core->friendAvatarChanged(friendId, pic);
} }
} }

View File

@ -20,6 +20,7 @@
#include "toxid.h" #include "toxid.h"
#include "core.h" #include "core.h"
#include "toxpk.h"
#include <tox/tox.h> #include <tox/tox.h>
@ -201,27 +202,9 @@ const uint8_t* ToxId::getBytes() const
* @brief Gets the Public Key part of the ToxID * @brief Gets the Public Key part of the ToxID
* @return Public Key of the ToxID * @return Public Key of the ToxID
*/ */
QByteArray ToxId::getPublicKey() const ToxPk ToxId::getPublicKey() const
{ {
return toxId.mid(0, TOX_PUBLIC_KEY_SIZE); return ToxPk(toxId.mid(0, TOX_PUBLIC_KEY_SIZE));
}
/**
* @brief Gets the Public Key part of the ToxID, convenience function for toxcore interface.
* @return Public Key of the ToxID as uint8_t*
*/
const uint8_t* ToxId::getPublicKeyBytes() const
{
return reinterpret_cast<const uint8_t*>(toxId.mid(0, TOX_PUBLIC_KEY_SIZE).constData());
}
/**
* @brief Returns the Public Key converted to QString.
* @return The Public Key as QString.
*/
QString ToxId::getPublicKeyString() const
{
return getPublicKey().toHex().toUpper();
} }
/** /**

View File

@ -21,6 +21,10 @@
#ifndef TOXID_H #ifndef TOXID_H
#define TOXID_H #define TOXID_H
#include "toxpk.h"
#include <cstdint>
#include <QByteArray>
#include <QString> #include <QString>
class ToxId class ToxId
@ -42,9 +46,7 @@ public:
static bool isToxId(const QString &id); static bool isToxId(const QString &id);
const uint8_t* getBytes() const; const uint8_t* getBytes() const;
QByteArray getToxId() const; QByteArray getToxId() const;
QByteArray getPublicKey() const; ToxPk getPublicKey() const;
const uint8_t* getPublicKeyBytes() const;
QString getPublicKeyString() const;
QString getNoSpamString() const; QString getNoSpamString() const;
private: private:

View File

@ -19,16 +19,16 @@ ToxPk::ToxPk()
/** /**
* @brief The copy constructor. * @brief The copy constructor.
* @param other ToxKey to copy * @param other ToxPk to copy
*/ */
ToxPk::ToxPk(const ToxPk& other) ToxPk::ToxPk(const ToxPk& other)
: key(other.key) : key(other.key)
{} {}
/** /**
* @brief Constructs a ToxKey from bytes. * @brief Constructs a ToxPk from bytes.
* @param rawId The bytes to construct the ToxKey from. The lenght must be exactly * @param rawId The bytes to construct the ToxPk from. The lenght must be exactly
* TOX_PUBLIC_KEY_SIZE, else the ToxKey will be empty. * TOX_PUBLIC_KEY_SIZE, else the ToxPk will be empty.
*/ */
ToxPk::ToxPk(const QByteArray& rawId) ToxPk::ToxPk(const QByteArray& rawId)
{ {
@ -43,8 +43,8 @@ ToxPk::ToxPk(const QByteArray& rawId)
} }
/** /**
* @brief Constructs a ToxKey from bytes. * @brief Constructs a ToxPk from bytes.
* @param rawId The bytes to construct the ToxKey from, will read exactly * @param rawId The bytes to construct the ToxPk from, will read exactly
* TOX_PUBLIC_KEY_SIZE from the specified buffer. * TOX_PUBLIC_KEY_SIZE from the specified buffer.
*/ */
ToxPk::ToxPk(const uint8_t* rawId) ToxPk::ToxPk(const uint8_t* rawId)
@ -53,9 +53,9 @@ ToxPk::ToxPk(const uint8_t* rawId)
} }
/** /**
* @brief Compares the equality of the ToxKey. * @brief Compares the equality of the ToxPk.
* @param other ToxKey to compare. * @param other ToxPk to compare.
* @return True if both ToxKeys are equal, false otherwise. * @return True if both ToxPks are equal, false otherwise.
*/ */
bool ToxPk::operator==(const ToxPk& other) const bool ToxPk::operator==(const ToxPk& other) const
{ {
@ -63,9 +63,9 @@ bool ToxPk::operator==(const ToxPk& other) const
} }
/** /**
* @brief Compares the inequality of the ToxKey. * @brief Compares the inequality of the ToxPk.
* @param other ToxKey to compare. * @param other ToxPk to compare.
* @return True if both ToxKeys are not equal, false otherwise. * @return True if both ToxPks are not equal, false otherwise.
*/ */
bool ToxPk::operator!=(const ToxPk& other) const bool ToxPk::operator!=(const ToxPk& other) const
{ {
@ -73,7 +73,7 @@ bool ToxPk::operator!=(const ToxPk& other) const
} }
/** /**
* @brief Converts the ToxKey to a uppercase hex string. * @brief Converts the ToxPk to a uppercase hex string.
* @return QString containing the hex representation of the key * @return QString containing the hex representation of the key
*/ */
QString ToxPk::toString() const QString ToxPk::toString() const
@ -84,7 +84,7 @@ QString ToxPk::toString() const
/** /**
* @brief Returns a pointer to the raw key data. * @brief Returns a pointer to the raw key data.
* @return Pointer to the raw key data, which is exactly TOX_PUBLIC_KEY_SIZE bytes * @return Pointer to the raw key data, which is exactly TOX_PUBLIC_KEY_SIZE bytes
* long. Returns a nullptr if the ToxKey is empty. * long. Returns a nullptr if the ToxPk is empty.
*/ */
const uint8_t* ToxPk::getBytes() const const uint8_t* ToxPk::getBytes() const
{ {
@ -97,7 +97,16 @@ const uint8_t* ToxPk::getBytes() const
} }
/** /**
* @brief Checks if the ToxKey contains a key. * @brief Get a copy of the key
* @return Copied key bytes
*/
QByteArray ToxPk::getKey() const
{
return QByteArray(key); // TODO: Is a copy really necessary?
}
/**
* @brief Checks if the ToxPk contains a key.
* @return True if there is a key, False otherwise. * @return True if there is a key, False otherwise.
*/ */
bool ToxPk::isEmpty() const bool ToxPk::isEmpty() const

View File

@ -3,7 +3,7 @@
#include <cstdint> #include <cstdint>
#include <QByteArray> #include <QByteArray>
#include <QByteArray> #include <QString>
class ToxPk class ToxPk
{ {
@ -16,6 +16,7 @@ public:
bool operator==(const ToxPk& other) const; bool operator==(const ToxPk& other) const;
bool operator!=(const ToxPk& other) const; bool operator!=(const ToxPk& other) const;
QString toString() const; QString toString() const;
QByteArray getKey() const;
const uint8_t* getBytes() const; const uint8_t* getBytes() const;
bool isEmpty() const; bool isEmpty() const;

View File

@ -30,16 +30,16 @@
#include "src/grouplist.h" #include "src/grouplist.h"
#include "src/group.h" #include "src/group.h"
Friend::Friend(uint32_t FriendId, const ToxId &UserId) Friend::Friend(uint32_t FriendId, const ToxPk& FriendPk)
: userName{Core::getInstance()->getPeerName(UserId)} : userName{Core::getInstance()->getPeerName(FriendPk)}
, userID(UserId), friendId(FriendId) , friendPk(FriendPk), friendId(FriendId)
, hasNewEvents(0), friendStatus(Status::Offline) , hasNewEvents(0), friendStatus(Status::Offline)
{ {
if (userName.size() == 0) if (userName.size() == 0)
userName = UserId.getPublicKeyString(); userName = FriendPk.toString();
userAlias = Settings::getInstance().getFriendAlias(UserId); userAlias = Settings::getInstance().getFriendAlias(FriendPk);
chatForm = new ChatForm(this); chatForm = new ChatForm(this);
} }
@ -65,7 +65,7 @@ void Friend::loadHistory()
void Friend::setName(QString name) void Friend::setName(QString name)
{ {
if (name.isEmpty()) if (name.isEmpty())
name = userID.getPublicKeyString(); name = friendPk.toString();
userName = name; userName = name;
if (userAlias.size() == 0) if (userAlias.size() == 0)
@ -124,9 +124,9 @@ bool Friend::hasAlias() const
return !userAlias.isEmpty(); return !userAlias.isEmpty();
} }
const ToxId &Friend::getToxId() const const ToxPk& Friend::getPublicKey() const
{ {
return userID; return friendPk;
} }
uint32_t Friend::getFriendID() const uint32_t Friend::getFriendID() const

View File

@ -32,7 +32,7 @@ class Friend : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
Friend(uint32_t FriendId, const ToxId &UserId); Friend(uint32_t FriendId, const ToxPk& FriendPk);
Friend(const Friend& other)=delete; Friend(const Friend& other)=delete;
~Friend(); ~Friend();
Friend& operator=(const Friend& other)=delete; Friend& operator=(const Friend& other)=delete;
@ -50,7 +50,7 @@ public:
void setEventFlag(int f); void setEventFlag(int f);
int getEventFlag() const; int getEventFlag() const;
const ToxId &getToxId() const; const ToxPk& getPublicKey() const;
uint32_t getFriendID() const; uint32_t getFriendID() const;
void setStatus(Status s); void setStatus(Status s);
@ -67,7 +67,7 @@ signals:
private: private:
QString userAlias, userName, statusMessage; QString userAlias, userName, statusMessage;
ToxId userID; ToxPk friendPk;
uint32_t friendId; uint32_t friendId;
int hasNewEvents; int hasNewEvents;
Status friendStatus; Status friendStatus;

View File

@ -25,17 +25,17 @@
#include <QHash> #include <QHash>
QHash<int, Friend*> FriendList::friendList; QHash<int, Friend*> FriendList::friendList;
QHash<QByteArray, int> FriendList::tox2id; QHash<QByteArray, int> FriendList::key2id;
Friend* FriendList::addFriend(int friendId, const ToxId& userId) Friend* FriendList::addFriend(int friendId, const ToxPk& friendPk)
{ {
auto friendChecker = friendList.find(friendId); auto friendChecker = friendList.find(friendId);
if (friendChecker != friendList.end()) if (friendChecker != friendList.end())
qWarning() << "addFriend: friendId already taken"; qWarning() << "addFriend: friendId already taken";
Friend* newfriend = new Friend(friendId, userId); Friend* newfriend = new Friend(friendId, friendPk);
friendList[friendId] = newfriend; friendList[friendId] = newfriend;
tox2id[userId.getPublicKey()] = friendId; key2id[friendPk.getKey()] = friendId;
return newfriend; return newfriend;
} }
@ -55,7 +55,7 @@ void FriendList::removeFriend(int friendId, bool fake)
if (f_it != friendList.end()) if (f_it != friendList.end())
{ {
if (!fake) if (!fake)
Settings::getInstance().removeFriendSettings(f_it.value()->getToxId()); Settings::getInstance().removeFriendSettings(f_it.value()->getPublicKey());
friendList.erase(f_it); friendList.erase(f_it);
} }
} }
@ -67,15 +67,15 @@ void FriendList::clear()
friendList.clear(); friendList.clear();
} }
Friend* FriendList::findFriend(const ToxId& userId) Friend* FriendList::findFriend(const ToxPk& friendPk)
{ {
auto id = tox2id.find(userId.getPublicKey()); auto id = key2id.find(friendPk.getKey());
if (id != tox2id.end()) if (id != key2id.end())
{ {
Friend *f = findFriend(*id); Friend *f = findFriend(*id);
if (!f) if (!f)
return nullptr; return nullptr;
if (f->getToxId() == userId) if (f->getPublicKey() == friendPk)
return f; return f;
} }

View File

@ -24,21 +24,21 @@ template <class T> class QList;
template <class A, class B> class QHash; template <class A, class B> class QHash;
class Friend; class Friend;
class QByteArray; class QByteArray;
class ToxId; class ToxPk;
class FriendList class FriendList
{ {
public: public:
static Friend* addFriend(int friendId, const ToxId &userId); static Friend* addFriend(int friendId, const ToxPk& friendPk);
static Friend* findFriend(int friendId); static Friend* findFriend(int friendId);
static Friend* findFriend(const ToxId &userId); static Friend* findFriend(const ToxPk& friendPk);
static QList<Friend*> getAllFriends(); static QList<Friend*> getAllFriends();
static void removeFriend(int friendId, bool fake = false); static void removeFriend(int friendId, bool fake = false);
static void clear(); static void clear();
private: private:
static QHash<int, Friend*> friendList; static QHash<int, Friend*> friendList;
static QHash<QByteArray, int> tox2id; static QHash<QByteArray, int> key2id;
}; };
#endif // FRIENDLIST_H #endif // FRIENDLIST_H

View File

@ -48,16 +48,16 @@ Group::~Group()
void Group::updatePeer(int peerId, QString name) void Group::updatePeer(int peerId, QString name)
{ {
ToxId id = Core::getInstance()->getGroupPeerToxId(groupId, peerId); ToxPk peerKey = Core::getInstance()->getGroupPeerPk(groupId, peerId);
QString toxid = id.getPublicKey(); QByteArray peerPk = peerKey.getKey();
peers[peerId] = name; peers[peerId] = name;
toxids[toxid] = name; toxids[peerPk] = name;
Friend *f = FriendList::findFriend(id); Friend *f = FriendList::findFriend(peerKey);
if (f != nullptr && f->hasAlias()) if (f != nullptr && f->hasAlias())
{ {
peers[peerId] = f->getDisplayedName(); peers[peerId] = f->getDisplayedName();
toxids[toxid] = f->getDisplayedName(); toxids[peerPk] = f->getDisplayedName();
} }
else else
{ {
@ -90,21 +90,21 @@ void Group::regeneratePeerList()
nPeers = peers.size(); nPeers = peers.size();
for (int i = 0; i < nPeers; ++i) for (int i = 0; i < nPeers; ++i)
{ {
ToxId id = core->getGroupPeerToxId(groupId, i); ToxPk id = core->getGroupPeerPk(groupId, i);
ToxId self = core->getSelfId(); ToxPk self = core->getSelfId().getPublicKey();
if (id == self) if (id == self)
selfPeerNum = i; selfPeerNum = i;
QString toxid = id.getPublicKey(); QByteArray peerPk = id.getKey();
toxids[toxid] = peers[i]; toxids[peerPk] = peers[i];
if (toxids[toxid].isEmpty()) if (toxids[peerPk].isEmpty())
toxids[toxid] = tr("<Empty>", "Placeholder when someone's name in a group chat is empty"); toxids[peerPk] = tr("<Empty>", "Placeholder when someone's name in a group chat is empty");
Friend *f = FriendList::findFriend(id); Friend *f = FriendList::findFriend(id);
if (f != nullptr && f->hasAlias()) if (f != nullptr && f->hasAlias())
{ {
peers[i] = f->getDisplayedName(); peers[i] = f->getDisplayedName();
toxids[toxid] = f->getDisplayedName(); toxids[peerPk] = f->getDisplayedName();
} }
} }
@ -168,9 +168,9 @@ int Group::getMentionedFlag() const
return userWasMentioned; return userWasMentioned;
} }
QString Group::resolveToxId(const ToxId &id) const QString Group::resolveToxId(const ToxPk &id) const
{ {
QString key = id.getPublicKeyString(); QByteArray key = id.getKey();
auto it = toxids.find(key); auto it = toxids.find(key);
if (it != toxids.end()) if (it != toxids.end())

View File

@ -29,7 +29,7 @@
class Friend; class Friend;
class GroupWidget; class GroupWidget;
class GroupChatForm; class GroupChatForm;
class ToxId; class ToxPk;
class Group : public QObject class Group : public QObject
{ {
@ -58,7 +58,7 @@ public:
void setName(const QString& name); void setName(const QString& name);
QString getName() const; QString getName() const;
QString resolveToxId(const ToxId &id) const; QString resolveToxId(const ToxPk& id) const;
signals: signals:
void titleChanged(GroupWidget* widget); void titleChanged(GroupWidget* widget);
@ -68,7 +68,7 @@ private:
GroupWidget* widget; GroupWidget* widget;
GroupChatForm* chatForm; GroupChatForm* chatForm;
QStringList peers; QStringList peers;
QMap<QString, QString> toxids; QMap<QByteArray, QString> toxids;
int hasNewMessages, userWasMentioned; int hasNewMessages, userWasMentioned;
int groupId; int groupId;
int nPeers; int nPeers;

View File

@ -300,9 +300,9 @@ QString Toxme::getPass(QString json, ExecCode &code) {
* @param id ToxId to delete. * @param id ToxId to delete.
* @return Status code returned from server. * @return Status code returned from server.
*/ */
Toxme::ExecCode Toxme::deleteAddress(QString server, ToxId id) Toxme::ExecCode Toxme::deleteAddress(QString server, ToxPk id)
{ {
const QString payload{"{\"public_key\":\""+id.toString().left(64)+"\"," const QString payload{"{\"public_key\":\""+id.toString()+"\","
"\"timestamp\":"+QString().setNum(time(0))+"}"}; "\"timestamp\":"+QString().setNum(time(0))+"}"};
server = server.trimmed(); server = server.trimmed();

View File

@ -45,7 +45,7 @@ public:
static ToxId lookup(QString address); static ToxId lookup(QString address);
static QString createAddress(ExecCode &code, QString server, ToxId id, QString address, static QString createAddress(ExecCode &code, QString server, ToxId id, QString address,
bool keepPrivate=true, QString bio=QString()); bool keepPrivate=true, QString bio=QString());
static ExecCode deleteAddress(QString server, ToxId id); static ExecCode deleteAddress(QString server, ToxPk id);
static QString getErrorMessage(int errorCode); static QString getErrorMessage(int errorCode);
static QString translateErrorMessage(int errorCode); static QString translateErrorMessage(int errorCode);

View File

@ -64,8 +64,8 @@ bool handleToxURI(const QString &toxURI)
QString toxaddr = toxURI.mid(4); QString toxaddr = toxURI.mid(4);
QString toxId = Toxme::lookup(toxaddr).toString(); ToxId toxId = Toxme::lookup(toxaddr);
if (toxId.isEmpty()) if (!toxId.isValid())
{ {
QMessageBox::warning(0, "qTox", QMessageBox::warning(0, "qTox",
ToxURIDialog::tr("%1 is not a valid Toxme address.") ToxURIDialog::tr("%1 is not a valid Toxme address.")

View File

@ -417,7 +417,7 @@ QString Profile::avatarPath(const QString& ownerId, bool forceUnencrypted)
return Settings::getInstance().getSettingsDirPath() + "avatars/" + ownerId + ".png"; return Settings::getInstance().getSettingsDirPath() + "avatars/" + ownerId + ".png";
QByteArray idData = ownerId.toUtf8(); QByteArray idData = ownerId.toUtf8();
QByteArray pubkeyData = core->getSelfId().getPublicKey(); QByteArray pubkeyData = core->getSelfId().getPublicKey().getKey();
constexpr int hashSize = TOX_PUBLIC_KEY_SIZE; constexpr int hashSize = TOX_PUBLIC_KEY_SIZE;
static_assert(hashSize >= crypto_generichash_BYTES_MIN static_assert(hashSize >= crypto_generichash_BYTES_MIN
&& hashSize <= crypto_generichash_BYTES_MAX, "Hash size not supported by libsodium"); && hashSize <= crypto_generichash_BYTES_MAX, "Hash size not supported by libsodium");
@ -434,7 +434,7 @@ QString Profile::avatarPath(const QString& ownerId, bool forceUnencrypted)
*/ */
QPixmap Profile::loadAvatar() QPixmap Profile::loadAvatar()
{ {
return loadAvatar(core->getSelfId().getPublicKeyString()); return loadAvatar(core->getSelfId().getPublicKey().getKey());
} }
/** /**
@ -495,7 +495,7 @@ QByteArray Profile::loadAvatarData(const QString& ownerId, const QString& passwo
return pic; return pic;
} }
void Profile::loadDatabase(const QString& id) void Profile::loadDatabase(const ToxId& id)
{ {
if(isRemoved) if(isRemoved)
{ {
@ -503,7 +503,7 @@ void Profile::loadDatabase(const QString& id)
return; return;
} }
QByteArray salt = ToxId {id}.getPublicKey(); QByteArray salt = id.getPublicKey().getKey();
if(salt.size() != TOX_PASS_SALT_LENGTH) if(salt.size() != TOX_PASS_SALT_LENGTH)
{ {
qWarning() << "Couldn't compute salt from public key" << name; qWarning() << "Couldn't compute salt from public key" << name;
@ -572,7 +572,7 @@ QByteArray Profile::getAvatarHash(const QString& ownerId)
*/ */
void Profile::removeAvatar() void Profile::removeAvatar()
{ {
removeAvatar(core->getSelfId().getPublicKeyString()); removeAvatar(core->getSelfId().getPublicKey().toString());
} }
/** /**
@ -600,7 +600,7 @@ History* Profile::getHistory()
void Profile::removeAvatar(const QString& ownerId) void Profile::removeAvatar(const QString& ownerId)
{ {
QFile::remove(avatarPath(ownerId)); QFile::remove(avatarPath(ownerId));
if (ownerId == core->getSelfId().getPublicKeyString()) if (ownerId == core->getSelfId().getPublicKey().toString())
core->setAvatar({}); core->setAvatar({});
} }
@ -789,7 +789,7 @@ void Profile::restartCore()
*/ */
void Profile::setPassword(const QString& newPassword) void Profile::setPassword(const QString& newPassword)
{ {
QByteArray avatar = loadAvatarData(core->getSelfId().getPublicKeyString()); QByteArray avatar = loadAvatarData(core->getSelfId().getPublicKey().toString());
QString oldPassword = password; QString oldPassword = password;
password = newPassword; password = newPassword;
passkey = core->createPasskey(password); passkey = core->createPasskey(password);
@ -801,14 +801,14 @@ void Profile::setPassword(const QString& newPassword)
} }
Nexus::getDesktopGUI()->reloadHistory(); Nexus::getDesktopGUI()->reloadHistory();
saveAvatar(avatar, core->getSelfId().getPublicKeyString()); saveAvatar(avatar, core->getSelfId().getPublicKey().toString());
QVector<uint32_t> friendList = core->getFriendList(); QVector<uint32_t> friendList = core->getFriendList();
QVectorIterator<uint32_t> i(friendList); QVectorIterator<uint32_t> i(friendList);
while (i.hasNext()) while (i.hasNext())
{ {
QString friendPublicKey = core->getFriendPublicKey(i.next()); QString friendPublicKey = core->getFriendPublicKey(i.next()).toString();
saveAvatar(loadAvatarData(friendPublicKey,oldPassword),friendPublicKey); saveAvatar(loadAvatarData(friendPublicKey, oldPassword), friendPublicKey);
} }
} }

View File

@ -21,15 +21,19 @@
#ifndef PROFILE_H #ifndef PROFILE_H
#define PROFILE_H #define PROFILE_H
#include <QVector> #include "src/core/toxid.h"
#include <QString>
#include <QByteArray>
#include <QPixmap>
#include <QObject>
#include <tox/toxencryptsave.h> #include <tox/toxencryptsave.h>
#include <memory>
#include "src/persistence/history.h" #include "src/persistence/history.h"
#include <memory>
#include <QByteArray>
#include <QObject>
#include <QPixmap>
#include <QString>
#include <QVector>
class Core; class Core;
class QThread; class QThread;
@ -82,7 +86,7 @@ public:
static QString getDbPath(const QString& profileName); static QString getDbPath(const QString& profileName);
private slots: private slots:
void loadDatabase(const QString& id); void loadDatabase(const ToxId& id);
private: private:
Profile(QString name, const QString& password, bool newProfile); Profile(QString name, const QString& password, bool newProfile);
static QVector<QString> getFilesByExt(QString extension); static QVector<QString> getFilesByExt(QString extension);

View File

@ -389,8 +389,7 @@ void Settings::loadPersonal(Profile* profile)
if (getEnableLogging()) if (getEnableLogging())
fp.activity = ps.value("activity", QDate()).toDate(); fp.activity = ps.value("activity", QDate()).toDate();
friendLst[ToxId(fp.addr).getPublicKey().getKey()] = fp;
friendLst[ToxId(fp.addr).getPublicKeyString()] = fp;
} }
ps.endArray(); ps.endArray();
} }
@ -641,7 +640,7 @@ void Settings::savePersonal(Profile* profile)
savePersonal(profile->getName(), profile->getPassword()); savePersonal(profile->getName(), profile->getPassword());
} }
void Settings::savePersonal(QString profileName, const QString &password) void Settings::savePersonal(QString profileName, const QString& password)
{ {
if (QThread::currentThread() != settingsThread) if (QThread::currentThread() != settingsThread)
return (void) QMetaObject::invokeMethod(&getInstance(), "savePersonal", return (void) QMetaObject::invokeMethod(&getInstance(), "savePersonal",
@ -1430,24 +1429,22 @@ void Settings::setAutoAwayTime(int newValue)
} }
} }
QString Settings::getAutoAcceptDir(const ToxId& id) const QString Settings::getAutoAcceptDir(const ToxPk& id) const
{ {
QMutexLocker locker{&bigLock}; QMutexLocker locker{&bigLock};
QString key = id.getPublicKeyString();
auto it = friendLst.find(key); auto it = friendLst.find(id.getKey());
if (it != friendLst.end()) if (it != friendLst.end())
return it->autoAcceptDir; return it->autoAcceptDir;
return QString(); return QString();
} }
void Settings::setAutoAcceptDir(const ToxId &id, const QString& dir) void Settings::setAutoAcceptDir(const ToxPk& id, const QString& dir)
{ {
QMutexLocker locker{&bigLock}; QMutexLocker locker{&bigLock};
QString key = id.getPublicKeyString();
auto it = friendLst.find(key); auto it = friendLst.find(id.getKey());
if (it != friendLst.end()) if (it != friendLst.end())
{ {
it->autoAcceptDir = dir; it->autoAcceptDir = dir;
@ -1459,24 +1456,22 @@ void Settings::setAutoAcceptDir(const ToxId &id, const QString& dir)
} }
} }
Settings::AutoAcceptCallFlags Settings::getAutoAcceptCall(const ToxId &id) const Settings::AutoAcceptCallFlags Settings::getAutoAcceptCall(const ToxPk& id) const
{ {
QMutexLocker locker{&bigLock}; QMutexLocker locker{&bigLock};
QString key = id.getPublicKeyString();
auto it = friendLst.find(key); auto it = friendLst.find(id.getKey());
if (it != friendLst.end()) if (it != friendLst.end())
return it->autoAcceptCall; return it->autoAcceptCall;
return Settings::AutoAcceptCallFlags(); return Settings::AutoAcceptCallFlags();
} }
void Settings::setAutoAcceptCall(const ToxId& id, AutoAcceptCallFlags accept) void Settings::setAutoAcceptCall(const ToxPk& id, AutoAcceptCallFlags accept)
{ {
QMutexLocker locker{&bigLock}; QMutexLocker locker{&bigLock};
QString key = id.getPublicKeyString();
auto it = friendLst.find(key); auto it = friendLst.find(id.getKey());
if(it != friendLst.end()) if(it != friendLst.end())
{ {
it->autoAcceptCall = accept; it->autoAcceptCall = accept;
@ -1484,22 +1479,22 @@ void Settings::setAutoAcceptCall(const ToxId& id, AutoAcceptCallFlags accept)
} }
} }
QString Settings::getContactNote(const ToxId &id) const QString Settings::getContactNote(const ToxPk& id) const
{ {
QMutexLocker locker{&bigLock}; QMutexLocker locker{&bigLock};
auto it = friendLst.find(id.getPublicKeyString()); auto it = friendLst.find(id.getKey());
if (it != friendLst.end()) if (it != friendLst.end())
return it->note; return it->note;
return QString(); return QString();
} }
void Settings::setContactNote(const ToxId &id, const QString& note) void Settings::setContactNote(const ToxPk& id, const QString& note)
{ {
QMutexLocker locker{&bigLock}; QMutexLocker locker{&bigLock};
auto it = friendLst.find(id.getPublicKeyString()); auto it = friendLst.find(id.getKey());
if (it != friendLst.end()) if (it != friendLst.end())
{ {
qDebug() << note; qDebug() << note;
@ -2009,7 +2004,8 @@ void Settings::setCamVideoFPS(unsigned short newValue)
QString Settings::getFriendAddress(const QString& publicKey) const QString Settings::getFriendAddress(const QString& publicKey) const
{ {
QMutexLocker locker{&bigLock}; QMutexLocker locker{&bigLock};
QString key = ToxId(publicKey).getPublicKeyString(); // TODO: using ToxId here is a hack
QByteArray key = ToxId(publicKey).getPublicKey().getKey();
auto it = friendLst.find(key); auto it = friendLst.find(key);
if (it != friendLst.end()) if (it != friendLst.end())
return it->addr; return it->addr;
@ -2020,7 +2016,8 @@ QString Settings::getFriendAddress(const QString& publicKey) const
void Settings::updateFriendAddress(const QString& newAddr) void Settings::updateFriendAddress(const QString& newAddr)
{ {
QMutexLocker locker{&bigLock}; QMutexLocker locker{&bigLock};
QString key = ToxId(newAddr).getPublicKeyString(); // TODO: using ToxId here is a hack
QByteArray key = ToxId(newAddr).getPublicKey().getKey();
auto it = friendLst.find(key); auto it = friendLst.find(key);
if (it != friendLst.end()) if (it != friendLst.end())
{ {
@ -2033,26 +2030,24 @@ void Settings::updateFriendAddress(const QString& newAddr)
fp.alias = ""; fp.alias = "";
fp.note = ""; fp.note = "";
fp.autoAcceptDir = ""; fp.autoAcceptDir = "";
friendLst[newAddr] = fp; friendLst[key] = fp;
} }
} }
QString Settings::getFriendAlias(const ToxId& id) const QString Settings::getFriendAlias(const ToxPk& id) const
{ {
QMutexLocker locker{&bigLock}; QMutexLocker locker{&bigLock};
QString key = id.getPublicKeyString(); auto it = friendLst.find(id.getKey());
auto it = friendLst.find(key);
if (it != friendLst.end()) if (it != friendLst.end())
return it->alias; return it->alias;
return QString(); return QString();
} }
void Settings::setFriendAlias(const ToxId& id, const QString& alias) void Settings::setFriendAlias(const ToxPk& id, const QString& alias)
{ {
QMutexLocker locker{&bigLock}; QMutexLocker locker{&bigLock};
QString key = id.getPublicKeyString(); auto it = friendLst.find(id.getKey());
auto it = friendLst.find(key);
if (it != friendLst.end()) if (it != friendLst.end())
{ {
it->alias = alias; it->alias = alias;
@ -2060,28 +2055,26 @@ void Settings::setFriendAlias(const ToxId& id, const QString& alias)
else else
{ {
friendProp fp; friendProp fp;
fp.addr = key; fp.addr = id.toString();
fp.alias = alias; fp.alias = alias;
fp.note = ""; fp.note = "";
fp.autoAcceptDir = ""; fp.autoAcceptDir = "";
friendLst[key] = fp; friendLst[id.getKey()] = fp;
} }
} }
int Settings::getFriendCircleID(const ToxId& id) const int Settings::getFriendCircleID(const ToxPk& id) const
{ {
QString key = id.getPublicKeyString(); auto it = friendLst.find(id.getKey());
auto it = friendLst.find(key);
if (it != friendLst.end()) if (it != friendLst.end())
return it->circleID; return it->circleID;
return -1; return -1;
} }
void Settings::setFriendCircleID(const ToxId& id, int circleID) void Settings::setFriendCircleID(const ToxPk& id, int circleID)
{ {
QString key = id.getPublicKeyString(); auto it = friendLst.find(id.getKey());
auto it = friendLst.find(key);
if (it != friendLst.end()) if (it != friendLst.end())
{ {
it->circleID = circleID; it->circleID = circleID;
@ -2089,29 +2082,27 @@ void Settings::setFriendCircleID(const ToxId& id, int circleID)
else else
{ {
friendProp fp; friendProp fp;
fp.addr = key; fp.addr = id.toString();
fp.alias = ""; fp.alias = "";
fp.note = ""; fp.note = "";
fp.autoAcceptDir = ""; fp.autoAcceptDir = "";
fp.circleID = circleID; fp.circleID = circleID;
friendLst[key] = fp; friendLst[id.getKey()] = fp;
} }
} }
QDate Settings::getFriendActivity(const ToxId& id) const QDate Settings::getFriendActivity(const ToxPk& id) const
{ {
QString key = id.getPublicKeyString(); auto it = friendLst.find(id.getKey());
auto it = friendLst.find(key);
if (it != friendLst.end()) if (it != friendLst.end())
return it->activity; return it->activity;
return QDate(); return QDate();
} }
void Settings::setFriendActivity(const ToxId& id, const QDate& activity) void Settings::setFriendActivity(const ToxPk& id, const QDate& activity)
{ {
QString key = id.getPublicKeyString(); auto it = friendLst.find(id.getKey());
auto it = friendLst.find(key);
if (it != friendLst.end()) if (it != friendLst.end())
{ {
it->activity = activity; it->activity = activity;
@ -2119,21 +2110,20 @@ void Settings::setFriendActivity(const ToxId& id, const QDate& activity)
else else
{ {
friendProp fp; friendProp fp;
fp.addr = key; fp.addr = id.toString();
fp.alias = ""; fp.alias = "";
fp.note = ""; fp.note = "";
fp.autoAcceptDir = ""; fp.autoAcceptDir = "";
fp.circleID = -1; fp.circleID = -1;
fp.activity = activity; fp.activity = activity;
friendLst[key] = fp; friendLst[id.getKey()] = fp;
} }
} }
void Settings::removeFriendSettings(const ToxId& id) void Settings::removeFriendSettings(const ToxPk& id)
{ {
QMutexLocker locker{&bigLock}; QMutexLocker locker{&bigLock};
QString key = id.getPublicKeyString(); friendLst.remove(id.getKey());
friendLst.remove(key);
} }
bool Settings::getFauxOfflineMessaging() const bool Settings::getFauxOfflineMessaging() const

View File

@ -31,7 +31,7 @@
#include <QFlags> #include <QFlags>
#include "src/core/corestructs.h" #include "src/core/corestructs.h"
class ToxId; class ToxPk;
class Profile; class Profile;
namespace Db { namespace Db {
@ -152,11 +152,11 @@ public:
void createPersonal(QString basename); void createPersonal(QString basename);
void savePersonal(); void savePersonal();
void savePersonal(Profile *profile); void savePersonal(Profile* profile);
void loadGlobal(); void loadGlobal();
void loadPersonal(); void loadPersonal();
void loadPersonal(Profile *profile); void loadPersonal(Profile* profile);
void resetToDefault(); void resetToDefault();
@ -203,7 +203,7 @@ signals:
void globalAutoAcceptDirChanged(const QString& path); void globalAutoAcceptDirChanged(const QString& path);
void checkUpdatesChanged(bool enabled); void checkUpdatesChanged(bool enabled);
void widgetDataChanged(const QString& key); void widgetDataChanged(const QString& key);
void autoAcceptCallChanged(const ToxId& id, AutoAcceptCallFlags accept); void autoAcceptCallChanged(const ToxPk& id, AutoAcceptCallFlags accept);
// GUI // GUI
void autoLoginChanged(bool enabled); void autoLoginChanged(bool enabled);
@ -407,14 +407,14 @@ public:
int getEmojiFontPointSize() const; int getEmojiFontPointSize() const;
void setEmojiFontPointSize(int value); void setEmojiFontPointSize(int value);
QString getContactNote(const ToxId& id) const; QString getContactNote(const ToxPk& id) const;
void setContactNote(const ToxId& id, const QString& note); void setContactNote(const ToxPk& id, const QString& note);
QString getAutoAcceptDir(const ToxId& id) const; QString getAutoAcceptDir(const ToxPk& id) const;
void setAutoAcceptDir(const ToxId& id, const QString& dir); void setAutoAcceptDir(const ToxPk& id, const QString& dir);
AutoAcceptCallFlags getAutoAcceptCall(const ToxId& id) const; AutoAcceptCallFlags getAutoAcceptCall(const ToxPk& id) const;
void setAutoAcceptCall(const ToxId& id, AutoAcceptCallFlags accept); void setAutoAcceptCall(const ToxPk& id, AutoAcceptCallFlags accept);
QString getGlobalAutoAcceptDir() const; QString getGlobalAutoAcceptDir() const;
void setGlobalAutoAcceptDir(const QString& dir); void setGlobalAutoAcceptDir(const QString& dir);
@ -461,16 +461,16 @@ public:
QString getFriendAddress(const QString& publicKey) const; QString getFriendAddress(const QString& publicKey) const;
void updateFriendAddress(const QString& newAddr); void updateFriendAddress(const QString& newAddr);
QString getFriendAlias(const ToxId& id) const; QString getFriendAlias(const ToxPk& id) const;
void setFriendAlias(const ToxId& id, const QString& alias); void setFriendAlias(const ToxPk& id, const QString& alias);
int getFriendCircleID(const ToxId& id) const; int getFriendCircleID(const ToxPk& id) const;
void setFriendCircleID(const ToxId& id, int circleID); void setFriendCircleID(const ToxPk& id, int circleID);
QDate getFriendActivity(const ToxId& id) const; QDate getFriendActivity(const ToxPk& id) const;
void setFriendActivity(const ToxId& id, const QDate &date); void setFriendActivity(const ToxPk& id, const QDate &date);
void removeFriendSettings(const ToxId& id); void removeFriendSettings(const ToxPk& id);
bool getFauxOfflineMessaging() const; bool getFauxOfflineMessaging() const;
void setFauxOfflineMessaging(bool value); void setFauxOfflineMessaging(bool value);
@ -533,7 +533,7 @@ private:
Settings& operator=(const Settings&) = delete; Settings& operator=(const Settings&) = delete;
private slots: private slots:
void savePersonal(QString profileName, const QString &password); void savePersonal(QString profileName, const QString& password);
private: private:
bool loaded; bool loaded;
@ -649,7 +649,7 @@ private:
bool expanded; bool expanded;
}; };
QHash<QString, friendProp> friendLst; QHash<QByteArray, friendProp> friendLst;
QVector<circleProp> circleLst; QVector<circleProp> circleLst;

View File

@ -172,7 +172,7 @@ void GroupNetCamView::clearPeers()
void GroupNetCamView::addPeer(int peer, const QString& name) void GroupNetCamView::addPeer(int peer, const QString& name)
{ {
QPixmap groupAvatar = Nexus::getProfile()->loadAvatar(Core::getInstance()->getGroupPeerToxId(group, peer).toString()); QPixmap groupAvatar = Nexus::getProfile()->loadAvatar(Core::getInstance()->getGroupPeerPk(group, peer).toString());
LabeledVideo* labeledVideo = new LabeledVideo(groupAvatar, this); LabeledVideo* labeledVideo = new LabeledVideo(groupAvatar, this);
labeledVideo->setText(name); labeledVideo->setText(name);
horLayout->insertWidget(horLayout->count() - 1, labeledVideo); horLayout->insertWidget(horLayout->count() - 1, labeledVideo);
@ -262,7 +262,7 @@ void GroupNetCamView::friendAvatarChanged(int FriendId, const QPixmap &pixmap)
for (uint32_t i = 0; i < Core::getInstance()->getGroupNumberPeers(group); ++i) for (uint32_t i = 0; i < Core::getInstance()->getGroupNumberPeers(group); ++i)
{ {
if (Core::getInstance()->getGroupPeerToxId(group, i) == f->getToxId()) if (Core::getInstance()->getGroupPeerPk(group, i) == f->getPublicKey())
{ {
auto peerVideo = videoList.find(i); auto peerVideo = videoList.find(i);

View File

@ -37,7 +37,7 @@ NetCamView::NetCamView(int friendId, QWidget* parent)
, friendId{friendId} , friendId{friendId}
, e(false) , e(false)
{ {
QString id = FriendList::findFriend(friendId)->getToxId().toString(); QString id = FriendList::findFriend(friendId)->getPublicKey().toString();
videoSurface = new VideoSurface(Nexus::getProfile()->loadAvatar(id), this); videoSurface = new VideoSurface(Nexus::getProfile()->loadAvatar(id), this);
videoSurface->setMinimumHeight(256); videoSurface->setMinimumHeight(256);
videoSurface->setContentsMargins(6, 6, 6, 6); videoSurface->setContentsMargins(6, 6, 6, 6);

View File

@ -8,7 +8,7 @@
#include <QFileDialog> #include <QFileDialog>
#include <QMessageBox> #include <QMessageBox>
AboutUser::AboutUser(ToxId &toxId, QWidget *parent) : AboutUser::AboutUser(ToxPk &toxId, QWidget *parent) :
QDialog(parent), QDialog(parent),
ui(new Ui::AboutUser) ui(new Ui::AboutUser)
{ {
@ -22,27 +22,27 @@ AboutUser::AboutUser(ToxId &toxId, QWidget *parent) :
connect(ui->selectSaveDir, &QPushButton::clicked, this, &AboutUser::onSelectDirClicked); connect(ui->selectSaveDir, &QPushButton::clicked, this, &AboutUser::onSelectDirClicked);
connect(ui->removeHistory, &QPushButton::clicked, this, &AboutUser::onRemoveHistoryClicked); connect(ui->removeHistory, &QPushButton::clicked, this, &AboutUser::onRemoveHistoryClicked);
this->toxId = toxId; this->friendPk = toxId;
QString dir = Settings::getInstance().getAutoAcceptDir(this->toxId); QString dir = Settings::getInstance().getAutoAcceptDir(this->friendPk);
ui->autoacceptfile->setChecked(!dir.isEmpty()); ui->autoacceptfile->setChecked(!dir.isEmpty());
ui->autoacceptcall->setCurrentIndex(Settings::getInstance().getAutoAcceptCall(this->toxId)); ui->autoacceptcall->setCurrentIndex(Settings::getInstance().getAutoAcceptCall(this->friendPk));
ui->selectSaveDir->setEnabled(ui->autoacceptfile->isChecked()); ui->selectSaveDir->setEnabled(ui->autoacceptfile->isChecked());
if(ui->autoacceptfile->isChecked()) if(ui->autoacceptfile->isChecked())
ui->selectSaveDir->setText(Settings::getInstance().getAutoAcceptDir(this->toxId)); ui->selectSaveDir->setText(Settings::getInstance().getAutoAcceptDir(this->friendPk));
} }
void AboutUser::setFriend(Friend *f) void AboutUser::setFriend(Friend *f)
{ {
this->setWindowTitle(f->getDisplayedName()); this->setWindowTitle(f->getDisplayedName());
ui->userName->setText(f->getDisplayedName()); ui->userName->setText(f->getDisplayedName());
ui->publicKey->setText(QString(f->getToxId().toString())); ui->publicKey->setText(QString(f->getPublicKey().toString()));
ui->publicKey->setCursorPosition(0); //scroll textline to left ui->publicKey->setCursorPosition(0); //scroll textline to left
ui->note->setPlainText(Settings::getInstance().getContactNote(f->getToxId())); ui->note->setPlainText(Settings::getInstance().getContactNote(f->getPublicKey()));
QPixmap avatar = Nexus::getProfile()->loadAvatar(f->getToxId().toString()); QPixmap avatar = Nexus::getProfile()->loadAvatar(f->getPublicKey().toString());
ui->statusMessage->setText(f->getStatusMessage()); ui->statusMessage->setText(f->getStatusMessage());
if(!avatar.isNull()) { if(!avatar.isNull()) {
ui->avatar->setPixmap(avatar); ui->avatar->setPixmap(avatar);
@ -59,7 +59,7 @@ void AboutUser::onAutoAcceptDirClicked()
{ {
dir = QDir::homePath(); dir = QDir::homePath();
ui->autoacceptfile->setChecked(false); ui->autoacceptfile->setChecked(false);
Settings::getInstance().setAutoAcceptDir(this->toxId, ""); Settings::getInstance().setAutoAcceptDir(this->friendPk, "");
ui->selectSaveDir->setText(tr("Auto accept for this contact is disabled")); ui->selectSaveDir->setText(tr("Auto accept for this contact is disabled"));
} }
else if (ui->autoacceptfile->isChecked()) else if (ui->autoacceptfile->isChecked())
@ -73,8 +73,8 @@ void AboutUser::onAutoAcceptDirClicked()
ui->autoacceptfile->setChecked(false); ui->autoacceptfile->setChecked(false);
return; // user canellced return; // user canellced
} }
Settings::getInstance().setAutoAcceptDir(this->toxId, dir); Settings::getInstance().setAutoAcceptDir(this->friendPk, dir);
ui->selectSaveDir->setText(Settings::getInstance().getAutoAcceptDir(this->toxId)); ui->selectSaveDir->setText(Settings::getInstance().getAutoAcceptDir(this->friendPk));
} }
Settings::getInstance().saveGlobal(); Settings::getInstance().saveGlobal();
ui->selectSaveDir->setEnabled(ui->autoacceptfile->isChecked()); ui->selectSaveDir->setEnabled(ui->autoacceptfile->isChecked());
@ -82,7 +82,7 @@ void AboutUser::onAutoAcceptDirClicked()
void AboutUser::onAutoAcceptCallClicked() void AboutUser::onAutoAcceptCallClicked()
{ {
Settings::getInstance().setAutoAcceptCall(this->toxId,Settings::AutoAcceptCallFlags(QFlag(ui->autoacceptcall->currentIndex()))); Settings::getInstance().setAutoAcceptCall(this->friendPk,Settings::AutoAcceptCallFlags(QFlag(ui->autoacceptcall->currentIndex())));
Settings::getInstance().savePersonal(); Settings::getInstance().savePersonal();
} }
@ -94,7 +94,7 @@ void AboutUser::onSelectDirClicked()
dir, dir,
QFileDialog::DontUseNativeDialog); QFileDialog::DontUseNativeDialog);
ui->autoacceptfile->setChecked(true); ui->autoacceptfile->setChecked(true);
Settings::getInstance().setAutoAcceptDir(this->toxId, dir); Settings::getInstance().setAutoAcceptDir(this->friendPk, dir);
Settings::getInstance().savePersonal(); Settings::getInstance().savePersonal();
} }
@ -103,8 +103,7 @@ void AboutUser::onSelectDirClicked()
*/ */
void AboutUser::onAcceptedClicked() void AboutUser::onAcceptedClicked()
{ {
ToxId toxId = ToxId(ui->publicKey->text()); Settings::getInstance().setContactNote(friendPk, ui->note->toPlainText());
Settings::getInstance().setContactNote(toxId, ui->note->toPlainText());
Settings::getInstance().saveGlobal(); Settings::getInstance().saveGlobal();
} }
@ -112,7 +111,7 @@ void AboutUser::onRemoveHistoryClicked()
{ {
History* history = Nexus::getProfile()->getHistory(); History* history = Nexus::getProfile()->getHistory();
if (history) if (history)
history->removeFriendHistory(toxId.getPublicKeyString()); history->removeFriendHistory(friendPk.toString());
QMessageBox::information(this, QMessageBox::information(this,
tr("History removed"), tr("History removed"),
tr("Chat history with %1 removed!").arg(ui->userName->text().toHtmlEscaped()), tr("Chat history with %1 removed!").arg(ui->userName->text().toHtmlEscaped()),

View File

@ -14,13 +14,13 @@ class AboutUser : public QDialog
Q_OBJECT Q_OBJECT
public: public:
explicit AboutUser(ToxId &toxID, QWidget *parent = 0); explicit AboutUser(ToxPk &toxID, QWidget *parent = 0);
~AboutUser(); ~AboutUser();
void setFriend(Friend *f); void setFriend(Friend *f);
private: private:
Ui::AboutUser *ui; Ui::AboutUser *ui;
ToxId toxId; ToxPk friendPk;
private slots: private slots:
void onAcceptedClicked(); void onAcceptedClicked();

View File

@ -154,7 +154,7 @@ void CircleWidget::contextMenuEvent(QContextMenuEvent* event)
void CircleWidget::dragEnterEvent(QDragEnterEvent* event) void CircleWidget::dragEnterEvent(QDragEnterEvent* event)
{ {
ToxId toxId(event->mimeData()->text()); ToxId toxId(event->mimeData()->text());
Friend *f = FriendList::findFriend(toxId); Friend *f = FriendList::findFriend(toxId.getPublicKey());
if (f != nullptr) if (f != nullptr)
event->acceptProposedAction(); event->acceptProposedAction();
@ -178,12 +178,12 @@ void CircleWidget::dropEvent(QDropEvent* event)
// Check, that the user has a friend with the same ToxId // Check, that the user has a friend with the same ToxId
ToxId toxId(event->mimeData()->text()); ToxId toxId(event->mimeData()->text());
Friend *f = FriendList::findFriend(toxId); Friend *f = FriendList::findFriend(toxId.getPublicKey());
if (!f) if (!f)
return; return;
// Save CircleWidget before changing the Id // Save CircleWidget before changing the Id
int circleId = Settings::getInstance().getFriendCircleID(toxId); int circleId = Settings::getInstance().getFriendCircleID(toxId.getPublicKey());
CircleWidget* circleWidget = getFromID(circleId); CircleWidget* circleWidget = getFromID(circleId);
addFriendWidget(widget, f->getStatus()); addFriendWidget(widget, f->getStatus());
@ -212,7 +212,7 @@ void CircleWidget::onExpand()
void CircleWidget::onAddFriendWidget(FriendWidget* w) void CircleWidget::onAddFriendWidget(FriendWidget* w)
{ {
Friend* f = FriendList::findFriend(w->friendId); Friend* f = FriendList::findFriend(w->friendId);
ToxId toxId = f->getToxId(); ToxPk toxId = f->getPublicKey();
Settings::getInstance().setFriendCircleID(toxId, id); Settings::getInstance().setFriendCircleID(toxId, id);
} }
@ -232,13 +232,13 @@ void CircleWidget::updateID(int index)
FriendWidget* friendWidget = qobject_cast<FriendWidget*>(friendOnlineLayout()->itemAt(i)->widget()); FriendWidget* friendWidget = qobject_cast<FriendWidget*>(friendOnlineLayout()->itemAt(i)->widget());
if (friendWidget != nullptr) if (friendWidget != nullptr)
Settings::getInstance().setFriendCircleID(FriendList::findFriend(friendWidget->friendId)->getToxId(), id); Settings::getInstance().setFriendCircleID(FriendList::findFriend(friendWidget->friendId)->getPublicKey(), id);
} }
for (int i = 0; i < friendOfflineLayout()->count(); ++i) for (int i = 0; i < friendOfflineLayout()->count(); ++i)
{ {
FriendWidget* friendWidget = qobject_cast<FriendWidget*>(friendOfflineLayout()->itemAt(i)->widget()); FriendWidget* friendWidget = qobject_cast<FriendWidget*>(friendOfflineLayout()->itemAt(i)->widget());
if (friendWidget != nullptr) if (friendWidget != nullptr)
Settings::getInstance().setFriendCircleID(FriendList::findFriend(friendWidget->friendId)->getToxId(), id); Settings::getInstance().setFriendCircleID(FriendList::findFriend(friendWidget->friendId)->getPublicKey(), id);
} }
} }

View File

@ -541,7 +541,7 @@ void ContentDialog::dragEnterEvent(QDragEnterEvent *event)
if (frnd) if (frnd)
{ {
ToxId toxId(event->mimeData()->text()); ToxId toxId(event->mimeData()->text());
Friend *contact = FriendList::findFriend(toxId); Friend *contact = FriendList::findFriend(toxId.getPublicKey());
if (!contact) if (!contact)
return; return;
@ -576,7 +576,7 @@ void ContentDialog::dropEvent(QDropEvent *event)
if (frnd) if (frnd)
{ {
ToxId toxId(event->mimeData()->text()); ToxId toxId(event->mimeData()->text());
Friend *contact = FriendList::findFriend(toxId); Friend *contact = FriendList::findFriend(toxId.getPublicKey());
if (!contact) if (!contact)
return; return;

View File

@ -163,26 +163,26 @@ void AddFriendForm::onUsernameSet(const QString& username)
void AddFriendForm::onSendTriggered() void AddFriendForm::onSendTriggered()
{ {
QString id = toxId.text().trimmed(); QString id = toxId.text().trimmed();
ToxId toxId;
if (!ToxId::isValidToxId(id)) if (!ToxId::isValidToxId(id))
{ {
ToxId toxId = Toxme::lookup(id); // Try Toxme toxId = Toxme::lookup(id); // Try Toxme
if (toxId.toString().isEmpty()) if (!toxId.isValid())
{ {
GUI::showWarning(tr("Couldn't add friend"), GUI::showWarning(tr("Couldn't add friend"),
tr("This Tox ID is invalid or does not exist", "Toxme error")); tr("This Tox ID is invalid or does not exist", "Toxme error"));
return; return;
} }
id = toxId.toString();
} }
deleteFriendRequest(id); deleteFriendRequest(toxId);
if (id.toUpper() == Core::getInstance()->getSelfId().toString().toUpper()) if (toxId == Core::getInstance()->getSelfId())
GUI::showWarning(tr("Couldn't add friend"), GUI::showWarning(tr("Couldn't add friend"),
tr("You can't add yourself as a friend!", tr("You can't add yourself as a friend!",
"When trying to add your own Tox ID as friend")); "When trying to add your own Tox ID as friend"));
else else
emit friendRequested(id, getMessage()); emit friendRequested(toxId, getMessage());
this->toxId.clear(); this->toxId.clear();
this->message.clear(); this->message.clear();
@ -231,13 +231,13 @@ void AddFriendForm::setIdFromClipboard()
} }
} }
void AddFriendForm::deleteFriendRequest(const QString& toxId) void AddFriendForm::deleteFriendRequest(const ToxId& toxId)
{ {
int size = Settings::getInstance().getFriendRequestSize(); int size = Settings::getInstance().getFriendRequestSize();
for (int i = 0; i < size; ++i) for (int i = 0; i < size; ++i)
{ {
Settings::Request request = Settings::getInstance().getFriendRequest(i); Settings::Request request = Settings::getInstance().getFriendRequest(i);
if (ToxId(toxId) == ToxId(request.address)) if (toxId == ToxId(request.address))
{ {
Settings::getInstance().removeFriendRequest(i); Settings::getInstance().removeFriendRequest(i);
return; return;
@ -252,7 +252,7 @@ void AddFriendForm::onFriendRequestAccepted()
int index = requestsLayout->indexOf(friendWidget); int index = requestsLayout->indexOf(friendWidget);
removeFriendRequestWidget(friendWidget); removeFriendRequestWidget(friendWidget);
Settings::Request request = Settings::getInstance().getFriendRequest(requestsLayout->count() - index - 1); Settings::Request request = Settings::getInstance().getFriendRequest(requestsLayout->count() - index - 1);
emit friendRequestAccepted(request.address); emit friendRequestAccepted(ToxId(request.address).getPublicKey());
Settings::getInstance().removeFriendRequest(requestsLayout->count() - index - 1); Settings::getInstance().removeFriendRequest(requestsLayout->count() - index - 1);
Settings::getInstance().savePersonal(); Settings::getInstance().savePersonal();
} }

View File

@ -20,6 +20,8 @@
#ifndef ADDFRIENDFORM_H #ifndef ADDFRIENDFORM_H
#define ADDFRIENDFORM_H #define ADDFRIENDFORM_H
#include "src/core/toxid.h"
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QLabel> #include <QLabel>
#include <QLineEdit> #include <QLineEdit>
@ -55,8 +57,8 @@ public:
bool addFriendRequest(const QString& friendAddress, const QString& message); bool addFriendRequest(const QString& friendAddress, const QString& message);
signals: signals:
void friendRequested(const QString& friendAddress, const QString& message); void friendRequested(const ToxId& friendAddress, const QString& message);
void friendRequestAccepted(const QString& friendAddress); void friendRequestAccepted(const ToxPk& friendAddress);
void friendRequestsSeen(); void friendRequestsSeen();
public slots: public slots:
@ -75,7 +77,7 @@ private:
void removeFriendRequestWidget(QWidget *friendWidget); void removeFriendRequestWidget(QWidget *friendWidget);
void retranslateAcceptButton(QPushButton* acceptButton); void retranslateAcceptButton(QPushButton* acceptButton);
void retranslateRejectButton(QPushButton* rejectButton); void retranslateRejectButton(QPushButton* rejectButton);
void deleteFriendRequest(const QString &toxId); void deleteFriendRequest(const ToxId& toxId);
void setIdFromClipboard(); void setIdFromClipboard();
private: private:

View File

@ -266,7 +266,7 @@ void ChatForm::startFileSend(ToxFile file)
QString name; QString name;
const Core* core = Core::getInstance(); const Core* core = Core::getInstance();
ToxId self = core->getSelfId(); ToxPk self = core->getSelfId().getPublicKey();
if (previousId != self) if (previousId != self)
{ {
name = core->getUsername(); name = core->getUsername();
@ -286,7 +286,7 @@ void ChatForm::onFileRecvRequest(ToxFile file)
Widget::getInstance()->newFriendMessageAlert(file.friendId); Widget::getInstance()->newFriendMessageAlert(file.friendId);
QString name; QString name;
ToxId friendId = f->getToxId(); ToxPk friendId = f->getPublicKey();
if (friendId != previousId) if (friendId != previousId)
{ {
name = f->getDisplayedName(); name = f->getDisplayedName();
@ -301,9 +301,9 @@ void ChatForm::onFileRecvRequest(ToxFile file)
FileTransferWidget* tfWidget = static_cast<FileTransferWidget*>(proxy->getWidget()); FileTransferWidget* tfWidget = static_cast<FileTransferWidget*>(proxy->getWidget());
// there is auto-accept for that conact // there is auto-accept for that conact
if (!Settings::getInstance().getAutoAcceptDir(f->getToxId()).isEmpty()) if (!Settings::getInstance().getAutoAcceptDir(f->getPublicKey()).isEmpty())
{ {
tfWidget->autoAcceptTransfer(Settings::getInstance().getAutoAcceptDir(f->getToxId())); tfWidget->autoAcceptTransfer(Settings::getInstance().getAutoAcceptDir(f->getPublicKey()));
} }
else if (Settings::getInstance().getAutoSaveEnabled()) else if (Settings::getInstance().getAutoSaveEnabled())
{ //global autosave to global directory { //global autosave to global directory
@ -323,8 +323,8 @@ void ChatForm::onAvInvite(uint32_t friendId, bool video)
ChatMessage::INFO, ChatMessage::INFO,
QDateTime::currentDateTime())); QDateTime::currentDateTime()));
/* AutoAcceptCall is set for this friend */ /* AutoAcceptCall is set for this friend */
if ((video && Settings::getInstance().getAutoAcceptCall(f->getToxId()).testFlag(Settings::AutoAcceptCall::Video)) || if ((video && Settings::getInstance().getAutoAcceptCall(f->getPublicKey()).testFlag(Settings::AutoAcceptCall::Video)) ||
(!video && Settings::getInstance().getAutoAcceptCall(f->getToxId()).testFlag(Settings::AutoAcceptCall::Audio))) (!video && Settings::getInstance().getAutoAcceptCall(f->getPublicKey()).testFlag(Settings::AutoAcceptCall::Audio)))
{ {
uint32_t friendId = f->getFriendID(); uint32_t friendId = f->getFriendID();
qDebug() << "automatic call answer"; qDebug() << "automatic call answer";
@ -587,7 +587,7 @@ void ChatForm::onFriendMessageReceived(quint32 friendId, const QString& message,
return; return;
QDateTime timestamp = QDateTime::currentDateTime(); QDateTime timestamp = QDateTime::currentDateTime();
addMessage(f->getToxId(), message, isAction, timestamp, true); addMessage(f->getPublicKey(), message, isAction, timestamp, true);
} }
void ChatForm::onStatusMessage(const QString& message) void ChatForm::onStatusMessage(const QString& message)
@ -716,10 +716,10 @@ void ChatForm::loadHistory(QDateTime since, bool processUndelivered)
} }
} }
auto msgs = Nexus::getProfile()->getHistory()->getChatHistory(f->getToxId().getPublicKeyString(), since, now); auto msgs = Nexus::getProfile()->getHistory()->getChatHistory(f->getPublicKey().toString(), since, now);
ToxId storedPrevId = previousId; ToxPk storedPrevId = previousId;
ToxId prevId; ToxPk prevId;
QList<ChatLine::Ptr> historyMessages; QList<ChatLine::Ptr> historyMessages;
@ -742,9 +742,9 @@ void ChatForm::loadHistory(QDateTime since, bool processUndelivered)
// Show each messages // Show each messages
const Core* core = Core::getInstance(); const Core* core = Core::getInstance();
ToxId authorId(it.sender); ToxPk authorPk(ToxId(it.sender).getPublicKey());
QString authorStr; QString authorStr;
bool isSelf = authorId == core->getSelfId(); bool isSelf = authorPk == core->getSelfId().getPublicKey();
if (!it.dispName.isEmpty()) if (!it.dispName.isEmpty())
{ {
@ -756,7 +756,7 @@ void ChatForm::loadHistory(QDateTime since, bool processUndelivered)
} }
else else
{ {
authorStr = resolveToxId(authorId); authorStr = resolveToxId(authorPk);
} }
bool isAction = it.message.startsWith(ACTION_PREFIX, Qt::CaseInsensitive); bool isAction = it.message.startsWith(ACTION_PREFIX, Qt::CaseInsensitive);
@ -769,10 +769,10 @@ void ChatForm::loadHistory(QDateTime since, bool processUndelivered)
isSelf, isSelf,
needSending ? QDateTime() : msgDateTime); needSending ? QDateTime() : msgDateTime);
if (!isAction && (prevId == authorId) && (prevMsgDateTime.secsTo(msgDateTime) < getChatLog()->repNameAfter) ) if (!isAction && (prevId == authorPk) && (prevMsgDateTime.secsTo(msgDateTime) < getChatLog()->repNameAfter) )
msg->hideSender(); msg->hideSender();
prevId = authorId; prevId = authorPk;
prevMsgDateTime = msgDateTime; prevMsgDateTime = msgDateTime;
if (needSending) if (needSending)
@ -1061,8 +1061,8 @@ void ChatForm::SendMessageStr(QString msg)
if (profile->isHistoryEnabled()) if (profile->isHistoryEnabled())
{ {
auto* offMsgEngine = getOfflineMsgEngine(); auto* offMsgEngine = getOfflineMsgEngine();
profile->getHistory()->addNewMessage(f->getToxId().getPublicKeyString(), qt_msg_hist, profile->getHistory()->addNewMessage(f->getPublicKey().toString(), qt_msg_hist,
Core::getInstance()->getSelfId().getPublicKeyString(), timestamp, status, Core::getInstance()->getUsername(), Core::getInstance()->getSelfId().toString(), timestamp, status, Core::getInstance()->getUsername(),
[offMsgEngine,rec,ma](int64_t id) [offMsgEngine,rec,ma](int64_t id)
{ {
offMsgEngine->registerReceipt(rec, id, ma); offMsgEngine->registerReceipt(rec, id, ma);

View File

@ -337,11 +337,11 @@ void GenericChatForm::onChatContextMenuRequested(QPoint pos)
menu.exec(pos); menu.exec(pos);
} }
ChatMessage::Ptr GenericChatForm::addMessage(const ToxId& author, const QString &message, bool isAction, ChatMessage::Ptr GenericChatForm::addMessage(const ToxPk& author, const QString &message, bool isAction,
const QDateTime &datetime, bool isSent) const QDateTime &datetime, bool isSent)
{ {
const Core* core = Core::getInstance(); const Core* core = Core::getInstance();
bool authorIsActiveProfile = author == core->getSelfId(); bool authorIsActiveProfile = author == core->getSelfId().getPublicKey();
QString authorStr = authorIsActiveProfile ? core->getUsername() : resolveToxId(author); QString authorStr = authorIsActiveProfile ? core->getUsername() : resolveToxId(author);
@ -356,7 +356,7 @@ ChatMessage::Ptr GenericChatForm::addMessage(const ToxId& author, const QString
if (isAction) if (isAction)
{ {
msg = ChatMessage::createChatMessage(authorStr, message, ChatMessage::ACTION, authorIsActiveProfile); msg = ChatMessage::createChatMessage(authorStr, message, ChatMessage::ACTION, authorIsActiveProfile);
previousId.clear(); previousId = ToxPk();
} }
else else
{ {
@ -378,13 +378,13 @@ ChatMessage::Ptr GenericChatForm::addMessage(const ToxId& author, const QString
ChatMessage::Ptr GenericChatForm::addSelfMessage(const QString &message, bool isAction, const QDateTime &datetime, bool isSent) ChatMessage::Ptr GenericChatForm::addSelfMessage(const QString &message, bool isAction, const QDateTime &datetime, bool isSent)
{ {
return addMessage(Core::getInstance()->getSelfId(), message, isAction, datetime, isSent); return addMessage(Core::getInstance()->getSelfId().getPublicKey(), message, isAction, datetime, isSent);
} }
void GenericChatForm::addAlertMessage(const ToxId &author, QString message, QDateTime datetime) void GenericChatForm::addAlertMessage(const ToxPk &author, QString message, QDateTime datetime)
{ {
QString authorStr = resolveToxId(author); QString authorStr = resolveToxId(author);
bool isSelf = author == Core::getInstance()->getSelfId(); bool isSelf = author == Core::getInstance()->getSelfId().getPublicKey();
ChatMessage::Ptr msg = ChatMessage::createChatMessage(authorStr, message, ChatMessage::ALERT, isSelf, datetime); ChatMessage::Ptr msg = ChatMessage::createChatMessage(authorStr, message, ChatMessage::ALERT, isSelf, datetime);
insertChatMessage(msg); insertChatMessage(msg);
@ -468,7 +468,7 @@ void GenericChatForm::focusInput()
void GenericChatForm::addSystemInfoMessage(const QString &message, ChatMessage::SystemMessageType type, const QDateTime &datetime) void GenericChatForm::addSystemInfoMessage(const QString &message, ChatMessage::SystemMessageType type, const QDateTime &datetime)
{ {
previousId.clear(); previousId = ToxPk();
insertChatMessage(ChatMessage::createChatInfoMessage(message, type, datetime)); insertChatMessage(ChatMessage::createChatInfoMessage(message, type, datetime));
} }
@ -480,7 +480,7 @@ void GenericChatForm::clearChatArea()
void GenericChatForm::clearChatArea(bool notinform) void GenericChatForm::clearChatArea(bool notinform)
{ {
chatWidget->clear(); chatWidget->clear();
previousId = ToxId(); previousId = ToxPk();
if (!notinform) if (!notinform)
addSystemInfoMessage(tr("Cleared"), ChatMessage::INFO, QDateTime::currentDateTime()); addSystemInfoMessage(tr("Cleared"), ChatMessage::INFO, QDateTime::currentDateTime());
@ -496,7 +496,7 @@ void GenericChatForm::onSelectAllClicked()
chatWidget->selectAll(); chatWidget->selectAll();
} }
QString GenericChatForm::resolveToxId(const ToxId &id) QString GenericChatForm::resolveToxId(const ToxPk &id)
{ {
Friend *f = FriendList::findFriend(id); Friend *f = FriendList::findFriend(id);
if (f) if (f)

View File

@ -62,11 +62,11 @@ public:
virtual void show() final{} virtual void show() final{}
virtual void show(ContentLayout* contentLayout); virtual void show(ContentLayout* contentLayout);
ChatMessage::Ptr addMessage(const ToxId& author, const QString &message, bool isAction, const QDateTime &datetime, bool isSent); ChatMessage::Ptr addMessage(const ToxPk& author, const QString &message, bool isAction, const QDateTime &datetime, bool isSent);
ChatMessage::Ptr addSelfMessage(const QString &message, bool isAction, const QDateTime &datetime, bool isSent); ChatMessage::Ptr addSelfMessage(const QString &message, bool isAction, const QDateTime &datetime, bool isSent);
void addSystemInfoMessage(const QString &message, ChatMessage::SystemMessageType type, const QDateTime &datetime); void addSystemInfoMessage(const QString &message, ChatMessage::SystemMessageType type, const QDateTime &datetime);
void addAlertMessage(const ToxId& author, QString message, QDateTime datetime); void addAlertMessage(const ToxPk& author, QString message, QDateTime datetime);
bool isEmpty(); bool isEmpty();
ChatLog* getChatLog() const; ChatLog* getChatLog() const;
@ -104,7 +104,7 @@ protected:
void showNetcam(); void showNetcam();
void hideNetcam(); void hideNetcam();
virtual GenericNetCamView* createNetcam() = 0; virtual GenericNetCamView* createNetcam() = 0;
QString resolveToxId(const ToxId &id); QString resolveToxId(const ToxPk &id);
virtual void insertChatMessage(ChatMessage::Ptr msg); virtual void insertChatMessage(ChatMessage::Ptr msg);
void adjustFileMenuPosition(); void adjustFileMenuPosition();
virtual void hideEvent(QHideEvent* event) override; virtual void hideEvent(QHideEvent* event) override;
@ -115,7 +115,7 @@ protected:
protected: protected:
QAction* saveChatAction, *clearAction, *quoteAction, *copyLinkAction; QAction* saveChatAction, *clearAction, *quoteAction, *copyLinkAction;
ToxId previousId; ToxPk previousId;
QDateTime prevMsgDateTime; QDateTime prevMsgDateTime;
Widget *parent; Widget *parent;
QMenu menu; QMenu menu;

View File

@ -283,7 +283,7 @@ void GroupChatForm::peerAudioPlaying(int peer)
void GroupChatForm::dragEnterEvent(QDragEnterEvent *ev) void GroupChatForm::dragEnterEvent(QDragEnterEvent *ev)
{ {
ToxId toxId = ToxId(ev->mimeData()->text()); ToxId toxId = ToxId(ev->mimeData()->text());
Friend *frnd = FriendList::findFriend(toxId); Friend *frnd = FriendList::findFriend(toxId.getPublicKey());
if (frnd) if (frnd)
ev->acceptProposedAction(); ev->acceptProposedAction();
} }
@ -291,7 +291,7 @@ void GroupChatForm::dragEnterEvent(QDragEnterEvent *ev)
void GroupChatForm::dropEvent(QDropEvent *ev) void GroupChatForm::dropEvent(QDropEvent *ev)
{ {
ToxId toxId = ToxId(ev->mimeData()->text()); ToxId toxId = ToxId(ev->mimeData()->text());
Friend *frnd = FriendList::findFriend(toxId); Friend *frnd = FriendList::findFriend(toxId.getPublicKey());
if (!frnd) if (!frnd)
return; return;

View File

@ -248,14 +248,14 @@ void ProfileForm::onSelfAvatarLoaded(const QPixmap& pic)
profilePicture->setPixmap(pic); profilePicture->setPixmap(pic);
} }
void ProfileForm::setToxId(const QString& id) void ProfileForm::setToxId(const ToxId& id)
{ {
toxId->setText(id); toxId->setText(id.toString());
toxId->setCursorPosition(0); toxId->setCursorPosition(0);
delete qr; delete qr;
qr = new QRWidget(); qr = new QRWidget();
qr->setQRData("tox:"+id); qr->setQRData("tox:"+id.toString());
bodyUI->qrCode->setPixmap(QPixmap::fromImage(qr->getImage()->scaledToWidth(150))); bodyUI->qrCode->setPixmap(QPixmap::fromImage(qr->getImage()->scaledToWidth(150)));
} }

View File

@ -71,7 +71,7 @@ public slots:
private slots: private slots:
void setPasswordButtonsText(); void setPasswordButtonsText();
void setToxId(const QString& id); void setToxId(const ToxId &id);
void copyIdClicked(); void copyIdClicked();
void onUserNameEdited(); void onUserNameEdited();
void onStatusMessageEdited(); void onStatusMessageEdited();

View File

@ -111,7 +111,7 @@ Time getTime(const QDate& date)
QDate getDateFriend(Friend* contact) QDate getDateFriend(Friend* contact)
{ {
return Settings::getInstance().getFriendActivity(contact->getToxId()); return Settings::getInstance().getFriendActivity(contact->getPublicKey());
} }
qint64 timeUntilTomorrow() qint64 timeUntilTomorrow()
@ -202,7 +202,7 @@ void FriendListWidget::setMode(Mode mode)
QList<Friend*> friendList = FriendList::getAllFriends(); QList<Friend*> friendList = FriendList::getAllFriends();
for (Friend* contact : friendList) for (Friend* contact : friendList)
{ {
int circleId = Settings::getInstance().getFriendCircleID(contact->getToxId()); int circleId = Settings::getInstance().getFriendCircleID(contact->getPublicKey());
addFriendWidget(contact->getFriendWidget(), contact->getStatus(), circleId); addFriendWidget(contact->getFriendWidget(), contact->getStatus(), circleId);
} }
@ -362,7 +362,7 @@ void FriendListWidget::removeFriendWidget(FriendWidget* w)
} }
else else
{ {
int id = Settings::getInstance().getFriendCircleID(contact->getToxId()); int id = Settings::getInstance().getFriendCircleID(contact->getPublicKey());
CircleWidget* circleWidget = CircleWidget::getFromID(id); CircleWidget* circleWidget = CircleWidget::getFromID(id);
if (circleWidget != nullptr) if (circleWidget != nullptr)
{ {
@ -384,7 +384,7 @@ void FriendListWidget::addCircleWidget(FriendWidget* friendWidget)
{ {
if (friendWidget != nullptr) if (friendWidget != nullptr)
{ {
CircleWidget* circleOriginal = CircleWidget::getFromID(Settings::getInstance().getFriendCircleID(FriendList::findFriend(friendWidget->friendId)->getToxId())); CircleWidget* circleOriginal = CircleWidget::getFromID(Settings::getInstance().getFriendCircleID(FriendList::findFriend(friendWidget->friendId)->getPublicKey()));
circleWidget->addFriendWidget(friendWidget, FriendList::findFriend(friendWidget->friendId)->getStatus()); circleWidget->addFriendWidget(friendWidget, FriendList::findFriend(friendWidget->friendId)->getStatus());
circleWidget->setExpanded(true); circleWidget->setExpanded(true);
@ -522,7 +522,7 @@ void FriendListWidget::cycleContacts(GenericChatroomWidget* activeChatroomWidget
if (friendWidget != nullptr) if (friendWidget != nullptr)
{ {
circleWidget = CircleWidget::getFromID(Settings::getInstance().getFriendCircleID(FriendList::findFriend(friendWidget->friendId)->getToxId())); circleWidget = CircleWidget::getFromID(Settings::getInstance().getFriendCircleID(FriendList::findFriend(friendWidget->friendId)->getPublicKey()));
if (circleWidget != nullptr) if (circleWidget != nullptr)
{ {
if (circleWidget->cycleContacts(friendWidget, forward)) if (circleWidget->cycleContacts(friendWidget, forward))
@ -608,7 +608,7 @@ void FriendListWidget::cycleContacts(GenericChatroomWidget* activeChatroomWidget
void FriendListWidget::dragEnterEvent(QDragEnterEvent* event) void FriendListWidget::dragEnterEvent(QDragEnterEvent* event)
{ {
ToxId toxId(event->mimeData()->text()); ToxId toxId(event->mimeData()->text());
Friend *frnd = FriendList::findFriend(toxId); Friend *frnd = FriendList::findFriend(toxId.getPublicKey());
if (frnd) if (frnd)
event->acceptProposedAction(); event->acceptProposedAction();
} }
@ -623,12 +623,12 @@ void FriendListWidget::dropEvent(QDropEvent* event)
// Check, that the user has a friend with the same ToxId // Check, that the user has a friend with the same ToxId
ToxId toxId(event->mimeData()->text()); ToxId toxId(event->mimeData()->text());
Friend *f = FriendList::findFriend(toxId); Friend *f = FriendList::findFriend(toxId.getPublicKey());
if (!f) if (!f)
return; return;
// Save CircleWidget before changing the Id // Save CircleWidget before changing the Id
int circleId = Settings::getInstance().getFriendCircleID(f->getToxId()); int circleId = Settings::getInstance().getFriendCircleID(f->getPublicKey());
CircleWidget* circleWidget = CircleWidget::getFromID(circleId); CircleWidget* circleWidget = CircleWidget::getFromID(circleId);
moveWidget(widget, f->getStatus(), true); moveWidget(widget, f->getStatus(), true);
@ -652,13 +652,13 @@ void FriendListWidget::moveWidget(FriendWidget* w, Status s, bool add)
{ {
if (mode == Name) if (mode == Name)
{ {
int circleId = Settings::getInstance().getFriendCircleID(FriendList::findFriend(w->friendId)->getToxId()); int circleId = Settings::getInstance().getFriendCircleID(FriendList::findFriend(w->friendId)->getPublicKey());
CircleWidget* circleWidget = CircleWidget::getFromID(circleId); CircleWidget* circleWidget = CircleWidget::getFromID(circleId);
if (circleWidget == nullptr || add) if (circleWidget == nullptr || add)
{ {
if (circleId != -1) if (circleId != -1)
Settings::getInstance().setFriendCircleID(FriendList::findFriend(w->friendId)->getToxId(), -1); Settings::getInstance().setFriendCircleID(FriendList::findFriend(w->friendId)->getPublicKey(), -1);
listLayout->addFriendWidget(w, s); listLayout->addFriendWidget(w, s);
return; return;

View File

@ -70,7 +70,7 @@ void FriendWidget::contextMenuEvent(QContextMenuEvent * event)
installEventFilter(this); // Disable leave event. installEventFilter(this); // Disable leave event.
QPoint pos = event->globalPos(); QPoint pos = event->globalPos();
ToxId id = FriendList::findFriend(friendId)->getToxId(); ToxPk id = FriendList::findFriend(friendId)->getPublicKey();
QString dir = Settings::getInstance().getAutoAcceptDir(id); QString dir = Settings::getInstance().getAutoAcceptDir(id);
QMenu menu; QMenu menu;
QAction* openChatWindow = nullptr; QAction* openChatWindow = nullptr;
@ -103,7 +103,7 @@ void FriendWidget::contextMenuEvent(QContextMenuEvent * event)
groupActions[groupAction] = group; groupActions[groupAction] = group;
} }
int circleId = Settings::getInstance().getFriendCircleID(FriendList::findFriend(friendId)->getToxId()); int circleId = Settings::getInstance().getFriendCircleID(FriendList::findFriend(friendId)->getPublicKey());
CircleWidget *circleWidget = CircleWidget::getFromID(circleId); CircleWidget *circleWidget = CircleWidget::getFromID(circleId);
QMenu* circleMenu = nullptr; QMenu* circleMenu = nullptr;
@ -314,7 +314,7 @@ void FriendWidget::updateStatusLight()
if (f->getEventFlag()) if (f->getEventFlag())
{ {
CircleWidget* circleWidget = CircleWidget::getFromID(Settings::getInstance().getFriendCircleID(FriendList::findFriend(friendId)->getToxId())); CircleWidget* circleWidget = CircleWidget::getFromID(Settings::getInstance().getFriendCircleID(FriendList::findFriend(friendId)->getPublicKey()));
if (circleWidget != nullptr) if (circleWidget != nullptr)
circleWidget->setExpanded(true); circleWidget->setExpanded(true);
@ -353,7 +353,7 @@ Friend* FriendWidget::getFriend() const
void FriendWidget::search(const QString &searchString, bool hide) void FriendWidget::search(const QString &searchString, bool hide)
{ {
searchName(searchString, hide); searchName(searchString, hide);
CircleWidget* circleWidget = CircleWidget::getFromID(Settings::getInstance().getFriendCircleID(FriendList::findFriend(friendId)->getToxId())); CircleWidget* circleWidget = CircleWidget::getFromID(Settings::getInstance().getFriendCircleID(FriendList::findFriend(friendId)->getPublicKey()));
if (circleWidget != nullptr) if (circleWidget != nullptr)
circleWidget->search(searchString); circleWidget->search(searchString);
} }
@ -414,7 +414,7 @@ void FriendWidget::mouseMoveEvent(QMouseEvent *ev)
if ((dragStartPos - ev->pos()).manhattanLength() > QApplication::startDragDistance()) if ((dragStartPos - ev->pos()).manhattanLength() > QApplication::startDragDistance())
{ {
QMimeData* mdata = new QMimeData; QMimeData* mdata = new QMimeData;
mdata->setText(getFriend()->getToxId().toString()); mdata->setText(getFriend()->getPublicKey().toString());
QDrag* drag = new QDrag(this); QDrag* drag = new QDrag(this);
drag->setMimeData(mdata); drag->setMimeData(mdata);
@ -428,6 +428,6 @@ void FriendWidget::setAlias(const QString& _alias)
QString alias = _alias.left(128); // same as TOX_MAX_NAME_LENGTH QString alias = _alias.left(128); // same as TOX_MAX_NAME_LENGTH
Friend* f = FriendList::findFriend(friendId); Friend* f = FriendList::findFriend(friendId);
f->setAlias(alias); f->setAlias(alias);
Settings::getInstance().setFriendAlias(f->getToxId(), alias); Settings::getInstance().setFriendAlias(f->getPublicKey(), alias);
Settings::getInstance().savePersonal(); Settings::getInstance().savePersonal();
} }

View File

@ -236,7 +236,7 @@ void GroupWidget::resetEventFlags()
void GroupWidget::dragEnterEvent(QDragEnterEvent *ev) void GroupWidget::dragEnterEvent(QDragEnterEvent *ev)
{ {
ToxId toxId = ToxId(ev->mimeData()->text()); ToxId toxId = ToxId(ev->mimeData()->text());
Friend *frnd = FriendList::findFriend(toxId); Friend *frnd = FriendList::findFriend(toxId.getPublicKey());
if (frnd) if (frnd)
ev->acceptProposedAction(); ev->acceptProposedAction();
@ -253,7 +253,7 @@ void GroupWidget::dragLeaveEvent(QDragLeaveEvent *)
void GroupWidget::dropEvent(QDropEvent *ev) void GroupWidget::dropEvent(QDropEvent *ev)
{ {
ToxId toxId = ToxId(ev->mimeData()->text()); ToxId toxId = ToxId(ev->mimeData()->text());
Friend *frnd = FriendList::findFriend(toxId); Friend *frnd = FriendList::findFriend(toxId.getPublicKey());
if (!frnd) if (!frnd)
return; return;

View File

@ -993,10 +993,9 @@ void Widget::reloadHistory()
} }
} }
void Widget::addFriend(int friendId, const QString &userId) void Widget::addFriend(int friendId, const ToxPk& friendPk)
{ {
ToxId userToxId = ToxId(userId); Friend* newfriend = FriendList::addFriend(friendId, friendPk);
Friend* newfriend = FriendList::addFriend(friendId, userToxId);
QString name = newfriend->getDisplayedName(); QString name = newfriend->getDisplayedName();
FriendWidget* widget = new FriendWidget(friendId, name); FriendWidget* widget = new FriendWidget(friendId, name);
@ -1009,14 +1008,14 @@ void Widget::addFriend(int friendId, const QString &userId)
const Settings& s = Settings::getInstance(); const Settings& s = Settings::getInstance();
QDate activityDate = s.getFriendActivity(userToxId); QDate activityDate = s.getFriendActivity(friendPk);
QDate chatDate = friendForm->getLatestDate(); QDate chatDate = friendForm->getLatestDate();
if (chatDate > activityDate && chatDate.isValid()) if (chatDate > activityDate && chatDate.isValid())
{ {
Settings::getInstance().setFriendActivity(userToxId, chatDate); Settings::getInstance().setFriendActivity(friendPk, chatDate);
} }
contactListWidget->addFriendWidget(widget, Status::Offline, s.getFriendCircleID(userToxId)); contactListWidget->addFriendWidget(widget, Status::Offline, s.getFriendCircleID(friendPk));
connect(newfriend, &Friend::displayedNameChanged, this, &Widget::onFriendDisplayChanged); connect(newfriend, &Friend::displayedNameChanged, this, &Widget::onFriendDisplayChanged);
connect(widget, &FriendWidget::chatroomWidgetClicked, this, &Widget::onChatroomWidgetClicked); connect(widget, &FriendWidget::chatroomWidgetClicked, this, &Widget::onChatroomWidgetClicked);
@ -1025,7 +1024,7 @@ void Widget::addFriend(int friendId, const QString &userId)
connect(widget, SIGNAL(removeFriend(int)), this, SLOT(removeFriend(int))); connect(widget, SIGNAL(removeFriend(int)), this, SLOT(removeFriend(int)));
// Try to get the avatar from the cache // Try to get the avatar from the cache
QPixmap avatar = Nexus::getProfile()->loadAvatar(userId); QPixmap avatar = Nexus::getProfile()->loadAvatar(friendPk.toString());
if (!avatar.isNull()) if (!avatar.isNull())
{ {
friendForm->onAvatarChange(friendId, avatar); friendForm->onAvatarChange(friendId, avatar);
@ -1036,7 +1035,7 @@ void Widget::addFriend(int friendId, const QString &userId)
widget->search(ui->searchContactText->text(), filterOffline(filter)); widget->search(ui->searchContactText->text(), filterOffline(filter));
} }
void Widget::addFriendFailed(const QString&, const QString& errorInfo) void Widget::addFriendFailed(const ToxPk&, const QString& errorInfo)
{ {
QString info = QString(tr("Couldn't request friendship")); QString info = QString(tr("Couldn't request friendship"));
if (!errorInfo.isEmpty()) if (!errorInfo.isEmpty())
@ -1226,7 +1225,7 @@ void Widget::onFriendMessageReceived(int friendId, const QString& message, bool
Profile* profile = Nexus::getProfile(); Profile* profile = Nexus::getProfile();
if (profile->isHistoryEnabled()) if (profile->isHistoryEnabled())
{ {
QString publicKey = f->getToxId().getPublicKeyString(); QString publicKey = f->getPublicKey().toString();
QString name = f->getDisplayedName(); QString name = f->getDisplayedName();
QString text = message; QString text = message;
if (isAction) if (isAction)
@ -1278,7 +1277,7 @@ void Widget::addFriendDialog(Friend *frnd, ContentDialog *dialog)
connect(core, &Core::friendAvatarRemoved, connect(core, &Core::friendAvatarRemoved,
friendWidget, &FriendWidget::onAvatarRemoved); friendWidget, &FriendWidget::onAvatarRemoved);
QPixmap avatar = Nexus::getProfile()->loadAvatar(frnd->getToxId().toString()); QPixmap avatar = Nexus::getProfile()->loadAvatar(frnd->getPublicKey().toString());
if (!avatar.isNull()) if (!avatar.isNull())
{ {
friendWidget->onAvatarChange(frnd->getFriendID(), avatar); friendWidget->onAvatarChange(frnd->getFriendID(), avatar);
@ -1469,9 +1468,9 @@ bool Widget::newMessageAlert(QWidget* currentWindow, bool isActive, bool sound,
return true; return true;
} }
void Widget::onFriendRequestReceived(const QString& userId, const QString& message) void Widget::onFriendRequestReceived(const ToxPk& friendPk, const QString& message)
{ {
if (addFriendForm->addFriendRequest(userId, message)) if (addFriendForm->addFriendRequest(friendPk.toString(), message))
{ {
friendRequestsUpdate(); friendRequestsUpdate();
newMessageAlert(window(), isActiveWindow(), true, true); newMessageAlert(window(), isActiveWindow(), true, true);
@ -1480,12 +1479,12 @@ void Widget::onFriendRequestReceived(const QString& userId, const QString& messa
void Widget::updateFriendActivity(Friend *frnd) void Widget::updateFriendActivity(Friend *frnd)
{ {
QDate date = Settings::getInstance().getFriendActivity(frnd->getToxId()); QDate date = Settings::getInstance().getFriendActivity(frnd->getPublicKey());
if (date != QDate::currentDate()) if (date != QDate::currentDate())
{ {
// Update old activity before after new one. Store old date first. // Update old activity before after new one. Store old date first.
QDate oldDate = Settings::getInstance().getFriendActivity(frnd->getToxId()); QDate oldDate = Settings::getInstance().getFriendActivity(frnd->getPublicKey());
Settings::getInstance().setFriendActivity(frnd->getToxId(), QDate::currentDate()); Settings::getInstance().setFriendActivity(frnd->getPublicKey(), QDate::currentDate());
contactListWidget->moveWidget(friendWidgets[frnd->getFriendID()], frnd->getStatus()); contactListWidget->moveWidget(friendWidgets[frnd->getFriendID()], frnd->getStatus());
contactListWidget->updateActivityDate(oldDate); contactListWidget->updateActivityDate(oldDate);
} }
@ -1505,7 +1504,7 @@ void Widget::removeFriend(Friend* f, bool fake)
if (ask.removeHistory()) if (ask.removeHistory())
{ {
Nexus::getProfile()->getHistory()->removeFriendHistory(f->getToxId().getPublicKeyString()); Nexus::getProfile()->getHistory()->removeFriendHistory(f->getPublicKey().toString());
} }
} }
@ -1669,7 +1668,7 @@ void Widget::copyFriendIdToClipboard(int friendId)
if (f != nullptr) if (f != nullptr)
{ {
QClipboard *clipboard = QApplication::clipboard(); QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(Nexus::getCore()->getFriendAddress(f->getFriendID()), QClipboard::Clipboard); clipboard->setText(Nexus::getCore()->getFriendPublicKey(f->getFriendID()).toString(), QClipboard::Clipboard);
} }
} }
@ -1710,8 +1709,8 @@ void Widget::onGroupMessageReceived(int groupnumber, int peernumber, const QStri
} }
const Core* core = Core::getInstance(); const Core* core = Core::getInstance();
ToxId author = core->getGroupPeerToxId(groupnumber, peernumber); ToxPk author = core->getGroupPeerPk(groupnumber, peernumber);
bool isSelf = author == core->getSelfId(); bool isSelf = author == core->getSelfId().getPublicKey();
bool targeted = !isSelf && (message.contains(nameMention) || message.contains(sanitizedNameMention)); bool targeted = !isSelf && (message.contains(nameMention) || message.contains(sanitizedNameMention));
if (targeted && !isAction) if (targeted && !isAction)

View File

@ -27,7 +27,9 @@
#include <QFileInfo> #include <QFileInfo>
#include "genericchatitemwidget.h" #include "genericchatitemwidget.h"
#include "src/core/corestructs.h" #include "src/core/corestructs.h"
#include "src/core/toxid.h"
#define PIXELS_TO_ACT 7 #define PIXELS_TO_ACT 7
@ -121,18 +123,18 @@ public slots:
void onStatusSet(Status status); void onStatusSet(Status status);
void onFailedToStartCore(); void onFailedToStartCore();
void onBadProxyCore(); void onBadProxyCore();
void onSelfAvatarLoaded(const QPixmap &pic); void onSelfAvatarLoaded(const QPixmap& pic);
void setUsername(const QString& username); void setUsername(const QString& username);
void setStatusMessage(const QString &statusMessage); void setStatusMessage(const QString &statusMessage);
void addFriend(int friendId, const QString& userId); void addFriend(int friendId, const ToxPk& friendPk);
void addFriendFailed(const QString& userId, const QString& errorInfo = QString()); void addFriendFailed(const ToxPk& userId, const QString& errorInfo = QString());
void onFriendshipChanged(int friendId); void onFriendshipChanged(int friendId);
void onFriendStatusChanged(int friendId, Status status); void onFriendStatusChanged(int friendId, Status status);
void onFriendStatusMessageChanged(int friendId, const QString& message); void onFriendStatusMessageChanged(int friendId, const QString& message);
void onFriendUsernameChanged(int friendId, const QString& username); void onFriendUsernameChanged(int friendId, const QString& username);
void onFriendDisplayChanged(FriendWidget* friendWidget, Status s); void onFriendDisplayChanged(FriendWidget* friendWidget, Status s);
void onFriendMessageReceived(int friendId, const QString& message, bool isAction); void onFriendMessageReceived(int friendId, const QString& message, bool isAction);
void onFriendRequestReceived(const QString& userId, const QString& message); void onFriendRequestReceived(const ToxPk& friendPk, const QString& message);
void updateFriendActivity(Friend* frnd); void updateFriendActivity(Friend* frnd);
void onMessageSendResult(uint32_t friendId, const QString& message, int messageId); void onMessageSendResult(uint32_t friendId, const QString& message, int messageId);
void onReceiptRecieved(int friendId, int receipt); void onReceiptRecieved(int friendId, int receipt);
@ -151,8 +153,8 @@ public slots:
void onGroupDialogShown(Group* g); void onGroupDialogShown(Group* g);
signals: signals:
void friendRequestAccepted(const QString& userId); void friendRequestAccepted(const ToxPk& friendPk);
void friendRequested(const QString& friendAddress, const QString& message); void friendRequested(const ToxId& friendAddress, const QString& message);
void statusSet(Status status); void statusSet(Status status);
void statusSelected(Status status); void statusSelected(Status status);
void usernameChanged(const QString& username); void usernameChanged(const QString& username);
@ -221,7 +223,7 @@ private:
bool newMessageAlert(QWidget* currentWindow, bool isActive, bool sound = true, bool notify = true); bool newMessageAlert(QWidget* currentWindow, bool isActive, bool sound = true, bool notify = true);
void setActiveToolMenuButton(ActiveToolMenuButton newActiveButton); void setActiveToolMenuButton(ActiveToolMenuButton newActiveButton);
void hideMainForms(GenericChatroomWidget* chatroomWidget); void hideMainForms(GenericChatroomWidget* chatroomWidget);
Group *createGroup(int groupId); Group* createGroup(int groupId);
void removeFriend(Friend* f, bool fake = false); void removeFriend(Friend* f, bool fake = false);
void removeGroup(Group* g, bool fake = false); void removeGroup(Group* g, bool fake = false);
void saveWindowGeometry(); void saveWindowGeometry();