RingD.cpp 52.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>
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"
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;
48
using namespace RingClientUWP::ViewModel;
atraczyk's avatar
atraczyk committed
49

atraczyk's avatar
atraczyk committed
50

51 52
using namespace Windows::System;

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

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

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

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

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

71
        auto type = accountDetails.find(DRing::Account::ConfProperties::TYPE)->second;
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
        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 {
94 95
                if (!ringID.empty())
                    RingClientUWP::ViewModel::AccountsViewModel::instance->addRingAccount(alias, ringID, accountId, deviceId, upnpState);
96
            }
97
        }
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
        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);
            }
118

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

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

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

    /* recipient */
Nicolas Jager's avatar
Nicolas Jager committed
136 137
    auto item = SmartPanelItemsViewModel::instance->_selectedItem;
    auto contact = item->_contact;
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    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);
154 155 156 157

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

158 159 160 161 162
    } else {
        WNG_("message not sent, see daemon outputs");
    }
}

163 164 165 166
// send message during video call
void RingClientUWP::RingD::sendSIPTextMessage(String^ message)
{
    /* account id */
Nicolas Jager's avatar
Nicolas Jager committed
167
    auto accountId = AccountListItemsViewModel::instance->_selectedItem->_account->accountID_;
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
    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();
}

192 193 194 195 196 197 198 199 200 201 202 203
// 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*/);
}

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

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

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

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

    tasksList_.push(task);
220 221 222
}

void
223
RingD::createSIPAccount(String^ alias, String^ sipPassword, String^ sipHostname, String^ sipusername)
224
{
225 226 227 228
    editModeOn_ = true;

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

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

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

    tasksList_.push(task);
237 238
}

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

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

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

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

258 259 260 261
    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);
262

263
}
264

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

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

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

285

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

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

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

304 305 306 307 308 309 310 311
void RingClientUWP::RingD::askToRefreshKnownDevices(String^ accountId)
{
    auto task = ref new RingD::Task(Request::GetKnownDevices);
    task->_accountId = accountId;

    tasksList_.push(task);
}

312 313 314 315 316 317 318 319 320
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);
}

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
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.");
        }
    });
}

338 339 340 341 342 343 344
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
345
    task->_accountId_new = Utils::toString(accountId);
346 347 348 349

    tasksList_.push(task);
}

350 351 352 353 354 355 356 357 358 359 360 361
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);
}

362 363 364 365 366 367 368
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
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
void
ShowCallToast(String^ callId, String^ from = nullptr)
{
    String^ payload =
        "<toast scenario='incomingCall'> "
            "<visual> "
                "<binding template='ToastGeneric'>"
                    "<text>GNU Ring - Incoming call"+ (from?(" from " + from):"") +"</text>"
                "</binding>"
            "</visual>"
            /*"<actions>"
                "<action arguments = '" + callId + "' content = 'Accept' />"
            "</actions>"*/
            "<audio src='ms-appx:///Assets/default.wav' loop='true'/>"
        "</toast>";

    auto doc = ref new XmlDocument();
    doc->LoadXml(payload);

    auto toast = ref new ToastNotification(doc);
    ToastNotificationManager::CreateToastNotifier()->Show(toast);
}

void
ShowMsgToast(String^ from, String^ payload)
{
    String^ xml =
        "<toast scenario='incomingMessage'> "
            "<visual> "
                "<binding template='ToastGeneric'>"
                    "<text>" + from + " : " + payload + "</text>"
                "</binding>"
            "</visual>"
            "<actions>"
                "<action arguments = '" + from + "'/>"
            "</actions>"
            "<audio src='ms-appx:///Assets/message_notification_sound.wav' loop='false'/>"
        "</toast>";

    auto doc = ref new XmlDocument();
    doc->LoadXml(xml);

    auto toast = ref new ToastNotification(doc);
    ToastNotificationManager::CreateToastNotifier()->Show(toast);
}

atraczyk's avatar
atraczyk committed
415
void
416
RingD::registerCallbacks()
atraczyk's avatar
atraczyk committed
417
{
418 419 420 421 422 423 424 425 426 427 428 429 430
    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);
431

432 433 434
            auto accountId2 = toPlatformString(accountId);
            auto callId2 = toPlatformString(callId);
            auto from2 = toPlatformString(from);
