EventSource.h (2751B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 /* 8 * This implementation has support only for http requests. It is because the 9 * spec has defined event streams only for http. HTTP is required because 10 * this implementation uses some http headers: "Last-Event-ID", "Cache-Control" 11 * and "Accept". 12 */ 13 14 #ifndef mozilla_dom_EventSource_h 15 #define mozilla_dom_EventSource_h 16 17 #include "mozilla/Atomics.h" 18 #include "mozilla/DOMEventTargetHelper.h" 19 #include "nsDeque.h" 20 #include "nsICookieJarSettings.h" 21 22 class nsIGlobalObject; 23 24 namespace mozilla { 25 26 class ErrorResult; 27 28 namespace dom { 29 30 struct EventSourceInit; 31 32 class EventSourceImpl; 33 34 class EventSource final : public DOMEventTargetHelper { 35 friend class EventSourceImpl; 36 37 public: 38 NS_DECL_ISUPPORTS_INHERITED 39 NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(EventSource, DOMEventTargetHelper) 40 virtual bool IsCertainlyAliveForCC() const override; 41 42 // EventTarget 43 void DisconnectFromOwner() override { 44 DOMEventTargetHelper::DisconnectFromOwner(); 45 Close(); 46 } 47 48 JSObject* WrapObject(JSContext* aCx, 49 JS::Handle<JSObject*> aGivenProto) override; 50 51 // WebIDL 52 static already_AddRefed<EventSource> Constructor( 53 const GlobalObject& aGlobal, const nsAString& aURL, 54 const EventSourceInit& aEventSourceInitDict, ErrorResult& aRv); 55 56 void GetUrl(nsAString& aURL) const { 57 AssertIsOnTargetThread(); 58 aURL = mOriginalURL; 59 } 60 61 bool WithCredentials() const { 62 AssertIsOnTargetThread(); 63 return mWithCredentials; 64 } 65 66 uint16_t ReadyState() const { 67 AssertIsOnTargetThread(); 68 return mReadyState; 69 } 70 71 IMPL_EVENT_HANDLER(open) 72 IMPL_EVENT_HANDLER(message) 73 IMPL_EVENT_HANDLER(error) 74 75 void Close(); 76 77 private: 78 EventSource(nsIGlobalObject* aGlobal, 79 nsICookieJarSettings* aCookieJarSettings, bool aWithCredentials); 80 virtual ~EventSource(); 81 // prevent bad usage 82 EventSource(const EventSource& x) = delete; 83 EventSource& operator=(const EventSource& x) = delete; 84 85 void AssertIsOnTargetThread() const { 86 MOZ_ASSERT(NS_IsMainThread() == mIsMainThread); 87 } 88 89 nsresult CreateAndDispatchSimpleEvent(const nsAString& aName); 90 91 // This EventSourceImpl is created, managed and destroyed 92 // by EventSource. 93 RefPtr<EventSourceImpl> mESImpl; 94 nsString mOriginalURL; 95 Atomic<uint32_t> mReadyState; 96 const bool mWithCredentials; 97 const bool mIsMainThread; 98 }; 99 100 } // namespace dom 101 } // namespace mozilla 102 103 #endif // mozilla_dom_EventSource_h