-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathSIPCall.cpp
More file actions
722 lines (583 loc) · 21 KB
/
SIPCall.cpp
File metadata and controls
722 lines (583 loc) · 21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
#include <QLoggingCategory>
#include <QRegularExpression>
#include <QUrl>
#include <qurlquery.h>
#include "SIPCall.h"
#include "SIPCallManager.h"
#include "SIPAccount.h"
#include "AudioManager.h"
#include "ResponseLoader.h"
#include "RingToneFactory.h"
#include "RingTone.h"
#include "EnumTranslation.h"
#include "CallHistory.h"
#include "CallHistoryItem.h"
#include "NumberStats.h"
#include "IMHandler.h"
#include "media/Sniffer.h"
#include "ViewHelper.h"
#include "Notification.h"
#include "NotificationManager.h"
#include "AvatarManager.h"
#include "GlobalCallState.h"
#include "pjsua-lib/pjsua.h"
Q_LOGGING_CATEGORY(lcSIPCall, "gonnect.sip.call")
using namespace std::chrono_literals;
SIPCall::SIPCall(SIPAccount *account, int callId, const QString &contactId, bool silent)
: ICallState(account),
pj::Call(*account, callId),
m_account(account),
m_isSilent(silent),
m_contactId(contactId)
{
auto &sipCallManager = SIPCallManager::instance();
sipCallManager.addCall(this);
m_imHandler = new IMHandler(this);
connect(m_imHandler, &IMHandler::capabilitiesChanged, this, &SIPCall::capabilitiesChanged);
connect(m_imHandler, &IMHandler::meetingRequested, [](const QString &accountId, int callId) {
SIPCallManager::instance().triggerCapability(accountId, callId, "jitsi:openMeeting");
});
// Initialize basic call info
// This can only be done here for incoming calls, because an outgoing call has its infos not set
// yet. But incoming calls must be treated here to check whether the contact/number is blocked
if (callId >= 0) {
const pj::CallInfo ci = getInfo();
const auto remoteUri = QString::fromStdString(ci.remoteUri);
if (!m_isSilent && !m_historyItem) {
setContactInfo(remoteUri, ci.role != PJSIP_ROLE_UAC);
updateIsBlocked();
}
}
connect(this, &SIPCall::isBlockedChanged, this,
[this]() { Q_EMIT SIPCallManager::instance().isBlockedChanged(this); });
connect(&sipCallManager, &SIPCallManager::blocksChanged, this, &SIPCall::updateIsBlocked);
// Forward muted state to ICallState
connect(&AudioManager::instance(), &AudioManager::isAudioCaptureMutedChanged, this,
&SIPCall::updateMutedState);
updateMutedState();
if (!silent) {
auto &globalCallState = GlobalCallState::instance();
Q_EMIT globalCallState.callStarted(false);
if (callId < 0) { // Call is outgoing
globalCallState.holdAllCalls(this);
}
}
m_callDelayCycleTimer.setInterval(10s);
connect(&m_callDelayCycleTimer, &QTimer::timeout, this, [this]() {
QString digit = QString("%1").arg((m_callDelayCounter % 9) + 1);
m_callDelayCounter++;
requestCallDelay(digit);
});
connect(this, &SIPCall::capabilitiesChanged, [this]() {
if (m_imHandler->dtmfDebugEnabled() && isEstablished()
&& !m_callDelayCycleTimer.isActive()) {
m_callDelayCycleTimer.start();
}
});
}
SIPCall::~SIPCall()
{
if (m_isEmergencyCall) {
Q_EMIT ViewHelper::instance().hideEmergency();
}
auto &ringToneFactory = RingToneFactory::instance();
if (m_incoming) {
ringToneFactory.zipTone()->stop();
} else {
ringToneFactory.ringingTone()->stop();
}
if (m_historyItem && m_wasEstablished) {
m_historyItem->endCall();
}
qDeleteAll(m_metadata);
m_metadata.clear();
SIPCallManager::instance().removeCall(this);
Q_EMIT GlobalCallState::instance().callEnded(false);
GlobalCallState::instance().unholdOtherCall();
}
void SIPCall::call(const QString &dst_uri, const pj::CallOpParam &prm)
{
// Extract "," DTMF string and store them for later playback
m_postTask = dst_uri.section(',', 1, -1, QString::SectionIncludeLeadingSep);
makeCall(dst_uri.toStdString(), prm);
}
void SIPCall::onCallState(pj::OnCallStateParam &prm)
{
Q_UNUSED(prm)
if (!m_managerNotified) {
SIPCallManager::instance().updateCallCount();
m_managerNotified = true;
}
const pj::CallInfo ci = getInfo();
const auto remoteUri = QString::fromStdString(ci.remoteUri);
if (!m_isSilent && !m_historyItem) {
setContactInfo(remoteUri, ci.role != PJSIP_ROLE_UAC);
updateIsBlocked();
}
auto &ringToneFactory = RingToneFactory::instance();
const auto statusCode = ci.lastStatusCode;
qCInfo(lcSIPCall).nospace() << "Call State: " << ci.stateText << " (" << remoteUri << ")"
<< " last status code: "
<< EnumTranslation::instance().sipStatusCode(statusCode) << " ("
<< statusCode << ") "
<< " last reason " << ci.lastReason << " contactId " << m_contactId;
switch (ci.state) {
case PJSIP_INV_STATE_NULL:
if (!m_isSilent) {
setCallState(ICallState::State::Idle);
ringToneFactory.ringingTone()->stop();
ringToneFactory.zipTone()->stop();
}
break;
case PJSIP_INV_STATE_CONNECTING:
case PJSIP_INV_STATE_CALLING:
if (!m_isSilent && !m_incoming) {
ringToneFactory.ringingTone()->start();
addCallState(ICallState::State::RingingOutgoing);
}
break;
case PJSIP_INV_STATE_INCOMING:
if (!m_isSilent && !m_incoming) {
if (!isEmergencyCall()
&& (GlobalCallState::instance().globalCallState()
& ICallState::State::CallActive)) {
addCallState(ICallState::State::KnockingIncoming);
ringToneFactory.zipTone()->start();
} else {
addCallState(ICallState::State::RingingIncoming);
ringToneFactory.ringingTone()->start();
}
}
break;
case PJSIP_INV_STATE_EARLY:
if (m_incoming) {
if (GlobalCallState::instance().globalCallState() & ICallState::State::CallActive) {
addCallState(ICallState::State::KnockingIncoming);
ringToneFactory.zipTone()->start();
} else {
addCallState(ICallState::State::RingingIncoming);
}
}
if (!m_isSilent && !m_incoming) {
m_wasEstablished = true;
m_earlyCallState = true;
Q_EMIT earlyCallStateChanged();
}
break;
case PJSIP_INV_STATE_CONFIRMED:
if (!m_isSilent) {
removeCallState(ICallState::State::RingingIncoming
| ICallState::State::KnockingIncoming);
removeCallState(ICallState::State::RingingOutgoing);
addCallState(ICallState::State::CallActive | ICallState::State::AudioActive);
ringToneFactory.ringingTone()->stop();
ringToneFactory.zipTone()->stop();
m_isEstablished = true;
m_wasEstablished = true;
m_establishedTime = QDateTime::currentDateTime();
if (isEmergencyCall()) {
Q_EMIT ViewHelper::instance().hideEmergency();
}
Q_EMIT establishedChanged();
m_earlyCallState = false;
Q_EMIT earlyCallStateChanged();
if (m_account && m_account->isInstantMessagingAllowed()) {
if (!m_imHandler->capabilitiesSent()) {
QTimer::singleShot(2s, this, [this]() { m_imHandler->sendCapabilities(); });
}
}
createOngoingCallNotification();
// Propagate already existing hold state that was set during ringing phase.
// For some reason, a direct hold() produces a pjsip error, hence the timer.
QTimer::singleShot(1ms, this, [this]() {
if (isHolding()) {
hold();
}
});
}
// Send DTMF post tasks if present
if (!m_postTask.isEmpty()) {
auto &cm = SIPCallManager::instance();
QString task = m_postTask;
cm.sendDtmf(m_account->id(), getId(), task);
m_postTask = "";
}
break;
case PJSIP_INV_STATE_DISCONNECTED:
if (!m_isEstablished && m_incoming) {
Q_EMIT missed();
}
qCInfo(lcSIPCall).nospace() << "Call state disconnected, reason: " << ci.lastReason << ", "
<< EnumTranslation::instance().sipStatusCode(statusCode) << " ("
<< statusCode << ")";
ringToneFactory.zipTone()->stop();
ringToneFactory.ringingTone()->stop();
if (!m_isSilent) {
setCallState(ICallState::State::Idle | (callState() & ICallState::State::Migrating));
if (m_isEstablished) {
ringToneFactory.endTone()->start();
}
if (!m_incoming) {
if (statusCode == PJSIP_SC_BUSY_HERE) {
ringToneFactory.busyTone()->start(5);
} else if (static_cast<int>(statusCode) >= 400
&& static_cast<int>(statusCode) < 700) {
ringToneFactory.congestionTone()->start(5);
}
}
}
if (isEmergencyCall()) {
Q_EMIT ViewHelper::instance().hideEmergency();
}
m_account->removeCall(this);
m_isEstablished = false;
m_earlyCallState = false;
if (m_imHandler->dtmfDebugEnabled() && m_callDelayCycleTimer.isActive()) {
m_callDelayCycleTimer.stop();
}
break;
default:
break;
}
qCInfo(lcSIPCall) << "Emitting call state of call" << getId() << "and status" << statusCode;
Q_EMIT SIPCallManager::instance().callState(getId(), statusCode);
}
void SIPCall::onCallMediaState(pj::OnCallMediaStateParam &prm)
{
Q_UNUSED(prm);
auto &audManager = AudioManager::instance();
pj::CallInfo ci = getInfo();
pj::AudioMedia aud_med;
pj::AudioMedia &speaker_media = audManager.getPlaybackDevMedia();
pj::AudioMedia &mic_media = audManager.getCaptureDevMedia();
for (unsigned i = 0; i < ci.media.size(); ++i) {
const auto &mediaInfo = ci.media[i];
if (mediaInfo.type == PJMEDIA_TYPE_AUDIO) {
switch (mediaInfo.status) {
case PJSUA_CALL_MEDIA_NONE:
break;
case PJSUA_CALL_MEDIA_LOCAL_HOLD:
break;
case PJSUA_CALL_MEDIA_ACTIVE:
case PJSUA_CALL_MEDIA_REMOTE_HOLD: {
if (!m_isSilent) {
addCallState(ICallState::State::CallActive | ICallState::State::AudioActive);
removeCallState(ICallState::State::RingingIncoming
| ICallState::State::KnockingIncoming);
RingToneFactory::instance().ringingTone()->stop();
RingToneFactory::instance().zipTone()->stop();
qCInfo(lcSIPCall) << "Found media, index" << i << "of" << ci.media.size();
aud_med = getAudioMedia(i);
mic_media.startTransmit(aud_med);
aud_med.startTransmit(speaker_media);
auto sniffer = new Sniffer(this);
sniffer->initialize();
aud_med.startTransmit(dynamic_cast<pj::AudioMediaPort &>(*sniffer));
connect(sniffer, &Sniffer::audioLevelChanged, this, [this, sniffer]() {
Q_EMIT SIPCallManager::instance().audioLevelChanged(this,
sniffer->audioLevel());
});
}
break;
}
case PJSUA_CALL_MEDIA_ERROR:
break;
}
}
}
}
void SIPCall::onInstantMessage(pj::OnInstantMessageParam &prm)
{
m_imHandler->process(QString::fromStdString(prm.contentType),
QString::fromStdString(prm.msgBody));
}
void SIPCall::onInstantMessageStatus(pj::OnInstantMessageStatusParam &prm)
{
if (prm.code >= 200 && prm.code < 300) {
return;
}
qCWarning(lcSIPCall) << "failed to send message:" << prm.code << prm.reason;
}
void SIPCall::onDtmfDigit(pj::OnDtmfDigitParam &prm)
{
// INFO: Currently only used for DTMF call latency debugging
setCallDelayRx(QDateTime::currentMSecsSinceEpoch(), QString::fromStdString(prm.digit));
}
void SIPCall::onCallTsxState(pj::OnCallTsxStateParam &prm)
{
const auto header = QString::fromStdString(prm.e.body.tsxState.src.rdata.wholeMsg);
if (header.startsWith("UPDATE")) {
static const QRegularExpression regex("P-Asserted-Identity: (?<identity>.*?)(\\r\\n?|\\n)");
const auto matchResult = regex.match(header);
if (matchResult.hasMatch()) {
const QString newIdentity = matchResult.captured("identity");
const pj::CallInfo ci = getInfo();
setContactInfo(newIdentity, ci.role != PJSIP_ROLE_UAC);
qCDebug(lcSIPCall) << "New call participant identity found:" << newIdentity;
}
}
}
pj::AudioMedia *SIPCall::audioMedia() const
{
const auto callInfo = getInfo();
for (unsigned i = 0; i < callInfo.media.size(); ++i) {
if (callInfo.media[i].type == PJMEDIA_TYPE_AUDIO) {
return static_cast<pj::AudioMedia *>(getMedia(i));
}
}
return nullptr;
}
bool SIPCall::hold()
{
pj::CallOpParam op(true);
setIsHolding(true);
try {
setHold(op);
} catch (pj::Error &err) {
qCWarning(lcSIPCall) << "failed to hold call:" << err.info();
return false;
}
return true;
}
bool SIPCall::unhold()
{
pj::CallOpParam op(true);
op.opt.flag = PJSUA_CALL_UNHOLD;
setIsHolding(false);
try {
reinvite(op);
} catch (pj::Error &err) {
qCWarning(lcSIPCall) << "failed to un-hold call:" << err.info();
return false;
}
return true;
}
void SIPCall::accept()
{
if (isEstablished()) {
qCCritical(lcSIPCall) << "Cannot accept call that is already established";
return;
}
if (m_hasAccepted) {
qCWarning(lcSIPCall) << "Call has already been accepted";
return;
}
if (m_hasRejected) {
qCWarning(lcSIPCall) << "Call has already been rejected";
return;
}
m_hasAccepted = true;
pj::CallOpParam prm;
prm.statusCode = PJSIP_SC_OK;
answer(prm);
}
void SIPCall::reject()
{
if (isEstablished()) {
qCCritical(lcSIPCall) << "Cannot reject call that is already established";
return;
}
if (m_hasAccepted) {
qCWarning(lcSIPCall) << "Call has already been accepted";
return;
}
if (m_hasRejected) {
qCWarning(lcSIPCall) << "Call has already been rejected";
return;
}
m_hasRejected = true;
pj::CallOpParam prm;
prm.statusCode = PJSIP_SC_DECLINE;
answer(prm);
}
void SIPCall::toggleHoldImpl()
{
if (m_isHolding) {
unhold();
} else {
hold();
}
}
void SIPCall::setIsHolding(bool value)
{
if (m_isHolding != value) {
if (!value && !SIPCallManager::instance().isConferenceMode()) {
GlobalCallState::instance().holdAllCalls(this);
}
m_isHolding = value;
Q_EMIT isHoldingChanged();
}
}
void SIPCall::setIsBlocked(bool value)
{
if (m_isBlocked != value) {
m_isBlocked = value;
Q_EMIT isBlockedChanged();
}
}
void SIPCall::setContactInfo(const QString &sipUrl, bool isIncoming)
{
if (m_sipUrl != sipUrl) {
m_sipUrl = sipUrl;
if (m_historyItem && m_wasEstablished) {
m_historyItem->endCall();
}
m_contactInfo = PhoneNumberUtil::instance().contactInfoBySipUrl(sipUrl);
m_isEmergencyCall = PhoneNumberUtil::isEmergencyCallUrl(sipUrl);
m_contactId = m_contactInfo.contact ? m_contactInfo.contact->id() : "";
if (!m_contactInfo.isAnonymous) {
NumberStats::instance().incrementCallCount(m_contactInfo.phoneNumber);
}
updateIsBlocked();
typedef CallHistoryItem::Type Type;
CallHistoryItem::Types historyType = Type::SIPCall;
if (isBlocked()) {
historyType |= Type::IncomingBlocked;
} else if (!isIncoming) {
historyType |= Type::Outgoing;
}
m_historyItem = CallHistory::instance().addHistoryItem(historyType, m_account->id(), sipUrl,
m_contactId,
m_contactInfo.isSipSubscriptable);
Q_EMIT contactChanged();
}
}
void SIPCall::updateIsBlocked()
{
bool isBlocked = false;
const auto &callManager = SIPCallManager::instance();
if (!m_contactId.isEmpty()) {
isBlocked = callManager.isContactBlocked(m_contactId);
}
if (!isBlocked) {
const auto contactInfo = PhoneNumberUtil::instance().contactInfoBySipUrl(m_sipUrl);
if (!contactInfo.isAnonymous) {
isBlocked = callManager.isPhoneNumberBlocked(contactInfo.phoneNumber);
}
}
setIsBlocked(isBlocked);
}
void SIPCall::updateMutedState()
{
qt_noop();
}
bool SIPCall::hasCapability(const QString &capability) const
{
return m_imHandler->hasCapability(capability);
}
bool SIPCall::triggerCapability(const QString &capability)
{
if (m_account && m_account->isInstantMessagingAllowed()) {
if (capability.startsWith("jitsi")) {
addCallState(ICallState::State::Migrating);
}
return m_imHandler->triggerCapability(capability, m_historyItem);
}
return false;
}
bool SIPCall::isEmergencyCall() const
{
return m_isEmergencyCall;
}
void SIPCall::onCallTransferRequest(pj::OnCallTransferRequestParam &prm)
{
/* Create new Call for call transfer */
prm.newCall = new SIPCall(m_account);
// TODO: account calls[]?
}
void SIPCall::onCallReplaceRequest(pj::OnCallReplaceRequestParam &prm)
{
/* Create new Call for call replace */
prm.newCall = new SIPCall(m_account);
// TODO: account calls[]?
}
void SIPCall::createOngoingCallNotification()
{
pj::CallInfo ci = getInfo();
// Create notification text
const auto contactInfo =
PhoneNumberUtil::instance().contactInfoBySipUrl(QString::fromStdString(ci.remoteUri));
const Contact *c = contactInfo.contact;
QStringList bodyParts;
const QString title =
tr("Active call with %1")
.arg((c && !c->name().isEmpty()) ? c->name() : contactInfo.phoneNumber);
if (c && !c->company().isEmpty()) {
bodyParts.append(c->company());
}
auto countries = contactInfo.countries;
if (!contactInfo.city.isEmpty()) {
countries.push_front(contactInfo.city);
}
if (countries.size()) {
bodyParts.append(countries.join(", "));
}
auto n = new Notification(title, bodyParts.join("\n"), Notification::Priority::normal, this);
auto &am = AvatarManager::instance();
QString avatar = c ? am.avatarPathFor(c->id()) : "";
if (avatar.isEmpty()) {
n->setIcon("call-incoming-symbolic");
} else {
n->setIcon(avatar);
n->setRoundedIcon(true);
}
n->setDisplayHint(Notification::tray | Notification::hideContentOnLockScreen);
n->setCategory("call.ongoing");
n->addButton(tr("Hang up"), "hangup", "call.hang-up", {});
QString ref = NotificationManager::instance().add(n);
connect(n, &Notification::actionInvoked, this, [this, ref](QString action, QVariantList) {
if (action == "hangup") {
NotificationManager::instance().remove(ref);
pj::CallOpParam prm;
prm.statusCode = PJSIP_SC_OK;
hangup(prm);
}
});
}
void SIPCall::addMetadata(const QString &data)
{
ResponseLoader loader(data);
m_metadata = loader.loadResponse();
if (!m_metadata.empty()) {
m_hasMetadata = true;
}
Q_EMIT metadataChanged();
}
void SIPCall::requestCallDelay(QString digit)
{
// DMTF
QString timestamp = QString("%1").arg(QDateTime::currentMSecsSinceEpoch());
auto &cm = SIPCallManager::instance();
cm.sendDtmf(m_account->id(), getId(), digit);
// IM
pj::SendInstantMessageParam prm;
prm.contentType = "application/x-www-form-urlencoded";
QUrlQuery q;
q.addQueryItem("timestamp", timestamp);
q.addQueryItem("digit", digit);
QUrl delayUrl("gonnect:");
delayUrl.setPath("callDelay");
delayUrl.setQuery(q);
prm.content = delayUrl.toString().toStdString();
try {
sendInstantMessage(prm);
} catch (pj::Error &err) {
qCWarning(lcSIPCall) << "failed to send call delay data:" << err.info();
}
}
void SIPCall::setCallDelayTx(qint64 timestamp, QString digit)
{
m_callDelayTx.first = timestamp;
m_callDelayTx.second = digit;
}
void SIPCall::setCallDelayRx(qint64 timestamp, QString digit)
{
m_callDelayRx.first = timestamp;
m_callDelayRx.second = digit;
if (m_callDelayRx.second != m_callDelayTx.second) {
m_callDelay = -1;
} else {
m_callDelay = m_callDelayRx.first - m_callDelayTx.first;
}
Q_EMIT callDelayChanged();
}