atraczyk's avatar
atraczyk committed
435

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

439 440
            CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
                CoreDispatcherPriority::High, ref new DispatchedHandler([=]()
atraczyk's avatar
atraczyk committed
441
            {
442 443 444
                incomingCall(accountId2, callId2, from2);
                stateChange(callId2, CallStatus::INCOMING_RINGING, 0);

445 446 447 448 449 450
                auto contact = ContactsViewModel::instance->findContactByRingId(from2);
                if (contact) {
                    auto item = SmartPanelItemsViewModel::instance->findItem(contact);
                    if (item)
                        item->_callId = callId2;
                }
451 452
            }));
        }),
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
        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);
            }));
        }),
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
        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);
            }));
        }),
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
        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);
            }));
        }),
501 502 503 504 505 506 507 508 509
        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
510

511 512
            auto callId2 = toPlatformString(callId);
            auto state2 = toPlatformString(state);
atraczyk's avatar
atraczyk committed
513

514
            auto state3 = translateCallStatus(state2);
515

516
            if (state3 == CallStatus::OUTGOING_RINGING ||
517
                    state3 == CallStatus::INCOMING_RINGING) {
518
                try {
atraczyk's avatar
atraczyk committed
519
                    Configuration::UserPreferences::instance->sendVCard(callId);
520 521 522 523 524 525
                }
                catch (Exception^ e) {
                    EXC_(e);
                }
            }

atraczyk's avatar
atraczyk committed
526 527 528 529 530 531 532 533 534 535 536 537 538 539
            if (state3 == CallStatus::INCOMING_RINGING) {
                if (isInBackground) {
                    ringtone_->Start();
                    ShowCallToast(callId2);
                }
                else
                    ringtone_->Start();
            }

            if (state3 == CallStatus::IN_PROGRESS) {
                ringtone_->Stop();
            }

            if (state3 == CallStatus::ENDED) {
540
                DRing::hangUp(callId); // solve a bug in the daemon API.
atraczyk's avatar
atraczyk committed
541 542
                ringtone_->Stop();
            }
543

544 545
            CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
                CoreDispatcherPriority::High, ref new DispatchedHandler([=]()
atraczyk's avatar
atraczyk committed
546
            {
547 548 549 550 551 552 553 554 555 556 557
                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
558

559 560
            auto accountId2 = toPlatformString(accountId);
            auto from2 = toPlatformString(from);
561

562 563 564
            for (auto i : payloads) {
                MSG_("payload = " + i.second);
                auto payload = Utils::toPlatformString(i.second);
565
                CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
566
                    CoreDispatcherPriority::High, ref new DispatchedHandler([=]()
567
                {
568
                    incomingAccountMessage(accountId2, from2, payload);
569
                }));
570 571 572 573 574 575 576 577 578 579
            }
        }),
        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);
580

581 582
            auto callId2 = toPlatformString(callId);
            auto from2 = toPlatformString(from);
583

584
            auto item = SmartPanelItemsViewModel::instance->findItem(callId2);
585 586 587 588 589
            Contact^ contact;
            if (item)
                contact = item->_contact;
            else
                WNG_("item not found!");
590

591
            static const unsigned int profileSize = VCardUtils::PROFILE_VCF.size();
592
            for (auto i : payloads) {
593 594 595 596
                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);
597
                    return;
598
                }
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613

                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) {
614
                CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::High,
615
                ref new DispatchedHandler([=]() {
atraczyk's avatar
atraczyk committed
616
                    reloadAccountList();
617 618 619 620
                    // enleves ce qui suit et utilises des evenements.
                    registrationStateRegistered();
                    // mettre a jour le wizard
                    /*if (editModeOn_) {
621 622 623
                        auto frame = dynamic_cast<Frame^>(Window::Current->Content);
                        dynamic_cast<RingClientUWP::MainPage^>(frame->Content)->showLoadingOverlay(false, false);
                        editModeOn_ = false;
624
                    }*/
625 626 627 628 629
                    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
630
                ref new DispatchedHandler([=]() {
631
                    setLoadingStatusText("Attempting to register account...", "#ff00f0f0");
632 633
                }));
            }
Nicolas Jager's avatar
Nicolas Jager committed
634 635 636 637 638 639 640 641 642 643
            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) {
644 645 646 647
                CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::High,
                ref new DispatchedHandler([=]() {
                    reloadAccountList();
                    registrationStateErrorGeneric(account_id);
648
                    setLoadingStatusText(Utils::toPlatformString("Failed to register account: " + state), "#ffff0000");
649
                    // ajoute cet event dans le wizard
atraczyk's avatar
atraczyk committed
650
                }));
