1 /*
2  * Copyright 2003-2021 The Music Player Daemon Project
3  * http://www.musicpd.org
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 
20 #include "Configured.hxx"
21 #include "Registry.hxx"
22 #include "StorageInterface.hxx"
23 #include "plugins/LocalStorage.hxx"
24 #include "config/Data.hxx"
25 #include "fs/StandardDirectory.hxx"
26 #include "fs/CheckFile.hxx"
27 #include "util/RuntimeError.hxx"
28 #include "util/UriExtract.hxx"
29 
30 static std::unique_ptr<Storage>
CreateConfiguredStorageUri(EventLoop & event_loop,const char * uri)31 CreateConfiguredStorageUri(EventLoop &event_loop, const char *uri)
32 {
33 	auto storage = CreateStorageURI(event_loop, uri);
34 	if (storage == nullptr)
35 		throw FormatRuntimeError("Unrecognized storage URI: %s", uri);
36 
37 	return storage;
38 }
39 
40 static AllocatedPath
GetConfiguredMusicDirectory(const ConfigData & config)41 GetConfiguredMusicDirectory(const ConfigData &config)
42 {
43 	AllocatedPath path = config.GetPath(ConfigOption::MUSIC_DIR);
44 	if (path.IsNull())
45 		path = GetUserMusicDir();
46 
47 	return path;
48 }
49 
50 static std::unique_ptr<Storage>
CreateConfiguredStorageLocal(const ConfigData & config)51 CreateConfiguredStorageLocal(const ConfigData &config)
52 {
53 	AllocatedPath path = GetConfiguredMusicDirectory(config);
54 	if (path.IsNull())
55 		return nullptr;
56 
57 	path.ChopSeparators();
58 	CheckDirectoryReadable(path);
59 	return CreateLocalStorage(path);
60 }
61 
62 std::unique_ptr<Storage>
CreateConfiguredStorage(const ConfigData & config,EventLoop & event_loop)63 CreateConfiguredStorage(const ConfigData &config, EventLoop &event_loop)
64 {
65 	auto uri = config.GetString(ConfigOption::MUSIC_DIR);
66 	if (uri != nullptr && uri_has_scheme(uri))
67 		return CreateConfiguredStorageUri(event_loop, uri);
68 
69 	return CreateConfiguredStorageLocal(config);
70 }
71 
72 bool
IsStorageConfigured(const ConfigData & config)73 IsStorageConfigured(const ConfigData &config) noexcept
74 {
75 	return config.GetParam(ConfigOption::MUSIC_DIR) != nullptr;
76 }
77