RingD.cpp 50.7 KB
Newer Older
1
/**************************************************************************
atraczyk's avatar
atraczyk committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
* Copyright (C) 2016 by Savoir-faire Linux                                *
* Author: Jäger Nicolas <nicolas.jager@savoirfairelinux.com>              *
* Author: Traczyk Andreas <traczyk.andreas@savoirfairelinux.com>          *
*                                                                         *
* This program is free software; you can redistribute it and/or modify    *
* it under the terms of the GNU General Public License as published by    *
* the Free Software Foundation; either version 3 of the License, or       *
* (at your option) any later version.                                     *
*                                                                         *
* This program is distributed in the hope that it will be useful,         *
* but WITHOUT ANY WARRANTY; without even the implied warranty of          *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           *
* GNU General Public License for more details.                            *
*                                                                         *
* You should have received a copy of the GNU General Public License       *
* along with this program.  If not, see <http://www.gnu.org/licenses/>.   *
**************************************************************************/
#include "pch.h"

Nicolas Jager's avatar
Nicolas Jager committed
21
22
/* daemon */
#include <dring.h>
Nicolas Jager's avatar
Nicolas Jager committed
23
24
#include "dring/call_const.h"

atraczyk's avatar
atraczyk committed
25
26
27
#include "callmanager_interface.h"
#include "configurationmanager_interface.h"
#include "presencemanager_interface.h"
atraczyk's avatar
atraczyk committed
28
#include "videomanager_interface.h"
atraczyk's avatar
atraczyk committed
29
30
#include "fileutils.h"
#include "account_schema.h"
atraczyk's avatar
atraczyk committed
31
#include "account_const.h"
32
#include "string_utils.h" // used to get some const expr like TRUE_STR
33
#include "gnutls\gnutls.h"
34
#include "media_const.h" // used to get some const expr like MEDIA_TYPE_VIDEO
atraczyk's avatar
atraczyk committed
35
36
37
38
39
40

#include "SmartPanel.xaml.h"

using namespace Windows::ApplicationModel::Core;
using namespace Windows::Storage;
using namespace Windows::UI::Core;
atraczyk's avatar
atraczyk committed
41
42
43
using namespace Windows::Media;
using namespace Windows::Media::MediaProperties;
using namespace Windows::Media::Capture;
44
using namespace Windows::System::Threading;
atraczyk's avatar
atraczyk committed
45
46
47

using namespace RingClientUWP;
using namespace RingClientUWP::Utils;
Nicolas Jager's avatar
Nicolas Jager committed
48
using namespace RingClientUWP::ViewModel;
atraczyk's avatar
atraczyk committed
49

atraczyk's avatar
atraczyk committed
50
51
using namespace Windows::System;

atraczyk's avatar
atraczyk committed
52
53
54
void
RingClientUWP::RingD::reloadAccountList()
{
55
    //RingClientUWP::ViewModel::AccountsViewModel::instance->clearAccountList();
Nicolas Jager's avatar
Nicolas Jager committed
56

atraczyk's avatar
atraczyk committed
57
    std::vector<std::string> accountList = DRing::getAccountList();
58
59
60
61
62
63
64

    /* if for any reason there is no account at all, screen the wizard */
    if (accountList.size() == 0) {
        summonWizard();
        return;
    }

atraczyk's avatar
atraczyk committed
65
    std::vector<std::string>::reverse_iterator rit = accountList.rbegin();
Nicolas Jager's avatar
Nicolas Jager committed
66

atraczyk's avatar
atraczyk committed
67
68
    for (; rit != accountList.rend(); ++rit) {
        std::map<std::string,std::string> accountDetails = DRing::getAccountDetails(*rit);
69

70
        auto type = accountDetails.find(DRing::Account::ConfProperties::TYPE)->second;
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
        if (type == "RING") {
            auto  ringID = accountDetails.find(DRing::Account::ConfProperties::USERNAME)->second;
            if (!ringID.empty())
                ringID = ringID.substr(5);

            bool upnpState = (accountDetails.find(DRing::Account::ConfProperties::UPNP_ENABLED)->second == ring::TRUE_STR)
                             ? true
                             : false;
            auto alias = accountDetails.find(DRing::Account::ConfProperties::ALIAS)->second;
            auto deviceId = accountDetails.find(DRing::Account::ConfProperties::RING_DEVICE_ID)->second;
            auto accountId = *rit;

            auto account = AccountsViewModel::instance->findItem(Utils::toPlatformString(accountId));

            if (account) {
                account->name_ = Utils::toPlatformString(alias);
                account->_upnpState = upnpState;
                account->accountType_ = Utils::toPlatformString(type);
                account->ringID_ = Utils::toPlatformString(ringID);
                accountUpdated(account);
            }
            else {
93
94
                if (!ringID.empty())
                    RingClientUWP::ViewModel::AccountsViewModel::instance->addRingAccount(alias, ringID, accountId, deviceId, upnpState);
95
            }
96
        }
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
        else { /* SIP */
            auto alias = accountDetails.find(DRing::Account::ConfProperties::ALIAS)->second;
            auto accountId = *rit;
            auto sipHostname = accountDetails.find(DRing::Account::ConfProperties::HOSTNAME)->second;
            auto sipUsername = accountDetails.find(DRing::Account::ConfProperties::USERNAME)->second;
            auto sipPassword = accountDetails.find(DRing::Account::ConfProperties::PASSWORD)->second;

            auto account = AccountsViewModel::instance->findItem(Utils::toPlatformString(accountId));

            if (account) {
                account->name_ = Utils::toPlatformString(alias);
                account->accountType_ = Utils::toPlatformString(type);
                account->_sipHostname = Utils::toPlatformString(sipHostname);
                account->_sipUsername = Utils::toPlatformString(sipUsername);
                account->_sipPassword = Utils::toPlatformString(sipPassword);
                accountUpdated(account);
            }
            else {
                RingClientUWP::ViewModel::AccountsViewModel::instance->addSipAccount(alias, accountId, sipHostname, sipUsername, sipPassword);
            }
117

118
119
            sipPassword = ""; // avoid to keep password in memory
        }
atraczyk's avatar
atraczyk committed
120
    }
Nicolas Jager's avatar
Nicolas Jager committed
121

atraczyk's avatar
atraczyk committed
122
123
124
125
    // load user preferences
    Configuration::UserPreferences::instance->load();
}

