Newer
Older
Kevin Whitaker
committed
/*
* Copyright (C) 2017 Kevin Whitaker <eyecreate@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "GroovePlayer.h"
#include "db/UserAction.h"
#include <Wt/WLogger>
#include <Wt/WServer>
#include <Wt/WApplication>
#include "WebInterface.h"
Kevin Whitaker
committed
#include <locale>
#include <Wt/WLogger>
#include <Wt/Dbo/Transaction>
#include <groovefingerprinter/fingerprinter.h>
Kevin Whitaker
committed
std::filesystem::path GroovePlayer::musicScanDir = "";
Kevin Whitaker
committed
GroovePlayer::GroovePlayer(std::string dbFile) : sqliteConnection(dbFile)
Kevin Whitaker
committed
{
sqlSession.setConnection(this->sqliteConnection);
sqlSession.mapClass<User>("user");
sqlSession.mapClass<AudioTrack>("tracks");
sqlSession.mapClass<UserAction>("actions");
try
{
sqlSession.createTables();
} catch(Wt::Dbo::Exception e)
{
Wt::log("info") << "Using Existing DB.";
}
groove_init();
grooveAudioScanner = new std::thread(grooveAudioScannerLoop);
grooveEvents = new std::thread(grooveEventLoop);
Kevin Whitaker
committed
}
Kevin Whitaker
committed
std::list<const AudioTrack*> GroovePlayer::getNextVoteBatch()
Kevin Whitaker
committed
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
/**
* This method will attempt to pick 3 tracks that will be up for selection next.
*
* The first track should be from the same album or artist.
* The second track should be from the same genre.
* The third track should be from something in a different genre.
*
* What is picked inside those requirements is a mix of random and TODO:based on past user actions(33% of time).
*
* The third track will be replaced by a recent request item if one exists.
*/
std::list<const AudioTrack*> selectedTracks;
Wt::Dbo::Transaction transaction(getInstance()->sqlSession);
//First make sure there are at least 3 tracks to suggest.
int trackCount = getInstance()->sqlSession.query<int>("select count(fingerprint) from tracks");
if(trackCount < 3)
{
//Return empty list to show there are not enough tracks to allow voting.
return selectedTracks;
}
//Determine first track
int trackAlbumCount = getInstance()->sqlSession.query<int>("select count(fingerprint) from tracks").where("album = ?").bind(getCurrentTrack()->trackAlbumName);
int trackArtistCount = getInstance()->sqlSession.query<int>("select count(fingerprint) from tracks").where("artist = ?").bind(getCurrentTrack()->trackArtistName);
int computerSlightOfHand = rand() % 10 + 1;
if(trackAlbumCount > 0 && computerSlightOfHand > 3)
{
//Pick item from album
Wt::Dbo::ptr<AudioTrack> eligibleTrack = getInstance()->sqlSession.find<AudioTrack>().where("album = ?").offset(rand() % trackAlbumCount).bind(getCurrentTrack()->trackAlbumName);
selectedTracks.push_back(eligibleTrack.get());
}
else if(trackArtistCount > 0)
{
//Pick item from artist
Wt::Dbo::ptr<AudioTrack> eligibleTrack = getInstance()->sqlSession.find<AudioTrack>().where("artist = ?").offset(rand() % trackArtistCount).bind(getCurrentTrack()->trackArtistName);
selectedTracks.push_back(eligibleTrack.get());
}
//Determine second track
int trackGenreCount = getInstance()->sqlSession.query<int>("select count(fingerprint) from tracks").where("genre = ?").bind(getCurrentTrack()->trackGenre);
if(trackGenreCount > 0)
{
//Pick item from genre
Wt::Dbo::ptr<AudioTrack> eligibleTrack = getInstance()->sqlSession.find<AudioTrack>().where("genre = ?").offset(rand() % trackGenreCount).bind(getCurrentTrack()->trackGenre);
selectedTracks.push_back(eligibleTrack.get());
}
//Determine third track
int trackNotGenreCount = getInstance()->sqlSession.query<int>("select count(fingerprint) from tracks").where("genre != ?").bind(getCurrentTrack()->trackGenre);
if(requestQueue.size() > 0)
{
//There's a request. Pick one up front and put as third item.
selectedTracks.push_back(requestQueue.front());
}
else if(trackNotGenreCount > 0)
{
//Pick from other genre
Wt::Dbo::ptr<AudioTrack> eligibleTrack = getInstance()->sqlSession.find<AudioTrack>().where("genre != ?").offset(rand() % trackNotGenreCount).bind(getCurrentTrack()->trackGenre);
selectedTracks.push_back(eligibleTrack.get());
}
else
{
//Pick randomly
Wt::Dbo::ptr<AudioTrack> eligibleTrack = getInstance()->sqlSession.find<AudioTrack>().offset(rand() % trackCount);
selectedTracks.push_back(eligibleTrack.get());
}
return selectedTracks;
}
void GroovePlayer::grooveEventLoop()
Kevin Whitaker
committed
{
/**
* On first boot, random track that has been played before will start(or random if no track has been played before).
* When voting ends, if no vote was cast, the first will be picked 60% of the time with second being 30% of the time and third being picked 10% of the time.
* Exception is if third track is a request, then it is picked. If another song is voted over this, it will be put in back of request queue.
*/
//TODO
}
GroovePlayer::PlayerEvents GroovePlayer::getNextPlayerEvent()
Kevin Whitaker
committed
Wt::Dbo::ptr<AudioTrack> GroovePlayer::getCurrentTrack()
{
Wt::Dbo::Transaction transaction(getInstance()->sqlSession);
Wt::Dbo::ptr<AudioTrack> track = getInstance()->sqlSession.find<AudioTrack>().where("path = ?").bind(currentItem->file->filename);
return track;
}
Kevin Whitaker
committed
bool GroovePlayer::addFileToTrackDBIfTagged(std::filesystem::path file)
{
//Now check if tags exist and put into DB.
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
struct GrooveFile* gfile = groove_file_open(file.c_str());
struct GrooveTag* artist_tag = groove_file_metadata_get(gfile, "artist", nullptr, 0);
struct GrooveTag* album_tag = groove_file_metadata_get(gfile, "album", nullptr, 0);
struct GrooveTag* name_tag = groove_file_metadata_get(gfile, "title", nullptr, 0);
struct GrooveTag* genre_tag = groove_file_metadata_get(gfile, "genre", nullptr, 0);
if(artist_tag == nullptr || album_tag == nullptr || name_tag == nullptr || genre_tag == nullptr)
{
//Only accept song with all metadata for DB.
groove_file_close(gfile);
return false;
}
//Take fingerprint and compare to DB.
struct GrooveFingerprinter* fingerprinter = groove_fingerprinter_create();
struct GrooveFingerprinterInfo info;
struct GroovePlaylist* playlist = groove_playlist_create();
groove_playlist_insert(playlist,gfile,1.0,1.0,nullptr);
groove_fingerprinter_attach(fingerprinter, playlist);
groove_fingerprinter_info_get(fingerprinter, &info, 1);
double trackLen = info.duration;
char* encodedFP;
groove_fingerprinter_encode(info.fingerprint,info.fingerprint_size,&encodedFP);
std::string fingerprint = std::string(encodedFP);
groove_fingerprinter_dealloc(encodedFP);
groove_fingerprinter_free_info(&info);
groove_fingerprinter_detach(fingerprinter);
groove_fingerprinter_destroy(fingerprinter);
groove_playlist_destroy(playlist);
Wt::Dbo::Transaction transaction(getInstance()->sqlSession);
int existing = getInstance()->sqlSession.query<int>("select count(fingerprint) from tracks").where("fingerprint = ?").bind(fingerprint);
if(existing >0)
{
//This track has a duplicate already.
groove_file_close(gfile);
return false;
}
//Add to DB.
AudioTrack* newTrack = new AudioTrack();
newTrack->trackName = groove_tag_value(name_tag);
newTrack->trackAlbumName = groove_tag_value(album_tag);
newTrack->trackArtistName = groove_tag_value(artist_tag);
newTrack->trackGenre = groove_tag_value(genre_tag);
newTrack->trackLengthSeconds = trackLen;
newTrack->trackFingerprint = fingerprint;
newTrack->trackPath = file.string();
getInstance()->sqlSession.add(newTrack);
groove_file_close(gfile);
return true;
Kevin Whitaker
committed
}
void GroovePlayer::removeOrphanedTracks()
{
Wt::Dbo::Transaction transaction(getInstance()->sqlSession);
Wt::Dbo::collection<Wt::Dbo::ptr<AudioTrack>> tracks = getInstance()->sqlSession.find<AudioTrack>();
for(Wt::Dbo::collection<Wt::Dbo::ptr<AudioTrack>>::const_iterator i = tracks.begin(); i != tracks.end(); ++i)
{
if(!std::filesystem::exists(std::filesystem::path((*i)->trackPath)))
{
Wt::Dbo::ptr<AudioTrack> item = getInstance()->sqlSession.find<AudioTrack>().where("fingerprint = ?").bind((*i)->trackFingerprint);
Wt::log("info") << (*i)->trackPath + " not found in filesystem. Removed from DB.";
item.remove();
}
}
}
Kevin Whitaker
committed
void GroovePlayer::grooveAudioScannerLoop()
{
if(!std::filesystem::exists(musicScanDir))
{
std::filesystem::create_directory(musicScanDir);
Wt::log("info") << "Directory "+std::filesystem::canonical(musicScanDir).string()+" didn't exist, so created.";
} else
{
Wt::log("info") << "Directory "+std::filesystem::canonical(musicScanDir).string()+" exists.";
}
Kevin Whitaker
committed
for(std::filesystem::directory_entry p: std::filesystem::directory_iterator(musicScanDir))
{
std::string extensionLowered;
for(auto elem : p.path().extension().string())
{
extensionLowered.push_back(std::tolower(elem));
}
if(extensionLowered == ".mp3") //TODO:think about supporting more than mp3s.
Kevin Whitaker
committed
{
if(addFileToTrackDBIfTagged(p.path()))
{
Wt::log("info") << p.path().string() << " was added to DB";
}
}
else
{
Wt::log("info") << p.path().string() + " was not an accepted audio file.";
}
Kevin Whitaker
committed
}
//Now check for tracks in DB without a file.
removeOrphanedTracks();
//TODO:use this code when sending to UI.
// Wt::WServer::instance()->postAll([]() {
// Wt::WApplication* app = Wt::WApplication::instance();
// if(app != nullptr)
// {
// static_cast<WebInterface*>(app)->updateUIFromServer();
// }
// }
// );