RingD.cpp 34.3 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 21 22 23 24 25
* 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"

/* daemon */
#include <dring.h>
#include "callmanager_interface.h"
#include "configurationmanager_interface.h"
#include "presencemanager_interface.h"
atraczyk's avatar
atraczyk committed
26
#include "videomanager_interface.h"
atraczyk's avatar
atraczyk committed
27 28
#include "fileutils.h"
#include "account_schema.h"
29
#include "account_const.h"
30 31
#include "string_utils.h" // used to get some const expr like TRUE_STR

atraczyk's avatar
atraczyk committed
32 33 34 35 36 37

#include "SmartPanel.xaml.h"

using namespace Windows::ApplicationModel::Core;
using namespace Windows::Storage;
using namespace Windows::UI::Core;
atraczyk's avatar
atraczyk committed
38 39 40
using namespace Windows::Media;
using namespace Windows::Media::MediaProperties;
using namespace Windows::Media::Capture;
atraczyk's avatar
atraczyk committed
41 42 43

using namespace RingClientUWP;
using namespace RingClientUWP::Utils;
44
using namespace RingClientUWP::ViewModel;
atraczyk's avatar
atraczyk committed
45

46 47
using namespace Windows::System;

atraczyk's avatar
atraczyk committed
48 49 50
void
RingClientUWP::RingD::reloadAccountList()
{
51
    //RingClientUWP::ViewModel::AccountsViewModel::instance->clearAccountList();
52

atraczyk's avatar
atraczyk committed
53
    std::vector<std::string> accountList = DRing::getAccountList();
54 55 56 57 58 59 60

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

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

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

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

113 114 115
            sipPassword = ""; // avoid to keep password in memory

        }
atraczyk's avatar
atraczyk committed
116
    }
117

atraczyk's avatar
atraczyk committed
118 119 120 121
    // load user preferences
    Configuration::UserPreferences::instance->load();
}

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

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

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

153 154 155 156 157
    } else {
        WNG_("message not sent, see daemon outputs");
    }
}

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

187
void
188
RingD::createRINGAccount(String^ alias, String^ archivePassword, bool upnp)
189
{
190 191 192 193 194
    editModeOn_ = true;

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

195 196 197 198 199 200 201
    auto task = ref new RingD::Task(Request::AddRingAccount);

    task->_alias = alias;
    task->_password = archivePassword;
    task->_upnp = upnp;

    tasksList_.push(task);
202 203 204
}

void
205
RingD::createSIPAccount(String^ alias, String^ sipPassword, String^ sipHostname, String^ sipusername)
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 217 218 219
    auto task = ref new RingD::Task(Request::AddSIPAccount);

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

    tasksList_.push(task);
220 221
}

222
void RingClientUWP::RingD::refuseIncommingCall(String^ callId)
223
{
224
    tasksList_.push(ref new RingD::Task(Request::RefuseIncommingCall, callId));
225 226
}

227
void RingClientUWP::RingD::acceptIncommingCall(String^ callId)
228
{
229
    tasksList_.push(ref new RingD::Task(Request::AcceptIncommingCall, callId));
230 231
}

Nicolas Jager's avatar
Nicolas Jager committed
232 233
void RingClientUWP::RingD::placeCall(Contact^ contact)
{
234
    MSG_("!--->> placeCall");
Nicolas Jager's avatar
Nicolas Jager committed
235
    auto to = contact->ringID_;
236 237 238 239 240 241 242 243 244 245
    String^ accountId;

    if (contact->_accountIdAssociated->IsEmpty()) {
        accountId = AccountListItemsViewModel::instance->_selectedItem->_account->accountID_;
        MSG_("adding account id to contact");
        contact->_accountIdAssociated = accountId;
    }
    else {
        accountId = contact->_accountIdAssociated;
    }
Nicolas Jager's avatar
Nicolas Jager committed
246 247 248 249 250 251

    auto to2 = Utils::toString(to);
    auto accountId2 = Utils::toString(accountId);

    auto callId2 = DRing::placeCall(accountId2, to2);

252 253


254
    if (callId2.empty()) {
Nicolas Jager's avatar
Nicolas Jager committed
255 256 257 258 259 260
        WNG_("call not created, the daemon didn't return a call Id");
        return;
    }

    auto callId = Utils::toPlatformString(callId2);

261
    _callIdsList->Append(callId);
262 263 264 265 266 267

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

268
    callPlaced(callId);
269 270 271 272 273 274

}

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