Nicolas Jager's avatar
Nicolas Jager committed
126
127
128
129
/* nb: send message during conversation not chat video message */
void RingClientUWP::RingD::sendAccountTextMessage(String^ message)
{
    /* account id */
Nicolas Jager's avatar
Nicolas Jager committed
130
    auto accountId = AccountListItemsViewModel::instance->_selectedItem->_account->accountID_;
Nicolas Jager's avatar
Nicolas Jager committed
131
132
133
134
    std::wstring accountId2(accountId->Begin());
    std::string accountId3(accountId2.begin(), accountId2.end());

    /* recipient */
Nicolas Jager's avatar
Nicolas Jager committed
135
136
    auto item = SmartPanelItemsViewModel::instance->_selectedItem;
    auto contact = item->_contact;
Nicolas Jager's avatar
Nicolas Jager committed
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
    auto toRingId = contact->ringID_;
    std::wstring toRingId2(toRingId->Begin());
    std::string toRingId3(toRingId2.begin(), toRingId2.end());

    /* payload(s) */
    std::wstring message2(message->Begin());
    std::string message3(message2.begin(), message2.end());
    std::map<std::string, std::string> payloads;
    payloads["text/plain"] = message3;

    /* daemon */
    auto sent = DRing::sendAccountTextMessage(accountId3, toRingId3, payloads);

    /* conversation */
    if (sent) {
        contact->_conversation->addMessage(""/* date not yet used*/, MSG_FROM_ME, message);
153
154
155
156

        /* save contacts conversation to disk */
        contact->saveConversationToFile();

Nicolas Jager's avatar
Nicolas Jager committed
157
158
159
160
161
    } else {
        WNG_("message not sent, see daemon outputs");
    }
}

162
163
164
165
// send message during video call
void RingClientUWP::RingD::sendSIPTextMessage(String^ message)
{
    /* account id */
Nicolas Jager's avatar
Nicolas Jager committed
166
    auto accountId = AccountListItemsViewModel::instance->_selectedItem->_account->accountID_;
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
    std::wstring accountId2(accountId->Begin());
    std::string accountId3(accountId2.begin(), accountId2.end());

    /* call */
    auto item = SmartPanelItemsViewModel::instance->_selectedItem;
    auto callId = item->_callId;
    std::wstring callId2(callId->Begin());
    std::string callId3(callId2.begin(), callId2.end());

    /* recipient */
    auto contact = item->_contact;

    /* payload(s) */
    std::wstring message2(message->Begin());
    std::string message3(message2.begin(), message2.end());
    std::map<std::string, std::string> payloads;
    payloads["text/plain"] = message3;

    /* daemon */
    DRing::sendTextMessage(callId3, payloads, accountId3, true /*not used*/);
    contact->_conversation->addMessage(""/* date not yet used*/, MSG_FROM_ME, message);
    contact->saveConversationToFile();
}

atraczyk's avatar
atraczyk committed
191
192
193
194
195
196
197
198
199
200
201
202
// send vcard
void RingClientUWP::RingD::sendSIPTextMessageVCF(std::string callID, std::map<std::string, std::string> message)
{
    /* account id */
    auto accountId = AccountListItemsViewModel::instance->_selectedItem->_account->accountID_;
    std::wstring accountId2(accountId->Begin());
    std::string accountId3(accountId2.begin(), accountId2.end());

    /* daemon */
    DRing::sendTextMessage(callID, message, accountId3, true /*not used*/);
}

atraczyk's avatar
atraczyk committed
203
void
Nicolas Jager's avatar
Nicolas Jager committed
204
RingD::createRINGAccount(String^ alias, String^ archivePassword, bool upnp, String^ registeredName)
atraczyk's avatar
atraczyk committed
205
{
206
207
208
209
210
    editModeOn_ = true;

    auto frame = dynamic_cast<Frame^>(Window::Current->Content);
    dynamic_cast<RingClientUWP::MainPage^>(frame->Content)->showLoadingOverlay(true, true);

211
212
213
214
215
    auto task = ref new RingD::Task(Request::AddRingAccount);

    task->_alias = alias;
    task->_password = archivePassword;
    task->_upnp = upnp;
Nicolas Jager's avatar
Nicolas Jager committed
216
    task->_registeredName = registeredName;
217
218

    tasksList_.push(task);
atraczyk's avatar
atraczyk committed
219
220
221
}

void
222
RingD::createSIPAccount(String^ alias, String^ sipPassword, String^ sipHostname, String^ sipusername)
atraczyk's avatar
atraczyk committed
223
{
224
225
226
227
    editModeOn_ = true;

    auto frame = dynamic_cast<Frame^>(Window::Current->Content);

228
229
230
231
232
233
234
235
    auto task = ref new RingD::Task(Request::AddSIPAccount);

    task->_alias = alias;
    task->_sipPassword = sipPassword;
    task->_sipHostname = sipHostname;
    task->_sipUsername = sipusername;

    tasksList_.push(task);
atraczyk's avatar
atraczyk committed
236
237
}

