-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathposteditorbackend.cpp
360 lines (301 loc) · 9.72 KB
/
posteditorbackend.cpp
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
// SPDX-FileCopyrightText: 2022 Carl Schwan <[email protected]>
// SPDX-License-Identifier: LGPL-2.1-or-later
#include "editor/posteditorbackend.h"
#include "account/abstractaccount.h"
#include "account/accountmanager.h"
#include "editor/attachmenteditormodel.h"
#include <KLocalizedString>
using namespace Qt::Literals::StringLiterals;
PostEditorBackend::PostEditorBackend(QObject *parent)
: QObject(parent)
, m_idenpotencyKey(QUuid::createUuid().toString())
, m_language(AccountManager::instance().selectedAccount()->preferences()->defaultLanguage())
, m_poll(new PollEditorBackend(this))
, m_account(AccountManager::instance().selectedAccount())
, m_attachmentEditorModel(new AttachmentEditorModel(this, m_account))
{
}
PostEditorBackend::~PostEditorBackend() = default;
QString PostEditorBackend::id() const
{
return m_id;
}
void PostEditorBackend::setId(const QString &id)
{
m_id = id;
}
QString PostEditorBackend::status() const
{
return m_status;
}
void PostEditorBackend::setStatus(const QString &status)
{
if (m_status == status) {
return;
}
m_status = status;
Q_EMIT statusChanged();
}
QString PostEditorBackend::spoilerText() const
{
return m_spoilerText;
}
void PostEditorBackend::setSpoilerText(const QString &spoilerText)
{
if (m_spoilerText == spoilerText) {
return;
}
m_spoilerText = spoilerText;
Q_EMIT spoilerTextChanged();
}
QString PostEditorBackend::inReplyTo() const
{
return m_inReplyTo;
}
void PostEditorBackend::setInReplyTo(const QString &inReplyTo)
{
if (m_inReplyTo == inReplyTo) {
return;
}
m_inReplyTo = inReplyTo;
Q_EMIT inReplyToChanged();
}
Post::Visibility PostEditorBackend::visibility() const
{
return m_visibility;
}
void PostEditorBackend::setVisibility(Post::Visibility visibility)
{
if (m_visibility == visibility) {
return;
}
m_visibility = visibility;
Q_EMIT visibilityChanged();
}
QString PostEditorBackend::language() const
{
return m_language;
}
void PostEditorBackend::setLanguage(const QString &language)
{
if (m_language == language) {
return;
}
m_language = language;
Q_EMIT languageChanged();
}
QDateTime PostEditorBackend::scheduledAt() const
{
return m_scheduledAt;
}
void PostEditorBackend::setScheduledAt(const QDateTime &scheduledAt)
{
if (m_scheduledAt == scheduledAt) {
return;
}
m_scheduledAt = scheduledAt;
Q_EMIT scheduledAtChanged();
}
AttachmentEditorModel *PostEditorBackend::attachmentEditorModel() const
{
return m_attachmentEditorModel;
}
QStringList PostEditorBackend::mentions() const
{
return m_mentions;
}
void PostEditorBackend::setMentions(const QStringList &mentions)
{
if (m_mentions == mentions) {
return;
}
m_mentions = mentions;
Q_EMIT mentionsChanged();
}
bool PostEditorBackend::sensitive() const
{
return m_sensitive;
}
void PostEditorBackend::setSensitive(bool sensitive)
{
if (m_sensitive == sensitive) {
return;
}
m_sensitive = sensitive;
Q_EMIT sensitiveChanged();
}
AbstractAccount *PostEditorBackend::account() const
{
return m_account;
}
void PostEditorBackend::setAccount(AbstractAccount *account)
{
if (m_account == account) {
return;
}
m_account = account;
Q_EMIT accountChanged();
}
void PostEditorBackend::setHasExistingPoll(bool hasExisting)
{
if (m_pollEnabled != hasExisting) {
m_pollEnabled = hasExisting;
Q_EMIT pollEnabledChanged();
}
}
int PostEditorBackend::charactersLeft() const
{
if (m_account == nullptr) {
return 0;
}
QRegularExpression re{QStringLiteral(R"((http|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-]))")};
re.setPatternOptions(QRegularExpression::DontCaptureOption);
const auto matches = re.match(m_status).capturedTexts();
// We want to accumulate each link, and then "add back" the characters you should
// have, taking the difference from charactersPreservedPerUrl.
const int sum = std::accumulate(matches.constBegin(), matches.constEnd(), 0, [this](int sum, const QString &link) {
return sum + link.length() - m_account->charactersReservedPerUrl();
});
return m_account->maxPostLength() - m_status.length() + sum;
}
void PostEditorBackend::copyFromOther(PostEditorBackend *other)
{
setId(other->id());
setSpoilerText(other->spoilerText());
setVisibility(other->visibility());
setLanguage(other->language());
setScheduledAt(other->scheduledAt());
setMentions(other->mentions());
setSensitive(other->sensitive());
setAccount(other->account());
m_pollEnabled = other->m_pollEnabled;
Q_EMIT pollEnabledChanged();
m_poll->copyFromOther(other->m_poll);
m_attachmentEditorModel->copyFromOther(other->m_attachmentEditorModel);
}
void PostEditorBackend::setupReplyTo(Post *post)
{
setInReplyTo(post->originalPostId());
setSpoilerText(post->spoilerText());
setVisibility(post->visibility());
QStringList mentions = {'@'_L1 + post->authorIdentity()->account()};
for (const auto &mention : post->mentions()) {
if (mentions.contains(mention)) {
continue;
}
mentions.append(mention);
}
setMentions(mentions);
}
QJsonDocument PostEditorBackend::toJsonDocument() const
{
QJsonObject obj;
obj["spoiler_text"_L1] = m_spoilerText;
obj["status"_L1] = m_status;
obj["sensitive"_L1] = m_sensitive;
obj["visibility"_L1] = Post::visibilityToString(m_visibility);
if (!m_inReplyTo.isEmpty()) {
obj["in_reply_to_id"_L1] = m_inReplyTo;
}
auto media_ids = QJsonArray();
for (const auto &att : std::as_const(m_attachmentEditorModel->attachments())) {
media_ids.append(att->m_id);
}
obj["media_ids"_L1] = media_ids;
obj["language"_L1] = m_language;
if (m_pollEnabled) {
obj["poll"_L1] = m_poll->toJsonObject();
}
if (m_scheduledAt.isValid()) {
obj["scheduled_at"_L1] = m_scheduledAt.toUTC().toString(Qt::DateFormat::ISODate);
}
return QJsonDocument(obj);
}
void PostEditorBackend::save()
{
// If we were editing a scheduled or draft post, make sure to clean up the previous iteration
if (!m_scheduledPostId.isEmpty()) {
m_account->deleteResource(m_account->apiUrl(QStringLiteral("/api/v1/scheduled_statuses/%1").arg(m_scheduledPostId)), true, this, {});
}
QUrl post_status_url = m_account->apiUrl(QStringLiteral("/api/v1/statuses"));
auto doc = toJsonDocument();
QHash<QByteArray, QByteArray> headers;
headers["Idempotency-Key"] = m_idenpotencyKey.toUtf8();
m_account->post(
post_status_url,
doc,
true,
this,
[this](QNetworkReply *) {
Q_EMIT posted(QStringLiteral(""));
},
[this](QNetworkReply *reply) {
auto data = reply->readAll();
auto doc = QJsonDocument::fromJson(data);
auto obj = doc.object();
if (obj.contains("error"_L1)) {
Q_EMIT posted(obj["error"_L1].toString());
} else {
Q_EMIT posted(i18n("An unknown error occurred."));
}
},
headers);
}
void PostEditorBackend::edit()
{
QUrl edit_status_url = m_account->apiUrl(QStringLiteral("/api/v1/statuses/%1").arg(m_id));
auto doc = toJsonDocument();
m_account->put(edit_status_url, doc, true, this, [this](QNetworkReply *reply) {
auto data = reply->readAll();
auto doc = QJsonDocument::fromJson(data);
auto obj = doc.object();
Q_EMIT editComplete(obj);
});
}
void PostEditorBackend::saveDraft()
{
// Set it far in the future so it's a "draft"
auto currentDate = QDateTime::currentDateTime();
currentDate = currentDate.addYears(3000);
setScheduledAt(currentDate);
save();
}
void PostEditorBackend::loadScheduledPost(const QString &id)
{
QUrl url = m_account->apiUrl(QStringLiteral("/api/v1/scheduled_statuses/%1").arg(id));
m_account->get(url, true, this, [this, id](QNetworkReply *reply) {
auto data = reply->readAll();
auto doc = QJsonDocument::fromJson(data);
auto obj = doc.object();
auto params = obj["params"_L1].toObject();
if (params["poll"_L1].isObject()) {
auto poll = params["poll"_L1].toObject();
auto options = poll["options"_L1].toArray();
m_poll->clearOptions();
// FIXME: everything but the last poll option is restored, due to limitations in how the poll composer is designed
for (int i = 0; i < options.size(); ++i) {
m_poll->addOption();
m_poll->setOption(i, options[i].toString());
}
m_poll->setExpiresIn(poll["expires_in"_L1].toInt());
m_poll->setMultipleChoice(poll["multiple"_L1].toBool());
m_poll->setHideTotals(poll["hide_totals"_L1].toBool());
m_pollEnabled = true;
} else {
m_pollEnabled = false;
}
Q_EMIT pollEnabledChanged();
setStatus(params["text"_L1].toString());
setLanguage(params["language"_L1].toString());
m_attachmentEditorModel->copyFromArray(obj["media_attachments"_L1].toArray());
setSensitive(params["sensitive"_L1].toBool());
setScheduledAt(QDateTime::fromString(params["scheduled_at"_L1].toString(), Qt::ISODate));
setSpoilerText(params["spoiler_text"_L1].toString());
setInReplyTo(params["in_reply_to"_L1].toString());
setVisibility(Post::stringToVisibility(params["visibility"_L1].toString()));
// Save this id for later, so we clean up the draft once we properly posted it.
m_scheduledPostId = id;
Q_EMIT scheduledPostLoaded();
});
}
#include "moc_posteditorbackend.cpp"