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 file,
5  * You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #ifndef mozilla_temporaryaccessgrantobserver_h
8 #define mozilla_temporaryaccessgrantobserver_h
9 
10 #include "mozilla/PrincipalHashKey.h"
11 #include "nsCOMPtr.h"
12 #include "nsHashKeys.h"
13 #include "nsHashtablesFwd.h"
14 #include "nsIObserver.h"
15 #include "nsString.h"
16 #include "PLDHashTable.h"
17 
18 class nsITimer;
19 class TemporaryAccessGrantCacheKey;
20 
21 namespace mozilla {
22 
23 class PermissionManager;
24 
25 class TemporaryAccessGrantCacheKey : public PrincipalHashKey {
26  public:
27   typedef std::pair<nsCOMPtr<nsIPrincipal>, nsCString> KeyType;
28   typedef const KeyType* KeyTypePointer;
29 
TemporaryAccessGrantCacheKey(KeyTypePointer aKey)30   explicit TemporaryAccessGrantCacheKey(KeyTypePointer aKey)
31       : PrincipalHashKey(aKey->first), mType(aKey->second) {}
32   TemporaryAccessGrantCacheKey(TemporaryAccessGrantCacheKey&& aOther) = default;
33 
34   ~TemporaryAccessGrantCacheKey() = default;
35 
GetKey()36   KeyType GetKey() const { return std::make_pair(mPrincipal, mType); }
KeyEquals(KeyTypePointer aKey)37   bool KeyEquals(KeyTypePointer aKey) const {
38     return PrincipalHashKey::KeyEquals(aKey->first) && mType == aKey->second;
39   }
40 
KeyToPointer(KeyType & aKey)41   static KeyTypePointer KeyToPointer(KeyType& aKey) { return &aKey; }
HashKey(KeyTypePointer aKey)42   static PLDHashNumber HashKey(KeyTypePointer aKey) {
43     if (!aKey) {
44       return 0;
45     }
46 
47     return HashGeneric(PrincipalHashKey::HashKey(aKey->first),
48                        HashString(aKey->second));
49   }
50 
51   enum { ALLOW_MEMMOVE = true };
52 
53  private:
54   nsCString mType;
55 };
56 
57 class TemporaryAccessGrantObserver final : public nsIObserver {
58  public:
59   NS_DECL_ISUPPORTS
60   NS_DECL_NSIOBSERVER
61 
62   static void Create(PermissionManager* aPM, nsIPrincipal* aPrincipal,
63                      const nsACString& aType);
64 
65   void SetTimer(nsITimer* aTimer);
66 
67  private:
68   TemporaryAccessGrantObserver(PermissionManager* aPM, nsIPrincipal* aPrincipal,
69                                const nsACString& aType);
70   ~TemporaryAccessGrantObserver() = default;
71 
72  private:
73   using ObserversTable =
74       nsTHashMap<TemporaryAccessGrantCacheKey, nsCOMPtr<nsITimer>>;
75   static UniquePtr<ObserversTable> sObservers;
76   nsCOMPtr<nsITimer> mTimer;
77   RefPtr<PermissionManager> mPM;
78   nsCOMPtr<nsIPrincipal> mPrincipal;
79   nsCString mType;
80 };
81 
82 }  // namespace mozilla
83 
84 #endif  // mozilla_temporaryaccessgrantobserver_h
85