278

279 280 281
void RingClientUWP::RingD::hangUpCall2(String ^ callId)
{
    MSG_("$1 hangUpCall2 : "+Utils::toString(callId));
282
    tasksList_.push(ref new RingD::Task(Request::HangUpCall, callId));
283 284
}

285 286 287 288 289 290 291 292 293 294 295 296
void RingClientUWP::RingD::pauseCall(String ^ callId)
{
    MSG_("$1 pauseCall : " + Utils::toString(callId));
    tasksList_.push(ref new RingD::Task(Request::PauseCall, callId));
}

void RingClientUWP::RingD::unPauseCall(String ^ callId)
{
    MSG_("$1 unPauseCall : " + Utils::toString(callId));
    tasksList_.push(ref new RingD::Task(Request::UnPauseCall, callId));
}

297 298 299 300 301 302 303 304
void RingClientUWP::RingD::askToRefreshKnownDevices(String^ accountId)
{
    auto task = ref new RingD::Task(Request::GetKnownDevices);
    task->_accountId = accountId;

    tasksList_.push(task);
}

305 306 307 308 309 310 311 312 313
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);
}

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
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.");
        }
    });
}

331 332 333 334 335 336 337 338 339 340 341 342 343
void RingClientUWP::RingD::updateAccount(String^ accountId)
{
    editModeOn_ = true;

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

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

    tasksList_.push(task);
}

344 345 346 347 348 349 350 351 352 353 354 355 356
void RingClientUWP::RingD::deleteAccount(String ^ accountId)
{
    editModeOn_ = true;

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

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

    tasksList_.push(task);
}

357 358 359 360 361 362 363
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
364 365 366
void
RingClientUWP::RingD::startDaemon()
{
367
    //eraseCacheFolder();
368 369
    editModeOn_ = true;

370

atraczyk's avatar
atraczyk committed
371 372 373 374 375
    create_task([&]()
    {
        using SharedCallback = std::shared_ptr<DRing::CallbackWrapperBase>;
        using namespace std::placeholders;

Nicolas Jager's avatar
Nicolas Jager committed
376 377
        auto dispatcher = CoreApplication::MainView->CoreWindow->Dispatcher;

atraczyk's avatar
atraczyk committed
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
        std::map<std::string, SharedCallback> 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);

                auto accountId2 = toPlatformString(accountId);
                auto callId2 = toPlatformString(callId);
                auto from2 = toPlatformString(from);

394 395 396
                /* fix some issue in the daemon --> <...@...> */
                from2 = Utils::TrimRingId(from2);

397
                CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
398
                    CoreDispatcherPriority::High, ref new DispatchedHandler([=]()
399 400
                {
                    incomingCall(accountId2, callId2, from2);
401
                    stateChange(callId2, CallStatus::RINGING, 0);
402 403 404 405

                    auto contact = ContactsViewModel::instance->findContactByName(from2);
                    auto item = SmartPanelItemsViewModel::instance->findItem(contact);
                    item->_callId = callId2;
406
                }));
atraczyk's avatar
atraczyk committed
407 408
            }),
            DRing::exportable_callback<DRing::CallSignal::StateChange>([this](
409 410 411
                        const std::string& callId,
                        const std::string& state,
                        int code)
atraczyk's avatar
atraczyk committed
412 413 414 415 416 417 418 419 420
            {
                MSG_("<StateChange>");
                MSG_("callId = " + callId);
                MSG_("state = " + state);
                MSG_("code = " + std::to_string(code));

                auto callId2 = toPlatformString(callId);
                auto state2 = toPlatformString(state);

421
                auto state3 = translateCallStatus(state2);
Nicolas Jager's avatar
Nicolas Jager committed
422

423
                if (state3 == CallStatus::NONE)
424 425
                    DRing::hangUp(callId); // solve a bug in the daemon API.

atraczyk's avatar
atraczyk committed
426

427
                CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
428
                    CoreDispatcherPriority::High, ref new DispatchedHandler([=]()
429
                {
Nicolas Jager's avatar
Nicolas Jager committed
430
                    stateChange(callId2, state3, code);
431
                }));
atraczyk's avatar
atraczyk committed
432
            }),
