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
|
// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
#include "../luaengine.h"
#include "../luatr.h"
#include "utils.h"
#include <coreplugin/dialogs/ioptionspage.h>
#include <coreplugin/icore.h>
#include <utils/aspects.h>
#include <utils/guardedcallback.h>
#include <utils/infobar.h>
#include <utils/layoutbuilder.h>
#include <utils/networkaccessmanager.h>
#include <utils/stylehelper.h>
#include <QApplication>
#include <QCheckBox>
#include <QJsonArray>
#include <QJsonDocument>
#include <QMessageBox>
#include <QMetaEnum>
#include <QNetworkAccessManager>
#include <QNetworkReply>
using namespace Utils;
using namespace Core;
using namespace std::string_view_literals;
namespace Lua::Internal {
static QString opToString(QNetworkAccessManager::Operation op)
{
switch (op) {
case QNetworkAccessManager::HeadOperation:
return "HEAD";
case QNetworkAccessManager::GetOperation:
return "GET";
case QNetworkAccessManager::PutOperation:
return "PUT";
case QNetworkAccessManager::PostOperation:
return "POST";
case QNetworkAccessManager::DeleteOperation:
return "DELETE";
case QNetworkAccessManager::CustomOperation:
return "CUSTOM";
default:
return "UNKNOWN";
}
}
void setupFetchModule()
{
class Module : AspectContainer
{
StringListAspect pluginsAllowedToFetch{this};
StringListAspect pluginsNotAllowedToFetch{this};
class LuaOptionsPage : public IOptionsPage
{
public:
LuaOptionsPage(Module *module)
{
setId("BB.Lua.Fetch");
setDisplayName(Tr::tr("Network Access"));
setCategory("ZY.Lua");
setSettingsProvider(
[module] { return static_cast<AspectContainer *>(module); });
}
};
LuaOptionsPage settingsPage{this};
public:
Module()
{
setSettingsGroup("Lua.Fetch");
setAutoApply(false);
pluginsAllowedToFetch.setSettingsKey("pluginsAllowedToFetch");
pluginsAllowedToFetch.setLabelText("Plugins allowed to fetch data from the internet");
pluginsAllowedToFetch.setToolTip(
"List of plugins that are allowed to fetch data from the internet");
pluginsAllowedToFetch.setUiAllowAdding(false);
pluginsAllowedToFetch.setUiAllowEditing(false);
pluginsNotAllowedToFetch.setSettingsKey("pluginsNotAllowedToFetch");
pluginsNotAllowedToFetch.setLabelText(
"Plugins not allowed to fetch data from the internet");
pluginsNotAllowedToFetch.setToolTip(
"List of plugins that are not allowed to fetch data from the internet");
pluginsNotAllowedToFetch.setUiAllowAdding(false);
pluginsNotAllowedToFetch.setUiAllowEditing(false);
setLayouter([this] {
using namespace Layouting;
// clang-format off
return Form {
pluginsAllowedToFetch, br,
pluginsNotAllowedToFetch, br,
};
// clang-format on
});
readSettings();
}
~Module() { writeSettings(); }
enum class IsAllowed { Yes, No, NeedsToAsk };
IsAllowed isAllowedToFetch(const QString &pluginName) const
{
if (pluginsAllowedToFetch().contains(pluginName))
return IsAllowed::Yes;
if (pluginsNotAllowedToFetch().contains(pluginName))
return IsAllowed::No;
return IsAllowed::NeedsToAsk;
}
void setAllowedToFetch(const QString &pluginName, IsAllowed allowed)
{
if (allowed == IsAllowed::Yes)
pluginsAllowedToFetch.appendValue(pluginName);
else if (allowed == IsAllowed::No)
pluginsNotAllowedToFetch.appendValue(pluginName);
if (allowed == IsAllowed::Yes)
pluginsNotAllowedToFetch.removeValue(pluginName);
else if (allowed == IsAllowed::No)
pluginsAllowedToFetch.removeValue(pluginName);
}
};
std::shared_ptr<Module> module = std::make_shared<Module>();
registerProvider(
"Fetch",
[mod = std::move(module),
infoBarCleaner = InfoBarCleaner()](sol::state_view lua) mutable -> sol::object {
const ScriptPluginSpec *pluginSpec = lua.get<ScriptPluginSpec *>("PluginSpec"sv);
sol::table async = lua.script("return require('async')", "_fetch_").get<sol::table>();
sol::function wrap = async["wrap"];
sol::table fetch = lua.create_table();
auto networkReplyType = lua.new_usertype<QNetworkReply>(
"QNetworkReply",
"error",
sol::property([](QNetworkReply *self) -> int { return self->error(); }),
"readAll",
[](QNetworkReply *r) { return r->readAll().toStdString(); },
"__tostring",
[](QNetworkReply *r) {
return QString("QNetworkReply(%1 \"%2\") => %3")
.arg(opToString(r->operation()))
.arg(r->url().toString())
.arg(r->error());
});
auto checkPermission = [mod,
&infoBarCleaner,
pluginName = pluginSpec->name,
guard = pluginSpec->connectionGuard.get()](
QString url,
std::function<void()> fetch,
std::function<void()> notAllowed) {
auto isAllowed = mod->isAllowedToFetch(pluginName);
if (isAllowed == Module::IsAllowed::Yes) {
fetch();
return;
}
if (isAllowed == Module::IsAllowed::No) {
notAllowed();
return;
}
if (QApplication::activeModalWidget()) {
// We are already showing a modal dialog,
// so we have to use a QMessageBox instead of the info bar
auto msgBox = new QMessageBox(
QMessageBox::Question,
Tr::tr("Allow Internet Access"),
Tr::tr("Allow the extension \"%1\" to fetch from the following URL:\n%2")
.arg(pluginName)
.arg(url),
QMessageBox::Yes | QMessageBox::No,
ICore::dialogParent());
msgBox->setCheckBox(new QCheckBox(Tr::tr("Remember choice")));
QObject::connect(
msgBox, &QMessageBox::accepted, guard, [mod, fetch, pluginName, msgBox]() {
if (msgBox->checkBox()->isChecked())
mod->setAllowedToFetch(pluginName, Module::IsAllowed::Yes);
fetch();
});
QObject::connect(
msgBox,
&QMessageBox::rejected,
guard,
[mod, notAllowed, pluginName, msgBox]() {
if (msgBox->checkBox()->isChecked())
mod->setAllowedToFetch(pluginName, Module::IsAllowed::No);
notAllowed();
});
msgBox->show();
return;
}
const Id infoBarId = Id("Fetch").withSuffix(pluginName);
infoBarCleaner.infoBarEntryAdded(infoBarId);
InfoBarEntry entry{
infoBarId,
Tr::tr("Allow the extension \"%1\" to fetch data from the internet?")
.arg(pluginName)};
entry.setTitle(Tr::tr("Allow Fetching Data?"));
entry.setInfoType(InfoLabel::Warning);
entry.setDetailsWidgetCreator([pluginName, url] {
const QString markdown = Tr::tr("Allow the extension \"%1\" to fetch data "
"from the following URL:\n\n")
.arg("**" + pluginName + "**")
+ QString("* [%1](%1)").arg(url);
QLabel *list = new QLabel();
list->setTextFormat(Qt::TextFormat::MarkdownText);
list->setText(markdown);
list->setMargin(StyleHelper::SpacingTokens::PaddingVXxs);
return list;
});
entry.addCustomButton(
Tr::tr("Always Allow"),
guardedCallback(
guard,
[mod, pluginName, fetch]() {
mod->setAllowedToFetch(pluginName, Module::IsAllowed::Yes);
fetch();
}),
{},
InfoBarEntry::ButtonAction::Hide);
entry.addCustomButton(
Tr::tr("Allow Once"),
guardedCallback(guard, [pluginName, fetch]() { fetch(); }),
{},
InfoBarEntry::ButtonAction::Hide);
entry.setCancelButtonInfo(
Tr::tr("Deny"), guardedCallback(guard, [mod, notAllowed, pluginName]() {
mod->setAllowedToFetch(pluginName, Module::IsAllowed::No);
notAllowed();
}));
ICore::infoBar()->addInfo(entry);
};
fetch["fetch_cb"] = [checkPermission,
pluginName = pluginSpec->name,
guard = pluginSpec->connectionGuard.get(),
mod](
const sol::main_table &options,
const sol::main_function &callback,
const sol::this_state &thisState) {
auto url = options.get<QString>("url"sv);
auto actualFetch = [guard, url, options, callback, thisState]() {
auto method = (options.get_or<QString>("method"sv, "GET")).toLower();
auto headers = options.get_or<sol::table>("headers"sv, {});
auto data = options.get_or<QString>("body"sv, {});
bool convertToTable
= options.get<std::optional<bool>>("convertToTable"sv).value_or(false);
QNetworkRequest request((QUrl(url)));
if (headers && !headers.empty()) {
for (const auto &[k, v] : headers)
request.setRawHeader(k.as<QString>().toUtf8(), v.as<QString>().toUtf8());
}
QNetworkReply *reply = nullptr;
if (method == "get")
reply = NetworkAccessManager::instance()->get(request);
else if (method == "post")
reply = NetworkAccessManager::instance()->post(request, data.toUtf8());
else
throw std::runtime_error("Unknown method: " + method.toStdString());
if (convertToTable) {
QObject::connect(
reply, &QNetworkReply::finished, guard, [reply, thisState, callback]() {
reply->deleteLater();
if (reply->error() != QNetworkReply::NoError) {
callback(
QString("%1 (%2):\n%3")
.arg(reply->errorString())
.arg(QString::fromLatin1(
QMetaEnum::fromType<QNetworkReply::NetworkError>()
.valueToKey(reply->error())))
.arg(QString::fromUtf8(reply->readAll())));
return;
}
QByteArray data = reply->readAll();
QJsonParseError error;
QJsonDocument doc = QJsonDocument::fromJson(data, &error);
if (error.error != QJsonParseError::NoError) {
callback(error.errorString());
return;
}
callback(toTable(thisState, doc));
});
} else {
QObject::connect(reply, &QNetworkReply::finished, guard, [reply, callback]() {
// We don't want the network reply to be deleted by the manager, but
// by the Lua GC
reply->setParent(nullptr);
callback(std::unique_ptr<QNetworkReply>(reply));
});
}
};
checkPermission(url, actualFetch, [callback, pluginName]() {
callback(
Tr::tr("Fetching is not allowed for the extension \"%1\". (You can edit "
"permissions in Preferences > Lua.)")
.arg(pluginName));
});
};
fetch["fetch"] = wrap(fetch["fetch_cb"]);
return fetch;
});
}
} // namespace Lua::Internal
|