PlaylistFile.cxx 9.92 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 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 "protocol/RangeArg.hxx"
30
#include "fs/io/TextFile.hxx"
31 32
#include "fs/io/FileOutputStream.hxx"
#include "fs/io/BufferedOutputStream.hxx"
33
#include "config/Data.hxx"
34 35
#include "config/Option.hxx"
#include "config/Defaults.hxx"
Max Kellermann's avatar
Max Kellermann committed
36
#include "Idle.hxx"
37
#include "fs/Limits.hxx"
38
#include "fs/Traits.hxx"
39
#include "fs/FileSystem.hxx"
40
#include "fs/FileInfo.hxx"
41
#include "fs/DirectoryReader.hxx"
42
#include "util/StringCompare.hxx"
Max Kellermann's avatar
Max Kellermann committed
43
#include "util/UriExtract.hxx"
44

45
#include <cassert>
Rosen Penev's avatar
Rosen Penev committed
46
#include <cstring>
47

48 49
static const char PLAYLIST_COMMENT = '#';

50 51 52 53
static unsigned playlist_max_length;
bool playlist_saveAbsolutePaths = DEFAULT_PLAYLIST_SAVE_ABSOLUTE_PATHS;

void
54
spl_global_init(const ConfigData &config)
55
{
56
	playlist_max_length =
57 58
		config.GetPositive(ConfigOption::MAX_PLAYLIST_LENGTH,
				   DEFAULT_PLAYLIST_MAX_LENGTH);
59 60

	playlist_saveAbsolutePaths =
61 62
		config.GetBool(ConfigOption::SAVE_ABSOLUTE_PATHS,
			       DEFAULT_PLAYLIST_SAVE_ABSOLUTE_PATHS);
63 64
}

65 66 67
bool
spl_valid_name(const char *name_utf8)
{
68
	if (StringIsEmpty(name_utf8))
69 70 71
		/* empty name not allowed */
		return false;

72 73 74 75 76 77 78 79 80 81 82
	/*
	 * 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.
	 */

Rosen Penev's avatar
Rosen Penev committed
83 84 85
	return std::strchr(name_utf8, '/') == nullptr &&
		std::strchr(name_utf8, '\n') == nullptr &&
		std::strchr(name_utf8, '\r') == nullptr;
86 87
}

88
static const AllocatedPath &
89
spl_map()
90
{
91
	const AllocatedPath &path_fs = map_spl_path();
92
	if (path_fs.IsNull())
93 94 95
		throw PlaylistError(PlaylistResult::DISABLED,
				    "Stored playlists are disabled");

96
	return path_fs;
97 98
}

99 100
static void
spl_check_name(const char *name_utf8)
101
{
102 103
	if (!spl_valid_name(name_utf8))
		throw PlaylistError(PlaylistResult::BAD_NAME,
104 105 106
				    "Bad playlist name");
}

107
AllocatedPath
108
spl_map_to_fs(const char *name_utf8)
109
{
110 111
	spl_map();
	spl_check_name(name_utf8);
112

113
	auto path_fs = map_spl_utf8_to_fs(name_utf8);
114
	if (path_fs.IsNull())
115 116
		throw PlaylistError(PlaylistResult::BAD_NAME,
				    "Bad playlist name");
117 118 119 120

	return path_fs;
}

121
static bool
122
LoadPlaylistFileInfo(PlaylistInfo &info,
123 124
		     const Path parent_path_fs,
		     const Path name_fs)
125
{
126 127 128
	if (name_fs.HasNewline())
		return false;

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

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

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

	try {
		info.name = name.ToUTF8Throw();
	} catch (...) {
148
		return false;
149
	}
150

151
	info.mtime = fi.GetModificationTime();
152
	return true;
153 154
}

155
PlaylistVector
156
ListPlaylistFiles()
157
{
158
	PlaylistVector list;
159

160 161
	const auto &parent_path_fs = spl_map();
	assert(!parent_path_fs.IsNull());
162

163
	DirectoryReader reader(parent_path_fs);
164

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

	return list;
}

