forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNotification.cpp
2492 lines (2160 loc) · 72.9 KB
/
Notification.cpp
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
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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 "mozilla/dom/Notification.h"
#include "mozilla/Move.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/Preferences.h"
#include "mozilla/Services.h"
#include "mozilla/unused.h"
#include "mozilla/dom/AppNotificationServiceOptionsBinding.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/NotificationEvent.h"
#include "mozilla/dom/PermissionMessageUtils.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/PromiseWorkerProxy.h"
#include "mozilla/dom/ServiceWorkerGlobalScopeBinding.h"
#include "nsContentPermissionHelper.h"
#include "nsContentUtils.h"
#include "nsDOMJSUtils.h"
#include "nsGlobalWindow.h"
#include "nsIAlertsService.h"
#include "nsIAppsService.h"
#include "nsIContentPermissionPrompt.h"
#include "nsIDocument.h"
#include "nsILoadContext.h"
#include "nsINotificationStorage.h"
#include "nsIPermissionManager.h"
#include "nsIScriptSecurityManager.h"
#include "nsIServiceWorkerManager.h"
#include "nsIUUIDGenerator.h"
#include "nsIXPConnect.h"
#include "nsNetUtil.h"
#include "nsProxyRelease.h"
#include "nsServiceManagerUtils.h"
#include "nsStructuredCloneContainer.h"
#include "nsToolkitCompsCID.h"
#include "nsXULAppAPI.h"
#include "ServiceWorkerManager.h"
#include "WorkerPrivate.h"
#include "WorkerRunnable.h"
#include "WorkerScope.h"
#ifdef MOZ_B2G
#include "nsIDOMDesktopNotification.h"
#endif
#ifndef MOZ_SIMPLEPUSH
#include "nsIPushNotificationService.h"
#endif
namespace mozilla {
namespace dom {
using namespace workers;
struct NotificationStrings
{
const nsString mID;
const nsString mTitle;
const nsString mDir;
const nsString mLang;
const nsString mBody;
const nsString mTag;
const nsString mIcon;
const nsString mData;
const nsString mBehavior;
const nsString mServiceWorkerRegistrationID;
};
class ScopeCheckingGetCallback : public nsINotificationStorageCallback
{
const nsString mScope;
public:
explicit ScopeCheckingGetCallback(const nsAString& aScope)
: mScope(aScope)
{}
NS_IMETHOD Handle(const nsAString& aID,
const nsAString& aTitle,
const nsAString& aDir,
const nsAString& aLang,
const nsAString& aBody,
const nsAString& aTag,
const nsAString& aIcon,
const nsAString& aData,
const nsAString& aBehavior,
const nsAString& aServiceWorkerRegistrationID,
JSContext* aCx) final
{
AssertIsOnMainThread();
MOZ_ASSERT(!aID.IsEmpty());
// Skip scopes that don't match when called from getNotifications().
if (!mScope.IsEmpty() && !mScope.Equals(aServiceWorkerRegistrationID)) {
return NS_OK;
}
NotificationStrings strings = {
nsString(aID),
nsString(aTitle),
nsString(aDir),
nsString(aLang),
nsString(aBody),
nsString(aTag),
nsString(aIcon),
nsString(aData),
nsString(aBehavior),
nsString(aServiceWorkerRegistrationID),
};
mStrings.AppendElement(Move(strings));
return NS_OK;
}
NS_IMETHOD Done(JSContext* aCx) override = 0;
protected:
virtual ~ScopeCheckingGetCallback()
{}
nsTArray<NotificationStrings> mStrings;
};
class NotificationStorageCallback final : public ScopeCheckingGetCallback
{
public:
NS_DECL_CYCLE_COLLECTING_ISUPPORTS
NS_DECL_CYCLE_COLLECTION_CLASS(NotificationStorageCallback)
NotificationStorageCallback(nsIGlobalObject* aWindow, const nsAString& aScope,
Promise* aPromise)
: ScopeCheckingGetCallback(aScope),
mWindow(aWindow),
mPromise(aPromise)
{
AssertIsOnMainThread();
MOZ_ASSERT(aWindow);
MOZ_ASSERT(aPromise);
}
NS_IMETHOD Done(JSContext* aCx) final
{
AutoJSAPI jsapi;
DebugOnly<bool> ok = jsapi.Init(mWindow, aCx);
MOZ_ASSERT(ok);
ErrorResult result;
nsAutoTArray<RefPtr<Notification>, 5> notifications;
for (uint32_t i = 0; i < mStrings.Length(); ++i) {
RefPtr<Notification> n =
Notification::ConstructFromFields(mWindow,
mStrings[i].mID,
mStrings[i].mTitle,
mStrings[i].mDir,
mStrings[i].mLang,
mStrings[i].mBody,
mStrings[i].mTag,
mStrings[i].mIcon,
mStrings[i].mData,
/* mStrings[i].mBehavior, not
* supported */
mStrings[i].mServiceWorkerRegistrationID,
result);
n->SetStoredState(true);
Unused << NS_WARN_IF(result.Failed());
if (!result.Failed()) {
notifications.AppendElement(n.forget());
}
}
mPromise->MaybeResolve(notifications);
return NS_OK;
}
private:
virtual ~NotificationStorageCallback()
{}
nsCOMPtr<nsIGlobalObject> mWindow;
RefPtr<Promise> mPromise;
const nsString mScope;
};
NS_IMPL_CYCLE_COLLECTING_ADDREF(NotificationStorageCallback)
NS_IMPL_CYCLE_COLLECTING_RELEASE(NotificationStorageCallback)
NS_IMPL_CYCLE_COLLECTION(NotificationStorageCallback, mWindow, mPromise);
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(NotificationStorageCallback)
NS_INTERFACE_MAP_ENTRY(nsINotificationStorageCallback)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
class NotificationGetRunnable final : public nsRunnable
{
const nsString mOrigin;
const nsString mTag;
nsCOMPtr<nsINotificationStorageCallback> mCallback;
public:
NotificationGetRunnable(const nsAString& aOrigin,
const nsAString& aTag,
nsINotificationStorageCallback* aCallback)
: mOrigin(aOrigin), mTag(aTag), mCallback(aCallback)
{}
NS_IMETHOD
Run() override
{
nsresult rv;
nsCOMPtr<nsINotificationStorage> notificationStorage =
do_GetService(NS_NOTIFICATION_STORAGE_CONTRACTID, &rv);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
rv = notificationStorage->Get(mOrigin, mTag, mCallback);
//XXXnsm Is it guaranteed mCallback will be called in case of failure?
Unused << NS_WARN_IF(NS_FAILED(rv));
return rv;
}
};
class NotificationPermissionRequest : public nsIContentPermissionRequest,
public nsIRunnable
{
public:
NS_DECL_CYCLE_COLLECTING_ISUPPORTS
NS_DECL_NSICONTENTPERMISSIONREQUEST
NS_DECL_NSIRUNNABLE
NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(NotificationPermissionRequest,
nsIContentPermissionRequest)
NotificationPermissionRequest(nsIPrincipal* aPrincipal, nsPIDOMWindow* aWindow,
NotificationPermissionCallback* aCallback)
: mPrincipal(aPrincipal), mWindow(aWindow),
mPermission(NotificationPermission::Default),
mCallback(aCallback)
{
mRequester = new nsContentPermissionRequester(mWindow);
}
protected:
virtual ~NotificationPermissionRequest() {}
nsresult CallCallback();
nsresult DispatchCallback();
nsCOMPtr<nsIPrincipal> mPrincipal;
nsCOMPtr<nsPIDOMWindow> mWindow;
NotificationPermission mPermission;
RefPtr<NotificationPermissionCallback> mCallback;
nsCOMPtr<nsIContentPermissionRequester> mRequester;
};
namespace {
class ReleaseNotificationControlRunnable final : public MainThreadWorkerControlRunnable
{
Notification* mNotification;
public:
explicit ReleaseNotificationControlRunnable(Notification* aNotification)
: MainThreadWorkerControlRunnable(aNotification->mWorkerPrivate)
, mNotification(aNotification)
{ }
bool
WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
{
mNotification->ReleaseObject();
return true;
}
};
class GetPermissionRunnable final : public WorkerMainThreadRunnable
{
NotificationPermission mPermission;
public:
explicit GetPermissionRunnable(WorkerPrivate* aWorker)
: WorkerMainThreadRunnable(aWorker)
, mPermission(NotificationPermission::Denied)
{ }
bool
MainThreadRun() override
{
ErrorResult result;
mPermission =
Notification::GetPermissionInternal(mWorkerPrivate->GetPrincipal(),
result);
return true;
}
NotificationPermission
GetPermission()
{
return mPermission;
}
};
class FocusWindowRunnable final : public nsRunnable
{
nsMainThreadPtrHandle<nsPIDOMWindow> mWindow;
public:
explicit FocusWindowRunnable(const nsMainThreadPtrHandle<nsPIDOMWindow>& aWindow)
: mWindow(aWindow)
{ }
NS_IMETHOD
Run()
{
AssertIsOnMainThread();
if (!mWindow->IsCurrentInnerWindow()) {
// Window has been closed, this observer is not valid anymore
return NS_OK;
}
nsIDocument* doc = mWindow->GetExtantDoc();
if (doc) {
// Browser UI may use DOMWebNotificationClicked to focus the tab
// from which the event was dispatched.
nsContentUtils::DispatchChromeEvent(doc, mWindow->GetOuterWindow(),
NS_LITERAL_STRING("DOMWebNotificationClicked"),
true, true);
}
return NS_OK;
}
};
nsresult
CheckScope(nsIPrincipal* aPrincipal, const nsACString& aScope)
{
AssertIsOnMainThread();
MOZ_ASSERT(aPrincipal);
nsCOMPtr<nsIURI> scopeURI;
nsresult rv = NS_NewURI(getter_AddRefs(scopeURI), aScope, nullptr, nullptr);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return aPrincipal->CheckMayLoad(scopeURI, /* report = */ true,
/* allowIfInheritsPrincipal = */ false);
}
} // anonymous namespace
// Subclass that can be directly dispatched to child workers from the main
// thread.
class NotificationWorkerRunnable : public WorkerRunnable
{
protected:
explicit NotificationWorkerRunnable(WorkerPrivate* aWorkerPrivate)
: WorkerRunnable(aWorkerPrivate, WorkerThreadUnchangedBusyCount)
{
}
bool
PreDispatch(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
{
return true;
}
void
PostDispatch(JSContext* aCx, WorkerPrivate* aWorkerPrivate,
bool aDispatchResult) override
{
}
bool
WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
{
aWorkerPrivate->AssertIsOnWorkerThread();
aWorkerPrivate->ModifyBusyCountFromWorker(aCx, true);
WorkerRunInternal(aCx, aWorkerPrivate);
return true;
}
void
PostRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate,
bool aRunResult) override
{
aWorkerPrivate->ModifyBusyCountFromWorker(aCx, false);
}
virtual void
WorkerRunInternal(JSContext* aCx, WorkerPrivate* aWorkerPrivate) = 0;
};
// Overrides dispatch and run handlers so we can directly dispatch from main
// thread to child workers.
class NotificationEventWorkerRunnable final : public NotificationWorkerRunnable
{
Notification* mNotification;
const nsString mEventName;
public:
NotificationEventWorkerRunnable(Notification* aNotification,
const nsString& aEventName)
: NotificationWorkerRunnable(aNotification->mWorkerPrivate)
, mNotification(aNotification)
, mEventName(aEventName)
{}
void
WorkerRunInternal(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
{
mNotification->DispatchTrustedEvent(mEventName);
}
};
class ReleaseNotificationRunnable final : public NotificationWorkerRunnable
{
Notification* mNotification;
public:
explicit ReleaseNotificationRunnable(Notification* aNotification)
: NotificationWorkerRunnable(aNotification->mWorkerPrivate)
, mNotification(aNotification)
{}
void
WorkerRunInternal(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
{
mNotification->ReleaseObject();
}
};
// Create one whenever you require ownership of the notification. Use with
// UniquePtr<>. See Notification.h for details.
class NotificationRef final {
friend class WorkerNotificationObserver;
private:
Notification* mNotification;
bool mInited;
// Only useful for workers.
void
Forget()
{
mNotification = nullptr;
}
public:
explicit NotificationRef(Notification* aNotification)
: mNotification(aNotification)
{
MOZ_ASSERT(mNotification);
if (mNotification->mWorkerPrivate) {
mNotification->mWorkerPrivate->AssertIsOnWorkerThread();
} else {
AssertIsOnMainThread();
}
mInited = mNotification->AddRefObject();
}
// This is only required because Gecko runs script in a worker's onclose
// handler (non-standard, Bug 790919) where calls to AddFeature() will fail.
// Due to non-standardness and added complications if we decide to support
// this, attempts to create a Notification in onclose just throw exceptions.
bool
Initialized()
{
return mInited;
}
~NotificationRef()
{
if (Initialized() && mNotification) {
Notification* notification = mNotification;
mNotification = nullptr;
if (notification->mWorkerPrivate && NS_IsMainThread()) {
// Try to pass ownership back to the worker. If the dispatch succeeds we
// are guaranteed this runnable will run, and that it will run after queued
// event runnables, so event runnables will have a safe pointer to the
// Notification.
//
// If the dispatch fails, the worker isn't running anymore and the event
// runnables have already run or been canceled. We can use a control
// runnable to release the reference.
RefPtr<ReleaseNotificationRunnable> r =
new ReleaseNotificationRunnable(notification);
AutoJSAPI jsapi;
jsapi.Init();
if (!r->Dispatch(jsapi.cx())) {
RefPtr<ReleaseNotificationControlRunnable> r =
new ReleaseNotificationControlRunnable(notification);
MOZ_ALWAYS_TRUE(r->Dispatch(jsapi.cx()));
}
} else {
notification->AssertIsOnTargetThread();
notification->ReleaseObject();
}
}
}
// XXXnsm, is it worth having some sort of WeakPtr like wrapper instead of
// a rawptr that the NotificationRef can invalidate?
Notification*
GetNotification()
{
MOZ_ASSERT(Initialized());
return mNotification;
}
};
class NotificationTask : public nsRunnable
{
public:
enum NotificationAction {
eShow,
eClose
};
NotificationTask(UniquePtr<NotificationRef> aRef, NotificationAction aAction)
: mNotificationRef(Move(aRef)), mAction(aAction)
{}
NS_IMETHOD
Run() override;
protected:
virtual ~NotificationTask() {}
UniquePtr<NotificationRef> mNotificationRef;
NotificationAction mAction;
};
uint32_t Notification::sCount = 0;
NS_IMPL_CYCLE_COLLECTION(NotificationPermissionRequest, mWindow)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(NotificationPermissionRequest)
NS_INTERFACE_MAP_ENTRY(nsIContentPermissionRequest)
NS_INTERFACE_MAP_ENTRY(nsIRunnable)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIContentPermissionRequest)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTING_ADDREF(NotificationPermissionRequest)
NS_IMPL_CYCLE_COLLECTING_RELEASE(NotificationPermissionRequest)
NS_IMETHODIMP
NotificationPermissionRequest::Run()
{
if (nsContentUtils::IsSystemPrincipal(mPrincipal)) {
mPermission = NotificationPermission::Granted;
} else {
// File are automatically granted permission.
nsCOMPtr<nsIURI> uri;
mPrincipal->GetURI(getter_AddRefs(uri));
if (uri) {
bool isFile;
uri->SchemeIs("file", &isFile);
if (isFile) {
mPermission = NotificationPermission::Granted;
}
}
}
// Grant permission if pref'ed on.
if (Preferences::GetBool("notification.prompt.testing", false)) {
if (Preferences::GetBool("notification.prompt.testing.allow", true)) {
mPermission = NotificationPermission::Granted;
} else {
mPermission = NotificationPermission::Denied;
}
}
if (mPermission != NotificationPermission::Default) {
return DispatchCallback();
}
return nsContentPermissionUtils::AskPermission(this, mWindow);
}
NS_IMETHODIMP
NotificationPermissionRequest::GetPrincipal(nsIPrincipal** aRequestingPrincipal)
{
NS_ADDREF(*aRequestingPrincipal = mPrincipal);
return NS_OK;
}
NS_IMETHODIMP
NotificationPermissionRequest::GetWindow(nsIDOMWindow** aRequestingWindow)
{
NS_ADDREF(*aRequestingWindow = mWindow);
return NS_OK;
}
NS_IMETHODIMP
NotificationPermissionRequest::GetElement(nsIDOMElement** aElement)
{
NS_ENSURE_ARG_POINTER(aElement);
*aElement = nullptr;
return NS_OK;
}
NS_IMETHODIMP
NotificationPermissionRequest::Cancel()
{
mPermission = NotificationPermission::Denied;
return DispatchCallback();
}
NS_IMETHODIMP
NotificationPermissionRequest::Allow(JS::HandleValue aChoices)
{
MOZ_ASSERT(aChoices.isUndefined());
mPermission = NotificationPermission::Granted;
return DispatchCallback();
}
NS_IMETHODIMP
NotificationPermissionRequest::GetRequester(nsIContentPermissionRequester** aRequester)
{
NS_ENSURE_ARG_POINTER(aRequester);
nsCOMPtr<nsIContentPermissionRequester> requester = mRequester;
requester.forget(aRequester);
return NS_OK;
}
inline nsresult
NotificationPermissionRequest::DispatchCallback()
{
if (!mCallback) {
return NS_OK;
}
nsCOMPtr<nsIRunnable> callbackRunnable = NS_NewRunnableMethod(this,
&NotificationPermissionRequest::CallCallback);
return NS_DispatchToMainThread(callbackRunnable);
}
nsresult
NotificationPermissionRequest::CallCallback()
{
ErrorResult rv;
mCallback->Call(mPermission, rv);
return rv.StealNSResult();
}
NS_IMETHODIMP
NotificationPermissionRequest::GetTypes(nsIArray** aTypes)
{
nsTArray<nsString> emptyOptions;
return nsContentPermissionUtils::CreatePermissionArray(NS_LITERAL_CSTRING("desktop-notification"),
NS_LITERAL_CSTRING("unused"),
emptyOptions,
aTypes);
}
// Observer that the alert service calls to do common tasks and/or dispatch to the
// specific observer for the context e.g. main thread, worker, or service worker.
class NotificationObserver final : public nsIObserver
{
public:
nsCOMPtr<nsIObserver> mObserver;
nsCOMPtr<nsIPrincipal> mPrincipal;
NS_DECL_ISUPPORTS
NS_DECL_NSIOBSERVER
NotificationObserver(nsIObserver* aObserver, nsIPrincipal* aPrincipal)
: mObserver(aObserver), mPrincipal(aPrincipal)
{
AssertIsOnMainThread();
MOZ_ASSERT(mObserver);
MOZ_ASSERT(mPrincipal);
}
protected:
virtual ~NotificationObserver()
{
AssertIsOnMainThread();
}
nsresult AdjustPushQuota(const char* aTopic);
};
NS_IMPL_ISUPPORTS(NotificationObserver, nsIObserver)
class MainThreadNotificationObserver : public nsIObserver
{
public:
UniquePtr<NotificationRef> mNotificationRef;
NS_DECL_ISUPPORTS
NS_DECL_NSIOBSERVER
explicit MainThreadNotificationObserver(UniquePtr<NotificationRef> aRef)
: mNotificationRef(Move(aRef))
{
AssertIsOnMainThread();
}
protected:
virtual ~MainThreadNotificationObserver()
{
AssertIsOnMainThread();
}
};
NS_IMPL_ISUPPORTS(MainThreadNotificationObserver, nsIObserver)
NS_IMETHODIMP
NotificationTask::Run()
{
AssertIsOnMainThread();
// Get a pointer to notification before the notification takes ownership of
// the ref (it owns itself temporarily, with ShowInternal() and
// CloseInternal() passing on the ownership appropriately.)
Notification* notif = mNotificationRef->GetNotification();
notif->mTempRef.swap(mNotificationRef);
if (mAction == eShow) {
notif->ShowInternal();
} else if (mAction == eClose) {
notif->CloseInternal();
} else {
MOZ_CRASH("Invalid action");
}
MOZ_ASSERT(!mNotificationRef);
return NS_OK;
}
// static
bool
Notification::PrefEnabled(JSContext* aCx, JSObject* aObj)
{
if (NS_IsMainThread()) {
return Preferences::GetBool("dom.webnotifications.enabled", false);
}
WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx);
if (!workerPrivate) {
return false;
}
if (workerPrivate->IsServiceWorker()) {
return workerPrivate->DOMServiceWorkerNotificationEnabled();
}
return workerPrivate->DOMWorkerNotificationEnabled();
}
// static
bool
Notification::IsGetEnabled(JSContext* aCx, JSObject* aObj)
{
return NS_IsMainThread();
}
Notification::Notification(nsIGlobalObject* aGlobal, const nsAString& aID,
const nsAString& aTitle, const nsAString& aBody,
NotificationDirection aDir, const nsAString& aLang,
const nsAString& aTag, const nsAString& aIconUrl,
const NotificationBehavior& aBehavior)
: DOMEventTargetHelper(),
mWorkerPrivate(nullptr), mObserver(nullptr),
mID(aID), mTitle(aTitle), mBody(aBody), mDir(aDir), mLang(aLang),
mTag(aTag), mIconUrl(aIconUrl), mBehavior(aBehavior), mData(JS::NullValue()),
mIsClosed(false), mIsStored(false), mTaskCount(0)
{
if (NS_IsMainThread()) {
// We can only call this on the main thread because
// Event::SetEventType() called down the call chain when dispatching events
// using DOMEventTargetHelper::DispatchTrustedEvent() will assume the event
// is a main thread event if it has a valid owner. It will then attempt to
// fetch the atom for the event name which asserts main thread only.
BindToOwner(aGlobal);
} else {
mWorkerPrivate = GetCurrentThreadWorkerPrivate();
MOZ_ASSERT(mWorkerPrivate);
}
}
void
Notification::SetAlertName()
{
AssertIsOnMainThread();
if (!mAlertName.IsEmpty()) {
return;
}
nsAutoString alertName;
nsresult rv = GetOrigin(GetPrincipal(), alertName);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
// Get the notification name that is unique per origin + tag/ID.
// The name of the alert is of the form origin#tag/ID.
alertName.Append('#');
if (!mTag.IsEmpty()) {
alertName.AppendLiteral("tag:");
alertName.Append(mTag);
} else {
alertName.AppendLiteral("notag:");
alertName.Append(mID);
}
mAlertName = alertName;
}
// May be called on any thread.
// static
already_AddRefed<Notification>
Notification::Constructor(const GlobalObject& aGlobal,
const nsAString& aTitle,
const NotificationOptions& aOptions,
ErrorResult& aRv)
{
// FIXME(nsm): If the sticky flag is set, throw an error.
ServiceWorkerGlobalScope* scope = nullptr;
UNWRAP_WORKER_OBJECT(ServiceWorkerGlobalScope, aGlobal.Get(), scope);
if (scope) {
aRv.ThrowTypeError<MSG_NOTIFICATION_NO_CONSTRUCTOR_IN_SERVICEWORKER>();
return nullptr;
}
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
RefPtr<Notification> notification =
CreateAndShow(global, aTitle, aOptions, EmptyString(), aRv);
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
// This is be ok since we are on the worker thread where this function will
// run to completion before the Notification has a chance to go away.
return notification.forget();
}
// static
already_AddRefed<Notification>
Notification::ConstructFromFields(
nsIGlobalObject* aGlobal,
const nsAString& aID,
const nsAString& aTitle,
const nsAString& aDir,
const nsAString& aLang,
const nsAString& aBody,
const nsAString& aTag,
const nsAString& aIcon,
const nsAString& aData,
const nsAString& aServiceWorkerRegistrationID,
ErrorResult& aRv)
{
MOZ_ASSERT(aGlobal);
AutoJSAPI jsapi;
DebugOnly<bool> ok = jsapi.Init(aGlobal);
MOZ_ASSERT(ok);
RootedDictionary<NotificationOptions> options(jsapi.cx());
options.mDir = Notification::StringToDirection(nsString(aDir));
options.mLang = aLang;
options.mBody = aBody;
options.mTag = aTag;
options.mIcon = aIcon;
RefPtr<Notification> notification = CreateInternal(aGlobal, aID, aTitle,
options);
notification->InitFromBase64(jsapi.cx(), aData, aRv);
if (NS_WARN_IF(aRv.Failed())) {
return nullptr;
}
notification->SetScope(aServiceWorkerRegistrationID);
return notification.forget();
}
nsresult
Notification::PersistNotification()
{
AssertIsOnMainThread();
nsresult rv;
nsCOMPtr<nsINotificationStorage> notificationStorage =
do_GetService(NS_NOTIFICATION_STORAGE_CONTRACTID, &rv);
if (NS_FAILED(rv)) {
return rv;
}
nsString origin;
rv = GetOrigin(GetPrincipal(), origin);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
nsString id;
GetID(id);
nsString alertName;
GetAlertName(alertName);
nsAutoString behavior;
if (!mBehavior.ToJSON(behavior)) {
return NS_ERROR_FAILURE;
}
rv = notificationStorage->Put(origin,
id,
mTitle,
DirectionToString(mDir),
mLang,
mBody,
mTag,
mIconUrl,
alertName,
mDataAsBase64,
behavior,
mScope);
if (NS_FAILED(rv)) {
return rv;
}
SetStoredState(true);
return NS_OK;
}
void
Notification::UnpersistNotification()
{
AssertIsOnMainThread();
if (IsStored()) {
nsCOMPtr<nsINotificationStorage> notificationStorage =
do_GetService(NS_NOTIFICATION_STORAGE_CONTRACTID);
if (notificationStorage) {
nsString origin;
nsresult rv = GetOrigin(GetPrincipal(), origin);
if (NS_SUCCEEDED(rv)) {
notificationStorage->Delete(origin, mID);
}
}
SetStoredState(false);
}
}
already_AddRefed<Notification>
Notification::CreateInternal(nsIGlobalObject* aGlobal,
const nsAString& aID,
const nsAString& aTitle,
const NotificationOptions& aOptions)
{
nsString id;
if (!aID.IsEmpty()) {
id = aID;
} else {
nsCOMPtr<nsIUUIDGenerator> uuidgen =
do_GetService("@mozilla.org/uuid-generator;1");
NS_ENSURE_TRUE(uuidgen, nullptr);
nsID uuid;
nsresult rv = uuidgen->GenerateUUIDInPlace(&uuid);
NS_ENSURE_SUCCESS(rv, nullptr);
char buffer[NSID_LENGTH];
uuid.ToProvidedString(buffer);
NS_ConvertASCIItoUTF16 convertedID(buffer);
id = convertedID;
}
RefPtr<Notification> notification = new Notification(aGlobal, id, aTitle,
aOptions.mBody,
aOptions.mDir,
aOptions.mLang,
aOptions.mTag,
aOptions.mIcon,
aOptions.mMozbehavior);
return notification.forget();
}
Notification::~Notification()
{
mData.setUndefined();
mozilla::DropJSObjects(this);
AssertIsOnTargetThread();
MOZ_ASSERT(!mFeature);
MOZ_ASSERT(!mTempRef);
}
NS_IMPL_CYCLE_COLLECTION_CLASS(Notification)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(Notification, DOMEventTargetHelper)
tmp->mData.setUndefined();
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(Notification, DOMEventTargetHelper)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(Notification, DOMEventTargetHelper)
NS_IMPL_CYCLE_COLLECTION_TRACE_JSVAL_MEMBER_CALLBACK(mData);