651 652 653
            }
        }),
        DRing::exportable_callback<DRing::ConfigurationSignal::AccountsChanged>([this]()
654
        {
655 656 657 658
            MSG_("<AccountsChanged>");
            CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::High,
            ref new DispatchedHandler([=]() {
                reloadAccountList();
Nicolas Jager's avatar
Nicolas Jager committed
659
                /*if (editModeOn_) {
660 661 662
                    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
663
                }*/
664 665
            }));
        }),
666
        DRing::exportable_callback<DRing::Debug::MessageSend>([&](const std::string& msg)
atraczyk's avatar
atraczyk committed
667
        {
668
            if (debugModeOn_) {
669
                dispatcher->RunAsync(CoreDispatcherPriority::High,
Nicolas Jager's avatar
Nicolas Jager committed
670
                ref new DispatchedHandler([=]() {
671 672 673 674 675
                    std::string displayMsg = msg.substr(56);
                    setLoadingStatusText(Utils::toPlatformString(displayMsg.substr(0,40) + "..."), "#ff000000");
                    DMSG_(msg);
                }));
            }
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 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
        })
    };
    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
752 753 754
                        }
                    }
                }
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
            }
        }),
        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
793 794 795 796
        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([=]() {
797
                MSG_("KnownDevicesChanged ---> C PAS FINI");
Nicolas Jager's avatar
Nicolas Jager committed
798 799 800 801 802 803 804 805 806 807
            }));
        }),
        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);
            }));
808 809 810
        }),
        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
811 812 813 814 815 816
            //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.
817
                    registeredNameFound(LookupStatus::SUCCESS, address, name);
Nicolas Jager's avatar
Nicolas Jager committed
818 819
                    break;
                case 1: // provided name is not valid.
820
                    registeredNameFound(LookupStatus::INVALID_NAME, address, name);
Nicolas Jager's avatar
Nicolas Jager committed
821 822
                    break;
                case 2: // everything went fine. Name/address pair was not found.
823
                    registeredNameFound(LookupStatus::NOT_FOUND, address, name);
Nicolas Jager's avatar
Nicolas Jager committed
824 825
                    break;
                case 3: // An error happened
826
                    registeredNameFound(LookupStatus::ERRORR, address, name);
Nicolas Jager's avatar
Nicolas Jager committed
827 828 829
                    break;
                }
            }));
Nicolas Jager's avatar
Nicolas Jager committed
830 831 832 833 834 835
        }),
        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);
            });
836 837 838 839
        })
    };
    registerConfHandlers(nameRegistrationHandlers);
}
atraczyk's avatar
atraczyk committed
840

841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
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();
}

867 868 869 870 871
void
RingD::initDaemon(int flags)
{
    DRing::init(static_cast<DRing::InitFlag>(flags));
}
872

873 874 875 876 877 878 879 880 881
void
RingD::startDaemon()
{
    if (daemonRunning_) {
        ERR_("daemon already runnging");
        return;
    }
    //eraseCacheFolder();
    editModeOn_ = true;
atraczyk's avatar
atraczyk committed
882

883 884
    IAsyncAction^ action = ThreadPool::RunAsync(ref new WorkItemHandler([=](IAsyncAction^ spAction)
    {
885
        daemonRunning_ = DRing::start();
886

887
        auto vcm = Video::VideoManager::instance->captureManager();
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
        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();
            }));
905 906
        }

907
        if (!daemonRunning_) {
atraczyk's avatar
atraczyk committed
908 909 910 911
            ERR_("\ndaemon didn't start.\n");
            return;
        }
        else {
912 913 914 915 916 917 918 919 920 921
            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,
922
                ref new DispatchedHandler([=]() {
atraczyk's avatar
atraczyk committed
923 924
                    reloadAccountList();
                }));
925
                break;
atraczyk's avatar
atraczyk committed
926
            }
