-
Notifications
You must be signed in to change notification settings - Fork 7
/
imagehandler.cpp
242 lines (210 loc) · 7.98 KB
/
imagehandler.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
/*
Hanghish
Copyright (C) 2015 Daniele Rogora
This file is part of Hangish.
Hangish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Hangish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with hangish. If not, see <http://www.gnu.org/licenses/>
*/
#include "imagehandler.h"
#include <utime.h>
QString galleryPath;
QString cachePath;
/*
* Some general notes:
* the method getImageAddr may be called by different threads at the same time; since buffer and Q* are shared, this would be a problem.
* Thus I implemented a basic locking mechanism that makes it executable by 1 thread at a time.
* The signal emitted at the end will trigger the update for the ther images, that will then the processed serially
*
* Google puts the jpg extension for all the images, whether they are JPEGs or not;
* this is not digested by Sailfish (both the native Jolla gallery and the QImage object), that looks at the suffix, and, if it doesn't find a JPEG it complains
* The workaround for this is to simply remove the suffix .jpg for all the images
*/
ImageHandler::ImageHandler(QObject *parent) :
QObject(parent)
{
lock = 0;
galleryPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation) + "/";
cachePath = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/";
nam = new QNetworkAccessManager();
}
void ImageHandler::setAuthenticator(OAuth2Auth *pAuth)
{
auth = pAuth;
}
QString ImageHandler::getImageAddr(QString imgUrl)
{
QString imgname = imgUrl;
imgname.replace('/', '_');
imgname.replace('%', '_');
if (imgname.endsWith(".jpg"))
imgname = imgname.left(imgname.size() - 4);
QString path = QString(cachePath + imgname);
QFile img(path);
if (img.exists()) {
//qDebug() << "Img exists " << imgname;
//Modify the lastModified field; this is necessary because otherwise the lastRead field is not updated
//Hope this is ok for Jolla QA
utime(QString(path).toStdString().c_str(), 0);
return path;
}
else {
if (lock.load()==1) {
qDebug() << "Another download in progress, returning url";
return imgUrl;
}
lock.store(1);
buffer.clear();
qDebug() << "Ok, let's download this";
QUrl url(imgUrl);
QNetworkRequest req(url);
req.setHeader(QNetworkRequest::CookieHeader, QVariant::fromValue(auth->getCookies()));
QNetworkReply *reply = nam->get(req);
//qDebug() << "Getting " << req.url().toString();
QObject::connect(reply, SIGNAL(readyRead()), this, SLOT(dataAvail()));
QObject::connect(reply, SIGNAL(finished()), this, SLOT(gotImage()));
return "";
}
return "";
}
QString ImageHandler::downloadVideo(QString videourl, bool toOpen) {
QString imgname = videourl;
imgname.replace('/', '_').replace('%', '_');
QString path = QString(cachePath + imgname);
QFile img(path);
if (img.exists()) {
//qDebug() << "Img exists " << imgname;
//Modify the lastModified field; this is necessary because otherwise the lastRead field is not updated
//Hope this is ok for Jolla QA
utime(QString(path).toStdString().c_str(), 0);
if (toOpen) {
QProcess *m_process = new QProcess(this);
m_process->start(QString("xdg-open " + path));
}
return path;
}
else {
if (lock.load()==1) {
qDebug() << "Another download in progress, returning url";
return "";
}
lock.store(1);
buffervideo.clear();
qDebug() << "Ok, let's download this";
QUrl url(videourl);
QNetworkRequest req(url);
req.setHeader(QNetworkRequest::CookieHeader, QVariant::fromValue(auth->getCookies()));
QNetworkReply *reply = nam->get(req);
//qDebug() << "Getting " << req.url().toString();
QObject::connect(reply, SIGNAL(readyRead()), this, SLOT(dataAvailVideo()));
QObject::connect(reply, SIGNAL(finished()), this, SLOT(gotVideo()));
return videourl;
}
}
void ImageHandler::dataAvailVideo()
{
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
//qDebug() << "DA " << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
buffervideo.append(reply->readAll());
}
void ImageHandler::gotVideo()
{
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
//qDebug() << "GI " << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
buffervideo.append(reply->readAll());
QString imgpath = QString(cachePath + reply->url().toString().replace('/', '_').replace('%', '_'));
//if (imgpath.endsWith(".mp4"))
// imgpath = imgpath.left(imgpath.size() - 4);
QFile img(imgpath);
img.open(QIODevice::WriteOnly);
img.write(buffervideo);
img.close();
//qDebug() << "Created ";
emit videoReady(imgpath);
lock.store(0);
QProcess *m_process = new QProcess(this);
m_process->start(QString("xdg-open " + imgpath));
}
void ImageHandler::dataAvail()
{
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
//qDebug() << "DA " << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
buffer.append(reply->readAll());
}
void ImageHandler::gotImage()
{
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
//qDebug() << "GI " << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
buffer.append(reply->readAll());
QString imgpath = QString(cachePath + reply->url().toString().replace('/', '_').replace('%', '_'));
if (imgpath.endsWith(".jpg"))
imgpath = imgpath.left(imgpath.size() - 4);
QFile img(imgpath);
img.open(QIODevice::WriteOnly);
img.write(buffer);
img.close();
//qDebug() << "Created ";
emit imgReady(reply->url().toString());
lock.store(0);
}
void delay()
{
QTime dieTime= QTime::currentTime().addSecs(1);
while( QTime::currentTime() < dieTime )
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
void ImageHandler::saveImageToGallery(QString imgUrl)
{
//qDebug() << "Saving";
QString savedAddr;
do {
savedAddr = getImageAddr(imgUrl);
delay();
} while (savedAddr=="" || savedAddr.startsWith("https://"));
QString fileName = imgUrl.right(imgUrl.size() - imgUrl.lastIndexOf('/')-1);
//qDebug() << fileName;
if (fileName.endsWith(".jpg"))
fileName = fileName.left(fileName.size() - 4);
QFile::copy(savedAddr, galleryPath + fileName);
emit savedToGallery();
}
void ImageHandler::saveVideoToGallery(QString imgUrl)
{
//qDebug() << "Saving";
QString savedAddr;
do {
savedAddr = downloadVideo(imgUrl, false);
delay();
} while (savedAddr=="" || savedAddr.startsWith("https://"));
QString fileName = imgUrl.right(imgUrl.size() - imgUrl.lastIndexOf('/')-1);
//qDebug() << fileName;
QFile::copy(savedAddr, galleryPath + fileName);
emit savedToGallery();
}
void ImageHandler::cleanCache()
{
qDebug() << "Cleaning images cache";
//Delete all the files that have not been accessed in the last 7 days
QDateTime now = QDateTime::currentDateTime();
QDir dir(cachePath);
dir.setNameFilters(QStringList() << "*.*");
dir.setFilter(QDir::Files);
QFileInfo fileInfo;
foreach(QString dirFile, dir.entryList())
{
//qDebug() << dirFile;
fileInfo.setFile(dir.absolutePath() + '/' + dirFile);
fileInfo.refresh();
QDateTime created = fileInfo.lastRead();
//qDebug() << created.toString();
if (created.addDays(7) < now)
dir.remove(dirFile);
}
}