5ddfcf4b93ad1b5c4df3df4b0304c073c81e72cb
[tomamp] / playlistmanager.cpp
1 #include "playlistmanager.h"
2 #include <QDir>
3 #include <QUrl>
4 #include <QMap>
5
6 QStringList allowedExtensions;
7
8
9 PlaylistManager::PlaylistManager(QWidget* parent)
10     : parentWidget (parent), lastMetaRead (-1)
11 {
12     allowedExtensions << "mp3" << "ogg" << "wav" << "wmv" << "wma";
13 //    qDebug () << Phonon::BackendCapabilities::availableMimeTypes();
14     metaInformationResolver = new Phonon::MediaObject(parent);
15     connect(metaInformationResolver, SIGNAL(stateChanged(Phonon::State,Phonon::State)),
16         this, SLOT(metaStateChanged(Phonon::State,Phonon::State)));
17 }
18
19 int PlaylistManager::indexOf(const Phonon::MediaSource &s) const
20 {
21     for (int i = 0; i < items.size(); ++i)
22     {
23         if (items[i].source == s)
24             return i;
25     }
26     return -1;
27 }
28
29 void PlaylistManager::parseAndAddFolder(const QString &dir, bool recursive)
30 {
31     QStringList filters;
32 //    filters << "*.mp3";
33
34     QStringList files = QDir (dir).entryList(filters);
35
36     if (files.isEmpty())
37         return;
38
39     qDebug () << "Parsing folder " << dir;
40
41     //settings.setValue("LastFolder", dir);
42     int index = items.size();
43     foreach (QString string, files)
44     {
45         if (string == "."  || string == "..")
46             continue;
47         QString fname = dir + "/" + string;
48         QFileInfo fi (fname);
49         if (fi.isDir())
50         {
51             if (recursive)
52                 parseAndAddFolder(fname, true);
53             continue;
54         }
55         if (fileSupported(fname))
56         {
57             qDebug () << "Adding: " << fname;
58             items.append(PlaylistItem (PlaylistItem (fname)));
59         }
60     }
61     if (!items.isEmpty())
62     {
63         metaInformationResolver->setCurrentSource(items.at(index).source);
64         lastMetaRead = index;
65     }
66     qDebug () << " SIZE: " << items.size ();
67     emit playlistChanged (index);
68 }
69
70 void PlaylistManager::addStringList(const QStringList& list)
71 {
72     int index = items.size();
73     foreach (QString string, list)
74     {
75         if (fileSupported(string) || string.toLower().startsWith("http"))
76         {
77             qDebug () << "Adding " << string;
78             items.append(PlaylistItem (string));
79         }
80     }
81     if (!items.isEmpty())
82     {
83         metaInformationResolver->setCurrentSource(items.at(index).source);
84         lastMetaRead = index;
85     }
86     emit playlistChanged(index);
87 }
88
89 void PlaylistManager::metaStateChanged(Phonon::State newState, Phonon::State oldState)
90 {
91     qDebug () << "Meta state now " << newState << " old state " << oldState;
92     // This is an ugly hack, since the metaInformationResolver doesn't properly load the assigned source when it's in the error state
93     // In order to properly read the next file we have to set it as current source again when the resolver entered the stopped state after the error
94     static bool wasError = false;
95     if (wasError && newState == Phonon::StoppedState)
96     {
97         metaInformationResolver->setCurrentSource(items[lastMetaRead].source);
98         wasError = false;
99         return;
100     }
101     if (newState == Phonon::ErrorState)
102     {
103         wasError = true;
104     }
105
106     if (newState != Phonon::StoppedState && newState != Phonon::ErrorState)
107     {
108         return;
109     }
110
111     int index = lastMetaRead;
112     qDebug () << "Reading meta info of " << metaInformationResolver->currentSource().fileName() << " => " << index;
113
114     QMap<QString, QString> metaData = metaInformationResolver->metaData();
115
116
117     if (index >= 0 && newState != Phonon::ErrorState)
118     {
119         items[index].artist = metaData.value("ARTIST");
120         items[index].title = metaData.value("TITLE");
121         items[index].album = metaData.value("ALBUM");
122         qDebug () << "Info is: " << items[index].artist << " - " << items[index].title;
123         if (metaData.isEmpty())
124             qDebug () << "Detected to be empty: " << items[index].uri;
125         else
126             items[index].playable = true;
127         emit itemUpdated (index);
128     }
129     if (index >= 0 && items.size () > index + 1)
130     {
131         metaInformationResolver->setCurrentSource(items[index + 1].source);
132         lastMetaRead = index + 1;
133     }
134 }
135
136 void PlaylistManager::savePlaylist(const QString& filenam)
137 {
138     QString filename = filenam;
139     if (filename.isEmpty())
140         return;
141     bool writepls = false;
142     if (filename.length() < 4 || (filename.right(4).toLower() != ".m3u" && filename.right(4).toLower() != ".pls"))
143     {
144         filename += ".pls";
145         writepls = true;
146     }
147     else if (filename.right(4).toLower() == ".pls")
148         writepls = true;
149     QFile f (filename);
150     try
151     {
152         f.open(QFile::WriteOnly);
153         if (writepls)
154         {
155             f.write ("[playlist]\n");
156             f.write (QString ("NumberOfEntries=%1\n").arg (items.size ()).toAscii());
157         }
158         for (int i = 0; i < items.size(); ++i)
159         {
160             if (writepls)
161             {
162                 f.write (QString ("File%1=%2\n").arg (i + 1).arg (items[i].uri).toAscii());
163                 f.write (QString ("Title%1=%2 - %3 - %4\n").arg (i + 1).arg (items[i].artist).arg (items[i].title).arg (items[i].album).toAscii());
164             }
165             else
166             {
167                 f.write (items[i].uri.toAscii());
168                 f.write ("\n");
169             }
170         }
171         if (writepls)
172             f.write ("Version=2\n");
173         f.close ();
174     }
175     catch (...)
176     {
177 //        QMessageBox::critical(this, "Write error", "Could not write playlist file", QMessageBox::Ok);
178     }
179 }
180
181 void PlaylistManager::loadPlaylist(const QString& filename)
182 {
183     clearPlaylist();
184     if (filename.right(4).toLower() == ".m3u")
185         appendPlaylist(filename);
186     else if (filename.right(4).toLower() == ".pls")
187         appendPlaylistPLS(filename);
188     if (!items.isEmpty())
189     {
190         metaInformationResolver->setCurrentSource(items.at(0).source);
191         lastMetaRead = 0;
192     }
193     emit playlistChanged (0);
194 }
195
196 void PlaylistManager::addPlaylist(const QString& filename)
197 {
198     int index = items.size();
199     if (filename.right(4).toLower() == ".m3u")
200         appendPlaylist(filename);
201     else if (filename.right(4).toLower() == ".pls")
202         appendPlaylistPLS(filename);
203     if (!items.isEmpty())
204     {
205         metaInformationResolver->setCurrentSource(items.at(index).source);
206         lastMetaRead = index;
207         emit playlistChanged (index);
208     }
209 }
210
211 void PlaylistManager::appendPlaylist(const QString& filename)
212 {
213     qDebug () << "Attempting to load playlist: " << filename;
214     QFile f(filename);
215     if (!f.open (QFile::ReadOnly))
216         return;
217     QString tmp = f.readAll();
218     f.close ();
219     QStringList lines = tmp.split("\n");
220     foreach (QString l, lines)
221     {
222         if (l.isEmpty() || (!QFileInfo (l).exists() && (l.indexOf("http") != 0)))
223         {
224             continue;
225         }
226         qDebug () << "Load " << l;
227         items.append(PlaylistItem (l));
228     }
229 }
230
231 void PlaylistManager::appendPlaylistPLS(const QString& filename)
232 {
233     qDebug () << "Attempting to load playlist: " << filename;
234     QFile f(filename);
235     if (!f.open (QFile::ReadOnly))
236         return;
237     QString tmp = f.readAll();
238     f.close ();
239     QStringList lines = tmp.split("\n");
240     QMap<int, int> filemap;
241
242     foreach (QString l, lines)
243     {
244         if (l.isEmpty() || l.trimmed().toLower() == "[playlist]" || l.trimmed().toLower() == "version=2")
245         {
246             continue;
247         }
248         qDebug () << "PLS " << l;
249         if (l.trimmed().toLower().left(4) == "file")
250         {
251             QStringList tokens = l.split('=');
252             if (tokens.size () < 2)
253                 continue;
254             tokens[0] = tokens[0].mid (4);
255             filemap.insert(tokens[0].toInt (), items.size ());
256             qDebug () << tokens;
257             items.append(PlaylistItem (tokens[1]));
258         }
259         else if (l.trimmed().toLower().left(5) == "title")
260         {
261             QStringList tokens = l.split('=');
262             if (tokens.size () < 2)
263                 continue;
264             tokens[0] = tokens[0].mid (5);
265             int toupdate = filemap[tokens[0].toInt()];
266             qDebug () << "Need to update " << toupdate << " for " << l;
267             QStringList metatok = tokens[1].split (" - ");
268             qDebug () << metatok;
269             if (metatok.size() > 2 && toupdate >= 0 && toupdate < items.size ())
270             {
271                 items[toupdate].artist = metatok[0];
272                 items[toupdate].title = metatok[1];
273                 metatok = metatok.mid (2);
274                 items[toupdate].album = metatok.join (" - ");
275             }
276             else
277             {
278                 items[toupdate].title = metatok.join (" - ");
279             }
280         }
281     }
282 }
283
284
285 void PlaylistManager::clearPlaylist()
286 {
287     items.clear();
288     emit playlistChanged(0);
289 /*    while (musicTable->rowCount())
290         musicTable->removeRow(0);
291     mediaObject->clear();*/
292 }
293
294 QStringList PlaylistManager::playlistStrings() const
295 {
296     QStringList ret;
297     for (int i = 0; i < items.size (); ++i)
298         ret << items[i].uri;
299     qDebug () << "Returning playlist " << ret << " SIZE: " << items.size ();
300     return ret;
301 }
302
303 void PlaylistManager::removeItem(int i)
304 {
305     items.removeAt (i);
306     emit playlistChanged(i);
307 }
308
309 bool PlaylistManager::fileSupported (const QString& fname) const
310 {
311     QString ext = fname.right(3).toLower();
312     foreach (QString e, allowedExtensions)
313     {
314         if (ext == e)
315             return true;
316     }
317
318     return false;
319 }