aboutsummaryrefslogtreecommitdiff
path: root/xbmc/music/MusicUtils.cpp
blob: c3e6b716253b82c62e5ab7ccc0d6c655dbcfda4f (plain)
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
/*
 *  Copyright (C) 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 "MusicUtils.h"

#include "FileItem.h"
#include "FileItemList.h"
#include "GUIPassword.h"
#include "PartyModeManager.h"
#include "PlayListPlayer.h"
#include "ServiceBroker.h"
#include "application/Application.h"
#include "application/ApplicationComponents.h"
#include "application/ApplicationPlayer.h"
#include "dialogs/GUIDialogBusy.h"
#include "dialogs/GUIDialogKaiToast.h"
#include "dialogs/GUIDialogSelect.h"
#include "filesystem/Directory.h"
#include "filesystem/MusicDatabaseDirectory.h"
#include "guilib/GUIComponent.h"
#include "guilib/GUIKeyboardFactory.h"
#include "guilib/GUIWindowManager.h"
#include "guilib/LocalizeStrings.h"
#include "media/MediaType.h"
#include "music/MusicDatabase.h"
#include "music/MusicDbUrl.h"
#include "music/MusicFileItemClassify.h"
#include "music/tags/MusicInfoTag.h"
#include "network/NetworkFileItemClassify.h"
#include "playlists/PlayList.h"
#include "playlists/PlayListFactory.h"
#include "profiles/ProfileManager.h"
#include "settings/Settings.h"
#include "settings/SettingsComponent.h"
#include "threads/IRunnable.h"
#include "utils/FileUtils.h"
#include "utils/JobManager.h"
#include "utils/StringUtils.h"
#include "utils/URIUtils.h"
#include "utils/log.h"
#include "video/VideoFileItemClassify.h"
#include "view/GUIViewState.h"

#include <memory>

using namespace KODI;
using namespace KODI::VIDEO;
using namespace MUSIC_INFO;
using namespace XFILE;
using namespace std::chrono_literals;

namespace MUSIC_UTILS
{
class CSetArtJob : public CJob
{
  CFileItemPtr pItem;
  std::string m_artType;
  std::string m_newArt;

public:
  CSetArtJob(const CFileItemPtr& item, const std::string& type, const std::string& newArt)
    : pItem(item), m_artType(type), m_newArt(newArt)
  {
  }

  ~CSetArtJob(void) override = default;

  bool HasSongExtraArtChanged(const CFileItemPtr& pSongItem,
                              const std::string& type,
                              const int itemID,
                              CMusicDatabase& db)
  {
    if (!pSongItem->HasMusicInfoTag())
      return false;
    int idSong = pSongItem->GetMusicInfoTag()->GetDatabaseId();
    if (idSong <= 0)
      return false;
    bool result = false;
    if (type == MediaTypeAlbum)
      // Update art when song is from album
      result = (itemID == pSongItem->GetMusicInfoTag()->GetAlbumId());
    else if (type == MediaTypeArtist)
    {
      // Update art when artist is song or album artist of the song
      if (pSongItem->HasProperty("artistid"))
      {
        // Check artistid property when we have it
        for (CVariant::const_iterator_array varid =
                 pSongItem->GetProperty("artistid").begin_array();
             varid != pSongItem->GetProperty("artistid").end_array(); ++varid)
        {
          int idArtist = static_cast<int>(varid->asInteger());
          result = (itemID == idArtist);
          if (result)
            break;
        }
      }
      else
      { // Check song artists in database
        result = db.IsSongArtist(idSong, itemID);
      }
      if (!result)
      {
        // Check song album artists
        result = db.IsSongAlbumArtist(idSong, itemID);
      }
    }
    return result;
  }

  // Asynchronously update song, album or artist art in library
  // and trigger update to album & artist art of the currently playing song
  // and songs queued in the current playlist
  bool DoWork(void) override
  {
    int itemID = pItem->GetMusicInfoTag()->GetDatabaseId();
    if (itemID <= 0)
      return false;
    std::string type = pItem->GetMusicInfoTag()->GetType();
    CMusicDatabase db;
    if (!db.Open())
      return false;
    if (!m_newArt.empty())
      db.SetArtForItem(itemID, type, m_artType, m_newArt);
    else
      db.RemoveArtForItem(itemID, type, m_artType);
    // Artwork changed so set datemodified field for artist, album or song
    db.SetItemUpdated(itemID, type);

    /* Update the art of the songs of the current music playlist.
      Song thumb is often a fallback from the album and fanart is from the artist(s).
      Clear the art if it is a song from the album or by the artist
      (as song or album artist) that has modified artwork. The new artwork gets
      loaded when the playlist is shown.
      */
    bool clearcache(false);
    const PLAYLIST::CPlayList& playlist =
        CServiceBroker::GetPlaylistPlayer().GetPlaylist(PLAYLIST::TYPE_MUSIC);

    for (int i = 0; i < playlist.size(); ++i)
    {
      CFileItemPtr songitem = playlist[i];
      if (HasSongExtraArtChanged(songitem, type, itemID, db))
      {
        songitem->ClearArt(); // Art gets reloaded when the current playist is shown
        clearcache = true;
      }
    }
    if (clearcache)
    {
      // Clear the music playlist from cache
      CFileItemList items("playlistmusic://");
      items.RemoveDiscCache(WINDOW_MUSIC_PLAYLIST);
    }

    // Similarly update the art of the currently playing song so it shows on OSD
    const auto& components = CServiceBroker::GetAppComponents();
    const auto appPlayer = components.GetComponent<CApplicationPlayer>();
    if (appPlayer->IsPlayingAudio() && g_application.CurrentFileItem().HasMusicInfoTag())
    {
      CFileItemPtr songitem = std::make_shared<CFileItem>(g_application.CurrentFileItem());
      if (HasSongExtraArtChanged(songitem, type, itemID, db))
        g_application.UpdateCurrentPlayArt();
    }

    db.Close();
    return true;
  }
};

