Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qpermissions_wasm.cpp
Go to the documentation of this file.
1// Copyright (C) 2022 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include <private/qpermissions_p.h>
6#include <private/qstdweb_p.h>
7
8#include <qglobalstatic.h>
9#include <qpermissions.h>
10#include <qmetaobject.h>
11#include <qnamespace.h>
12#include <qmetatype.h>
13#include <qstring.h>
14#include <qtimer.h>
15#include <qhash.h>
16
17#include <emscripten.h>
18#include <emscripten/bind.h>
19#include <emscripten/val.h>
20
21#include <utility>
22#include <string>
23#include <queue>
24
25QT_BEGIN_NAMESPACE
26
27using namespace QPermissions::Private;
28using namespace emscripten;
29
30namespace
31{
32 constexpr const char *wapiGranted = "granted";
33 constexpr const char *wapiDenied = "denied";
34 constexpr const char *wapiPrompt = "prompt";
35 constexpr const char *wapiCamera = "camera";
36 constexpr const char *wapiVideoCapture = "video_capture"; // Alternative to "camera".
37 constexpr const char *wapiMicrophone = "microphone";
38 constexpr const char *wapiAudioCapture = "audio_capture"; // Alternative to "microphone".
39 constexpr const char *wapiGeolocation = "geolocation";
40
41 void updatePermission(const std::string &name, const std::string &state,
42 PermissionCallback callback);
43
44 void checkPermission(const std::string &permissionName)
45 {
46 val permissions = val::global("navigator")["permissions"];
47 if (permissions.isUndefined() || permissions.isNull())
48 return;
49
50 qstdweb::PromiseCallbacks callbacks;
51 callbacks.thenFunc = [permissionName](val permissionState)
52 {
53 updatePermission(permissionName, permissionState["state"].as<std::string>(), {});
54 };
55 callbacks.catchFunc = [permissionName](val err)
56 {
57 if (err["name"].as<std::string>() == "NotAllowedError")
58 return updatePermission(permissionName, wapiDenied, {});
59
60 qCInfo(lcPermissions, "'%s' '%s'", err["name"].as<std::string>().c_str(),
61 err["message"].as<std::string>().c_str());
62 };
63
64 val query = val::object();
65 query.set("name", val(permissionName));
66
67 qstdweb::Promise::make(permissions, QStringLiteral("query"), callbacks, query);
68 }
69
70 void checkPermissions()
71 {
72 checkPermission(wapiCamera);
73 checkPermission(wapiMicrophone);
74 checkPermission(wapiGeolocation);
75 }
76
77 void bootstrapCheckPermissions()
78 {
79 QTimer::singleShot(0, []{checkPermissions();});
80 }
81
82 Q_CONSTRUCTOR_FUNCTION(bootstrapCheckPermissions);
83
84 int permissionTypeIdFromString(const std::string &permission)
85 {
86 if (permission == wapiCamera || permission == wapiVideoCapture)
87 return qMetaTypeId<QCameraPermission>();
88 if (permission == wapiMicrophone || permission == wapiAudioCapture)
89 return qMetaTypeId<QMicrophonePermission>();
90 if (permission == wapiGeolocation)
91 return qMetaTypeId<QLocationPermission>();
92
93 qCWarning(lcPermissions, "Unknown permission type '%s'", permission.c_str());
94
95 return -1;
96 }
97
98 Qt::PermissionStatus permissionStatusFromString(const std::string &state)
99 {
100 if (state == wapiGranted)
102 if (state == wapiDenied)
104 if (state == wapiPrompt)
106
107 qCWarning(lcPermissions, "Unknown permission state '%s'", state.c_str());
108
110 }
111
112 using PermissionHash = QHash<int, Qt::PermissionStatus>;
113 Q_GLOBAL_STATIC(PermissionHash, permissionStatuses);
114
115 void updatePermission(const std::string &name, const std::string &state, PermissionCallback callback)
116 {
117 qCDebug(lcPermissions) << "Updating" << name << "permission to" << state;
118
119 const int type = permissionTypeIdFromString(name);
120 if (type == -1)
121 return; // Unknown permission type
122
123 const auto status = permissionStatusFromString(state);
124 (*permissionStatuses)[type] = status;
125
126 if (callback)
127 callback(status);
128 }
129
130 void requestMediaDevicePermission(const std::string &device, const PermissionCallback &cb)
131 {
132 Q_ASSERT(cb);
133
134 val mediaDevices = val::global("navigator")["mediaDevices"];
135 if (mediaDevices.isUndefined())
137
138 qstdweb::PromiseCallbacks queryCallbacks;
139 queryCallbacks.thenFunc = [device, cb](val)
140 {
141 updatePermission(device, wapiGranted, cb);
142 };
143 queryCallbacks.catchFunc = [device, cb](val error)
144 {
145 if (error["name"].as<std::string>() == "NotAllowedError")
146 return updatePermission(device, wapiDenied, cb);
147 updatePermission(device, wapiPrompt, cb);
148 };
149
150 val constraint = val::object();
151 if (device == wapiCamera)
152 constraint.set("video", true);
153 else
154 constraint.set("audio", true);
155
156 qstdweb::Promise::make(mediaDevices, QStringLiteral("getUserMedia"), queryCallbacks, constraint);
157 }
158
159 using GeoRequest = std::pair<QPermission, PermissionCallback>;
160 Q_GLOBAL_STATIC(std::deque<GeoRequest>, geolocationRequestQueue);
161
162 bool processingLocationRequest = false;
163
164 void processNextGeolocationRequest();
165
166 void geolocationSuccess(val position)
167 {
168 Q_UNUSED(position);
169 Q_ASSERT(geolocationRequestQueue->size());
170
171 processingLocationRequest = false;
172
173 auto cb = geolocationRequestQueue->front().second;
174 geolocationRequestQueue->pop_front();
175 updatePermission(wapiGeolocation, wapiGranted, cb);
176 processNextGeolocationRequest();
177 }
178
179 void geolocationError(val error)
180 {
181 Q_ASSERT(geolocationRequestQueue->size());
182
183 static int deniedError = []
184 {
185 val posErr = val::global("GeolocationPositionError");
186 if (posErr.isUndefined() || posErr.isNull())
187 return 1;
188 return posErr["PERMISSION_DENIED"].as<int>();
189 }();
190
191 processingLocationRequest = false;
192
193 auto cb = geolocationRequestQueue->front().second;
194 geolocationRequestQueue->pop_front();
195
196 const int errorCode = error["code"].as<int>();
197 updatePermission(wapiGeolocation, errorCode == deniedError ? wapiDenied : wapiPrompt, cb);
198 processNextGeolocationRequest();
199 }
200
201 EMSCRIPTEN_BINDINGS(qt_permissions) {
202 function("qtLocationSuccess", &geolocationSuccess);
203 function("qtLocationError", &geolocationError);
204 }
205
206 void processNextGeolocationRequest()
207 {
208 if (processingLocationRequest)
209 return;
210
211 if (geolocationRequestQueue->empty())
212 return;
213
214 processingLocationRequest = true;
215
216 val geolocation = val::global("navigator")["geolocation"];
217 Q_ASSERT(!geolocation.isUndefined());
218 Q_ASSERT(!geolocation.isNull());
219
220 const auto &permission = geolocationRequestQueue->front().first;
221 const auto locationPermission = *permission.value<QLocationPermission>();
222 const bool highAccuracy = locationPermission.accuracy() == QLocationPermission::Precise;
223
224 val options = val::object();
225 options.set("enableHighAccuracy", highAccuracy ? true : false);
226 geolocation.call<void>("getCurrentPosition", val::module_property("qtLocationSuccess"),
227 val::module_property("qtLocationError"), options);
228 }
229
230 void requestGeolocationPermission(const QPermission &permission, const PermissionCallback &cb)
231 {
232 Q_ASSERT(cb);
233 Q_UNUSED(permission);
234 Q_UNUSED(cb);
235
236 val geolocation = val::global("navigator")["geolocation"];
237 if (geolocation.isUndefined() || geolocation.isNull())
239
240 if (processingLocationRequest)
241 qCWarning(lcPermissions, "Permission to access location requested, while another request is in progress");
242
243 geolocationRequestQueue->push_back(std::make_pair(permission, cb));
244 processNextGeolocationRequest();
245 }
246} // Unnamed namespace
247
248namespace QPermissions::Private
249{
251 {
252 const auto it = permissionStatuses->find(permission.type().id());
253 return it != permissionStatuses->end() ? it.value() : Qt::PermissionStatus::Undetermined;
254 }
255
256 void requestPermission(const QPermission &permission, const PermissionCallback &callback)
257 {
258 Q_ASSERT(permission.type().isValid());
259 Q_ASSERT(callback);
260
261 const auto status = checkPermission(permission);
263 return callback(status);
264
265 const int requestedTypeId = permission.type().id();
266 if (requestedTypeId == qMetaTypeId<QCameraPermission>())
267 return requestMediaDevicePermission(wapiCamera, callback);
268
269 if (requestedTypeId == qMetaTypeId<QMicrophonePermission>())
270 return requestMediaDevicePermission(wapiMicrophone, callback);
271
272 if (requestedTypeId == qMetaTypeId<QLocationPermission>())
273 return requestGeolocationPermission(permission, callback);
274
275 (*permissionStatuses)[requestedTypeId] = Qt::PermissionStatus::Denied;
277 }
278}
279
280QT_END_NAMESPACE
\inmodule QtCore
Definition qhash.h:843
\inmodule QtCore \inheaderfile QPermissions
void requestPermission(const QPermission &permission, const PermissionCallback &callback)
Qt::PermissionStatus checkPermission(const QPermission &permission)
Definition qcompare.h:111
PermissionStatus
#define Q_GLOBAL_STATIC(TYPE, NAME,...)
#define QStringLiteral(str)
Definition qstring.h:1825