summaryrefslogtreecommitdiffstats
path: root/dom/presentation/PresentationConnection.cpp
blob: e9c4a71ca22718bdae4b165238902946d12a625b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
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
752
753
754
755
756
757
758
759
760
761
762
763
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "PresentationConnection.h"

#include "ControllerConnectionCollection.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/dom/DOMException.h"
#include "mozilla/dom/File.h"
#include "mozilla/dom/MessageEvent.h"
#include "mozilla/dom/MessageEventBinding.h"
#include "mozilla/dom/PresentationConnectionCloseEvent.h"
#include "mozilla/ErrorNames.h"
#include "mozilla/DebugOnly.h"
#include "nsContentUtils.h"
#include "nsCycleCollectionParticipant.h"
#include "nsIPresentationService.h"
#include "nsServiceManagerUtils.h"
#include "nsStringStream.h"
#include "PresentationConnectionList.h"
#include "PresentationLog.h"

using namespace mozilla;
using namespace mozilla::dom;

NS_IMPL_CYCLE_COLLECTION_CLASS(PresentationConnection)

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(PresentationConnection, DOMEventTargetHelper)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOwningConnectionList)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(PresentationConnection, DOMEventTargetHelper)
  tmp->Shutdown();
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mOwningConnectionList)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END

NS_IMPL_ADDREF_INHERITED(PresentationConnection, DOMEventTargetHelper)
NS_IMPL_RELEASE_INHERITED(PresentationConnection, DOMEventTargetHelper)

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(PresentationConnection)
  NS_INTERFACE_MAP_ENTRY(nsIPresentationSessionListener)
  NS_INTERFACE_MAP_ENTRY(nsIRequest)
NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)

PresentationConnection::PresentationConnection(nsPIDOMWindowInner* aWindow,
                                               const nsAString& aId,
                                               const nsAString& aUrl,
                                               const uint8_t aRole,
                                               PresentationConnectionList* aList)
  : DOMEventTargetHelper(aWindow)
  , mId(aId)
  , mUrl(aUrl)
  , mState(PresentationConnectionState::Connecting)
  , mOwningConnectionList(aList)
  , mBinaryType(PresentationConnectionBinaryType::Arraybuffer)
{
  MOZ_ASSERT(aRole == nsIPresentationService::ROLE_CONTROLLER ||
             aRole == nsIPresentationService::ROLE_RECEIVER);
  mRole = aRole;
}

/* virtual */ PresentationConnection::~PresentationConnection()
{
}

/* static */ already_AddRefed<PresentationConnection>
PresentationConnection::Create(nsPIDOMWindowInner* aWindow,
                               const nsAString& aId,
                               const nsAString& aUrl,
                               const uint8_t aRole,
                               PresentationConnectionList* aList)
{
  MOZ_ASSERT(aRole == nsIPresentationService::ROLE_CONTROLLER ||
             aRole == nsIPresentationService::ROLE_RECEIVER);
  RefPtr<PresentationConnection> connection =
    new PresentationConnection(aWindow, aId, aUrl, aRole, aList);
  if (NS_WARN_IF(!connection->Init())) {
    return nullptr;
  }

  if (aRole == nsIPresentationService::ROLE_CONTROLLER) {
    ControllerConnectionCollection::GetSingleton()->AddConnection(connection,
                                                                  aRole);
  }

  return connection.forget();
}

bool
PresentationConnection::Init()
{
  if (NS_WARN_IF(mId.IsEmpty())) {
    return false;
  }

  nsCOMPtr<nsIPresentationService> service =
    do_GetService(PRESENTATION_SERVICE_CONTRACTID);
  if(NS_WARN_IF(!service)) {
    return false;
  }

  nsresult rv = service->RegisterSessionListener(mId, mRole, this);
  if(NS_WARN_IF(NS_FAILED(rv))) {
    return false;
  }

  rv = AddIntoLoadGroup();
  if(NS_WARN_IF(NS_FAILED(rv))) {
    return false;
  }

  return true;
}

