-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplugin.cpp
More file actions
312 lines (268 loc) · 10.4 KB
/
plugin.cpp
File metadata and controls
312 lines (268 loc) · 10.4 KB
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
// Copyright (c) 2025-2025 Manuel Schneider
#include "configwidget.h"
#include "handlers.h"
#include "plugin.h"
#include <QCoreApplication>
#include <QCoroTask>
#include <QDir>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>
#include <QSettings>
#include <QThread>
#include <QtConcurrentRun>
#include <albert/app.h>
#include <albert/icon.h>
#include <albert/logging.h>
#include <albert/matcher.h>
#include <albert/networkutil.h>
#include <albert/standarditem.h>
#include <albert/systemutil.h>
#include <albert/usagescoring.h>
#include <qt6keychain/keychain.h>
ALBERT_LOGGING_CATEGORY("github")
using namespace Qt::StringLiterals;
using namespace albert;
using namespace github;
using namespace std;
namespace
{
static const auto keychain_service = u"albert.github"_s;
static const auto keychain_key = u"secrets"_s;
static const auto ck_saved_searches = "saved_searches"_L1;
}
Plugin::Plugin()
{
search_handlers_.emplace_back(make_unique<UserSearchHandler>(api));
search_handlers_.emplace_back(make_unique<RepoSearchHandler>(api));
search_handlers_.emplace_back(make_unique<IssueSearchHandler>(api));
}
Plugin::~Plugin() = default;
void Plugin::initialize()
{
QtConcurrent::run([this] {
readSavedSearches();
for (const auto &handler : search_handlers_)
connect(handler.get(), &GithubSearchHandler::savedSearchesChanged,
this, &Plugin::writeSavedSearches);
})
.then(this, [this] {
auto *job = new QKeychain::ReadPasswordJob(keychain_service, this); // Deletes itself
job->setKey(keychain_key);
connect(job, &QKeychain::ReadPasswordJob::finished, this, [this, job] {
if (job->error())
WARN << "Failed to read secrets from keychain:" << job->errorString();
else if (auto secrets = job->textData().split(QChar::Tabulation);
secrets.size() != 3)
WARN << "Unexpected format of the secrets read from keychain.";
else
{
api.oauth.setClientId(secrets[0]);
api.oauth.setClientSecret(secrets[1]);
api.oauth.setTokens(secrets[2]);
DEBG << "Successfully read secrets from keychain.";
}
connect(&api.oauth, &OAuth2::clientIdChanged, this, &Plugin::writeSecrets);
connect(&api.oauth, &OAuth2::clientSecretChanged, this, &Plugin::writeSecrets);
connect(&api.oauth, &OAuth2::tokensChanged, this, &Plugin::writeSecrets);
emit initialized();
});
job->start();
})
.onCanceled(this, [] {
WARN << "Cancelled plugin initialization.";
})
.onFailed(this, [](const QUnhandledException &que) {
if (que.exception())
rethrow_exception(que.exception());
else
throw runtime_error("QUnhandledException::exception() returned nullptr.");
})
.onFailed(this, [](const exception &e) {
CRIT << "Exception while initializing plugin:" << e.what();
})
.onFailed(this, [] {
CRIT << "Unknown exception while initializing plugin.";
});
}
void Plugin::writeSavedSearches()
{
auto s = settings();
s->beginGroup(ck_saved_searches);
for (const auto &handler : search_handlers_)
{
const auto saved_searches = handler->savedSearches();
s->beginWriteArray(handler->id().section(u'.', 1)); // drop "github."
for (size_t i = 0; i < saved_searches.size(); ++i)
{
s->setArrayIndex(i);
s->setValue("title", saved_searches.at(i).first),
s->setValue("query", saved_searches.at(i).second);
}
s->endArray();
}
}
void Plugin::readSavedSearches()
{
if (auto s = settings();
s->childGroups().contains(ck_saved_searches))
{
s->beginGroup(ck_saved_searches);
for (const auto &handler : search_handlers_)
{
vector<pair<QString, QString>> saved_searches;
auto size = s->beginReadArray(handler->id().section(u'.', 1)); // drop "github."
for (int i = 0; i < size; ++i)
{
s->setArrayIndex(i);
saved_searches.emplace_back(s->value("title").toString(),
s->value("query").toString());
}
s->endArray();
handler->setSavedSearches(saved_searches);
}
}
else
{
for (const auto &handler : search_handlers_)
handler->setSavedSearches(handler->defaultSearches());
}
}
void Plugin::writeSecrets()
{
QStringList secrets = {api.oauth.clientId(),
api.oauth.clientSecret(),
api.oauth.accessToken()};
auto job = new QKeychain::WritePasswordJob(keychain_service, this); // Deletes itself
job->setKey(keychain_key);
job->setTextData(secrets.join(QChar::Tabulation));
connect(job, &QKeychain::Job::finished, this, [=] {
if (job->error())
WARN << "Failed to write secrets to keychain:" << job->errorString();
else
DEBG << "Successfully wrote secrets to keychain.";
});
job->start();
}
vector<Extension*> Plugin::extensions()
{
vector<Extension*> extensions{this};
for (const auto &handler : search_handlers_)
extensions.push_back(handler.get());
return extensions;
}
QWidget *Plugin::buildConfigWidget()
{
return new ConfigWidget(*this, api.oauth);
}
QString Plugin::defaultTrigger() const { return u"gh "_s; }
void Plugin::handle(const QUrl &url)
{
api.oauth.handleCallback(url);
App::instance().showSettings(id());
}
vector<RankItem> Plugin::rankItems(QueryContext &ctx)
{
vector<RankItem> r;
Matcher matcher(ctx);
for (const auto &handler : search_handlers_)
for (const auto &[t, q] : handler->savedSearches())
if (auto m = matcher.match(t); m)
{
auto _q = handler->trigger() + q;
vector<Action> actions;
actions.emplace_back(
u"show"_s,
Plugin::tr("Show"),
[=] { App::instance().show(_q + QChar::Space); },
false);
actions.emplace_back(u"github"_s, Plugin::tr("Show on GitHub"), [=] {
openUrl(u"https://github.com/search?q="_s + percentEncoded(q));
});
r.emplace_back(StandardItem::make(t, t, ::move(_q),
[]{ return Icon::image(u":github"_s); },
::move(actions)),
m);
}
return r;
}
// void Plugin::readSavedSearches()
// {
// if (QFile file(savedSearchesFilePath());
// !file.exists())
// return;
// else if (!file.open(QIODevice::ReadOnly))
// WARN << "Failed to read saved searches:" << file.errorString();
// else
// {
// QJsonParseError error;
// if (const auto doc = QJsonDocument::fromJson(file.readAll(), &error);
// error.error != QJsonParseError::NoError)
// WARN << "Failed to parse JSON (saved searches):" << error.errorString();
// else
// {
// const auto root_obj = doc.object();
// for (auto handler : initializer_list<GithubSearchHandler*> {&user_search_handler,
// &repo_search_handler,
// &issue_search_handler})
// {
// std::flat_map<QString, QString> saved_searches;
// const auto cat_object = root_obj[handler->id().section(u'.', 1)].toObject();
// for (auto it = cat_object.begin(); it != cat_object.end(); ++it)
// saved_searches.emplace(it.key(), it.value().toString());
// handler->setSavedSearches(std::move(saved_searches));
// }
// }
// }
// }
// void Plugin::writeSavedSearches()
// {
// QJsonObject saved_searches;
// for (const auto handler : initializer_list<GithubSearchHandler*>{&user_search_handler,
// &repo_search_handler,
// &issue_search_handler})
// {
// QJsonObject searches;
// for (const auto &[title, query] : handler->savedSearches())
// searches[title] = query;
// saved_searches[handler->id().section(u'.', 1)] = searches; // drop "github."
// }
// if (!QDir(savedSearchesFilePath().parent_path()).mkpath(u".."_s))
// WARN << "Failed to create directory:" << savedSearchesFilePath().parent_path();
// else if (QFile file(savedSearchesFilePath());
// !file.open(QIODevice::WriteOnly))
// WARN << "Failed to write saved searches:" << file.errorString();
// else if (file.write(QJsonDocument(saved_searches).toJson()) == -1)
// WARN << "Failed to write saved searches:" << file.errorString();
// else
// DEBG << "Sucessfully wrote saved searches to" << file.fileName();
// }
// void Plugin::restoreDefaultSavedSearches()
// {
// issue_search_handler.setSavedSearches({
// {Plugin::tr("Assigned issues"), u"is:open is:issue assignee:@me"_s},
// {Plugin::tr("Created issues"), u"is:open is:issue author:@me"_s},
// {Plugin::tr("Assigned pull requests"), u"is:open is:pr assignee:@me"_s},
// {Plugin::tr("Created pull requests"), u"is:open is:pr author:@me"_s},
// {Plugin::tr("Review requests"), u"is:open is:pr review-requested:@me"_s},
// {Plugin::tr("Mentions"), u"mentions:@me"_s},
// {Plugin::tr("Recent activity"), u"involves:@me"_s}
// });
// repo_search_handler.setSavedSearches({
// {
// Plugin::tr("My repositories"),
// u"sort:updated-desc fork:true user:@me"_s
// },
// {
// Plugin::tr("Albert repositories"),
// u"sort:updated-desc fork:true archived:false org:albertlauncher"_s
// },
// {
// Plugin::tr("Archived Albert repositories"),
// u"sort:updated-desc fork:true archived:true org:albertlauncher"_s
// }
// });
// writeSavedSearches();
// }