433
            DRing::exportable_callback<DRing::ConfigurationSignal::IncomingAccountMessage>([&](
434 435 436
                        const std::string& accountId,
                        const std::string& from,
                        const std::map<std::string, std::string>& payloads)
atraczyk's avatar
atraczyk committed
437 438 439 440 441
            {
                MSG_("<IncomingAccountMessage>");
                MSG_("accountId = " + accountId);
                MSG_("from = " + from);

442 443 444
                auto accountId2 = toPlatformString(accountId);
                auto from2 = toPlatformString(from);

atraczyk's avatar
atraczyk committed
445 446 447
                for (auto i : payloads) {
                    MSG_("payload = " + i.second);
                    auto payload = Utils::toPlatformString(i.second);
448
                    CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
449
                        CoreDispatcherPriority::High, ref new DispatchedHandler([=]()
450 451 452
                    {
                        incomingAccountMessage(accountId2, from2, payload);
                    }));
atraczyk's avatar
atraczyk committed
453 454
                }
            }),
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
            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);

                auto callId2 = toPlatformString(callId);
                auto from2 = toPlatformString(from);

                const std::string PROFILE_VCF = "x-ring/ring.profile.vcard";
                static const unsigned int profileSize = PROFILE_VCF.size();

                for (auto i : payloads) {
                    if (i.first.compare(0, profileSize, PROFILE_VCF) == 0) {
                        MSG_("VCARD");
                        return;
                    }
                    MSG_("payload.first = " + i.first);
                    MSG_("payload.second = " + i.second);

                    auto payload = Utils::toPlatformString(i.second);
                    CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
480
                        CoreDispatcherPriority::High, ref new DispatchedHandler([=]()
481
                    {
482
                        incomingMessage(callId2, payload);
483
                        MSG_("message recu :" + i.second);
484 485 486
                    }));
                }
            }),
487
            DRing::exportable_callback<DRing::ConfigurationSignal::RegistrationStateChanged>([this](
488 489
                        const std::string& account_id, const std::string& state,
                        int detailsCode, const std::string& detailsStr)
490
            {
491
                MSG_("<RegistrationStateChanged>: ID = " + account_id + " state = " + state);
492
                if (state == DRing::Account::States::REGISTERED) {
493
                    CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::High,
494
                    ref new DispatchedHandler([=]() {
atraczyk's avatar
atraczyk committed
495
                        reloadAccountList();
496
                        if (editModeOn_) {
497 498
                            auto frame = dynamic_cast<Frame^>(Window::Current->Content);
                            dynamic_cast<RingClientUWP::MainPage^>(frame->Content)->showLoadingOverlay(false, false);
499
                            editModeOn_ = false;
500
                        }
501 502 503
                    }));
                }
            }),
atraczyk's avatar
atraczyk committed
504 505
            DRing::exportable_callback<DRing::ConfigurationSignal::AccountsChanged>([this]()
            {
506
                MSG_("<AccountsChanged>");
507
                CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::High,
508
                ref new DispatchedHandler([=]() {
atraczyk's avatar
atraczyk committed
509
                    reloadAccountList();
510 511 512 513 514
                    if (editModeOn_) {
                        auto frame = dynamic_cast<Frame^>(Window::Current->Content);
                        dynamic_cast<RingClientUWP::MainPage^>(frame->Content)->showLoadingOverlay(false, false);
                        editModeOn_ = false;
                    }
atraczyk's avatar
atraczyk committed
515
                }));
Nicolas Jager's avatar
Nicolas Jager committed
516
            }),
