/
VideoDatabase.cpp
11086 lines (9758 loc) · 401 KB
/
VideoDatabase.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2016-2018 Team Kodi
* This file is part of Kodi - https://kodi.tv
*
* SPDX-License-Identifier: GPL-2.0-or-later
* See LICENSES/README.md for more information.
*/
#include "VideoDatabase.h"
#include "Application.h"
#include "FileItem.h"
#include "GUIInfoManager.h"
#include "GUIPassword.h"
#include "ServiceBroker.h"
#include "TextureCache.h"
#include "URL.h"
#include "Util.h"
#include "VideoInfoScanner.h"
#include "XBDateTime.h"
#include "addons/AddonManager.h"
#include "dbwrappers/dataset.h"
#include "dialogs/GUIDialogExtendedProgressBar.h"
#include "dialogs/GUIDialogKaiToast.h"
#include "dialogs/GUIDialogProgress.h"
#include "dialogs/GUIDialogYesNo.h"
#include "filesystem/Directory.h"
#include "filesystem/File.h"
#include "filesystem/MultiPathDirectory.h"
#include "filesystem/PluginDirectory.h"
#include "filesystem/StackDirectory.h"
#include "guilib/GUIComponent.h"
#include "guilib/GUIWindowManager.h"
#include "guilib/LocalizeStrings.h"
#include "guilib/guiinfo/GUIInfoLabels.h"
#include "interfaces/AnnouncementManager.h"
#include "messaging/helpers/DialogOKHelper.h"
#include "music/Artist.h"
#include "playlists/SmartPlayList.h"
#include "profiles/ProfileManager.h"
#include "settings/AdvancedSettings.h"
#include "settings/MediaSettings.h"
#include "settings/MediaSourceSettings.h"
#include "settings/Settings.h"
#include "settings/SettingsComponent.h"
#include "storage/MediaManager.h"
#include "utils/FileUtils.h"
#include "utils/GroupUtils.h"
#include "utils/LabelFormatter.h"
#include "utils/StringUtils.h"
#include "utils/URIUtils.h"
#include "utils/Variant.h"
#include "utils/XMLUtils.h"
#include "utils/log.h"
#include "video/VideoDbUrl.h"
#include "video/VideoInfoTag.h"
#include "video/VideoLibraryQueue.h"
#include "video/windows/GUIWindowVideoBase.h"
#include <algorithm>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <unordered_set>
using namespace dbiplus;
using namespace XFILE;
using namespace VIDEO;
using namespace ADDON;
using namespace KODI::MESSAGING;
using namespace KODI::GUILIB;
//********************************************************************************************************************************
CVideoDatabase::CVideoDatabase(void) = default;
//********************************************************************************************************************************
CVideoDatabase::~CVideoDatabase(void) = default;
//********************************************************************************************************************************
bool CVideoDatabase::Open()
{
return CDatabase::Open(CServiceBroker::GetSettingsComponent()->GetAdvancedSettings()->m_databaseVideo);
}
void CVideoDatabase::CreateTables()
{
CLog::Log(LOGINFO, "create bookmark table");
m_pDS->exec("CREATE TABLE bookmark ( idBookmark integer primary key, idFile integer, timeInSeconds double, totalTimeInSeconds double, thumbNailImage text, player text, playerState text, type integer)\n");
CLog::Log(LOGINFO, "create settings table");
m_pDS->exec("CREATE TABLE settings ( idFile integer, Deinterlace bool,"
"ViewMode integer,ZoomAmount float, PixelRatio float, VerticalShift float, AudioStream integer, SubtitleStream integer,"
"SubtitleDelay float, SubtitlesOn bool, Brightness float, Contrast float, Gamma float,"
"VolumeAmplification float, AudioDelay float, ResumeTime integer,"
"Sharpness float, NoiseReduction float, NonLinStretch bool, PostProcess bool,"
"ScalingMethod integer, DeinterlaceMode integer, StereoMode integer, StereoInvert bool, VideoStream integer,"
"TonemapMethod integer, TonemapParam float, Orientation integer, CenterMixLevel integer)\n");
CLog::Log(LOGINFO, "create stacktimes table");
m_pDS->exec("CREATE TABLE stacktimes (idFile integer, times text)\n");
CLog::Log(LOGINFO, "create genre table");
m_pDS->exec("CREATE TABLE genre ( genre_id integer primary key, name TEXT)\n");
m_pDS->exec("CREATE TABLE genre_link (genre_id integer, media_id integer, media_type TEXT)");
CLog::Log(LOGINFO, "create country table");
m_pDS->exec("CREATE TABLE country ( country_id integer primary key, name TEXT)");
m_pDS->exec("CREATE TABLE country_link (country_id integer, media_id integer, media_type TEXT)");
CLog::Log(LOGINFO, "create movie table");
std::string columns = "CREATE TABLE movie ( idMovie integer primary key, idFile integer";
for (int i = 0; i < VIDEODB_MAX_COLUMNS; i++)
columns += StringUtils::Format(",c{:02} text", i);
columns += ", idSet integer, userrating integer, premiered text)";
m_pDS->exec(columns);
CLog::Log(LOGINFO, "create actor table");
m_pDS->exec("CREATE TABLE actor ( actor_id INTEGER PRIMARY KEY, name TEXT, art_urls TEXT )");
m_pDS->exec("CREATE TABLE actor_link(actor_id INTEGER, media_id INTEGER, media_type TEXT, role TEXT, cast_order INTEGER)");
m_pDS->exec("CREATE TABLE director_link(actor_id INTEGER, media_id INTEGER, media_type TEXT)");
m_pDS->exec("CREATE TABLE writer_link(actor_id INTEGER, media_id INTEGER, media_type TEXT)");
CLog::Log(LOGINFO, "create path table");
m_pDS->exec(
"CREATE TABLE path ( idPath integer primary key, strPath text, strContent text, strScraper "
"text, strHash text, scanRecursive integer, useFolderNames bool, strSettings text, noUpdate "
"bool, exclude bool, allAudio bool, dateAdded text, idParentPath integer)");
CLog::Log(LOGINFO, "create files table");
m_pDS->exec("CREATE TABLE files ( idFile integer primary key, idPath integer, strFilename text, playCount integer, lastPlayed text, dateAdded text)");
CLog::Log(LOGINFO, "create tvshow table");
columns = "CREATE TABLE tvshow ( idShow integer primary key";
for (int i = 0; i < VIDEODB_MAX_COLUMNS; i++)
columns += StringUtils::Format(",c{:02} text", i);
columns += ", userrating integer, duration INTEGER)";
m_pDS->exec(columns);
CLog::Log(LOGINFO, "create episode table");
columns = "CREATE TABLE episode ( idEpisode integer primary key, idFile integer";
for (int i = 0; i < VIDEODB_MAX_COLUMNS; i++)
{
std::string column;
if ( i == VIDEODB_ID_EPISODE_SEASON || i == VIDEODB_ID_EPISODE_EPISODE || i == VIDEODB_ID_EPISODE_BOOKMARK)
column = StringUtils::Format(",c{:02} varchar(24)", i);
else
column = StringUtils::Format(",c{:02} text", i);
columns += column;
}
columns += ", idShow integer, userrating integer, idSeason integer)";
m_pDS->exec(columns);
CLog::Log(LOGINFO, "create tvshowlinkpath table");
m_pDS->exec("CREATE TABLE tvshowlinkpath (idShow integer, idPath integer)\n");
CLog::Log(LOGINFO, "create movielinktvshow table");
m_pDS->exec("CREATE TABLE movielinktvshow ( idMovie integer, IdShow integer)\n");
CLog::Log(LOGINFO, "create studio table");
m_pDS->exec("CREATE TABLE studio ( studio_id integer primary key, name TEXT)\n");
m_pDS->exec("CREATE TABLE studio_link (studio_id integer, media_id integer, media_type TEXT)");
CLog::Log(LOGINFO, "create musicvideo table");
columns = "CREATE TABLE musicvideo ( idMVideo integer primary key, idFile integer";
for (int i = 0; i < VIDEODB_MAX_COLUMNS; i++)
columns += StringUtils::Format(",c{:02} text", i);
columns += ", userrating integer, premiered text)";
m_pDS->exec(columns);
CLog::Log(LOGINFO, "create streaminfo table");
m_pDS->exec("CREATE TABLE streamdetails (idFile integer, iStreamType integer, "
"strVideoCodec text, fVideoAspect float, iVideoWidth integer, iVideoHeight integer, "
"strAudioCodec text, iAudioChannels integer, strAudioLanguage text, "
"strSubtitleLanguage text, iVideoDuration integer, strStereoMode text, strVideoLanguage text)");
CLog::Log(LOGINFO, "create sets table");
m_pDS->exec("CREATE TABLE sets ( idSet integer primary key, strSet text, strOverview text)");
CLog::Log(LOGINFO, "create seasons table");
m_pDS->exec("CREATE TABLE seasons ( idSeason integer primary key, idShow integer, season integer, name text, userrating integer)");
CLog::Log(LOGINFO, "create art table");
m_pDS->exec("CREATE TABLE art(art_id INTEGER PRIMARY KEY, media_id INTEGER, media_type TEXT, type TEXT, url TEXT)");
CLog::Log(LOGINFO, "create tag table");
m_pDS->exec("CREATE TABLE tag (tag_id integer primary key, name TEXT)");
m_pDS->exec("CREATE TABLE tag_link (tag_id integer, media_id integer, media_type TEXT)");
CLog::Log(LOGINFO, "create rating table");
m_pDS->exec("CREATE TABLE rating (rating_id INTEGER PRIMARY KEY, media_id INTEGER, media_type TEXT, rating_type TEXT, rating FLOAT, votes INTEGER)");
CLog::Log(LOGINFO, "create uniqueid table");
m_pDS->exec("CREATE TABLE uniqueid (uniqueid_id INTEGER PRIMARY KEY, media_id INTEGER, media_type TEXT, value TEXT, type TEXT)");
}
void CVideoDatabase::CreateLinkIndex(const char *table)
{
m_pDS->exec(PrepareSQL("CREATE UNIQUE INDEX ix_%s_1 ON %s (name(255))", table, table));
m_pDS->exec(PrepareSQL("CREATE UNIQUE INDEX ix_%s_link_1 ON %s_link (%s_id, media_type(20), media_id)", table, table, table));
m_pDS->exec(PrepareSQL("CREATE UNIQUE INDEX ix_%s_link_2 ON %s_link (media_id, media_type(20), %s_id)", table, table, table));
m_pDS->exec(PrepareSQL("CREATE INDEX ix_%s_link_3 ON %s_link (media_type(20))", table, table));
}
void CVideoDatabase::CreateForeignLinkIndex(const char *table, const char *foreignkey)
{
m_pDS->exec(PrepareSQL("CREATE UNIQUE INDEX ix_%s_link_1 ON %s_link (%s_id, media_type(20), media_id)", table, table, foreignkey));
m_pDS->exec(PrepareSQL("CREATE UNIQUE INDEX ix_%s_link_2 ON %s_link (media_id, media_type(20), %s_id)", table, table, foreignkey));
m_pDS->exec(PrepareSQL("CREATE INDEX ix_%s_link_3 ON %s_link (media_type(20))", table, table));
}
void CVideoDatabase::CreateAnalytics()
{
/* indexes should be added on any columns that are used in in */
/* a where or a join. primary key on a column is the same as a */
/* unique index on that column, so there is no need to add any */
/* index if no other columns are refered */
/* order of indexes are important, for an index to be considered all */
/* columns up to the column in question have to have been specified */
/* select * from foolink where foo_id = 1, can not take */
/* advantage of a index that has been created on ( bar_id, foo_id ) */
/* however an index on ( foo_id, bar_id ) will be considered for use */
CLog::Log(LOGINFO, "{} - creating indices", __FUNCTION__);
m_pDS->exec("CREATE INDEX ix_bookmark ON bookmark (idFile, type)");
m_pDS->exec("CREATE UNIQUE INDEX ix_settings ON settings ( idFile )\n");
m_pDS->exec("CREATE UNIQUE INDEX ix_stacktimes ON stacktimes ( idFile )\n");
m_pDS->exec("CREATE INDEX ix_path ON path ( strPath(255) )");
m_pDS->exec("CREATE INDEX ix_path2 ON path ( idParentPath )");
m_pDS->exec("CREATE INDEX ix_files ON files ( idPath, strFilename(255) )");
m_pDS->exec("CREATE UNIQUE INDEX ix_movie_file_1 ON movie (idFile, idMovie)");
m_pDS->exec("CREATE UNIQUE INDEX ix_movie_file_2 ON movie (idMovie, idFile)");
m_pDS->exec("CREATE UNIQUE INDEX ix_tvshowlinkpath_1 ON tvshowlinkpath ( idShow, idPath )\n");
m_pDS->exec("CREATE UNIQUE INDEX ix_tvshowlinkpath_2 ON tvshowlinkpath ( idPath, idShow )\n");
m_pDS->exec("CREATE UNIQUE INDEX ix_movielinktvshow_1 ON movielinktvshow ( idShow, idMovie)\n");
m_pDS->exec("CREATE UNIQUE INDEX ix_movielinktvshow_2 ON movielinktvshow ( idMovie, idShow)\n");
m_pDS->exec("CREATE UNIQUE INDEX ix_episode_file_1 on episode (idEpisode, idFile)");
m_pDS->exec("CREATE UNIQUE INDEX id_episode_file_2 on episode (idFile, idEpisode)");
std::string createColIndex =
StringUtils::Format("CREATE INDEX ix_episode_season_episode on episode (c{:02}, c{:02})",
VIDEODB_ID_EPISODE_SEASON, VIDEODB_ID_EPISODE_EPISODE);
m_pDS->exec(createColIndex);
createColIndex = StringUtils::Format("CREATE INDEX ix_episode_bookmark on episode (c{:02})",
VIDEODB_ID_EPISODE_BOOKMARK);
m_pDS->exec(createColIndex);
m_pDS->exec("CREATE INDEX ix_episode_show1 on episode(idEpisode,idShow)");
m_pDS->exec("CREATE INDEX ix_episode_show2 on episode(idShow,idEpisode)");
m_pDS->exec("CREATE UNIQUE INDEX ix_musicvideo_file_1 on musicvideo (idMVideo, idFile)");
m_pDS->exec("CREATE UNIQUE INDEX ix_musicvideo_file_2 on musicvideo (idFile, idMVideo)");
m_pDS->exec("CREATE INDEX ixMovieBasePath ON movie ( c23(12) )");
m_pDS->exec("CREATE INDEX ixMusicVideoBasePath ON musicvideo ( c14(12) )");
m_pDS->exec("CREATE INDEX ixEpisodeBasePath ON episode ( c19(12) )");
m_pDS->exec("CREATE INDEX ix_streamdetails ON streamdetails (idFile)");
m_pDS->exec("CREATE INDEX ix_seasons ON seasons (idShow, season)");
m_pDS->exec("CREATE INDEX ix_art ON art(media_id, media_type(20), type(20))");
m_pDS->exec("CREATE INDEX ix_rating ON rating(media_id, media_type(20))");
m_pDS->exec("CREATE INDEX ix_uniqueid1 ON uniqueid(media_id, media_type(20), type(20))");
m_pDS->exec("CREATE INDEX ix_uniqueid2 ON uniqueid(media_type(20), value(20))");
m_pDS->exec("CREATE UNIQUE INDEX ix_actor_1 ON actor (name(255))");
m_pDS->exec("CREATE UNIQUE INDEX ix_actor_link_1 ON "
"actor_link (actor_id, media_type(20), media_id, role(255))");
m_pDS->exec("CREATE INDEX ix_actor_link_2 ON "
"actor_link (media_id, media_type(20), actor_id)");
m_pDS->exec("CREATE INDEX ix_actor_link_3 ON actor_link (media_type(20))");
CreateLinkIndex("tag");
CreateForeignLinkIndex("director", "actor");
CreateForeignLinkIndex("writer", "actor");
CreateLinkIndex("studio");
CreateLinkIndex("genre");
CreateLinkIndex("country");
CLog::Log(LOGINFO, "{} - creating triggers", __FUNCTION__);
m_pDS->exec("CREATE TRIGGER delete_movie AFTER DELETE ON movie FOR EACH ROW BEGIN "
"DELETE FROM genre_link WHERE media_id=old.idMovie AND media_type='movie'; "
"DELETE FROM actor_link WHERE media_id=old.idMovie AND media_type='movie'; "
"DELETE FROM director_link WHERE media_id=old.idMovie AND media_type='movie'; "
"DELETE FROM studio_link WHERE media_id=old.idMovie AND media_type='movie'; "
"DELETE FROM country_link WHERE media_id=old.idMovie AND media_type='movie'; "
"DELETE FROM writer_link WHERE media_id=old.idMovie AND media_type='movie'; "
"DELETE FROM movielinktvshow WHERE idMovie=old.idMovie; "
"DELETE FROM art WHERE media_id=old.idMovie AND media_type='movie'; "
"DELETE FROM tag_link WHERE media_id=old.idMovie AND media_type='movie'; "
"DELETE FROM rating WHERE media_id=old.idMovie AND media_type='movie'; "
"DELETE FROM uniqueid WHERE media_id=old.idMovie AND media_type='movie'; "
"END");
m_pDS->exec("CREATE TRIGGER delete_tvshow AFTER DELETE ON tvshow FOR EACH ROW BEGIN "
"DELETE FROM actor_link WHERE media_id=old.idShow AND media_type='tvshow'; "
"DELETE FROM director_link WHERE media_id=old.idShow AND media_type='tvshow'; "
"DELETE FROM studio_link WHERE media_id=old.idShow AND media_type='tvshow'; "
"DELETE FROM tvshowlinkpath WHERE idShow=old.idShow; "
"DELETE FROM genre_link WHERE media_id=old.idShow AND media_type='tvshow'; "
"DELETE FROM movielinktvshow WHERE idShow=old.idShow; "
"DELETE FROM seasons WHERE idShow=old.idShow; "
"DELETE FROM art WHERE media_id=old.idShow AND media_type='tvshow'; "
"DELETE FROM tag_link WHERE media_id=old.idShow AND media_type='tvshow'; "
"DELETE FROM rating WHERE media_id=old.idShow AND media_type='tvshow'; "
"DELETE FROM uniqueid WHERE media_id=old.idShow AND media_type='tvshow'; "
"END");
m_pDS->exec("CREATE TRIGGER delete_musicvideo AFTER DELETE ON musicvideo FOR EACH ROW BEGIN "
"DELETE FROM actor_link WHERE media_id=old.idMVideo AND media_type='musicvideo'; "
"DELETE FROM director_link WHERE media_id=old.idMVideo AND media_type='musicvideo'; "
"DELETE FROM genre_link WHERE media_id=old.idMVideo AND media_type='musicvideo'; "
"DELETE FROM studio_link WHERE media_id=old.idMVideo AND media_type='musicvideo'; "
"DELETE FROM art WHERE media_id=old.idMVideo AND media_type='musicvideo'; "
"DELETE FROM tag_link WHERE media_id=old.idMVideo AND media_type='musicvideo'; "
"END");
m_pDS->exec("CREATE TRIGGER delete_episode AFTER DELETE ON episode FOR EACH ROW BEGIN "
"DELETE FROM actor_link WHERE media_id=old.idEpisode AND media_type='episode'; "
"DELETE FROM director_link WHERE media_id=old.idEpisode AND media_type='episode'; "
"DELETE FROM writer_link WHERE media_id=old.idEpisode AND media_type='episode'; "
"DELETE FROM art WHERE media_id=old.idEpisode AND media_type='episode'; "
"DELETE FROM rating WHERE media_id=old.idEpisode AND media_type='episode'; "
"DELETE FROM uniqueid WHERE media_id=old.idEpisode AND media_type='episode'; "
"END");
m_pDS->exec("CREATE TRIGGER delete_season AFTER DELETE ON seasons FOR EACH ROW BEGIN "
"DELETE FROM art WHERE media_id=old.idSeason AND media_type='season'; "
"END");
m_pDS->exec("CREATE TRIGGER delete_set AFTER DELETE ON sets FOR EACH ROW BEGIN "
"DELETE FROM art WHERE media_id=old.idSet AND media_type='set'; "
"END");
m_pDS->exec("CREATE TRIGGER delete_person AFTER DELETE ON actor FOR EACH ROW BEGIN "
"DELETE FROM art WHERE media_id=old.actor_id AND media_type IN ('actor','artist','writer','director'); "
"END");
m_pDS->exec("CREATE TRIGGER delete_tag AFTER DELETE ON tag_link FOR EACH ROW BEGIN "
"DELETE FROM tag WHERE tag_id=old.tag_id AND tag_id NOT IN (SELECT DISTINCT tag_id FROM tag_link); "
"END");
m_pDS->exec("CREATE TRIGGER delete_file AFTER DELETE ON files FOR EACH ROW BEGIN "
"DELETE FROM bookmark WHERE idFile=old.idFile; "
"DELETE FROM settings WHERE idFile=old.idFile; "
"DELETE FROM stacktimes WHERE idFile=old.idFile; "
"DELETE FROM streamdetails WHERE idFile=old.idFile; "
"END");
CreateViews();
}
void CVideoDatabase::CreateViews()
{
CLog::Log(LOGINFO, "create episode_view");
std::string episodeview = PrepareSQL("CREATE VIEW episode_view AS SELECT "
" episode.*,"
" files.strFileName AS strFileName,"
" path.strPath AS strPath,"
" files.playCount AS playCount,"
" files.lastPlayed AS lastPlayed,"
" files.dateAdded AS dateAdded,"
" tvshow.c%02d AS strTitle,"
" tvshow.c%02d AS genre,"
" tvshow.c%02d AS studio,"
" tvshow.c%02d AS premiered,"
" tvshow.c%02d AS mpaa,"
" bookmark.timeInSeconds AS resumeTimeInSeconds, "
" bookmark.totalTimeInSeconds AS totalTimeInSeconds, "
" bookmark.playerState AS playerState, "
" rating.rating AS rating, "
" rating.votes AS votes, "
" rating.rating_type AS rating_type, "
" uniqueid.value AS uniqueid_value, "
" uniqueid.type AS uniqueid_type "
"FROM episode"
" JOIN files ON"
" files.idFile=episode.idFile"
" JOIN tvshow ON"
" tvshow.idShow=episode.idShow"
" JOIN seasons ON"
" seasons.idSeason=episode.idSeason"
" JOIN path ON"
" files.idPath=path.idPath"
" LEFT JOIN bookmark ON"
" bookmark.idFile=episode.idFile AND bookmark.type=1"
" LEFT JOIN rating ON"
" rating.rating_id=episode.c%02d"
" LEFT JOIN uniqueid ON"
" uniqueid.uniqueid_id=episode.c%02d",
VIDEODB_ID_TV_TITLE, VIDEODB_ID_TV_GENRE,
VIDEODB_ID_TV_STUDIOS, VIDEODB_ID_TV_PREMIERED,
VIDEODB_ID_TV_MPAA, VIDEODB_ID_EPISODE_RATING_ID,
VIDEODB_ID_EPISODE_IDENT_ID);
m_pDS->exec(episodeview);
CLog::Log(LOGINFO, "create tvshowcounts");
std::string tvshowcounts = PrepareSQL("CREATE VIEW tvshowcounts AS SELECT "
" tvshow.idShow AS idShow,"
" MAX(files.lastPlayed) AS lastPlayed,"
" NULLIF(COUNT(episode.c12), 0) AS totalCount,"
" COUNT(files.playCount) AS watchedcount,"
" NULLIF(COUNT(DISTINCT(episode.c12)), 0) AS totalSeasons, "
" MAX(files.dateAdded) as dateAdded "
" FROM tvshow"
" LEFT JOIN episode ON"
" episode.idShow=tvshow.idShow"
" LEFT JOIN files ON"
" files.idFile=episode.idFile "
"GROUP BY tvshow.idShow");
m_pDS->exec(tvshowcounts);
CLog::Log(LOGINFO, "create tvshowlinkpath_minview");
// This view only exists to workaround a limitation in MySQL <5.7 which is not able to
// perform subqueries in joins.
// Also, the correct solution is to remove the path information altogether, since a
// TV series can always have multiple paths. It is used in the GUI at the moment, but
// such usage should be removed together with this view and the path columns in tvshow_view.
//!@todo Remove the hacky selection of a semi-random path for tvshows from the queries and UI
std::string tvshowlinkpathview = PrepareSQL("CREATE VIEW tvshowlinkpath_minview AS SELECT "
" idShow, "
" min(idPath) AS idPath "
"FROM tvshowlinkpath "
"GROUP BY idShow");
m_pDS->exec(tvshowlinkpathview);
CLog::Log(LOGINFO, "create tvshow_view");
std::string tvshowview = PrepareSQL("CREATE VIEW tvshow_view AS SELECT "
" tvshow.*,"
" path.idParentPath AS idParentPath,"
" path.strPath AS strPath,"
" tvshowcounts.dateAdded AS dateAdded,"
" lastPlayed, totalCount, watchedcount, totalSeasons, "
" rating.rating AS rating, "
" rating.votes AS votes, "
" rating.rating_type AS rating_type, "
" uniqueid.value AS uniqueid_value, "
" uniqueid.type AS uniqueid_type "
"FROM tvshow"
" LEFT JOIN tvshowlinkpath_minview ON "
" tvshowlinkpath_minview.idShow=tvshow.idShow"
" LEFT JOIN path ON"
" path.idPath=tvshowlinkpath_minview.idPath"
" INNER JOIN tvshowcounts ON"
" tvshow.idShow = tvshowcounts.idShow "
" LEFT JOIN rating ON"
" rating.rating_id=tvshow.c%02d "
" LEFT JOIN uniqueid ON"
" uniqueid.uniqueid_id=tvshow.c%02d ",
VIDEODB_ID_TV_RATING_ID, VIDEODB_ID_TV_IDENT_ID);
m_pDS->exec(tvshowview);
CLog::Log(LOGINFO, "create season_view");
std::string seasonview = PrepareSQL("CREATE VIEW season_view AS SELECT "
" seasons.idSeason AS idSeason,"
" seasons.idShow AS idShow,"
" seasons.season AS season,"
" seasons.name AS name,"
" seasons.userrating AS userrating,"
" tvshow_view.strPath AS strPath,"
" tvshow_view.c%02d AS showTitle,"
" tvshow_view.c%02d AS plot,"
" tvshow_view.c%02d AS premiered,"
" tvshow_view.c%02d AS genre,"
" tvshow_view.c%02d AS studio,"
" tvshow_view.c%02d AS mpaa,"
" count(DISTINCT episode.idEpisode) AS episodes,"
" count(files.playCount) AS playCount,"
" min(episode.c%02d) AS aired "
"FROM seasons"
" JOIN tvshow_view ON"
" tvshow_view.idShow = seasons.idShow"
" JOIN episode ON"
" episode.idShow = seasons.idShow AND episode.c%02d = seasons.season"
" JOIN files ON"
" files.idFile = episode.idFile "
"GROUP BY seasons.idSeason,"
" seasons.idShow,"
" seasons.season,"
" seasons.name,"
" seasons.userrating,"
" tvshow_view.strPath,"
" tvshow_view.c%02d,"
" tvshow_view.c%02d,"
" tvshow_view.c%02d,"
" tvshow_view.c%02d,"
" tvshow_view.c%02d,"
" tvshow_view.c%02d ",
VIDEODB_ID_TV_TITLE, VIDEODB_ID_TV_PLOT, VIDEODB_ID_TV_PREMIERED,
VIDEODB_ID_TV_GENRE, VIDEODB_ID_TV_STUDIOS, VIDEODB_ID_TV_MPAA,
VIDEODB_ID_EPISODE_AIRED, VIDEODB_ID_EPISODE_SEASON,
VIDEODB_ID_TV_TITLE, VIDEODB_ID_TV_PLOT, VIDEODB_ID_TV_PREMIERED,
VIDEODB_ID_TV_GENRE, VIDEODB_ID_TV_STUDIOS, VIDEODB_ID_TV_MPAA);
m_pDS->exec(seasonview);
CLog::Log(LOGINFO, "create musicvideo_view");
m_pDS->exec("CREATE VIEW musicvideo_view AS SELECT"
" musicvideo.*,"
" files.strFileName as strFileName,"
" path.strPath as strPath,"
" files.playCount as playCount,"
" files.lastPlayed as lastPlayed,"
" files.dateAdded as dateAdded, "
" bookmark.timeInSeconds AS resumeTimeInSeconds, "
" bookmark.totalTimeInSeconds AS totalTimeInSeconds, "
" bookmark.playerState AS playerState "
"FROM musicvideo"
" JOIN files ON"
" files.idFile=musicvideo.idFile"
" JOIN path ON"
" path.idPath=files.idPath"
" LEFT JOIN bookmark ON"
" bookmark.idFile=musicvideo.idFile AND bookmark.type=1");
CLog::Log(LOGINFO, "create movie_view");
std::string movieview = PrepareSQL("CREATE VIEW movie_view AS SELECT"
" movie.*,"
" sets.strSet AS strSet,"
" sets.strOverview AS strSetOverview,"
" files.strFileName AS strFileName,"
" path.strPath AS strPath,"
" files.playCount AS playCount,"
" files.lastPlayed AS lastPlayed, "
" files.dateAdded AS dateAdded, "
" bookmark.timeInSeconds AS resumeTimeInSeconds, "
" bookmark.totalTimeInSeconds AS totalTimeInSeconds, "
" bookmark.playerState AS playerState, "
" rating.rating AS rating, "
" rating.votes AS votes, "
" rating.rating_type AS rating_type, "
" uniqueid.value AS uniqueid_value, "
" uniqueid.type AS uniqueid_type "
"FROM movie"
" LEFT JOIN sets ON"
" sets.idSet = movie.idSet"
" JOIN files ON"
" files.idFile=movie.idFile"
" JOIN path ON"
" path.idPath=files.idPath"
" LEFT JOIN bookmark ON"
" bookmark.idFile=movie.idFile AND bookmark.type=1"
" LEFT JOIN rating ON"
" rating.rating_id=movie.c%02d"
" LEFT JOIN uniqueid ON"
" uniqueid.uniqueid_id=movie.c%02d",
VIDEODB_ID_RATING_ID, VIDEODB_ID_IDENT_ID);
m_pDS->exec(movieview);
}
//********************************************************************************************************************************
int CVideoDatabase::GetPathId(const std::string& strPath)
{
std::string strSQL;
try
{
int idPath=-1;
if (nullptr == m_pDB)
return -1;
if (nullptr == m_pDS)
return -1;
std::string strPath1(strPath);
if (URIUtils::IsStack(strPath) || StringUtils::StartsWithNoCase(strPath, "rar://") || StringUtils::StartsWithNoCase(strPath, "zip://"))
URIUtils::GetParentPath(strPath,strPath1);
URIUtils::AddSlashAtEnd(strPath1);
strSQL=PrepareSQL("select idPath from path where strPath='%s'",strPath1.c_str());
m_pDS->query(strSQL);
if (!m_pDS->eof())
idPath = m_pDS->fv("path.idPath").get_asInt();
m_pDS->close();
return idPath;
}
catch (...)
{
CLog::Log(LOGERROR, "{} unable to getpath ({})", __FUNCTION__, strSQL);
}
return -1;
}
bool CVideoDatabase::GetPaths(std::set<std::string> &paths)
{
try
{
if (nullptr == m_pDB)
return false;
if (nullptr == m_pDS)
return false;
paths.clear();
// grab all paths with movie content set
if (!m_pDS->query("select strPath,noUpdate from path"
" where (strContent = 'movies' or strContent = 'musicvideos')"
" and strPath NOT like 'multipath://%%'"
" order by strPath"))
return false;
while (!m_pDS->eof())
{
if (!m_pDS->fv("noUpdate").get_asBool())
paths.insert(m_pDS->fv("strPath").get_asString());
m_pDS->next();
}
m_pDS->close();
// then grab all tvshow paths
if (!m_pDS->query("select strPath,noUpdate from path"
" where ( strContent = 'tvshows'"
" or idPath in (select idPath from tvshowlinkpath))"
" and strPath NOT like 'multipath://%%'"
" order by strPath"))
return false;
while (!m_pDS->eof())
{
if (!m_pDS->fv("noUpdate").get_asBool())
paths.insert(m_pDS->fv("strPath").get_asString());
m_pDS->next();
}
m_pDS->close();
// finally grab all other paths holding a movie which is not a stack or a rar archive
// - this isnt perfect but it should do fine in most situations.
// reason we need it to hold a movie is stacks from different directories (cdx folders for instance)
// not making mistakes must take priority
if (!m_pDS->query("select strPath,noUpdate from path"
" where idPath in (select idPath from files join movie on movie.idFile=files.idFile)"
" and idPath NOT in (select idPath from tvshowlinkpath)"
" and idPath NOT in (select idPath from files where strFileName like 'video_ts.ifo')" // dvd folders get stacked to a single item in parent folder
" and idPath NOT in (select idPath from files where strFileName like 'index.bdmv')" // bluray folders get stacked to a single item in parent folder
" and strPath NOT like 'multipath://%%'"
" and strContent NOT in ('movies', 'tvshows', 'None')" // these have been added above
" order by strPath"))
return false;
while (!m_pDS->eof())
{
if (!m_pDS->fv("noUpdate").get_asBool())
paths.insert(m_pDS->fv("strPath").get_asString());
m_pDS->next();
}
m_pDS->close();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "{} failed", __FUNCTION__);
}
return false;
}
bool CVideoDatabase::GetPathsLinkedToTvShow(int idShow, std::vector<std::string> &paths)
{
std::string sql;
try
{
sql = PrepareSQL("SELECT strPath FROM path JOIN tvshowlinkpath ON tvshowlinkpath.idPath=path.idPath WHERE idShow=%i", idShow);
m_pDS->query(sql);
while (!m_pDS->eof())
{
paths.emplace_back(m_pDS->fv(0).get_asString());
m_pDS->next();
}
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "{} error during query: {}", __FUNCTION__, sql);
}
return false;
}
bool CVideoDatabase::GetPathsForTvShow(int idShow, std::set<int>& paths)
{
std::string strSQL;
try
{
if (nullptr == m_pDB)
return false;
if (nullptr == m_pDS)
return false;
// add base path
strSQL = PrepareSQL("SELECT strPath FROM tvshow_view WHERE idShow=%i", idShow);
if (m_pDS->query(strSQL))
paths.insert(GetPathId(m_pDS->fv(0).get_asString()));
// add all other known paths
strSQL = PrepareSQL("SELECT DISTINCT idPath FROM files JOIN episode ON episode.idFile=files.idFile WHERE episode.idShow=%i",idShow);
m_pDS->query(strSQL);
while (!m_pDS->eof())
{
paths.insert(m_pDS->fv(0).get_asInt());
m_pDS->next();
}
m_pDS->close();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "{} error during query: {}", __FUNCTION__, strSQL);
}
return false;
}
int CVideoDatabase::RunQuery(const std::string &sql)
{
auto start = std::chrono::steady_clock::now();
int rows = -1;
if (m_pDS->query(sql))
{
rows = m_pDS->num_rows();
if (rows == 0)
m_pDS->close();
}
auto end = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
CLog::Log(LOGDEBUG, LOGDATABASE, "{} took {} ms for {} items query: {}", __FUNCTION__,
duration.count(), rows, sql);
return rows;
}
bool CVideoDatabase::GetSubPaths(const std::string &basepath, std::vector<std::pair<int, std::string>>& subpaths)
{
std::string sql;
try
{
if (!m_pDB || !m_pDS)
return false;
std::string path(basepath);
URIUtils::AddSlashAtEnd(path);
sql = PrepareSQL("SELECT idPath,strPath FROM path WHERE SUBSTR(strPath,1,%i)='%s'"
" AND idPath NOT IN (SELECT idPath FROM files WHERE strFileName LIKE 'video_ts.ifo')"
" AND idPath NOT IN (SELECT idPath FROM files WHERE strFileName LIKE 'index.bdmv')"
, StringUtils::utf8_strlen(path.c_str()), path.c_str());
m_pDS->query(sql);
while (!m_pDS->eof())
{
subpaths.emplace_back(m_pDS->fv(0).get_asInt(), m_pDS->fv(1).get_asString());
m_pDS->next();
}
m_pDS->close();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "{} error during query: {}", __FUNCTION__, sql);
}
return false;
}
int CVideoDatabase::AddPath(const std::string& strPath, const std::string &parentPath /*= "" */, const CDateTime& dateAdded /* = CDateTime() */)
{
std::string strSQL;
try
{
int idPath = GetPathId(strPath);
if (idPath >= 0)
return idPath; // already have the path
if (nullptr == m_pDB)
return -1;
if (nullptr == m_pDS)
return -1;
std::string strPath1(strPath);
if (URIUtils::IsStack(strPath) || StringUtils::StartsWithNoCase(strPath, "rar://") || StringUtils::StartsWithNoCase(strPath, "zip://"))
URIUtils::GetParentPath(strPath,strPath1);
URIUtils::AddSlashAtEnd(strPath1);
int idParentPath = GetPathId(parentPath.empty() ? URIUtils::GetParentPath(strPath1) : parentPath);
// add the path
if (idParentPath < 0)
{
if (dateAdded.IsValid())
strSQL=PrepareSQL("insert into path (idPath, strPath, dateAdded) values (NULL, '%s', '%s')", strPath1.c_str(), dateAdded.GetAsDBDateTime().c_str());
else
strSQL=PrepareSQL("insert into path (idPath, strPath) values (NULL, '%s')", strPath1.c_str());
}
else
{
if (dateAdded.IsValid())
strSQL = PrepareSQL("insert into path (idPath, strPath, dateAdded, idParentPath) values (NULL, '%s', '%s', %i)", strPath1.c_str(), dateAdded.GetAsDBDateTime().c_str(), idParentPath);
else
strSQL=PrepareSQL("insert into path (idPath, strPath, idParentPath) values (NULL, '%s', %i)", strPath1.c_str(), idParentPath);
}
m_pDS->exec(strSQL);
idPath = (int)m_pDS->lastinsertid();
return idPath;
}
catch (...)
{
CLog::Log(LOGERROR, "{} unable to addpath ({})", __FUNCTION__, strSQL);
}
return -1;
}
bool CVideoDatabase::GetPathHash(const std::string &path, std::string &hash)
{
try
{
if (nullptr == m_pDB)
return false;
if (nullptr == m_pDS)
return false;
std::string strSQL=PrepareSQL("select strHash from path where strPath='%s'", path.c_str());
m_pDS->query(strSQL);
if (m_pDS->num_rows() == 0)
return false;
hash = m_pDS->fv("strHash").get_asString();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "{} ({}) failed", __FUNCTION__, path);
}
return false;
}
bool CVideoDatabase::GetSourcePath(const std::string &path, std::string &sourcePath)
{
SScanSettings dummy;
return GetSourcePath(path, sourcePath, dummy);
}
bool CVideoDatabase::GetSourcePath(const std::string &path, std::string &sourcePath, SScanSettings& settings)
{
try
{
if (path.empty() || m_pDB == nullptr || m_pDS == nullptr)
return false;
std::string strPath2;
if (URIUtils::IsMultiPath(path))
strPath2 = CMultiPathDirectory::GetFirstPath(path);
else
strPath2 = path;
std::string strPath1 = URIUtils::GetDirectory(strPath2);
int idPath = GetPathId(strPath1);
if (idPath > -1)
{
// check if the given path already is a source itself
std::string strSQL = PrepareSQL("SELECT path.useFolderNames, path.scanRecursive, path.noUpdate, path.exclude FROM path WHERE "
"path.idPath = %i AND "
"path.strContent IS NOT NULL AND path.strContent != '' AND "
"path.strScraper IS NOT NULL AND path.strScraper != ''", idPath);
if (m_pDS->query(strSQL) && !m_pDS->eof())
{
settings.parent_name_root = settings.parent_name = m_pDS->fv(0).get_asBool();
settings.recurse = m_pDS->fv(1).get_asInt();
settings.noupdate = m_pDS->fv(2).get_asBool();
settings.exclude = m_pDS->fv(3).get_asBool();
m_pDS->close();
sourcePath = path;
return true;
}
}
// look for parent paths until there is one which is a source
std::string strParent;
bool found = false;
while (URIUtils::GetParentPath(strPath1, strParent))
{
std::string strSQL = PrepareSQL("SELECT path.strContent, path.strScraper, path.scanRecursive, path.useFolderNames, path.noUpdate, path.exclude FROM path WHERE strPath = '%s'", strParent.c_str());
if (m_pDS->query(strSQL) && !m_pDS->eof())
{
std::string strContent = m_pDS->fv(0).get_asString();
std::string strScraper = m_pDS->fv(1).get_asString();
if (!strContent.empty() && !strScraper.empty())
{
settings.parent_name_root = settings.parent_name = m_pDS->fv(2).get_asBool();
settings.recurse = m_pDS->fv(3).get_asInt();
settings.noupdate = m_pDS->fv(4).get_asBool();
settings.exclude = m_pDS->fv(5).get_asBool();
found = true;
break;
}
}
strPath1 = strParent;
}
m_pDS->close();
if (found)
{
sourcePath = strParent;
return true;
}
}
catch (...)
{
CLog::Log(LOGERROR, "{} failed", __FUNCTION__);
}
return false;
}
//********************************************************************************************************************************
int CVideoDatabase::AddFile(const std::string& strFileNameAndPath,
const std::string& parentPath /* = "" */,
const CDateTime& dateAdded /* = CDateTime() */,
int playcount /* = 0 */,
const CDateTime& lastPlayed /* = CDateTime() */)
{
std::string strSQL = "";
try
{
int idFile;
if (nullptr == m_pDB)
return -1;
if (nullptr == m_pDS)
return -1;
const auto finalDateAdded = GetDateAdded(strFileNameAndPath, dateAdded);
std::string strFileName, strPath;
SplitPath(strFileNameAndPath,strPath,strFileName);
int idPath = AddPath(strPath, parentPath, finalDateAdded);
if (idPath < 0)
return -1;
std::string strSQL=PrepareSQL("select idFile from files where strFileName='%s' and idPath=%i", strFileName.c_str(),idPath);
m_pDS->query(strSQL);
if (m_pDS->num_rows() > 0)
{
idFile = m_pDS->fv("idFile").get_asInt() ;
m_pDS->close();
return idFile;
}
m_pDS->close();
std::string strPlaycount = "NULL";
if (playcount > 0)
strPlaycount = std::to_string(playcount);
std::string strLastPlayed = "NULL";
if (lastPlayed.IsValid())
strLastPlayed = "'" + lastPlayed.GetAsDBDateTime() + "'";
strSQL = PrepareSQL("INSERT INTO files (idFile, idPath, strFileName, playCount, lastPlayed, dateAdded) "
"VALUES(NULL, %i, '%s', " + strPlaycount + ", " + strLastPlayed + ", '%s')",
idPath, strFileName.c_str(), finalDateAdded.GetAsDBDateTime().c_str());
m_pDS->exec(strSQL);
idFile = (int)m_pDS->lastinsertid();
return idFile;
}
catch (...)
{
CLog::Log(LOGERROR, "{} unable to addfile ({})", __FUNCTION__, strSQL);
}
return -1;
}
int CVideoDatabase::AddFile(const CFileItem& item)
{
if (item.IsVideoDb() && item.HasVideoInfoTag())
{
const auto videoInfoTag = item.GetVideoInfoTag();
if (videoInfoTag->m_iFileId != -1)
return videoInfoTag->m_iFileId;
else
return AddFile(*videoInfoTag);
}
return AddFile(item.GetPath());
}
int CVideoDatabase::AddFile(const CVideoInfoTag& details, const std::string& parentPath /* = "" */)
{
return AddFile(details.GetPath(), parentPath, details.m_dateAdded, details.GetPlayCount(),
details.m_lastPlayed);
}
void CVideoDatabase::UpdateFileDateAdded(CVideoInfoTag& details)
{
if (details.GetPath().empty() || GetAndFillFileId(details) <= 0)
return;
CDateTime finalDateAdded;
try
{
if (nullptr == m_pDB)