927 928
            }

929
            /* at this point the config.yml is safe. */
930 931 932 933
            std::string tokenFile = localFolder_ + "\\creation.token";
            if (fileExists(tokenFile)) {
                fileDelete(tokenFile);
            }
934

Nicolas Jager's avatar
Nicolas Jager committed
935
            while (daemonRunning) {
atraczyk's avatar
atraczyk committed
936 937
                DRing::pollEvents();
                dequeueTasks();
938
                Sleep(5);
atraczyk's avatar
atraczyk committed
939 940
            }
        }
941
    },Platform::CallbackContext::Any), WorkItemPriority::High);
atraczyk's avatar
atraczyk committed
942 943 944 945
}

RingD::RingD()
{
atraczyk's avatar
atraczyk committed
946
    ringtone_ = ref new Ringtone("default.wav");
atraczyk's avatar
atraczyk committed
947
    localFolder_ = Utils::toString(ApplicationData::Current->LocalFolder->Path);
948
    callIdsList_ = ref new Vector<String^>();
949
    currentCallId = nullptr;
950
    WriteLine("XBOX: " + isOnXBox.ToString());
atraczyk's avatar
atraczyk committed
951 952
}

953 954 955 956 957 958
std::string
RingD::getLocalFolder()
{
    return localFolder_ + Utils::toString("\\");
}

atraczyk's avatar
atraczyk committed
959 960 961 962 963
void
RingD::dequeueTasks()
{
    for (int i = 0; i < tasksList_.size(); i++) {
        auto task = tasksList_.front();
964 965
        auto request = dynamic_cast<Task^>(task)->request;
        switch (request) {
atraczyk's avatar
atraczyk committed
966
        case Request::None:
967
            break;
968 969 970 971 972 973 974 975 976 977 978
        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
979 980 981
                /* if for any reason there is no callid, do not propagate the event*/
                if (!callId.empty())
                    callPlaced(Utils::toPlatformString(callId));
982 983 984

            }));
        }
985
        case Request::AddRingAccount:
986 987
        {
            std::map<std::string, std::string> ringAccountDetails;
988 989 990 991
            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
992
            ringAccountDetails.insert(std::make_pair(DRing::Account::ConfProperties::TYPE,"RING"));
993 994
            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
995 996 997 998 999 1000 1001
            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
1002
                registerName_new(newAccountId, Utils::toString(task->_password), Utils::toString(task->_registeredName));
1003 1004
        }
        break;
1005
        case Request::AddSIPAccount:
1006 1007
        {
            std::map<std::string, std::string> sipAccountDetails;
1008 1009
            sipAccountDetails.insert(std::make_pair(DRing::Account::ConfProperties::ALIAS
                                                    , Utils::toString(task->_alias)));
atraczyk's avatar
atraczyk committed
1010
            sipAccountDetails.insert(std::make_pair(DRing::Account::ConfProperties::TYPE,"SIP"));
1011 1012 1013 1014 1015 1016
            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)));
1017 1018 1019
            DRing::addAccount(sipAccountDetails);
        }
        break;
1020 1021
        case Request::RefuseIncommingCall:
        {
1022
            auto callId = task->_callId;
1023 1024 1025 1026 1027 1028
            auto callId2 = Utils::toString(callId);
            DRing::refuse(callId2);
        }
        break;
        case Request::AcceptIncommingCall:
        {
1029
            auto callId = task->_callId;
1030 1031 1032 1033
            auto callId2 = Utils::toString(callId);
            DRing::accept(callId2);
        }
        break;
Nicolas Jager's avatar
Nicolas Jager committed
1034
        case Request::CancelOutGoingCall:
1035
        case Request::HangUpCall:
Nicolas Jager's avatar
Nicolas Jager committed
1036
        {
1037
            auto callId = task->_callId;
1038

1039
            DRing::hangUp(Utils::toString(callId));
1040

Nicolas Jager's avatar
Nicolas Jager committed
1041 1042
        }
        break;
1043 1044
        case Request::PauseCall:
        {
1045
            DRing::hold(task->_callid_new);
1046 1047 1048 1049
        }
        break;
        case Request::UnPauseCall:
        {
1050
            DRing::unhold(task->_callid_new);
1051 1052
        }
        break;
