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)
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));
100  RemoveDirContents(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  foreach (Device *dev, 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  foreach (Device *dev, m_devices)
204  if (dev)
205  {
206  clear << dev->m_mount;
207  dev->RemoveThumbs();
208  }
209  }
210  else
211  {
212  // Remove single device & its thumbnails, optionally ejecting it
213  Device *dev = m_devices.take(devId);
214  if (dev)
215  {
216  if (action == "DEVICE EJECT")
217  dev->Close(true);
218  clear << dev->m_mount;
219  delete dev;
220  }
221  }
222  return clear;
223 }
224 
225 
231 int DeviceManager::LocateMount(const QString &mount) const
232 {
233  DeviceMap::const_iterator it = m_devices.constBegin();
234  while (it != m_devices.constEnd())
235  {
236  if (it.value()->m_mount == mount)
237  return it.key();
238  ++it;
239  }
240  return DEVICE_INVALID;
241 }
242 
243 
246 {
248  foreach (int id, m_devices.keys())
249  {
250  Device *dev = m_devices.value(id);
251  if (dev)
252  paths.insert(id, dev->m_mount);
253  }
254  return paths;
255 }
256 
257 
260 {
261  QList<int> absent;
262  foreach (int id, m_devices.keys())
263  {
264  Device *dev = m_devices.value(id);
265  if (dev && !dev->isPresent())
266  absent << id;
267  }
268  return absent;
269 }
270 
271 
276  m_imageFileExt(SupportedImages()),
277  m_videoFileExt(SupportedVideos())
278 {
279  // Generate glob list from supported extensions
280  QStringList glob;
281  foreach (const QString &ext, m_imageFileExt + m_videoFileExt)
282  glob << "*." + ext;
283 
284  // Apply filters to only detect image files
285  m_dirFilter.setNameFilters(glob);
286  m_dirFilter.setFilter(QDir::AllDirs | QDir::Files | QDir::Readable |
287  QDir::NoDotAndDotDot | QDir::NoSymLinks);
288 
289  // Sync files before dirs to improve thumb generation response
290  // Order by time (oldest first) - this determines the order thumbs appear
291  m_dirFilter.setSorting(QDir::DirsLast | QDir::Time | QDir::Reversed);
292 }
293 
299 {
300  // Determine supported picture formats from Qt
301  QStringList formats;
302  foreach (const QByteArray &ext, QImageReader::supportedImageFormats())
303  formats << QString(ext);
304  return formats;
305 }
306 
307 
313 {
314  // Determine supported video formats from MythVideo
315  QStringList formats;
318  for (auto p = faList.cbegin(); p != faList.cend(); ++p)
319  {
320  if (!p->use_default && p->playcommand == "Internal")
321  formats << QString(p->extension);
322  }
323  return formats;
324 }
325 
326 
335 ImageItem *ImageAdapterLocal::CreateItem(const QFileInfo &fi, int parentId,
336  int devId, const QString & /*base*/) const
337 {
338  auto *im = new ImageItem();
339 
340  im->m_parentId = parentId;
341  im->m_device = devId;
342  im->m_filePath = fi.absoluteFilePath();
343 
344  if (parentId == GALLERY_DB_ID)
345  {
346  // Import devices show time of import, other devices show 'last scan time'
347 #if QT_VERSION < QT_VERSION_CHECK(5,8,0)
348  im->m_date = im->m_filePath.contains(IMPORTDIR)
349  ? fi.lastModified().toTime_t()
350  : QDateTime::currentMSecsSinceEpoch() / 1000;
351 #else
352  im->m_date = im->m_filePath.contains(IMPORTDIR)
353  ? fi.lastModified().toSecsSinceEpoch()
354  : QDateTime::currentSecsSinceEpoch();
355 #endif
356  im->m_modTime = im->m_date;
357  im->m_type = kDevice;
358  return im;
359  }
360 
361 #if QT_VERSION < QT_VERSION_CHECK(5,8,0)
362  im->m_modTime = fi.lastModified().toTime_t();
363 #else
364  im->m_modTime = fi.lastModified().toSecsSinceEpoch();
365 #endif
366 
367  if (fi.isDir())
368  {
369  im->m_type = kDirectory;
370  return im;
371  }
372 
373  im->m_extension = fi.suffix().toLower();
374  im->m_type = GetImageType(im->m_extension);
375 
376  if (im->m_type == kUnknown)
377  {
378  delete im;
379  return nullptr;
380  }
381 
382  im->m_thumbPath = GetAbsThumbPath(ThumbDir(im->m_device), ThumbPath(*im));
383  im->m_size = fi.size();
384 
385  return im;
386 }
387 
388 
394 void ImageAdapterLocal::Notify(const QString &mesg,
395  const QStringList &extra)
396 {
397  QString host(gCoreContext->GetHostName());
398  gCoreContext->SendEvent(MythEvent(QString("%1 %2").arg(mesg, host), extra));
399 }
400 
401 
410 ImageItem *ImageAdapterSg::CreateItem(const QFileInfo &fi, int parentId,
411  int /*devId*/, const QString &base) const
412 {
413  auto *im = new ImageItem();
414 
415  im->m_device = 0;
416  im->m_parentId = parentId;
417 
418  if (parentId == GALLERY_DB_ID)
419  {
420  // All SG dirs map to a single Db dir
421  im->m_filePath = "";
422  im->m_type = kDevice;
423  im->m_date = QDateTime::currentMSecsSinceEpoch() / 1000;
424  im->m_modTime = im->m_date;
425  return im;
426  }
427 
428  // Strip SG path & leading / to leave a relative path
429  im->m_filePath = fi.absoluteFilePath().mid(base.size() + 1);
430 #if QT_VERSION < QT_VERSION_CHECK(5,8,0)
431  im->m_modTime = fi.lastModified().toTime_t();
432 #else
433  im->m_modTime = fi.lastModified().toSecsSinceEpoch();
434 #endif
435 
436  if (fi.isDir())
437  {
438  im->m_type = kDirectory;
439  return im;
440  }
441 
442  im->m_extension = fi.suffix().toLower();
443  im->m_type = GetImageType(im->m_extension);
444 
445  if (im->m_type == kUnknown)
446  {
447  delete im;
448  return nullptr;
449  }
450 
451  im->m_thumbPath = GetAbsThumbPath(ThumbDir(im->m_device), ThumbPath(*im));
452  im->m_size = fi.size();
453 
454  return im;
455 }
456 
457 
463 void ImageAdapterSg::Notify(const QString &mesg,
464  const QStringList &extra)
465 {
466  gCoreContext->SendEvent(MythEvent(mesg, extra));
467 }
468 
469 
475 {
476  StringMap map;
477  int i = 0;
478  foreach (const QString &path, m_sg.GetDirList())
479  map.insert(i++, path);
480  return map;
481 }
482 
483 
491 {
492  if (im->IsDevice())
493  return m_sg.FindNextDirMostFree();
494  return im->m_filePath.startsWith("/") ? im->m_filePath
495  : m_sg.FindFile(im->m_filePath);
496 }
497 
498 
499 // Database fields used by several image queries
500 #define DB_COLUMNS \
501 "file_id, filename, name, dir_id, type, modtime, size, " \
502 "extension, date, hidden, orientation, angle, path, zoom"
503 // Id, filepath, basename, parentId, type, modtime, size,
504 // extension, image date, hidden, orientation, cover id, comment, device id
505 
506 
512 template <class FS>
514 {
515  auto *im = new ImageItem(FS::ImageId(query.value(0).toInt()));
516 
517  // Ordered as per DB_COLUMNS
518  im->m_filePath = query.value(1).toString();
519  im->m_baseName = query.value(2).toString();
520  im->m_parentId = FS::ImageId(query.value(3).toInt());
521  im->m_type = query.value(4).toInt();
522  im->m_modTime = query.value(5).toInt();
523  im->m_size = query.value(6).toInt();
524  im->m_extension = query.value(7).toString();
525  im->m_date = query.value(8).toUInt();
526  im->m_isHidden = query.value(9).toBool();
527  im->m_orientation = query.value(10).toInt();
528  im->m_userThumbnail = FS::ImageId(query.value(11).toInt());
529  im->m_comment = query.value(12).toString();
530  im->m_device = query.value(13).toInt();
531  im->m_url = FS::MakeFileUrl(im->m_filePath);
532 
533  if (im->IsFile())
534  {
535  // Only pics/vids have thumbs
536  QString thumbPath(FS::ThumbPath(*im));
537  QString devPath(FS::ThumbDir(im->m_device));
538  QString url(FS::MakeThumbUrl(devPath, thumbPath));
539 
540  im->m_thumbPath = FS::GetAbsThumbPath(devPath, thumbPath);
541  im->m_thumbNails.append(qMakePair(im->m_id, url));
542  }
543  return im;
544 }
545 
546 
555 template <class FS>
556 int ImageDb<FS>::GetImages(const QString &ids, ImageList &files, ImageList &dirs,
557  const QString &refine) const
558 {
559  if (ids.isEmpty())
560  return 0;
561 
562  QString select = QString("file_id IN (%1) %2").arg(FS::DbIds(ids), refine);
563  return ReadImages(dirs, files, select);
564 }
565 
566 
575 template <class FS>
576 int ImageDb<FS>::GetChildren(QString ids, ImageList &files, ImageList &dirs,
577  const QString &refine) const
578 {
579  QString select = QString("dir_id IN (%1) %2").arg(FS::DbIds(ids), refine);
580  return ReadImages(dirs, files, select);
581 }
582 
583 
593 template <class FS>
595  ImageList &files, ImageList &dirs,
596  const QString &refine) const
597 {
598  MSqlQuery query(MSqlQuery::InitCon());
599  query.prepare(QString("SELECT " DB_COLUMNS " FROM %1 "
600  "WHERE (dir_id = :ID1 OR file_id = :ID2) "
601  "%2;").arg(m_table, refine));
602 
603  // Qt < 5.4 won't bind multiple occurrences
604  int dbId = FS::DbId(id);
605  query.bindValue(":ID1", dbId);
606  query.bindValue(":ID2", dbId);
607 
608  if (!query.exec())
609  {
610  MythDB::DBError(DBLOC, query);
611  return -1;
612  }
613  while (query.next())
614  {
615  ImagePtr im(CreateImage(query));
616 
617  if (im->IsFile())
618  files.append(im);
619  else if (im->m_id == id)
620  parent = im;
621  else
622  dirs.append(im);
623  }
624  return query.size();
625 }
626 
627 
635 template <class FS>
636 bool ImageDb<FS>::GetDescendants(const QString &ids,
637  ImageList &files, ImageList &dirs) const
638 {
639  if (ids.isEmpty())
640  return false;
641 
642  if (ReadImages(dirs, files, QString("file_id IN (%1)").arg(FS::DbIds(ids))) < 0)
643  return false;
644 
645  MSqlQuery query(MSqlQuery::InitCon());
646  QString sql =
647  QString("SELECT " DB_COLUMNS
648  ", LENGTH(filename) - LENGTH(REPLACE(filename, '/', ''))"
649  " AS depth "
650  "FROM %1 WHERE filename LIKE :PREFIX "
651  "ORDER BY depth;").arg(m_table);
652 
653  foreach (const ImagePtr &im1, dirs)
654  {
655  query.prepare(sql);
656  query.bindValue(":PREFIX", im1->m_filePath + "/%");
657 
658  if (!query.exec())
659  {
660  MythDB::DBError(DBLOC, query);
661  return false;
662  }
663 
664  while (query.next())
665  {
666  ImagePtr im2(CreateImage(query));
667  if (im2->IsDirectory())
668  dirs.append(im2);
669  else
670  files.append(im2);
671  }
672  }
673  return true;
674 }
675 
676 
684 template <class FS>
685 bool ImageDb<FS>::GetImageTree(int id, ImageList &files, const QString &refine) const
686 {
687  // Load starting children
688  ImageList dirs;
689  if (GetChildren(QString::number(id), files, dirs, refine) < 0)
690  return false;
691 
692  foreach (const ImagePtr &im, dirs)
693  if (!GetImageTree(im->m_id, files, refine))
694  return false;
695  return true;
696 }
697 
698 
704 template <class FS>
706 {
707  MSqlQuery query(MSqlQuery::InitCon());
708  query.prepare(QString("SELECT " DB_COLUMNS " FROM %1").arg(m_table));
709 
710  if (!query.exec())
711  {
712  MythDB::DBError(DBLOC, query);
713  return false;
714  }
715 
716  while (query.next())
717  {
718  ImagePtr im(CreateImage(query));
719  if (im->IsDirectory())
720  dirs.insert(im->m_filePath, im);
721  else
722  files.insert(im->m_filePath, im);
723  }
724  return true;
725 }
726 
727 
735 template <class FS>
736 void ImageDb<FS>::ClearDb(int devId, const QString &action)
737 {
738  if (action == "DEVICE CLOSE ALL")
739  // Retain Db images when closing UI
740  return;
741 
742  MSqlQuery query(MSqlQuery::InitCon());
743 
744  if (action == "DEVICE CLEAR ALL")
745  {
746  // Clear images from all devices. Reset auto-increment
747  query.prepare(QString("TRUNCATE TABLE %1;").arg(m_table));
748 
749  if (!query.exec())
750  MythDB::DBError(DBLOC, query);
751  }
752  else // Actions DEVICE REMOVE & DEVICE EJECT
753  {
754  // Delete all images of the device
755  query.prepare(QString("DELETE IGNORE FROM %1 WHERE zoom = :FS;").arg(m_table));
756  query.bindValue(":FS", devId);
757 
758  if (!query.exec())
759  MythDB::DBError(DBLOC, query);
760  }
761 }
762 
763 
771 template <class FS>
772 int ImageDb<FS>::InsertDbImage(ImageItemK &im, bool checkForDuplicate) const
773 {
774  MSqlQuery query(MSqlQuery::InitCon());
775 
776  if (checkForDuplicate)
777  {
778  query.prepare(QString("SELECT file_id FROM %1 WHERE filename = :NAME;")
779  .arg(m_table));
780 
781  query.bindValue(":NAME", im.m_filePath);
782 
783  if (!query.exec())
784  {
785  MythDB::DBError(DBLOC, query);
786  return -1;
787  }
788 
789  if (query.size() > 0)
790  {
791  LOG(VB_FILE, LOG_DEBUG, QString("Image: %1 already exists in Db")
792  .arg(im.m_filePath));
793  return query.value(0).toInt();
794  }
795  }
796 
797  query.prepare(QString("INSERT INTO %1 (" DB_COLUMNS ") VALUES (0, "
798  ":FILEPATH, :NAME, :PARENT, :TYPE, :MODTIME, "
799  ":SIZE, :EXTENSION, :DATE, :HIDDEN, :ORIENT, "
800  ":COVER, :COMMENT, :FS);").arg(m_table));
801 
802  query.bindValue(":FILEPATH", im.m_filePath);
803  query.bindValue(":NAME", FS::BaseNameOf(im.m_filePath));
804  query.bindValue(":FS", im.m_device);
805  query.bindValue(":PARENT", FS::DbId(im.m_parentId));
806  query.bindValue(":TYPE", im.m_type);
807  query.bindValue(":MODTIME", im.m_modTime);
808  query.bindValue(":SIZE", im.m_size);
809  query.bindValue(":EXTENSION", im.m_extension);
810  query.bindValue(":DATE", im.m_date);
811  query.bindValue(":ORIENT", im.m_orientation);
812  query.bindValue(":COMMENT", im.m_comment.isNull() ? "" : im.m_comment);
813  query.bindValue(":HIDDEN", im.m_isHidden);
814  query.bindValue(":COVER", FS::DbId(im.m_userThumbnail));
815 
816  if (query.exec())
817  return FS::ImageId(query.lastInsertId().toInt());
818 
819  MythDB::DBError(DBLOC, query);
820  return -1;
821 }
822 
823 
829 template <class FS>
831 {
832  MSqlQuery query(MSqlQuery::InitCon());
833  query.prepare(QString
834  ("UPDATE %1 SET "
835  "filename = :FILEPATH, name = :NAME, "
836  "dir_id = :PARENT, type = :TYPE, "
837  "modtime = :MODTIME, size = :SIZE, "
838  "extension = :EXTENSION, date = :DATE, zoom = :FS, "
839  "hidden = :HIDDEN, orientation = :ORIENT, "
840  "angle = :COVER, path = :COMMENT "
841  "WHERE file_id = :ID;").arg(m_table));
842 
843  query.bindValue(":ID", FS::DbId(im.m_id));
844  query.bindValue(":FILEPATH", im.m_filePath);
845  query.bindValue(":NAME", FS::BaseNameOf(im.m_filePath));
846  query.bindValue(":PARENT", FS::DbId(im.m_parentId));
847  query.bindValue(":TYPE", im.m_type);
848  query.bindValue(":MODTIME", im.m_modTime);
849  query.bindValue(":SIZE", im.m_size);
850  query.bindValue(":EXTENSION", im.m_extension);
851  query.bindValue(":DATE", im.m_date);
852  query.bindValue(":FS", im.m_device);
853  query.bindValue(":HIDDEN", im.m_isHidden);
854  query.bindValue(":ORIENT", im.m_orientation);
855  query.bindValue(":COVER", FS::DbId(im.m_userThumbnail));
856  query.bindValue(":COMMENT", im.m_comment.isNull() ? "" : im.m_comment);
857 
858  if (query.exec())
859  return true;
860 
861  MythDB::DBError(DBLOC, query);
862  return false;
863 }
864 
865 
872 template <class FS>
873 QStringList ImageDb<FS>::RemoveFromDB(const ImageList &imList) const
874 {
875  QStringList ids;
876  if (!imList.isEmpty())
877  {
878  foreach (const ImagePtr &im, imList)
879  ids << QString::number(FS::DbId(im->m_id));
880 
881  QString idents = ids.join(",");
882  MSqlQuery query(MSqlQuery::InitCon());
883  query.prepare(QString("DELETE IGNORE FROM %1 WHERE file_id IN (%2);")
884  .arg(m_table, idents));
885 
886  if (!query.exec())
887  {
888  MythDB::DBError(DBLOC, query);
889  return QStringList();
890  }
891  }
892  return ids;
893 }
894 
895 
902 template <class FS>
903 bool ImageDb<FS>::SetHidden(bool hide, QString ids) const
904 {
905  if (ids.isEmpty())
906  return false;
907 
908  MSqlQuery query(MSqlQuery::InitCon());
909 
910  query.prepare(QString("UPDATE %1 SET "
911  "hidden = :HIDDEN "
912  "WHERE file_id IN (%2);").arg(m_table, FS::DbIds(ids)));
913  query.bindValue(":HIDDEN", hide ? 1 : 0);
914 
915  if (query.exec())
916  return true;
917 
918  MythDB::DBError(DBLOC, query);
919  return false;
920 }
921 
922 
928 template <class FS>
929 bool ImageDb<FS>::SetCover(int dir, int id) const
930 {
931  MSqlQuery query(MSqlQuery::InitCon());
932 
933  query.prepare(QString("UPDATE %1 SET "
934  "angle = :COVER "
935  "WHERE file_id = :DIR").arg(m_table));
936  query.bindValue(":COVER", FS::DbId(id));
937  query.bindValue(":DIR", FS::DbId(dir));
938  \
939  if (query.exec())
940  return true;
941 
942  MythDB::DBError(DBLOC, query);
943  return false;
944 }
945 
946 
952 template <class FS>
953 bool ImageDb<FS>::SetOrientation(int id, int orientation) const
954 {
955  MSqlQuery query(MSqlQuery::InitCon());
956 
957  query.prepare(QString("UPDATE %1 SET ").arg(m_table) +
958  "orientation = :ORIENTATION "
959  "WHERE file_id = :ID");
960  query.bindValue(":ORIENTATION", orientation);
961  query.bindValue(":ID", FS::DbId(id));
962  \
963  if (query.exec())
964  return true;
965 
966  MythDB::DBError(DBLOC, query);
967  return false;
968 }
969 
970 
978 template <class FS>
980  const QString &selector) const
981 {
982  MSqlQuery query(MSqlQuery::InitCon());
983  query.prepare(QString("SELECT " DB_COLUMNS " FROM %1 WHERE %2")
984  .arg(m_table, selector));
985  if (!query.exec())
986  {
987  MythDB::DBError(DBLOC, query);
988  return -1;
989  }
990 
991  while (query.next())
992  {
993  ImagePtr im(CreateImage(query));
994 
995  if (im->IsFile())
996  files.append(im);
997  else
998  dirs.append(im);
999  }
1000  return query.size();
1001 }
1002 
1003 
1013 template <class FS>
1014 void ImageDb<FS>::GetDescendantCount(int id, bool all, int &dirs,
1015  int &pics, int &videos, int &sizeKb) const
1016 {
1017  QString whereClause;
1018  if (!all)
1019  {
1020  whereClause = "WHERE filename LIKE "
1021  "( SELECT CONCAT(filename, '/%') "
1022  " FROM %2 WHERE file_id = :ID);";
1023  }
1024 
1025  MSqlQuery query(MSqlQuery::InitCon());
1026  query.prepare(QString("SELECT SUM(type <= :FLDR) AS Fldr, "
1027  " SUM(type = :PIC) AS Pics, "
1028  " SUM(type = :VID) AS Vids, "
1029  " SUM(size / 1024) "
1030  "FROM %2 %1;").arg(whereClause).arg(m_table));
1031 
1032  query.bindValue(":FLDR", kDirectory);
1033  query.bindValue(":PIC", kImageFile);
1034  query.bindValue(":VID", kVideoFile);
1035  if (!all)
1036  query.bindValue(":ID", FS::DbId(id));
1037 
1038  if (!query.exec())
1039  {
1040  MythDB::DBError(DBLOC, query);
1041  }
1042  else if (query.next())
1043  {
1044  dirs += query.value(0).toInt();
1045  pics += query.value(1).toInt();
1046  videos += query.value(2).toInt();
1047  sizeKb += query.value(3).toInt();
1048  }
1049 }
1050 
1051 
1056 {
1057  // Be has a single SG device
1059 }
1060 
1061 
1066  : ImageDb(QString("`%1_%2`").arg(DB_TABLE, gCoreContext->GetHostName())),
1067  m_DbExists(false)
1068 {
1069  // Remove any table leftover from a previous FE crash
1070  DropTable();
1071 }
1072 
1073 
1078 {
1079  MSqlQuery query(MSqlQuery::InitCon());
1080  query.prepare(QString("DROP TABLE IF EXISTS %1;").arg(m_table));
1081  if (query.exec())
1082  m_DbExists = false;
1083  else
1084  MythDB::DBError(DBLOC, query);
1085 }
1086 
1087 
1092 {
1093  if (m_DbExists)
1094  return true;
1095 
1096  MSqlQuery query(MSqlQuery::InitCon());
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  }
1111  MythDB::DBError(DBLOC, query);
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  foreach (const QString &def, 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  foreach (const ImagePtr &im, 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  foreach (ImagePtr im, 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  foreach (const QString &relPath, 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  foreach (const ImagePtrK &im, 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  // Use saved settings
1957  (gCoreContext->GetNumSetting("GalleryImageOrder"),
1958  gCoreContext->GetNumSetting("GalleryDirOrder"),
1959  gCoreContext->GetBoolSetting("GalleryShowHidden"),
1960  gCoreContext->GetNumSetting("GalleryShowType"),
1961  gCoreContext->GetSetting("GalleryDateFormat"));
1962  return *s_instance;
1963 }
1964 
1965 
1974 void ImageManagerFe::CreateThumbnails(const ImageIdList &ids, bool forFolder)
1975 {
1976  // Split images into <locals, remotes>
1977  StringPair lists = ImageItem::PartitionIds(ids);
1978 
1979  if (!lists.second.isEmpty())
1980  {
1981  LOG(VB_FILE, LOG_DEBUG, LOC +
1982  QString("Sending CREATE_THUMBNAILS %1 (forFolder %2)")
1983  .arg(lists.second).arg(forFolder));
1984 
1985  QStringList message;
1986  message << QString::number(forFolder) << lists.second;
1987  gCoreContext->SendEvent(MythEvent("CREATE_THUMBNAILS", message));
1988  }
1989 
1990  if (!lists.first.isEmpty())
1991  {
1992  LOG(VB_FILE, LOG_DEBUG, LOC +
1993  QString("Creating local thumbnails %1 (forFolder %2)")
1994  .arg(lists.first).arg(forFolder));
1995 
1996  QStringList message;
1997  message << QString::number(forFolder) << lists.first;
1998  HandleCreateThumbnails(message);
1999  }
2000 }
2001 
2002 
2009 QString ImageManagerFe::ScanImagesAction(bool start, bool local)
2010 {
2011  QStringList command;
2012  command << (start ? "START" : "STOP");
2013 
2014  if (!local)
2015  {
2016  command.push_front("IMAGE_SCAN");
2017  bool ok = gCoreContext->SendReceiveStringList(command, true);
2018  return ok ? "" : command[1];
2019  }
2020 
2021  // Create database on first scan
2022  if (!CreateTable())
2023  return "Couldn't create database";
2024 
2025  QStringList err = HandleScanRequest(command[0]);
2026  return err[0] == "OK" ? "" : err[1];
2027 }
2028 
2029 
2036 {
2037  QStringList strList;
2038  strList << "IMAGE_SCAN" << "QUERY";
2039 
2040  if (!gCoreContext->SendReceiveStringList(strList))
2041  {
2042  LOG(VB_GENERAL, LOG_ERR, LOC + QString("Scan query failed : %1")
2043  .arg(strList.join(",")));
2044  }
2045  return strList;
2046 }
2047 
2048 
2055 QString ImageManagerFe::HideFiles(bool hidden, const ImageIdList &ids)
2056 {
2057  // Split images into <locals, remotes>
2058  StringPair lists = ImageItem::PartitionIds(ids);
2059  QString result = "";
2060 
2061  if (!lists.second.isEmpty())
2062  {
2063  QStringList message;
2064  message << "IMAGE_HIDE" << QString::number(hidden) << lists.second;
2065 
2066  if (!gCoreContext->SendReceiveStringList(message, true))
2067  result = message[1];
2068  }
2069 
2070  if (!lists.first.isEmpty())
2071  {
2072  QStringList err = HandleHide(hidden, lists.first);
2073  if (err[0] != "OK")
2074  result = err[1];
2075  }
2076  return result;
2077 }
2078 
2079 
2087  const ImageIdList &ids)
2088 {
2089  // Split images into <locals, remotes>
2090  StringPair lists = ImageItem::PartitionIds(ids);
2091  QString result = "";
2092 
2093  if (!lists.second.isEmpty())
2094  {
2095  QStringList message;
2096  message << "IMAGE_TRANSFORM" << QString::number(transform) << lists.second;
2097 
2098  if (!gCoreContext->SendReceiveStringList(message, true))
2099  result = message[1];
2100  }
2101 
2102  if (!lists.first.isEmpty())
2103  {
2104  QStringList err = HandleTransform(transform, lists.first);
2105  if (err[0] != "OK")
2106  result = err[1];
2107  }
2108  return result;
2109 }
2110 
2111 
2118 QString ImageManagerFe::SetCover(int parent, int cover)
2119 {
2120  if (!ImageItem::IsLocalId(parent))
2121  {
2122  QStringList message;
2123  message << "IMAGE_COVER" << QString::number(parent) << QString::number(cover);
2124 
2125  bool ok = gCoreContext->SendReceiveStringList(message, true);
2126  return ok ? "" : message[1];
2127  }
2128 
2129  QStringList err = HandleCover(parent, cover);
2130  return err[0] == "OK" ? "" : err[1];
2131 }
2132 
2133 
2139 {
2140  if (ImageItem::IsLocalId(id))
2141  HandleGetMetadata(QString::number(id));
2142  else
2143  gCoreContext->SendEvent(MythEvent("IMAGE_GET_METADATA", QString::number(id)));
2144 }
2145 
2146 
2149 {
2150  QStringList message("IMAGE_SCAN");
2151  message << "DEVICE CLEAR ALL";
2152  gCoreContext->SendReceiveStringList(message, true);
2153 }
2154 
2155 
2162 QString ImageManagerFe::IgnoreDirs(const QString &excludes)
2163 {
2164  QStringList message("IMAGE_IGNORE");
2165  message << excludes;
2166  bool ok = gCoreContext->SendReceiveStringList(message, true);
2167  return ok ? "" : message[1];
2168 }
2169 
2170 
2178 QString ImageManagerFe::MakeDir(int parent, const QStringList &names, bool rescan)
2179 {
2180  QString destId = QString::number(parent);
2181 
2182  if (!ImageItem::IsLocalId(parent))
2183  {
2184  QStringList message("IMAGE_CREATE_DIRS");
2185  message << destId << QString::number(rescan) << names;
2186  bool ok = gCoreContext->SendReceiveStringList(message, true);
2187  return ok ? "" : message[1];
2188  }
2189  QStringList err = HandleDirs(destId, rescan, names);
2190  return (err[0] == "OK") ? "" : err[1];
2191 }
2192 
2193 
2200 QString ImageManagerFe::RenameFile(const ImagePtrK& im, const QString &name)
2201 {
2202  if (!im->IsLocal())
2203  {
2204  QStringList message("IMAGE_RENAME");
2205  message << QString::number(im->m_id) << name;
2206  bool ok = gCoreContext->SendReceiveStringList(message, true);
2207  return ok ? "" : message[1];
2208  }
2209  QStringList err = HandleRename(QString::number(im->m_id), name);
2210  return (err[0] == "OK") ? "" : err[1];
2211 }
2212 
2213 
2220 QString ImageManagerFe::CreateImages(int destId, const ImageListK &images)
2221 {
2222  if (images.isEmpty())
2223  return "";
2224 
2225  // Define field seperator & include it in message
2226  const QString seperator("...");
2227  QStringList imageDefs(seperator);
2228  ImageIdList ids;
2229  foreach (const ImagePtrK &im, images)
2230  {
2231  ids << im->m_id;
2232 
2233  // Copies preserve hide state, orientation & cover
2234  QStringList aDef;
2235  aDef << QString::number(im->m_id)
2236  << QString::number(im->m_type)
2237  << im->m_filePath
2238  << QString::number(im->m_isHidden)
2239  << QString::number(im->m_orientation)
2240  << QString::number(im->m_userThumbnail);
2241 
2242  imageDefs << aDef.join(seperator);
2243  }
2244 
2245  // Images are either all local or all remote
2246  if (ImageItem::IsLocalId(destId))
2247  {
2248  QStringList err = HandleDbCreate(imageDefs);
2249  return (err[0] == "OK") ? "" : err[1];
2250  }
2251  imageDefs.prepend("IMAGE_COPY");
2252  bool ok = gCoreContext->SendReceiveStringList(imageDefs, true);
2253  return ok ? "" : imageDefs[1];
2254 }
2255 
2256 
2264 QString ImageManagerFe::MoveDbImages(const ImagePtrK& destDir, ImageListK &images,
2265  const QString &srcPath)
2266 {
2267  QStringList idents;
2268  foreach (const ImagePtrK &im, images)
2269  idents << QString::number(im->m_id);
2270 
2271  // Images are either all local or all remote
2272  if (destDir->IsLocal())
2273  {
2274  QStringList err = HandleDbMove(idents.join(","), srcPath,
2275  destDir->m_filePath);
2276  return (err[0] == "OK") ? "" : err[1];
2277  }
2278 
2279  QStringList message("IMAGE_MOVE");
2280  message << idents.join(",") << srcPath << destDir->m_filePath;
2281  bool ok = gCoreContext->SendReceiveStringList(message, true);
2282  return ok ? "" : message[1];
2283 }
2284 
2285 
2292 {
2293  StringPair lists = ImageItem::PartitionIds(ids);
2294 
2295  QString result = "";
2296  if (!lists.second.isEmpty())
2297  {
2298  QStringList message("IMAGE_DELETE");
2299  message << lists.second;
2300 
2301  bool ok = gCoreContext->SendReceiveStringList(message, true);
2302  if (!ok)
2303  result = message[1];
2304  }
2305  if (!lists.first.isEmpty())
2306  {
2307  QStringList err = HandleDelete(lists.first);
2308  if (err[0] != "OK")
2309  result = err[1];
2310  }
2311  return result;
2312 }
2313 
2314 
2322 {
2323  if (im->m_id == GALLERY_DB_ID)
2324  return "";
2325 
2326 #if QT_VERSION < QT_VERSION_CHECK(5,8,0)
2327  uint secs = 0;
2328 #else
2329  qint64 secs = 0;
2330 #endif
2332 
2333  if (im->m_date > 0)
2334  {
2335  secs = im->m_date;
2336  format |= MythDate::kTime;
2337  }
2338  else
2339  secs = im->m_modTime;
2340 
2341 #if QT_VERSION < QT_VERSION_CHECK(5,8,0)
2342  return MythDate::toString(QDateTime::fromTime_t(secs), format);
2343 #else
2344  return MythDate::toString(QDateTime::fromSecsSinceEpoch(secs), format);
2345 #endif
2346 }
2347 
2348 
2355 QString ImageManagerFe::ShortDateOf(const ImagePtrK& im) const
2356 {
2357  if (im->m_id == GALLERY_DB_ID)
2358  return "";
2359 
2360 #if QT_VERSION < QT_VERSION_CHECK(5,8,0)
2361  uint secs(im->m_date > 0 ? im->m_date : im->m_modTime);
2362  return QDateTime::fromTime_t(secs).date().toString(m_dateFormat);
2363 #else
2364  qint64 secs(im->m_date > 0 ? im->m_date : im->m_modTime);
2365  return QDateTime::fromSecsSinceEpoch(secs).date().toString(m_dateFormat);
2366 #endif
2367 }
2368 
2369 
2376 {
2377  if (im.m_id == GALLERY_DB_ID)
2378  return tr("Gallery");
2379  if (im.m_id == PHOTO_DB_ID)
2380  return tr("Photographs");
2381  return im.IsLocal() ? DeviceName(im.m_device)
2382  : m_remote->DeviceName(im.m_device);
2383 }
2384 
2385 
2393 QString ImageManagerFe::CrumbName(ImageItemK &im, bool getPath) const
2394 {
2395  if (im.IsDevice())
2396  return DeviceCaption(im);
2397 
2398  if (!getPath)
2399  return im.m_baseName;
2400 
2401  QString dev;
2402  QString path(im.m_filePath);
2403 
2404  if (im.IsLocal())
2405  {
2406  // Replace local mount path with device name
2407  path.remove(0, DeviceMount(im.m_device).size());
2408  dev = DeviceName(im.m_device);
2409  }
2410  return dev + path.replace("/", " > ");
2411 }
2412 
2413 
2414 void ImageManagerFe::CloseDevices(int devId, bool eject)
2415 {
2416  QString reason = (devId == DEVICE_INVALID)
2417  ? "DEVICE CLOSE ALL"
2418  : eject ? "DEVICE EJECT" : "DEVICE REMOVE";
2419  HandleScanRequest(reason, devId);
2420 }
2421 
2422 
2428 {
2430  if (!monitor)
2431  return false;
2432 
2433  // Detect all local media
2434  QList<MythMediaDevice*> devices
2436 
2437  foreach (MythMediaDevice* dev, devices)
2438  {
2439  if (monitor->ValidateAndLock(dev) && dev->isUsable())
2440  OpenDevice(dev->getDeviceModel(), dev->getMountPath(), dev);
2441  else
2442  monitor->Unlock(dev);
2443  }
2444 
2445  if (DeviceCount() > 0)
2446  {
2447  // Close devices that are no longer present
2448  foreach (int devId, GetAbsentees())
2449  CloseDevices(devId);
2450 
2451  // Start local scan
2452  QString err = ScanImagesAction(true, true);
2453  if (!err.isEmpty())
2454  LOG(VB_GENERAL, LOG_ERR, LOC + err);
2455  }
2456  return DeviceCount() > 0;
2457 }
2458 
2459 
2465 {
2467 
2468  if (!event || !monitor)
2469  return;
2470 
2471  MythMediaDevice *dev = event->getDevice();
2472  if (!dev)
2473  return;
2474 
2475  MythMediaType type = dev->getMediaType();
2476  MythMediaStatus status = dev->getStatus();
2477 
2478  LOG(VB_FILE, LOG_DEBUG, LOC +
2479  QString("Media event for %1 (%2) at %3, type %4, status %5 (was %6)")
2480  .arg(dev->getDeviceModel(), dev->getVolumeID(), dev->getMountPath())
2481  .arg(type).arg(status).arg(event->getOldStatus()));
2482 
2484  {
2485  LOG(VB_FILE, LOG_DEBUG, LOC +
2486  QString("Ignoring event - wrong type %1").arg(type));
2487  return;
2488  }
2489 
2490  if (status == MEDIASTAT_USEABLE || status == MEDIASTAT_MOUNTED)
2491  {
2492  // New device. Lock it & scan
2493  if (monitor->ValidateAndLock(dev))
2494  {
2495  OpenDevice(dev->getDeviceModel(), dev->getMountPath(), dev);
2496  ScanImagesAction(true, true);
2497  }
2498  else
2499  monitor->Unlock(dev);
2500  return;
2501  }
2502 
2503  // Device has disappeared
2504  int devId = LocateMount(dev->getMountPath());
2505  if (devId != DEVICE_INVALID)
2506  CloseDevices(devId);
2507 }
2508 
2509 
2511 {
2512  auto *tmp = new QTemporaryDir(QDir::tempPath() % "/" IMPORTDIR "-XXXXXX");
2513  if (!tmp->isValid())
2514  {
2515  delete tmp;
2516  return "";
2517  }
2518 
2519  QString time(QDateTime::currentDateTime().toString("mm:ss"));
2520  OpenDevice("Import " + time, tmp->path(), nullptr, tmp);
2521  return tmp->path();
2522 }
2523 
2524 
2525 // Must define the valid template implementations to generate code for the
2526 // instantiations (as they are defined in the cpp rather than header).
2527 // Otherwise the linker will fail with undefined references...
2528 template class ImageDb<ImageAdapterSg>;
2529 template class ImageDb<ImageAdapterLocal>;
2530 template class ImageHandler<ImageDbSg>;
2531 template class ImageHandler<ImageDbLocal>;
MythMediaType getMediaType() const
Definition: mythmedia.h:91
void DropTable()
Remove local image table.
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:782
A video.
Definition: imagetypes.h:39
static QString FormatSize(int sizeKib)
Definition: imagemanager.h:139
QString DeviceName(int devId) const
Get model name of the device.
QSharedPointer< ImageItem > ImagePtr
Definition: imagetypes.h:173
QStringList HandleDirs(const QString &, bool rescan, const QStringList &relPaths) const
Creates new image directories.
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:863
QStringList GetDirList(void) const
Definition: storagegroup.h:23
static Device kNullDevice
Abstract class for image metadata.
Definition: imagemetadata.h:95
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:58
VERBOSE_PREAMBLE Most true
Definition: verbosedefs.h:91
bool RemoveFromDB(Bookmark *site)
QString Description()
Generate text description of orientation.
QString ShortDateOf(const ImagePtrK &) const
Return a short datestamp for thumbnail captions.
QStringList HandleDbMove(const QString &, const QString &, QString) const
Updates images that have been renamed.
int m_dirOrder
Display ordering of dirs.
Definition: imagemanager.h:436
#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:439
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:510
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:144
The image manager for use by Frontends.
Definition: imagemanager.h:452
qint64 m_date
Image creation date, from Exif metadata.
Definition: imagetypes.h:114
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:100
const association_list & getList() const
Definition: dbaccess.cpp:807
QSqlQuery wrapper that fetches a DB connection from the connection pool.
Definition: mythdbcon.h:125
QStringList HandleGetMetadata(const QString &) const
Read meta data for an image.
QString MakeDir(int, const QStringList &names, bool rescan=true)
Create directories.
#define RESULT_ERR(ERR, MESG)
Database API.
Definition: imagemanager.h:270
Manages a collection of images.
int size(void) const
Definition: mythdbcon.h:203
#define RESULT_OK(MESG)
#define EXIF_MYTH_SIZE
Definition: imagemetadata.h:37
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:148
QDir m_dirFilter
A pre-configured dir for reading image/video files.
Definition: imagemanager.h:171
int m_parentId
Id of parent dir.
Definition: imagetypes.h:103
ImageDbSg * m_remote
Remote database access.
Definition: imagemanager.h:434
Show Pictures & Videos.
Definition: imagemanager.h:74
std::vector< file_association > association_list
Definition: dbaccess.h:153
QString m_refineClause
SQL clause for image filtering/ordering.
Definition: imagemanager.h:440
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.
bool m_showHidden
Whether hidden images are displayed.
Definition: imagemanager.h:438
ImageManagerFe(int order, int dirOrder, bool showAll, int showType, QString dateFormat)
Definition: imagemanager.h:497
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...
bool isImport() const
QStringList CloseDevices(int devId, const QString &action)
Remove a device (or all devices)
bool IsDevice() const
Definition: imagetypes.h:131
const char * formats[8]
Definition: vbilut.cpp:190
StorageGroup m_sg
Images storage group.
Definition: imagemanager.h:262
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:134
static guint32 * tmp
Definition: goom_core.c:35
Exif date Latest -> Earliest.
Definition: imagetypes.h:54
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:179
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:101
bool isPresent() const
void RemoveFiles(ImageList &) const
Deletes images and dirs from the filesystem.
QStringList HandleDelete(const QString &) const
Deletes images/dirs.
The image manager to be used by the Backend.
Definition: imagemanager.h:374
MythMediaStatus getOldStatus(void) const
Definition: mythmedia.h:189
QString GetConfDir(void)
Definition: mythdirs.cpp:224
QVariant value(int i) const
Definition: mythdbcon.h:198
Hide videos.
Definition: imagemanager.h:75
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:121
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:42
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:173
int m_fileOrder
Display ordering of pics/videos.
Definition: imagemanager.h:437
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:387
This class is used as a container for messages.
Definition: mythevent.h:16
#define TEMP_SUBDIR
Definition: imagemanager.h:61
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
VERBOSE_PREAMBLE false
Definition: verbosedefs.h:85
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:139
#define EXIF_MYTH_ORIENT
Definition: imagemetadata.h:38
QVariant lastInsertId()
Return the id of the last inserted row.
Definition: mythdbcon.cpp:887
ImageAdapterBase()
Constructor.
static void clear(SettingsMap &cache, SettingsMap &overrides, const QString &myKey)
Definition: mythdb.cpp:836
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:161
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
QStringList HandleCreateThumbnails(const QStringList &) const
Creates thumbnails on-demand.
QStringList HandleTransform(int, const QString &) const
Change orientation of pictures by applying a transformation.
#define THUMBNAIL_SUBDIR
Definition: imagemanager.h:63
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.
QString CreateImages(int, const ImageListK &images)
Copies database images (but not the files themselves).
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.
int Transform(int)
Adjust orientation to apply a transform to an image.
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:132
QString FindNextDirMostFree(void)
Reflect about horizontal axis.
Definition: imagemetadata.h:47
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:507
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.
qint64 m_modTime
Filesystem modified datestamp.
Definition: imagetypes.h:108
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:155
QString m_table
Db table name.
Definition: imagemanager.h:306
static MSqlQueryInfo InitCon(ConnectionReuse=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:137
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:116
QString m_baseName
File/Dir name with extension (no path)
Definition: imagetypes.h:99
DeviceMap m_devices
Device store.
Definition: imagemanager.h:115
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:174
#define EXIF_MYTH_PATH
Definition: imagemetadata.h:35
ImageDbSg()
SG database constructor.
static FileAssociations & getFileAssociation()
Definition: dbaccess.cpp:832
void DeviceEvent(MythMediaEvent *event)
Manage events for local devices.
Task to read all metadata from file.
A picture.
Definition: imagetypes.h:38
QStringList HandleRename(const QString &, const QString &) const
Change name of an image/dir.
QString DeleteFiles(const ImageIdList &)
Delete images.
static MThreadPool * globalInstance(void)
QStringList HandleDbCreate(QStringList) const
Creates images for files created by a copy operation.
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:30
bool prepare(const QString &query)
QSqlQuery::prepare() is not thread safe in Qt <= 3.3.2.
Definition: mythdbcon.cpp:807
QList< int > ImageIdList
Definition: imagetypes.h:59
#define LOG(_MASK_, _LEVEL_, _STRING_)
Definition: mythlogging.h:41
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.
static QString LongDateOf(const ImagePtrK &)
Return a timestamp/datestamp for an image or dir.
QString MoveDbImages(const ImagePtrK &destDir, ImageListK &images, const QString &)
Moves database images (but not the files themselves).
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:175
int m_device
Id of media device. Always 0 (SG) for remotes, 1+ for local devices.
Definition: imagetypes.h:102
void CloseDevices(int devId=DEVICE_INVALID, bool eject=false)
Client request to display a directory thumbnail.
Definition: imagethumbs.h:31
void RemoveThumbs(void)
Delete thumbnails associated with device.
#define LOC
bool SetOrientation(int id, int orientation) const
Sets image orientation in Db.
#define EXIF_MYTH_HOST
Definition: imagemetadata.h:34
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.
bool isUsable() const
Is this device "ready", for a plugin to access?
Definition: mythmedia.h:84
static QStringList ScanQuery()
Returns storage group scanner status.
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:104
#define EXIF_MYTH_NAME
Definition: imagemetadata.h:36
#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.
ImageDbLocal()
Local database constructor.
Hide pictures.
Definition: imagemanager.h:76
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:96
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 HandleCover(int, int) const
Updates/resets cover thumbnail for an image dir.
QString CreateImport()
QStringList HandleScanRequest(const QString &, int devId=DEVICE_INVALID) const
Process scan requests.
QHash< QString, ImagePtr > ImageHash
Definition: imagetypes.h:175
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:96
QString GetHostName(void)
QString m_comment
User comment, from Exif metadata.
Definition: imagetypes.h:117
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.
QStringList HandleHide(bool, const QString &ids) const
Hides/unhides images/dirs.
int m_size
Filesize (files only)
Definition: imagetypes.h:110
#define GALLERY_DB_ID
Definition: imagetypes.h:26
QStringList HandleIgnore(const QString &) const
Updates exclusion list for images.
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:136
#define DEVICE_INVALID
Definition: imagemanager.h:65
bool m_isHidden
If true, image won't be shown.
Definition: imagetypes.h:120
#define IMAGE_STORAGE_GROUP
Definition: imagemanager.h:57
StringMap GetDeviceDirs() const
Get all known devices.
Default local time.
Definition: mythdate.h:19
QList< ImagePtrK > ImageListK
Definition: imagetypes.h:180
void Close(bool eject=false)
Releases device.