PlaylistFile.cxx 9.01 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2020 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 46
#include <cassert>

Max Kellermann's avatar
Max Kellermann committed
47
#include <string.h>
48

49 50
static const char PLAYLIST_COMMENT = '#';

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

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

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

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

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

84 85 86
	return strchr(name_utf8, '/') == nullptr &&
		strchr(name_utf8, '\n') == nullptr &&
		strchr(name_utf8, '\r') == nullptr;
87 88
}

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

97
	return path_fs;
98 99
}

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

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

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

	return path_fs;
}

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

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

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

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

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

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

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

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

164
	DirectoryReader reader(parent_path_fs);
165

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

	return list;
}

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

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

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

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

190
	bos.Flush();
191 192

	fos.Commit();
193 194
}

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

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

203
	TextFile file(path_fs);
204

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

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

221 222
		std::string uri_utf8;

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

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

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

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

263
	auto contents = LoadPlaylistFile(utf8path);
264

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

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

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

275
	SavePlaylistFile(contents, utf8path);
276 277

	idle_add(IDLE_STORED_PLAYLIST);
278 279
}

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

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

	idle_add(IDLE_STORED_PLAYLIST);
297 298
}

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

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

315
	idle_add(IDLE_STORED_PLAYLIST);
316 317
}

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

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

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

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

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

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

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

344
	BufferedOutputStream bos(fos);
345

346 347
	playlist_print_song(bos, song);

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

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

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

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

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

382
	idle_add(IDLE_STORED_PLAYLIST);
383
}
384

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

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

394
	spl_rename_internal(from_path_fs, to_path_fs);
395
}