1053 1054
        case Request::RegisterDevice:
        {
1055 1056
            auto pin = Utils::toString(task->_pin);
            auto password = Utils::toString(task->_password);
1057 1058 1059 1060 1061 1062 1063 1064

            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);
1065 1066 1067 1068 1069 1070

            CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::High,
            ref new DispatchedHandler([=]() {
                auto frame = dynamic_cast<Frame^>(Window::Current->Content);
                dynamic_cast<RingClientUWP::MainPage^>(frame->Content)->showLoadingOverlay(true, true);
            }));
1071
        }
1072
        break;
1073 1074 1075 1076 1077 1078
        case Request::GetKnownDevices:
        {
            auto accountId = task->_accountId;
            auto accountId2 = Utils::toString(accountId);

            auto devicesList = DRing::getKnownRingDevices(accountId2);
1079 1080 1081
            if (devicesList.empty())
                break;

1082 1083
            auto devicesList2 = translateKnownRingDevices(devicesList);

1084 1085 1086 1087
            CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::Normal,
            ref new DispatchedHandler([=]() {
                devicesListRefreshed(devicesList2);
            }));
Nicolas Jager's avatar
Nicolas Jager committed
1088
            break;
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
        }
        case Request::ExportOnRing:
        {
            auto accountId = task->_accountId;
            auto password = task->_password;

            auto accountId2 = Utils::toString(accountId);
            auto password2 = Utils::toString(password);

            DRing::exportOnRing(accountId2, password2);
1099 1100 1101 1102
            break;
        }
        case Request::UpdateAccount:
        {
Nicolas Jager's avatar
Nicolas Jager committed
1103 1104
            auto account = AccountListItemsViewModel::instance->findItem(Utils::toPlatformString(task->_accountId_new))->_account;
            std::map<std::string, std::string> accountDetails = DRing::getAccountDetails(task->_accountId_new);
Nicolas Jager's avatar
Nicolas Jager committed
1105 1106 1107 1108
            std::map<std::string, std::string> accountDetailsOld(accountDetails);



1109 1110
            accountDetails[DRing::Account::ConfProperties::ALIAS] = Utils::toString(account->name_);

Nicolas Jager's avatar
Nicolas Jager committed
1111 1112 1113 1114 1115
            if (accountDetails[DRing::Account::ConfProperties::TYPE] == "RING") {
                if (accountDetails == accountDetailsOld)
                    break;

                accountDetails[DRing::Account::ConfProperties::UPNP_ENABLED] = (account->_upnpState) ? ring::TRUE_STR : ring::FALSE_STR;
Nicolas Jager's avatar
Nicolas Jager committed
1116 1117
                CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::High,
                ref new DispatchedHandler([=]() {
Nicolas Jager's avatar
Nicolas Jager committed
1118 1119 1120 1121 1122 1123 1124 1125 1126
                    auto frame = dynamic_cast<Frame^>(Window::Current->Content);
                    dynamic_cast<RingClientUWP::MainPage^>(frame->Content)->showLoadingOverlay(true, true);
                }));
            }
            else {
                accountDetails[DRing::Account::ConfProperties::HOSTNAME] = Utils::toString(account->_sipHostname);
                accountDetails[DRing::Account::ConfProperties::PASSWORD] = Utils::toString(account->_sipPassword);
                accountDetails[DRing::Account::ConfProperties::USERNAME] = Utils::toString(account->_sipUsername);
            }
Nicolas Jager's avatar
Nicolas Jager committed
1127

1128 1129
            DRing::setAccountDetails(Utils::toString(account->accountID_), accountDetails);
            break;
1130 1131 1132 1133 1134 1135
        }
        case Request::DeleteAccount:
        {
            auto accountId = task->_accountId;
            auto accountId2 = Utils::toString(accountId);

Nicolas Jager's avatar
Nicolas Jager committed
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
            std::map<std::string, std::string> accountDetails = DRing::getAccountDetails(task->_accountId_new);

            if (accountDetails[DRing::Account::ConfProperties::TYPE] == "RING")
                CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::High,
                ref new DispatchedHandler([=]() {
                auto frame = dynamic_cast<Frame^>(Window::Current->Content);
                dynamic_cast<RingClientUWP::MainPage^>(frame->Content)->showLoadingOverlay(true, true);
            }));