238
void RingClientUWP::RingD::refuseIncommingCall(String^ callId)
239
{
240
    tasksList_.push(ref new RingD::Task(Request::RefuseIncommingCall, callId));
241
242
}

243
void RingClientUWP::RingD::acceptIncommingCall(String^ callId)
244
{
245
    tasksList_.push(ref new RingD::Task(Request::AcceptIncommingCall, callId));
246
247
}

Nicolas Jager's avatar
Nicolas Jager committed
248
249
void RingClientUWP::RingD::placeCall(Contact^ contact)
{
250
    MSG_("!--->> placeCall");
251
252
253

    if (contact->_accountIdAssociated->IsEmpty()) {
        MSG_("adding account id to contact");
254
        contact->_accountIdAssociated = AccountListItemsViewModel::instance->_selectedItem->_account->accountID_;
255
    }
Nicolas Jager's avatar
Nicolas Jager committed
256

257
258
259
260
    auto task = ref new RingD::Task(Request::PlaceCall);
    task->_accountId_new = Utils::toString(contact->_accountIdAssociated);
    task->_ringId_new = Utils::toString(contact->ringID_);
    tasksList_.push(task);
261

262
}
263

264
265
266
267
268
269
void RingClientUWP::RingD::pauseCall(const std::string & callId)
{
    auto task = ref new RingD::Task(Request::PauseCall);
    task->_callid_new = callId;
    tasksList_.push(task);
}
270

271
272
273
274
275
void RingClientUWP::RingD::unPauseCall(const std::string & callId)
{
    auto task = ref new RingD::Task(Request::UnPauseCall);
    task->_callid_new = callId;
    tasksList_.push(task);
276
277
278
279
280
}

void RingClientUWP::RingD::cancelOutGoingCall2(String ^ callId)
{
    MSG_("$1 cancelOutGoingCall2 : " + Utils::toString(callId));
281
    tasksList_.push(ref new RingD::Task(Request::HangUpCall, callId));
Nicolas Jager's avatar
Nicolas Jager committed
282
283
}

284

285
286
287
void RingClientUWP::RingD::hangUpCall2(String ^ callId)
{
    MSG_("$1 hangUpCall2 : "+Utils::toString(callId));
288
    tasksList_.push(ref new RingD::Task(Request::HangUpCall, callId));
289
290
}

291
void RingClientUWP::RingD::pauseCall(String ^ callId) // do not use it, rm during refacto
292
293
294
295
296
{
    MSG_("$1 pauseCall : " + Utils::toString(callId));
    tasksList_.push(ref new RingD::Task(Request::PauseCall, callId));
}

297
void RingClientUWP::RingD::unPauseCall(String ^ callId) // do not use it, rm during refacto
298
299
300
301
302
{
    MSG_("$1 unPauseCall : " + Utils::toString(callId));
    tasksList_.push(ref new RingD::Task(Request::UnPauseCall, callId));
}

Nicolas Jager's avatar
Nicolas Jager committed
303
304
305
306
307
308
309
310
void RingClientUWP::RingD::askToRefreshKnownDevices(String^ accountId)
{
    auto task = ref new RingD::Task(Request::GetKnownDevices);
    task->_accountId = accountId;

    tasksList_.push(task);
}

311
312
313
314
315
316
317
318
319
void RingClientUWP::RingD::askToExportOnRing(String ^ accountId, String ^ password)
{
    auto task = ref new RingD::Task(Request::ExportOnRing);
    task->_accountId = accountId;
    task->_password = password;

    tasksList_.push(task);
}

320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
void RingClientUWP::RingD::eraseCacheFolder()
{
    StorageFolder^ localFolder = ApplicationData::Current->LocalFolder;
    String^ folderName = ".cache";

    task<IStorageItem^>(localFolder->TryGetItemAsync(folderName)).then([this](IStorageItem^ folder)
    {
        if (folder) {
            MSG_("erasing cache folder.");
            folder->DeleteAsync();
        }
        else {
            WNG_("cache folder not found.");
        }
    });
}

337
338
339
340
341
342
343
void RingClientUWP::RingD::updateAccount(String^ accountId)
{
    editModeOn_ = true;

    auto frame = dynamic_cast<Frame^>(Window::Current->Content);

    auto task = ref new RingD::Task(Request::UpdateAccount);
Nicolas Jager's avatar
Nicolas Jager committed
344
    task->_accountId_new = Utils::toString(accountId);
345
346
347
348

    tasksList_.push(task);
}

349
350
351
352
353
354
355
356
357
358
359
360
void RingClientUWP::RingD::deleteAccount(String ^ accountId)
{
    editModeOn_ = true;

    auto frame = dynamic_cast<Frame^>(Window::Current->Content);

    auto task = ref new RingD::Task(Request::DeleteAccount);
    task->_accountId = accountId;

    tasksList_.push(task);
}

361
362
363
364
365
366
367
void RingClientUWP::RingD::registerThisDevice(String ^ pin, String ^ archivePassword)
{
    tasksList_.push(ref new RingD::Task(Request::RegisterDevice, pin, archivePassword));
    archivePassword = "";
    pin = "";
}

