Version bump
[someplayer] / src / filestorage.cpp
1 /*
2  * SomePlayer - An alternate music player for Maemo 5
3  * Copyright (C) 2010 Nikolay (somebody) Tischenko <niktischenko@gmail.com>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18  */
19
20 #include "filestorage.h"
21 #include <QDir>
22 #include <QDirIterator>
23 #include <QFileInfo>
24 #include <QTextStream>
25 #include <QtXml/QtXml>
26 // legacy _start_
27 #include <QRegExp>
28 // legacy _end_
29
30 using namespace SomePlayer::Storage;
31 using namespace SomePlayer::DataObjects;
32
33 FileStorage::FileStorage(QString path) {
34         _path_prefix = path;
35
36         Playlist current = getCurrentPlaylist();
37         if (current.name() == PLAYLIST_BAD_NAME) {
38                 current.setName(_CURRENT_PLAYLIST_NAME_);
39                 saveCurrentPlaylist(current);
40         }
41 }
42
43 QList<Playlist> FileStorage::getPlaylists() {
44         QList<Playlist> stub;
45         return stub;
46 }
47
48 Playlist FileStorage::getPlaylist(QString name) {
49         if (name == _CURRENT_PLAYLIST_SUBST_)
50                 name = _CURRENT_PLAYLIST_NAME_;
51         QFile playlistFile (_path_prefix + "/" + name + "." + _PLAYLIST_FILE_EXTENSION_OLD_); // remove OLD_ in next version
52         Playlist playlist;
53         playlist.setName(PLAYLIST_BAD_NAME);
54         // legacy _start_
55         if (playlistFile.exists()) {
56                 qWarning() << "Old playlist file format deteced";
57                 QRegExp meta_regexp;
58                 meta_regexp.setPattern("#META\\ +\\[(\\d+)\\]\\[(\\d+)\\].*::(.+)::,::(.+)::,::(.+)::");
59                 QRegExp path_regexp;
60                 path_regexp.setPattern("#PATH (.+)");
61                 playlistFile.open(QFile::ReadOnly);
62                 QTextStream stream(&playlistFile);
63                 QString buffer = stream.readLine();
64                 if (buffer.startsWith("#SOMEPLAYLIST")) {
65                         while (!stream.atEnd()) {
66                                 buffer = stream.readLine();
67                                 if (meta_regexp.indexIn(buffer) != -1) {
68                                         int seconds = meta_regexp.cap(2).toInt();
69                                         QString artist = meta_regexp.cap(3);
70                                         QString album = meta_regexp.cap(4);
71                                         QString title = meta_regexp.cap(5);
72                                         buffer = stream.readLine();
73                                         if (path_regexp.indexIn(buffer) != -1) {
74                                                 QString source = path_regexp.cap(1);
75                                                 TrackMetadata meta(title, artist, album, seconds);
76                                                 Track track(meta, source);
77                                                 playlist.addTrack(track);
78                                         }
79                                 }
80                         }
81                 }
82                 playlist.setName(name);
83                 qWarning() << "Saving playlist in new format";
84                 savePlaylist(playlist);
85                 playlistFile.close();
86                 playlistFile.remove();
87         } else {
88                 playlistFile.setFileName(_path_prefix + "/" + name + "." + _PLAYLIST_FILE_EXTENSION_);
89         // legacy _end_
90                 if (playlistFile.exists()) {
91                         playlist.setName(name);
92                         QDomDocument doc;
93                         playlistFile.open(QFile::ReadOnly);
94                         doc.setContent(&playlistFile);
95                         playlistFile.close();
96                         QDomElement eplaylist = doc.documentElement();
97                         if (eplaylist.tagName() == "playlist") {
98                                 QDomElement etracklist = eplaylist.firstChildElement("trackList");
99                                 if (!etracklist.isNull()) {
100                                         QDomElement etrack = etracklist.firstChildElement("track");
101                                         while (!etrack.isNull()) {
102                                                 QDomElement elocation = etrack.firstChildElement("location");
103                                                 QDomElement eextension = etrack.firstChildElement("extension");
104                                                 if (!eextension.isNull()) {
105                                                         QDomElement ecl_clip = eextension.firstChildElement("cl:clip");
106                                                         if (!ecl_clip.isNull()) {
107                                                                 QString artist = ecl_clip.attribute("artist");
108                                                                 QString album = ecl_clip.attribute("album");
109                                                                 QString title = ecl_clip.attribute("title");
110                                                                 QDomElement eduration = etrack.firstChildElement("duration");
111                                                                 if (!eduration.isNull()) {
112                                                                         QVariant duration = eduration.text();
113                                                                         QByteArray basource;
114                                                                         basource.append(elocation.text());
115                                                                         QString source = QUrl::fromEncoded(basource).toLocalFile();
116                                                                         TrackMetadata meta(title, artist, album, duration.toInt()/1000);
117                                                                         Track track(meta, source);
118                                                                         playlist.addTrack(track);
119                                                                 }
120                                                         }
121                                                 }
122                                                 etrack = etrack.nextSiblingElement("track");
123                                         }
124                                 }
125                         }
126         // legacy _start_
127                 }
128         // legacy _end_
129         }
130         return playlist;
131 }
132
133 QStringList FileStorage::getPlaylistsNames() {
134         QDir directory(_path_prefix);
135         QDirIterator iterator(directory, QDirIterator::FollowSymlinks);
136         QStringList playlistNames;
137         while (iterator.hasNext()) {
138                 QString entry = iterator.next();
139                 QFileInfo info(entry);
140                 QString suffix = info.suffix().toLower();
141                 if (suffix == _PLAYLIST_FILE_EXTENSION_) {
142                         QString name = info.fileName().replace(QString(".%1").arg(_PLAYLIST_FILE_EXTENSION_), "", Qt::CaseInsensitive);
143                         if (name == _CURRENT_PLAYLIST_NAME_)
144                             name = _CURRENT_PLAYLIST_SUBST_;
145                         playlistNames.append(name);
146                 }
147                 // legacy _start_
148                 else if (suffix == _PLAYLIST_FILE_EXTENSION_OLD_){
149                         QString name = info.fileName().replace(QString(".%1").arg(_PLAYLIST_FILE_EXTENSION_OLD_), "", Qt::CaseInsensitive);
150                         if (name == _CURRENT_PLAYLIST_NAME_)
151                             name = _CURRENT_PLAYLIST_SUBST_;
152                         playlistNames.append(name);
153                 }
154                 // legacy _end_
155         }
156         return playlistNames;
157 }
158
159 void FileStorage::savePlaylist(Playlist playlist) {
160         QString name = playlist.name();
161         if (playlist.name() == _CURRENT_PLAYLIST_SUBST_)
162                 name = _CURRENT_PLAYLIST_NAME_;
163         QString filename = _path_prefix + "/" + name + "."_PLAYLIST_FILE_EXTENSION_;
164         QFile playlistFile(filename);
165         if (playlistFile.exists()) {
166                 playlistFile.remove();
167         }
168         playlistFile.open(QFile::WriteOnly);
169         QTextStream stream(&playlistFile);
170         QDomDocument doc;
171         QDomElement root = doc.createElement("playlist");
172         root.setAttribute("version", "1");
173         root.setAttribute("xmlns", "http://xspf.org/ns/0/");
174         root.setAttribute("xmlns:cl", "http://example.com");
175         QDomElement tracklist = doc.createElement("trackList");
176         foreach (Track track, playlist.tracks()) {
177                 QDomElement etrack = doc.createElement("track");
178                 QDomElement elocation = doc.createElement("location");
179                 QDomElement eextension = doc.createElement("extension");
180                 QDomElement ecl_clip = doc.createElement("cl:clip");
181                 QDomElement etitle = doc.createElement("title");
182                 QDomElement eduration = doc.createElement("duration");
183                 etitle.appendChild(doc.createTextNode(QString("%1 - %2").arg(track.metadata().artist()).arg(track.metadata().title())));
184                 ecl_clip.setAttribute("title", track.metadata().title());
185                 ecl_clip.setAttribute("artist", track.metadata().artist());
186                 ecl_clip.setAttribute("album", track.metadata().album());
187                 eextension.appendChild(ecl_clip);
188                 eextension.setAttribute("application", "http://example.com");
189                 elocation.appendChild(doc.createTextNode(QString("%1").arg(QUrl::fromLocalFile(track.source()).toEncoded().constData())));
190                 eduration.appendChild(doc.createTextNode(QString("%1").arg(track.metadata().length()*1000)));
191                 etrack.appendChild(elocation);
192                 etrack.appendChild(eextension);
193                 etrack.appendChild(etitle);
194                 etrack.appendChild(eduration);
195                 tracklist.appendChild(etrack);
196         }
197         root.appendChild(tracklist);
198         doc.appendChild(root);
199         stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
200         stream << doc.toString();
201 }
202
203 void FileStorage::removePlaylist(Playlist playlist) {
204         QString filename = _path_prefix + "/" + playlist.name() + "." + _PLAYLIST_FILE_EXTENSION_;
205         QFile file(filename);
206         file.remove();
207 }
208
209 void FileStorage::removePlaylist(QString name) {
210         QString filename = _path_prefix + "/" + (name == _CURRENT_PLAYLIST_SUBST_ ? _CURRENT_PLAYLIST_NAME_ : name)
211                            + "." + _PLAYLIST_FILE_EXTENSION_;
212         QFile file(filename);
213         file.remove();
214 }
215
216 void FileStorage::importPlaylist(QString name) {
217         QRegExp forname("^.+\\/([^/]+)\\.[^.]+");
218         QRegExp fordir("(.+)\\/");
219         QString plsnam(name);
220         QString dir(name);
221         if (plsnam.indexOf(forname) == -1) {
222                 return;
223         }
224         if (dir.indexOf(fordir) == -1) {
225                 return;
226         }
227         dir = fordir.cap(1);
228         plsnam = forname.cap(1);
229         QStringList existed = getPlaylistsNames();
230         if (existed.contains(plsnam)) {
231                 return;
232         }
233         QFile plsfile (name);
234         plsfile.open(QFile::ReadOnly);
235         QTextStream stream(&plsfile);
236         QStringList trackfiles;
237         while (!stream.atEnd()) {
238                 QString buf = stream.readLine();
239                 if (buf.startsWith("#")) {
240                         continue;
241                 }
242                 if (buf.startsWith("/")) {
243                         trackfiles.append(buf);
244                 } else {
245                         trackfiles.append(dir+"/"+buf);
246                 }
247         }
248         QList<Track> tracks;
249         TagResolver resover;
250         foreach (QString trackfile, trackfiles) {
251                 if (!QFile::exists(trackfile)) {
252                         continue;
253                 }
254                 tracks.append(resover.decodeOne(trackfile));
255         }
256         Playlist playlist;
257         playlist.setName(plsnam);
258         playlist.setTracks(tracks);
259         savePlaylist(playlist);
260 }
261
262 Playlist FileStorage::getCurrentPlaylist() {
263         return getPlaylist(_CURRENT_PLAYLIST_NAME_);
264 }
265
266 void FileStorage::saveCurrentPlaylist(Playlist playlist) {
267         playlist.setName(_CURRENT_PLAYLIST_NAME_);
268         savePlaylist(playlist);
269 }
270
271 LastPlayed FileStorage::getLastPlayedForCurPlaylist() {
272         QFile playlistFile (_path_prefix + "/" + _CURRENT_PLAYLIST_NAME_ + "." + _PLAYLIST_FILE_EXTENSION_);
273         int trackId = 0;
274         int position = 0;
275         if (playlistFile.exists()) {
276                 QDomDocument doc;
277                 playlistFile.open(QFile::ReadOnly);
278                 doc.setContent(&playlistFile);
279                 playlistFile.close();
280                 QDomElement eplaylist = doc.documentElement();
281                 if (eplaylist.tagName() == "playlist") {
282                         QDomElement eextension = eplaylist.firstChildElement("extension");
283                         if (!eextension.isNull()) {
284                                 QDomElement elastplay = eextension.firstChildElement("lastplay");
285                                 if (!elastplay.isNull()) {
286                                         trackId = elastplay.attribute("track_id").toInt();
287                                         position = elastplay.attribute("position").toInt();
288                                 }
289                         }
290                 }
291         }
292         LastPlayed lp = {trackId, position};
293         return lp;
294 }
295
296 void FileStorage::saveLastPlayedForCurPlaylist(LastPlayed lastplayed) {
297         QFile playlistFile (_path_prefix + "/" + _CURRENT_PLAYLIST_NAME_ + "." + _PLAYLIST_FILE_EXTENSION_);
298         QDomDocument doc;
299         if (playlistFile.exists()) {
300                 playlistFile.open(QFile::ReadOnly);
301                 doc.setContent(&playlistFile);
302                 playlistFile.close();
303                 QDomElement eplaylist = doc.documentElement();
304                 if (eplaylist.tagName() == "playlist") {
305                         QDomElement eextension = eplaylist.firstChildElement("extension");
306                         if (eextension.isNull()) {
307                                 eextension = doc.createElement("extension");
308                                 eextension.setAttribute("application", "http://example.com");
309                                 QDomElement elastplay = doc.createElement("lastplay");
310                                 elastplay.setAttribute("track_id", lastplayed.trackId);
311                                 elastplay.setAttribute("position", lastplayed.position);
312                                 eextension.appendChild(elastplay);
313                                 eplaylist.appendChild(eextension);
314                         } else {
315                                 QDomElement elastplay = eextension.firstChildElement("lastplay");
316                                 if (elastplay.isNull()) {
317                                         elastplay = doc.createElement("lastplay");
318                                         eextension.appendChild(elastplay);
319                                 }
320                                 elastplay.setAttribute("track_id", lastplayed.trackId);
321                                 elastplay.setAttribute("position", lastplayed.position);
322                         }
323                 }
324         }
325         playlistFile.open(QFile::WriteOnly);
326         QTextStream stream(&playlistFile);
327         stream << doc.toString();
328 }