1146 1147
            DRing::removeAccount(accountId2);
            break;
1148
        }
1149 1150 1151
        case Request::GetCallsList:
        {
            auto callsList = DRing::getCallList();
1152 1153 1154 1155
            dispatcher->RunAsync(CoreDispatcherPriority::High,
            ref new DispatchedHandler([&]() {
                callsListRecieved(callsList);
            }));
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
            MSG_("list of calls returned by the daemon :");
            for (auto call : callsList)
                MSG_(call);
            MSG_("[EOL]"); // end of list
            break;
        }
        case Request::KillCall:
        {
            auto callId = task->_callId;
            auto callId2 = Utils::toString(callId);
            MSG_("asking daemon to kill : " + callId2);
            DRing::hangUp(callId2);
            break;
        }
        case Request::switchDebug:
        {
            debugModeOn_ = !debugModeOn_;
            break;
        }
1175 1176 1177 1178 1179 1180
        case Request::MuteVideo:
        {
            auto callId = Utils::toString(task->_callId);
            bool muted = task->_muted;
            DRing::muteLocalMedia(callId, DRing::Media::Details::MEDIA_TYPE_VIDEO, muted);
        }
1181 1182 1183 1184 1185 1186
        case Request::MuteAudio:
        {
            DRing::muteLocalMedia(task->_callid_new
                                  , DRing::Media::Details::MEDIA_TYPE_AUDIO
                                  , task->_audioMuted_new);
        }
Nicolas Jager's avatar
Nicolas Jager committed
1187 1188 1189 1190 1191 1192 1193 1194
        case Request::LookUpName:
        {
            auto alias = task->_alias;
            DRing::lookupName("", "", Utils::toString(alias));
            break;
        }
        case Request::LookUpAddress:
        {
Nicolas Jager's avatar
Nicolas Jager committed
1195
            DRing::lookupAddress("", "", Utils::toString(task->_address));
Nicolas Jager's avatar
Nicolas Jager committed
1196 1197 1198 1199 1200
            break;
        }
        case Request::RegisterName:
        {
            auto accountDetails = DRing::getAccountDetails(task->_accountId_new);
Nicolas Jager's avatar
Nicolas Jager committed
1201
            bool result;
Nicolas Jager's avatar
Nicolas Jager committed
1202 1203 1204 1205

            if (accountDetails[DRing::Account::ConfProperties::USERNAME].empty())
                registerName_new(task->_accountId_new, task->_password_new, task->_publicUsername_new);
            else
Nicolas Jager's avatar
Nicolas Jager committed
1206
            {
Nicolas Jager's avatar
Nicolas Jager committed
1207 1208
                result = DRing::registerName(task->_accountId_new, task->_password_new, task->_publicUsername_new);

Nicolas Jager's avatar
Nicolas Jager committed
1209 1210 1211 1212 1213
                CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::High,
                ref new DispatchedHandler([=]() {
                    nameRegistred(result);
                }));
            }
Nicolas Jager's avatar
Nicolas Jager committed
1214

Nicolas Jager's avatar
Nicolas Jager committed
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226

            //const wchar_t* toto = task->_accountId->Data();
            //auto accountId = ref new String(toto);// Utils::toString(task->_accountId);
            //auto accountDetails = DRing::getAccountDetails(Utils::toString(accountId));

            //if (accountDetails[DRing::Account::ConfProperties::USERNAME].empty())
            //    registerName(task->_accountId, task->_password, task->_registeredName);
            //else
            //    DRing::registerName(Utils::toString(task->_accountId), Utils::toString(task->_password), Utils::toString(task->_registeredName));

            break;
        }
atraczyk's avatar
atraczyk committed
1227 1228 1229 1230 1231 1232
        default:
            break;
        }
        tasksList_.pop();
    }
}
Nicolas Jager's avatar
Nicolas Jager committed
1233

1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
void RingClientUWP::RingD::getCallsList()
{
    auto task = ref new RingD::Task(Request::GetCallsList);

    tasksList_.push(task);

}