void
PresentationConnection::Shutdown()
{
  PRES_DEBUG("connection shutdown:id[%s], role[%d]\n",
             NS_ConvertUTF16toUTF8(mId).get(), mRole);

  nsCOMPtr<nsIPresentationService> service =
    do_GetService(PRESENTATION_SERVICE_CONTRACTID);
  if (NS_WARN_IF(!service)) {
    return;
  }

  DebugOnly<nsresult> rv = service->UnregisterSessionListener(mId, mRole);
  NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "UnregisterSessionListener failed");

  DebugOnly<nsresult> rv2 = RemoveFromLoadGroup();
  NS_WARNING_ASSERTION(NS_SUCCEEDED(rv2), "RemoveFromLoadGroup failed");

  if (mRole == nsIPresentationService::ROLE_CONTROLLER) {
    ControllerConnectionCollection::GetSingleton()->RemoveConnection(this,
                                                                     mRole);
  }
}

/* virtual */ void
PresentationConnection::DisconnectFromOwner()
{
  Unused << NS_WARN_IF(NS_FAILED(ProcessConnectionWentAway()));
  DOMEventTargetHelper::DisconnectFromOwner();
}

/* virtual */ JSObject*
PresentationConnection::WrapObject(JSContext* aCx,
                                   JS::Handle<JSObject*> aGivenProto)
{
  return PresentationConnectionBinding::Wrap(aCx, this, aGivenProto);
}

void
PresentationConnection::GetId(nsAString& aId) const
{
  aId = mId;
}

void
PresentationConnection::GetUrl(nsAString& aUrl) const
{
  aUrl = mUrl;
}

PresentationConnectionState
PresentationConnection::State() const
{
  return mState;
}

PresentationConnectionBinaryType
PresentationConnection::BinaryType() const
{
  return mBinaryType;
}

void
PresentationConnection::SetBinaryType(PresentationConnectionBinaryType aType)
{
  mBinaryType = aType;
}

void
PresentationConnection::Send(const nsAString& aData,
                             ErrorResult& aRv)
{
  // Sending is not allowed if the session is not connected.
  if (NS_WARN_IF(mState != PresentationConnectionState::Connected)) {
    aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
    return;
  }

  nsCOMPtr<nsIPresentationService> service =
    do_GetService(PRESENTATION_SERVICE_CONTRACTID);
  if(NS_WARN_IF(!service)) {
    AsyncCloseConnectionWithErrorMsg(
      NS_LITERAL_STRING("Unable to send message due to an internal error."));
    return;
  }

  nsresult rv = service->SendSessionMessage(mId, mRole, aData);
  if(NS_WARN_IF(NS_FAILED(rv))) {
    const uint32_t kMaxMessageLength = 256;
    nsAutoString data(Substring(aData, 0, kMaxMessageLength));

    AsyncCloseConnectionWithErrorMsg(
      NS_LITERAL_STRING("Unable to send message: \"") + data +
      NS_LITERAL_STRING("\""));
  }
}

void
PresentationConnection::Send(Blob& aData,
                             ErrorResult& aRv)
{
  if (NS_WARN_IF(mState != PresentationConnectionState::Connected)) {
    aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
    return;
  }

  nsCOMPtr<nsIPresentationService> service =
    do_GetService(PRESENTATION_SERVICE_CONTRACTID);
  if(NS_WARN_IF(!service)) {
    AsyncCloseConnectionWithErrorMsg(
      NS_LITERAL_STRING("Unable to send message due to an internal error."));
    return;
  }

  nsresult rv = service->SendSessionBlob(mId, mRole, &aData);
  if(NS_WARN_IF(NS_FAILED(rv))) {
    AsyncCloseConnectionWithErrorMsg(
      NS_LITERAL_STRING("Unable to send binary message for Blob message."));
  }
}