class CSetSongRatingJob : public CJob
{
  std::string strPath;
  int idSong;
  int iUserrating;

public:
  CSetSongRatingJob(const std::string& filePath, int userrating)
    : strPath(filePath), idSong(-1), iUserrating(userrating)
  {
  }

  CSetSongRatingJob(int songId, int userrating) : strPath(), idSong(songId), iUserrating(userrating)
  {
  }

  ~CSetSongRatingJob(void) override = default;

  bool DoWork(void) override
  {
    // Asynchronously update song userrating in library
    CMusicDatabase db;
    if (db.Open())
    {
      if (idSong > 0)
        db.SetSongUserrating(idSong, iUserrating);
      else
        db.SetSongUserrating(strPath, iUserrating);
      db.Close();
    }

    return true;
  }
};

void UpdateArtJob(const std::shared_ptr<CFileItem>& pItem,
                  const std::string& strType,
                  const std::string& strArt)
{
  // Asynchronously update that type of art in the database
  CSetArtJob* job = new CSetArtJob(pItem, strType, strArt);
  CServiceBroker::GetJobManager()->AddJob(job, nullptr);
}

// Add art types required in Kodi and configured by the user
void AddHardCodedAndExtendedArtTypes(std::vector<std::string>& artTypes, const CMusicInfoTag& tag)
{
  for (const auto& artType : GetArtTypesToScan(tag.GetType()))
  {
    if (find(artTypes.begin(), artTypes.end(), artType) == artTypes.end())
      artTypes.push_back(artType);
  }
}

// Add art types currently assigned to the media item
void AddCurrentArtTypes(std::vector<std::string>& artTypes,
                        const CMusicInfoTag& tag,
                        CMusicDatabase& db)
{
  std::map<std::string, std::string> currentArt;
  db.GetArtForItem(tag.GetDatabaseId(), tag.GetType(), currentArt);
  for (const auto& art : currentArt)
  {
    if (!art.second.empty() && find(artTypes.begin(), artTypes.end(), art.first) == artTypes.end())
      artTypes.push_back(art.first);
  }
}