atraczyk's avatar
atraczyk committed
368
void
369
RingD::registerCallbacks()
atraczyk's avatar
atraczyk committed
370
{
371
372
373
374
375
376
377
378
379
380
381
382
383
    dispatcher = CoreApplication::MainView->CoreWindow->Dispatcher;

    callHandlers = {
        // use IncomingCall only to register the call client sided, use StateChange to determine the impact on the UI
        DRing::exportable_callback<DRing::CallSignal::IncomingCall>([this](
            const std::string& accountId,
            const std::string& callId,
            const std::string& from)
        {
            MSG_("<IncomingCall>");
            MSG_("accountId = " + accountId);
            MSG_("callId = " + callId);
            MSG_("from = " + from);
384

385
386
387
            auto accountId2 = toPlatformString(accountId);
            auto callId2 = toPlatformString(callId);
            auto from2 = toPlatformString(from);
atraczyk's avatar
atraczyk committed
388

389
390
            /* fix some issue in the daemon --> <...@...> */
            from2 = Utils::TrimRingId(from2);
Nicolas Jager's avatar
Nicolas Jager committed
391

392
393
            CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
                CoreDispatcherPriority::High, ref new DispatchedHandler([=]()
atraczyk's avatar
atraczyk committed
394
            {
395
396
397
                incomingCall(accountId2, callId2, from2);
                stateChange(callId2, CallStatus::INCOMING_RINGING, 0);

Nicolas Jager's avatar
Nicolas Jager committed
398
399
400
401
402
403
                auto contact = ContactsViewModel::instance->findContactByRingId(from2);
                if (contact) {
                    auto item = SmartPanelItemsViewModel::instance->findItem(contact);
                    if (item)
                        item->_callId = callId2;
                }
404
405
            }));
        }),
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
        DRing::exportable_callback<DRing::CallSignal::PeerHold>([this](
                    const std::string& callId,
                    bool state)
        {
            // why this cllaback exist ? why are we not using stateChange ?
            MSG_("<PeerHold>");
            MSG_("callId = " + callId);
            MSG_("state = " + Utils::toString(state.ToString()));

            CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
                CoreDispatcherPriority::High, ref new DispatchedHandler([=]()
            {
                if (state)
                    stateChange(Utils::toPlatformString(callId), CallStatus::PEER_PAUSED, 0);
                else
                    stateChange(Utils::toPlatformString(callId), CallStatus::IN_PROGRESS, 0);
            }));
        }),
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
        DRing::exportable_callback<DRing::CallSignal::AudioMuted>([this](
                    const std::string& callId,
                    bool state)
        {
            // why this cllaback exist ? why are we not using stateChange ?
            MSG_("<AudioMuted>");
            MSG_("callId = " + callId);
            MSG_("state = " + Utils::toString(state.ToString()));

            CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
                CoreDispatcherPriority::High, ref new DispatchedHandler([=]()
            {
                audioMuted(callId, state);
            }));
        }),
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
        DRing::exportable_callback<DRing::CallSignal::VideoMuted>([this](
                    const std::string& callId,
                    bool state)
        {
            // why this cllaback exist ? why are we not using stateChange ?
            MSG_("<VideoMuted>");
            MSG_("callId = " + callId);
            MSG_("state = " + Utils::toString(state.ToString()));

            CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
                CoreDispatcherPriority::High, ref new DispatchedHandler([=]()
            {
                videoMuted(callId, state);
            }));
        }),
454
455
456
457
458
459
460
461
462
        DRing::exportable_callback<DRing::CallSignal::StateChange>([this](
                    const std::string& callId,
                    const std::string& state,
                    int code)
        {
            MSG_("<StateChange>");
            MSG_("callId = " + callId);
            MSG_("state = " + state);
            MSG_("code = " + std::to_string(code));
atraczyk's avatar
atraczyk committed
463

464
465
            auto callId2 = toPlatformString(callId);
            auto state2 = toPlatformString(state);
atraczyk's avatar
atraczyk committed
466

467
            auto state3 = translateCallStatus(state2);
468

atraczyk's avatar
atraczyk committed
469
            if (state3 == CallStatus::OUTGOING_RINGING ||
Nicolas Jager's avatar
Nicolas Jager committed
470
                    state3 == CallStatus::INCOMING_RINGING) {
atraczyk's avatar
atraczyk committed
471
                try {
472
                    //Configuration::UserPreferences::instance->sendVCard(callId);
atraczyk's avatar
atraczyk committed
473
474
475
476
477
478
                }
                catch (Exception^ e) {
                    EXC_(e);
                }
            }

479
480
            if (state3 == CallStatus::ENDED)
                DRing::hangUp(callId); // solve a bug in the daemon API.
481

482
483
            CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
                CoreDispatcherPriority::High, ref new DispatchedHandler([=]()
atraczyk's avatar
atraczyk committed
484
            {
485
486
487
488
489
490
491
492
493
494
495
                stateChange(callId2, state3, code);
            }));
        }),
        DRing::exportable_callback<DRing::ConfigurationSignal::IncomingAccountMessage>([&](
                    const std::string& accountId,
                    const std::string& from,
                    const std::map<std::string, std::string>& payloads)
        {
            MSG_("<IncomingAccountMessage>");
            MSG_("accountId = " + accountId);
            MSG_("from = " + from);
Nicolas Jager's avatar
Nicolas Jager committed
496

497
498
            auto accountId2 = toPlatformString(accountId);
            auto from2 = toPlatformString(from);
499

500
501
502
            for (auto i : payloads) {
                MSG_("payload = " + i.second);
                auto payload = Utils::toPlatformString(i.second);
503
                CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
504
                    CoreDispatcherPriority::High, ref new DispatchedHandler([=]()
505
                {
506
                    incomingAccountMessage(accountId2, from2, payload);
507
                }));
508
509
510
511
512
513
514
515
516
517
            }
        }),
        DRing::exportable_callback<DRing::CallSignal::IncomingMessage>([&](
                    const std::string& callId,
                    const std::string& from,
                    const std::map<std::string, std::string>& payloads)
        {
            MSG_("<IncomingMessage>");
            MSG_("callId = " + callId);
            MSG_("from = " + from);
518

519
520
            auto callId2 = toPlatformString(callId);
            auto from2 = toPlatformString(from);
521

atraczyk's avatar
atraczyk committed
522
            auto item = SmartPanelItemsViewModel::instance->findItem(callId2);
523
524
525
526
527
            Contact^ contact;
            if (item)
                contact = item->_contact;
            else
                WNG_("item not found!");
528

atraczyk's avatar
atraczyk committed
529
            static const unsigned int profileSize = VCardUtils::PROFILE_VCF.size();
530
            for (auto i : payloads) {
atraczyk's avatar
atraczyk committed
531
532
533
534
                if (i.first.compare(0, profileSize, VCardUtils::PROFILE_VCF) == 0) {
                    MSG_("payload.first = " + i.first);
                    MSG_("payload.second = " + i.second);
                    int res = contact->getVCard()->receiveChunk(i.first, i.second);
535
                    return;
atraczyk's avatar
atraczyk committed
536
                }
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551

                auto payload = Utils::toPlatformString(i.second);
                CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
                    CoreDispatcherPriority::High, ref new DispatchedHandler([=]()
                {
                    incomingMessage(callId2, payload);
                }));
            }
        }),
        DRing::exportable_callback<DRing::ConfigurationSignal::RegistrationStateChanged>([this](
                    const std::string& account_id, const std::string& state,
                    int detailsCode, const std::string& detailsStr)
        {
            MSG_("<RegistrationStateChanged>: ID = " + account_id + " state = " + state);
            if (state == DRing::Account::States::REGISTERED) {
552
                CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::High,
Nicolas Jager's avatar
Nicolas Jager committed
553
                ref new DispatchedHandler([=]() {
atraczyk's avatar
atraczyk committed
554
                    reloadAccountList();
555
556
557
558
                    // enleves ce qui suit et utilises des evenements.
                    registrationStateRegistered();
                    // mettre a jour le wizard
                    /*if (editModeOn_) {
559
560
561
                        auto frame = dynamic_cast<Frame^>(Window::Current->Content);
                        dynamic_cast<RingClientUWP::MainPage^>(frame->Content)->showLoadingOverlay(false, false);
                        editModeOn_ = false;
562
                    }*/
563
564
565
566
567
                    setLoadingStatusText("Registration successful", "#ff00ff00");
                }));
            }
            else if (state == DRing::Account::States::TRYING) {
                CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::High,
Nicolas Jager's avatar
Nicolas Jager committed
568
                ref new DispatchedHandler([=]() {
569
                    setLoadingStatusText("Attempting to register account...", "#ff00f0f0");
570
571
                }));
            }