void
PresentationConnection::Send(const ArrayBuffer& aData,
                             ErrorResult& aRv)
{
  if (NS_WARN_IF(mState != PresentationConnectionState::Connected)) {
    aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
    return;
  }

  nsCOMPtr<nsIPresentationService> service =
    do_GetService(PRESENTATION_SERVICE_CONTRACTID);
  if(NS_WARN_IF(!service)) {
    AsyncCloseConnectionWithErrorMsg(
      NS_LITERAL_STRING("Unable to send message due to an internal error."));
    return;
  }

  aData.ComputeLengthAndData();

  static_assert(sizeof(*aData.Data()) == 1, "byte-sized data required");

  uint32_t length = aData.Length();
  char* data = reinterpret_cast<char*>(aData.Data());
  nsDependentCSubstring msgString(data, length);

  nsresult rv = service->SendSessionBinaryMsg(mId, mRole, msgString);
  if(NS_WARN_IF(NS_FAILED(rv))) {
    AsyncCloseConnectionWithErrorMsg(
      NS_LITERAL_STRING("Unable to send binary message for ArrayBuffer message."));
  }
}

void
PresentationConnection::Send(const ArrayBufferView& aData,
                             ErrorResult& aRv)
{
  if (NS_WARN_IF(mState != PresentationConnectionState::Connected)) {
    aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
    return;
  }

  nsCOMPtr<nsIPresentationService> service =
    do_GetService(PRESENTATION_SERVICE_CONTRACTID);
  if(NS_WARN_IF(!service)) {
    AsyncCloseConnectionWithErrorMsg(
      NS_LITERAL_STRING("Unable to send message due to an internal error."));
    return;
  }

  aData.ComputeLengthAndData();

  static_assert(sizeof(*aData.Data()) == 1, "byte-sized data required");

  uint32_t length = aData.Length();
  char* data = reinterpret_cast<char*>(aData.Data());
  nsDependentCSubstring msgString(data, length);

  nsresult rv = service->SendSessionBinaryMsg(mId, mRole, msgString);
  if(NS_WARN_IF(NS_FAILED(rv))) {
    AsyncCloseConnectionWithErrorMsg(
      NS_LITERAL_STRING("Unable to send binary message for ArrayBufferView message."));
  }
}

void
PresentationConnection::Close(ErrorResult& aRv)
{
  // It only works when the state is CONNECTED or CONNECTING.
  if (NS_WARN_IF(mState != PresentationConnectionState::Connected &&
                 mState != PresentationConnectionState::Connecting)) {
    return;
  }

  nsCOMPtr<nsIPresentationService> service =
    do_GetService(PRESENTATION_SERVICE_CONTRACTID);
  if(NS_WARN_IF(!service)) {
    aRv.Throw(NS_ERROR_DOM_OPERATION_ERR);
    return;
  }

  Unused << NS_WARN_IF(NS_FAILED(
    service->CloseSession(mId,
                          mRole,
                          nsIPresentationService::CLOSED_REASON_CLOSED)));
}

void
PresentationConnection::Terminate(ErrorResult& aRv)
{
  // It only works when the state is CONNECTED.
  if (NS_WARN_IF(mState != PresentationConnectionState::Connected)) {
    return;
  }

  nsCOMPtr<nsIPresentationService> service =
    do_GetService(PRESENTATION_SERVICE_CONTRACTID);
  if(NS_WARN_IF(!service)) {
    aRv.Throw(NS_ERROR_DOM_OPERATION_ERR);
    return;
  }

  Unused << NS_WARN_IF(NS_FAILED(service->TerminateSession(mId, mRole)));
}

bool
PresentationConnection::Equals(uint64_t aWindowId,
                               const nsAString& aId)
{
  return GetOwner() &&
         aWindowId == GetOwner()->WindowID() &&
         mId.Equals(aId);
}