// Add art types that exist for other media items of the same type
void AddMediaTypeArtTypes(std::vector<std::string>& artTypes,
                          const CMusicInfoTag& tag,
                          CMusicDatabase& db)
{
  std::vector<std::string> dbArtTypes;
  db.GetArtTypes(tag.GetType(), dbArtTypes);
  for (const auto& artType : dbArtTypes)
  {
    if (find(artTypes.begin(), artTypes.end(), artType) == artTypes.end())
      artTypes.push_back(artType);
  }
}

// Add art types from available but unassigned artwork for this media item
void AddAvailableArtTypes(std::vector<std::string>& artTypes,
                          const CMusicInfoTag& tag,
                          CMusicDatabase& db)
{
  for (const auto& artType : db.GetAvailableArtTypesForItem(tag.GetDatabaseId(), tag.GetType()))
  {
    if (find(artTypes.begin(), artTypes.end(), artType) == artTypes.end())
      artTypes.push_back(artType);
  }
}

bool FillArtTypesList(CFileItem& musicitem, CFileItemList& artlist)
{
  const CMusicInfoTag& tag = *musicitem.GetMusicInfoTag();
  if (tag.GetDatabaseId() < 1 || tag.GetType().empty())
    return false;
  if (tag.GetType() != MediaTypeArtist && tag.GetType() != MediaTypeAlbum &&
      tag.GetType() != MediaTypeSong)
    return false;

  artlist.Clear();

  CMusicDatabase db;
  db.Open();

  std::vector<std::string> artTypes;

  AddHardCodedAndExtendedArtTypes(artTypes, tag);
  AddCurrentArtTypes(artTypes, tag, db);
  AddMediaTypeArtTypes(artTypes, tag, db);
  AddAvailableArtTypes(artTypes, tag, db);

  db.Close();

  for (const auto& type : artTypes)
  {
    CFileItemPtr artitem(new CFileItem(type, false));
    // Localise the names of common types of art
    if (type == "banner")
      artitem->SetLabel(g_localizeStrings.Get(20020));
    else if (type == "fanart")
      artitem->SetLabel(g_localizeStrings.Get(20445));
    else if (type == "poster")
      artitem->SetLabel(g_localizeStrings.Get(20021));
    else if (type == "thumb")
      artitem->SetLabel(g_localizeStrings.Get(21371));
    else
      artitem->SetLabel(type);
    // Set art type as art item property
    artitem->SetProperty("arttype", type);
    // Set current art as art item thumb
    if (musicitem.HasArt(type))
      artitem->SetArt("thumb", musicitem.GetArt(type));
    artlist.Add(artitem);
  }

  return !artlist.IsEmpty();
}

std::string ShowSelectArtTypeDialog(CFileItemList& artitems)
{
  // Prompt for choice
  CGUIDialogSelect* dialog =
      CServiceBroker::GetGUI()->GetWindowManager().GetWindow<CGUIDialogSelect>(
          WINDOW_DIALOG_SELECT);
  if (!dialog)
    return "";

  dialog->SetHeading(CVariant{13521});
  dialog->Reset();
  dialog->SetUseDetails(true);
  dialog->EnableButton(true, 13516);

  dialog->SetItems(artitems);
  dialog->Open();

  if (dialog->IsButtonPressed())
  {
    // Get the new art type name
    std::string strArtTypeName;
    if (!CGUIKeyboardFactory::ShowAndGetInput(strArtTypeName,
                                              CVariant{g_localizeStrings.Get(13516)}, false))
      return "";
    // Add new type to the list of art types
    CFileItemPtr artitem(new CFileItem(strArtTypeName, false));
    artitem->SetLabel(strArtTypeName);
    artitem->SetProperty("arttype", strArtTypeName);
    artitems.Add(artitem);

    return strArtTypeName;
  }

  return dialog->GetSelectedFileItem()->GetProperty("arttype").asString();
}

int ShowSelectRatingDialog(int iSelected)
{
  CGUIDialogSelect* dialog =
      CServiceBroker::GetGUI()->GetWindowManager().GetWindow<CGUIDialogSelect>(
          WINDOW_DIALOG_SELECT);
  if (dialog)
  {
    dialog->SetHeading(CVariant{38023});
    dialog->Add(g_localizeStrings.Get(38022));
    for (int i = 1; i <= 10; i++)
      dialog->Add(StringUtils::Format("{}: {}", g_localizeStrings.Get(563), i));
    dialog->SetSelected(iSelected);
    dialog->Open();

    int userrating = dialog->GetSelectedItem();
    userrating = std::max(userrating, -1);
    userrating = std::min(userrating, 10);
    return userrating;
  }
  return -1;
}

