PlaylistFile.cxx 9.07 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 The Music Player Daemon Project
3
 * http://www.musicpd.org
4 5 6 7 8 9 10 11 12 13
 *
 * 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.
14 15 16 17
 *
 * 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.
18 19
 */

20
#include "config.h"
Max Kellermann's avatar
Max Kellermann committed
21
#include "PlaylistFile.hxx"
22
#include "PlaylistSave.hxx"
23
#include "PlaylistError.hxx"
24 25
#include "db/PlaylistInfo.hxx"
#include "db/PlaylistVector.hxx"
26
#include "song/DetachedSong.hxx"
27
#include "SongLoader.hxx"
Max Kellermann's avatar
Max Kellermann committed
28
#include "Mapper.hxx"
29
#include "fs/io/TextFile.hxx"
30 31
#include "fs/io/FileOutputStream.hxx"
#include "fs/io/BufferedOutputStream.hxx"
32
#include "config/Data.hxx"
33 34
#include "config/Option.hxx"
#include "config/Defaults.hxx"
Max Kellermann's avatar
Max Kellermann committed
35
#include "Idle.hxx"
36
#include "fs/Limits.hxx"
37
#include "fs/AllocatedPath.hxx"
38
#include "fs/Traits.hxx"
39
#include "fs/FileSystem.hxx"
40
#include "fs/FileInfo.hxx"
41
#include "fs/DirectoryReader.hxx"
42
#include "util/Macros.hxx"
43
#include "util/StringCompare.hxx"
Max Kellermann's avatar
Max Kellermann committed
44
#include "util/UriUtil.hxx"
45

46 47
#include <memory>

Max Kellermann's avatar
Max Kellermann committed
48 49
#include <assert.h>
#include <string.h>
50
#include <errno.h>
51

52 53
static const char PLAYLIST_COMMENT = '#';

54 55 56 57
static unsigned playlist_max_length;
bool playlist_saveAbsolutePaths = DEFAULT_PLAYLIST_SAVE_ABSOLUTE_PATHS;

void
58
spl_global_init(const ConfigData &config)
59
{
60
	playlist_max_length =
61 62
		config.GetPositive(ConfigOption::MAX_PLAYLIST_LENGTH,
				   DEFAULT_PLAYLIST_MAX_LENGTH);
63 64

	playlist_saveAbsolutePaths =
65 66
		config.GetBool(ConfigOption::SAVE_ABSOLUTE_PATHS,
			       DEFAULT_PLAYLIST_SAVE_ABSOLUTE_PATHS);
67 68
}

69 70 71
bool
spl_valid_name(const char *name_utf8)
{
72
	if (StringIsEmpty(name_utf8))
73 74 75
		/* empty name not allowed */
		return false;

76 77 78 79 80 81 82 83 84 85 86
	/*
	 * Not supporting '/' was done out of laziness, and we should
	 * really strive to support it in the future.
	 *
	 * Not supporting '\r' and '\n' is done out of protocol
	 * limitations (and arguably laziness), but bending over head
	 * over heels to modify the protocol (and compatibility with
	 * all clients) to support idiots who put '\r' and '\n' in
	 * filenames isn't going to happen, either.
	 */

87 88 89
	return strchr(name_utf8, '/') == nullptr &&
		strchr(name_utf8, '\n') == nullptr &&
		strchr(name_utf8, '\r') == nullptr;
90 91
}

92
static const AllocatedPath &
93
spl_map()
94
{
95
	const AllocatedPath &path_fs = map_spl_path();
96
	if (path_fs.IsNull())
97 98 99
		throw PlaylistError(PlaylistResult::DISABLED,
				    "Stored playlists are disabled");

100
	return path_fs;
101 102
}

103 104
static void
spl_check_name(const char *name_utf8)
105
{
106 107
	if (!spl_valid_name(name_utf8))
		throw PlaylistError(PlaylistResult::BAD_NAME,
108 109 110
				    "Bad playlist name");
}

111
AllocatedPath
112
spl_map_to_fs(const char *name_utf8)
113
{
114 115
	spl_map();
	spl_check_name(name_utf8);
116

117
	auto path_fs = map_spl_utf8_to_fs(name_utf8);
118
	if (path_fs.IsNull())
119 120
		throw PlaylistError(PlaylistResult::BAD_NAME,
				    "Bad playlist name");
121 122 123 124

	return path_fs;
}

125
static bool
126
LoadPlaylistFileInfo(PlaylistInfo &info,
127 128
		     const Path parent_path_fs,
		     const Path name_fs)