NS_IMETHODIMP
PresentationConnection::NotifyStateChange(const nsAString& aSessionId,
                                          uint16_t aState,
                                          nsresult aReason)
{
  PRES_DEBUG("connection state change:id[%s], state[%x], reason[%x], role[%d]\n",
             NS_ConvertUTF16toUTF8(aSessionId).get(), aState,
             aReason, mRole);

  if (!aSessionId.Equals(mId)) {
    return NS_ERROR_INVALID_ARG;
  }

  // A terminated connection should always remain in terminated.
  if (mState == PresentationConnectionState::Terminated) {
    return NS_OK;
  }

  PresentationConnectionState state;
  switch (aState) {
    case nsIPresentationSessionListener::STATE_CONNECTING:
      state = PresentationConnectionState::Connecting;
      break;
    case nsIPresentationSessionListener::STATE_CONNECTED:
      state = PresentationConnectionState::Connected;
      break;
    case nsIPresentationSessionListener::STATE_CLOSED:
      state = PresentationConnectionState::Closed;
      break;
    case nsIPresentationSessionListener::STATE_TERMINATED:
      state = PresentationConnectionState::Terminated;
      break;
    default:
      NS_WARNING("Unknown presentation session state.");
      return NS_ERROR_INVALID_ARG;
  }

  if (mState == state) {
    return NS_OK;
  }
  mState = state;

  nsresult rv = ProcessStateChanged(aReason);
  if(NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
  }

  if (mOwningConnectionList) {
    mOwningConnectionList->NotifyStateChange(aSessionId, this);
  }

  return NS_OK;
}

nsresult
PresentationConnection::ProcessStateChanged(nsresult aReason)
{
  switch (mState) {
    case PresentationConnectionState::Connecting:
      return NS_OK;
    case PresentationConnectionState::Connected: {
      RefPtr<AsyncEventDispatcher> asyncDispatcher =
        new AsyncEventDispatcher(this, NS_LITERAL_STRING("connect"), false);
      return asyncDispatcher->PostDOMEvent();
    }
    case PresentationConnectionState::Closed: {
      PresentationConnectionClosedReason reason =
        PresentationConnectionClosedReason::Closed;

      nsString errorMsg;
      if (NS_FAILED(aReason)) {
        reason = PresentationConnectionClosedReason::Error;
        nsCString name, message;

        // If aReason is not a DOM error, use error name as message.
        if (NS_FAILED(NS_GetNameAndMessageForDOMNSResult(aReason,
                                                         name,
                                                         message))) {
          mozilla::GetErrorName(aReason, message);
          message.InsertLiteral("Internal error: ", 0);
        }
        CopyUTF8toUTF16(message, errorMsg);
      }

      Unused <<
        NS_WARN_IF(NS_FAILED(DispatchConnectionCloseEvent(reason, errorMsg)));

      return RemoveFromLoadGroup();
    }
    case PresentationConnectionState::Terminated: {
      // Ensure onterminate event is fired.
      RefPtr<AsyncEventDispatcher> asyncDispatcher =
        new AsyncEventDispatcher(this, NS_LITERAL_STRING("terminate"), false);
      Unused << NS_WARN_IF(NS_FAILED(asyncDispatcher->PostDOMEvent()));

      nsCOMPtr<nsIPresentationService> service =
        do_GetService(PRESENTATION_SERVICE_CONTRACTID);
      if (NS_WARN_IF(!service)) {
        return NS_ERROR_NOT_AVAILABLE;
      }

      nsresult rv = service->UnregisterSessionListener(mId, mRole);
      if(NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
      }

      return RemoveFromLoadGroup();
    }
    default:
      MOZ_CRASH("Unknown presentation session state.");
      return NS_ERROR_INVALID_ARG;
  }
}