Nicolas Jager's avatar
Nicolas Jager committed
572
573
574
575
576
577
578
579
580
581
            else if (state == DRing::Account::States::ERROR_GENERIC
                     || state == DRing::Account::States::ERROR_AUTH
                     || state == DRing::Account::States::ERROR_NETWORK
                     || state == DRing::Account::States::ERROR_HOST
                     || state == DRing::Account::States::ERROR_CONF_STUN
                     || state == DRing::Account::States::ERROR_EXIST_STUN
                     || state == DRing::Account::States::ERROR_SERVICE_UNAVAILABLE
                     || state == DRing::Account::States::ERROR_NOT_ACCEPTABLE
                     || state == DRing::Account::States::ERROR_NEED_MIGRATION
                     || state == DRing::Account::States::REQUEST_TIMEOUT) {
582
583
584
585
                CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::High,
                ref new DispatchedHandler([=]() {
                    reloadAccountList();
                    registrationStateErrorGeneric(account_id);
586
                    setLoadingStatusText(Utils::toPlatformString("Failed to register account: " + state), "#ffff0000");
587
                    // ajoute cet event dans le wizard
atraczyk's avatar
atraczyk committed
588
                }));
589
590
591
            }
        }),
        DRing::exportable_callback<DRing::ConfigurationSignal::AccountsChanged>([this]()
atraczyk's avatar
atraczyk committed
592
        {
593
594
595
596
            MSG_("<AccountsChanged>");
            CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::High,
            ref new DispatchedHandler([=]() {
                reloadAccountList();
Nicolas Jager's avatar
Nicolas Jager committed
597
                /*if (editModeOn_) {
598
599
600
                    auto frame = dynamic_cast<Frame^>(Window::Current->Content);
                    dynamic_cast<RingClientUWP::MainPage^>(frame->Content)->showLoadingOverlay(false, false);
                    editModeOn_ = false;
Nicolas Jager's avatar
Nicolas Jager committed
601
                }*/
602
603
            }));
        }),
