blob: f56ccc0d6759981501c55f84909c8cdb747432d4 [file] [log] [blame]
Yingdi Yu04842232013-10-23 14:03:09 -07001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
2/*
3 * Copyright (c) 2013, Regents of the University of California
4 * Yingdi Yu
5 *
6 * BSD license, See the LICENSE file for more information
7 *
Yingdi Yu42f66462013-10-31 17:38:22 -07008 * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
9 * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
10 * Yingdi Yu <yingdi@cs.ucla.edu>
Yingdi Yu04842232013-10-23 14:03:09 -070011 */
12
13#include "chatdialog.h"
14#include "ui_chatdialog.h"
15
Yingdi Yu42f66462013-10-31 17:38:22 -070016#include <QScrollBar>
17
Yingdi Yuc4d08d22013-10-23 23:07:29 -070018#ifndef Q_MOC_RUN
19#include <ndn.cxx/security/identity/identity-manager.h>
Yingdi Yuc4d08d22013-10-23 23:07:29 -070020#include <ndn.cxx/security/encryption/basic-encryption-manager.h>
Yingdi Yu42f66462013-10-31 17:38:22 -070021#include <sync-intro-certificate.h>
22#include <boost/random/random_device.hpp>
23#include <boost/random/uniform_int_distribution.hpp>
Yingdi Yuc4d08d22013-10-23 23:07:29 -070024#include "logging.h"
25#endif
26
Yingdi Yu04842232013-10-23 14:03:09 -070027using namespace std;
Yingdi Yu04842232013-10-23 14:03:09 -070028
Yingdi Yuc4d08d22013-10-23 23:07:29 -070029INIT_LOGGER("ChatDialog");
30
Yingdi Yu42f66462013-10-31 17:38:22 -070031static const int HELLO_INTERVAL = FRESHNESS * 3 / 4;
32
33Q_DECLARE_METATYPE(std::vector<Sync::MissingDataInfo> )
34Q_DECLARE_METATYPE(size_t)
35
36ChatDialog::ChatDialog(ndn::Ptr<ContactManager> contactManager,
37 const ndn::Name& chatroomPrefix,
38 const ndn::Name& localPrefix,
39 const ndn::Name& defaultIdentity,
Yingdi Yu42372442013-11-06 18:43:31 -080040 const std::string& nick,
41 bool trial,
Yingdi Yu04842232013-10-23 14:03:09 -070042 QWidget *parent)
Yingdi Yu42f66462013-10-31 17:38:22 -070043: QDialog(parent)
44 , ui(new Ui::ChatDialog)
45 , m_contactManager(contactManager)
46 , m_chatroomPrefix(chatroomPrefix)
47 , m_localPrefix(localPrefix)
48 , m_defaultIdentity(defaultIdentity)
49 , m_invitationPolicyManager(ndn::Ptr<InvitationPolicyManager>(new InvitationPolicyManager(m_chatroomPrefix.get(-1).toUri())))
Yingdi Yu42372442013-11-06 18:43:31 -080050 , m_nick(nick)
Yingdi Yu42f66462013-10-31 17:38:22 -070051 , m_sock(NULL)
52 , m_lastMsgTime(0)
53 // , m_historyInitialized(false)
54 , m_joined(false)
55 , m_inviteListDialog(new InviteListDialog(m_contactManager))
Yingdi Yu04842232013-10-23 14:03:09 -070056{
Yingdi Yu42f66462013-10-31 17:38:22 -070057 qRegisterMetaType<std::vector<Sync::MissingDataInfo> >("std::vector<Sync::MissingDataInfo>");
58 qRegisterMetaType<size_t>("size_t");
59
Yingdi Yuc4d08d22013-10-23 23:07:29 -070060 ui->setupUi(this);
61
Yingdi Yu42f66462013-10-31 17:38:22 -070062 m_localChatPrefix = m_localPrefix;
Yingdi Yu42372442013-11-06 18:43:31 -080063 m_localChatPrefix.append("%F0.").append(m_defaultIdentity);
Yingdi Yu42f66462013-10-31 17:38:22 -070064 m_localChatPrefix.append("chronos").append(m_chatroomPrefix.get(-1));
65
66 m_session = time(NULL);
67 m_scene = new DigestTreeScene(this);
68
69 initializeSetting();
70 updateLabels();
71
72 ui->treeViewer->setScene(m_scene);
73 ui->treeViewer->hide();
74 m_scene->plot("Empty");
75 QRectF rect = m_scene->itemsBoundingRect();
76 m_scene->setSceneRect(rect);
77
78 m_rosterModel = new QStringListModel(this);
79 ui->listView->setModel(m_rosterModel);
80
81 m_timer = new QTimer(this);
82
Yingdi Yu42372442013-11-06 18:43:31 -080083 setWrapper(trial);
Yingdi Yu42f66462013-10-31 17:38:22 -070084
85 connect(ui->inviteButton, SIGNAL(clicked()),
86 this, SLOT(openInviteListDialog()));
87 connect(m_inviteListDialog, SIGNAL(invitionDetermined(QString, bool)),
88 this, SLOT(sendInvitationWrapper(QString, bool)));
89 connect(ui->lineEdit, SIGNAL(returnPressed()),
90 this, SLOT(returnPressed()));
91 connect(ui->treeButton, SIGNAL(pressed()),
92 this, SLOT(treeButtonPressed()));
93 connect(this, SIGNAL(dataReceived(QString, const char *, size_t, bool, bool)),
94 this, SLOT(processData(QString, const char *, size_t, bool, bool)));
95 connect(this, SIGNAL(treeUpdated(const std::vector<Sync::MissingDataInfo>)),
96 this, SLOT(processTreeUpdate(const std::vector<Sync::MissingDataInfo>)));
97 connect(m_timer, SIGNAL(timeout()),
98 this, SLOT(replot()));
99 connect(m_scene, SIGNAL(replot()),
100 this, SLOT(replot()));
101 // TODO: TrayIcon
102 // connect(trayIcon, SIGNAL(messageClicked()),
103 // this, SLOT(showNormal()));
104 // connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
105 // this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
106 connect(m_scene, SIGNAL(rosterChanged(QStringList)),
107 this, SLOT(updateRosterList(QStringList)));
108
109 // m_identityManager = ndn::Ptr<ndn::security::IdentityManager>::Create();
110 // // ndn::Ptr<ndn::security::EncryptionManager> encryptionManager = ndn::Ptr<ndn::security::EncryptionManager>(new ndn::security::BasicEncryptionManager(privateStorage, "/tmp/encryption.db"));
111
112 // ndn::Name certificateName = m_identityManager->getDefaultCertificateNameByIdentity(m_defaultIdentity);
113 // m_syncPolicyManager = ndn::Ptr<SyncPolicyManager>(new SyncPolicyManager(m_defaultIdentity, certificateName, m_chatroomPrefix));
114
115 initializeSync();
Yingdi Yu04842232013-10-23 14:03:09 -0700116}
117
Yingdi Yu42f66462013-10-31 17:38:22 -0700118// ChatDialog::ChatDialog(const ndn::Name& chatroomPrefix,
119// const ndn::Name& localPrefix,
120// const ndn::Name& defaultIdentity,
121// const ndn::security::IdentityCertificate& identityCertificate,
122// QWidget *parent)
123// : QDialog(parent)
124// , ui(new Ui::ChatDialog)
125// , m_chatroomPrefix(chatroomPrefix)
126// , m_localPrefix(localPrefix)
127// , m_defaultIdentity(defaultIdentity)
128// , m_invitationPolicyManager(ndn::Ptr<InvitationPolicyManager>(new InvitationPolicyManager(m_chatroomPrefix.get(-1).toUri())))
129
130// , m_sock(NULL)
131// , m_lastMsgTime(0)
132// // , m_historyInitialized(false)
133// , m_joined(false)
134// {
135// qRegisterMetaType<std::vector<Sync::MissingDataInfo> >("std::vector<Sync::MissingDataInfo>");
136// qRegisterMetaType<size_t>("size_t");
137
138// ui->setupUi(this);
139
140// m_localChatPrefix = m_localPrefix;
141// m_localChatPrefix.append("FH").append(m_defaultIdentity);
142// m_localChatPrefix.append("chronos").append(m_chatroomPrefix.get(-1));
143
144// m_session = time(NULL);
145// m_scene = new DigestTreeScene(this);
146
147// initializeSetting();
148// updateLabels();
149
150// ui->treeViewer->setScene(m_scene);
151// ui->treeViewer->hide();
152// m_scene->plot("Empty");
153// QRectF rect = m_scene->itemsBoundingRect();
154// m_scene->setSceneRect(rect);
155
156// m_rosterModel = new QStringListModel(this);
157// ui->listView->setModel(m_rosterModel);
158
159// m_timer = new QTimer(this);
160
161// setWrapper();
162
163// connect(ui->lineEdit, SIGNAL(returnPressed()),
164// this, SLOT(returnPressed()));
165// connect(ui->treeButton, SIGNAL(pressed()),
166// this, SLOT(treeButtonPressed()));
167// connect(this, SIGNAL(dataReceived(QString, const char *, size_t, bool, bool)),
168// this, SLOT(processData(QString, const char *, size_t, bool, bool)));
169// connect(this, SIGNAL(treeUpdated(const std::vector<Sync::MissingDataInfo>)),
170// this, SLOT(processTreeUpdate(const std::vector<Sync::MissingDataInfo>)));
171// connect(m_timer, SIGNAL(timeout()),
172// this, SLOT(replot()));
173// connect(m_scene, SIGNAL(replot()),
174// this, SLOT(replot()));
175// // TODO: TrayIcon
176// // connect(trayIcon, SIGNAL(messageClicked()),
177// // this, SLOT(showNormal()));
178// // connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
179// // this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
180// connect(m_scene, SIGNAL(rosterChanged(QStringList)),
181// this, SLOT(updateRosterList(QStringList)));
182
183// // m_identityManager = ndn::Ptr<ndn::security::IdentityManager>::Create();
184// // // ndn::Ptr<ndn::security::EncryptionManager> encryptionManager = ndn::Ptr<ndn::security::EncryptionManager>(new ndn::security::BasicEncryptionManager(privateStorage, "/tmp/encryption.db"));
185
186// // ndn::Name certificateName = m_identityManager->getDefaultCertificateNameByIdentity(m_defaultIdentity);
187// // m_syncPolicyManager = ndn::Ptr<SyncPolicyManager>(new SyncPolicyManager(m_defaultIdentity, certificateName, m_chatroomPrefix));
188
189// initializeSync();
190// }
191
Yingdi Yu04842232013-10-23 14:03:09 -0700192ChatDialog::~ChatDialog()
193{
Yingdi Yu42372442013-11-06 18:43:31 -0800194 _LOG_DEBUG("about to leave 4!");
195 if(m_sock != NULL)
196 {
197 sendLeave();
198 delete m_sock;
199 m_sock = NULL;
200 }
201 // m_handler->shutdown();
Yingdi Yu04842232013-10-23 14:03:09 -0700202}
203
204void
Yingdi Yu42372442013-11-06 18:43:31 -0800205ChatDialog::setWrapper(bool trial)
Yingdi Yu04842232013-10-23 14:03:09 -0700206{
Yingdi Yu42f66462013-10-31 17:38:22 -0700207 m_identityManager = ndn::Ptr<ndn::security::IdentityManager>::Create();
208 // ndn::Ptr<ndn::security::EncryptionManager> encryptionManager = ndn::Ptr<ndn::security::EncryptionManager>(new ndn::security::BasicEncryptionManager(privateStorage, "/tmp/encryption.db"));
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700209
Yingdi Yu42f66462013-10-31 17:38:22 -0700210 ndn::Name certificateName = m_identityManager->getDefaultCertificateNameByIdentity(m_defaultIdentity);
211 m_syncPolicyManager = ndn::Ptr<SyncPolicyManager>(new SyncPolicyManager(m_defaultIdentity, certificateName, m_chatroomPrefix));
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700212
Yingdi Yu42f66462013-10-31 17:38:22 -0700213 m_keychain = ndn::Ptr<ndn::security::Keychain>(new ndn::security::Keychain(m_identityManager, m_invitationPolicyManager, NULL));
214
215 m_handler = ndn::Ptr<ndn::Wrapper>(new ndn::Wrapper(m_keychain));
Yingdi Yu42372442013-11-06 18:43:31 -0800216
217 if(trial == true)
218 {
219 ndn::Ptr<ndn::Interest> interest = ndn::Ptr<ndn::Interest>(new ndn::Interest(ndn::Name("/local/ndn/prefix")));
220 ndn::Ptr<ndn::Closure> closure = ndn::Ptr<ndn::Closure>(new ndn::Closure(boost::bind(&ChatDialog::onUnverified,
221 this,
222 _1),
223 boost::bind(&ChatDialog::onTimeout,
224 this,
225 _1,
226 _2),
227 boost::bind(&ChatDialog::onUnverified,
228 this,
229 _1)));
230
231 m_handler->sendInterest(interest, closure);
232 }
Yingdi Yu04842232013-10-23 14:03:09 -0700233}
234
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700235void
Yingdi Yu42f66462013-10-31 17:38:22 -0700236ChatDialog::initializeSetting()
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700237{
Yingdi Yu42f66462013-10-31 17:38:22 -0700238 // TODO: nick name may be changed.
Yingdi Yu42372442013-11-06 18:43:31 -0800239 m_user.setNick(QString::fromStdString(m_nick));
Yingdi Yu42f66462013-10-31 17:38:22 -0700240 m_user.setChatroom(QString::fromStdString(m_chatroomPrefix.get(-1).toUri()));
241 m_user.setOriginPrefix(QString::fromStdString(m_localPrefix.toUri()));
242 m_user.setPrefix(QString::fromStdString(m_localChatPrefix.toUri()));
243 m_scene->setCurrentPrefix(QString::fromStdString(m_localChatPrefix.toUri()));
244}
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700245
Yingdi Yu42f66462013-10-31 17:38:22 -0700246void
247ChatDialog::updateLabels()
248{
249 QString settingDisp = QString("Chatroom: %1").arg(m_user.getChatroom());
250 ui->infoLabel->setStyleSheet("QLabel {color: #630; font-size: 16px; font: bold \"Verdana\";}");
251 ui->infoLabel->setText(settingDisp);
252 QString prefixDisp;
253 if (m_user.getPrefix().startsWith("/private/local"))
254 {
255 prefixDisp = QString("<Warning: no connection to hub or hub does not support prefix autoconfig.>\n <Prefix = %1>").arg(m_user.getPrefix());
256 ui->prefixLabel->setStyleSheet("QLabel {color: red; font-size: 12px; font: bold \"Verdana\";}");
257 }
258 else
259 {
260 prefixDisp = QString("<Prefix = %1>").arg(m_user.getPrefix());
261 ui->prefixLabel->setStyleSheet("QLabel {color: Green; font-size: 12px; font: bold \"Verdana\";}");
262 }
263 ui->prefixLabel->setText(prefixDisp);
264}
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700265
Yingdi Yu42f66462013-10-31 17:38:22 -0700266void
267ChatDialog::sendInvitation(ndn::Ptr<ContactItem> contact, bool isIntroducer)
268{
269 m_invitationPolicyManager->addTrustAnchor(contact->getSelfEndorseCertificate());
270
271 ndn::Name certificateName = m_identityManager->getDefaultCertificateNameByIdentity(m_defaultIdentity);
272
273 ndn::Name interestName("/ndn/broadcast/chronos/invitation");
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700274 interestName.append(contact->getNameSpace());
275 interestName.append("chatroom");
276 interestName.append(m_chatroomPrefix.get(-1));
277 interestName.append("inviter-prefix");
278 interestName.append(m_localPrefix);
279 interestName.append("inviter");
280 interestName.append(certificateName);
281
282 string signedUri = interestName.toUri();
Yingdi Yu42f66462013-10-31 17:38:22 -0700283 ndn::Blob signedBlob(signedUri.c_str(), signedUri.size());
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700284
Yingdi Yu42f66462013-10-31 17:38:22 -0700285 ndn::Ptr<const ndn::signature::Sha256WithRsa> sha256sig = ndn::DynamicCast<const ndn::signature::Sha256WithRsa>(m_identityManager->signByCertificate(signedBlob, certificateName));
286 const ndn::Blob& sigBits = sha256sig->getSignatureBits();
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700287
288 interestName.append(sigBits.buf(), sigBits.size());
Yingdi Yu42372442013-11-06 18:43:31 -0800289 interestName.appendVersion();
290
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700291
Yingdi Yu42f66462013-10-31 17:38:22 -0700292 ndn::Ptr<ndn::Interest> interest = ndn::Ptr<ndn::Interest>(new ndn::Interest(interestName));
293 ndn::Ptr<ndn::Closure> closure = ndn::Ptr<ndn::Closure>(new ndn::Closure(boost::bind(&ChatDialog::onInviteReplyVerified,
294 this,
295 _1,
296 contact->getNameSpace(),
297 isIntroducer),
298 boost::bind(&ChatDialog::onInviteTimeout,
299 this,
300 _1,
301 _2,
302 contact->getNameSpace(),
303 7),
304 boost::bind(&ChatDialog::onUnverified,
305 this,
306 _1)));
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700307
308 m_handler->sendInterest(interest, closure);
309}
310
311void
Yingdi Yu42f66462013-10-31 17:38:22 -0700312ChatDialog::addTrustAnchor(const EndorseCertificate& selfEndorseCertificate)
313{ m_invitationPolicyManager->addTrustAnchor(selfEndorseCertificate); }
314
315void
316ChatDialog::addChatDataRule(const ndn::Name& prefix,
317 const ndn::security::IdentityCertificate& identityCertificate,
318 bool isIntroducer)
319{ m_syncPolicyManager->addChatDataRule(prefix, identityCertificate, isIntroducer); }
320
321void
322ChatDialog::publishIntroCert(ndn::Ptr<ndn::security::IdentityCertificate> dskCertificate, bool isIntroducer)
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700323{
Yingdi Yu42f66462013-10-31 17:38:22 -0700324 SyncIntroCertificate syncIntroCertificate(m_chatroomPrefix,
325 dskCertificate->getPublicKeyName(),
326 m_identityManager->getDefaultKeyNameForIdentity(m_defaultIdentity),
327 dskCertificate->getNotBefore(),
328 dskCertificate->getNotAfter(),
329 dskCertificate->getPublicKeyInfo(),
330 (isIntroducer ? SyncIntroCertificate::INTRODUCER : SyncIntroCertificate::PRODUCER));
331 ndn::Name certName = m_identityManager->getDefaultCertificateNameByIdentity(m_defaultIdentity);
Yingdi Yued8cfc42013-11-01 17:37:51 -0700332 _LOG_DEBUG("publishIntroCert: " << syncIntroCertificate.getName());
Yingdi Yu42f66462013-10-31 17:38:22 -0700333 m_identityManager->signByCertificate(syncIntroCertificate, certName);
334 m_handler->putToNdnd(*syncIntroCertificate.encodeToWire());
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700335}
336
337void
Yingdi Yu42f66462013-10-31 17:38:22 -0700338ChatDialog::invitationRejected(const ndn::Name& identity)
339{
340 _LOG_DEBUG(" " << identity.toUri() << " rejected your invitation!");
341 //TODO:
342}
343
344void
345ChatDialog::invitationAccepted(const ndn::Name& identity, ndn::Ptr<ndn::Data> data, const string& inviteePrefix, bool isIntroducer)
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700346{
347 _LOG_DEBUG(" " << identity.toUri() << " accepted your invitation!");
Yingdi Yu42f66462013-10-31 17:38:22 -0700348 ndn::Ptr<const ndn::signature::Sha256WithRsa> sha256sig = boost::dynamic_pointer_cast<const ndn::signature::Sha256WithRsa> (data->getSignature());
349 const ndn::Name & keyLocatorName = sha256sig->getKeyLocator().getKeyName();
350 ndn::Ptr<ndn::security::IdentityCertificate> dskCertificate = m_invitationPolicyManager->getValidatedDskCertificate(keyLocatorName);
Yingdi Yuc90deb12013-11-06 18:51:19 -0800351 m_syncPolicyManager->addChatDataRule(inviteePrefix, *dskCertificate, isIntroducer);
Yingdi Yu42f66462013-10-31 17:38:22 -0700352 publishIntroCert(dskCertificate, isIntroducer);
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700353}
354
355void
Yingdi Yu42f66462013-10-31 17:38:22 -0700356ChatDialog::onInviteReplyVerified(ndn::Ptr<ndn::Data> data, const ndn::Name& identity, bool isIntroducer)
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700357{
358 string content(data->content().buf(), data->content().size());
359 if(content.empty())
360 invitationRejected(identity);
361 else
Yingdi Yu42f66462013-10-31 17:38:22 -0700362 invitationAccepted(identity, data, content, isIntroducer);
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700363}
364
365void
Yingdi Yu42f66462013-10-31 17:38:22 -0700366ChatDialog::onInviteTimeout(ndn::Ptr<ndn::Closure> closure, ndn::Ptr<ndn::Interest> interest, const ndn::Name& identity, int retry)
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700367{
368 if(retry > 0)
369 {
Yingdi Yu42f66462013-10-31 17:38:22 -0700370 ndn::Ptr<ndn::Closure> newClosure = ndn::Ptr<ndn::Closure>(new ndn::Closure(closure->m_dataCallback,
371 boost::bind(&ChatDialog::onInviteTimeout,
372 this,
373 _1,
374 _2,
375 identity,
376 retry - 1),
377 closure->m_unverifiedCallback,
378 closure->m_stepCount)
379 );
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700380 m_handler->sendInterest(interest, newClosure);
381 }
382 else
383 invitationRejected(identity);
384}
385
386void
Yingdi Yu42f66462013-10-31 17:38:22 -0700387ChatDialog::onUnverified(ndn::Ptr<ndn::Data> data)
Yingdi Yuc4d08d22013-10-23 23:07:29 -0700388{}
389
Yingdi Yu42f66462013-10-31 17:38:22 -0700390void
Yingdi Yu42372442013-11-06 18:43:31 -0800391ChatDialog::onTimeout(ndn::Ptr<ndn::Closure> closure,
392 ndn::Ptr<ndn::Interest> interest)
393{}
394
395void
Yingdi Yu42f66462013-10-31 17:38:22 -0700396ChatDialog::initializeSync()
397{
398
399 m_sock = new Sync::SyncSocket(m_chatroomPrefix.toUri(),
400 m_syncPolicyManager,
401 bind(&ChatDialog::processTreeUpdateWrapper, this, _1, _2),
402 bind(&ChatDialog::processRemoveWrapper, this, _1));
403
404 usleep(100000);
405
406 QTimer::singleShot(600, this, SLOT(sendJoin()));
407 m_timer->start(FRESHNESS * 1000);
408 disableTreeDisplay();
409 QTimer::singleShot(2200, this, SLOT(enableTreeDisplay()));
410 // Sync::CcnxWrapperPtr handle = boost::make_shared<Sync::CcnxWrapper> ();
411 // handle->setInterestFilter(m_user.getPrefix().toStdString(), bind(&ChatDialog::respondHistoryRequest, this, _1));
412 // _LOG_DEBUG("initializeSync is done!");
413}
414
415void
416ChatDialog::returnPressed()
417{
418 QString text = ui->lineEdit->text();
419 if (text.isEmpty())
420 return;
421
422 ui->lineEdit->clear();
423
424 if (text.startsWith("boruoboluomi"))
425 {
426 summonReaper ();
427 // reapButton->show();
428 fitView();
429 return;
430 }
431
432 if (text.startsWith("minimanihong"))
433 {
434 // reapButton->hide();
435 fitView();
436 return;
437 }
438
439 SyncDemo::ChatMessage msg;
440 formChatMessage(text, msg);
441
442 appendMessage(msg);
443
444 sendMsg(msg);
445
446 fitView();
447}
448
449void
450ChatDialog::treeButtonPressed()
451{
452 if (ui->treeViewer->isVisible())
453 {
454 ui->treeViewer->hide();
455 ui->treeButton->setText("Show ChronoSync Tree");
456 }
457 else
458 {
459 ui->treeViewer->show();
460 ui->treeButton->setText("Hide ChronoSync Tree");
461 }
462
463 fitView();
464}
465
466void ChatDialog::disableTreeDisplay()
467{
468 ui->treeButton->setEnabled(false);
469 ui->treeViewer->hide();
470 fitView();
471}
472
473void ChatDialog::enableTreeDisplay()
474{
475 ui->treeButton->setEnabled(true);
476 // treeViewer->show();
477 // fitView();
478}
479
480void
481ChatDialog::processTreeUpdateWrapper(const std::vector<Sync::MissingDataInfo> v, Sync::SyncSocket *sock)
482{
483 emit treeUpdated(v);
484 _LOG_DEBUG("<<< Tree update signal emitted");
485}
486
487void
488ChatDialog::processRemoveWrapper(std::string prefix)
489{
490 _LOG_DEBUG("Sync REMOVE signal received for prefix: " << prefix);
491}
492
493void
494ChatDialog::processTreeUpdate(const std::vector<Sync::MissingDataInfo> v)
495{
496 _LOG_DEBUG("<<< processing Tree Update");
497
498 if (v.empty())
499 {
500 return;
501 }
502
503 // reflect the changes on digest tree
504 {
505 boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
506 m_scene->processUpdate(v, m_sock->getRootDigest().c_str());
507 }
508
509 int n = v.size();
510 int totalMissingPackets = 0;
511 for (int i = 0; i < n; i++)
512 {
513 totalMissingPackets += v[i].high.getSeq() - v[i].low.getSeq() + 1;
514 }
515
516 for (int i = 0; i < n; i++)
517 {
518 if (totalMissingPackets < 4)
519 {
520 for (Sync::SeqNo seq = v[i].low; seq <= v[i].high; ++seq)
521 {
522 m_sock->fetchData(v[i].prefix, seq, bind(&ChatDialog::processDataWrapper, this, _1), 2);
523 _LOG_DEBUG("<<< Fetching " << v[i].prefix << "/" <<seq.getSession() <<"/" << seq.getSeq());
524 }
525 }
526 else
527 {
528 m_sock->fetchData(v[i].prefix, v[i].high, bind(&ChatDialog::processDataNoShowWrapper, this, _1), 2);
529 }
530 }
531
532 // adjust the view
533 fitView();
534
535}
536
537void
538ChatDialog::processDataWrapper(ndn::Ptr<ndn::Data> data)
539{
540 string name = data->getName().toUri();
541 const char* buf = data->content().buf();
542 size_t len = data->content().size();
543
544 char *tempBuf = new char[len];
545 memcpy(tempBuf, buf, len);
546 emit dataReceived(name.c_str(), tempBuf, len, true, false);
547 _LOG_DEBUG("<<< " << name << " fetched");
548}
549
550void
551ChatDialog::processDataNoShowWrapper(ndn::Ptr<ndn::Data> data)
552{
553 string name = data->getName().toUri();
554 const char* buf = data->content().buf();
555 size_t len = data->content().size();
556
557 char *tempBuf = new char[len];
558 memcpy(tempBuf, buf, len);
559 emit dataReceived(name.c_str(), tempBuf, len, false, false);
560
561 // if (!m_historyInitialized)
562 // {
563 // fetchHistory(name);
564 // m_historyInitialized = true;
565 // }
566}
567
568// void
569// ChatDialog::fetchHistory(std::string name)
570// {
571
572// /****************************/
573// /* TODO: fix following part */
574// /****************************/
575// string nameWithoutSeq = name.substr(0, name.find_last_of('/'));
576// string prefix = nameWithoutSeq.substr(0, nameWithoutSeq.find_last_of('/'));
577// prefix += "/history";
578// // Ptr<Wrapper>CcnxWrapperPtr handle = boost::make_shared<Sync::CcnxWrapper> ();
579// // QString randomString = getRandomString();
580// // for (int i = 0; i < MAX_HISTORY_ENTRY; i++)
581// // {
582// // QString interest = QString("%1/%2/%3").arg(prefix.c_str()).arg(randomString).arg(i);
583// // handle->sendInterest(interest.toStdString(), bind(&ChatDialog::processDataHistoryWrapper, this, _1, _2, _3));
584// // }
585// }
586
587void
588ChatDialog::processData(QString name, const char *buf, size_t len, bool show, bool isHistory)
589{
590 SyncDemo::ChatMessage msg;
591 bool corrupted = false;
592 if (!msg.ParseFromArray(buf, len))
593 {
594 _LOG_DEBUG("Errrrr.. Can not parse msg with name: " << name.toStdString() << ". what is happening?");
595 // nasty stuff: as a remedy, we'll form some standard msg for inparsable msgs
596 msg.set_from("inconnu");
597 msg.set_type(SyncDemo::ChatMessage::OTHER);
598 corrupted = true;
599 }
600
601 delete [] buf;
602 buf = NULL;
603
604 // display msg received from network
605 // we have to do so; this function is called by ccnd thread
606 // so if we call appendMsg directly
607 // Qt crash as "QObject: Cannot create children for a parent that is in a different thread"
608 // the "cannonical" way to is use signal-slot
609 if (show && !corrupted)
610 {
611 appendMessage(msg, isHistory);
612 }
613
614 if (!isHistory)
615 {
616 // update the tree view
617 std::string stdStrName = name.toStdString();
618 std::string stdStrNameWithoutSeq = stdStrName.substr(0, stdStrName.find_last_of('/'));
619 std::string prefix = stdStrNameWithoutSeq.substr(0, stdStrNameWithoutSeq.find_last_of('/'));
620 _LOG_DEBUG("<<< updating scene for" << prefix << ": " << msg.from());
621 if (msg.type() == SyncDemo::ChatMessage::LEAVE)
622 {
623 processRemove(prefix.c_str());
624 }
625 else
626 {
627 boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
628 m_scene->msgReceived(prefix.c_str(), msg.from().c_str());
629 }
630 }
631 fitView();
632}
633
634void
635ChatDialog::processRemove(QString prefix)
636{
637 _LOG_DEBUG("<<< remove node for prefix" << prefix.toStdString());
638
639 bool removed = m_scene->removeNode(prefix);
640 if (removed)
641 {
642 boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
643 m_scene->plot(m_sock->getRootDigest().c_str());
644 }
645}
646
647void
648ChatDialog::sendJoin()
649{
650 m_joined = true;
651 SyncDemo::ChatMessage msg;
652 formControlMessage(msg, SyncDemo::ChatMessage::JOIN);
653 sendMsg(msg);
654 boost::random::random_device rng;
655 boost::random::uniform_int_distribution<> uniform(1, FRESHNESS / 5 * 1000);
656 m_randomizedInterval = HELLO_INTERVAL * 1000 + uniform(rng);
657 QTimer::singleShot(m_randomizedInterval, this, SLOT(sendHello()));
658}
659
660void
661ChatDialog::sendHello()
662{
663 time_t now = time(NULL);
664 int elapsed = now - m_lastMsgTime;
665 if (elapsed >= m_randomizedInterval / 1000)
666 {
667 SyncDemo::ChatMessage msg;
668 formControlMessage(msg, SyncDemo::ChatMessage::HELLO);
669 sendMsg(msg);
670 boost::random::random_device rng;
671 boost::random::uniform_int_distribution<> uniform(1, FRESHNESS / 5 * 1000);
672 m_randomizedInterval = HELLO_INTERVAL * 1000 + uniform(rng);
673 QTimer::singleShot(m_randomizedInterval, this, SLOT(sendHello()));
674 }
675 else
676 {
677 QTimer::singleShot((m_randomizedInterval - elapsed * 1000), this, SLOT(sendHello()));
678 }
679}
680
681void
682ChatDialog::sendLeave()
683{
684 SyncDemo::ChatMessage msg;
685 formControlMessage(msg, SyncDemo::ChatMessage::LEAVE);
686 sendMsg(msg);
687 usleep(500000);
688 m_sock->remove(m_user.getPrefix().toStdString());
689 usleep(5000);
690 m_joined = false;
691 _LOG_DEBUG("Sync REMOVE signal sent");
692}
693
694void
695ChatDialog::replot()
696{
697 boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
698 m_scene->plot(m_sock->getRootDigest().c_str());
699 fitView();
700}
701
702void
703ChatDialog::summonReaper()
704{
705 Sync::SyncLogic &logic = m_sock->getLogic ();
706 map<string, bool> branches = logic.getBranchPrefixes();
707 QMap<QString, DisplayUserPtr> roster = m_scene->getRosterFull();
708
709 m_zombieList.clear();
710
711 QMapIterator<QString, DisplayUserPtr> it(roster);
712 map<string, bool>::iterator mapIt;
713 while(it.hasNext())
714 {
715 it.next();
716 DisplayUserPtr p = it.value();
717 if (p != DisplayUserNullPtr)
718 {
719 mapIt = branches.find(p->getPrefix().toStdString());
720 if (mapIt != branches.end())
721 {
722 mapIt->second = true;
723 }
724 }
725 }
726
727 for (mapIt = branches.begin(); mapIt != branches.end(); ++mapIt)
728 {
729 // this is zombie. all active users should have been marked true
730 if (! mapIt->second)
731 {
732 m_zombieList.append(mapIt->first.c_str());
733 }
734 }
735
736 m_zombieIndex = 0;
737
738 // start reaping
739 reap();
740}
741
742void
743ChatDialog::reap()
744{
745 if (m_zombieIndex < m_zombieList.size())
746 {
747 string prefix = m_zombieList.at(m_zombieIndex).toStdString();
748 m_sock->remove(prefix);
749 _LOG_DEBUG("Reaped: prefix = " << prefix);
750 m_zombieIndex++;
751 // reap again in 10 seconds
752 QTimer::singleShot(10000, this, SLOT(reap()));
753 }
754}
755
756void
757ChatDialog::updateRosterList(QStringList staleUserList)
758{
759 boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
760 QStringList rosterList = m_scene->getRosterList();
761 m_rosterModel->setStringList(rosterList);
762 QString user;
763 QStringListIterator it(staleUserList);
764 while(it.hasNext())
765 {
766 std::string nick = it.next().toStdString();
767 if (nick.empty())
768 continue;
769
770 SyncDemo::ChatMessage msg;
771 formControlMessage(msg, SyncDemo::ChatMessage::LEAVE);
772 msg.set_from(nick);
773 appendMessage(msg);
774 }
775}
776
777void
778ChatDialog::resizeEvent(QResizeEvent *e)
779{
780 fitView();
781}
782
783void
784ChatDialog::showEvent(QShowEvent *e)
785{
786 fitView();
787}
788
789void
790ChatDialog::fitView()
791{
792 boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
793 QRectF rect = m_scene->itemsBoundingRect();
794 m_scene->setSceneRect(rect);
795 ui->treeViewer->fitInView(m_scene->itemsBoundingRect(), Qt::KeepAspectRatio);
796}
797
798void
799ChatDialog::formChatMessage(const QString &text, SyncDemo::ChatMessage &msg) {
800 msg.set_from(m_user.getNick().toStdString());
801 msg.set_to(m_user.getChatroom().toStdString());
802 msg.set_data(text.toUtf8().constData());
803 time_t seconds = time(NULL);
804 msg.set_timestamp(seconds);
805 msg.set_type(SyncDemo::ChatMessage::CHAT);
806}
807
808void
809ChatDialog::formControlMessage(SyncDemo::ChatMessage &msg, SyncDemo::ChatMessage::ChatMessageType type)
810{
811 msg.set_from(m_user.getNick().toStdString());
812 msg.set_to(m_user.getChatroom().toStdString());
813 time_t seconds = time(NULL);
814 msg.set_timestamp(seconds);
815 msg.set_type(type);
816}
817
818void
819ChatDialog::appendMessage(const SyncDemo::ChatMessage msg, bool isHistory)
820{
821 boost::recursive_mutex::scoped_lock lock(m_msgMutex);
822
823 if (msg.type() == SyncDemo::ChatMessage::CHAT)
824 {
825
826 if (!msg.has_data())
827 {
828 return;
829 }
830
831 if (msg.from().empty() || msg.data().empty())
832 {
833 return;
834 }
835
836 if (!msg.has_timestamp())
837 {
838 return;
839 }
840
841 // if (m_history.size() == MAX_HISTORY_ENTRY)
842 // {
843 // m_history.dequeue();
844 // }
845
846 // m_history.enqueue(msg);
847
848 QTextCharFormat nickFormat;
849 nickFormat.setForeground(Qt::darkGreen);
850 nickFormat.setFontWeight(QFont::Bold);
851 nickFormat.setFontUnderline(true);
852 nickFormat.setUnderlineColor(Qt::gray);
853
854 QTextCursor cursor(ui->textEdit->textCursor());
855 cursor.movePosition(QTextCursor::End);
856 QTextTableFormat tableFormat;
857 tableFormat.setBorder(0);
858 QTextTable *table = cursor.insertTable(1, 2, tableFormat);
859 QString from = QString("%1 ").arg(msg.from().c_str());
860 QTextTableCell fromCell = table->cellAt(0, 0);
861 fromCell.setFormat(nickFormat);
862 fromCell.firstCursorPosition().insertText(from);
863
864 time_t timestamp = msg.timestamp();
865 printTimeInCell(table, timestamp);
866
867 QTextCursor nextCursor(ui->textEdit->textCursor());
868 nextCursor.movePosition(QTextCursor::End);
869 table = nextCursor.insertTable(1, 1, tableFormat);
870 table->cellAt(0, 0).firstCursorPosition().insertText(QString::fromUtf8(msg.data().c_str()));
871 if (!isHistory)
872 {
873 showMessage(from, QString::fromUtf8(msg.data().c_str()));
874 }
875 }
876
877 if (msg.type() == SyncDemo::ChatMessage::JOIN || msg.type() == SyncDemo::ChatMessage::LEAVE)
878 {
879 QTextCharFormat nickFormat;
880 nickFormat.setForeground(Qt::gray);
881 nickFormat.setFontWeight(QFont::Bold);
882 nickFormat.setFontUnderline(true);
883 nickFormat.setUnderlineColor(Qt::gray);
884
885 QTextCursor cursor(ui->textEdit->textCursor());
886 cursor.movePosition(QTextCursor::End);
887 QTextTableFormat tableFormat;
888 tableFormat.setBorder(0);
889 QTextTable *table = cursor.insertTable(1, 2, tableFormat);
890 QString action;
891 if (msg.type() == SyncDemo::ChatMessage::JOIN)
892 {
893 action = "enters room";
894 }
895 else
896 {
897 action = "leaves room";
898 }
899
900 QString from = QString("%1 %2 ").arg(msg.from().c_str()).arg(action);
901 QTextTableCell fromCell = table->cellAt(0, 0);
902 fromCell.setFormat(nickFormat);
903 fromCell.firstCursorPosition().insertText(from);
904
905 time_t timestamp = msg.timestamp();
906 printTimeInCell(table, timestamp);
907 }
908
909 QScrollBar *bar = ui->textEdit->verticalScrollBar();
910 bar->setValue(bar->maximum());
911}
912
913QString
914ChatDialog::formatTime(time_t timestamp)
915{
916 struct tm *tm_time = localtime(&timestamp);
917 int hour = tm_time->tm_hour;
918 QString amOrPM;
919 if (hour > 12)
920 {
921 hour -= 12;
922 amOrPM = "PM";
923 }
924 else
925 {
926 amOrPM = "AM";
927 if (hour == 0)
928 {
929 hour = 12;
930 }
931 }
932
933 char textTime[12];
934 sprintf(textTime, "%d:%02d:%02d %s", hour, tm_time->tm_min, tm_time->tm_sec, amOrPM.toStdString().c_str());
935 return QString(textTime);
936}
937
938void
939ChatDialog::printTimeInCell(QTextTable *table, time_t timestamp)
940{
941 QTextCharFormat timeFormat;
942 timeFormat.setForeground(Qt::gray);
943 timeFormat.setFontUnderline(true);
944 timeFormat.setUnderlineColor(Qt::gray);
945 QTextTableCell timeCell = table->cellAt(0, 1);
946 timeCell.setFormat(timeFormat);
947 timeCell.firstCursorPosition().insertText(formatTime(timestamp));
948}
949
950void
951ChatDialog::showMessage(QString from, QString data)
952{
953 if (!isActiveWindow())
954 {
955 //TODO: Notification to be done
956 // trayIcon->showMessage(QString("Chatroom %1 has a new message").arg(m_user.getChatroom()), QString("<%1>: %2").arg(from).arg(data), QSystemTrayIcon::Information, 20000);
957 // trayIcon->setIcon(QIcon(":/images/note.png"));
958 }
959}
960
961void
962ChatDialog::sendMsg(SyncDemo::ChatMessage &msg)
963{
964 // send msg
965 size_t size = msg.ByteSize();
966 char *buf = new char[size];
967 msg.SerializeToArray(buf, size);
968 if (!msg.IsInitialized())
969 {
970 _LOG_DEBUG("Errrrr.. msg was not probally initialized "<<__FILE__ <<":"<<__LINE__<<". what is happening?");
971 abort();
972 }
973 m_sock->publishData(m_user.getPrefix().toStdString(), m_session, buf, size, FRESHNESS);
974
975 delete buf;
976
977 m_lastMsgTime = time(NULL);
978
979 int nextSequence = m_sock->getNextSeq(m_user.getPrefix().toStdString(), m_session);
980 Sync::MissingDataInfo mdi = {m_user.getPrefix().toStdString(), Sync::SeqNo(0), Sync::SeqNo(nextSequence - 1)};
981 std::vector<Sync::MissingDataInfo> v;
982 v.push_back(mdi);
983 {
984 boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
985 m_scene->processUpdate(v, m_sock->getRootDigest().c_str());
986 m_scene->msgReceived(m_user.getPrefix(), m_user.getNick());
987 }
988}
989
990void
991ChatDialog::openInviteListDialog()
992{
993 m_inviteListDialog->setInviteLabel(m_chatroomPrefix.toUri());
994 m_inviteListDialog->show();
995}
996
997void
998ChatDialog::sendInvitationWrapper(QString invitee, bool isIntroducer)
999{
1000 ndn::Name inviteeNamespace(invitee.toUtf8().constData());
1001 ndn::Ptr<ContactItem> inviteeItem = m_contactManager->getContact(inviteeNamespace);
1002 sendInvitation(inviteeItem, isIntroducer);
1003}
1004
Yingdi Yu42372442013-11-06 18:43:31 -08001005void
1006ChatDialog::closeEvent(QCloseEvent *e)
1007{
1008 hide();
1009 _LOG_DEBUG("about to leave 1");
1010 emit closeChatDialog(m_chatroomPrefix);
1011}
1012
1013
1014
Yingdi Yu42f66462013-10-31 17:38:22 -07001015
Yingdi Yu04842232013-10-23 14:03:09 -07001016#if WAF
1017#include "chatdialog.moc"
1018#include "chatdialog.cpp.moc"
1019#endif