NS_IMETHODIMP
PresentationConnection::NotifyMessage(const nsAString& aSessionId,
                                      const nsACString& aData,
                                      bool aIsBinary)
{
  PRES_DEBUG("connection %s:id[%s], data[%s], role[%d]\n", __func__,
             NS_ConvertUTF16toUTF8(aSessionId).get(),
             nsPromiseFlatCString(aData).get(), mRole);

  if (!aSessionId.Equals(mId)) {
    return NS_ERROR_INVALID_ARG;
  }

  // No message should be expected when the session is not connected.
  if (NS_WARN_IF(mState != PresentationConnectionState::Connected)) {
    return NS_ERROR_DOM_INVALID_STATE_ERR;
  }

  if (NS_WARN_IF(NS_FAILED(DoReceiveMessage(aData, aIsBinary)))) {
    AsyncCloseConnectionWithErrorMsg(
      NS_LITERAL_STRING("Unable to receive a message."));
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}

nsresult
PresentationConnection::DoReceiveMessage(const nsACString& aData, bool aIsBinary)
{
  // Transform the data.
  AutoJSAPI jsapi;
  if (!jsapi.Init(GetOwner())) {
    return NS_ERROR_FAILURE;
  }
  JSContext* cx = jsapi.cx();
  JS::Rooted<JS::Value> jsData(cx);

  nsresult rv;
  if (aIsBinary) {
    if (mBinaryType == PresentationConnectionBinaryType::Blob) {
      RefPtr<Blob> blob =
        Blob::CreateStringBlob(GetOwner(), aData, EmptyString());
      MOZ_ASSERT(blob);

      if (!ToJSValue(cx, blob, &jsData)) {
        return NS_ERROR_FAILURE;
      }
    } else if (mBinaryType == PresentationConnectionBinaryType::Arraybuffer) {
      JS::Rooted<JSObject*> arrayBuf(cx);
      rv = nsContentUtils::CreateArrayBuffer(cx, aData, arrayBuf.address());
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
      }
      jsData.setObject(*arrayBuf);
    } else {
      NS_RUNTIMEABORT("Unknown binary type!");
      return NS_ERROR_UNEXPECTED;
    }
  } else {
    NS_ConvertUTF8toUTF16 utf16Data(aData);
    if(NS_WARN_IF(!ToJSValue(cx, utf16Data, &jsData))) {
      return NS_ERROR_FAILURE;
    }
  }

  return DispatchMessageEvent(jsData);
}

nsresult
PresentationConnection::DispatchConnectionCloseEvent(
  PresentationConnectionClosedReason aReason,
  const nsAString& aMessage,
  bool aDispatchNow)
{
  if (mState != PresentationConnectionState::Closed) {
    MOZ_ASSERT(false, "The connection state should be closed.");
    return NS_ERROR_FAILURE;
  }

  PresentationConnectionCloseEventInit init;
  init.mReason = aReason;
  init.mMessage = aMessage;

  RefPtr<PresentationConnectionCloseEvent> closedEvent =
    PresentationConnectionCloseEvent::Constructor(this,
                                                   NS_LITERAL_STRING("close"),
                                                   init);
  closedEvent->SetTrusted(true);

  if (aDispatchNow) {
    bool ignore;
    return DOMEventTargetHelper::DispatchEvent(closedEvent, &ignore);
  }

  RefPtr<AsyncEventDispatcher> asyncDispatcher =
    new AsyncEventDispatcher(this, static_cast<Event*>(closedEvent));
  return asyncDispatcher->PostDOMEvent();
}

nsresult
PresentationConnection::DispatchMessageEvent(JS::Handle<JS::Value> aData)
{
  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetOwner());
  if (NS_WARN_IF(!global)) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  // Get the origin.
  nsAutoString origin;
  nsresult rv = nsContentUtils::GetUTFOrigin(global->PrincipalOrNull(), origin);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  RefPtr<MessageEvent> messageEvent = new MessageEvent(this, nullptr, nullptr);

  messageEvent->InitMessageEvent(nullptr,
                                 NS_LITERAL_STRING("message"),
                                 false, false, aData, origin,
                                 EmptyString(), nullptr,
                                 Sequence<OwningNonNull<MessagePort>>());
  messageEvent->SetTrusted(true);

  RefPtr<AsyncEventDispatcher> asyncDispatcher =
    new AsyncEventDispatcher(this, static_cast<Event*>(messageEvent));
  return asyncDispatcher->PostDOMEvent();
}

nsresult
PresentationConnection::ProcessConnectionWentAway()
{
  if (mState != PresentationConnectionState::Connected &&
      mState != PresentationConnectionState::Connecting) {
    // If the state is not connected or connecting, do not need to
    // close the session.
    return NS_OK;
  }

  mState = PresentationConnectionState::Terminated;

  nsCOMPtr<nsIPresentationService> service =
    do_GetService(PRESENTATION_SERVICE_CONTRACTID);
  if (NS_WARN_IF(!service)) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  return service->CloseSession(
    mId, mRole, nsIPresentationService::CLOSED_REASON_WENTAWAY);
}

NS_IMETHODIMP
PresentationConnection::GetName(nsACString &aResult)
{
  aResult.AssignLiteral("about:presentation-connection");
  return NS_OK;
}