604
        DRing::exportable_callback<DRing::Debug::MessageSend>([&](const std::string& msg)
atraczyk's avatar
atraczyk committed
605
        {
606
            if (debugModeOn_) {
607
                dispatcher->RunAsync(CoreDispatcherPriority::High,
Nicolas Jager's avatar
Nicolas Jager committed
608
                ref new DispatchedHandler([=]() {
609
610
611
612
613
                    std::string displayMsg = msg.substr(56);
                    setLoadingStatusText(Utils::toPlatformString(displayMsg.substr(0,40) + "..."), "#ff000000");
                    DMSG_(msg);
                }));
            }
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
        })
    };
    registerCallHandlers(callHandlers);

    getAppPathHandler =
    {
        DRing::exportable_callback<DRing::ConfigurationSignal::GetAppDataPath>
        ([this](std::vector<std::string>* paths) {
            paths->emplace_back(localFolder_);
        })
    };
    registerCallHandlers(getAppPathHandler);

    getAppUserNameHandler =
    {
        DRing::exportable_callback<DRing::ConfigurationSignal::GetAppUserName>
        ([this](std::vector<std::string>* unames) {
            unames->emplace_back(Utils::toString(
                UserModel::instance->firstName +
                "." +
                UserModel::instance->lastName));
        })
    };
    registerCallHandlers(getAppUserNameHandler);

    incomingVideoHandlers =
    {
        DRing::exportable_callback<DRing::VideoSignal::DeviceEvent>
        ([this]() {
            MSG_("<DeviceEvent>");
        }),
        DRing::exportable_callback<DRing::VideoSignal::DecodingStarted>
        ([&](const std::string &id, const std::string &shmPath, int width, int height, bool isMixer) {
            dispatcher->RunAsync(CoreDispatcherPriority::High,
            ref new DispatchedHandler([=]() {
                Video::VideoManager::instance->rendererManager()->startedDecoding(
                    Utils::toPlatformString(id),
                    width,
                    height);
                auto callId2 = Utils::toPlatformString(id);
                incomingVideoMuted(callId2, false);
            }));
        }),
        DRing::exportable_callback<DRing::VideoSignal::DecodingStopped>
        ([&](const std::string &id, const std::string &shmPath, bool isMixer) {
            dispatcher->RunAsync(CoreDispatcherPriority::High,
            ref new DispatchedHandler([=]() {
                Video::VideoManager::instance->rendererManager()->removeRenderer(Utils::toPlatformString(id));
                auto callId2 = Utils::toPlatformString(id);
                incomingVideoMuted(callId2, true);
            }));
        })
    };
    registerVideoHandlers(incomingVideoHandlers);

    using namespace Video;
    outgoingVideoHandlers =
    {
        DRing::exportable_callback<DRing::VideoSignal::GetCameraInfo>
        ([this](const std::string& device,
        std::vector<std::string> *formats,
        std::vector<unsigned> *sizes,
        std::vector<unsigned> *rates) {
            MSG_("<GetCameraInfo>");
            auto device_list = VideoManager::instance->captureManager()->deviceList;

            for (unsigned int i = 0; i < device_list->Size; i++) {
                auto dev = device_list->GetAt(i);
                if (device == Utils::toString(dev->name())) {
                    Vector<Video::Resolution^>^ resolutions = dev->resolutionList();
                    for (auto res : resolutions) {
                        formats->emplace_back(Utils::toString(res->activeRate()->format()));
                        sizes->emplace_back(res->width());
                        sizes->emplace_back(res->height());
                        for (auto rate : res->rateList()) {
                            rates->emplace_back(rate->value());
atraczyk's avatar
atraczyk committed
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
723
724
725
726
727
728
729
730
            }
        }),
        DRing::exportable_callback<DRing::VideoSignal::SetParameters>
        ([&](const std::string& device,
             std::string format,
             const int width,
             const int height,
        const int rate) {
            dispatcher->RunAsync(CoreDispatcherPriority::High,
            ref new DispatchedHandler([=]() {
                MSG_("<SetParameters>");
                VideoManager::instance->captureManager()->activeDevice->SetDeviceProperties(
                    Utils::toPlatformString(format),width,height,rate);
            }));
        }),
        DRing::exportable_callback<DRing::VideoSignal::StartCapture>
        ([&](const std::string& device) {
            dispatcher->RunAsync(CoreDispatcherPriority::High,
            ref new DispatchedHandler([=]() {
                VideoManager::instance->captureManager()->InitializeCameraAsync(false);
                VideoManager::instance->captureManager()->videoFrameCopyInvoker->Start();
            }));
        }),
        DRing::exportable_callback<DRing::VideoSignal::StopCapture>
        ([&]() {
            dispatcher->RunAsync(CoreDispatcherPriority::High,
            ref new DispatchedHandler([=]() {
                VideoManager::instance->captureManager()->StopPreviewAsync();
                if (VideoManager::instance->captureManager()->captureTaskTokenSource)
                    VideoManager::instance->captureManager()->captureTaskTokenSource->cancel();
                VideoManager::instance->captureManager()->videoFrameCopyInvoker->Stop();
            }));
        })
    };
    registerVideoHandlers(outgoingVideoHandlers);

    nameRegistrationHandlers =
    {
Nicolas Jager's avatar
Nicolas Jager committed
731
732
733
734
        DRing::exportable_callback<DRing::ConfigurationSignal::KnownDevicesChanged>([&](const std::string& accountId, const std::map<std::string, std::string>& devices)
        {
            dispatcher->RunAsync(CoreDispatcherPriority::High,
            ref new DispatchedHandler([=]() {
atraczyk's avatar
atraczyk committed
735
                MSG_("KnownDevicesChanged ---> C PAS FINI");
Nicolas Jager's avatar
Nicolas Jager committed
736
737
738
739
740
741
742
743
744
745
            }));
        }),
        DRing::exportable_callback<DRing::ConfigurationSignal::ExportOnRingEnded>([&](const std::string& accountId, int status, const std::string& pin)
        {
            auto accountId2 = Utils::toPlatformString(accountId);
            auto pin2 = (pin.empty()) ? "Error bad password" : "Your generated pin : " + Utils::toPlatformString(pin);
            dispatcher->RunAsync(CoreDispatcherPriority::High,
            ref new DispatchedHandler([=]() {
                exportOnRingEnded(accountId2, pin2);
            }));
746
747
748
        }),
        DRing::exportable_callback<DRing::ConfigurationSignal::RegisteredNameFound>(
        [this](const std::string &accountId, int status, const std::string &address, const std::string &name) {
Nicolas Jager's avatar
Nicolas Jager committed
749
750
751
752
753
754
            //MSG_("<RegisteredNameFound>" + name + " : " + address + " status=" +std::to_string(status));
            CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::Normal,
            ref new DispatchedHandler([=]() {
                switch (status)
                {
                case 0: // everything went fine. Name/address pair was found.
755
                    registeredNameFound(LookupStatus::SUCCESS, address, name);
Nicolas Jager's avatar
Nicolas Jager committed
756
757
                    break;
                case 1: // provided name is not valid.
758
                    registeredNameFound(LookupStatus::INVALID_NAME, address, name);
Nicolas Jager's avatar
Nicolas Jager committed
759
760
                    break;
                case 2: // everything went fine. Name/address pair was not found.
761
                    registeredNameFound(LookupStatus::NOT_FOUND, address, name);
Nicolas Jager's avatar
Nicolas Jager committed
762
763
                    break;
                case 3: // An error happened
764
                    registeredNameFound(LookupStatus::ERRORR, address, name);
Nicolas Jager's avatar
Nicolas Jager committed
765
766
767
                    break;
                }
            }));
Nicolas Jager's avatar
Nicolas Jager committed
768
769
770
771
772
773
        }),
        DRing::exportable_callback<DRing::ConfigurationSignal::VolatileDetailsChanged>(
        [this](const std::string& accountId, const std::map<std::string, std::string>& details) {
            ref new DispatchedHandler([=]() {
                volatileDetailsChanged(accountId, details);
            });
774
775
776
777
        })
    };
    registerConfHandlers(nameRegistrationHandlers);
}
atraczyk's avatar
atraczyk committed
778

779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
void
RingD::init()
{
    if (daemonInitialized_) {
        CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::Normal,
        ref new DispatchedHandler([=]() {
            finishCaptureDeviceEnumeration();
        }));
        return;
    }

    gnutls_global_init();
    RingD::instance->registerCallbacks();
    RingD::instance->initDaemon( DRing::DRING_FLAG_CONSOLE_LOG | DRing::DRING_FLAG_DEBUG );
    Video::VideoManager::instance->captureManager()->EnumerateWebcamsAsync();

    daemonInitialized_ = true;
}

