-
Notifications
You must be signed in to change notification settings - Fork 341
/
imagemanager.cpp
2544 lines (2148 loc) · 74 KB
/
imagemanager.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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "imagemanager.h"
#include <QImageReader>
#include <QRunnable>
#include <utility>
#include "dbaccess.h" // for FileAssociations
#include "mthreadpool.h"
#include "mythdate.h"
#include "mythmediamonitor.h"
#define LOC QString("ImageManager: ")
#define DBLOC QString("ImageDb(%1): ").arg(m_table)
// Must be empty as it's prepended to path
#define STORAGE_GROUP_MOUNT ""
#define DB_TABLE "gallery_files"
#define RESULT_ERR(ERR, MESG) \
{ LOG(VB_GENERAL, LOG_ERR, LOC + (MESG)); \
return QStringList("ERROR") << (ERR); }
#define RESULT_OK(MESG) \
{ LOG(VB_FILE, LOG_DEBUG, LOC + (MESG)); \
return QStringList("OK"); }
#define IMPORTDIR "Import"
//! A device containing images (ie. USB stick, CD, storage group etc)
class Device
{
public:
Device(QString name, QString mount,
MythMediaDevice *media = nullptr, QTemporaryDir *import = nullptr)
: m_present(true), m_name(std::move(name)), m_mount(std::move(mount)),
m_media(media), m_dir(import)
{
// Path relative to TEMP storage group
m_thumbs = QString("%1/%2").arg(THUMBNAIL_SUBDIR, m_name);
}
//! Delete device, its thumbnails and any imported images
~Device()
{
Close();
// Remove imported images
delete m_dir;
// Clean up non-SG thumbnails
if (m_mount != STORAGE_GROUP_MOUNT)
RemoveThumbs();
}
//! Releases device
void Close(bool eject = false)
{
// Imports remain present; others do not
m_present = isImport();
// Release device
if (m_media)
{
if (eject)
{
LOG(VB_GENERAL, LOG_INFO, LOC + QString("Ejecting '%1' at '%2'")
.arg(m_name, m_mount));
MediaMonitor::GetMediaMonitor()->EjectMedia(m_media->getDevicePath());
}
else
LOG(VB_MEDIA, LOG_DEBUG, LOC + QString("Unlocked '%1'").arg(m_name));
MediaMonitor::GetMediaMonitor()->Unlock(m_media);
m_media = nullptr;
}
}
/*!
\brief Clears all files and sub-dirs within a directory
\param path Dir to clear
*/
static void RemoveDirContents(const QString& path)
{
QDir(path).removeRecursively();
}
//! Delete thumbnails associated with device
void RemoveThumbs(void) const
{
// Remove thumbnails
QString dir = QString("%1/" TEMP_SUBDIR "/%2").arg(GetConfDir(), m_thumbs);
LOG(VB_FILE, LOG_INFO, LOC + QString("Removing thumbnails in %1").arg(dir));
RemoveDirContents(dir);
QDir::root().rmpath(dir);
}
bool isImport() const { return m_dir; }
bool isPresent() const { return m_present; }
void setPresent(MythMediaDevice *media) { m_present = true; m_media = media; }
//! True when gallery UI is running & device is useable. Always true for imports
bool m_present;
QString m_name; //!< Device model/volume/id
QString m_mount; //!< Mountpoint
QString m_thumbs; //!< Dir sub-path of device thumbnails
MythMediaDevice *m_media; //!< Set for MediaMonitor devices only
QTemporaryDir *m_dir; //!< Dir path of images: import devices only
};
static Device kNullDevice = Device("Unknown Device", "<Invalid Path>");
DeviceManager::~DeviceManager()
{
qDeleteAll(m_devices);
}
//! Get path at which the device is mounted
QString DeviceManager::DeviceMount(int devId) const
{
return m_devices.value(devId, &kNullDevice)->m_mount;
}
//! Get model name of the device
QString DeviceManager::DeviceName(int devId) const
{
return m_devices.value(devId, &kNullDevice)->m_name;
}
QString DeviceManager::ThumbDir(int fs) const
{
return m_devices.value(fs, &kNullDevice)->m_thumbs;
}
/*!
\brief Define a new device and assign it a unique id. If the device is already
known, its existing id is returned.
\param name Device model/volume/id
\param mount Device mountpoint
\param media Set for MediaMonitor devices only
\param dir Dir path of images: import devices only
\return int A unique id for this device.
*/
int DeviceManager::OpenDevice(const QString &name, const QString &mount,
MythMediaDevice *media, QTemporaryDir *dir)
{
// Handle devices reappearing at same mountpoint.
// If a USB is unplugged whilst in use (without unmounting) we get no event
// but we do when it's re-inserted
QString state("Known");
int id = LocateMount(mount);
if (id == DEVICE_INVALID)
{
state = "New";
id = m_devices.isEmpty() ? 0 : (m_devices.constEnd() - 1).key() + 1;
m_devices.insert(id, new Device(name, mount, media, dir));
}
else if (m_devices.value(id))
m_devices.value(id)->setPresent(media);
LOG(VB_GENERAL, LOG_INFO, LOC +
QString("%1 device %2 mounted at '%3' [Id %4]")
.arg(state, name, mount).arg(id));
return id;
}
/*!
\brief Remove a device (or all devices)
\param devId Id of device to remove
\param action What action to take.
\return bool True if device is recognized
*/
QStringList DeviceManager::CloseDevices(int devId, const QString &action)
{
QStringList clear;
if (action == "DEVICE CLOSE ALL")
{
// Close all devices but retain their thumbnails
for (auto *dev : qAsConst(m_devices))
if (dev)
dev->Close();
}
else if (action == "DEVICE CLEAR ALL")
{
// Remove all thumbnails but retain devices
for (const auto *dev : qAsConst(m_devices)) {
if (dev)
{
clear << dev->m_mount;
dev->RemoveThumbs();
}
}
}
else
{
// Remove single device & its thumbnails, optionally ejecting it
Device *dev = m_devices.take(devId);
if (dev)
{
if (action == "DEVICE EJECT")
dev->Close(true);
clear << dev->m_mount;
delete dev;
}
}
return clear;
}
/*!
\brief Find the id of a device
\param mount Device mountpoint
\return int Id (positive) if found, 0 if unknown
*/
int DeviceManager::LocateMount(const QString &mount) const
{
DeviceMap::const_iterator it = m_devices.constBegin();
while (it != m_devices.constEnd())
{
if (it.value()->m_mount == mount)
return it.key();
++it;
}
return DEVICE_INVALID;
}
//! Get all known devices
StringMap DeviceManager::GetDeviceDirs() const
{
StringMap paths;
#if QT_VERSION < QT_VERSION_CHECK(5,10,0)
for (int id : m_devices.keys())
{
Device *dev = m_devices.value(id);
if (dev)
paths.insert(id, dev->m_mount);
}
#elif QT_VERSION < QT_VERSION_CHECK(5,15,0)
for (auto it = m_devices.constKeyValueBegin();
it != m_devices.constKeyValueEnd(); ++it)
{
if ((*it).second)
paths.insert((*it).first, (*it).second->m_mount);
}
#else
for (auto it = m_devices.constKeyValueBegin();
it != m_devices.constKeyValueEnd(); ++it)
{
if (it->second)
paths.insert(it->first, it->second->m_mount);
}
#endif
return paths;
}
//! Get list of mountpoints for non-import devices
QList<int> DeviceManager::GetAbsentees()
{
QList<int> absent;
#if QT_VERSION < QT_VERSION_CHECK(5,10,0)
for (int id : m_devices.keys())
{
Device *dev = m_devices.value(id);
if (dev && !dev->isPresent())
absent << id;
}
#elif QT_VERSION < QT_VERSION_CHECK(5,15,0)
for (auto it = m_devices.constKeyValueBegin();
it != m_devices.constKeyValueEnd(); it++)
{
Device *dev = (*it).second;
if (dev && !dev->isPresent())
absent << (*it).first;
}
#else
for (auto it = m_devices.constKeyValueBegin();
it != m_devices.constKeyValueEnd(); it++)
{
Device *dev = it->second;
if (dev && !dev->isPresent())
absent << it->first;
}
#endif
return absent;
}
/*!
\brief Constructor
*/
ImageAdapterBase::ImageAdapterBase() :
m_imageFileExt(SupportedImages()),
m_videoFileExt(SupportedVideos())
{
// Generate glob list from supported extensions
QStringList glob;
QStringList allExt = m_imageFileExt + m_videoFileExt;
for (const auto& ext : qAsConst(allExt))
glob << "*." + ext;
// Apply filters to only detect image files
m_dirFilter.setNameFilters(glob);
m_dirFilter.setFilter(QDir::AllDirs | QDir::Files | QDir::Readable |
QDir::NoDotAndDotDot | QDir::NoSymLinks);
// Sync files before dirs to improve thumb generation response
// Order by time (oldest first) - this determines the order thumbs appear
m_dirFilter.setSorting(QDir::DirsLast | QDir::Time | QDir::Reversed);
}
/*!
\brief Return recognised pictures
\return List of file extensions
*/
QStringList ImageAdapterBase::SupportedImages()
{
// Determine supported picture formats from Qt
QStringList formats;
QList<QByteArray> supported = QImageReader::supportedImageFormats();
for (const auto& ext : qAsConst(supported))
formats << QString(ext);
return formats;
}
/*!
\brief Return recognised video extensions
\return List of file extensions
*/
QStringList ImageAdapterBase::SupportedVideos()
{
// Determine supported video formats from MythVideo
QStringList formats;
const FileAssociations::association_list faList =
FileAssociations::getFileAssociation().getList();
for (const auto & fa : faList)
{
if (!fa.use_default && fa.playcommand == "Internal")
formats << QString(fa.extension);
}
return formats;
}
/*!
\brief Construct a local image from a file
\param fi File
\param parentId Id of the parent dir
\param devId Id of device containing the file
\param base Unused but required for adapter interface
\return ImageItem An image object
*/
ImageItem *ImageAdapterLocal::CreateItem(const QFileInfo &fi, int parentId,
int devId, const QString & /*base*/) const
{
auto *im = new ImageItem();
im->m_parentId = parentId;
im->m_device = devId;
im->m_filePath = fi.absoluteFilePath();
if (parentId == GALLERY_DB_ID)
{
// Import devices show time of import, other devices show 'last scan time'
im->m_date = im->m_filePath.contains(IMPORTDIR)
? fi.lastModified().toSecsSinceEpoch()
: QDateTime::currentSecsSinceEpoch();
im->m_modTime = im->m_date;
im->m_type = kDevice;
return im;
}
im->m_modTime = fi.lastModified().toSecsSinceEpoch();
if (fi.isDir())
{
im->m_type = kDirectory;
return im;
}
im->m_extension = fi.suffix().toLower();
im->m_type = GetImageType(im->m_extension);
if (im->m_type == kUnknown)
{
delete im;
return nullptr;
}
im->m_thumbPath = GetAbsThumbPath(ThumbDir(im->m_device), ThumbPath(*im));
im->m_size = fi.size();
return im;
}
/*!
* \brief Send local message to UI about local ids
* \param mesg Message name
* \param extra Message data
*/
void ImageAdapterLocal::Notify(const QString &mesg,
const QStringList &extra)
{
QString host(gCoreContext->GetHostName());
gCoreContext->SendEvent(MythEvent(QString("%1 %2").arg(mesg, host), extra));
}
/*!
\brief Construct a remote image from a file
\param fi File
\param parentId Id of the parent dir
\param devId Unused
\param base SG dir path
\return ImageItem An image object
*/
ImageItem *ImageAdapterSg::CreateItem(const QFileInfo &fi, int parentId,
int /*devId*/, const QString &base) const
{
auto *im = new ImageItem();
im->m_device = 0;
im->m_parentId = parentId;
if (parentId == GALLERY_DB_ID)
{
// All SG dirs map to a single Db dir
im->m_filePath = "";
im->m_type = kDevice;
im->m_date = QDateTime::currentMSecsSinceEpoch() / 1000;
im->m_modTime = im->m_date;
return im;
}
// Strip SG path & leading / to leave a relative path
im->m_filePath = fi.absoluteFilePath().mid(base.size() + 1);
im->m_modTime = fi.lastModified().toSecsSinceEpoch();
if (fi.isDir())
{
im->m_type = kDirectory;
return im;
}
im->m_extension = fi.suffix().toLower();
im->m_type = GetImageType(im->m_extension);
if (im->m_type == kUnknown)
{
delete im;
return nullptr;
}
im->m_thumbPath = GetAbsThumbPath(ThumbDir(im->m_device), ThumbPath(*im));
im->m_size = fi.size();
return im;
}
/*!
* \brief Send message to all clients about remote ids
* \param mesg Message name
* \param extra Message data
*/
void ImageAdapterSg::Notify(const QString &mesg,
const QStringList &extra)
{
gCoreContext->SendEvent(MythEvent(mesg, extra));
}
/*!
\brief Returns SG dirs
\return StringMap Map <Arbitrary id, Device Path>
*/
StringMap ImageAdapterSg::GetScanDirs() const
{
StringMap map;
int i = 0;
QStringList paths = m_sg.GetDirList();
for (const auto& path : qAsConst(paths))
map.insert(i++, path);
return map;
}
/*!
\brief Get absolute filepath for a remote image
\details For the SG node the path of SG dir with most space is returned
\param im Image
\return QString Absolute filepath
*/
QString ImageAdapterSg::GetAbsFilePath(const ImagePtrK &im) const
{
if (im->IsDevice())
return m_sg.FindNextDirMostFree();
return im->m_filePath.startsWith("/") ? im->m_filePath
: m_sg.FindFile(im->m_filePath);
}
// Database fields used by several image queries
#define DB_COLUMNS \
"file_id, filename, name, dir_id, type, modtime, size, " \
"extension, date, hidden, orientation, angle, path, zoom"
// Id, filepath, basename, parentId, type, modtime, size,
// extension, image date, hidden, orientation, cover id, comment, device id
/*!
\brief Create image from Db query data
\param query Db query result
\return ImageItem An image object
*/
template <class FS>
ImageItem *ImageDb<FS>::CreateImage(const MSqlQuery &query) const
{
auto *im = new ImageItem(FS::ImageId(query.value(0).toInt()));
// Ordered as per DB_COLUMNS
im->m_filePath = query.value(1).toString();
im->m_baseName = query.value(2).toString();
im->m_parentId = FS::ImageId(query.value(3).toInt());
im->m_type = query.value(4).toInt();
im->m_modTime = query.value(5).toInt();
im->m_size = query.value(6).toInt();
im->m_extension = query.value(7).toString();
im->m_date = query.value(8).toUInt();
im->m_isHidden = query.value(9).toBool();
im->m_orientation = query.value(10).toInt();
im->m_userThumbnail = FS::ImageId(query.value(11).toInt());
im->m_comment = query.value(12).toString();
im->m_device = query.value(13).toInt();
im->m_url = FS::MakeFileUrl(im->m_filePath);
if (im->IsFile())
{
// Only pics/vids have thumbs
QString thumbPath(FS::ThumbPath(*im));
QString devPath(FS::ThumbDir(im->m_device));
QString url(FS::MakeThumbUrl(devPath, thumbPath));
im->m_thumbPath = FS::GetAbsThumbPath(devPath, thumbPath);
im->m_thumbNails.append(qMakePair(im->m_id, url));
}
return im;
}
/*!
* \brief Read database images/dirs by id
* \param[in] ids Comma-separated list of ids
* \param[in,out] files List of files
* \param[in,out] dirs List of dirs
* \param[in] refine SQL clause to refine selection & apply ordering
* \return int Number of items matching query, -1 on SQL error
*/
template <class FS>
int ImageDb<FS>::GetImages(const QString &ids, ImageList &files, ImageList &dirs,
const QString &refine) const
{
if (ids.isEmpty())
return 0;
QString select = QString("file_id IN (%1) %2").arg(FS::DbIds(ids), refine);
return ReadImages(dirs, files, select);
}
/*!
\brief Read immediate children of a dir
\param[in,out] dirs List of child subdirs
\param[in,out] files List of child files
\param[in] ids Comma-separated list of dir ids
\param[in] refine SQL clause to refine selection & apply ordering
\return int Number of items matching query, -1 on SQL error
*/
template <class FS>
int ImageDb<FS>::GetChildren(QString ids, ImageList &files, ImageList &dirs,
const QString &refine) const
{
QString select = QString("dir_id IN (%1) %2").arg(FS::DbIds(ids), refine);
return ReadImages(dirs, files, select);
}
/*!
\brief Read a dir and its immediate children from Db
\param[in] id Dir id
\param[out] parent Dir item
\param[in,out] dirs Ordered/filtered child subdirs
\param[in,out] files Ordered/filtered child files
\param[in] refine SQL clause for filtering/ordering child images
\return int Number of items matching query.
*/
template <class FS>
int ImageDb<FS>::GetDirectory(int id, ImagePtr &parent,
ImageList &files, ImageList &dirs,
const QString &refine) const
{
MSqlQuery query(MSqlQuery::InitCon());
query.prepare(QString("SELECT " DB_COLUMNS " FROM %1 "
"WHERE (dir_id = :ID1 OR file_id = :ID2) "
"%2;").arg(m_table, refine));
// Qt < 5.4 won't bind multiple occurrences
int dbId = FS::DbId(id);
query.bindValue(":ID1", dbId);
query.bindValue(":ID2", dbId);
if (!query.exec())
{
MythDB::DBError(DBLOC, query);
return -1;
}
while (query.next())
{
ImagePtr im(CreateImage(query));
if (im->IsFile())
files.append(im);
else if (im->m_id == id)
parent = im;
else
dirs.append(im);
}
return query.size();
}
/*!
\brief Return images and all of their descendants.
\param[in] ids Image ids
\param[in,out] files Ordered/filtered files
\param[in,out] dirs Ordered/filtered dirs
*/
template <class FS>
bool ImageDb<FS>::GetDescendants(const QString &ids,
ImageList &files, ImageList &dirs) const
{
if (ids.isEmpty())
return false;
if (ReadImages(dirs, files, QString("file_id IN (%1)").arg(FS::DbIds(ids))) < 0)
return false;
MSqlQuery query(MSqlQuery::InitCon());
QString sql =
QString("SELECT " DB_COLUMNS
", LENGTH(filename) - LENGTH(REPLACE(filename, '/', ''))"
" AS depth "
"FROM %1 WHERE filename LIKE :PREFIX "
"ORDER BY depth;").arg(m_table);
for (const auto& im1 : qAsConst(dirs))
{
query.prepare(sql);
query.bindValue(":PREFIX", im1->m_filePath + "/%");
if (!query.exec())
{
MythDB::DBError(DBLOC, query);
return false;
}
while (query.next())
{
ImagePtr im2(CreateImage(query));
if (im2->IsDirectory())
dirs.append(im2);
else
files.append(im2);
}
}
return true;
}
/*!
\brief Returns all files in the sub-tree of a dir.
\param[in,out] files List of images within sub-tree. Direct children first, then
depth-first traversal of peer sub-dirs. Each level ordered as per refine criteria
\param id Dir id
\param refine SQL clause defining filter & ordering criteria
*/
template <class FS>
bool ImageDb<FS>::GetImageTree(int id, ImageList &files, const QString &refine) const
{
// Load starting children
ImageList dirs;
if (GetChildren(QString::number(id), files, dirs, refine) < 0)
return false;
for (const auto& im : qAsConst(dirs))
if (!GetImageTree(im->m_id, files, refine))
return false;
return true;
}
/*!
* \brief Read all database images and dirs as map. No filters or ordering applied.
* \param[in,out] files Map <filepath, image>
* \param[in,out] dirs Map <filepath, dir>
*/
template <class FS>
bool ImageDb<FS>::ReadAllImages(ImageHash &files, ImageHash &dirs) const
{
MSqlQuery query(MSqlQuery::InitCon());
query.prepare(QString("SELECT " DB_COLUMNS " FROM %1").arg(m_table));
if (!query.exec())
{
MythDB::DBError(DBLOC, query);
return false;
}
while (query.next())
{
ImagePtr im(CreateImage(query));
if (im->IsDirectory())
dirs.insert(im->m_filePath, im);
else
files.insert(im->m_filePath, im);
}
return true;
}
/*!
\brief Clear Db for device & remove device
\param devId Device id, 0 to clear all devices
\param action The myth protocol message. Determines whether/how much information is removed from the database.
\return Either list of ids that have been deleted or "ALL" with list of
filepath prefixes that will remove device images from the UI image cache
*/
template <class FS>
void ImageDb<FS>::ClearDb(int devId, const QString &action)
{
if (action == "DEVICE CLOSE ALL")
// Retain Db images when closing UI
return;
MSqlQuery query(MSqlQuery::InitCon());
if (action == "DEVICE CLEAR ALL")
{
// Clear images from all devices. Reset auto-increment
query.prepare(QString("TRUNCATE TABLE %1;").arg(m_table));
if (!query.exec())
MythDB::DBError(DBLOC, query);
}
else // Actions DEVICE REMOVE & DEVICE EJECT
{
// Delete all images of the device
query.prepare(QString("DELETE IGNORE FROM %1 WHERE zoom = :FS;").arg(m_table));
query.bindValue(":FS", devId);
if (!query.exec())
MythDB::DBError(DBLOC, query);
}
}
/*!
\brief Adds new image to database, optionally checking for existing filepath
\param im Image to add
\param checkForDuplicate If true, the image will not be added if its filepath
already exists in Db.
\return int Id of new image or the existing image with same filepath
*/
template <class FS>
int ImageDb<FS>::InsertDbImage(ImageItemK &im, bool checkForDuplicate) const
{
MSqlQuery query(MSqlQuery::InitCon());
if (checkForDuplicate)
{
query.prepare(QString("SELECT file_id FROM %1 WHERE filename = :NAME;")
.arg(m_table));
query.bindValue(":NAME", im.m_filePath);
if (!query.exec())
{
MythDB::DBError(DBLOC, query);
return -1;
}
if (query.size() > 0)
{
LOG(VB_FILE, LOG_DEBUG, QString("Image: %1 already exists in Db")
.arg(im.m_filePath));
return query.value(0).toInt();
}
}
query.prepare(QString("INSERT INTO %1 (" DB_COLUMNS ") VALUES (0, "
":FILEPATH, :NAME, :PARENT, :TYPE, :MODTIME, "
":SIZE, :EXTENSION, :DATE, :HIDDEN, :ORIENT, "
":COVER, :COMMENT, :FS);").arg(m_table));
query.bindValue(":FILEPATH", im.m_filePath);
query.bindValue(":NAME", FS::BaseNameOf(im.m_filePath));
query.bindValue(":FS", im.m_device);
query.bindValue(":PARENT", FS::DbId(im.m_parentId));
query.bindValue(":TYPE", im.m_type);
query.bindValue(":MODTIME", im.m_modTime);
query.bindValue(":SIZE", im.m_size);
query.bindValue(":EXTENSION", im.m_extension);
query.bindValue(":DATE", im.m_date);
query.bindValue(":ORIENT", im.m_orientation);
query.bindValue(":COMMENT", im.m_comment.isNull() ? "" : im.m_comment);
query.bindValue(":HIDDEN", im.m_isHidden);
query.bindValue(":COVER", FS::DbId(im.m_userThumbnail));
if (query.exec())
return FS::ImageId(query.lastInsertId().toInt());
MythDB::DBError(DBLOC, query);
return -1;
}
/*!
* \brief Updates or creates database image or dir
* \details Item does not need to pre-exist
* \param im Image or dir
*/
template <class FS>
bool ImageDb<FS>::UpdateDbImage(ImageItemK &im) const
{
MSqlQuery query(MSqlQuery::InitCon());
query.prepare(QString
("UPDATE %1 SET "
"filename = :FILEPATH, name = :NAME, "
"dir_id = :PARENT, type = :TYPE, "
"modtime = :MODTIME, size = :SIZE, "
"extension = :EXTENSION, date = :DATE, zoom = :FS, "
"hidden = :HIDDEN, orientation = :ORIENT, "
"angle = :COVER, path = :COMMENT "
"WHERE file_id = :ID;").arg(m_table));
query.bindValue(":ID", FS::DbId(im.m_id));
query.bindValue(":FILEPATH", im.m_filePath);
query.bindValue(":NAME", FS::BaseNameOf(im.m_filePath));
query.bindValue(":PARENT", FS::DbId(im.m_parentId));
query.bindValue(":TYPE", im.m_type);
query.bindValue(":MODTIME", im.m_modTime);
query.bindValue(":SIZE", im.m_size);
query.bindValue(":EXTENSION", im.m_extension);
query.bindValue(":DATE", im.m_date);
query.bindValue(":FS", im.m_device);
query.bindValue(":HIDDEN", im.m_isHidden);
query.bindValue(":ORIENT", im.m_orientation);
query.bindValue(":COVER", FS::DbId(im.m_userThumbnail));
query.bindValue(":COMMENT", im.m_comment.isNull() ? "" : im.m_comment);
if (query.exec())
return true;
MythDB::DBError(DBLOC, query);
return false;
}
/*!
* \brief Remove images/dirs from database
* \details Item does not need to exist in db
* \param imList List of items to delete
* \return QStringList List of ids that were successfully removed
*/
template <class FS>
QStringList ImageDb<FS>::RemoveFromDB(const ImageList &imList) const
{
QStringList ids;
if (!imList.isEmpty())
{
for (const auto& im : qAsConst(imList))
ids << QString::number(FS::DbId(im->m_id));
QString idents = ids.join(",");
MSqlQuery query(MSqlQuery::InitCon());
query.prepare(QString("DELETE IGNORE FROM %1 WHERE file_id IN (%2);")
.arg(m_table, idents));
if (!query.exec())
{
MythDB::DBError(DBLOC, query);
return QStringList();
}
}
return ids;
}
/*!
* \brief Sets hidden status of an image/dir in database
* \param hide True = hidden, False = unhidden
* \param ids List of item ids
* \return bool False if db update failed
*/
template <class FS>
bool ImageDb<FS>::SetHidden(bool hide, QString ids) const
{
if (ids.isEmpty())
return false;
MSqlQuery query(MSqlQuery::InitCon());
query.prepare(QString("UPDATE %1 SET "
"hidden = :HIDDEN "
"WHERE file_id IN (%2);").arg(m_table, FS::DbIds(ids)));
query.bindValue(":HIDDEN", hide ? 1 : 0);
if (query.exec())
return true;
MythDB::DBError(DBLOC, query);
return false;
}
/*!
* \brief Set the thumbnail(s) to be used for a dir
* \param dir Dir id
* \param id Image id to use as cover/thumbnail
*/
template <class FS>
bool ImageDb<FS>::SetCover(int dir, int id) const
{
MSqlQuery query(MSqlQuery::InitCon());
query.prepare(QString("UPDATE %1 SET "
"angle = :COVER "
"WHERE file_id = :DIR").arg(m_table));
query.bindValue(":COVER", FS::DbId(id));
query.bindValue(":DIR", FS::DbId(dir));
\
if (query.exec())
return true;
MythDB::DBError(DBLOC, query);
return false;
}
/*!
\brief Sets image orientation in Db
\param id Image id
\param orientation Exif orientation code
*/
template <class FS>
bool ImageDb<FS>::SetOrientation(int id, int orientation) const
{
MSqlQuery query(MSqlQuery::InitCon());
query.prepare(QString("UPDATE %1 SET ").arg(m_table) +
"orientation = :ORIENTATION "
"WHERE file_id = :ID");
query.bindValue(":ORIENTATION", orientation);
query.bindValue(":ID", FS::DbId(id));
\
if (query.exec())
return true;
MythDB::DBError(DBLOC, query);
return false;
}
/*!
\brief Read selected database images/dirs
\param[out] dirs List of the dirs
\param[out] files List of the files
\param selector SQL clause specifying selection and ordering of images
\return int Number of items retreved