void UpdateSongRatingJob(const std::shared_ptr<CFileItem>& pItem, int userrating)
{
  // Asynchronously update the song user rating in music library
  const CMusicInfoTag* tag = pItem->GetMusicInfoTag();
  CSetSongRatingJob* job;
  if (tag && tag->GetType() == MediaTypeSong && tag->GetDatabaseId() > 0)
    // Use song ID when known
    job = new CSetSongRatingJob(tag->GetDatabaseId(), userrating);
  else
    job = new CSetSongRatingJob(pItem->GetPath(), userrating);
  CServiceBroker::GetJobManager()->AddJob(job, nullptr);
}

std::vector<std::string> GetArtTypesToScan(const MediaType& mediaType)
{
  std::vector<std::string> arttypes;
  // Get default types of art that are to be automatically fetched during scanning
  if (mediaType == MediaTypeArtist)
  {
    arttypes = {"thumb", "fanart"};
    for (auto& artType : CServiceBroker::GetSettingsComponent()->GetSettings()->GetList(
             CSettings::SETTING_MUSICLIBRARY_ARTISTART_WHITELIST))
    {
      if (find(arttypes.begin(), arttypes.end(), artType.asString()) == arttypes.end())
        arttypes.emplace_back(artType.asString());
    }
  }
  else if (mediaType == MediaTypeAlbum)
  {
    arttypes = {"thumb"};
    for (auto& artType : CServiceBroker::GetSettingsComponent()->GetSettings()->GetList(
             CSettings::SETTING_MUSICLIBRARY_ALBUMART_WHITELIST))
    {
      if (find(arttypes.begin(), arttypes.end(), artType.asString()) == arttypes.end())
        arttypes.emplace_back(artType.asString());
    }
  }
  return arttypes;
}

bool IsValidArtType(const std::string& potentialArtType)
{
  // Check length and is ascii
  return potentialArtType.length() <= 25 &&
         std::find_if_not(potentialArtType.begin(), potentialArtType.end(),
                          StringUtils::isasciialphanum) == potentialArtType.end();
}

} // namespace MUSIC_UTILS

namespace
{
class CAsyncGetItemsForPlaylist : public IRunnable
{
public:
  CAsyncGetItemsForPlaylist(const std::shared_ptr<CFileItem>& item, CFileItemList& queuedItems)
    : m_item(item), m_queuedItems(queuedItems)
  {
  }

  ~CAsyncGetItemsForPlaylist() override = default;

  void Run() override
  {
    // fast lookup is needed here
    m_queuedItems.SetFastLookup(true);

    m_musicDatabase.Open();
    GetItemsForPlaylist(m_item);
    m_musicDatabase.Close();
  }

private:
  void GetItemsForPlaylist(const std::shared_ptr<CFileItem>& item);