175
static void
176
SavePlaylistFile(Path path_fs, const PlaylistFileContents &contents)
177
{
178
	assert(!path_fs.IsNull());
179

180
	FileOutputStream fos(path_fs);
181 182
	BufferedOutputStream bos(fos);

183
	for (const auto &uri_utf8 : contents)
184
		playlist_print_uri(bos, uri_utf8.c_str());
185

186
	bos.Flush();
187 188

	fos.Commit();
189 190
}

191 192
static PlaylistFileContents
LoadPlaylistFile(Path path_fs)
193
try {
194 195
	PlaylistFileContents contents;

196
	assert(!path_fs.IsNull());
197

198
	TextFile file(path_fs);
199

200
	char *s;
201
	while ((s = file.ReadLine()) != nullptr) {
202
		if (*s == 0 || *s == PLAYLIST_COMMENT)
203
			continue;
204

205
#ifdef _UNICODE
206 207 208 209 210
		/* 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())
211 212
			continue;
#else
Max Kellermann's avatar
Max Kellermann committed
213
		const Path path = Path::FromFS(s);
214
#endif
Max Kellermann's avatar
Max Kellermann committed
215

216 217
		std::string uri_utf8;

218
		if (!uri_has_scheme(s)) {
219
#ifdef ENABLE_DATABASE
Max Kellermann's avatar
Max Kellermann committed
220
			uri_utf8 = map_fs_to_utf8(path);
221
			if (uri_utf8.empty()) {
Max Kellermann's avatar
Max Kellermann committed
222
				if (path.IsAbsolute()) {
223
					uri_utf8 = path.ToUTF8();
224 225 226 227 228
					if (uri_utf8.empty())
						continue;
				} else
					continue;
			}
229 230 231
#else
			continue;
#endif
232
		} else {
Max Kellermann's avatar
Max Kellermann committed
233
			uri_utf8 = path.ToUTF8();
234
			if (uri_utf8.empty())
235 236
				continue;
		}
237

238
		contents.emplace_back(std::move(uri_utf8));
239
		if (contents.size() >= playlist_max_length)
240
			break;
241 242
	}

243
	return contents;
244 245 246 247
} catch (const std::system_error &e) {
	if (IsFileNotFound(e))
		throw PlaylistError::NoSuchList();
	throw;
248 249
}

250 251 252 253 254
static PlaylistFileContents
MaybeLoadPlaylistFile(Path path_fs, PlaylistFileEditor::LoadMode load_mode)
try {
	if (load_mode == PlaylistFileEditor::LoadMode::NO)
		return {};
255

256 257 258 259 260
	return LoadPlaylistFile(path_fs);
} catch (const PlaylistError &error) {
	if (error.GetCode() == PlaylistResult::NO_SUCH_LIST &&
	    load_mode == PlaylistFileEditor::LoadMode::TRY)
		return {};
261

262 263 264 265 266 267 268 269 270 271
	throw;
 }

PlaylistFileEditor::PlaylistFileEditor(const char *name_utf8,
				       LoadMode load_mode)
	:path(spl_map_to_fs(name_utf8)),
	 contents(MaybeLoadPlaylistFile(path, load_mode))
{
}

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
void
PlaylistFileEditor::Insert(std::size_t i, const char *uri)
{
	if (i > size())
		throw PlaylistError(PlaylistResult::BAD_RANGE, "Bad position");

	if (size() >= playlist_max_length)
		throw PlaylistError(PlaylistResult::TOO_LARGE,
				    "Stored playlist is too large");

	contents.emplace(std::next(contents.begin(), i), uri);
}

void
PlaylistFileEditor::Insert(std::size_t i, const DetachedSong &song)
{
	const char *uri = playlist_saveAbsolutePaths
		? song.GetRealURI()
		: song.GetURI();

	Insert(i, uri);
}

295 296 297
void
PlaylistFileEditor::MoveIndex(unsigned src, unsigned dest)
{
298 299
	if (src >= contents.size() || dest >= contents.size())
		throw PlaylistError(PlaylistResult::BAD_RANGE, "Bad range");
300

301 302 303
	const auto src_i = std::next(contents.begin(), src);
	auto value = std::move(*src_i);
	contents.erase(src_i);
304

305 306
	const auto dest_i = std::next(contents.begin(), dest);
	contents.insert(dest_i, std::move(value));
307
}
308

309 310 311 312 313 314 315 316
void
PlaylistFileEditor::RemoveIndex(unsigned i)
{
	if (i >= contents.size())
		throw PlaylistError(PlaylistResult::BAD_RANGE, "Bad range");

	contents.erase(std::next(contents.begin(), i));
}
317

318 319 320 321 322 323 324 325 326 327
void
PlaylistFileEditor::RemoveRange(RangeArg range)
{
	if (!range.CheckClip(size()))
		throw PlaylistError::BadRange();

	contents.erase(std::next(contents.begin(), range.start),
		       std::next(contents.begin(), range.end));
}

328 329 330 331
void
PlaylistFileEditor::Save()
{
	SavePlaylistFile(path, contents);
332
	idle_add(IDLE_STORED_PLAYLIST);
333 334
}

335 336
void
spl_clear(const char *utf8path)
337
{
338 339
	const auto path_fs = spl_map_to_fs(utf8path);
	assert(!path_fs.IsNull());
340

341 342 343 344 345 346 347 348 349
	try {
		TruncateFile(path_fs);
	} catch (const std::system_error &e) {
		if (IsFileNotFound(e))
			throw PlaylistError(PlaylistResult::NO_SUCH_LIST,
					    "No such playlist");
		else
			throw;
	}
350 351

	idle_add(IDLE_STORED_PLAYLIST);
352 353
}

354 355
void
spl_delete(const char *name_utf8)
356
{
357 358
	const auto path_fs = spl_map_to_fs(name_utf8);
	assert(!path_fs.IsNull());
359

360 361 362 363 364 365 366 367 368
	try {
		RemoveFile(path_fs);
	} catch (const std::system_error &e) {
		if (IsFileNotFound(e))
			throw PlaylistError(PlaylistResult::NO_SUCH_LIST,
					    "No such playlist");
		else
			throw;
	}
369

370
	idle_add(IDLE_STORED_PLAYLIST);
371 372
}

373 374
void
spl_append_song(const char *utf8path, const DetachedSong &song)
375
try {
376 377
	const auto path_fs = spl_map_to_fs(utf8path);
	assert(!path_fs.IsNull());
378

379
	FileOutputStream fos(path_fs, FileOutputStream::Mode::APPEND_OR_CREATE);
380

381 382 383
	if (fos.Tell() / (MPD_PATH_MAX + 1) >= playlist_max_length)
		throw PlaylistError(PlaylistResult::TOO_LARGE,
				    "Stored playlist is too large");
384

385
	BufferedOutputStream bos(fos);
386

387 388
	playlist_print_song(bos, song);

389
	bos.Flush();
390 391
	fos.Commit();

392
	idle_add(IDLE_STORED_PLAYLIST);
393 394 395 396
} catch (const std::system_error &e) {
	if (IsFileNotFound(e))
		throw PlaylistError::NoSuchList();
	throw;
397 398
}

399
void
400
spl_append_uri(const char *utf8file,
401
	       const SongLoader &loader, const char *url)
402
{
403
	spl_append_song(utf8file, loader.LoadSong(url));
404 405
}

406 407
static void
spl_rename_internal(Path from_path_fs, Path to_path_fs)
408
{
409 410 411
	if (FileExists(to_path_fs))
		throw PlaylistError(PlaylistResult::LIST_EXISTS,
				    "Playlist exists already");
412

413 414 415
	try {
		RenameFile(from_path_fs, to_path_fs);
	} catch (const std::system_error &e) {
416
		if (IsFileNotFound(e))
417 418 419 420 421
			throw PlaylistError(PlaylistResult::NO_SUCH_LIST,
					    "No such playlist");
		else
			throw;
	}
422

423
	idle_add(IDLE_STORED_PLAYLIST);
424
}
425

426 427
void
spl_rename(const char *utf8from, const char *utf8to)
428
{
429 430
	const auto from_path_fs = spl_map_to_fs(utf8from);
	assert(!from_path_fs.IsNull());
431

432 433
	const auto to_path_fs = spl_map_to_fs(utf8to);
	assert(!to_path_fs.IsNull());
434

435
	spl_rename_internal(from_path_fs, to_path_fs);
436
}