Nicolas Jager's avatar
Nicolas Jager committed
517 518
            DRing::exportable_callback<DRing::Debug::MessageSend>([&](const std::string& toto)
            {
519
                dispatcher->RunAsync(CoreDispatcherPriority::High,
Nicolas Jager's avatar
Nicolas Jager committed
520 521 522
                ref new DispatchedHandler([=]() {
                    RingDebug::instance->print(toto);
                }));
523 524 525 526 527 528 529
            }),


            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([=]() {
530 531 532 533 534 535
                    RingDebug::instance->print("KnownDevicesChanged ---> C PAS FINI");
                }));
            }),
            DRing::exportable_callback<DRing::ConfigurationSignal::ExportOnRingEnded>([&](const std::string& accountId, int status, const std::string& pin)
            {
                auto accountId2 = Utils::toPlatformString(accountId);
Nicolas Jager's avatar
Nicolas Jager committed
536
                auto pin2 = (pin.empty()) ? "Error bad password" : "Your generated pin : " + Utils::toPlatformString(pin);
537 538 539
                dispatcher->RunAsync(CoreDispatcherPriority::High,
                ref new DispatchedHandler([=]() {
                    exportOnRingEnded(accountId2, pin2);
540
                }));
Nicolas Jager's avatar
Nicolas Jager committed
541
            })
542 543


atraczyk's avatar
atraczyk committed
544 545 546 547 548 549 550 551 552 553 554 555
        };
        registerCallHandlers(callHandlers);

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

556 557 558 559 560 561 562 563 564 565 566 567
        std::map<std::string, SharedCallback> 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);

atraczyk's avatar
atraczyk committed
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
        std::map<std::string, SharedCallback> incomingVideoHandlers =
        {
            DRing::exportable_callback<DRing::VideoSignal::DeviceEvent>
            ([this]() {
                MSG_("<DeviceEvent>");
            }),
            DRing::exportable_callback<DRing::VideoSignal::DecodingStarted>
            ([this](const std::string &id, const std::string &shmPath, int width, int height, bool isMixer) {
                MSG_("<DecodingStarted>");
                Video::VideoManager::instance->rendererManager()->startedDecoding(
                    Utils::toPlatformString(id),
                    width,
                    height);
            }),
            DRing::exportable_callback<DRing::VideoSignal::DecodingStopped>
            ([this](const std::string &id, const std::string &shmPath, bool isMixer) {
                MSG_("<DecodingStopped>");
                MSG_("Removing renderer id:" + id);
                Video::VideoManager::instance->rendererManager()->removeRenderer(Utils::toPlatformString(id));
            })
        };
        registerVideoHandlers(incomingVideoHandlers);

        using namespace Video;
        std::map<std::string, SharedCallback> outgoingVideoHandlers =
        {
            DRing::exportable_callback<DRing::VideoSignal::GetCameraInfo>
            ([this](const std::string& device,
596 597 598
            std::vector<std::string> *formats,
            std::vector<unsigned> *sizes,
            std::vector<unsigned> *rates) {
atraczyk's avatar
atraczyk committed
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
                MSG_("\n<GetCameraInfo>\n");
                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())) {
                        auto channel = dev->channel();
                        Vector<Video::Resolution^>^ resolutions = channel->resolutionList();
                        for (auto res : resolutions) {
                            formats->emplace_back(Utils::toString(res->format()));
                            sizes->emplace_back(res->size()->width());
                            sizes->emplace_back(res->size()->height());
                            rates->emplace_back(res->activeRate()->value());
                        }
                    }
                }
            }),
            DRing::exportable_callback<DRing::VideoSignal::SetParameters>
            ([this](const std::string& device,
                    std::string format,
                    const int width,
                    const int height,
621
            const int rate) {
atraczyk's avatar
atraczyk committed
622 623 624 625 626 627 628
                MSG_("\n<SetParameters>\n");
                VideoManager::instance->captureManager()->activeDevice->SetDeviceProperties(
                    Utils::toPlatformString(format),width,height,rate);
            }),
            DRing::exportable_callback<DRing::VideoSignal::StartCapture>
            ([&](const std::string& device) {
                MSG_("\n<StartCapture>\n");
629
                dispatcher->RunAsync(CoreDispatcherPriority::High,
atraczyk's avatar
atraczyk committed
630 631 632 633 634 635 636 637
                ref new DispatchedHandler([=]() {
                    VideoManager::instance->captureManager()->InitializeCameraAsync();
                    VideoManager::instance->captureManager()->videoFrameCopyInvoker->Start();
                }));
            }),
            DRing::exportable_callback<DRing::VideoSignal::StopCapture>
            ([&]() {
                MSG_("\n<StopCapture>\n");
638
                dispatcher->RunAsync(CoreDispatcherPriority::High,
atraczyk's avatar
atraczyk committed
639 640 641 642 643 644 645 646 647 648
                ref new DispatchedHandler([=]() {
                    VideoManager::instance->captureManager()->StopPreviewAsync();
                    if (VideoManager::instance->captureManager()->captureTaskTokenSource)
                        VideoManager::instance->captureManager()->captureTaskTokenSource->cancel();
                    VideoManager::instance->captureManager()->videoFrameCopyInvoker->Stop();
                }));
            })
        };
        registerVideoHandlers(outgoingVideoHandlers);