  const std::shared_ptr<CFileItem> m_item;
  CFileItemList& m_queuedItems;
  CMusicDatabase m_musicDatabase;
};

SortDescription GetSortDescription(const CGUIViewState& state, const CFileItemList& items)
{
  SortDescription sortDescTrackNumber;

  auto sortDescriptions = state.GetSortDescriptions();
  for (auto& sortDescription : sortDescriptions)
  {
    if (sortDescription.sortBy == SortByTrackNumber)
    {
      // check whether at least one item has actually a track number set
      for (const auto& item : items)
      {
        if (item->HasMusicInfoTag() && item->GetMusicInfoTag()->GetTrackNumber() > 0)
        {
          // First choice for folders containing a single album
          sortDescTrackNumber = sortDescription;
          sortDescTrackNumber.sortOrder = SortOrderAscending;
          break; // leave items loop. we can still find ByArtistThenYear. so, no return here.
        }
      }
    }
    else if (sortDescription.sortBy == SortByArtistThenYear)
    {
      // check whether songs from at least two different albums are in the list
      int lastAlbumId = -1;
      for (const auto& item : items)
      {
        if (item->HasMusicInfoTag())
        {
          const auto tag = item->GetMusicInfoTag();
          if (lastAlbumId != -1 && tag->GetAlbumId() != lastAlbumId)
          {
            // First choice for folders containing multiple albums
            sortDescription.sortOrder = SortOrderAscending;
            return sortDescription;
          }
          lastAlbumId = tag->GetAlbumId();
        }
      }
    }
  }

  if (sortDescTrackNumber.sortBy != SortByNone)
    return sortDescTrackNumber;
  else
    return state.GetSortMethod(); // last resort
}

void CAsyncGetItemsForPlaylist::GetItemsForPlaylist(const std::shared_ptr<CFileItem>& item)
{
  if (item->IsParentFolder() || !item->CanQueue() || item->IsRAR() || item->IsZIP())
    return;

  if (MUSIC::IsMusicDb(*item) && item->m_bIsFolder && !item->IsParentFolder())
  {
    // we have a music database folder, just grab the "all" item underneath it
    XFILE::CMusicDatabaseDirectory dir;

    if (!dir.ContainsSongs(item->GetPath()))
    {
      // grab the ALL item in this category
      // Genres will still require 2 lookups, and queuing the entire Genre folder
      // will require 3 lookups (genre, artist, album)
      CMusicDbUrl musicUrl;
      if (musicUrl.FromString(item->GetPath()))
      {
        musicUrl.AppendPath("-1/");

        const auto allItem = std::make_shared<CFileItem>(musicUrl.ToString(), true);
        allItem->SetCanQueue(true); // workaround for CanQueue() check above
        GetItemsForPlaylist(allItem);
      }
      return;
    }
  }

  if (item->m_bIsFolder)
  {
    // Check if we add a locked share
    if (item->m_bIsShareOrDrive)
    {
      if (!g_passwordManager.IsItemUnlocked(item.get(), "music"))
        return;
    }

    CFileItemList items;
    XFILE::CDirectory::GetDirectory(item->GetPath(), items, "", XFILE::DIR_FLAG_DEFAULTS);

    const std::unique_ptr<CGUIViewState> state(
        CGUIViewState::GetViewState(WINDOW_MUSIC_NAV, items));
    if (state)
    {
      LABEL_MASKS labelMasks;
      state->GetSortMethodLabelMasks(labelMasks);

      const CLabelFormatter fileFormatter(labelMasks.m_strLabelFile, labelMasks.m_strLabel2File);
      const CLabelFormatter folderFormatter(labelMasks.m_strLabelFolder,
                                            labelMasks.m_strLabel2Folder);
      for (const auto& i : items)
      {
        if (i->IsLabelPreformatted())
          continue;

        if (i->m_bIsFolder)
          folderFormatter.FormatLabels(i.get());
        else
          fileFormatter.FormatLabels(i.get());
      }

      SortDescription sortDesc;
      if (CServiceBroker::GetGUI()->GetWindowManager().GetActiveWindow() == WINDOW_MUSIC_NAV)
        sortDesc = state->GetSortMethod();
      else
        sortDesc = GetSortDescription(*state, items);

      if (sortDesc.sortBy == SortByLabel)
        items.ClearSortState();

      items.Sort(sortDesc);
    }

    for (const auto& i : items)
    {
      GetItemsForPlaylist(i);
    }
  }
  else
  {
    if (item->IsPlayList())
    {
      const std::unique_ptr<PLAYLIST::CPlayList> playList(
          PLAYLIST::CPlayListFactory::Create(*item));
      if (!playList)
      {
        CLog::Log(LOGERROR, "{} failed to create playlist {}", __FUNCTION__, item->GetPath());
        return;
      }

      if (!playList->Load(item->GetPath()))
      {
        CLog::Log(LOGERROR, "{} failed to load playlist {}", __FUNCTION__, item->GetPath());
        return;
      }

      for (int i = 0; i < playList->size(); ++i)
      {
        GetItemsForPlaylist((*playList)[i]);
      }
    }
    else if (NETWORK::IsInternetStream(*item) && !MUSIC::IsMusicDb(*item))
    {
      // just queue the internet stream, it will be expanded on play
      m_queuedItems.Add(item);
    }
    else if (item->IsPlugin() && item->GetProperty("isplayable").asBoolean())
    {
      // python files can be played
      m_queuedItems.Add(item);
    }
    else if (!item->IsNFO() && (MUSIC::IsAudio(*item) || IsVideo(*item)))
    {
      const auto itemCheck = m_queuedItems.Get(item->GetPath());
      if (!itemCheck || itemCheck->GetStartOffset() != item->GetStartOffset())
      {
        // add item
        m_musicDatabase.SetPropertiesForFileItem(*item);
        m_queuedItems.Add(item);
      }
    }
  }
}

void ShowToastNotification(const CFileItem& item, int titleId)
{
  std::string localizedMediaType;
  std::string title;

  if (item.HasMusicInfoTag())
  {
    localizedMediaType = CMediaTypes::GetCapitalLocalization(item.GetMusicInfoTag()->GetType());
    title = item.GetMusicInfoTag()->GetTitle();
  }

  if (title.empty())
    title = item.GetLabel();
  if (title.empty())
    return; // no meaningful toast possible.

  const std::string message =
      localizedMediaType.empty() ? title : localizedMediaType + ": " + title;

  CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Info, g_localizeStrings.Get(titleId),
                                        message);
}

