PlaylistFile.cxx 9.02 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 "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/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 176
static void
SavePlaylistFile(const PlaylistFileContents &contents, const char *utf8path)
177
{
178
	assert(utf8path != nullptr);
179

180 181
	const auto path_fs = spl_map_to_fs(utf8path);
	assert(!path_fs.IsNull());
182

183
	FileOutputStream fos(path_fs);
184 185
	BufferedOutputStream bos(fos);

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

189
	bos.Flush();
190 191

	fos.Commit();
192 193
}

194
PlaylistFileContents
195
LoadPlaylistFile(const char *utf8path)
196
try {
197 198
	PlaylistFileContents contents;

199 200
	const auto path_fs = spl_map_to_fs(utf8path);
	assert(!path_fs.IsNull());
201

202
	TextFile file(path_fs);
203

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

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

220 221
		std::string uri_utf8;

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

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

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

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

262
	auto contents = LoadPlaylistFile(utf8path);
263

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

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

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

274
	SavePlaylistFile(contents, utf8path);
275 276

	idle_add(IDLE_STORED_PLAYLIST);
277 278
}

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

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

	idle_add(IDLE_STORED_PLAYLIST);
296 297
}

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

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

314
	idle_add(IDLE_STORED_PLAYLIST);
315 316
}

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

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

325
	contents.erase(std::next(contents.begin(), pos));
326

327
	SavePlaylistFile(contents, utf8path);
328
	idle_add(IDLE_STORED_PLAYLIST);
329 330
}

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

337
	FileOutputStream fos(path_fs, FileOutputStream::Mode::APPEND_OR_CREATE);
338

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

343
	BufferedOutputStream bos(fos);
344

345 346
	playlist_print_song(bos, song);

347
	bos.Flush();
348 349
	fos.Commit();

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

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

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

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

381
	idle_add(IDLE_STORED_PLAYLIST);
382
}
383

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

390 391
	const auto to_path_fs = spl_map_to_fs(utf8to);
	assert(!to_path_fs.IsNull());
392

393
	spl_rename_internal(from_path_fs, to_path_fs);
394
}