-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplaylist.cpp
224 lines (179 loc) · 6.7 KB
/
playlist.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
#include "playlist.h"
#include <QtNetwork/QNetworkReply>
#include <QStandardPaths>
#include <QJsonArray>
#include <QJsonParseError>
#include <QMetaEnum>
#include <QApplication>
#include <QDesktopWidget>
#include <QDebug>
template <typename T>
static T toCaseInsensitiveEnum(const QString& key, bool* ok) {
auto enumerator = QMetaEnum::fromType<T>();
for (int i = 0; i < enumerator.keyCount(); i++) {
if (key.compare(enumerator.key(i), Qt::CaseInsensitive) == 0) {
*ok = true;
return static_cast<T>(enumerator.value(i));
}
}
*ok = false;
return static_cast<T>(-1);
}
Playlist::Playlist(QObject *parent) : QObject(parent) {
_cachePath.setPath(QStandardPaths::writableLocation(QStandardPaths::CacheLocation));
if (! _cachePath.exists()) {
_cachePath.mkpath(".");
}
_entryPath.setPath(_cachePath.filePath("entries"));
if (! _entryPath.exists()) {
_entryPath.mkpath(".");
}
connect(&_metadataRefreshTimer, &QTimer::timeout, this, &Playlist::refreshMetadata);
_metadataRefreshTimer.start(10000);
}
Playlist::~Playlist() {
_metadataRefreshTimer.stop();
}
const Entry &Playlist::next() {
++_playbackIterator;
if (_playbackIterator == _entries.end()) {
_playbackIterator = _entries.begin();
}
return *_playbackIterator;
}
void Playlist::macAddress(const QString &address) {
_mac = address;
}
void Playlist::url(const QString &url) {
_url = url;
}
void Playlist::cleanupStaleEntries() {
QSet<QString> entries = _entryPath.entryList({}, QDir::Files).toSet();
for (auto& entry : _entries) {
entries.remove(entry.fileId);
}
for (auto& staleEntry : entries) {
QFile fileEntry(_entryPath.filePath(staleEntry));
fileEntry.remove();
qInfo() << "Removed stale entry" << fileEntry.fileName();
}
}
void Playlist::downloadEntries() {
if (_refreshIterator == _refreshEntries.end()) {
_entries = _refreshEntries;
_playbackIterator = _entries.end();
--_playbackIterator;
emit playlistAvailable();
cleanupStaleEntries();
return;
}
QFile entryFile(_entryPath.filePath(_refreshIterator->fileId));
if (! entryFile.exists()) {
qDebug() << "Downloading" << _refreshIterator->url;
auto reply = _nam.get(QNetworkRequest(_refreshIterator->url));
connect(reply, &QNetworkReply::finished, this, &Playlist::onFetchEntryFinished);
} else {
++_refreshIterator;
downloadEntries();
}
}
void Playlist::onFetchEntryFinished() {
auto reply = qobject_cast<QNetworkReply*>(sender());
reply->deleteLater();
if (reply->error() != QNetworkReply::NoError) {
qWarning() << "Failed to download item at url" << _refreshIterator->url << ", removing entry";
_refreshEntries.erase(_refreshIterator);
} else {
QFile entryFile(_entryPath.filePath(_refreshIterator->fileId));
entryFile.open(QIODevice::WriteOnly);
entryFile.write(reply->readAll());
_refreshIterator->loaded = true;
++_refreshIterator;
}
downloadEntries();
}
void Playlist::parseMetadataEntries(QJsonArray entries) {
_refreshEntries.clear();
QRect desktopResolution = QApplication::desktop()->screenGeometry();
for (QJsonValueRef entry_value : entries) {
QJsonObject entryObj = entry_value.toObject();
bool typeOk;
Playlist::Type type = toCaseInsensitiveEnum<Playlist::Type>(entryObj["type"].toString(), &typeOk);
if (! typeOk) {
qWarning() << "Garbage in sequence, skipping entry";
qWarning() << "\t" << entryObj;
continue;
}
Entry entry;
entry.fileId = entryObj["fileId"].toString();
entry.filePath = _entryPath.filePath(entry.fileId);
entry.type = type;
switch (type) {
case Playlist::Type::IMAGE:
// {\"id\":\"ad934f06-973a-4937-b402-0a057871340a\",\"type\":\"image\",\"fileId\":\"7635d251-e3a1-4818-b59c-86b089514256\",\"durationMillis\":15000}
entry.durationMillis = entryObj["durationMillis"].toInt();
entry.url.setUrl(QString("%1/api/getImage/%2/%3/%4").arg(_url).arg(entry.fileId).arg(desktopResolution.width()).arg(desktopResolution.height()));
break;
case Playlist::Type::VIDEO:
// {\"id\":\"af46cf69-b8d2-4f5d-bf31-c57736e4f92b\",\"type\":\"video\",\"fileId\":\"e8043297-5ac3-45c6-a92b-ad5e19468c2f\",\"transcodingComplete\":true}
entry.url.setUrl(QString("%1/api/getVideo/%2/%3").arg(_url).arg(_mac).arg(entry.fileId));
break;
}
_refreshEntries.append(entry);
}
_refreshIterator = _refreshEntries.begin();
downloadEntries();
}
void Playlist::parseMetadata() {
QFile input(_cachePath.filePath("metadata"));
input.open(QIODevice::ReadOnly);
QJsonObject root = openJsonFile(input);
if (root.isEmpty()) {
qWarning() << Q_FUNC_INFO << "Failed to parse metadata file, located at" << input.fileName();
return;
}
QJsonObject data = root["data"].toObject();
QJsonObject sequence = data["sequence"].toObject();
QString sequenceId = sequence["id"].toString();
qint64 published = sequence["published"].toVariant().toLongLong();
if (published != _published || _sequenceId != sequenceId) {
parseMetadataEntries(sequence["entries"].toArray());
}
_sequenceId = sequenceId;
_published = published;
}
void Playlist::refreshMetadata() {
QNetworkRequest req(QUrl(QString("%1/api/getSequence/%2.json").arg(_url).arg(_mac)));
auto reply = _nam.get(req);
connect(reply, &QNetworkReply::finished, this, &Playlist::onRefreshFinished);
}
void Playlist::checkForCachedMetadata() {
if (QFile(_cachePath.filePath("metadata")).exists()) {
parseMetadata();
}
}
void Playlist::onRefreshFinished() {
auto reply = qobject_cast<QNetworkReply*>(sender());
reply->deleteLater();
if (reply->error() != QNetworkReply::NoError) {
qWarning() << Q_FUNC_INFO << "Failed to refresh metadata";
return;
}
QFile output(_cachePath.filePath("metadata"));
output.open(QIODevice::WriteOnly);
output.write(reply->readAll());
output.close();
parseMetadata();
}
QJsonObject Playlist::openJsonFile(QFile& sourceFile) {
QJsonParseError parseError;
QString rawJson = QString::fromUtf8(sourceFile.readAll());
QJsonDocument json = QJsonDocument::fromJson(rawJson.toUtf8(), &parseError);
if (parseError.error != QJsonParseError::NoError) {
qWarning() << "Failed to parse JSON";
qWarning() << "\t" << parseError.errorString();
return QJsonObject();
}
QJsonObject rootObject = json.object();
return rootObject;
}