std::string GetMusicDbItemPath(const CFileItem& item)
{
  std::string path = item.GetPath();
  if (!URIUtils::IsMusicDb(path))
    path = item.GetProperty("original_listitem_url").asString();

  if (URIUtils::IsMusicDb(path))
    return path;

  return {};
}

void AddItemToPlayListAndPlay(const std::shared_ptr<CFileItem>& itemToQueue,
                              const std::shared_ptr<CFileItem>& itemToPlay,
                              const std::string& player)
{
  // recursively add items to list
  CFileItemList queuedItems;
  MUSIC_UTILS::GetItemsForPlayList(itemToQueue, queuedItems);

  auto& playlistPlayer = CServiceBroker::GetPlaylistPlayer();
  playlistPlayer.ClearPlaylist(PLAYLIST::TYPE_MUSIC);
  playlistPlayer.Reset();
  playlistPlayer.Add(PLAYLIST::TYPE_MUSIC, queuedItems);

  // figure out where to start playback
  PLAYLIST::CPlayList& playList = playlistPlayer.GetPlaylist(PLAYLIST::TYPE_MUSIC);
  int pos = 0;
  if (itemToPlay)
  {
    for (const std::shared_ptr<CFileItem>& queuedItem : queuedItems)
    {
      if (queuedItem->IsSamePath(itemToPlay.get()))
        break;

      pos++;
    }
  }

  if (playlistPlayer.IsShuffled(PLAYLIST::TYPE_MUSIC))
  {
    playList.Swap(0, playList.FindOrder(pos));
    pos = 0;
  }

  playlistPlayer.SetCurrentPlaylist(PLAYLIST::TYPE_MUSIC);
  playlistPlayer.Play(pos, player);
}
} // unnamed namespace

