-
Notifications
You must be signed in to change notification settings - Fork 0
/
library.go
1435 lines (1204 loc) · 33.5 KB
/
library.go
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
package library
import (
"errors"
"fmt"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/anacrolix/missinggo/perf"
"github.com/asdine/storm"
"github.com/asdine/storm/q"
"github.com/op/go-logging"
"github.com/projectx13/projectx/cache"
"github.com/projectx13/projectx/config"
"github.com/projectx13/projectx/database"
"github.com/projectx13/projectx/tmdb"
"github.com/projectx13/projectx/trakt"
"github.com/projectx13/projectx/util"
"github.com/projectx13/projectx/xbmc"
)
const (
movieType = "movie"
showType = "show"
episodeType = "episode"
trueType = "true"
falseType = "false"
resolveExpiration = 7 * 24 * time.Hour
resolveFileExpiration = 60 * 24 * time.Hour
)
const (
// MovieType ...
MovieType = iota
// ShowType ...
ShowType
// SeasonType ...
SeasonType
// EpisodeType ...
EpisodeType
)
const (
// StateDeleted ...
StateDeleted = iota
// StateActive ...
StateActive
)
const (
// ActionUpdate ...
ActionUpdate = iota
// ActionDelete ...
ActionDelete
// ActionSafeDelete ...
ActionSafeDelete
)
const (
// TVDBScraper ...
TVDBScraper = iota
// TMDBScraper ...
TMDBScraper
// TraktScraper ...
TraktScraper
// IMDBScraper ...
IMDBScraper
)
const (
// Active ...
Active = iota
// Deleted ...
Deleted
)
const (
// Delete ...
Delete = iota
// Update ...
Update
// Batch ...
Batch
// BatchDelete ...
BatchDelete
// DeleteTorrent ...
DeleteTorrent
)
var (
removedEpisodes = make(chan *removedEpisode)
closer = util.Event{}
log = logging.MustGetLogger("library")
cacheStore *cache.DBStore
initialized = false
resolveRegexp = regexp.MustCompile(`^plugin://plugin.video.projectx.*?(\d+)(\W|$)`)
pendingShows = []int{}
)
var l = &Library{
UIDs: []*UniqueIDs{},
Movies: []*Movie{},
Shows: []*Show{},
WatchedTrakt: []uint64{},
}
// InitDB ...
func InitDB() {
cacheStore = cache.NewDBStore()
}
// Get returns singleton instance for Library
func Get() *Library {
return l
}
// Init makes preparations on program start
func Init() {
InitDB()
if err := checkMoviesPath(); err != nil {
xbmc.Notify("projectx", err.Error(), config.AddonIcon())
return
}
if err := checkShowsPath(); err != nil {
xbmc.Notify("projectx", err.Error(), config.AddonIcon())
return
}
go func() {
// Give time to Kodi to start its JSON-RPC service
time.Sleep(5 * time.Second)
RefreshLocal()
Refresh()
initialized = true
}()
// Removed episodes debouncer
go func() {
var episodes []*removedEpisode
closing := closer.C()
timer := time.NewTicker(3 * time.Second)
defer timer.Stop()
defer close(removedEpisodes)
for {
select {
case <-closing:
return
case <-timer.C:
if len(episodes) == 0 {
break
}
shows := make(map[string][]*removedEpisode, 0)
for _, episode := range episodes {
shows[episode.ShowName] = append(shows[episode.ShowName], episode)
}
var label string
var labels []string
if len(episodes) > 1 {
for showName, showEpisodes := range shows {
var libraryTotal int
if l.Shows == nil {
break
}
show, err := GetShowByTMDB(showEpisodes[0].ShowID)
if show != nil && err == nil {
libraryTotal = len(show.Episodes)
}
if libraryTotal == 0 {
break
}
if len(showEpisodes) == libraryTotal {
ID := strconv.Itoa(showEpisodes[0].ShowID)
if _, err := RemoveShow(ID); err != nil {
log.Error("Unable to remove show after removing all episodes...")
}
} else {
labels = append(labels, fmt.Sprintf("%d episodes of %s", len(showEpisodes), showName))
}
// Add single episodes to removed prefix
var tmdbIDs []int
for _, showEpisode := range showEpisodes {
tmdbIDs = append(tmdbIDs, showEpisode.ID)
}
if err := updateBatchDBItem(tmdbIDs, StateDeleted, EpisodeType, showEpisodes[0].ShowID); err != nil {
log.Error(err)
}
}
if len(labels) > 0 {
label = strings.Join(labels, ", ")
if xbmc.DialogConfirmFocused("projectx", fmt.Sprintf("LOCALIZE[30278];;%s", label)) {
xbmc.VideoLibraryClean()
}
}
} else {
for showName, episode := range shows {
label = fmt.Sprintf("%s S%02dE%02d", showName, episode[0].Season, episode[0].Episode)
if err := updateDBItem(episode[0].ID, StateDeleted, EpisodeType, episode[0].ShowID); err != nil {
log.Error(err)
}
}
if xbmc.DialogConfirmFocused("projectx", fmt.Sprintf("LOCALIZE[30278];;%s", label)) {
xbmc.VideoLibraryClean()
}
}
episodes = make([]*removedEpisode, 0)
case episode, ok := <-removedEpisodes:
if !ok {
break
}
episodes = append(episodes, episode)
}
}
}()
updateDelay := config.Get().UpdateDelay
if updateDelay > 0 {
if updateDelay < 10 {
// Give time to projectx to update its cache of libraryMovies, libraryShows and libraryEpisodes
updateDelay = 10
}
go func() {
time.Sleep(time.Duration(updateDelay) * time.Second)
closing := closer.C()
select {
case <-closing:
return
default:
PlanTraktUpdate()
updateLibraryShows()
}
}()
}
log.Notice("Warming up caches...")
go func() {
time.Sleep(30 * time.Second)
if !tmdb.WarmingUp.IsSet() {
xbmc.Notify("projectx", "LOCALIZE[30147]", config.AddonIcon())
}
}()
started := time.Now()
language := config.Get().Language
tmdb.PopularMovies(tmdb.DiscoverFilters{}, language, 1)
tmdb.PopularShows(tmdb.DiscoverFilters{}, language, 1)
if _, _, err := trakt.TopMovies("trending", "1"); err != nil {
log.Warning(err)
}
if _, _, err := trakt.TopShows("trending", "1"); err != nil {
log.Warning(err)
}
tmdb.WarmingUp.Set()
took := time.Since(started)
if took.Seconds() > 30 {
xbmc.Notify("projectx", "LOCALIZE[30148]", config.AddonIcon())
}
log.Noticef("Caches warmed up in %s", took)
updateFrequency := util.Max(1, config.Get().UpdateFrequency)
traktFrequency := util.Max(1, config.Get().TraktSyncFrequencyMin)
updateTicker := time.NewTicker(time.Duration(updateFrequency) * time.Hour)
traktSyncTicker := time.NewTicker(time.Duration(traktFrequency) * time.Minute)
markedForRemovalTicker := time.NewTicker(30 * time.Second)
watcherTicker := time.NewTicker(1 * time.Second)
defer updateTicker.Stop()
defer traktSyncTicker.Stop()
defer markedForRemovalTicker.Stop()
defer watcherTicker.Stop()
closing := closer.C()
for {
select {
case <-watcherTicker.C:
if l.Running.IsOverall || l.Running.IsMovies || l.Running.IsShows || l.Running.IsEpisodes || l.Running.IsKodi || l.Running.IsTrakt {
continue
} else if l.Pending.IsKodi {
go RefreshKodi()
} else if l.Pending.IsTrakt {
go RefreshTrakt()
} else if l.Pending.IsMovies {
go RefreshMovies()
} else if l.Pending.IsShows {
go RefreshShows()
} else if l.Pending.IsEpisodes {
go RefreshEpisodes()
} else if l.Pending.IsOverall {
go Refresh()
}
case <-updateTicker.C:
if config.Get().UpdateFrequency > 0 && config.Get().LibraryEnabled && config.Get().LibrarySyncEnabled && (config.Get().LibrarySyncPlaybackEnabled || !xbmc.PlayerIsPlaying()) {
go func() {
if err := updateLibraryShows(); err != nil {
log.Warning(err)
return
}
PlanKodiUpdate()
}()
}
case <-traktSyncTicker.C:
PlanTraktUpdate()
case <-markedForRemovalTicker.C:
var items []database.BTItem
database.GetStormDB().Select(q.Eq("State", database.StatusRemove)).Find(&items)
infoHash := ""
for _, item := range items {
// Remove from projectx's library to prevent duplicates
if item.Type == movieType {
if IsDuplicateMovie(strconv.Itoa(item.ID)) {
if _, err := RemoveMovie(item.ID); err != nil {
log.Warning("Nothing left to remove from projectx")
}
}
} else {
if IsDuplicateEpisode(item.ShowID, item.Season, item.Episode) {
if err := RemoveEpisode(item.ID, item.ShowID, item.Season, item.Episode); err != nil {
log.Warning(err)
}
}
}
database.GetStormDB().DeleteStruct(&item)
log.Infof("Removed %s from database", infoHash)
}
case <-closing:
return
}
}
}
// MoviesLibraryPath contains calculated path for saving Movies strm files
func MoviesLibraryPath() string {
return filepath.Join(config.Get().LibraryPath, "Movies")
}
// ShowsLibraryPath contains calculated path for saving Shows strm files
func ShowsLibraryPath() string {
return filepath.Join(config.Get().LibraryPath, "Shows")
}
//
// Library updates
//
func updateLibraryShows() error {
if !config.Get().LibraryEnabled || !config.Get().LibrarySyncEnabled || (!config.Get().LibrarySyncPlaybackEnabled && xbmc.PlayerIsPlaying()) {
return nil
}
if err := checkShowsPath(); err != nil {
return err
}
begin := time.Now()
var lis []database.LibraryItem
if err := database.GetStormDB().Select(q.Eq("MediaType", ShowType), q.Eq("State", StateActive)).Find(&lis); err != nil && err != storm.ErrNotFound {
log.Infof("Could not get list of library items: %s", err)
}
for _, i := range lis {
if i.ID == 0 || i.ShowID == 0 {
continue
}
if _, err := writeShowStrm(i.ShowID, false, false); err != nil {
log.Errorf("Error updating show: %s", err)
}
}
log.Infof("Library updated in %s", time.Since(begin))
PlanKodiUpdate()
return nil
}
//
// Path checks
//
func checkLibraryPath() error {
libraryPath := config.Get().LibraryPath
if libraryPath == "" || libraryPath == "." {
log.Warningf("Library path is not initialized")
return errors.New("LOCALIZE[30220]")
}
if fileInfo, err := os.Stat(libraryPath); err != nil {
if fileInfo == nil {
log.Warningf("Library path is invalid")
return errors.New("Invalid library path")
}
if !fileInfo.IsDir() {
log.Warningf("Library path is not a directory")
return errors.New("Library path is not a directory")
}
log.Warningf("Error getting Library path: %v", err)
return err
}
return nil
}
func checkMoviesPath() error {
if err := checkLibraryPath(); err != nil {
return err
}
moviesLibraryPath := MoviesLibraryPath()
if _, err := os.Stat(moviesLibraryPath); os.IsNotExist(err) {
if err := os.Mkdir(moviesLibraryPath, 0755); err != nil {
log.Error(err)
return err
}
}
return nil
}
func checkShowsPath() error {
if err := checkLibraryPath(); err != nil {
return err
}
showsLibraryPath := ShowsLibraryPath()
if _, err := os.Stat(showsLibraryPath); os.IsNotExist(err) {
if err := os.Mkdir(showsLibraryPath, 0755); err != nil {
log.Error(err)
return err
}
}
return nil
}
//
// Writers
//
func writeMovieStrm(tmdbID string, force bool) (*tmdb.Movie, error) {
movie := tmdb.GetMovieByID(tmdbID, config.Get().StrmLanguage)
if movie == nil {
return nil, errors.New("Can't find the movie")
}
movieName := movie.OriginalTitle
if config.Get().StrmLanguage != config.Get().Language && movie.Title != "" {
movieName = movie.Title
}
movieStrm := util.ToFileName(fmt.Sprintf("%s (%s)", movieName, strings.Split(movie.ReleaseDate, "-")[0]))
moviePath := filepath.Join(MoviesLibraryPath(), movieStrm)
if _, err := os.Stat(moviePath); os.IsNotExist(err) {
if err := os.Mkdir(moviePath, 0755); err != nil {
log.Error(err)
return movie, err
}
} else if force {
os.Chtimes(moviePath, time.Now().Local(), time.Now().Local())
}
movieStrmPath := filepath.Join(moviePath, fmt.Sprintf("%s.strm", movieStrm))
if config.Get().LibraryNFOMovies {
writeMovieNFO(movie, filepath.Join(moviePath, fmt.Sprintf("%s.nfo", movieStrm)))
}
playLink := URLForXBMC("/library/movie/play/%s", tmdbID)
if _, err := os.Stat(movieStrmPath); !force && err == nil {
// log.Debugf("Movie strm file already exists at %s", movieStrmPath)
// return movie, fmt.Errorf("LOCALIZE[30287];;%s", movie.Title)
return movie, nil
}
if err := ioutil.WriteFile(movieStrmPath, []byte(playLink), 0644); err != nil {
log.Errorf("Could not write strm file: %s", err)
return movie, err
}
return movie, nil
}
func writeMovieNFO(m *tmdb.Movie, p string) error {
out := `<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<movie>
<uniqueid type="unknown" default="false">%v</uniqueid>
<uniqueid type="projectx" default="false">%v</uniqueid>
<uniqueid type="tmdb" default="true">%v</uniqueid>
<uniqueid type="imdb" default="false">%v</uniqueid>
<uniqueid type="tvdb" default="false">%v</uniqueid>
</movie>
https://www.themoviedb.org/movie/%v
`
out = fmt.Sprintf(out,
m.ID,
m.ID,
m.ID,
m.ExternalIDs.IMDBId,
m.ExternalIDs.TVDBID,
m.ID,
)
if m.ExternalIDs.IMDBId != "" {
out += fmt.Sprintf("https://www.imdb.com/title/%s/\n", m.ExternalIDs.IMDBId)
}
if err := ioutil.WriteFile(p, []byte(out), 0644); err != nil {
log.Errorf("Could not write NFO file: %s", err)
return err
}
return nil
}
func writeShowStrm(showID int, adding, force bool) (*tmdb.Show, error) {
// We should not write strm filex for shows that are marked as deleted
if wasRemoved(showID, ShowType) {
return nil, fmt.Errorf("Show is marked as removed")
}
defer perf.ScopeTimer()()
show := tmdb.GetShow(showID, config.Get().StrmLanguage)
if show == nil {
return nil, fmt.Errorf("Unable to get show (%d)", showID)
}
showPath, showStrm := getShowPath(show)
if _, err := os.Stat(showPath); os.IsNotExist(err) {
if err := os.Mkdir(showPath, 0755); err != nil {
log.Error(err)
return show, err
}
} else if force {
os.Chtimes(showPath, time.Now().Local(), time.Now().Local())
}
if config.Get().LibraryNFOShows {
writeShowNFO(show, filepath.Join(showPath, "tvshow.nfo"))
}
now := util.UTCBod()
addSpecials := config.Get().AddSpecials
for _, season := range show.Seasons {
if season.EpisodeCount == 0 {
continue
}
if config.Get().ShowUnairedSeasons == false {
firstAired, _ := time.Parse("2006-01-02", show.FirstAirDate)
if firstAired.After(now) || firstAired.Equal(now) {
continue
}
}
if addSpecials == false && season.Season == 0 {
continue
}
seasonTMDB := tmdb.GetSeason(showID, season.Season, config.Get().Language, len(show.Seasons))
if seasonTMDB == nil {
continue
}
episodes := seasonTMDB.Episodes
var reAddIDs []int
for _, episode := range episodes {
if episode == nil {
continue
}
if config.Get().ShowUnairedEpisodes == false {
if episode.AirDate == "" {
continue
}
firstAired, _ := time.Parse("2006-01-02", episode.AirDate)
if firstAired.After(now) || firstAired.Equal(now) {
continue
}
}
if adding {
reAddIDs = append(reAddIDs, episode.ID)
}
if !force && IsDuplicateEpisode(showID, season.Season, episode.EpisodeNumber) {
continue
}
episodeStrmPath := filepath.Join(showPath, fmt.Sprintf("%s S%02dE%02d.strm", showStrm, season.Season, episode.EpisodeNumber))
playLink := URLForXBMC("/library/show/play/%d/%d/%d", showID, season.Season, episode.EpisodeNumber)
if _, err := os.Stat(episodeStrmPath); !force && err == nil {
continue
}
if err := ioutil.WriteFile(episodeStrmPath, []byte(playLink), 0644); err != nil {
log.Error(err)
return show, err
}
}
if len(reAddIDs) > 0 {
if err := updateBatchDBItem(reAddIDs, StateActive, EpisodeType, showID); err != nil {
log.Error(err)
}
}
}
return show, nil
}
func writeShowNFO(s *tmdb.Show, p string) error {
out := `<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<tvshow>
<uniqueid type="unknown" default="false">%v</uniqueid>
<uniqueid type="projectx" default="false">%v</uniqueid>
<uniqueid type="tmdb" default="true">%v</uniqueid>
<uniqueid type="imdb" default="false">%v</uniqueid>
<uniqueid type="tvdb" default="false">%v</uniqueid>
</tvshow>
https://www.themoviedb.org/tv/%v
`
out = fmt.Sprintf(out,
s.ID,
s.ID,
s.ID,
s.ExternalIDs.IMDBId,
s.ExternalIDs.TVDBID,
s.ID,
)
if s.ExternalIDs.IMDBId != "" {
out += fmt.Sprintf("https://www.imdb.com/title/%v/\n", s.ExternalIDs.IMDBId)
}
if s.ExternalIDs.TVDBID != "" {
out += fmt.Sprintf("https://www.thetvdb.com/?tab=series&id=%v&lid=7\n", s.ExternalIDs.TVDBID)
}
if err := ioutil.WriteFile(p, []byte(out), 0644); err != nil {
log.Errorf("Could not write NFO file: %s", err)
return err
}
return nil
}
//
// Removers
//
// RemoveMovie removes movie from the library
func RemoveMovie(tmdbID int) (*tmdb.Movie, error) {
if err := checkMoviesPath(); err != nil {
return nil, err
}
defer func() {
deleteDBItem(tmdbID, MovieType, true)
}()
ID := strconv.Itoa(tmdbID)
movie := tmdb.GetMovieByID(ID, config.Get().StrmLanguage)
if movie == nil {
return nil, errors.New("Can't resolve movie")
}
titles := []string{movie.Title, movie.OriginalTitle}
path := ""
for _, t := range titles {
movieStrm := util.ToFileName(fmt.Sprintf("%s (%s)", t, strings.Split(movie.ReleaseDate, "-")[0]))
moviePath := filepath.Join(MoviesLibraryPath(), movieStrm)
if _, err := os.Stat(moviePath); err == nil {
path = moviePath
break
}
}
if path == "" {
log.Warningf("Cannot stat movie strm file")
return movie, errors.New("LOCALIZE[30282]")
}
if err := os.RemoveAll(path); err != nil {
log.Warningf("Cannot remove movie strm file: %s", err)
return movie, err
}
log.Warningf("%s removed from library", movie.Title)
return movie, nil
}
// RemoveShow removes show from the library
func RemoveShow(tmdbID string) (*tmdb.Show, error) {
if err := checkShowsPath(); err != nil {
return nil, err
}
ID, _ := strconv.Atoi(tmdbID)
defer func() {
deleteDBItem(ID, ShowType, true)
}()
show := tmdb.GetShow(ID, config.Get().StrmLanguage)
if show == nil {
return nil, errors.New("Unable to find show to remove")
}
titles := []string{show.Name, show.OriginalName}
path := ""
for _, t := range titles {
showStrm := util.ToFileName(fmt.Sprintf("%s (%s)", t, strings.Split(show.FirstAirDate, "-")[0]))
showPath := filepath.Join(ShowsLibraryPath(), showStrm)
if _, err := os.Stat(showPath); err == nil {
path = showPath
break
}
}
if path == "" {
log.Warningf("Cannot stat show strm file")
return show, errors.New("LOCALIZE[30282]")
}
if err := os.RemoveAll(path); err != nil {
log.Error(err)
return show, err
}
log.Warningf("Directory %s removed from disk", path)
log.Warningf("%s removed from library", show.Name)
return show, nil
}
// RemoveEpisode removes episode from the library
func RemoveEpisode(tmdbID int, showID int, seasonNumber int, episodeNumber int) error {
if err := checkShowsPath(); err != nil {
return err
}
show := tmdb.GetShow(showID, config.Get().StrmLanguage)
if show == nil {
return errors.New("Unable to find show to remove episode")
}
showName := show.OriginalName
if config.Get().StrmLanguage != config.Get().Language && show.Name != "" {
showName = show.Name
}
showPath := util.ToFileName(fmt.Sprintf("%s (%s)", showName, strings.Split(show.FirstAirDate, "-")[0]))
episodeStrm := fmt.Sprintf("%s S%02dE%02d.strm", showPath, seasonNumber, episodeNumber)
episodePath := filepath.Join(ShowsLibraryPath(), showPath, episodeStrm)
alreadyRemoved := false
if _, err := os.Stat(episodePath); err != nil {
alreadyRemoved = true
}
if !alreadyRemoved {
if err := os.Remove(episodePath); err != nil {
return err
}
}
removedEpisodes <- &removedEpisode{
ID: tmdbID,
ShowID: showID,
ShowName: show.Name,
Season: seasonNumber,
Episode: episodeNumber,
}
if !alreadyRemoved {
log.Noticef("%s removed from library", episodeStrm)
} else {
return errors.New("Nothing left to remove from projectx")
}
return nil
}
//
// Duplicate handling
//
// IsDuplicateMovie checks if movie exists in the library
func IsDuplicateMovie(tmdbID string) bool {
l.mu.UIDs.Lock()
defer l.mu.UIDs.Unlock()
defer perf.ScopeTimer()()
query, _ := strconv.Atoi(tmdbID)
for _, u := range l.UIDs {
if u.TMDB != 0 && u.MediaType == MovieType && u.TMDB == query {
return true
}
}
return false
}
// IsDuplicateShow checks if show exists in the library
func IsDuplicateShow(tmdbID string) bool {
defer perf.ScopeTimer()()
l.mu.UIDs.Lock()
defer l.mu.UIDs.Unlock()
query, _ := strconv.Atoi(tmdbID)
for _, u := range l.UIDs {
if u.TMDB != 0 && u.MediaType == ShowType && u.TMDB == query {
return true
}
}
return false
}
// IsDuplicateShowByInt checks if show exists in the library
func IsDuplicateShowByInt(tmdbID int) bool {
defer perf.ScopeTimer()()
l.mu.UIDs.Lock()
defer l.mu.UIDs.Unlock()
for _, u := range l.UIDs {
if u.TMDB != 0 && u.MediaType == ShowType && u.TMDB == tmdbID {
return true
}
}
return false
}
// IsDuplicateEpisode checks if episode exists in the library
func IsDuplicateEpisode(tmdbShowID int, seasonNumber int, episodeNumber int) bool {
l.mu.Shows.RLock()
defer l.mu.Shows.RUnlock()
defer perf.ScopeTimer()()
for _, s := range l.Shows {
if tmdbShowID != s.UIDs.TMDB {
continue
}
for _, e := range s.Episodes {
if e.Season == seasonNumber && e.Episode == episodeNumber {
return true
}
}
}
return false
}
// IsAddedToLibrary checks if specific TMDB exists in the library
func IsAddedToLibrary(id string, mediaType int) (isAdded bool) {
defer perf.ScopeTimer()()
if mediaType == MovieType {
return IsDuplicateMovie(id)
} else if mediaType == ShowType {
return IsDuplicateShow(id)
}
return false
}
//
// Database updates
//
func updateDBItem(tmdbID int, state int, mediaType int, showID int) error {
defer perf.ScopeTimer()()
li := database.LibraryItem{
ID: tmdbID,
MediaType: mediaType,
ShowID: showID,
State: state,
}
if err := database.GetStormDB().Save(&li); err != nil {
log.Debugf("updateDBItem failed: %s", err)
return err
}
return nil
}
func updateBatchDBItem(tmdbIds []int, state int, mediaType int, showID int) error {
defer perf.ScopeTimer()()
tx, err := database.GetStormDB().Begin(true)
if err != nil {
return err
}
defer tx.Rollback()
for _, id := range tmdbIds {
li := database.LibraryItem{
ID: id,
MediaType: mediaType,
ShowID: showID,
State: state,
}
err = tx.Save(&li)
if err != nil {
return err
}
}
return tx.Commit()
}
func deleteDBItem(tmdbID int, mediaType int, removal bool) error {
defer perf.ScopeTimer()()
var li database.LibraryItem
if err := database.GetStormDB().One("ID", tmdbID, &li); err != nil {
log.Debugf("Cannot find deleted item: %s", err)
return err
}
if removal {
li.State = StateDeleted
} else {
li.State = StateActive
}
if err := database.GetStormDB().Save(&li); err != nil {
log.Debugf("Cannot update deleted item: %s", err)
return err
}
return nil
}
// func deleteBatchDBItem(tmdbIds []int, mediaType int) error {
// // tx, err := database.Get().Begin()
// // if err != nil {
// // log.Debugf("Cannot start transaction: %s", err)
// // return err
// // }
// // for _, id := range tmdbIds {
// // _, err := tx.Exec(`UPDATE library_items SET state = ? WHERE tmdbId = ? AND mediaType = ?`, StateDeleted, id, mediaType)
// // if err != nil {
// // log.Debugf("deleteDBItem failed: %s", err)
// // tx.Rollback()
// // return err
// // }
// // }
// // tx.Commit()
// return nil
// }
func wasRemoved(id int, mediaType int) (wasRemoved bool) {
defer perf.ScopeTimer()()
var li database.LibraryItem
if err := database.GetStormDB().Select(q.Eq("ID", id), q.Eq("MediaType", mediaType), q.Eq("State", StateDeleted)).First(&li); err != nil && li.ID != 0 {
return true
}
return false
}
//
// Maintenance
//
// CloseLibrary ...
func CloseLibrary() {
log.Info("Closing library...")
closer.Set()
}
// ClearPageCache deletes cached page listings
func ClearPageCache() {
cacheDB := database.GetCache()
if cacheDB != nil {
cacheDB.DeleteWithPrefix(database.CommonBucket, []byte("page."))
}