1 /*
2 * SPDX-FileCopyrightText: 2020 George Florea Bănuș <georgefb899@gmail.com>
3 *
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 */
6
7 #include "worker.h"
8
9 #include "application.h"
10 #include "framedecoder.h"
11
12 #include <QCryptographicHash>
13 #include <QDebug>
14 #include <QDir>
15 #include <QFileInfo>
16 #include <QThread>
17
18 #include <KFileMetaData/ExtractorCollection>
19 #include <KFileMetaData/SimpleExtractionResult>
20
instance()21 Worker* Worker::instance()
22 {
23 static Worker w;
24 return &w;
25 }
26
getMetaData(int index,const QString & path)27 void Worker::getMetaData(int index, const QString &path)
28 {
29 QString mimeType = Application::mimeType(path);
30 KFileMetaData::ExtractorCollection exCol;
31 QList<KFileMetaData::Extractor*> extractors = exCol.fetchExtractors(mimeType);
32 KFileMetaData::SimpleExtractionResult result(path, mimeType,
33 KFileMetaData::ExtractionResult::ExtractMetaData);
34 if (extractors.size() == 0) {
35 return;
36 }
37 KFileMetaData::Extractor* ex = extractors.first();
38 ex->extract(&result);
39 auto properties = result.properties();
40
41 Q_EMIT metaDataReady(index, properties);
42 }
43
makePlaylistThumbnail(const QString & id,int width)44 void Worker::makePlaylistThumbnail(const QString &id, int width)
45 {
46 QImage image;
47
48 QUrl file(id);
49 file.setScheme(QStringLiteral("file"));
50
51 // figure out absolute path of the thumbnail
52 auto md5Hash = QCryptographicHash::hash(file.toString().toUtf8(), QCryptographicHash::Md5);
53 QString cacheDir(QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation));
54 QString appDir("haruna");
55 QString fileDir(md5Hash.toHex());
56 QString filename(QString(md5Hash.toHex()).append(".png"));
57 QString cachedFilePath = cacheDir + "/" + appDir + "/" + fileDir + "/" + filename;
58
59 // load existing thumbnail if there is one
60 if (QFileInfo::exists(cachedFilePath) && image.load(cachedFilePath)) {
61 Q_EMIT thumbnailSuccess(image);
62 return;
63 }
64
65 FrameDecoder frameDecoder(file.toLocalFile(), nullptr);
66 if (!frameDecoder.getInitialized()) {
67 return;
68 }
69 //before seeking, a frame has to be decoded
70 if (!frameDecoder.decodeVideoFrame()) {
71 return;
72 }
73
74 int secondToSeekTo = frameDecoder.getDuration() * 20 / 100;
75 frameDecoder.seek(secondToSeekTo);
76
77 VideoFrame videoFrame;
78 frameDecoder.getScaledVideoFrame(width, true, videoFrame);
79 frameDecoder.writeFrame(videoFrame, image);
80
81 if (image.isNull()) {
82 qDebug() << QStringLiteral("Failed to create thumbnail for file: %1").arg(id);
83 return;
84 }
85 Q_EMIT thumbnailSuccess(image);
86
87 QFileInfo fi(cachedFilePath);
88 // create folders where the file will be saved
89 if (QDir().mkpath(fi.absolutePath())) {
90 if (!image.save(cachedFilePath)) {
91 qDebug() << QStringLiteral("Failed to save thumbnail for file: %1").arg(id);
92 }
93 }
94 }
95