PlaylistFile.cxx 8.98 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 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
	if (name_fs_end == nullptr)
138
		return false;
139

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

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

	try {
		info.name = name.ToUTF8Throw();
	} catch (...) {
150
		return false;
151
	}
152

153
	info.mtime = fi.GetModificationTime();
154
	return true;
155 156
}

157
PlaylistVector
158
ListPlaylistFiles()
159
{
160
	PlaylistVector list;
161

162 163
	const auto &parent_path_fs = spl_map();
	assert(!parent_path_fs.IsNull());
164

165
	DirectoryReader reader(parent_path_fs);
166

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

	return list;
}

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

182 183
	const auto path_fs = spl_map_to_fs(utf8path);
	assert(!path_fs.IsNull());
184

185
	FileOutputStream fos(path_fs);
186 187
	BufferedOutputStream bos(fos);

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

191
	bos.Flush();
192 193

	fos.Commit();
194 195
}

196
PlaylistFileContents
197
LoadPlaylistFile(const char *utf8path)
198
try {
199 200
	PlaylistFileContents contents;

201 202
	const auto path_fs = spl_map_to_fs(utf8path);
	assert(!path_fs.IsNull());
203

204
	TextFile file(path_fs);
205

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

211
#ifdef _UNICODE
212 213 214 215 216
		/* 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())
217 218
			continue;
#else
Max Kellermann's avatar
Max Kellermann committed
219
		const Path path = Path::FromFS(s);
220
#endif
Max Kellermann's avatar
Max Kellermann committed
221

222 223
		std::string uri_utf8;

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

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

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

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

264
	auto contents = LoadPlaylistFile(utf8path);
265

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

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

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

276
	SavePlaylistFile(contents, utf8path);
277 278

	idle_add(IDLE_STORED_PLAYLIST);
279 280
}

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

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

	idle_add(IDLE_STORED_PLAYLIST);
298 299
}

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

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

316
	idle_add(IDLE_STORED_PLAYLIST);
317 318
}

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

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

327
	contents.erase(std::next(contents.begin(), pos));
328

329
	SavePlaylistFile(contents, utf8path);
330
	idle_add(IDLE_STORED_PLAYLIST);
331 332
}

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

339
	FileOutputStream fos(path_fs, FileOutputStream::Mode::APPEND_OR_CREATE);
340

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

345
	BufferedOutputStream bos(fos);
346

347 348
	playlist_print_song(bos, song);

349
	bos.Flush();
350 351
	fos.Commit();

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

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

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

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

383
	idle_add(IDLE_STORED_PLAYLIST);
384
}
385

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

392 393
	const auto to_path_fs = spl_map_to_fs(utf8to);
	assert(!to_path_fs.IsNull());
394

395
	spl_rename_internal(from_path_fs, to_path_fs);
396
}