notification on playlist save error, small changes
[tomamp] / 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     if (items.size () > index)
63     {
64         metaInformationResolver->setCurrentSource(items.at(index).source);
65         lastMetaRead = index;
66     }
67     qDebug () << " SIZE: " << items.size ();
68     emit playlistChanged (index);
69 }
70
71 void PlaylistManager::addStringList(const QStringList& list)
72 {
73     int index = items.size();
74     foreach (QString string, list)
75     {
76         if (fileSupported(string) || string.toLower().startsWith("http"))
77         {
78             qDebug () << "Adding " << string;
79             items.append(PlaylistItem (string));
80         }
81     }
82 //    if (!items.isEmpty())
83     if (items.size () > index)
84     {
85         metaInformationResolver->setCurrentSource(items.at(index).source);
86         lastMetaRead = index;
87     }
88     emit playlistChanged(index);
89 }
90
91 void PlaylistManager::metaStateChanged(Phonon::State newState, Phonon::State oldState)
92 {
93     qDebug () << "Meta state now " << newState << " old state " << oldState;
94     // This is an ugly hack, since the metaInformationResolver doesn't properly load the assigned source when it's in the error state
95     // 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
96     static bool wasError = false;
97     if (wasError && newState == Phonon::StoppedState)
98     {
99         metaInformationResolver->setCurrentSource(items[lastMetaRead].source);
100         wasError = false;
101         return;
102     }
103     if (newState == Phonon::ErrorState)
104     {
105         wasError = true;
106     }
107
108     if (newState != Phonon::StoppedState && newState != Phonon::ErrorState)
109     {
110         return;
111     }
112
113     int index = lastMetaRead;
114     qDebug () << "Reading meta info of " << metaInformationResolver->currentSource().fileName() << " => " << index;
115
116     QMap<QString, QString> metaData = metaInformationResolver->metaData();
117
118
119     if (index >= 0 && newState != Phonon::ErrorState && index < items.size ())
120     {
121         items[index].artist = metaData.value("ARTIST");
122         items[index].title = metaData.value("TITLE");
123         items[index].album = metaData.value("ALBUM");
124 /*        items[index].year = metaData.value("DATE");
125         items[index].genre = metaData.value("GENRE");
126         qDebug () << "Meta " << metaData;
127         qDebug () << "Info is: " << items[index].year << " - " << items[index].genre;*/
128         if (metaData.isEmpty())
129             qDebug () << "Detected to be empty: " << items[index].uri;
130         else
131             items[index].playable = true;
132         emit itemUpdated (index);
133     }
134     if (index >= 0 && items.size () > index + 1)
135     {
136         metaInformationResolver->setCurrentSource(items[index + 1].source);
137         lastMetaRead = index + 1;
138     }
139 }
140
141 bool PlaylistManager::savePlaylist(const QString& filenam)
142 {
143     QString filename = filenam;
144     if (filename.isEmpty())
145         return false;
146     bool writepls = false;
147     if (filename.length() < 4 || (filename.right(4).toLower() != ".m3u" && filename.right(4).toLower() != ".pls"))
148     {
149         filename += ".pls";
150         writepls = true;
151     }
152     else if (filename.right(4).toLower() == ".pls")
153         writepls = true;
154     QFile f (filename);
155     try
156     {
157         f.open(QFile::WriteOnly);
158         if (writepls)
159         {
160             f.write ("[playlist]\n");
161             f.write (QString ("NumberOfEntries=%1\n").arg (items.size ()).toAscii());
162         }
163         for (int i = 0; i < items.size(); ++i)
164         {
165             if (writepls)
166             {
167                 f.write (QString ("File%1=%2\n").arg (i + 1).arg (items[i].uri).toAscii());
168                 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());
169             }
170             else
171             {
172                 f.write (items[i].uri.toAscii());
173                 f.write ("\n");
174             }
175         }
176         if (writepls)
177             f.write ("Version=2\n");
178         f.close ();
179         return true;
180     }
181     catch (...)
182     {
183     }
184     return false;
185 }
186
187 void PlaylistManager::loadPlaylist(const QString& filename)
188 {
189     clearPlaylist();
190     if (filename.right(4).toLower() == ".m3u")
191         appendPlaylist(filename);
192     else if (filename.right(4).toLower() == ".pls")
193         appendPlaylistPLS(filename);
194     if (!items.isEmpty())
195     {
196         metaInformationResolver->setCurrentSource(items.at(0).source);
197         lastMetaRead = 0;
198     }
199     emit playlistChanged (0);
200 }
201
202 void PlaylistManager::addPlaylist(const QString& filename)
203 {
204     int index = items.size();
205     if (filename.right(4).toLower() == ".m3u")
206         appendPlaylist(filename);
207     else if (filename.right(4).toLower() == ".pls")
208         appendPlaylistPLS(filename);
209     if (items.size () > index)
210 //    if (!items.isEmpty())
211     {
212         metaInformationResolver->setCurrentSource(items.at(index).source);
213         lastMetaRead = index;
214         emit playlistChanged (index);
215     }
216 }
217
218 void PlaylistManager::appendPlaylist(const QString& filename)
219 {
220     qDebug () << "Attempting to load playlist: " << filename;
221     QFile f(filename);
222     if (!f.open (QFile::ReadOnly))
223         return;
224     QString tmp = f.readAll();
225     f.close ();
226     QStringList lines = tmp.split("\n");
227     foreach (QString l, lines)
228     {
229         if (l.isEmpty() || (!QFileInfo (l).exists() && (l.indexOf("http") != 0)))
230         {
231             continue;
232         }
233         qDebug () << "Load " << l;
234         items.append(PlaylistItem (l));
235     }
236 }
237
238 void PlaylistManager::appendPlaylistPLS(const QString& filename)
239 {
240     qDebug () << "Attempting to load playlist: " << filename;
241     QFile f(filename);
242     if (!f.open (QFile::ReadOnly))
243         return;
244     QString tmp = f.readAll();
245     f.close ();
246     QStringList lines = tmp.split("\n");
247     QMap<int, int> filemap;
248
249     foreach (QString l, lines)
250     {
251         if (l.isEmpty() || l.trimmed().toLower() == "[playlist]" || l.trimmed().toLower() == "version=2")
252         {
253             continue;
254         }
255         qDebug () << "PLS " << l;
256         if (l.trimmed().toLower().left(4) == "file")
257         {
258             QStringList tokens = l.split('=');
259             if (tokens.size () < 2)
260                 continue;
261             tokens[0] = tokens[0].mid (4);
262             filemap.insert(tokens[0].toInt (), items.size ());
263             qDebug () << tokens;
264             items.append(PlaylistItem (tokens[1]));
265         }
266         else if (l.trimmed().toLower().left(5) == "title")
267         {
268             QStringList tokens = l.split('=');
269             if (tokens.size () < 2)
270                 continue;
271             tokens[0] = tokens[0].mid (5);
272             int toupdate = filemap[tokens[0].toInt()];
273             qDebug () << "Need to update " << toupdate << " for " << l;
274             QStringList metatok = tokens[1].split (" - ");
275             qDebug () << metatok;
276             if (metatok.size() > 2 && toupdate >= 0 && toupdate < items.size ())
277             {
278                 items[toupdate].artist = metatok[0];
279                 items[toupdate].title = metatok[1];
280                 metatok = metatok.mid (2);
281                 items[toupdate].album = metatok.join (" - ");
282             }
283             else
284             {
285                 items[toupdate].title = metatok.join (" - ");
286             }
287         }
288     }
289 }
290
291
292 void PlaylistManager::clearPlaylist()
293 {
294     items.clear();
295     emit playlistChanged(0);
296 /*    while (musicTable->rowCount())
297         musicTable->removeRow(0);
298     mediaObject->clear();*/
299 }
300
301 QStringList PlaylistManager::playlistStrings() const
302 {
303     QStringList ret;
304     for (int i = 0; i < items.size (); ++i)
305         ret << items[i].uri;
306     qDebug () << "Returning playlist " << ret << " SIZE: " << items.size ();
307     return ret;
308 }
309
310 void PlaylistManager::removeItem(int i)
311 {
312     items.removeAt (i);
313     emit itemRemoved(i);
314 }
315
316
317 bool PlaylistManager::fileSupported (const QString& fname) const
318 {
319     QString ext = fname.right(3).toLower();
320     foreach (QString e, allowedExtensions)
321     {
322         if (ext == e)
323             return true;
324     }
325
326     return false;
327 }
328
329 bool PlaylistManager::moveItemUp (int i)
330 {
331     if (i)
332     {
333         PlaylistItem tmp = items[i - 1];
334         items[i - 1] = items[i];
335         items[i] = tmp;
336         return true;
337 //        emit playlistChanged(i - 1);
338     }
339     return false;
340 }
341
342 bool PlaylistManager::moveItemDown (int i)
343 {
344     if (i < items.size () - 1)
345     {
346         PlaylistItem tmp = items[i + 1];
347         items[i + 1] = items[i];
348         items[i] = tmp;
349         return true;
350 //        emit playlistChanged(i - 1);
351     }
352     return false;
353 }