void
RingD::deinit()
{
    DRing::fini();
    gnutls_global_deinit();
}

805
806
807
808
809
void
RingD::initDaemon(int flags)
{
    DRing::init(static_cast<DRing::InitFlag>(flags));
}
810

811
812
813
814
815
816
817
818
819
void
RingD::startDaemon()
{
    if (daemonRunning_) {
        ERR_("daemon already runnging");
        return;
    }
    //eraseCacheFolder();
    editModeOn_ = true;
atraczyk's avatar
atraczyk committed
820

821
822
    IAsyncAction^ action = ThreadPool::RunAsync(ref new WorkItemHandler([=](IAsyncAction^ spAction)
    {
823
        daemonRunning_ = DRing::start();
824

825
        auto vcm = Video::VideoManager::instance->captureManager();
atraczyk's avatar
atraczyk committed
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
        if (vcm->deviceList->Size > 0) {
            std::string deviceName = DRing::getDefaultDevice();
            std::map<std::string, std::string> settings = DRing::getSettings(deviceName);
            int rate = stoi(settings["rate"]);
            std::string size = settings["size"];
            std::string::size_type pos = size.find('x');
            int width = std::stoi(size.substr(0, pos));
            int height = std::stoi(size.substr(pos + 1, size.length()));
            for (auto dev : vcm->deviceList) {
                if (!Utils::toString(dev->name()).compare(deviceName))
                    vcm->activeDevice = dev;
            }
            vcm->activeDevice->SetDeviceProperties("", width, height, rate);
            CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::Normal,
            ref new DispatchedHandler([=]() {
                finishCaptureDeviceEnumeration();
            }));
843
844
        }

845
        if (!daemonRunning_) {
atraczyk's avatar
atraczyk committed
846
847
848
849
            ERR_("\ndaemon didn't start.\n");
            return;
        }
        else {
850
851
852
853
854
855
856
857
858
859
            switch (_startingStatus) {
            case StartingStatus::REGISTERING_ON_THIS_PC:
            case StartingStatus::REGISTERING_THIS_DEVICE:
            {
                break;
            }
            case StartingStatus::NORMAL:
            default:
            {
                CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::Normal,
Nicolas Jager's avatar
Nicolas Jager committed
860
                ref new DispatchedHandler([=]() {
atraczyk's avatar
atraczyk committed
861
862
                    reloadAccountList();
                }));
863
                break;
atraczyk's avatar
atraczyk committed
864
            }
865
866
            }

867
            /* at this point the config.yml is safe. */
atraczyk's avatar
atraczyk committed
868
869
870
871
            std::string tokenFile = localFolder_ + "\\creation.token";
            if (fileExists(tokenFile)) {
                fileDelete(tokenFile);
            }
872

Nicolas Jager's avatar
Nicolas Jager committed
873
            while (daemonRunning) {
atraczyk's avatar
atraczyk committed
874
875
                DRing::pollEvents();
                dequeueTasks();
876
                Sleep(5);
atraczyk's avatar
atraczyk committed
877
878
            }
        }
879
    },Platform::CallbackContext::Any), WorkItemPriority::High);
atraczyk's avatar
atraczyk committed
880
881
882
883
884
}

RingD::RingD()
{
    localFolder_ = Utils::toString(ApplicationData::Current->LocalFolder->Path);
885
    callIdsList_ = ref new Vector<String^>();
886
    currentCallId = nullptr;
atraczyk's avatar
atraczyk committed
887
888
}

atraczyk's avatar
atraczyk committed
889
890
891
892
893
894
std::string
RingD::getLocalFolder()
{
    return localFolder_ + Utils::toString("\\");
}