void RingClientUWP::RingD::killCall(String ^ callId)
{
    if (callId == "-all") {
        auto callsList = DRing::getCallList();

        for (auto call : callsList) {
            auto task = ref new RingD::Task(Request::KillCall);
            task->_callId = Utils::toPlatformString(call);

            tasksList_.push(task);
        }
        return;
    }

    auto task = ref new RingD::Task(Request::KillCall);
    task->_callId = callId;

    tasksList_.push(task);

}

void RingClientUWP::RingD::switchDebug()
{
    auto task = ref new RingD::Task(Request::switchDebug);

    tasksList_.push(task);
}

1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
void RingClientUWP::RingD::muteVideo(String ^ callId, bool muted)
{
    auto task = ref new RingD::Task(Request::MuteVideo);

    task->_callId = callId;
    task->_muted = muted;

    tasksList_.push(task);
}

1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
void RingClientUWP::RingD::muteAudio(const std::string& callId, bool muted)
{
    auto task = ref new RingD::Task(Request::MuteAudio);

    task->_callid_new = callId;
    task->_audioMuted_new = muted;

    tasksList_.push(task);
}

Nicolas Jager's avatar
Nicolas Jager committed
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
void RingClientUWP::RingD::lookUpName(String ^ name)
{
    auto task = ref new RingD::Task(Request::LookUpName);
    task->_alias = name;

    tasksList_.push(task);
}

void
RingD::registerName(String^ accountId, String^ password, String^ username)
{
    auto task = ref new RingD::Task(Request::RegisterName);
    task->_accountId = ref new String(accountId->Data());
    task->_password = password;
    task->_alias = username;

    tasksList_.push(task);
}

void RingClientUWP::RingD::registerName_new(const std::string & accountId, const std::string & password, const std::string & username)
{
    auto task = ref new RingD::Task(Request::RegisterName);
    task->_accountId_new = accountId;
    task->_password_new = password;
    task->_publicUsername_new = username;

    tasksList_.push(task);
}

std::map<std::string, std::string>
RingClientUWP::RingD::getVolatileAccountDetails(Account^ account)
{
    return DRing::getVolatileAccountDetails(Utils::toString(account->accountID_));
}

void RingClientUWP::RingD::lookUpAddress(String^ address)
{
    auto task = ref new RingD::Task(Request::LookUpAddress);
    task->_address = address;

    tasksList_.push(task);
}

std::string RingClientUWP::RingD::registeredName(Account^ account)
{
    auto volatileAccountDetails = DRing::getVolatileAccountDetails(Utils::toString(account->accountID_));
    return volatileAccountDetails[DRing::Account::VolatileProperties::REGISTERED_NAME];
}

1339
RingClientUWP::CallStatus RingClientUWP::RingD::translateCallStatus(String^ state)
Nicolas Jager's avatar
Nicolas Jager committed
1340 1341
{
    if (state == "INCOMING")
1342
        return CallStatus::INCOMING_RINGING;
Nicolas Jager's avatar
Nicolas Jager committed
1343 1344 1345 1346

    if (state == "CURRENT")
        return CallStatus::IN_PROGRESS;

1347 1348 1349 1350 1351 1352 1353 1354
    if (state == "OVER")
        return CallStatus::ENDED;

    if (state == "RINGING")
        return CallStatus::OUTGOING_RINGING;

    if (state == "CONNECTING")
        return CallStatus::SEARCHING;
Nicolas Jager's avatar
Nicolas Jager committed
1355

1356 1357 1358 1359 1360 1361
    if (state == "HOLD")
        return CallStatus::PAUSED;

    if (state == "PEER_PAUSED")
        return CallStatus::PEER_PAUSED;

1362

Nicolas Jager's avatar
Nicolas Jager committed
1363 1364
    return CallStatus::NONE;
}
1365

1366 1367 1368 1369 1370 1371 1372
String^
RingD::getUserName()
{
    auto users = User::FindAllAsync();
    return nullptr;
}

1373 1374 1375 1376 1377 1378 1379
Vector<String^>^ RingClientUWP::RingD::translateKnownRingDevices(const std::map<std::string, std::string> devices)
{
    auto devicesList = ref new Vector<String^>();

    for (auto i : devices) {
        MSG_("devices.first = " + i.first);
        MSG_("devices.second = " + i.second);
1380 1381
        auto deviceName = Utils::toPlatformString(i.second);
        devicesList->Append(deviceName);
1382 1383 1384 1385
    }

    return devicesList;
}