649
        DRing::init(static_cast<DRing::InitFlag>(DRing::DRING_FLAG_CONSOLE_LOG |
650
                    DRing::DRING_FLAG_DEBUG));
atraczyk's avatar
atraczyk committed
651 652 653 654 655 656

        if (!DRing::start()) {
            ERR_("\ndaemon didn't start.\n");
            return;
        }
        else {
657 658 659 660 661 662 663 664 665 666
            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,
667
                ref new DispatchedHandler([=]() {
atraczyk's avatar
atraczyk committed
668 669
                    reloadAccountList();
                }));
670
                break;
atraczyk's avatar
atraczyk committed
671
            }
672 673
            }

674 675 676 677 678 679 680 681 682 683 684 685 686 687 688

            /* at this point the config.yml is safe. */
            Utils::fileExists(ApplicationData::Current->LocalFolder, "creation.token")
            .then([this](bool token_exists)
            {
                if (token_exists) {
                    StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
                    task<StorageFile^>(storageFolder->GetFileAsync("creation.token")).then([this](StorageFile^ file)
                    {
                        file->DeleteAsync();
                    });
                }
            });


atraczyk's avatar
atraczyk committed
689 690 691
            while (true) {
                DRing::pollEvents();
                dequeueTasks();
692
                Sleep(5);
atraczyk's avatar
atraczyk committed
693 694 695 696 697 698 699 700 701
            }
            DRing::fini();
        }
    });
}

RingD::RingD()
{
    localFolder_ = Utils::toString(ApplicationData::Current->LocalFolder->Path);
702
    callIdsList_ = ref new Vector<String^>();
703
    currentCallId = nullptr;
atraczyk's avatar
atraczyk committed
704 705 706 707 708 709 710
}

void
RingD::dequeueTasks()
{
    for (int i = 0; i < tasksList_.size(); i++) {
        auto task = tasksList_.front();
711 712
        auto request = dynamic_cast<Task^>(task)->request;
        switch (request) {
atraczyk's avatar
atraczyk committed
713
        case Request::None:
714 715
            break;
        case Request::AddRingAccount:
716 717
        {
            std::map<std::string, std::string> ringAccountDetails;
718 719 720 721
            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
722
            ringAccountDetails.insert(std::make_pair(DRing::Account::ConfProperties::TYPE,"RING"));
723 724
            ringAccountDetails.insert(std::make_pair(DRing::Account::ConfProperties::UPNP_ENABLED
                                      , (task->_upnp)? ring::TRUE_STR : ring::FALSE_STR));
725 726 727
            DRing::addAccount(ringAccountDetails);
        }
        break;
728
        case Request::AddSIPAccount:
729 730
        {
            std::map<std::string, std::string> sipAccountDetails;
731 732
            sipAccountDetails.insert(std::make_pair(DRing::Account::ConfProperties::ALIAS
                                                    , Utils::toString(task->_alias)));
atraczyk's avatar
atraczyk committed
733
            sipAccountDetails.insert(std::make_pair(DRing::Account::ConfProperties::TYPE,"SIP"));
734 735 736 737 738 739
            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)));
740 741 742
            DRing::addAccount(sipAccountDetails);
        }
        break;