atraczyk's avatar
atraczyk committed
895
896
897
898
899
void
RingD::dequeueTasks()
{
    for (int i = 0; i < tasksList_.size(); i++) {
        auto task = tasksList_.front();
900
901
        auto request = dynamic_cast<Task^>(task)->request;
        switch (request) {
atraczyk's avatar
atraczyk committed
902
        case Request::None:
903
            break;
904
905
906
907
908
909
910
911
912
913
914
        case Request::PlaceCall:
        {
            auto callId = DRing::placeCall(task->_accountId_new, task->_ringId_new);
            CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::High,
            ref new DispatchedHandler([=]() {

                auto contact = ContactsViewModel::instance->findContactByRingId(Utils::toPlatformString(task->_ringId_new));
                auto item = SmartPanelItemsViewModel::instance->findItem(contact);
                item->_callId = Utils::toPlatformString(callId);
                //MSG_("$1 place call with id : " + Utils::toString(item->_callId));

Nicolas Jager's avatar
Nicolas Jager committed
915
916
917
                /* if for any reason there is no callid, do not propagate the event*/
                if (!callId.empty())
                    callPlaced(Utils::toPlatformString(callId));
918
919
920

            }));
        }
921
        case Request::AddRingAccount:
922
923
        {
            std::map<std::string, std::string> ringAccountDetails;
924
925
926
927
            ringAccountDetails.insert(std::make_pair(DRing::Account::ConfProperties::ALIAS
                                      , Utils::toString(task->_alias)));
            ringAccountDetails.insert(std::make_pair(DRing::Account::ConfProperties::ARCHIVE_PASSWORD,
                                      Utils::toString(task->_password)));
atraczyk's avatar
atraczyk committed
928
            ringAccountDetails.insert(std::make_pair(DRing::Account::ConfProperties::TYPE,"RING"));
929
930
            ringAccountDetails.insert(std::make_pair(DRing::Account::ConfProperties::UPNP_ENABLED
                                      , (task->_upnp)? ring::TRUE_STR : ring::FALSE_STR));
Nicolas Jager's avatar
Nicolas Jager committed
931
932
933
934
935
936
937
            ringAccountDetails.insert(std::make_pair(DRing::Account::VolatileProperties::REGISTERED_NAME
                                      , Utils::toString(task->_registeredName)));


            auto newAccountId = DRing::addAccount(ringAccountDetails);

            if (!task->_registeredName->IsEmpty())
atraczyk's avatar
atraczyk committed
938
                registerName_new(newAccountId, Utils::toString(task->_password), Utils::toString(task->_registeredName));
939
940
        }
        break;
941
        case Request::AddSIPAccount:
942
943
        {
            std::map<std::string, std::string> sipAccountDetails;
944
945
            sipAccountDetails.insert(std::make_pair(DRing::Account::ConfProperties::ALIAS
                                                    , Utils::toString(task->_alias)));
atraczyk's avatar
atraczyk committed
946
            sipAccountDetails.insert(std::make_pair(DRing::Account::ConfProperties::TYPE,"SIP"));
947
948
949
950
951
952
            sipAccountDetails.insert(std::make_pair(DRing::Account::ConfProperties::PASSWORD
                                                    , Utils::toString(task->_sipPassword)));
            sipAccountDetails.insert(std::make_pair(DRing::Account::ConfProperties::HOSTNAME
                                                    , Utils::toString(task->_sipHostname)));
            sipAccountDetails.insert(std::make_pair(DRing::Account::ConfProperties::USERNAME
                                                    , Utils::toString(task->_sipUsername)));
953
954
955
            DRing::addAccount(sipAccountDetails);
        }
        break;
956
957
        case Request::RefuseIncommingCall:
        {
958
            auto callId = task->_callId;
959
960
961
962
963
964
            auto callId2 = Utils::toString(callId);
            DRing::refuse(callId2);
        }
        break;
        case Request::AcceptIncommingCall:
        {
965
            auto callId = task->_callId;
966
967
968
969
            auto callId2 = Utils::toString(callId);
            DRing::accept(callId2);
        }
        break;
Nicolas Jager's avatar
Nicolas Jager committed
970
        case Request::CancelOutGoingCall:
971
        case Request::HangUpCall:
Nicolas Jager's avatar
Nicolas Jager committed
972
        {
973
            auto callId = task->_callId;
Nicolas Jager's avatar
Nicolas Jager committed
974

975
            DRing::hangUp(Utils::toString(callId));
Nicolas Jager's avatar
Nicolas Jager committed
976

Nicolas Jager's avatar
Nicolas Jager committed
977
978
        }
        break;
979
980
        case Request::PauseCall:
        {
981
            DRing::hold(task->_callid_new);
982
983
984
985
        }
        break;
        case Request::UnPauseCall:
        {
986
            DRing::unhold(task->_callid_new);
987
988
        }
        break;
989
990
        case Request::RegisterDevice:
        {
991
992
            auto pin = Utils::toString(task->_pin);
            auto password = Utils::toString(task->_password);
993
994
995
996
997
998
999
1000

            std::map<std::string, std::string> deviceDetails;
            deviceDetails.insert(std::make_pair(DRing::Account::ConfProperties::TYPE, "RING"));
            //deviceDetails.insert(std::make_pair(DRing::Account::ConfProperties::UPNP_ENABLED, "true"));
            //deviceDetails.insert(std::make_pair(DRing::Account::ConfProperties::ALIAS, "MonSuperUsername"));
            deviceDetails.insert(std::make_pair(DRing::Account::ConfProperties::ARCHIVE_PIN, pin));
            deviceDetails.insert(std::make_pair(DRing::Account::ConfProperties::ARCHIVE_PASSWORD, password));
            DRing::addAccount(deviceDetails);
For faster browsing, not all history is shown. View entire blame