129
{
130 131 132
	if (name_fs.HasNewline())
		return false;

133
	const auto *const name_fs_str = name_fs.c_str();
134
	const auto *const name_fs_end =
135 136
		FindStringSuffix(name_fs_str,
				 PATH_LITERAL(PLAYLIST_FILE_SUFFIX));
137 138 139
	if (name_fs_end == nullptr ||
	    /* no empty playlist names (raw file name = ".m3u") */
	    name_fs_end == name_fs_str)
140
		return false;
141

142
	FileInfo fi;
143
	if (!GetFileInfo(parent_path_fs / name_fs, fi) ||
144
	    !fi.IsRegular())
145
		return false;
146

147
	const auto name = AllocatedPath::FromFS(name_fs_str, name_fs_end);
148 149 150 151

	try {
		info.name = name.ToUTF8Throw();
	} catch (...) {
152
		return false;
153
	}
154

155
	info.mtime = fi.GetModificationTime();
156
	return true;
157 158
}

159
PlaylistVector
160
ListPlaylistFiles()
161
{
162
	PlaylistVector list;
163

164 165
	const auto &parent_path_fs = spl_map();
	assert(!parent_path_fs.IsNull());
166

167
	DirectoryReader reader(parent_path_fs);
168

169
	PlaylistInfo info;
170
	while (reader.ReadEntry()) {
171
		const auto entry = reader.GetEntry();
172
		if (LoadPlaylistFileInfo(info, parent_path_fs, entry))
173
			list.push_back(std::move(info));
174 175 176 177 178
	}

	return list;
}

179 180
static void
SavePlaylistFile(const PlaylistFileContents &contents, const char *utf8path)
181
{
182
	assert(utf8path != nullptr);
183

184 185
	const auto path_fs = spl_map_to_fs(utf8path);
	assert(!path_fs.IsNull());
186

187
	FileOutputStream fos(path_fs);
188 189
	BufferedOutputStream bos(fos);

190
	for (const auto &uri_utf8 : contents)
191
		playlist_print_uri(bos, uri_utf8.c_str());
192

193
	bos.Flush();
194 195

	fos.Commit();
196 197
}

198
PlaylistFileContents
199
LoadPlaylistFile(const char *utf8path)
200
try {
201 202
	PlaylistFileContents contents;

203 204
	const auto path_fs = spl_map_to_fs(utf8path);
	assert(!path_fs.IsNull());
205

206
	TextFile file(path_fs);
207

208
	char *s;
209
	while ((s = file.ReadLine()) != nullptr) {
210
		if (*s == 0 || *s == PLAYLIST_COMMENT)
211
			continue;
212

213
#ifdef _UNICODE
214 215 216 217 218
		/* on Windows, playlists always contain UTF-8, because
		   its "narrow" charset (i.e. CP_ACP) is incapable of
		   storing all Unicode paths */
		const auto path = AllocatedPath::FromUTF8(s);
		if (path.IsNull())
219 220
			continue;
#else
Max Kellermann's avatar
Max Kellermann committed
221
		const Path path = Path::FromFS(s);
222
#endif
Max Kellermann's avatar
Max Kellermann committed
223

224 225
		std::string uri_utf8;

226
		if (!uri_has_scheme(s)) {
227
#ifdef ENABLE_DATABASE
Max Kellermann's avatar
Max Kellermann committed
228
			uri_utf8 = map_fs_to_utf8(path);
229
			if (uri_utf8.empty()) {
Max Kellermann's avatar
Max Kellermann committed
230
				if (path.IsAbsolute()) {
231
					uri_utf8 = path.ToUTF8();
232 233 234 235 236
					if (uri_utf8.empty())
						continue;
				} else
					continue;
			}
237 238 239
#else
			continue;
#endif
240
		} else {
Max Kellermann's avatar
Max Kellermann committed
241
			uri_utf8 = path.ToUTF8();
242
			if (uri_utf8.empty())
243 244
				continue;
		}
245

246
		contents.emplace_back(std::move(uri_utf8));
247
		if (contents.size() >= playlist_max_length)
248
			break;
249 250
	}

251
	return contents;
252 253 254 255
} catch (const std::system_error &e) {
	if (IsFileNotFound(e))
		throw PlaylistError::NoSuchList();
	throw;
256 257
}

