void PopupDistantChatDialog::init(const RsGxsId &gxs_id,const QString & title) { _pid = gxs_id ; PopupChatDialog::init(ChatId(gxs_id), title) ; RsGxsId own_gxs_id ; uint32_t status ; // do not use setOwnId, because we don't want the user to change the GXS avatar from the chat window // it will not be transmitted. if(rsMsgs->getDistantChatStatus(gxs_id,status,&own_gxs_id)) ui.ownAvatarWidget->setId(ChatId(own_gxs_id)); }
/** Constructor */ ChatMsgItem::ChatMsgItem(FeedHolder *parent, uint32_t feedId, const RsPeerId &peerId, const std::string &message) : FeedItem(NULL), mParent(parent), mFeedId(feedId), mPeerId(peerId) { /* Invoke the Qt Designer generated object setup routine */ setupUi(this); messageFrame->setVisible(false); sendButton->hide(); cancelButton->hide(); sendButton->setEnabled(false); /* general ones */ connect( clearButton, SIGNAL( clicked( void ) ), this, SLOT( removeItem ( void ) ) ); /* specific ones */ connect( chatButton, SIGNAL( clicked( void ) ), this, SLOT( openChat ( void ) ) ); connect( msgButton, SIGNAL( clicked( void ) ), this, SLOT( sendMsg ( void ) ) ); connect( quickmsgButton, SIGNAL( clicked( ) ), this, SLOT( togglequickmessage() ) ); connect( cancelButton, SIGNAL( clicked( ) ), this, SLOT( togglequickmessage() ) ); connect( sendButton, SIGNAL( clicked( ) ), this, SLOT( sendMessage() ) ); connect(NotifyQt::getInstance(), SIGNAL(peerHasNewAvatar(const QString&)), this, SLOT(updateAvatar(const QString&))); avatar->setId(ChatId(mPeerId)); updateItemStatic(); updateItem(); insertChat(message); }
void AvatarWidget::setOwnId() { mFlag.isOwnId = true; setToolTip(tr("Click to change your avatar")); setId(ChatId(rsPeers->getOwnId())); }
ChannelMessage::ChannelMessage(MessagePacket packet) : Message(packet->id(), QByteArray(), LS("channel"), LS("addChannelMessage")) , m_packet(packet) { setDate(m_packet->date()); setAuthor(m_packet->sender()); m_tab = detectTab(m_packet->sender(), m_packet->dest()); if (!m_packet->internalId().isEmpty()) m_data.insert(kInternalId, ChatId(m_packet->internalId()).toString()); m_data.insert(kCommand, packet->command()); m_data.insert(kDirection, m_packet->sender() == ChatClient::id() ? kOutgoing : kIncoming); /// Если это собственное сообщение, то для него при необходимости устанавливается /// статус "offline" или "rejected". const int status = packet->status(); if (isOffline(status)) m_data.insert(kStatus, kOffline); else if (status != Notice::OK && status != Notice::Found && status < Notice::UserStatus) m_data.insert(kStatus, kRejected); if (status == MessageNotice::Removed) { m_data.insert(kStatus, kRemoved); m_data.insert(kText, QString(LS("<span class='message-removed' data-tr='message-removed'>%1</span> <i class='message-trash'></i>")).arg(WebBridge::i()->translate("message-removed"))); } else m_data.insert(kText, TokenFilter::filter(LS("channel"), packet->text(), 0, packet->id())); if (!packet->oid.isNull()) { m_data.insert(kOID, QString(ChatId::toBase32(packet->oid.byteArray()))); m_data.insert(kMDate, packet->mdate); } }
/*! * Определение доступных прав пользователя, для определения какие действия над сообщением возможны. */ int HistoryChatView::permissions(const MessageRecord &record) const { if (!record.id) return NoPermissions; FeedPtr messages = ChatClient::server()->feed(FEED_NAME_MESSAGES, false); if (!messages) return NoPermissions; const QVariantMap data = messages->data(); const int flags = data.value(MESSAGES_FEED_EDITABLE_KEY, DefaultEditFlags).toInt(); const bool timeout = (qAbs(ChatClient::date() - record.date) / 1000) > data.value(MESSAGES_FEED_TIMEOUT_KEY, DefaultTimeOut).toInt(); if (record.senderId == ChatClient::id() && (flags & SelfEdit) && !timeout) return Remove | Modify; if (ChatId(record.destId).type() != ChatId::ChannelId) return NoPermissions; const int acl = ClientFeeds::match(ChatClient::channels()->get(record.destId), ChatClient::channel()); if ((acl & Acl::SpecialWrite) || (acl & Acl::Edit)) { int out = 0; if (flags & ModeratorRemove) out |= Remove; if (flags & ModeratorEdit) out |= Modify; return out; } return NoPermissions; }
void ChatLobbyDialog::init() { ChatLobbyInfo linfo ; QString title; std::list<ChatLobbyInfo>::const_iterator lobbyIt; if(rsMsgs->getChatLobbyInfo(lobbyId,linfo)) { title = QString::fromUtf8(linfo.lobby_name.c_str()); QString msg = tr("Welcome to lobby %1").arg(RsHtml::plainText(linfo.lobby_name)); _lobby_name = QString::fromUtf8(linfo.lobby_name.c_str()) ; if (!linfo.lobby_topic.empty()) { msg += "\n" + tr("Topic: %1").arg(RsHtml::plainText(linfo.lobby_topic)); } ui.chatWidget->setWelcomeMessage(msg); } ChatDialog::init(ChatId(lobbyId), title); RsGxsId gxs_id; rsMsgs->getIdentityForChatLobby(lobbyId, gxs_id); RsIdentityDetails details ; // This lets the backend some time to load our own identity in cache. // It will only loop for at most 1 second the first time. for(int i=0; i<3; ++i) if(rsIdentity->getIdDetails(gxs_id,details)) break ; else usleep(1000*300) ; ui.chatWidget->setName(QString::fromUtf8(details.mNickname.c_str())); //ui.chatWidget->addToolsAction(ui.actionChangeNickname); ui.chatWidget->setDefaultExtraFileFlags(RS_FILE_REQ_ANONYMOUS_ROUTING); lastUpdateListTime = 0; // add to window ChatLobbyWidget *chatLobbyPage = dynamic_cast<ChatLobbyWidget*>(MainWindow::getPage(MainWindow::ChatLobby)); if (chatLobbyPage) { chatLobbyPage->addChatPage(this) ; } /** List of muted Participants */ mutedParticipants.clear() ; // load settings processSettings(true); }
int ShareMessages::read(MessagePacket packet) { if (packet->command() != LS("image") || Hooks::MessagesImpl::isIgnored(packet)) return 0; if (ChatId(packet->id()).type() != ChatId::MessageId) return 0; m_share->read(packet); return 1; }
/*! * Чтение нового входящего сообщения. */ bool NodeMessages::read(PacketReader *reader) { if (ChatId(reader->sender()).type() != ChatId::UserId) return cleanup(); m_sender = Ch::channel(reader->sender(), ChatId::UserId); if (!m_sender) return cleanup(); MessageNotice packet(m_type, reader); m_packet = &packet; const qint64 date = m_packet->date(); FeedEvent *event = createEvent(); if (event->status != Notice::OK) { reject(event->status); FeedEvents::start(event); return cleanup(); } if (packet.direction() == Notice::Internal) { if (m_packet->command() == LS("ping")) pong(date); Core::i()->route(m_dest); delete event; return cleanup(); } FeedPtr feed = m_dest->feed(FEED_NAME_MESSAGES, true, false); event->diffTo = event->date; event->date = m_packet->date(); if (m_dest->type() == ChatId::UserId && m_dest->status().value() == Status::Offline) { event->status = Notice::ChannelOffline; reject(event->status); NodeMessagesDB::add(packet, event->status); Ch::gc(m_dest); } else { if (feed->get(MESSAGES_FEED_LOGGING_KEY).status == Notice::OK) NodeMessagesDB::add(packet); Core::i()->route(m_dest); } FeedStorage::save(feed, m_packet->date()); FeedEvents::start(event); return cleanup(); }
void ImgurUploader::upload(QNetworkAccessManager *net, UploadItemPtr item, const QVariant &data) { m_net = net; const QVariantMap map = data.toMap(); const QVariantList authData = map.value(LS("a")).toList(); if (authData.size() == 3) { m_clientId = authData.at(0).toString(); m_clientSecret = authData.at(1).toString(); m_queue.enqueue(item); getToken(ChatId(ChatId::MessageId), "refresh_token", authData.value(2).toByteArray(), authData); return; } QNetworkReply *reply = 0; if (item->type() == ImageItem::Type) { ImageItem *i = uploaditem_cast<ImageItem*>(item.data()); QHttpPart image; image.setHeader(QNetworkRequest::ContentTypeHeader, "image/png"); image.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"image\"; filename=\"" + DateTime::toDateTime(item->date()).toString(LS("yyyy-MM-dd_hh-mm-ss")).toLatin1() + ".png\""); image.setBody(i->raw); QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); multiPart->append(image); if (!item->title().isEmpty()) { QHttpPart title; title.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"title\"")); title.setBody(item->title().toUtf8()); multiPart->append(title); } QNetworkRequest request(QUrl(LS("https://api.imgur.com/3/image"))); request.setRawHeader("User-Agent", OsInfo::userAgent()); if (authData.size() == 4) request.setRawHeader("Authorization", "Bearer " + authData.value(3).toByteArray()); else request.setRawHeader("Authorization", "Client-ID " + authData.value(0).toByteArray()); reply = net->post(request, multiPart); multiPart->setParent(reply); } prepare(reply, item->id()); }
void AvatarWidget::setGxsId(const RsGxsId &id) { mId = ChatId(); mGxsId = id; setPixmap(QPixmap()); if (id.isNull()) { setEnabled(false); } refreshAvatarImage(); refreshStatus(); }
/*! * Авторизация пользователя, если пользователь не существует, будет создан новый. */ AuthResult ExternalAuthTask::auth(const QVariantMap &data) { QByteArray id = SimpleID::decode(data.value(LS("id")).toByteArray()); if (SimpleID::typeOf(id) != SimpleID::UserId) return AuthResult(Notice::Forbidden, m_data.id); AuthResult result = AnonymousAuth::isCollision(id, m_data.nick, m_data.id, Storage::value(STORAGE_NICK_OVERRIDE).toBool()); if (result.action == AuthResult::Reject) { if (result.status == Notice::NickAlreadyUse) m_cache[m_data.id + m_data.cookie] = data; return result; } ChatChannel channel = Ch::channel(id, SimpleID::UserId); bool created = false; if (!channel) { channel = ChatChannel(new ServerChannel(id, m_data.nick)); created = true; channel->setAccount(); channel->account()->provider = data.value(LS("provider")).toString(); channel->account()->groups += LS("registered"); channel->account()->setDate(DateTime::utc()); channel->setName(m_data.nick); channel->gender().setRaw(m_data.gender); channel->user()->set(User(data.value(LS("user")).toMap())); } if (channel->status().value() == Status::Offline) { channel->setDate(); channel->status().set(m_data.status); } if (!channel->isValid()) return AuthResult(Notice::BadRequest, m_data.id); Core::add(channel); Ch::userChannel(channel, m_data, m_host, created, m_socket); LOG_INFO("N3010", "Core/ExternalAuth", channel->name() << "@" << m_host + "/" + ChatId(channel->id()).toString() << ", " << m_data.host) m_cache.remove(m_data.id + m_data.cookie); return AuthResult(id, m_data.id); }
GroupChatToaster::GroupChatToaster(const RsPeerId &peerId, const QString &message) : QWidget(NULL) { /* Invoke the Qt Designer generated object setup routine */ ui.setupUi(this); this->peerId = peerId; connect(ui.toasterButton, SIGNAL(clicked()), SLOT(chatButtonSlot())); connect(ui.closeButton, SIGNAL(clicked()), SLOT(hide())); /* set informations */ ui.textLabel->setText(RsHtml().formatText(NULL, message, RSHTML_FORMATTEXT_EMBED_SMILEYS | RSHTML_FORMATTEXT_EMBED_LINKS | RSHTML_FORMATTEXT_CLEANSTYLE)); ui.toasterLabel->setText(QString::fromUtf8(rsPeers->getPeerName(peerId).c_str())); ui.avatarWidget->setFrameType(AvatarWidget::STATUS_FRAME); ui.avatarWidget->setDefaultAvatar(":/images/user/personal64.png"); ui.avatarWidget->setId(ChatId(peerId)); }
void PaintChatWindow::on_pushButtonSend_clicked() { std::string html; if(chatType == ChatWidget::CHATTYPE_PRIVATE) { imgToHtmlString(html, ui->paintWidget->getImage()); } if(chatType == ChatWidget::CHATTYPE_LOBBY) { QImage img = ui->paintWidget->getImage(); imgToHtmlString(html, img, MAX_LOBBY_MSG_SIZE); } rsMsgs->sendChat(ChatId(chatId), html); // chatWidget->addChatMsg(false, QString::fromStdString(rsPeers->getPeerName(rsPeers->getOwnId())), // QDateTime::currentDateTime(), QDateTime::currentDateTime(), // QString::fromStdString(html), ChatWidget::MSGTYPE_NORMAL ); }
bool VkontakteAuthCreator::serve(const QUrl &url, const QString &path, Tufao::HttpServerRequest *request, Tufao::HttpServerResponse *response, QObject *parent) { if (path == LS("/oauth2/vkontakte")) { AuthHandler::setError(response, Tufao::HttpServerResponse::BAD_REQUEST); } else if (path.startsWith(LS("/oauth2/vkontakte/"))) { const QByteArray state = path.section(LC('/'), 3, 3).toLatin1(); if (ChatId(state.left(ChatId::kEncodedSize)).type() != ChatId::MessageId) { AuthHandler::setError(response, Tufao::HttpServerResponse::BAD_REQUEST); return true; } new VkontakteAuth(state, url, path, request, response, parent); return true; } return false; }
void CreateLobbyDialog::createLobby() { std::set<RsPeerId> shareList; ui->keyShareList->selectedIds<RsPeerId,FriendSelectionWidget::IDTYPE_SSL>(shareList, false); // if (shareList.empty()) { // QMessageBox::warning(this, "RetroShare", tr("Please select at least one friend"), QMessageBox::Ok, QMessageBox::Ok); // return; // } // create chat lobby !! std::string lobby_name = ui->lobbyName_LE->text().toUtf8().constData() ; std::string lobby_topic = ui->lobbyTopic_LE->text().toUtf8().constData() ; // set nick name ! RsGxsId gxs_id ; switch(ui->idChooser_CB->getChosenId(gxs_id)) { case GxsIdChooser::NoId: case GxsIdChooser::None: return ; default: break ; } // add to group ChatLobbyFlags lobby_flags ; if(ui->security_CB->currentIndex() == 0) lobby_flags |= RS_CHAT_LOBBY_FLAGS_PUBLIC ; if(ui->pgp_signed_CB->isChecked()) lobby_flags |= RS_CHAT_LOBBY_FLAGS_PGP_SIGNED ; ChatLobbyId id = rsMsgs->createChatLobby(lobby_name,gxs_id, lobby_topic, shareList, lobby_flags); std::cerr << "gui: Created chat lobby " << std::hex << id << std::dec << std::endl ; // open chat window !! ChatDialog::chatFriend(ChatId(id)) ; close(); }
void VOIPGUIHandler::ReceivedInvitation(const RsPeerId &peer_id, int flags) { #ifdef VOIPGUIHANDLER_DEBUG std::cerr << "****** VOIPGUIHandler: received Invitation from peer " << peer_id.toStdString() << " with flags==" << flags << std::endl; #endif ChatDialog *di = ChatDialog::getChat(ChatId(peer_id), Settings->getChatFlags()); if (di) { ChatWidget *cw = di->getChatWidget(); if(cw) { const QList<ChatWidgetHolder*> &chatWidgetHolderList = cw->chatWidgetHolderList(); foreach (ChatWidgetHolder *chatWidgetHolder, chatWidgetHolderList) { VOIPChatWidgetHolder *acwh = dynamic_cast<VOIPChatWidgetHolder*>(chatWidgetHolder) ; if (acwh) acwh->ReceivedInvitation(peer_id, flags); } } } else {
/** Constructor */ SecurityItem::SecurityItem(FeedHolder *parent, uint32_t feedId, const RsPgpId &gpgId, const RsPeerId &sslId, const std::string &sslCn, const std::string& ip_address,uint32_t type, bool isHome) : FeedItem(NULL), mParent(parent), mFeedId(feedId), mGpgId(gpgId), mSslId(sslId), mSslCn(sslCn), mIP(ip_address), mType(type), mIsHome(isHome) { /* Invoke the Qt Designer generated object setup routine */ setupUi(this); //quickmsgButton->hide(); chatButton->hide(); removeFriendButton->setEnabled(false); removeFriendButton->hide(); peerDetailsButton->setEnabled(false); friendRequesttoolButton->hide(); requestLabel->hide(); /* general ones */ connect( expandButton, SIGNAL( clicked( void ) ), this, SLOT( toggle ( void ) ) ); connect( clearButton, SIGNAL( clicked( void ) ), this, SLOT( removeItem ( void ) ) ); /* specific ones */ connect( chatButton, SIGNAL( clicked( void ) ), this, SLOT( openChat ( void ) ) ); //connect( quickmsgButton, SIGNAL( clicked( ) ), this, SLOT( sendMsg() ) ); connect( removeFriendButton, SIGNAL(clicked()), this, SLOT(removeFriend())); connect( peerDetailsButton, SIGNAL(clicked()), this, SLOT(peerDetails())); connect( friendRequesttoolButton, SIGNAL(clicked()), this, SLOT(friendRequest())); connect(NotifyQt::getInstance(), SIGNAL(friendsChanged()), this, SLOT(updateItem())); avatar->setId(ChatId(mSslId)); expandFrame->hide(); updateItemStatic(); updateItem(); }
void VOIPGUIHandler::ReceivedVoipData(const RsPeerId &peer_id) { std::vector<RsVOIPDataChunk> chunks ; if(!rsVOIP->getIncomingData(peer_id,chunks)) { std::cerr << "VOIPGUIHandler::ReceivedVoipData(): No data chunks to get. Weird!" << std::endl; return ; } ChatDialog *di = ChatDialog::getChat(ChatId(peer_id), Settings->getChatFlags()); if (di) { ChatWidget *cw = di->getChatWidget(); if (cw) { const QList<ChatWidgetHolder*> &chatWidgetHolderList = cw->chatWidgetHolderList(); foreach (ChatWidgetHolder *chatWidgetHolder, chatWidgetHolderList) { VOIPChatWidgetHolder *acwh = dynamic_cast<VOIPChatWidgetHolder*>(chatWidgetHolder) ; if (acwh) { for (unsigned int chunkIndex=0; chunkIndex<chunks.size(); chunkIndex++) { QByteArray qb(reinterpret_cast<const char *>(chunks[chunkIndex].data),chunks[chunkIndex].size); if(chunks[chunkIndex].type == RsVOIPDataChunk::RS_VOIP_DATA_TYPE_AUDIO) acwh->addAudioData(peer_id, &qb); else if(chunks[chunkIndex].type == RsVOIPDataChunk::RS_VOIP_DATA_TYPE_VIDEO) acwh->addVideoData(peer_id, &qb); else std::cerr << "VOIPGUIHandler: Unknown data type received. type=" << chunks[chunkIndex].type << std::endl; } break; } } } } else {
void SecurityIpItem::setup() { /* Invoke the Qt Designer generated object setup routine */ ui->setupUi(this); ui->peerDetailsButton->setEnabled(false); /* general ones */ connect(ui->expandButton, SIGNAL(clicked(void)), this, SLOT(toggle(void))); connect(ui->clearButton, SIGNAL(clicked(void)), this, SLOT(removeItem(void))); /* specific ones */ connect(ui->peerDetailsButton, SIGNAL(clicked()), this, SLOT(peerDetails())); connect(ui->rsBanListButton, SIGNAL(banListChanged(QString)), this, SLOT(banIpListChanged(QString))); ui->avatar->setId(ChatId(mSslId)); ui->rsBanListButton->setMode(RsBanListToolButton::LIST_WHITELIST, RsBanListToolButton::MODE_ADD); ui->rsBanListChangedLabel->hide(); ui->expandFrame->hide(); updateItemStatic(); updateItem(); }
void PopupChatWindow::removeDialog(ChatDialog *dialog) { QObject::disconnect(dialog, SIGNAL(infoChanged(ChatDialog*)), this, SLOT(tabInfoChanged(ChatDialog*))); QObject::disconnect(dialog, SIGNAL(newMessage(ChatDialog*)), this, SLOT(tabNewMessage(ChatDialog*))); if (tabbedWindow) { ui.tabWidget->removeDialog(dialog); if (ui.tabWidget->count() == 0) { deleteLater(); } } else { QObject::disconnect(dialog, SIGNAL(dialogClose(ChatDialog*)), this, SLOT(dialogClose(ChatDialog*))); if (chatDialog == dialog) { saveSettings(); dialog->removeFromParent(this); ui.horizontalLayout->removeWidget(dialog); chatDialog = NULL; chatId = ChatId(); deleteLater(); } } }
*/ QString AbstractClientPrivate::serverName(const AuthReply &reply) { if (reply.serverName.isEmpty() || reply.serverName == QLatin1String("*")) return url.host(); return reply.serverName; } /*! * Чтение пакета Protocol::AuthReplyPacket. */ AbstractClientPrivate::AuthReplyAction AbstractClientPrivate::authReply(const AuthReply &reply) { SCHAT_DEBUG_STREAM(this << "AbstractClientPrivate::authReply" << reply.status << Notice::status(reply.status) << ChatId(reply.userId).toString() << reply.userId.toHex()) if (clientState == AbstractClient::ClientOnline) return Nothing; Q_Q(AbstractClient); server->setName(serverName(reply)); if (reply.status == Notice::OK) { const bool setup = isSetup(reply); collisions = 0; authorized = false; q->setAuthorized(reply.userId); channel->setId(reply.userId); channel->account()->cookie = reply.cookie;
void MsgItem::updateItemStatic() { /* fill in */ #ifdef DEBUG_ITEM std::cerr << "MsgItem::updateItemStatic()"; std::cerr << std::endl; #endif MessageInfo mi; if (!rsMail) return; if (!rsMail->getMessage(mMsgId, mi)) return; /* get peer Id */ if(mi.msgflags & RS_MSG_SIGNED) avatar->setGxsId(mi.rsgxsid_srcId); else avatar->setId(ChatId(mi.rspeerid_srcId)); QString title; QString srcName; if ((mi.msgflags & RS_MSG_SYSTEM) && mi.rspeerid_srcId == rsPeers->getOwnId()) srcName = "RetroShare"; else { if(mi.msgflags & RS_MSG_SIGNED) { RsIdentityDetails details ; rsIdentity->getIdDetails(mi.rsgxsid_srcId, details) ; srcName = QString::fromUtf8(details.mNickname.c_str()); } else srcName = QString::fromUtf8(rsPeers->getPeerName(mi.rspeerid_srcId).c_str()); } timestampLabel->setText(DateTime::formatLongDateTime(mi.ts)); if (!mIsHome) { title = tr("Message From") + ": "; } else { /* subject */ uint32_t box = mi.msgflags & RS_MSG_BOXMASK; switch(box) { case RS_MSG_SENTBOX: title = tr("Sent Msg") + ": "; replyButton->setEnabled(false); break; case RS_MSG_DRAFTBOX: title = tr("Draft Msg") + ": "; replyButton->setEnabled(false); break; case RS_MSG_OUTBOX: title = tr("Pending Msg") + ": "; //deleteButton->setEnabled(false); replyButton->setEnabled(false); break; default: case RS_MSG_INBOX: title = ""; break; } } title += srcName; titleLabel->setText(title); subjectLabel->setText(QString::fromUtf8(mi.title.c_str())); mMsg = QString::fromUtf8(mi.msg.c_str()); if (wasExpanded() || expandFrame->isVisible()) { fillExpandFrame(); } std::list<FileInfo>::iterator it; for(it = mi.files.begin(); it != mi.files.end(); ++it) { /* add file */ SubFileItem *fi = new SubFileItem(it->hash, it->fname, it->path, it->size, SFI_STATE_REMOTE, mi.rspeerid_srcId); mFileItems.push_back(fi); QLayout *layout = expandFrame->layout(); layout->addWidget(fi); } playButton->setEnabled(false); if (mIsHome) { /* disable buttons */ clearButton->setEnabled(false); //gotoButton->setEnabled(false); /* hide buttons */ clearButton->hide(); } }
void ChatHandler::tick() { RS_STACK_MUTEX(mMtx); /********** LOCKED **********/ // first fetch lobbies std::vector<Lobby> lobbies; std::list<ChatLobbyId> subscribed_ids; mRsMsgs->getChatLobbyList(subscribed_ids); for(std::list<ChatLobbyId>::iterator lit = subscribed_ids.begin(); lit != subscribed_ids.end(); ++lit) { ChatLobbyInfo info; if(mRsMsgs->getChatLobbyInfo(*lit,info)) { Lobby l; l.id = *lit; l.name = info.lobby_name; l.topic = info.lobby_topic; l.subscribed = true; l.auto_subscribe = info.lobby_flags & RS_CHAT_LOBBY_FLAGS_AUTO_SUBSCRIBE; l.is_private = !(info.lobby_flags & RS_CHAT_LOBBY_FLAGS_PUBLIC); l.is_broadcast = false; l.gxs_id = info.gxs_id; lobbies.push_back(l); } } ChatId id = ChatId::makeBroadcastId(); { Lobby l; l.id = id.toLobbyId(); l.name = "BroadCast"; l.topic = "Retroshare broadcast chat: messages are sent to all connected friends."; l.subscribed = true; l.auto_subscribe = false; l.is_private = false; l.is_broadcast = true; l.gxs_id = id.toGxsId(); lobbies.push_back(l); } std::vector<VisibleChatLobbyRecord> unsubscribed_lobbies; mRsMsgs->getListOfNearbyChatLobbies(unsubscribed_lobbies); for(std::vector<VisibleChatLobbyRecord>::iterator vit = unsubscribed_lobbies.begin(); vit != unsubscribed_lobbies.end(); ++vit) { const VisibleChatLobbyRecord& info = *vit; if(std::find(subscribed_ids.begin(), subscribed_ids.end(), info.lobby_id) == subscribed_ids.end()) { Lobby l; l.id = info.lobby_id; l.name = info.lobby_name; l.topic = info.lobby_topic; l.subscribed = false; l.auto_subscribe = info.lobby_flags & RS_CHAT_LOBBY_FLAGS_AUTO_SUBSCRIBE; l.is_private = !(info.lobby_flags & RS_CHAT_LOBBY_FLAGS_PUBLIC); l.is_broadcast = false; l.gxs_id = RsGxsId(); lobbies.push_back(l); } } // process new messages bool changed = false; bool lobby_unread_count_changed = false; std::vector<std::list<ChatMessage>::iterator> done; std::vector<RsPeerId> peers_changed; bool gxs_id_failed = false; // to prevent asking for multiple failing gxs ids in one tick, to not flush the cache for(std::list<ChatMessage>::iterator lit = mRawMsgs.begin(); lit != mRawMsgs.end(); ++lit) { ChatMessage& msg = *lit; std::string author_id; std::string author_name; if(msg.chat_id.isBroadcast()) { author_id = msg.broadcast_peer_id.toStdString(); author_name = mRsPeers->getPeerName(msg.broadcast_peer_id); } else if(msg.chat_id.isGxsId()) { author_id = msg.chat_id.toGxsId().toStdString(); RsIdentityDetails details; if(!gxs_id_failed && mRsIdentity->getIdDetails(msg.chat_id.toGxsId(), details)) { author_name = details.mNickname; } else { gxs_id_failed = true; continue; } } else if(msg.chat_id.isLobbyId()) { author_id = msg.lobby_peer_gxs_id.toStdString(); RsIdentityDetails details; if(!gxs_id_failed && mRsIdentity->getIdDetails(msg.lobby_peer_gxs_id, details)) { author_name = details.mNickname; lobby_unread_count_changed = true; } else { gxs_id_failed = true; continue; } } else if(msg.chat_id.isPeerId()) { RsPeerId id; if(msg.incoming) id = msg.chat_id.toPeerId(); else id = mRsPeers->getOwnId(); author_id = id.toStdString(); author_name = mRsPeers->getPeerName(id); if(std::find(peers_changed.begin(), peers_changed.end(), msg.chat_id.toPeerId()) == peers_changed.end()) peers_changed.push_back(msg.chat_id.toPeerId()); } else { std::cerr << "Error in ChatHandler::tick(): unhandled chat_id=" << msg.chat_id.toStdString() << std::endl; // remove from queue, so msgs with wrong ids to not pile up done.push_back(lit); continue; } if(mChatInfo.find(msg.chat_id) == mChatInfo.end()) { ChatInfo info; info.is_broadcast = msg.chat_id.isBroadcast(); info.is_gxs_id = msg.chat_id.isGxsId(); info.is_lobby = msg.chat_id.isLobbyId(); info.is_peer = msg.chat_id.isPeerId(); if(msg.chat_id.isLobbyId()) { for(std::vector<Lobby>::iterator vit = mLobbies.begin(); vit != mLobbies.end(); ++vit) { if(vit->id == msg.chat_id.toLobbyId()) info.remote_author_name = vit->name; } } else if(msg.chat_id.isGxsId()) { RsIdentityDetails details; if(!gxs_id_failed && mRsIdentity->getIdDetails(msg.chat_id.toGxsId(), details)) { info.remote_author_id = msg.chat_id.toGxsId().toStdString(); info.remote_author_name = details.mNickname; } else { gxs_id_failed = true; continue; } } else if(msg.chat_id.isPeerId()) { info.remote_author_id = msg.chat_id.toPeerId().toStdString(); info.remote_author_name = mRsPeers->getPeerName(msg.chat_id.toPeerId()); } mChatInfo[msg.chat_id] = info; } Msg m; m.read = !msg.incoming; m.incoming = msg.incoming; m.was_send = msg.online; m.author_id = author_id; m.author_name = author_name; // remove html tags from chat message // extract links form href getPlainText(msg.msg, m.msg, m.links); m.recv_time = msg.recvTime; m.send_time = msg.sendTime; m.id = RSRandom::random_u32(); mMsgs[msg.chat_id].push_back(m); done.push_back(lit); changed = true; } for(std::vector<std::list<ChatMessage>::iterator>::iterator vit = done.begin(); vit != done.end(); ++vit) mRawMsgs.erase(*vit); // send changes if(changed) { mStateTokenServer->replaceToken(mMsgStateToken); mStateTokenServer->replaceToken(mUnreadMsgsStateToken); } for(std::vector<RsPeerId>::iterator vit = peers_changed.begin(); vit != peers_changed.end(); ++vit) { const std::list<Msg>& msgs = mMsgs[ChatId(*vit)]; uint32_t count = 0; for(std::list<Msg>::const_iterator lit = msgs.begin(); lit != msgs.end(); ++lit) if(!lit->read) count++; if(mUnreadMsgNotify) mUnreadMsgNotify->notifyUnreadMsgCountChanged(*vit, count); } std::sort(lobbies.begin(), lobbies.end(), &compare_lobby_id); if(lobby_unread_count_changed || mLobbies != lobbies) { mStateTokenServer->replaceToken(mLobbiesStateToken); mLobbies = lobbies; } }
void PopupDistantChatDialog::updateDisplay() { if(RsAutoUpdatePage::eventsLocked()) // we need to do that by end, because it's not possible to derive from both PopupChatDialog and RsAutoUpdatePage return ; // which both derive from QObject. Signals-slot connexions won't work anymore. if(!isVisible()) return ; //std::cerr << "Checking tunnel..." ; // make sure about the tunnel status // uint32_t status= RS_DISTANT_CHAT_STATUS_UNKNOWN; rsMsgs->getDistantChatStatus(_pid,status) ; ui.avatarWidget->setId(ChatId(_pid)); QString msg; switch(status) { case RS_DISTANT_CHAT_STATUS_UNKNOWN: //std::cerr << "Unknown hash. Error!" << std::endl; _status_label->setIcon(QIcon(IMAGE_GRY_LED)) ; msg = tr("Hash Error. No tunnel."); _status_label->setToolTip(msg) ; getChatWidget()->updateStatusString("%1", msg, true); getChatWidget()->blockSending(tr("Can't send message, because there is no tunnel.")); setPeerStatus(RS_STATUS_OFFLINE) ; break ; case RS_DISTANT_CHAT_STATUS_REMOTELY_CLOSED: std::cerr << "Chat remotely closed. " << std::endl; _status_label->setIcon(QIcon(IMAGE_RED_LED)) ; _status_label->setToolTip(QObject::tr("Distant peer has closed the chat")) ; getChatWidget()->updateStatusString("%1", tr("The person you're talking to has deleted the secured chat tunnel. You may remove the chat window now."), true); getChatWidget()->blockSending(tr("Can't send message, because the chat partner deleted the secure tunnel.")); setPeerStatus(RS_STATUS_OFFLINE) ; break ; case RS_DISTANT_CHAT_STATUS_TUNNEL_DN: //std::cerr << "Tunnel asked. Waiting for reponse. " << std::endl; _status_label->setIcon(QIcon(IMAGE_RED_LED)) ; msg = QObject::tr("Tunnel is pending..."); _status_label->setToolTip(msg) ; getChatWidget()->updateStatusString("%1", msg, true); getChatWidget()->blockSending(msg); setPeerStatus(RS_STATUS_OFFLINE) ; break ; case RS_DISTANT_CHAT_STATUS_TUNNEL_OK: //std::cerr << "Tunnel is ok. " << std::endl; _status_label->setIcon(QIcon(IMAGE_YEL_LED)) ; msg = QObject::tr("Secured tunnel established. Waiting for ACK..."); _status_label->setToolTip(msg) ; getChatWidget()->updateStatusString("%1", msg, true); getChatWidget()->blockSending(msg); setPeerStatus(RS_STATUS_ONLINE) ; break ; case RS_DISTANT_CHAT_STATUS_CAN_TALK: //std::cerr << "Tunnel is ok and data is transmitted." << std::endl; _status_label->setIcon(QIcon(IMAGE_GRN_LED)) ; msg = QObject::tr("Secured tunnel is working. You can talk!"); _status_label->setToolTip(msg) ; getChatWidget()->unblockSending(); setPeerStatus(RS_STATUS_ONLINE) ; break ; } }
void ChatLobbyToaster::chatButtonSlot() { ChatDialog::chatFriend(ChatId(mLobbyId)); hide(); }
void NotifyQt::UpdateGUI() { if(RsAutoUpdatePage::eventsLocked()) return ; { QMutexLocker m(&_mutex) ; if(!_enabled) return ; } static bool already_updated = false ; // these only update once at start because they may already have been set before // the gui is running, then they get updated by callbacks. if(!already_updated) { emit messagesChanged() ; emit neighboursChanged(); emit configChanged(); already_updated = true ; } /* Finally Check for PopupMessages / System Error Messages */ if (rsNotify) { uint32_t sysid; uint32_t type; std::string title, id, msg; /* You can set timeToShow, timeToLive and timeToHide or can leave the standard */ ToasterItem *toaster = NULL; if (rsNotify->NotifyPopupMessage(type, id, title, msg)) { uint popupflags = Settings->getNotifyFlags(); switch(type) { case RS_POPUP_ENCRYPTED_MSG: SoundManager::play(SOUND_MESSAGE_ARRIVED); if ((popupflags & RS_POPUP_MSG) && !_disableAllToaster) { toaster = new ToasterItem(new MessageToaster("", tr("Encrypted message"), QString("[%1]").arg(tr("Encrypted message")))); } break; case RS_POPUP_MSG: SoundManager::play(SOUND_MESSAGE_ARRIVED); if ((popupflags & RS_POPUP_MSG) && !_disableAllToaster) { toaster = new ToasterItem(new MessageToaster(id, QString::fromUtf8(title.c_str()), QString::fromUtf8(msg.c_str()))); } break; case RS_POPUP_CONNECT: SoundManager::play(SOUND_USER_ONLINE); if ((popupflags & RS_POPUP_CONNECT) && !_disableAllToaster) { toaster = new ToasterItem(new OnlineToaster(RsPeerId(id))); } break; case RS_POPUP_DOWNLOAD: SoundManager::play(SOUND_DOWNLOAD_COMPLETE); if ((popupflags & RS_POPUP_DOWNLOAD) && !_disableAllToaster) { /* id = file hash */ toaster = new ToasterItem(new DownloadToaster(RsFileHash(id), QString::fromUtf8(title.c_str()))); } break; case RS_POPUP_CHAT: if ((popupflags & RS_POPUP_CHAT) && !_disableAllToaster) { // TODO: fix for distant chat, look up if dstant chat uses RS_POPUP_CHAT ChatDialog *chatDialog = ChatDialog::getChat(ChatId(RsPeerId(id))); ChatWidget *chatWidget; if (chatDialog && (chatWidget = chatDialog->getChatWidget()) && chatWidget->isActive()) { // do not show when active break; } toaster = new ToasterItem(new ChatToaster(RsPeerId(id), QString::fromUtf8(msg.c_str()))); } break; case RS_POPUP_GROUPCHAT: if ((popupflags & RS_POPUP_GROUPCHAT) && !_disableAllToaster) { MainWindow *mainWindow = MainWindow::getInstance(); if (mainWindow && mainWindow->isActiveWindow() && !mainWindow->isMinimized()) { if (MainWindow::getActivatePage() == MainWindow::Friends) { if (FriendsDialog::isGroupChatActive()) { // do not show when active break; } } } toaster = new ToasterItem(new GroupChatToaster(RsPeerId(id), QString::fromUtf8(msg.c_str()))); } break; case RS_POPUP_CHATLOBBY: if ((popupflags & RS_POPUP_CHATLOBBY) && !_disableAllToaster) { ChatId chat_id(id); ChatDialog *chatDialog = ChatDialog::getChat(chat_id); ChatWidget *chatWidget; if (chatDialog && (chatWidget = chatDialog->getChatWidget()) && chatWidget->isActive()) { // do not show when active break; } ChatLobbyDialog *chatLobbyDialog = dynamic_cast<ChatLobbyDialog*>(chatDialog); RsGxsId sender(title); if (!chatLobbyDialog || chatLobbyDialog->isParticipantMuted(sender)) break; // participant is muted toaster = new ToasterItem(new ChatLobbyToaster(chat_id.toLobbyId(), sender, QString::fromUtf8(msg.c_str()))); } break; case RS_POPUP_CONNECT_ATTEMPT: if ((popupflags & RS_POPUP_CONNECT_ATTEMPT) && !_disableAllToaster) { // id = gpgid // title = ssl name // msg = peer id toaster = new ToasterItem(new FriendRequestToaster(RsPgpId(id), QString::fromUtf8(title.c_str()), RsPeerId(msg))); } break; } } /*Now check Plugins*/ if (!toaster) { int pluginCount = rsPlugins->nbPlugins(); for (int i = 0; i < pluginCount; ++i) { RsPlugin *rsPlugin = rsPlugins->plugin(i); if (rsPlugin) { ToasterNotify *toasterNotify = rsPlugin->qt_toasterNotify(); if (toasterNotify) { toaster = toasterNotify->toasterItem(); continue; } } } } if (toaster) { /* init attributes */ toaster->widget->setWindowFlags(Qt::ToolTip | Qt::WindowStaysOnTopHint); /* add toaster to waiting list */ //QMutexLocker lock(&waitingToasterMutex); waitingToasterList.push_back(toaster); } if (rsNotify->NotifySysMessage(sysid, type, title, msg)) { /* make a warning message */ switch(type) { case RS_SYS_ERROR: QMessageBox::critical(MainWindow::getInstance(), QString::fromUtf8(title.c_str()), QString::fromUtf8(msg.c_str())); break; case RS_SYS_WARNING: QMessageBox::warning(MainWindow::getInstance(), QString::fromUtf8(title.c_str()), QString::fromUtf8(msg.c_str())); break; default: case RS_SYS_INFO: QMessageBox::information(MainWindow::getInstance(), QString::fromUtf8(title.c_str()), QString::fromUtf8(msg.c_str())); break; } } if (rsNotify->NotifyLogMessage(sysid, type, title, msg)) { /* make a log message */ std::string logMesString = title + " " + msg; switch(type) { case RS_SYS_ERROR: case RS_SYS_WARNING: case RS_SYS_INFO: emit logInfoChanged(QString::fromUtf8(logMesString.c_str())); } } } /* Now start the waiting toasters */ startWaitingToasters(); }
void ConfCertDialog::load() { RsPeerDetails detail; if(!rsPeers->getPeerDetails(peerId, detail)) { QMessageBox::information(this, tr("RetroShare"), tr("Error : cannot get peer details.")); close(); return; } ui._direct_transfer_CB->setChecked( detail.service_perm_flags & RS_NODE_PERM_DIRECT_DL ) ; ui._allow_push_CB->setChecked( detail.service_perm_flags & RS_NODE_PERM_ALLOW_PUSH) ; //ui.pgpfingerprint->setText(QString::fromUtf8(detail.name.c_str())); ui.peerid->setText(QString::fromStdString(detail.id.toStdString())); RetroShareLink link; link.createPerson(detail.gpg_id); ui.pgpfingerprint->setText(link.toHtml()); ui.pgpfingerprint->setToolTip(link.title()); ui.avatar->setId(ChatId(peerId)); ui.loc->setText(QString::fromUtf8(detail.location.c_str())); // Dont Show a timestamp in RS calculate the day ui.lastcontact->setText(DateTime::formatLongDateTime(detail.lastConnect)); /* set retroshare version */ std::string version; rsDisc->getPeerVersion(detail.id, version); ui.version->setText(QString::fromStdString(version)); RsPeerCryptoParams cdet ; if(RsControl::instance()->getPeerCryptoDetails(detail.id,cdet) && cdet.connexion_state!=0) { QString ct ; ct += QString::fromStdString(cdet.cipher_version) + ": "; ct += QString::fromStdString(cdet.cipher_name); if(cdet.cipher_version != "TLSv1.2") ct += QString::number(cdet.cipher_bits_1); ui.crypto_info->setText(ct) ; } else ui.crypto_info->setText(tr("Not connected")) ; if (detail.isHiddenNode) { // enable only the first row and set name of the first label to "Hidden Address" ui.l_localAddress->setText(tr("Hidden Address")); ui.l_extAddress->setEnabled(false); ui.extAddress->setEnabled(false); ui.l_portExternal->setEnabled(false); ui.extPort->setEnabled(false); ui.l_dynDNS->setEnabled(false); ui.dynDNS->setEnabled(false); /* set hidden address */ ui.localAddress->setText(QString::fromStdString(detail.hiddenNodeAddress)); ui.localPort -> setValue(detail.hiddenNodePort); // set everything else to none ui.extAddress->setText(tr("none")); ui.extPort->setValue(0); ui.dynDNS->setText(tr("none")); } else { // enable everything and set name of the first label to "Local Address" ui.l_localAddress->setText(tr("Local Address")); ui.l_extAddress->setEnabled(true); ui.extAddress->setEnabled(true); ui.l_portExternal->setEnabled(true); ui.extPort->setEnabled(true); ui.l_dynDNS->setEnabled(true); ui.dynDNS->setEnabled(true); /* set local address */ ui.localAddress->setText(QString::fromStdString(detail.localAddr)); ui.localPort -> setValue(detail.localPort); /* set the server address */ ui.extAddress->setText(QString::fromStdString(detail.extAddr)); ui.extPort -> setValue(detail.extPort); ui.dynDNS->setText(QString::fromStdString(detail.dyndns)); } ui.statusline->setText(StatusDefs::connectStateString(detail)); ui.ipAddressList->clear(); for(std::list<std::string>::const_iterator it(detail.ipAddressList.begin());it!=detail.ipAddressList.end();++it) ui.ipAddressList->addItem(QString::fromStdString(*it)); ui.loc->show(); ui.label_loc->show(); ui.statusline->show(); ui.label_status->show(); ui.lastcontact->show(); ui.label_last_contact->show(); ui.version->show(); ui.label_version->show(); ui.groupBox->show(); ui.groupBox_4->show(); ui.tabWidget->show(); //ui.rsid->hide(); //ui.label_rsid->hide(); ui.pgpfingerprint->show(); //ui.pgpfingerprint_label->show(); ui.stabWidget->setTabEnabled(2,true) ; ui.stabWidget->setTabEnabled(3,true) ; ui.stabWidget->setTabEnabled(4,true) ; loadInvitePage() ; }