namespace MUSIC_UTILS
{
bool IsAutoPlayNextItem(const CFileItem& item)
{
  if (!item.HasMusicInfoTag())
    return false;

  const auto settings = CServiceBroker::GetSettingsComponent()->GetSettings();
  return settings->GetBool(CSettings::SETTING_MUSICPLAYER_AUTOPLAYNEXTITEM) &&
         !settings->GetBool(CSettings::SETTING_MUSICPLAYER_QUEUEBYDEFAULT);
}

void PlayItem(const std::shared_ptr<CFileItem>& itemIn,
              const std::string& player,
              ContentUtils::PlayMode mode /* = ContentUtils::PlayMode::CHECK_AUTO_PLAY_NEXT_ITEM */)
{
  auto item = itemIn;

  //  Allow queuing of unqueueable items
  //  when we try to queue them directly
  if (!itemIn->CanQueue())
  {
    // make a copy to not alter the original item
    item = std::make_shared<CFileItem>(*itemIn);
    item->SetCanQueue(true);
  }

  if (item->m_bIsFolder)
  {
    AddItemToPlayListAndPlay(item, nullptr, player);
  }
  else if (item->HasMusicInfoTag())
  {
    if (mode == ContentUtils::PlayMode::PLAY_FROM_HERE ||
        (mode == ContentUtils::PlayMode::CHECK_AUTO_PLAY_NEXT_ITEM && IsAutoPlayNextItem(*item)))
    {
      // Add item and all its siblings to the playlist and play. Prefer musicdb path if available,
      // because it provides more information than just a plain file system path for example.
      std::string parentPath = item->GetProperty("ParentPath").asString();
      if (parentPath.empty())
      {
        std::string path = GetMusicDbItemPath(*item);
        if (path.empty())
          path = item->GetPath();

        URIUtils::GetParentPath(path, parentPath);

        if (parentPath.empty())
        {
          CLog::LogF(LOGERROR, "Unable to obtain parent path for '{}'", item->GetPath());
          return;
        }
      }

      const auto parentItem = std::make_shared<CFileItem>(parentPath, true);
      if (item->GetStartOffset() == STARTOFFSET_RESUME)
        parentItem->SetStartOffset(STARTOFFSET_RESUME);

      AddItemToPlayListAndPlay(parentItem, item, player);
    }
    else // mode == PlayMode::PLAY_ONLY_THIS
    {
      // song, so just play it
      auto& playlistPlayer = CServiceBroker::GetPlaylistPlayer();
      playlistPlayer.Reset();
      playlistPlayer.SetCurrentPlaylist(PLAYLIST::TYPE_NONE);
      playlistPlayer.Play(item, player);
    }
  }
}

void QueueItem(const std::shared_ptr<CFileItem>& itemIn, QueuePosition pos)
{
  auto item = itemIn;

  //  Allow queuing of unqueueable items
  //  when we try to queue them directly
  if (!itemIn->CanQueue())
  {
    // make a copy to not alter the original item
    item = std::make_shared<CFileItem>(*itemIn);
    item->SetCanQueue(true);
  }

  auto& player = CServiceBroker::GetPlaylistPlayer();

  PLAYLIST::Id playlistId = player.GetCurrentPlaylist();
  if (playlistId == PLAYLIST::TYPE_NONE)
  {
    const auto& components = CServiceBroker::GetAppComponents();
    playlistId = components.GetComponent<CApplicationPlayer>()->GetPreferredPlaylist();
  }

  if (playlistId == PLAYLIST::TYPE_NONE)
    playlistId = PLAYLIST::TYPE_MUSIC;

  // Check for the partymode playlist item, do nothing when "PartyMode.xsp" not exists
  if (item->IsSmartPlayList() && !CFileUtils::Exists(item->GetPath()))
  {
    const auto profileManager = CServiceBroker::GetSettingsComponent()->GetProfileManager();
    if (item->GetPath() == profileManager->GetUserDataItem("PartyMode.xsp"))
      return;
  }

  const int oldSize = player.GetPlaylist(playlistId).size();

  CFileItemList queuedItems;
  GetItemsForPlayList(item, queuedItems);

  // if party mode, add items but DONT start playing
  if (g_partyModeManager.IsEnabled())
  {
    g_partyModeManager.AddUserSongs(queuedItems, false);
    return;
  }

  const auto& components = CServiceBroker::GetAppComponents();
  const auto appPlayer = components.GetComponent<CApplicationPlayer>();

  if (pos == QueuePosition::POSITION_BEGIN && appPlayer->IsPlaying())
    player.Insert(playlistId, queuedItems,
                  CServiceBroker::GetPlaylistPlayer().GetCurrentItemIdx() + 1);
  else
    player.Add(playlistId, queuedItems);

  bool playbackStarted = false;

  if (!appPlayer->IsPlaying() && player.GetPlaylist(playlistId).size())
  {
    const int winID = CServiceBroker::GetGUI()->GetWindowManager().GetActiveWindow();
    if (winID == WINDOW_MUSIC_NAV)
    {
      CGUIViewState* viewState = CGUIViewState::GetViewState(winID, queuedItems);
      if (viewState)
        viewState->SetPlaylistDirectory("playlistmusic://");
    }

    player.Reset();
    player.SetCurrentPlaylist(playlistId);
    player.Play(oldSize, ""); // start playing at the first new item

    playbackStarted = true;
  }

  if (!playbackStarted)
  {
    if (pos == QueuePosition::POSITION_END)
      ShowToastNotification(*item, 38082); // Added to end of playlist
    else
      ShowToastNotification(*item, 38083); // Added to playlist to play next
  }
}

bool GetItemsForPlayList(const std::shared_ptr<CFileItem>& item, CFileItemList& queuedItems)
{
  CAsyncGetItemsForPlaylist getItems(item, queuedItems);
  return CGUIDialogBusy::Wait(&getItems,
                              500, // 500ms before busy dialog appears
                              true); // can be cancelled
}

namespace
{
bool IsNonExistingUserPartyModePlaylist(const CFileItem& item)
{
  if (!item.IsSmartPlayList())
    return false;

  const std::string& path{item.GetPath()};
  const auto profileManager{CServiceBroker::GetSettingsComponent()->GetProfileManager()};
  return ((profileManager->GetUserDataItem("PartyMode.xsp") == path) && !CFileUtils::Exists(path));
}
} // unnamed namespace

bool IsItemPlayable(const CFileItem& item)
{
  // Exclude all parent folders
  if (item.IsParentFolder())
    return false;

  // Exclude all video library items
  if (IsVideoDb(item) || StringUtils::StartsWithNoCase(item.GetPath(), "library://video/"))
    return false;

  // Exclude other components
  if (item.IsPVR() || item.IsPlugin() || item.IsScript() || item.IsAddonsPath())
    return false;

  // Exclude special items
  if (StringUtils::StartsWithNoCase(item.GetPath(), "newsmartplaylist://") ||
      StringUtils::StartsWithNoCase(item.GetPath(), "newplaylist://"))
    return false;

  // Include playlists located at one of the possible music playlist locations
  if (item.IsPlayList())
  {
    if (StringUtils::StartsWithNoCase(item.GetMimeType(), "audio/"))
      return true;

    if (StringUtils::StartsWithNoCase(item.GetPath(), "special://musicplaylists/") ||
        StringUtils::StartsWithNoCase(item.GetPath(), "special://profile/playlists/music/"))
      return true;

    // Has user changed default playlists location and the list is located there?
    const auto settings = CServiceBroker::GetSettingsComponent()->GetSettings();
    std::string path = settings->GetString(CSettings::SETTING_SYSTEM_PLAYLISTSPATH);
    StringUtils::TrimRight(path, "/");
    if (StringUtils::StartsWith(item.GetPath(), StringUtils::Format("{}/music/", path)))
      return true;

    if (!item.m_bIsFolder && !item.HasMusicInfoTag())
    {
      // Unknown location. Type cannot be determined for non-folder items.
      return false;
    }
  }

  if (IsNonExistingUserPartyModePlaylist(item))
    return false;

  if (item.m_bIsFolder &&
      (MUSIC::IsMusicDb(item) || StringUtils::StartsWithNoCase(item.GetPath(), "library://music/")))
  {
    // Exclude top level nodes - eg can't play 'genres' just a specific genre etc
    const XFILE::MUSICDATABASEDIRECTORY::NODE_TYPE node =
        XFILE::CMusicDatabaseDirectory::GetDirectoryParentType(item.GetPath());
    if (node == XFILE::MUSICDATABASEDIRECTORY::NODE_TYPE_OVERVIEW)
      return false;

    return true;
  }

  if (item.HasMusicInfoTag() && item.CanQueue())
    return true;
  else if (!item.m_bIsFolder && MUSIC::IsAudio(item))
    return true;
  else if (item.m_bIsFolder)
  {
    // Not a music-specific folder (just file:// or nfs://). Allow play if context is Music window.
    if (CServiceBroker::GetGUI()->GetWindowManager().GetActiveWindow() == WINDOW_MUSIC_NAV &&
        item.GetPath() != "add") // Exclude "Add music source" item
      return true;
  }
  return false;
}

} // namespace MUSIC_UTILS