743 744
        case Request::RefuseIncommingCall:
        {
745
            auto callId = task->_callId;
746 747 748 749 750 751
            auto callId2 = Utils::toString(callId);
            DRing::refuse(callId2);
        }
        break;
        case Request::AcceptIncommingCall:
        {
752
            auto callId = task->_callId;
753 754 755 756
            auto callId2 = Utils::toString(callId);
            DRing::accept(callId2);
        }
        break;
Nicolas Jager's avatar
Nicolas Jager committed
757
        case Request::CancelOutGoingCall:
758
        case Request::HangUpCall:
Nicolas Jager's avatar
Nicolas Jager committed
759
        {
760 761
            auto callId = task->_callId;
            DRing::hangUp(Utils::toString(callId));
Nicolas Jager's avatar
Nicolas Jager committed
762 763
        }
        break;
764 765 766 767 768 769 770 771 772 773
        case Request::PauseCall:
        {
            DRing::hold(Utils::toString(task->_callId));
        }
        break;
        case Request::UnPauseCall:
        {
            DRing::unhold(Utils::toString(task->_callId));
        }
        break;
774 775
        case Request::RegisterDevice:
        {
776 777
            auto pin = Utils::toString(task->_pin);
            auto password = Utils::toString(task->_password);
778 779 780 781 782 783 784 785 786

            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);
        }
787 788 789 790 791 792
        case Request::GetKnownDevices:
        {
            auto accountId = task->_accountId;
            auto accountId2 = Utils::toString(accountId);

            auto devicesList = DRing::getKnownRingDevices(accountId2);
793 794 795
            if (devicesList.empty())
                break;

796 797
            auto devicesList2 = translateKnownRingDevices(devicesList);

798 799 800 801
            CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(CoreDispatcherPriority::Normal,
            ref new DispatchedHandler([=]() {
                devicesListRefreshed(devicesList2);
            }));
Nicolas Jager's avatar
Nicolas Jager committed
802
            break;
803 804 805 806 807 808 809 810 811 812
        }
        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);
813 814 815 816 817 818 819 820 821 822 823 824 825
            break;
        }
        case Request::UpdateAccount:
        {
            auto accountId = task->_accountId;
            auto accountId2 = Utils::toString(accountId);
            auto account = AccountListItemsViewModel::instance->findItem(accountId)->_account;
            std::map<std::string, std::string> accountDetails = DRing::getAccountDetails(accountId2);
            accountDetails[DRing::Account::ConfProperties::UPNP_ENABLED] = (account->_upnpState) ? ring::TRUE_STR : ring::FALSE_STR;
            accountDetails[DRing::Account::ConfProperties::ALIAS] = Utils::toString(account->name_);

            DRing::setAccountDetails(Utils::toString(account->accountID_), accountDetails);
            break;
826 827 828 829 830 831 832 833
        }
        case Request::DeleteAccount:
        {
            auto accountId = task->_accountId;
            auto accountId2 = Utils::toString(accountId);

            DRing::removeAccount(accountId2);
            break;
834
        }
atraczyk's avatar
atraczyk committed
835 836 837 838 839 840
        default:
            break;
        }
        tasksList_.pop();
    }
}
Nicolas Jager's avatar
Nicolas Jager committed
841

842
RingClientUWP::CallStatus RingClientUWP::RingD::translateCallStatus(String^ state)
Nicolas Jager's avatar
Nicolas Jager committed
843 844
{
    if (state == "INCOMING")
845
        return CallStatus::RINGING;
Nicolas Jager's avatar
Nicolas Jager committed
846 847 848 849

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

850 851
    if (state == "CONNECTING" || state == "RINGING")
        return CallStatus::CONNECTING;
Nicolas Jager's avatar
Nicolas Jager committed
852

853

Nicolas Jager's avatar
Nicolas Jager committed
854 855
    return CallStatus::NONE;
}
856

857 858 859 860 861 862 863
String^
RingD::getUserName()
{
    auto users = User::FindAllAsync();
    return nullptr;
}

864 865 866 867 868 869 870
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);
871 872
        auto deviceName = Utils::toPlatformString(i.second);
        devicesList->Append(deviceName);
873 874 875
    }


876

877 878
    return devicesList;
}