NS_IMETHODIMP
PresentationConnection::IsPending(bool* aRetval)
{
  *aRetval = true;
  return NS_OK;
}

NS_IMETHODIMP
PresentationConnection::GetStatus(nsresult* aStatus)
{
  *aStatus = NS_OK;
  return NS_OK;
}

NS_IMETHODIMP
PresentationConnection::Cancel(nsresult aStatus)
{
  nsCOMPtr<nsIRunnable> event =
    NewRunnableMethod(this, &PresentationConnection::ProcessConnectionWentAway);
  return NS_DispatchToCurrentThread(event);
}
NS_IMETHODIMP
PresentationConnection::Suspend(void)
{
  return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
PresentationConnection::Resume(void)
{
  return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP
PresentationConnection::GetLoadGroup(nsILoadGroup** aLoadGroup)
{
  *aLoadGroup = nullptr;

  nsCOMPtr<nsIDocument> doc = GetOwner() ? GetOwner()->GetExtantDoc() : nullptr;
  if (!doc) {
    return NS_ERROR_FAILURE;
  }

  *aLoadGroup = doc->GetDocumentLoadGroup().take();
  return NS_OK;
}

NS_IMETHODIMP
PresentationConnection::SetLoadGroup(nsILoadGroup * aLoadGroup)
{
  return NS_ERROR_UNEXPECTED;
}

NS_IMETHODIMP
PresentationConnection::GetLoadFlags(nsLoadFlags* aLoadFlags)
{
  *aLoadFlags = nsIRequest::LOAD_BACKGROUND;
  return NS_OK;
}

NS_IMETHODIMP
PresentationConnection::SetLoadFlags(nsLoadFlags aLoadFlags)
{
  return NS_OK;
}

nsresult
PresentationConnection::AddIntoLoadGroup()
{
  // Avoid adding to loadgroup multiple times
  if (mWeakLoadGroup) {
    return NS_OK;
  }

  nsCOMPtr<nsILoadGroup> loadGroup;
  nsresult rv = GetLoadGroup(getter_AddRefs(loadGroup));
  if(NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  rv = loadGroup->AddRequest(this, nullptr);
  if(NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  mWeakLoadGroup = do_GetWeakReference(loadGroup);
  return NS_OK;
}

nsresult
PresentationConnection::RemoveFromLoadGroup()
{
  if (!mWeakLoadGroup) {
    return NS_OK;
  }

  nsCOMPtr<nsILoadGroup> loadGroup = do_QueryReferent(mWeakLoadGroup);
  if (loadGroup) {
    mWeakLoadGroup = nullptr;
    return loadGroup->RemoveRequest(this, nullptr, NS_OK);
  }

  return NS_OK;
}

void
PresentationConnection::AsyncCloseConnectionWithErrorMsg(const nsAString& aMessage)
{
  if (mState == PresentationConnectionState::Terminated) {
    return;
  }

  nsString message = nsString(aMessage);
  RefPtr<PresentationConnection> self = this;
  nsCOMPtr<nsIRunnable> r =
    NS_NewRunnableFunction([self, message]() -> void {
      // Set |mState| to |PresentationConnectionState::Closed| here to avoid
      // calling |ProcessStateChanged|.
      self->mState = PresentationConnectionState::Closed;

      // Make sure dispatching the event and closing the connection are invoked
      // at the same time by setting |aDispatchNow| to true.
      Unused << NS_WARN_IF(NS_FAILED(
        self->DispatchConnectionCloseEvent(PresentationConnectionClosedReason::Error,
                                           message,
                                           true)));

      nsCOMPtr<nsIPresentationService> service =
        do_GetService(PRESENTATION_SERVICE_CONTRACTID);
      if(NS_WARN_IF(!service)) {
        return;
      }

      Unused << NS_WARN_IF(NS_FAILED(
        service->CloseSession(self->mId,
                              self->mRole,
                              nsIPresentationService::CLOSED_REASON_ERROR)));
    });

  Unused << NS_WARN_IF(NS_FAILED(NS_DispatchToMainThread(r)));
}