MythTV  master
imagemanager.cpp
Go to the documentation of this file.
1 #include "imagemanager.h"
2 
3 #include <QImageReader>
4 #include <QRunnable>
5 #include <utility>
6 
7 #include "dbaccess.h" // for FileAssociations
8 #include "mthreadpool.h"
9 #include "mythdate.h"
10 #include "mythmediamonitor.h"
11 
12 
13 #define LOC QString("ImageManager: ")
14 #define DBLOC QString("ImageDb(%1): ").arg(m_table)
15 
16 // Must be empty as it's prepended to path
17 #define STORAGE_GROUP_MOUNT ""
18 
19 #define DB_TABLE "gallery_files"
20 
21 #define RESULT_ERR(ERR, MESG) \
22 { LOG(VB_GENERAL, LOG_ERR, LOC + (MESG)); \
23  return QStringList("ERROR") << (ERR); }
24 
25 #define RESULT_OK(MESG) \
26 { LOG(VB_FILE, LOG_DEBUG, LOC + (MESG)); \
27  return QStringList("OK"); }
28 
29 #define IMPORTDIR "Import"
30 
31 
33 class Device
34 {
35 public:
36  Device(QString name, QString mount,
37  MythMediaDevice *media = nullptr, QTemporaryDir *import = nullptr)
38  : m_present(true), m_name(std::move(name)), m_mount(std::move(mount)),
39  m_media(media), m_dir(import)
40  {
41  // Path relative to TEMP storage group
42  m_thumbs = QString("%1/%2").arg(THUMBNAIL_SUBDIR, m_name);
43  }
44 
45 
48  {
49  Close();
50 
51  // Remove imported images
52  delete m_dir;
53 
54  // Clean up non-SG thumbnails
56  RemoveThumbs();
57  }
58 
59 
61  void Close(bool eject = false)
62  {
63  // Imports remain present; others do not
64  m_present = isImport();
65 
66  // Release device
67  if (m_media)
68  {
69  if (eject)
70  {
71  LOG(VB_GENERAL, LOG_INFO, LOC + QString("Ejecting '%1' at '%2'")
72  .arg(m_name, m_mount));
74  }
75  else
76  LOG(VB_MEDIA, LOG_DEBUG, LOC + QString("Unlocked '%1'").arg(m_name));
77 
79  m_media = nullptr;
80  }
81  }
82 
83 
88  static void RemoveDirContents(const QString& path)
89  {
90  QDir(path).removeRecursively();
91  }
92 
93 
95  void RemoveThumbs(void) const
96  {
97  // Remove thumbnails
98  QString dir = QString("%1/" TEMP_SUBDIR "/%2").arg(GetConfDir(), m_thumbs);
99  LOG(VB_FILE, LOG_INFO, LOC + QString("Removing thumbnails in %1").arg(dir));
101  QDir::root().rmpath(dir);
102  }
103 
104 
105  bool isImport() const { return m_dir; }
106  bool isPresent() const { return m_present; }
107  void setPresent(MythMediaDevice *media) { m_present = true; m_media = media; }
108 
110  bool m_present;
111  QString m_name;
112  QString m_mount;
113  QString m_thumbs;
115  QTemporaryDir *m_dir;
116 };
117 
118 
119 static Device kNullDevice = Device("Unknown Device", "<Invalid Path>");
120 
121 
123 {
124  qDeleteAll(m_devices);
125 }
126 
127 
129 QString DeviceManager::DeviceMount(int devId) const
130 {
131  return m_devices.value(devId, &kNullDevice)->m_mount;
132 }
133 
134 
136 QString DeviceManager::DeviceName(int devId) const
137 {
138  return m_devices.value(devId, &kNullDevice)->m_name;
139 }
140 
141 
142 QString DeviceManager::ThumbDir(int fs) const
143 {
144  return m_devices.value(fs, &kNullDevice)->m_thumbs;
145 }
146 
147 
157 int DeviceManager::OpenDevice(const QString &name, const QString &mount,
158  MythMediaDevice *media, QTemporaryDir *dir)
159 {
160  // Handle devices reappearing at same mountpoint.
161  // If a USB is unplugged whilst in use (without unmounting) we get no event
162  // but we do when it's re-inserted
163  QString state("Known");
164  int id = LocateMount(mount);
165 
166  if (id == DEVICE_INVALID)
167  {
168  state = "New";
169  id = m_devices.isEmpty() ? 0 : (m_devices.constEnd() - 1).key() + 1;
170  m_devices.insert(id, new Device(name, mount, media, dir));
171  }
172  else if (m_devices.value(id))
173  m_devices.value(id)->setPresent(media);
174 
175  LOG(VB_GENERAL, LOG_INFO, LOC +
176  QString("%1 device %2 mounted at '%3' [Id %4]")
177  .arg(state, name, mount).arg(id));
178 
179  return id;
180 }
181 
182 
189 QStringList DeviceManager::CloseDevices(int devId, const QString &action)
190 {
191  QStringList clear;
192 
193  if (action == "DEVICE CLOSE ALL")
194  {
195  // Close all devices but retain their thumbnails
196  for (auto *dev : qAsConst(m_devices))
197  if (dev)
198  dev->Close();
199  }
200  else if (action == "DEVICE CLEAR ALL")
201  {
202  // Remove all thumbnails but retain devices
203  for (const auto *dev : qAsConst(m_devices)) {
204  if (dev)
205  {
206  clear << dev->m_mount;
207  dev->RemoveThumbs();
208  }
209  }
210  }
211  else
212  {
213  // Remove single device & its thumbnails, optionally ejecting it
214  Device *dev = m_devices.take(devId);
215  if (dev)
216  {
217  if (action == "DEVICE EJECT")
218  dev->Close(true);
219  clear << dev->m_mount;
220  delete dev;
221  }
222  }
223  return clear;
224 }
225 
226 
232 int DeviceManager::LocateMount(const QString &mount) const
233 {
234  DeviceMap::const_iterator it = m_devices.constBegin();
235  while (it != m_devices.constEnd())
236  {
237  if (it.value()->m_mount == mount)
238  return it.key();
239  ++it;
240  }
241  return DEVICE_INVALID;
242 }
243 
244 
247 {
249  for (int id : m_devices.keys())
250  {
251  Device *dev = m_devices.value(id);
252  if (dev)
253  paths.insert(id, dev->m_mount);
254  }
255  return paths;
256 }
257 
258 
261 {
262  QList<int> absent;
263  for (int id : m_devices.keys())
264  {
265  Device *dev = m_devices.value(id);
266  if (dev && !dev->isPresent())
267  absent << id;
268  }
269  return absent;
270 }
271 
272 
277  m_imageFileExt(SupportedImages()),
278  m_videoFileExt(SupportedVideos())
279 {
280  // Generate glob list from supported extensions
281  QStringList glob;
282  for (const auto& ext : (m_imageFileExt + m_videoFileExt))
283  glob << "*." + ext;
284 
285  // Apply filters to only detect image files
286  m_dirFilter.setNameFilters(glob);
287  m_dirFilter.setFilter(QDir::AllDirs | QDir::Files | QDir::Readable |
288  QDir::NoDotAndDotDot | QDir::NoSymLinks);
289 
290  // Sync files before dirs to improve thumb generation response
291  // Order by time (oldest first) - this determines the order thumbs appear
292  m_dirFilter.setSorting(QDir::DirsLast | QDir::Time | QDir::Reversed);
293 }
294 
300 {
301  // Determine supported picture formats from Qt
302  QStringList formats;
303  for (const auto& ext : QImageReader::supportedImageFormats())
304  formats << QString(ext);
305  return formats;
306 }
307 
308 
314 {
315  // Determine supported video formats from MythVideo
316  QStringList formats;
319  for (const auto & fa : faList)
320  {
321  if (!fa.use_default && fa.playcommand == "Internal")
322  formats << QString(fa.extension);
323  }
324  return formats;
325 }
326 
327 
336 ImageItem *ImageAdapterLocal::CreateItem(const QFileInfo &fi, int parentId,
337  int devId, const QString & /*base*/) const
338 {
339  auto *im = new ImageItem();
340 
341  im->m_parentId = parentId;
342  im->m_device = devId;
343  im->m_filePath = fi.absoluteFilePath();
344 
345  if (parentId == GALLERY_DB_ID)
346  {
347  // Import devices show time of import, other devices show 'last scan time'
348 #if QT_VERSION < QT_VERSION_CHECK(5,8,0)
349  im->m_date = im->m_filePath.contains(IMPORTDIR)
350  ? fi.lastModified().toTime_t()
351  : QDateTime::currentMSecsSinceEpoch() / 1000;
352 #else
353  im->m_date = im->m_filePath.contains(IMPORTDIR)
354  ? fi.lastModified().toSecsSinceEpoch()
355  : QDateTime::currentSecsSinceEpoch();
356 #endif
357  im->m_modTime = im->m_date;
358  im->m_type = kDevice;
359  return im;
360  }
361 
362 #if QT_VERSION < QT_VERSION_CHECK(5,8,0)
363  im->m_modTime = fi.lastModified().toTime_t();
364 #else
365  im->m_modTime = fi.lastModified().toSecsSinceEpoch();
366 #endif
367 
368  if (fi.isDir())
369  {
370  im->m_type = kDirectory;
371  return im;
372  }
373 
374  im->m_extension = fi.suffix().toLower();
375  im->m_type = GetImageType(im->m_extension);
376 
377  if (im->m_type == kUnknown)
378  {
379  delete im;
380  return nullptr;
381  }
382 
383  im->m_thumbPath = GetAbsThumbPath(ThumbDir(im->m_device), ThumbPath(*im));
384  im->m_size = fi.size();
385 
386  return im;
387 }
388 
389 
395 void ImageAdapterLocal::Notify(const QString &mesg,
396  const QStringList &extra)
397 {
398  QString host(gCoreContext->GetHostName());
399  gCoreContext->SendEvent(MythEvent(QString("%1 %2").arg(mesg, host), extra));
400 }
401 
402 
411 ImageItem *ImageAdapterSg::CreateItem(const QFileInfo &fi, int parentId,
412  int /*devId*/, const QString &base) const
413 {
414  auto *im = new ImageItem();
415 
416  im->m_device = 0;
417  im->m_parentId = parentId;
418 
419  if (parentId == GALLERY_DB_ID)
420  {
421  // All SG dirs map to a single Db dir
422  im->m_filePath = "";
423  im->m_type = kDevice;
424  im->m_date = QDateTime::currentMSecsSinceEpoch() / 1000;
425  im->m_modTime = im->m_date;
426  return im;
427  }
428 
429  // Strip SG path & leading / to leave a relative path
430  im->m_filePath = fi.absoluteFilePath().mid(base.size() + 1);
431 #if QT_VERSION < QT_VERSION_CHECK(5,8,0)
432  im->m_modTime = fi.lastModified().toTime_t();
433 #else
434  im->m_modTime = fi.lastModified().toSecsSinceEpoch();
435 #endif
436 
437  if (fi.isDir())
438  {
439  im->m_type = kDirectory;
440  return im;
441  }
442 
443  im->m_extension = fi.suffix().toLower();
444  im->m_type = GetImageType(im->m_extension);
445 
446  if (im->m_type == kUnknown)
447  {
448  delete im;
449  return nullptr;
450  }
451 
452  im->m_thumbPath = GetAbsThumbPath(ThumbDir(im->m_device), ThumbPath(*im));
453  im->m_size = fi.size();
454 
455  return im;
456 }
457 
458 
464 void ImageAdapterSg::Notify(const QString &mesg,
465  const QStringList &extra)
466 {
467  gCoreContext->SendEvent(MythEvent(mesg, extra));
468 }
469 
470 
476 {
477  StringMap map;
478  int i = 0;
479  for (const auto& path : m_sg.GetDirList())
480  map.insert(i++, path);
481  return map;
482 }
483 
484 
492 {
493  if (im->IsDevice())
494  return m_sg.FindNextDirMostFree();
495  return im->m_filePath.startsWith("/") ? im->m_filePath
496  : m_sg.FindFile(im->m_filePath);
497 }
498 
499 
500 // Database fields used by several image queries
501 #define DB_COLUMNS \
502 "file_id, filename, name, dir_id, type, modtime, size, " \
503 "extension, date, hidden, orientation, angle, path, zoom"
504 // Id, filepath, basename, parentId, type, modtime, size,
505 // extension, image date, hidden, orientation, cover id, comment, device id
506 
507 
513 template <class FS>
515 {
516  auto *im = new ImageItem(FS::ImageId(query.value(0).toInt()));
517 
518  // Ordered as per DB_COLUMNS
519  im->m_filePath = query.value(1).toString();
520  im->m_baseName = query.value(2).toString();
521  im->m_parentId = FS::ImageId(query.value(3).toInt());
522  im->m_type = query.value(4).toInt();
523  im->m_modTime = query.value(5).toInt();
524  im->m_size = query.value(6).toInt();
525  im->m_extension = query.value(7).toString();
526  im->m_date = query.value(8).toUInt();
527  im->m_isHidden = query.value(9).toBool();
528  im->m_orientation = query.value(10).toInt();
529  im->m_userThumbnail = FS::ImageId(query.value(11).toInt());
530  im->m_comment = query.value(12).toString();
531  im->m_device = query.value(13).toInt();
532  im->m_url = FS::MakeFileUrl(im->m_filePath);
533 
534  if (im->IsFile())
535  {
536  // Only pics/vids have thumbs
537  QString thumbPath(FS::ThumbPath(*im));
538  QString devPath(FS::ThumbDir(im->m_device));
539  QString url(FS::MakeThumbUrl(devPath, thumbPath));
540 
541  im->m_thumbPath = FS::GetAbsThumbPath(devPath, thumbPath);
542  im->m_thumbNails.append(qMakePair(im->m_id, url));
543  }
544  return im;
545 }
546 
547 
556 template <class FS>
557 int ImageDb<FS>::GetImages(const QString &ids, ImageList &files, ImageList &dirs,
558  const QString &refine) const
559 {
560  if (ids.isEmpty())
561  return 0;
562 
563  QString select = QString("file_id IN (%1) %2").arg(FS::DbIds(ids), refine);
564  return ReadImages(dirs, files, select);
565 }
566 
567 
576 template <class FS>
577 int ImageDb<FS>::GetChildren(QString ids, ImageList &files, ImageList &dirs,
578  const QString &refine) const
579 {
580  QString select = QString("dir_id IN (%1) %2").arg(FS::DbIds(ids), refine);
581  return ReadImages(dirs, files, select);
582 }
583 
584 
594 template <class FS>
596  ImageList &files, ImageList &dirs,
597  const QString &refine) const
598 {
600  query.prepare(QString("SELECT " DB_COLUMNS " FROM %1 "
601  "WHERE (dir_id = :ID1 OR file_id = :ID2) "
602  "%2;").arg(m_table, refine));
603 
604  // Qt < 5.4 won't bind multiple occurrences
605  int dbId = FS::DbId(id);
606  query.bindValue(":ID1", dbId);
607  query.bindValue(":ID2", dbId);
608 
609  if (!query.exec())
610  {
612  return -1;
613  }
614  while (query.next())
615  {
616  ImagePtr im(CreateImage(query));
617 
618  if (im->IsFile())
619  files.append(im);
620  else if (im->m_id == id)
621  parent = im;
622  else
623  dirs.append(im);
624  }
625  return query.size();
626 }
627 
628 
636 template <class FS>
637 bool ImageDb<FS>::GetDescendants(const QString &ids,
638  ImageList &files, ImageList &dirs) const
639 {
640  if (ids.isEmpty())
641  return false;
642 
643  if (ReadImages(dirs, files, QString("file_id IN (%1)").arg(FS::DbIds(ids))) < 0)
644  return false;
645 
647  QString sql =
648  QString("SELECT " DB_COLUMNS
649  ", LENGTH(filename) - LENGTH(REPLACE(filename, '/', ''))"
650  " AS depth "
651  "FROM %1 WHERE filename LIKE :PREFIX "
652  "ORDER BY depth;").arg(m_table);
653 
654  for (const auto& im1 : qAsConst(dirs))
655  {
656  query.prepare(sql);
657  query.bindValue(":PREFIX", im1->m_filePath + "/%");
658 
659  if (!query.exec())
660  {
662  return false;
663  }
664 
665  while (query.next())
666  {
667  ImagePtr im2(CreateImage(query));
668  if (im2->IsDirectory())
669  dirs.append(im2);
670  else
671  files.append(im2);
672  }
673  }
674  return true;
675 }
676 
677 
685 template <class FS>
686 bool ImageDb<FS>::GetImageTree(int id, ImageList &files, const QString &refine) const
687 {
688  // Load starting children
689  ImageList dirs;
690  if (GetChildren(QString::number(id), files, dirs, refine) < 0)
691  return false;
692 
693  for (const auto& im : qAsConst(dirs))
694  if (!GetImageTree(im->m_id, files, refine))
695  return false;
696  return true;
697 }
698 
699 
705 template <class FS>
707 {
709  query.prepare(QString("SELECT " DB_COLUMNS " FROM %1").arg(m_table));
710 
711  if (!query.exec())
712  {
714  return false;
715  }
716 
717  while (query.next())
718  {
719  ImagePtr im(CreateImage(query));
720  if (im->IsDirectory())
721  dirs.insert(im->m_filePath, im);
722  else
723  files.insert(im->m_filePath, im);
724  }
725  return true;
726 }
727 
728 
736 template <class FS>
737 void ImageDb<FS>::ClearDb(int devId, const QString &action)
738 {
739  if (action == "DEVICE CLOSE ALL")
740  // Retain Db images when closing UI
741  return;
742 
744 
745  if (action == "DEVICE CLEAR ALL")
746  {
747  // Clear images from all devices. Reset auto-increment
748  query.prepare(QString("TRUNCATE TABLE %1;").arg(m_table));
749 
750  if (!query.exec())
752  }
753  else // Actions DEVICE REMOVE & DEVICE EJECT
754  {
755  // Delete all images of the device
756  query.prepare(QString("DELETE IGNORE FROM %1 WHERE zoom = :FS;").arg(m_table));
757  query.bindValue(":FS", devId);
758 
759  if (!query.exec())
761  }
762 }
763 
764 
772 template <class FS>
773 int ImageDb<FS>::InsertDbImage(ImageItemK &im, bool checkForDuplicate) const
774 {
776 
777  if (checkForDuplicate)
778  {
779  query.prepare(QString("SELECT file_id FROM %1 WHERE filename = :NAME;")
780  .arg(m_table));
781 
782  query.bindValue(":NAME", im.m_filePath);
783 
784  if (!query.exec())
785  {
787  return -1;
788  }
789 
790  if (query.size() > 0)
791  {
792  LOG(VB_FILE, LOG_DEBUG, QString("Image: %1 already exists in Db")
793  .arg(im.m_filePath));
794  return query.value(0).toInt();
795  }
796  }
797 
798  query.prepare(QString("INSERT INTO %1 (" DB_COLUMNS ") VALUES (0, "
799  ":FILEPATH, :NAME, :PARENT, :TYPE, :MODTIME, "
800  ":SIZE, :EXTENSION, :DATE, :HIDDEN, :ORIENT, "
801  ":COVER, :COMMENT, :FS);").arg(m_table));
802 
803  query.bindValue(":FILEPATH", im.m_filePath);
804  query.bindValue(":NAME", FS::BaseNameOf(im.m_filePath));
805  query.bindValue(":FS", im.m_device);
806  query.bindValue(":PARENT", FS::DbId(im.m_parentId));
807  query.bindValue(":TYPE", im.m_type);
808  query.bindValue(":MODTIME", im.m_modTime);
809  query.bindValue(":SIZE", im.m_size);
810  query.bindValue(":EXTENSION", im.m_extension);
811  query.bindValue(":DATE", im.m_date);
812  query.bindValue(":ORIENT", im.m_orientation);
813  query.bindValue(":COMMENT", im.m_comment.isNull() ? "" : im.m_comment);
814  query.bindValue(":HIDDEN", im.m_isHidden);
815  query.bindValue(":COVER", FS::DbId(im.m_userThumbnail));
816 
817  if (query.exec())
818  return FS::ImageId(query.lastInsertId().toInt());
819 
821  return -1;
822 }
823 
824 
830 template <class FS>
832 {
834  query.prepare(QString
835  ("UPDATE %1 SET "
836  "filename = :FILEPATH, name = :NAME, "
837  "dir_id = :PARENT, type = :TYPE, "
838  "modtime = :MODTIME, size = :SIZE, "
839  "extension = :EXTENSION, date = :DATE, zoom = :FS, "
840  "hidden = :HIDDEN, orientation = :ORIENT, "
841  "angle = :COVER, path = :COMMENT "
842  "WHERE file_id = :ID;").arg(m_table));
843 
844  query.bindValue(":ID", FS::DbId(im.m_id));
845  query.bindValue(":FILEPATH", im.m_filePath);
846  query.bindValue(":NAME", FS::BaseNameOf(im.m_filePath));
847  query.bindValue(":PARENT", FS::DbId(im.m_parentId));
848  query.bindValue(":TYPE", im.m_type);
849  query.bindValue(":MODTIME", im.m_modTime);
850  query.bindValue(":SIZE", im.m_size);
851  query.bindValue(":EXTENSION", im.m_extension);
852  query.bindValue(":DATE", im.m_date);
853  query.bindValue(":FS", im.m_device);
854  query.bindValue(":HIDDEN", im.m_isHidden);
855  query.bindValue(":ORIENT", im.m_orientation);
856  query.bindValue(":COVER", FS::DbId(im.m_userThumbnail));
857  query.bindValue(":COMMENT", im.m_comment.isNull() ? "" : im.m_comment);
858 
859  if (query.exec())
860  return true;
861 
863  return false;
864 }
865 
866 
873 template <class FS>
874 QStringList ImageDb<FS>::RemoveFromDB(const ImageList &imList) const
875 {
876  QStringList ids;
877  if (!imList.isEmpty())
878  {
879  for (const auto& im : qAsConst(imList))
880  ids << QString::number(FS::DbId(im->m_id));
881 
882  QString idents = ids.join(",");
884  query.prepare(QString("DELETE IGNORE FROM %1 WHERE file_id IN (%2);")
885  .arg(m_table, idents));
886 
887  if (!query.exec())
888  {
890  return QStringList();
891  }
892  }
893  return ids;
894 }
895 
896 
903 template <class FS>
904 bool ImageDb<FS>::SetHidden(bool hide, QString ids) const
905 {
906  if (ids.isEmpty())
907  return false;
908 
910 
911  query.prepare(QString("UPDATE %1 SET "
912  "hidden = :HIDDEN "
913  "WHERE file_id IN (%2);").arg(m_table, FS::DbIds(ids)));
914  query.bindValue(":HIDDEN", hide ? 1 : 0);
915 
916  if (query.exec())
917  return true;
918 
920  return false;
921 }
922 
923 
929 template <class FS>
930 bool ImageDb<FS>::SetCover(int dir, int id) const
931 {
933 
934  query.prepare(QString("UPDATE %1 SET "
935  "angle = :COVER "
936  "WHERE file_id = :DIR").arg(m_table));
937  query.bindValue(":COVER", FS::DbId(id));
938  query.bindValue(":DIR", FS::DbId(dir));
939  \
940  if (query.exec())
941  return true;
942 
944  return false;
945 }
946 
947 
953 template <class FS>
954 bool ImageDb<FS>::SetOrientation(int id, int orientation) const
955 {
957 
958  query.prepare(QString("UPDATE %1 SET ").arg(m_table) +
959  "orientation = :ORIENTATION "
960  "WHERE file_id = :ID");
961  query.bindValue(":ORIENTATION", orientation);
962  query.bindValue(":ID", FS::DbId(id));
963  \
964  if (query.exec())
965  return true;
966 
968  return false;
969 }
970 
971 
979 template <class FS>
981  const QString &selector) const
982 {
984  query.prepare(QString("SELECT " DB_COLUMNS " FROM %1 WHERE %2")
985  .arg(m_table, selector));
986  if (!query.exec())
987  {
989  return -1;
990  }
991 
992  while (query.next())
993  {
994  ImagePtr im(CreateImage(query));
995 
996  if (im->IsFile())
997  files.append(im);
998  else
999  dirs.append(im);
1000  }
1001  return query.size();
1002 }
1003 
1004 
1014 template <class FS>
1015 void ImageDb<FS>::GetDescendantCount(int id, bool all, int &dirs,
1016  int &pics, int &videos, int &sizeKb) const
1017 {
1018  QString whereClause;
1019  if (!all)
1020  {
1021  whereClause = "WHERE filename LIKE "
1022  "( SELECT CONCAT(filename, '/%') "
1023  " FROM %2 WHERE file_id = :ID);";
1024  }
1025 
1027  query.prepare(QString("SELECT SUM(type <= :FLDR) AS Fldr, "
1028  " SUM(type = :PIC) AS Pics, "
1029  " SUM(type = :VID) AS Vids, "
1030  " SUM(size / 1024) "
1031  "FROM %2 %1;").arg(whereClause).arg(m_table));
1032 
1033  query.bindValue(":FLDR", kDirectory);
1034  query.bindValue(":PIC", kImageFile);
1035  query.bindValue(":VID", kVideoFile);
1036  if (!all)
1037  query.bindValue(":ID", FS::DbId(id));
1038 
1039  if (!query.exec())
1040  {
1042  }
1043  else if (query.next())
1044  {
1045  dirs += query.value(0).toInt();
1046  pics += query.value(1).toInt();
1047  videos += query.value(2).toInt();
1048  sizeKb += query.value(3).toInt();
1049  }
1050 }
1051 
1052 
1057 {
1058  // Be has a single SG device
1060 }
1061 
1062 
1067  : ImageDb(QString("`%1_%2`").arg(DB_TABLE, gCoreContext->GetHostName()))
1068 {
1069  // Remove any table leftover from a previous FE crash
1070  DropTable();
1071 }
1072 
1073 
1078 {
1080  query.prepare(QString("DROP TABLE IF EXISTS %1;").arg(m_table));
1081  if (query.exec())
1082  m_DbExists = false;
1083  else
1085 }
1086 
1087 
1092 {
1093  if (m_DbExists)
1094  return true;
1095 
1097 
1098  // Create temporary table
1099  query.prepare(QString("CREATE TABLE %1 LIKE " DB_TABLE ";").arg(m_table));
1100  if (query.exec())
1101  {
1102  // Store it in memory only
1103  query.prepare(QString("ALTER TABLE %1 ENGINE = MEMORY;").arg(m_table));
1104  if (query.exec())
1105  {
1106  m_DbExists = true;
1107  LOG(VB_FILE, LOG_DEBUG, QString("Created Db table %1").arg(m_table));
1108  return true;
1109  }
1110  }
1112 
1113  // Clean up after failure
1114  query.prepare(QString("DROP TABLE IF EXISTS %1;").arg(m_table));
1115  query.exec();
1116  return false;
1117 }
1118 
1119 
1123 class ReadMetaThread : public QRunnable
1124 {
1125 public:
1126  ReadMetaThread(ImagePtrK im, QString path)
1127  : m_im(std::move(im)), m_path(std::move(path)) {}
1128 
1129  void run() override // QRunnable
1130  {
1131  QStringList tags;
1132  QString orientation;
1133  QString size;
1134 
1135  // Read metadata for files only
1136  if (m_im->IsFile())
1137  {
1138  ImageMetaData *metadata = (m_im->m_type == kVideoFile)
1141  tags = metadata->GetAllTags();
1142  orientation = Orientation(m_im->m_orientation).Description();
1143  size = ImageAdapterBase::FormatSize(m_im->m_size / 1024);
1144  delete metadata;
1145  }
1146 
1147  // Add identifier at front
1148  tags.prepend(QString::number(m_im->m_id));
1149 
1150  // Include file info
1151  tags << ImageMetaData::ToString(EXIF_MYTH_HOST, "Host",
1153  tags << ImageMetaData::ToString(EXIF_MYTH_PATH, "Path",
1155  tags << ImageMetaData::ToString(EXIF_MYTH_NAME, "Name",
1157  tags << ImageMetaData::ToString(EXIF_MYTH_SIZE, "Size", size);
1158  tags << ImageMetaData::ToString(EXIF_MYTH_ORIENT, "Orientation",
1159  orientation);
1160 
1161  MythEvent me("IMAGE_METADATA", tags);
1162  gCoreContext->SendEvent(me);
1163  }
1164 
1165 private:
1167  QString m_path;
1168 };
1169 
1170 
1179 template <class DBFS>
1180 QStringList ImageHandler<DBFS>::HandleGetMetadata(const QString &id) const
1181 {
1182  // Find image in DB
1183  ImageList files;
1184  ImageList dirs;
1185  if (DBFS::GetImages(id, files, dirs) != 1)
1186  RESULT_ERR("Image not found", QString("Unknown image %1").arg(id))
1187 
1188  ImagePtr im = files.isEmpty() ? dirs[0] : files[0];
1189 
1190  QString absPath = DBFS::GetAbsFilePath(im);
1191  if (absPath.isEmpty())
1192  RESULT_ERR("Image not found",
1193  QString("File %1 not found").arg(im->m_filePath))
1194 
1195  auto *worker = new ReadMetaThread(im, absPath);
1196 
1197  MThreadPool::globalInstance()->start(worker, "ImageMetaData");
1198 
1199  RESULT_OK(QString("Fetching metadata for %1").arg(id))
1200 }
1201 
1202 
1210 template <class DBFS>
1211 QStringList ImageHandler<DBFS>::HandleRename(const QString &id,
1212  const QString &newBase) const
1213 {
1214  // Sanity check new name
1215  if (newBase.isEmpty() || newBase.contains("/") || newBase.contains("\\"))
1216  RESULT_ERR("Invalid name", QString("Invalid name %1").arg(newBase))
1217 
1218  // Find image in DB
1219  ImageList files;
1220  ImageList dirs;
1221  if (DBFS::GetImages(id, files, dirs) != 1)
1222  RESULT_ERR("Image not found", QString("Image %1 not in Db").arg(id))
1223 
1224  ImagePtr im = files.isEmpty() ? dirs[0] : files[0];
1225 
1226  // Find file
1227  QString oldPath = DBFS::GetAbsFilePath(im);
1228  if (oldPath.isEmpty())
1229  RESULT_ERR("Image not found",
1230  QString("File %1 not found").arg(im->m_filePath))
1231 
1232  // Generate new filename
1233  QFileInfo oldFi = QFileInfo(oldPath);
1234  QString newName = im->IsDirectory()
1235  ? newBase : QString("%1.%2").arg(newBase, oldFi.suffix());
1236 
1237  im->m_filePath = DBFS::ConstructPath(DBFS::PathOf(im->m_filePath), newName);
1238 
1239  // Ensure no SG duplicate files are created. (Creating clone dirs is ok)
1240  if (im->IsFile())
1241  {
1242  QString existPath = DBFS::GetAbsFilePath(im);
1243  if (!existPath.isEmpty())
1244  RESULT_ERR("Filename already used",
1245  QString("Renaming %1 to %2 will create a duplicate of %3")
1246  .arg(oldPath, im->m_filePath, existPath))
1247  }
1248 
1249  // Rename file or directory
1250  QString newPath = oldFi.dir().absoluteFilePath(newName);
1251  if (!QFile::rename(oldPath, newPath))
1252  RESULT_ERR("Rename failed",
1253  QString("Rename of %1 -> %2 failed").arg(oldPath, newPath))
1254 
1255  if (im->IsDirectory())
1256  {
1257  // Dir name change affects path of all sub-dirs & files and their thumbs
1258  HandleScanRequest("START");
1259  }
1260  else // file
1261  {
1262  // Update db
1263  DBFS::UpdateDbImage(*im);
1264 
1265  // Image is modified, not deleted
1266  QStringList mesg("");
1267  mesg << QString::number(im->m_id);
1268 
1269  // Rename thumbnail.
1270  m_thumbGen->MoveThumbnail(im);
1271 
1272  // Notify clients of changed image
1273  DBFS::Notify("IMAGE_DB_CHANGED", mesg);
1274  }
1275  RESULT_OK(QString("Renamed %1 -> %2").arg(oldPath, newPath))
1276 }
1277 
1278 
1286 template <class DBFS>
1287 QStringList ImageHandler<DBFS>::HandleDelete(const QString &ids) const
1288 {
1289  // Get subtree of all files
1290  ImageList files;
1291  ImageList dirs;
1292  // Dirs will be in depth-first order, (subdirs after parent)
1293  DBFS::GetDescendants(ids, files, dirs);
1294 
1295  // Remove files from filesystem first
1296  RemoveFiles(files);
1297  // ... then dirs, which should now be empty
1298  RemoveFiles(dirs);
1299 
1300  // Fail if nothing deleted
1301  if (files.isEmpty() && dirs.isEmpty())
1302  RESULT_ERR("Delete failed", QString("Delete of %1 failed").arg(ids))
1303 
1304  // Update Db
1305  DBFS::RemoveFromDB(files + dirs);
1306 
1307  // Clean up thumbnails
1308  QStringList mesg(m_thumbGen->DeleteThumbs(files));
1309 
1310  // Notify clients of deleted ids
1311  DBFS::Notify("IMAGE_DB_CHANGED", mesg);
1312 
1313  return QStringList("OK");
1314 }
1315 
1316 
1329 template <class DBFS>
1330 QStringList ImageHandler<DBFS>::HandleDbCreate(QStringList defs) const
1331 {
1332  if (defs.isEmpty())
1333  RESULT_ERR("Copy Failed", "Empty defs")
1334 
1335  // First item is the field seperator
1336  const QString separator = defs.takeFirst();
1337 
1338  // Convert cover ids to their new equivalent. Map<source id, new id>
1339  // Dirs follow their children so new cover ids will be defined before they
1340  // are used
1341  QHash<QString, int> idMap;
1342 
1343  // Create skeleton Db images using copied settings.
1344  // Scanner will update other attributes
1345  ImageItem im;
1346  for (const auto& def : qAsConst(defs))
1347  {
1348  QStringList aDef = def.split(separator);
1349 
1350  // Expects id, type, path, hidden, orientation, cover
1351  if (aDef.size() != 6)
1352  {
1353  // Coding error
1354  LOG(VB_GENERAL, LOG_ERR,
1355  LOC + QString("Bad definition: (%1)").arg(def));
1356  continue;
1357  }
1358 
1359  LOG(VB_FILE, LOG_DEBUG, LOC + QString("Creating %1").arg(aDef.join(",")));
1360 
1361  im.m_type = aDef[1].toInt();
1362  im.m_filePath = aDef[2];
1363  im.m_isHidden = (aDef[3].toInt() != 0);
1364  im.m_orientation = aDef[4].toInt();
1365  im.m_userThumbnail = idMap.value(aDef[5]);
1366 
1367  // Don't insert duplicate filepaths
1368  int newId = DBFS::InsertDbImage(im, true);
1369 
1370  // Record old->new id map in case it's being used as a cover
1371  idMap.insert(aDef[0], newId);
1372  }
1373  HandleScanRequest("START");
1374 
1375  RESULT_OK("Created Db images")
1376 }
1377 
1378 
1388 template <class DBFS>
1389 QStringList ImageHandler<DBFS>::HandleDbMove(const QString &ids,
1390  const QString &srcPath,
1391  QString destPath) const
1392 {
1393  // Sanity check new path
1394  if (destPath.contains(".."))
1395  RESULT_ERR("Invalid path", QString("Invalid path %1").arg(destPath))
1396 
1397  // Get subtrees of renamed files
1398  ImageList images;
1399  ImageList dirs;
1400  ImageList files;
1401  bool ok = DBFS::GetDescendants(ids, files, dirs);
1402  images << dirs << files;
1403 
1404  if (!ok || images.isEmpty())
1405  RESULT_ERR("Image not found", QString("Images %1 not in Db").arg(ids))
1406 
1407  if (!destPath.isEmpty() && !destPath.endsWith(QChar('/')))
1408  destPath.append("/");
1409 
1410  // Update path of images only. Scanner will repair parentId
1411  for (const auto& im : qAsConst(images))
1412  {
1413  QString old = im->m_filePath;
1414 
1415  if (srcPath.isEmpty())
1416  {
1417  // Image in SG root
1418  im->m_filePath.prepend(destPath);
1419  }
1420  else if (im->m_filePath.startsWith(srcPath))
1421  {
1422  // All other images
1423  im->m_filePath.replace(srcPath, destPath);
1424  }
1425  else
1426  {
1427  // Coding error
1428  LOG(VB_GENERAL, LOG_ERR,
1429  LOC + QString("Bad image: (%1 -> %2)").arg(srcPath, destPath));
1430  continue;
1431  }
1432 
1433  LOG(VB_FILE, LOG_DEBUG,
1434  LOC + QString("Db Renaming %1 -> %2").arg(old, im->m_filePath));
1435 
1436  DBFS::UpdateDbImage(*im);
1437 
1438  // Rename thumbnail
1439  if (im->IsFile())
1440  m_thumbGen->MoveThumbnail(im);
1441  }
1442  HandleScanRequest("START");
1443 
1444  RESULT_OK(QString("Moved %1 from %2 -> %3").arg(ids).arg(srcPath, destPath))
1445 }
1446 
1447 
1455 template <class DBFS>
1456 QStringList ImageHandler<DBFS>::HandleHide(bool hide, const QString &ids) const
1457 {
1458  if (!DBFS::SetHidden(hide, ids))
1459  RESULT_ERR("Hide failed", QString("Db hide failed for %1").arg(ids))
1460 
1461  // Send changed ids only (none deleted)
1462  QStringList mesg = QStringList("") << ids;
1463  DBFS::Notify("IMAGE_DB_CHANGED", mesg);
1464 
1465  RESULT_OK(QString("Images %1 now %2hidden").arg(ids, hide ? "" : "un"))
1466 }
1467 
1468 
1477 template <class DBFS>
1478 QStringList ImageHandler<DBFS>::HandleTransform(int transform,
1479  const QString &ids) const
1480 {
1481  if (transform < kResetToExif || transform > kFlipVertical)
1482  RESULT_ERR("Transform failed", QString("Bad transform %1").arg(transform))
1483 
1484  ImageList files;
1485  ImageList dirs;
1486  if (DBFS::GetImages(ids, files, dirs) < 1 || files.isEmpty())
1487  RESULT_ERR("Image not found", QString("Images %1 not in Db").arg(ids))
1488 
1489  // Update db
1490  for (const auto& im : qAsConst(files))
1491  {
1492  int old = im->m_orientation;
1493  im->m_orientation = Orientation(im->m_orientation).Transform(transform);
1494 
1495  // Update Db
1496  if (DBFS::SetOrientation(im->m_id, im->m_orientation))
1497  {
1498  LOG(VB_FILE, LOG_DEBUG, LOC + QString("Transformed %1 from %2 to %3")
1499  .arg(im->m_filePath).arg(old).arg(im->m_orientation));
1500  }
1501  }
1502 
1503  // Images are changed, not deleted
1504  QStringList mesg("");
1505 
1506  // Clean up thumbnails
1507  mesg << m_thumbGen->DeleteThumbs(files);
1508 
1509  // Notify clients of changed images
1510  DBFS::Notify("IMAGE_DB_CHANGED", mesg);
1511 
1512  return QStringList("OK");
1513 }
1514 
1515 
1524 template <class DBFS>
1525 QStringList ImageHandler<DBFS>::HandleDirs(const QString &destId,
1526  bool rescan,
1527  const QStringList &relPaths) const
1528 {
1529  // Find image in DB
1530  ImageList files;
1531  ImageList dirs;
1532  if (DBFS::GetImages(destId, files, dirs) != 1 || dirs.isEmpty())
1533  RESULT_ERR("Destination not found",
1534  QString("Image %1 not in Db").arg(destId))
1535 
1536  // Find dir. SG device (Photographs) uses most-free filesystem
1537  QString destPath = DBFS::GetAbsFilePath(dirs[0]);
1538  if (destPath.isEmpty())
1539  RESULT_ERR("Destination not found",
1540  QString("Dest dir %1 not found").arg(dirs[0]->m_filePath))
1541 
1542  QDir destDir(destPath);
1543  bool succeeded = false;
1544  for (const auto& relPath : qAsConst(relPaths))
1545  {
1546  // Validate dir name
1547  if (relPath.isEmpty() || relPath.contains("..") || relPath.startsWith(QChar('/')))
1548  continue;
1549 
1550  QString newPath = DBFS::ConstructPath(destDir.absolutePath(), relPath);
1551  if (!destDir.mkpath(relPath))
1552  {
1553  LOG(VB_GENERAL, LOG_ERR,
1554  LOC + QString("Failed to create dir %1").arg(newPath));
1555  continue;
1556  }
1557  LOG(VB_FILE, LOG_DEBUG, LOC + QString("Dir %1 created").arg(newPath));
1558  succeeded = true;
1559  }
1560 
1561  if (!succeeded)
1562  // Failures should only occur due to user input
1563  RESULT_ERR("Invalid Name", QString("Invalid name %1")
1564  .arg(relPaths.join(",")))
1565 
1566  if (rescan)
1567  // Rescan to detect new dir
1568  HandleScanRequest("START");
1569 
1570  return QStringList("OK");
1571 }
1572 
1573 
1580 template <class DBFS>
1581 QStringList ImageHandler<DBFS>::HandleCover(int dir, int cover) const
1582 {
1583  if (!DBFS::SetCover(dir, cover))
1584  RESULT_ERR("Set Cover failed",
1585  QString("Failed to set %1 to cover %2").arg(dir).arg(cover))
1586 
1587  // Image has changed, nothing deleted
1588  QStringList mesg = QStringList("") << QString::number(dir);
1589  DBFS::Notify("IMAGE_DB_CHANGED", mesg);
1590 
1591  RESULT_OK(QString("Cover of %1 is now %2").arg(dir).arg(cover));
1592 }
1593 
1594 
1603 template <class DBFS>
1604 QStringList ImageHandler<DBFS>::HandleIgnore(const QString &exclusions) const
1605 {
1606  // Save new setting. FE will have already saved it but not cleared the cache
1607  gCoreContext->SaveSettingOnHost("GalleryIgnoreFilter", exclusions, nullptr);
1608 
1609  // Rescan
1610  HandleScanRequest("START");
1611 
1612  RESULT_OK(QString("Using exclusions '%1'").arg(exclusions))
1613 }
1614 
1615 
1623 template <class DBFS>
1624 QStringList ImageHandler<DBFS>::HandleScanRequest(const QString &command,
1625  int devId) const
1626 {
1627  if (!m_scanner)
1628  RESULT_ERR("Missing Scanner", "Missing Scanner");
1629 
1630  if (command == "START")
1631  {
1632  // Must be dormant to start a scan
1633  if (m_scanner->IsScanning())
1634  RESULT_ERR("", "Scanner is busy");
1635 
1636  m_scanner->ChangeState(true);
1637  RESULT_OK("Scan requested");
1638  }
1639  else if (command == "STOP")
1640  {
1641  // Must be scanning to interrupt
1642  if (!m_scanner->IsScanning())
1643  RESULT_ERR("Scanner not running", "Scanner not running");
1644 
1645  m_scanner->ChangeState(false);
1646  RESULT_OK("Terminate scan requested");
1647  }
1648  else if (command == "QUERY")
1649  {
1650  return QStringList("OK") << m_scanner->GetProgress();
1651  }
1652  else if (command.startsWith(QString("DEVICE")))
1653  {
1654  m_scanner->EnqueueClear(devId, command);
1655  RESULT_OK(QString("Clearing device %1 %2").arg(command).arg(devId))
1656  }
1657  RESULT_ERR("Unknown command", QString("Unknown command %1").arg(command));
1658 }
1659 
1660 
1668 template <class DBFS>
1670 (const QStringList &message) const
1671 {
1672  if (message.size() != 2)
1673  RESULT_ERR("Unknown Command",
1674  QString("Bad request: %1").arg(message.join("|")))
1675 
1676  int priority = message.at(0).toInt()
1678 
1679  // get specific image details from db
1680  ImageList files;
1681  ImageList dirs;
1682  DBFS::GetImages(message.at(1), files, dirs);
1683 
1684  for (const auto& im : qAsConst(files))
1685  // notify clients when done; highest priority
1686  m_thumbGen->CreateThumbnail(im, priority, true);
1687 
1688  return QStringList("OK");
1689 }
1690 
1691 
1701 template <class DBFS>
1703 {
1704  QMutableListIterator<ImagePtr> it(images);
1705  it.toBack();
1706  while (it.hasPrevious())
1707  {
1708  ImagePtrK im = it.previous();
1709 
1710  // Remove file or directory
1711  QString absFilename = DBFS::GetAbsFilePath(im);
1712 
1713  bool success = !absFilename.isEmpty()
1714  && (im->IsFile() ? QFile::remove(absFilename)
1715  : QDir::root().rmdir(absFilename));
1716  if (success)
1717  LOG(VB_FILE, LOG_DEBUG, LOC + QString("Deleted %1").arg(absFilename));
1718  else
1719  {
1720  LOG(VB_GENERAL, LOG_ERR, LOC +
1721  QString("Can't delete %1").arg(absFilename));
1722  // Remove from list
1723  it.remove();
1724  }
1725  }
1726 }
1727 
1728 
1735 {
1736  switch (type)
1737  {
1738  case kPicOnly: return QString("AND type != %1").arg(kVideoFile);
1739  case kVideoOnly: return QString("AND type != %1").arg(kImageFile);
1740  case kPicAndVideo: return "";
1741  }
1742  return "";
1743 }
1744 
1745 
1752 {
1753  m_refineClause = QString("%2 %3 "
1754  "ORDER BY "
1755  "CASE WHEN type <= %1 THEN %4, "
1756  "CASE WHEN type > %1 THEN %5 ")
1757  .arg(kDirectory)
1758  .arg(m_showHidden ? "" : "AND hidden = 0",
1762 }
1763 
1764 
1771 {
1772  // prepare the sorting statement
1773  switch (order)
1774  {
1775  default:
1776  case kSortByNameAsc: return "name END ASC";
1777  case kSortByNameDesc: return "name END DESC";
1778  case kSortByModTimeAsc: return "modtime END ASC";
1779  case kSortByModTimeDesc: return "modtime END DESC";
1780  case kSortByExtAsc: return "extension END ASC, name ASC";
1781  case kSortByExtDesc: return "extension END DESC, name DESC";
1782  case kSortBySizeAsc: return "size END ASC, name ASC";
1783  case kSortBySizeDesc: return "size END DESC, name DESC";
1784  case kSortByDateAsc: return "IF(date=0, modtime, date) END ASC";
1785  case kSortByDateDesc: return "IF(date=0, modtime, date) END DESC";
1786  }
1787 }
1788 
1789 
1799  ImageList &files, ImageList &dirs) const
1800 {
1801  // Only Root node will invoke both Db queries but result set will be small
1802  // For Root the SG is always ordered before local devices
1803  // Root node has no Db entry so the 2 queries will not overwrite the parent.
1804  int count = 0;
1805  if (!ImageItem::IsLocalId(id))
1806  count = m_remote->GetDirectory(id, parent, files, dirs, m_refineClause);
1808  count += ImageHandler::GetDirectory(id, parent, files, dirs, m_refineClause);
1809 
1810  if (id == GALLERY_DB_ID)
1811  {
1812  // Add a Root node
1813  parent = ImagePtr(new ImageItem(GALLERY_DB_ID));
1814  parent->m_parentId = GALLERY_DB_ID;
1815  parent->m_type = kDevice;
1816 
1817  ++count;
1818  }
1819  return count;
1820 }
1821 
1822 
1831  ImageList &files, ImageList &dirs) const
1832 {
1833  // Ids are either all local or all remote. GALLERY_DB_ID not valid
1834  StringPair lists = ImageItem::PartitionIds(ids);
1835 
1836  if (!lists.second.isEmpty())
1837  return m_remote->GetImages(lists.second, files, dirs, m_refineClause);
1838  if (m_DbExists && !lists.first.isEmpty())
1839  return ImageHandler::GetImages(lists.first, files, dirs, m_refineClause);
1840  return 0;
1841 }
1842 
1843 
1851 int ImageDbReader::GetChildren(int id, ImageList &files, ImageList &dirs) const
1852 {
1853  int count = 0;
1854  if (!ImageItem::IsLocalId(id))
1855  count = m_remote->GetChildren(QString::number(id), files, dirs,
1856  m_refineClause);
1858  count += ImageHandler::GetChildren(QString::number(id), files, dirs,
1859  m_refineClause);
1860  return count;
1861 }
1862 
1863 
1871  ImageList &files, ImageList &dirs) const
1872 {
1873  // Ids are either all local or all remote
1874  StringPair lists = ImageItem::PartitionIds(ids);
1875 
1876  if (!lists.second.isEmpty())
1877  m_remote->GetDescendants(lists.second, files, dirs);
1878  if (m_DbExists && !lists.first.isEmpty())
1879  ImageHandler::GetDescendants(lists.first, files, dirs);
1880 }
1881 
1882 
1889 void ImageDbReader::GetImageTree(int id, ImageList &files) const
1890 {
1891  if (!ImageItem::IsLocalId(id))
1892  m_remote->GetImageTree(id, files, m_refineClause);
1894  ImageHandler::GetImageTree(id, files, m_refineClause);
1895 }
1896 
1897 
1906 void ImageDbReader::GetDescendantCount(int id, int &dirs, int &pics,
1907  int &videos, int &sizeKb) const
1908 {
1909  if (id == GALLERY_DB_ID)
1910  {
1911  // Sum both unfiltered tables
1912  m_remote->GetDescendantCount(id, true, dirs, pics, videos, sizeKb);
1913  if (m_DbExists)
1914  ImageHandler::GetDescendantCount(id, true, dirs, pics, videos, sizeKb);
1915  }
1916  else if (!ImageItem::IsLocalId(id))
1917  {
1918  // Don't filter on SG path (it's blank)
1920  dirs, pics, videos, sizeKb);
1921  }
1922  else if (m_DbExists)
1923  {
1924  // Always filter on device/dir
1925  ImageHandler::GetDescendantCount(id, false, dirs, pics, videos, sizeKb);
1926  }
1927 }
1928 
1929 
1934 
1935 
1941 {
1942  if (!s_instance)
1943  s_instance = new ImageManagerBe();
1944  return s_instance;
1945 }
1946 
1947 
1953 {
1954  if (!s_instance)
1955  {
1956  // Use saved settings
1958  (gCoreContext->GetNumSetting("GalleryImageOrder"),
1959  gCoreContext->GetNumSetting("GalleryDirOrder"),
1960  gCoreContext->GetBoolSetting("GalleryShowHidden"),
1961  gCoreContext->GetNumSetting("GalleryShowType"),
1962  gCoreContext->GetSetting("GalleryDateFormat"));
1963  }
1964  return *s_instance;
1965 }
1966 
1967 
1976 void ImageManagerFe::CreateThumbnails(const ImageIdList &ids, bool forFolder)
1977 {
1978  // Split images into <locals, remotes>
1979  StringPair lists = ImageItem::PartitionIds(ids);
1980 
1981  if (!lists.second.isEmpty())
1982  {
1983  LOG(VB_FILE, LOG_DEBUG, LOC +
1984  QString("Sending CREATE_THUMBNAILS %1 (forFolder %2)")
1985  .arg(lists.second).arg(forFolder));
1986 
1987  QStringList message;
1988  message << QString::number(static_cast<int>(forFolder)) << lists.second;
1989  gCoreContext->SendEvent(MythEvent("CREATE_THUMBNAILS", message));
1990  }
1991 
1992  if (!lists.first.isEmpty())
1993  {
1994  LOG(VB_FILE, LOG_DEBUG, LOC +
1995  QString("Creating local thumbnails %1 (forFolder %2)")
1996  .arg(lists.first).arg(forFolder));
1997 
1998  QStringList message;
1999  message << QString::number(static_cast<int>(forFolder)) << lists.first;
2000  HandleCreateThumbnails(message);
2001  }
2002 }
2003 
2004 
2011 QString ImageManagerFe::ScanImagesAction(bool start, bool local)
2012 {
2013  QStringList command;
2014  command << (start ? "START" : "STOP");
2015 
2016  if (!local)
2017  {
2018  command.push_front("IMAGE_SCAN");
2019  bool ok = gCoreContext->SendReceiveStringList(command, true);
2020  return ok ? "" : command[1];
2021  }
2022 
2023  // Create database on first scan
2024  if (!CreateTable())
2025  return "Couldn't create database";
2026 
2027  QStringList err = HandleScanRequest(command[0]);
2028  return err[0] == "OK" ? "" : err[1];
2029 }
2030 
2031 
2038 {
2039  QStringList strList;
2040  strList << "IMAGE_SCAN" << "QUERY";
2041 
2042  if (!gCoreContext->SendReceiveStringList(strList))
2043  {
2044  LOG(VB_GENERAL, LOG_ERR, LOC + QString("Scan query failed : %1")
2045  .arg(strList.join(",")));
2046  }
2047  return strList;
2048 }
2049 
2050 
2057 QString ImageManagerFe::HideFiles(bool hidden, const ImageIdList &ids)
2058 {
2059  // Split images into <locals, remotes>
2060  StringPair lists = ImageItem::PartitionIds(ids);
2061  QString result = "";
2062 
2063  if (!lists.second.isEmpty())
2064  {
2065  QStringList message;
2066  message << "IMAGE_HIDE" << QString::number(static_cast<int>(hidden)) << lists.second;
2067 
2068  if (!gCoreContext->SendReceiveStringList(message, true))
2069  result = message[1];
2070  }
2071 
2072  if (!lists.first.isEmpty())
2073  {
2074  QStringList err = HandleHide(hidden, lists.first);
2075  if (err[0] != "OK")
2076  result = err[1];
2077  }
2078  return result;
2079 }
2080 
2081 
2089  const ImageIdList &ids)
2090 {
2091  // Split images into <locals, remotes>
2092  StringPair lists = ImageItem::PartitionIds(ids);
2093  QString result = "";
2094 
2095  if (!lists.second.isEmpty())
2096  {
2097  QStringList message;
2098  message << "IMAGE_TRANSFORM" << QString::number(transform) << lists.second;
2099 
2100  if (!gCoreContext->SendReceiveStringList(message, true))
2101  result = message[1];
2102  }
2103 
2104  if (!lists.first.isEmpty())
2105  {
2106  QStringList err = HandleTransform(transform, lists.first);
2107  if (err[0] != "OK")
2108  result = err[1];
2109  }
2110  return result;
2111 }
2112 
2113 
2120 QString ImageManagerFe::SetCover(int parent, int cover)
2121 {
2122  if (!ImageItem::IsLocalId(parent))
2123  {
2124  QStringList message;
2125  message << "IMAGE_COVER" << QString::number(parent) << QString::number(cover);
2126 
2127  bool ok = gCoreContext->SendReceiveStringList(message, true);
2128  return ok ? "" : message[1];
2129  }
2130 
2131  QStringList err = HandleCover(parent, cover);
2132  return err[0] == "OK" ? "" : err[1];
2133 }
2134 
2135 
2141 {
2142  if (ImageItem::IsLocalId(id))
2143  HandleGetMetadata(QString::number(id));
2144  else
2145  gCoreContext->SendEvent(MythEvent("IMAGE_GET_METADATA", QString::number(id)));
2146 }
2147 
2148 
2151 {
2152  QStringList message("IMAGE_SCAN");
2153  message << "DEVICE CLEAR ALL";
2154  gCoreContext->SendReceiveStringList(message, true);
2155 }
2156 
2157 
2164 QString ImageManagerFe::IgnoreDirs(const QString &excludes)
2165 {
2166  QStringList message("IMAGE_IGNORE");
2167  message << excludes;
2168  bool ok = gCoreContext->SendReceiveStringList(message, true);
2169  return ok ? "" : message[1];
2170 }
2171 
2172 
2180 QString ImageManagerFe::MakeDir(int parent, const QStringList &names, bool rescan)
2181 {
2182  QString destId = QString::number(parent);
2183 
2184  if (!ImageItem::IsLocalId(parent))
2185  {
2186  QStringList message("IMAGE_CREATE_DIRS");
2187  message << destId << QString::number(static_cast<int>(rescan)) << names;
2188  bool ok = gCoreContext->SendReceiveStringList(message, true);
2189  return ok ? "" : message[1];
2190  }
2191  QStringList err = HandleDirs(destId, rescan, names);
2192  return (err[0] == "OK") ? "" : err[1];
2193 }
2194 
2195 
2202 QString ImageManagerFe::RenameFile(const ImagePtrK& im, const QString &name)
2203 {
2204  if (!im->IsLocal())
2205  {
2206  QStringList message("IMAGE_RENAME");
2207  message << QString::number(im->m_id) << name;
2208  bool ok = gCoreContext->SendReceiveStringList(message, true);
2209  return ok ? "" : message[1];
2210  }
2211  QStringList err = HandleRename(QString::number(im->m_id), name);
2212  return (err[0] == "OK") ? "" : err[1];
2213 }
2214 
2215 
2222 QString ImageManagerFe::CreateImages(int destId, const ImageListK &images)
2223 {
2224  if (images.isEmpty())
2225  return "";
2226 
2227  // Define field seperator & include it in message
2228  const QString seperator("...");
2229  QStringList imageDefs(seperator);
2230  ImageIdList ids;
2231  for (const auto& im : qAsConst(images))
2232  {
2233  ids << im->m_id;
2234 
2235  // Copies preserve hide state, orientation & cover
2236  QStringList aDef;
2237  aDef << QString::number(im->m_id)
2238  << QString::number(im->m_type)
2239  << im->m_filePath
2240  << QString::number(static_cast<int>(im->m_isHidden))
2241  << QString::number(im->m_orientation)
2242  << QString::number(im->m_userThumbnail);
2243 
2244  imageDefs << aDef.join(seperator);
2245  }
2246 
2247  // Images are either all local or all remote
2248  if (ImageItem::IsLocalId(destId))
2249  {
2250  QStringList err = HandleDbCreate(imageDefs);
2251  return (err[0] == "OK") ? "" : err[1];
2252  }
2253  imageDefs.prepend("IMAGE_COPY");
2254  bool ok = gCoreContext->SendReceiveStringList(imageDefs, true);
2255  return ok ? "" : imageDefs[1];
2256 }
2257 
2258 
2266 QString ImageManagerFe::MoveDbImages(const ImagePtrK& destDir, ImageListK &images,
2267  const QString &srcPath)
2268 {
2269  QStringList idents;
2270  for (const auto& im : qAsConst(images))
2271  idents << QString::number(im->m_id);
2272 
2273  // Images are either all local or all remote
2274  if (destDir->IsLocal())
2275  {
2276  QStringList err = HandleDbMove(idents.join(","), srcPath,
2277  destDir->m_filePath);
2278  return (err[0] == "OK") ? "" : err[1];
2279  }
2280 
2281  QStringList message("IMAGE_MOVE");
2282  message << idents.join(",") << srcPath << destDir->m_filePath;
2283  bool ok = gCoreContext->SendReceiveStringList(message, true);
2284  return ok ? "" : message[1];
2285 }
2286 
2287 
2294 {
2295  StringPair lists = ImageItem::PartitionIds(ids);
2296 
2297  QString result = "";
2298  if (!lists.second.isEmpty())
2299  {
2300  QStringList message("IMAGE_DELETE");
2301  message << lists.second;
2302 
2303  bool ok = gCoreContext->SendReceiveStringList(message, true);
2304  if (!ok)
2305  result = message[1];
2306  }
2307  if (!lists.first.isEmpty())
2308  {
2309  QStringList err = HandleDelete(lists.first);
2310  if (err[0] != "OK")
2311  result = err[1];
2312  }
2313  return result;
2314 }
2315 
2316 
2324 {
2325  if (im->m_id == GALLERY_DB_ID)
2326  return "";
2327 
2328 #if QT_VERSION < QT_VERSION_CHECK(5,8,0)
2329  uint secs = 0;
2330 #else
2331  qint64 secs = 0;
2332 #endif
2334 
2335  if (im->m_date > 0)
2336  {
2337  secs = im->m_date;
2338  format |= MythDate::kTime;
2339  }
2340  else
2341  secs = im->m_modTime;
2342 
2343 #if QT_VERSION < QT_VERSION_CHECK(5,8,0)
2344  return MythDate::toString(QDateTime::fromTime_t(secs), format);
2345 #else
2346  return MythDate::toString(QDateTime::fromSecsSinceEpoch(secs), format);
2347 #endif
2348 }
2349 
2350 
2357 QString ImageManagerFe::ShortDateOf(const ImagePtrK& im) const
2358 {
2359  if (im->m_id == GALLERY_DB_ID)
2360  return "";
2361 
2362 #if QT_VERSION < QT_VERSION_CHECK(5,8,0)
2363  uint secs(im->m_date > 0 ? im->m_date : im->m_modTime);
2364  return QDateTime::fromTime_t(secs).date().toString(m_dateFormat);
2365 #else
2366  qint64 secs(im->m_date > 0 ? im->m_date : im->m_modTime);
2367  return QDateTime::fromSecsSinceEpoch(secs).date().toString(m_dateFormat);
2368 #endif
2369 }
2370 
2371 
2378 {
2379  if (im.m_id == GALLERY_DB_ID)
2380  return tr("Gallery");
2381  if (im.m_id == PHOTO_DB_ID)
2382  return tr("Photographs");
2383  return im.IsLocal() ? DeviceName(im.m_device)
2384  : m_remote->DeviceName(im.m_device);
2385 }
2386 
2387 
2395 QString ImageManagerFe::CrumbName(ImageItemK &im, bool getPath) const
2396 {
2397  if (im.IsDevice())
2398  return DeviceCaption(im);
2399 
2400  if (!getPath)
2401  return im.m_baseName;
2402 
2403  QString dev;
2404  QString path(im.m_filePath);
2405 
2406  if (im.IsLocal())
2407  {
2408  // Replace local mount path with device name
2409  path.remove(0, DeviceMount(im.m_device).size());
2410  dev = DeviceName(im.m_device);
2411  }
2412  return dev + path.replace("/", " > ");
2413 }
2414 
2415 
2416 void ImageManagerFe::CloseDevices(int devId, bool eject)
2417 {
2418  QString reason = (devId == DEVICE_INVALID)
2419  ? "DEVICE CLOSE ALL"
2420  : eject ? "DEVICE EJECT" : "DEVICE REMOVE";
2421  HandleScanRequest(reason, devId);
2422 }
2423 
2424 
2430 {
2432  if (!monitor)
2433  return false;
2434 
2435  // Detect all local media
2436  QList<MythMediaDevice*> devices
2438 
2439  for (auto *dev : qAsConst(devices))
2440  {
2441  if (monitor->ValidateAndLock(dev) && dev->isUsable())
2442  OpenDevice(dev->getDeviceModel(), dev->getMountPath(), dev);
2443  else
2444  monitor->Unlock(dev);
2445  }
2446 
2447  if (DeviceCount() > 0)
2448  {
2449  // Close devices that are no longer present
2450  for (int devId : GetAbsentees())
2451  CloseDevices(devId);
2452 
2453  // Start local scan
2454  QString err = ScanImagesAction(true, true);
2455  if (!err.isEmpty())
2456  LOG(VB_GENERAL, LOG_ERR, LOC + err);
2457  }
2458  return DeviceCount() > 0;
2459 }
2460 
2461 
2467 {
2469 
2470  if (!event || !monitor)
2471  return;
2472 
2473  MythMediaDevice *dev = event->getDevice();
2474  if (!dev)
2475  return;
2476 
2477  MythMediaType type = dev->getMediaType();
2478  MythMediaStatus status = dev->getStatus();
2479 
2480  LOG(VB_FILE, LOG_DEBUG, LOC +
2481  QString("Media event for %1 (%2) at %3, type %4, status %5 (was %6)")
2482  .arg(dev->getDeviceModel(), dev->getVolumeID(), dev->getMountPath())
2483  .arg(type).arg(status).arg(event->getOldStatus()));
2484 
2486  {
2487  LOG(VB_FILE, LOG_DEBUG, LOC +
2488  QString("Ignoring event - wrong type %1").arg(type));
2489  return;
2490  }
2491 
2492  if (status == MEDIASTAT_USEABLE || status == MEDIASTAT_MOUNTED)
2493  {
2494  // New device. Lock it & scan
2495  if (monitor->ValidateAndLock(dev))
2496  {
2497  OpenDevice(dev->getDeviceModel(), dev->getMountPath(), dev);
2498  ScanImagesAction(true, true);
2499  }
2500  else
2501  monitor->Unlock(dev);
2502  return;
2503  }
2504 
2505  // Device has disappeared
2506  int devId = LocateMount(dev->getMountPath());
2507  if (devId != DEVICE_INVALID)
2508  CloseDevices(devId);
2509 }
2510 
2511 
2513 {
2514  auto *tmp = new QTemporaryDir(QDir::tempPath() % "/" IMPORTDIR "-XXXXXX");
2515  if (!tmp->isValid())
2516  {
2517  delete tmp;
2518  return "";
2519  }
2520 
2521  QString time(QDateTime::currentDateTime().toString("mm:ss"));
2522  OpenDevice("Import " + time, tmp->path(), nullptr, tmp);
2523  return tmp->path();
2524 }
2525 
2526 
2527 // Must define the valid template implementations to generate code for the
2528 // instantiations (as they are defined in the cpp rather than header).
2529 // Otherwise the linker will fail with undefined references...
2530 template class ImageDb<ImageAdapterSg>;
2531 template class ImageDb<ImageAdapterLocal>;
2532 template class ImageHandler<ImageDbSg>;
2533 template class ImageHandler<ImageDbLocal>;
MythMediaType getMediaType() const
Definition: mythmedia.h:91
void DropTable()
Remove local image table.
QStringList HandleDelete(const QString &ids) const
Deletes images/dirs.
File size Largest -> Smallest.
Definition: imagetypes.h:52
static QString OrderSelector(int order)
Generate SQL ordering clause.
bool next(void)
Wrap QSqlQuery::next() so we can display the query results.
Definition: mythdbcon.cpp:783
void RemoveThumbs(void) const
Delete thumbnails associated with device.
A video.
Definition: imagetypes.h:39
static QString FormatSize(int sizeKib)
Definition: imagemanager.h:143
QString DeviceName(int devId) const
Get model name of the device.
QSharedPointer< ImageItem > ImagePtr
Definition: imagetypes.h:166
void GetDescendantCount(int id, bool all, int &dirs, int &pics, int &videos, int &sizeKb) const
Return counts of dirs, pics, videos and size in the subtree of a dir.
Name Z-A.
Definition: imagetypes.h:46
const QString & getDevicePath() const
Definition: mythmedia.h:61
void bindValue(const QString &placeholder, const QVariant &val)
Add a single binding.
Definition: mythdbcon.cpp:864
QStringList GetDirList(void) const
Definition: storagegroup.h:23
static Device kNullDevice
Abstract class for image metadata.
Definition: imagemetadata.h:99
int ReadImages(ImageList &dirs, ImageList &files, const QString &selector) const
Read selected database images/dirs.
MythMediaType
Definition: mythmedia.h:24
Encapsulates Exif orientation processing.
Definition: imagemetadata.h:62
VERBOSE_PREAMBLE Most true
Definition: verbosedefs.h:91
bool RemoveFromDB(Bookmark *site)
int m_dirOrder
Display ordering of dirs.
Definition: imagemanager.h:440
QString MakeDir(int parent, const QStringList &names, bool rescan=true)
Create directories.
#define DB_COLUMNS
QString toString(MarkTypes type)
void EjectMedia(const QString &path)
A device sub directory.
Definition: imagetypes.h:37
QString ChangeOrientation(ImageFileTransform transform, const ImageIdList &ids)
Apply an orientation transform to images.
bool CreateTable()
Create local database table, if it doesn't exist.
Extension Z-A.
Definition: imagetypes.h:50
int m_showType
Type of images to display - pic only/video only/both.
Definition: imagemanager.h:443
int InsertDbImage(ImageItemK &im, bool checkForDuplicate=false) const
Adds new image to database, optionally checking for existing filepath.
QString m_dateFormat
UI format for thumbnail date captions.
Definition: imagemanager.h:514
void GetDescendantCount(int id, int &dirs, int &pics, int &videos, int &sizeKb) const
Return counts of dirs, pics and videos in the subtree of a dir. Also dir size.
ImageItem * CreateImage(const MSqlQuery &query) const
Create image from Db query data.
#define STORAGE_GROUP_MOUNT
static QString GetAbsThumbPath(const QString &devPath, const QString &path)
Get absolute filepath for thumbnail of an image.
Definition: imagemanager.h:148
The image manager for use by Frontends.
Definition: imagemanager.h:456
qint64 m_date
Image creation date, from Exif metadata.
Definition: imagetypes.h:106
bool SetHidden(bool hide, QString ids) const
Sets hidden status of an image/dir in database.
QString m_filePath
Absolute for local images. Usually SG-relative for remotes.
Definition: imagetypes.h:92
const association_list & getList() const
Definition: dbaccess.cpp:805
QSqlQuery wrapper that fetches a DB connection from the connection pool.
Definition: mythdbcon.h:125
void RemoveFiles(ImageList &images) const
Deletes images and dirs from the filesystem.
#define RESULT_ERR(ERR, MESG)
Database API.
Definition: imagemanager.h:274
Manages a collection of images.
QStringList HandleDbMove(const QString &ids, const QString &srcPath, QString destPath) const
Updates images that have been renamed.
int Transform(int transform)
Adjust orientation to apply a transform to an image.
int size(void) const
Definition: mythdbcon.h:203
#define RESULT_OK(MESG)
#define EXIF_MYTH_SIZE
Definition: imagemetadata.h:41
static QString LongDateOf(const ImagePtrK &im)
Return a timestamp/datestamp for an image or dir.
static void ClearStorageGroup()
Clear database & thumbnails of Storage Group images.
static QString ThumbPath(const ImageItem &im)
Thumbnails of videos are a JPEG snapshot with jpg suffix appended.
Definition: imagemanager.h:152
QDir m_dirFilter
A pre-configured dir for reading image/video files.
Definition: imagemanager.h:175
int m_parentId
Id of parent dir.
Definition: imagetypes.h:95
ImageDbSg * m_remote
Remote database access.
Definition: imagemanager.h:438
Show Pictures & Videos.
Definition: imagemanager.h:78
std::vector< file_association > association_list
Definition: dbaccess.h:154
QString m_refineClause
SQL clause for image filtering/ordering.
Definition: imagemanager.h:444
QStringList HandleDirs(const QString &destId, bool rescan, const QStringList &relPaths) const
Creates new image directories.
QString GetAbsFilePath(const ImagePtrK &im) const
Get absolute filepath for a remote image.
MythCoreContext * gCoreContext
This global variable contains the MythCoreContext instance for the app.
QString CreateImages(int destId, const ImageListK &images)
Copies database images (but not the files themselves).
QString Description() const
Generate text description of orientation.
bool m_showHidden
Whether hidden images are displayed.
Definition: imagemanager.h:442
ImageManagerFe(int order, int dirOrder, bool showAll, int showType, QString dateFormat)
Definition: imagemanager.h:501
static void Notify(const QString &mesg, const QStringList &extra)
Send message to all clients about remote ids.
int OpenDevice(const QString &name, const QString &mount, MythMediaDevice *media=nullptr, QTemporaryDir *dir=nullptr)
Define a new device and assign it a unique id. If the device is already known, its existing id is ret...
static guint32 * tmp
Definition: goom_core.cpp:30
bool isImport() const
QStringList CloseDevices(int devId, const QString &action)
Remove a device (or all devices)
bool IsDevice() const
Definition: imagetypes.h:123
const char * formats[8]
Definition: vbilut.cpp:188
StorageGroup m_sg
Images storage group.
Definition: imagemanager.h:266
int GetChildren(int id, ImageList &files, ImageList &dirs) const
Return (local or remote) images that are direct children of a dir.
bool IsLocal() const
Definition: imagetypes.h:126
Exif date Latest -> Earliest.
Definition: imagetypes.h:54
QString DeleteFiles(const ImageIdList &ids)
Delete images.
QStringList RemoveFromDB(const ImageList &imList) const
Remove images/dirs from database.
static void RemoveDirContents(const QString &path)
Clears all files and sub-dirs within a directory.
bool ReadAllImages(ImageHash &files, ImageHash &dirs) const
Read all database images and dirs as map. No filters or ordering applied.
void CreateThumbnails(const ImageIdList &ids, bool forFolder)
Create thumbnails or verify that they already exist.
QList< int > GetAbsentees()
Get list of mountpoints for non-import devices.
QSharedPointer< ImageItemK > ImagePtrK
Definition: imagetypes.h:172
static ImageMetaData * FromPicture(const QString &filePath)
Factory to retrieve metadata from pictures.
QString HideFiles(bool hidden, const ImageIdList &ids)
Hide/unhide images.
QString m_extension
Image file extension.
Definition: imagetypes.h:93
bool isPresent() const
The image manager to be used by the Backend.
Definition: imagemanager.h:378
MythMediaStatus getOldStatus(void) const
Definition: mythmedia.h:190
QString GetConfDir(void)
Definition: mythdirs.cpp:224
QVariant value(int i) const
Definition: mythdbcon.h:198
Hide videos.
Definition: imagemanager.h:79
A device containing images (ie. USB stick, CD, storage group etc)
QString m_mount
Mountpoint.
bool UpdateDbImage(ImageItemK &im) const
Updates or creates database image or dir.
const QString & getVolumeID() const
Definition: mythmedia.h:72
int m_userThumbnail
Id of thumbnail to use as cover (dirs only)
Definition: imagetypes.h:113
void run() override
MythMediaDevice * m_media
Set for MediaMonitor devices only.
int GetDirectory(int id, ImagePtr &parent, ImageList &files, ImageList &dirs) const
Return images (local and/or remote) for a dir and its direct children.
ImageFileTransform
Image transformations.
Definition: imagemetadata.h:46
bool SendReceiveStringList(QStringList &strlist, bool quickTimeout=false, bool block=true)
Send a message to the backend and wait for a response.
QStringList m_imageFileExt
List of file extensions recognised as pictures.
Definition: imagemanager.h:177
int m_fileOrder
Display ordering of pics/videos.
Definition: imagemanager.h:441
QString ThumbDir(int fs) const
QString SetCover(int parent, int cover)
Set image to use as a cover thumbnail(s)
static ImageManagerBe * s_instance
BE Gallery instance.
Definition: imagemanager.h:391
This class is used as a container for messages.
Definition: mythevent.h:16
#define TEMP_SUBDIR
Definition: imagemanager.h:67
MBASE_PUBLIC QDateTime fromSecsSinceEpoch(uint seconds)
This function takes the number of seconds since the start of the epoch and returns a QDateTime with t...
Definition: mythdate.cpp:88
QStringList HandleCreateThumbnails(const QStringList &message) const
Creates thumbnails on-demand.
int GetChildren(QString ids, ImageList &files, ImageList &dirs, const QString &refine="") const
Read immediate children of a dir.
static bool IsLocalParent(int id)
Parents of locals are locals or root.
Definition: imagetypes.h:131
#define EXIF_MYTH_ORIENT
Definition: imagemetadata.h:42
MSqlQuery query(MSqlQuery::InitCon())
QVariant lastInsertId()
Return the id of the last inserted row.
Definition: mythdbcon.cpp:888
ImageAdapterBase()
Constructor.
QStringList HandleScanRequest(const QString &command, int devId=DEVICE_INVALID) const
Process scan requests.
static void clear(SettingsMap &cache, SettingsMap &overrides, const QString &myKey)
Definition: mythdb.cpp:846
static ImageManagerBe * getInstance()
Get Backend Gallery.
Name A-Z.
Definition: imagetypes.h:45
ImageNodeType GetImageType(const QString &ext) const
Determine file type from its extension.
Definition: imagemanager.h:165
QString ScanImagesAction(bool start, bool local=false)
Handle scanner start/stop commands.
bool SetCover(int dir, int id) const
Set the thumbnail(s) to be used for a dir.
QMap< int, QString > StringMap
Definition: imagetypes.h:62
#define THUMBNAIL_SUBDIR
Definition: imagemanager.h:69
QString GetSetting(const QString &key, const QString &defaultval="")
static QString ToString(const QString &name, const QString &label, const QString &value)
Encodes metadata into a string as <tag name><tag label><tag value>
bool GetImageTree(int id, ImageList &files, const QString &refine) const
Returns all files in the sub-tree of a dir.
ImageItem * CreateItem(const QFileInfo &fi, int parentId, int devId, const QString &base) const
Construct a local image from a file.
StringMap GetScanDirs() const
Returns SG dirs.
Default local time.
Definition: mythdate.h:16
static MediaMonitor * GetMediaMonitor(void)
int GetDirectory(int id, ImagePtr &parent, ImageList &files, ImageList &dirs, const QString &refine) const
Read a dir and its immediate children from Db.
Extension A-Z.
Definition: imagetypes.h:49
static QString IgnoreDirs(const QString &excludes)
Set directories to ignore during scans of the storage group.
static QString BaseNameOf(const QString &path)
Extracts file name (incl extension) from a filepath.
Definition: imagemanager.h:136
QString FindNextDirMostFree(void)
Reflect about horizontal axis.
Definition: imagemetadata.h:51
void SetRefinementClause()
Sets filter/ordering SQL clause used when reading database according to current filter/sort settings.
QString RenameFile(const ImagePtrK &im, const QString &name)
Rename an image.
int GetImages(const ImageIdList &ids, ImageList &files, ImageList &dirs) const
Returns images (local or remote but not a combination)
static ImageManagerFe * s_instance
FE Gallery instance.
Definition: imagemanager.h:511
static QStringList SupportedVideos()
Return recognised video extensions.
int GetImages(const QString &ids, ImageList &files, ImageList &dirs, const QString &refine="") const
Read database images/dirs by id.
QList< MythMediaDevice * > GetMedias(unsigned mediatypes)
Ask for available media.
QStringList HandleRename(const QString &id, const QString &newBase) const
Change name of an image/dir.
QStringList HandleGetMetadata(const QString &id) const
Read meta data for an image.
qint64 m_modTime
Filesystem modified datestamp.
Definition: imagetypes.h:100
Add year to string if not included.
Definition: mythdate.h:22
const QString & getDeviceModel() const
Definition: mythmedia.h:67
virtual QStringList GetAllTags()=0
unsigned int uint
Definition: compat.h:140
void GetImageTree(int id, ImageList &files) const
Return all files (local or remote) in the sub-trees of a dir.
static StringPair PartitionIds(const ImageIdList &ids)
Separates list of ids into a list of local ids and a list of remote ids.
Definition: imagetypes.h:147
QString m_table
Db table name.
Definition: imagemanager.h:310
static MSqlQueryInfo InitCon(ConnectionReuse _reuse=kNormalConnection)
Only use this in combination with MSqlQuery constructor.
Definition: mythdbcon.cpp:535
ReadMetaThread(ImagePtrK im, QString path)
void Unlock(MythMediaDevice *pMedia)
decrements the MythMediaDevices reference count
File modified time Latest -> Earliest.
Definition: imagetypes.h:48
#define IMPORTDIR
static bool IsLocalId(int id)
Determine image type (local/remote) from its id. Root/Gallery is remote.
Definition: imagetypes.h:129
QString toString(const QDateTime &raw_dt, uint format)
Returns formatted string representing the time.
Definition: mythdate.cpp:101
int m_orientation
Image orientation.
Definition: imagetypes.h:108
QString m_baseName
File/Dir name with extension (no path)
Definition: imagetypes.h:91
DeviceMap m_devices
Device store.
Definition: imagemanager.h:119
QPair< QString, QString > StringPair
Definition: imagetypes.h:60
bool GetDescendants(const QString &ids, ImageList &files, ImageList &dirs) const
Return images and all of their descendants.
QList< ImagePtr > ImageList
Definition: imagetypes.h:167
#define EXIF_MYTH_PATH
Definition: imagemetadata.h:39
ImageDbSg()
SG database constructor.
static FileAssociations & getFileAssociation()
Definition: dbaccess.cpp:830
void DeviceEvent(MythMediaEvent *event)
Manage events for local devices.
Task to read all metadata from file.
A picture.
Definition: imagetypes.h:38
static MThreadPool * globalInstance(void)
void setPresent(MythMediaDevice *media)
QString DeviceCaption(ImageItemK &im) const
Return translated device name.
void ClearDb(int devId, const QString &action)
Clear Db for device & remove device.
int GetNumSetting(const QString &key, int defaultval=0)
Client request to display an image thumbnail.
Definition: imagethumbs.h:34
bool prepare(const QString &query)
QSqlQuery::prepare() is not thread safe in Qt <= 3.3.2.
Definition: mythdbcon.cpp:808
QList< int > ImageIdList
Definition: imagetypes.h:59
Exif date Earliest -> Latest.
Definition: imagetypes.h:53
void start(QRunnable *runnable, const QString &debugName, int priority=0)
bool ValidateAndLock(MythMediaDevice *pMedia)
Validates the MythMediaDevice and increments its reference count.
bool GetBoolSetting(const QString &key, bool defaultval=false)
QString DeviceMount(int devId) const
Get path at which the device is mounted.
QString FindFile(const QString &filename)
const QString & getMountPath() const
Definition: mythmedia.h:58
QStringList m_videoFileExt
List of file extensions recognised as videos.
Definition: imagemanager.h:179
int m_device
Id of media device. Always 0 (SG) for remotes, 1+ for local devices.
Definition: imagetypes.h:94
void CloseDevices(int devId=DEVICE_INVALID, bool eject=false)
Client request to display a directory thumbnail.
Definition: imagethumbs.h:35
QStringList HandleCover(int dir, int cover) const
Updates/resets cover thumbnail for an image dir.
#define LOC
bool SetOrientation(int id, int orientation) const
Sets image orientation in Db.
#define EXIF_MYTH_HOST
Definition: imagemetadata.h:38
static QString TypeSelector(int type)
Generate SQL type filter clause.
Represents a picture, video or directory.
Definition: imagetypes.h:67
#define DBLOC
QString m_name
Device model/volume/id.
static QStringList ScanQuery()
Returns storage group scanner status.
QStringList HandleHide(bool hide, const QString &ids) const
Hides/unhides images/dirs.
bool DetectLocalDevices()
Detect and scan local devices.
void GetDescendants(const ImageIdList &ids, ImageList &files, ImageList &dirs) const
Return all (local or remote) images that are direct children of a dir.
int m_type
Type of node: dir, video etc.
Definition: imagetypes.h:96
#define EXIF_MYTH_NAME
Definition: imagemetadata.h:40
#define PHOTO_DB_ID
Definition: imagetypes.h:28
Storage Group and local mounted media.
Definition: imagetypes.h:35
File modified time Earliest -> Latest.
Definition: imagetypes.h:47
QString m_thumbs
Dir sub-path of device thumbnails.
QStringList HandleDbCreate(QStringList defs) const
Creates images for files created by a copy operation.
QString MoveDbImages(const ImagePtrK &destDir, ImageListK &images, const QString &srcPath)
Moves database images (but not the files themselves).
ImageDbLocal()
Local database constructor.
QString ShortDateOf(const ImagePtrK &im) const
Return a short datestamp for thumbnail captions.
Hide pictures.
Definition: imagemanager.h:80
MythMediaStatus
Definition: mythmedia.h:12
bool exec(void)
Wrap QSqlQuery::exec() so we can display SQL.
Definition: mythdbcon.cpp:603
bool m_present
True when gallery UI is running & device is useable. Always true for imports.
Unprocessable file type.
Definition: imagetypes.h:34
int DeviceCount() const
Definition: imagemanager.h:100
bool SaveSettingOnHost(const QString &key, const QString &newValue, const QString &host)
QTemporaryDir * m_dir
Dir path of images: import devices only.
#define DB_TABLE
static void DBError(const QString &where, const MSqlQuery &query)
Definition: mythdb.cpp:179
static void Notify(const QString &mesg, const QStringList &extra)
Send local message to UI about local ids.
int LocateMount(const QString &mount) const
Find the id of a device.
static ImageManagerFe & getInstance()
Get Frontend Gallery.
QStringList HandleTransform(int transform, const QString &ids) const
Change orientation of pictures by applying a transformation.
QString CreateImport()
QHash< QString, ImagePtr > ImageHash
Definition: imagetypes.h:168
void RequestMetaData(int id)
Requests all exif/ffmpeg tags for an image, which returns by event.
int m_id
Uniquely identifies an image (file/dir).
Definition: imagetypes.h:88
QString GetHostName(void)
QStringList HandleIgnore(const QString &exclusions) const
Updates exclusion list for images.
QString m_comment
User comment, from Exif metadata.
Definition: imagetypes.h:109
QString CrumbName(ImageItemK &im, bool getPath=false) const
Return a displayable name (with optional path) for an image.
ImageItem * CreateItem(const QFileInfo &fi, int parentId, int devId, const QString &base) const
Construct a remote image from a file.
void SendEvent(const MythEvent &event)
~Device()
Delete device, its thumbnails and any imported images.
int m_size
Filesize (files only)
Definition: imagetypes.h:102
#define GALLERY_DB_ID
Definition: imagetypes.h:26
Device(QString name, QString mount, MythMediaDevice *media=nullptr, QTemporaryDir *import=nullptr)
static QStringList SupportedImages()
Return recognised pictures.
File size Smallest -> Largest.
Definition: imagetypes.h:51
static ImageMetaData * FromVideo(const QString &filePath)
Factory to retrieve metadata from videos.
MythMediaStatus getStatus() const
Definition: mythmedia.h:70
static QString PathOf(const QString &path)
Extracts path from a filepath.
Definition: imagemanager.h:140
#define DEVICE_INVALID
Definition: imagemanager.h:71
bool m_isHidden
If true, image won't be shown.
Definition: imagetypes.h:112
#define IMAGE_STORAGE_GROUP
Definition: imagemanager.h:63
StringMap GetDeviceDirs() const
Get all known devices.
Default local time.
Definition: mythdate.h:19
QList< ImagePtrK > ImageListK
Definition: imagetypes.h:173
void Close(bool eject=false)
Releases device.
#define LOG(_MASK_, _LEVEL_, _QSTRING_)
Definition: mythlogging.h:23