258 259
void
spl_move_index(const char *utf8path, unsigned src, unsigned dest)
260
{
261 262 263
	if (src == dest)
		/* this doesn't check whether the playlist exists, but
		   what the hell.. */
264
		return;
265

266
	auto contents = LoadPlaylistFile(utf8path);
267

268 269
	if (src >= contents.size() || dest >= contents.size())
		throw PlaylistError(PlaylistResult::BAD_RANGE, "Bad range");
270

271 272 273
	const auto src_i = std::next(contents.begin(), src);
	auto value = std::move(*src_i);
	contents.erase(src_i);
274

275 276
	const auto dest_i = std::next(contents.begin(), dest);
	contents.insert(dest_i, std::move(value));
277

278
	SavePlaylistFile(contents, utf8path);
279 280

	idle_add(IDLE_STORED_PLAYLIST);
281 282
}

283 284
void
spl_clear(const char *utf8path)
285
{
286 287
	const auto path_fs = spl_map_to_fs(utf8path);
	assert(!path_fs.IsNull());
288

289 290 291 292 293 294 295 296 297
	try {
		TruncateFile(path_fs);
	} catch (const std::system_error &e) {
		if (IsFileNotFound(e))
			throw PlaylistError(PlaylistResult::NO_SUCH_LIST,
					    "No such playlist");
		else
			throw;
	}
298 299

	idle_add(IDLE_STORED_PLAYLIST);
300 301
}

302 303
void
spl_delete(const char *name_utf8)
304
{
305 306
	const auto path_fs = spl_map_to_fs(name_utf8);
	assert(!path_fs.IsNull());
307

308 309 310 311 312 313 314 315 316
	try {
		RemoveFile(path_fs);
	} catch (const std::system_error &e) {
		if (IsFileNotFound(e))
			throw PlaylistError(PlaylistResult::NO_SUCH_LIST,
					    "No such playlist");
		else
			throw;
	}
317

318
	idle_add(IDLE_STORED_PLAYLIST);
319 320
}

321 322
void
spl_remove_index(const char *utf8path, unsigned pos)
323
{
324
	auto contents = LoadPlaylistFile(utf8path);
325

326 327
	if (pos >= contents.size())
		throw PlaylistError(PlaylistResult::BAD_RANGE, "Bad range");
328

329
	contents.erase(std::next(contents.begin(), pos));
330

331
	SavePlaylistFile(contents, utf8path);
332
	idle_add(IDLE_STORED_PLAYLIST);
333 334
}

335 336
void
spl_append_song(const char *utf8path, const DetachedSong &song)
337
try {
338 339
	const auto path_fs = spl_map_to_fs(utf8path);
	assert(!path_fs.IsNull());
340

341
	FileOutputStream fos(path_fs, FileOutputStream::Mode::APPEND_OR_CREATE);
342

343 344 345
	if (fos.Tell() / (MPD_PATH_MAX + 1) >= playlist_max_length)
		throw PlaylistError(PlaylistResult::TOO_LARGE,
				    "Stored playlist is too large");
346

347
	BufferedOutputStream bos(fos);
348

349 350
	playlist_print_song(bos, song);

351
	bos.Flush();
352 353
	fos.Commit();

354
	idle_add(IDLE_STORED_PLAYLIST);
355 356 357 358
} catch (const std::system_error &e) {
	if (IsFileNotFound(e))
		throw PlaylistError::NoSuchList();
	throw;
359 360
}

361
void
362
spl_append_uri(const char *utf8file,
363
	       const SongLoader &loader, const char *url)
364
{
365
	spl_append_song(utf8file, loader.LoadSong(url));
366 367
}

368 369
static void
spl_rename_internal(Path from_path_fs, Path to_path_fs)
370
{
371 372 373
	if (FileExists(to_path_fs))
		throw PlaylistError(PlaylistResult::LIST_EXISTS,
				    "Playlist exists already");
374

375 376 377
	try {
		RenameFile(from_path_fs, to_path_fs);
	} catch (const std::system_error &e) {
378
		if (IsFileNotFound(e))
379 380 381 382 383
			throw PlaylistError(PlaylistResult::NO_SUCH_LIST,
					    "No such playlist");
		else
			throw;
	}
384

385
	idle_add(IDLE_STORED_PLAYLIST);
386
}
387

388 389
void
spl_rename(const char *utf8from, const char *utf8to)
390
{
391 392
	const auto from_path_fs = spl_map_to_fs(utf8from);
	assert(!from_path_fs.IsNull());
393

394 395
	const auto to_path_fs = spl_map_to_fs(utf8to);
	assert(!to_path_fs.IsNull());
396

397
	spl_rename_internal(from_path_fs, to_path_fs);
398
}