UpnpDatabasePlugin.cxx 18 KB
Newer Older
1
/*
2
 * Copyright 2003-2016 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 * http://www.musicpd.org
 *
 * 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.
 *
 * 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.
 */

#include "config.h"
#include "UpnpDatabasePlugin.hxx"
22 23
#include "Directory.hxx"
#include "Tags.hxx"
24
#include "lib/upnp/ClientInit.hxx"
25 26 27
#include "lib/upnp/Discovery.hxx"
#include "lib/upnp/ContentDirectoryService.hxx"
#include "lib/upnp/Util.hxx"
28
#include "db/Interface.hxx"
Max Kellermann's avatar
Max Kellermann committed
29 30 31 32 33
#include "db/DatabasePlugin.hxx"
#include "db/Selection.hxx"
#include "db/DatabaseError.hxx"
#include "db/LightDirectory.hxx"
#include "db/LightSong.hxx"
34
#include "db/Stats.hxx"
35
#include "config/Block.hxx"
36 37 38 39
#include "tag/TagBuilder.hxx"
#include "tag/TagTable.hxx"
#include "util/Error.hxx"
#include "util/Domain.hxx"
40
#include "fs/Traits.hxx"
41 42 43 44 45 46 47 48 49 50 51 52
#include "Log.hxx"
#include "SongFilter.hxx"

#include <string>
#include <vector>
#include <set>

#include <assert.h>
#include <string.h>

static const char *const rootid = "0";

53
class UpnpSong : public LightSong {
54
	std::string uri2, real_uri2;
55 56 57 58

	Tag tag2;

public:
59 60 61
	UpnpSong(UPnPDirObject &&object, std::string &&_uri)
		:uri2(std::move(_uri)),
		 real_uri2(std::move(object.url)),
62
		 tag2(std::move(object.tag)) {
63 64
		directory = nullptr;
		uri = uri2.c_str();
65
		real_uri = real_uri2.c_str();
66 67
		tag = &tag2;
		mtime = 0;
68
		start_time = end_time = SongTime::zero();
69 70 71
	}
};

72
class UpnpDatabase : public Database {
73
	UpnpClient_Handle handle;
74
	UPnPDeviceDirectory *discovery;
75 76

public:
77 78
	UpnpDatabase():Database(upnp_db_plugin) {}

79
	static Database *Create(EventLoop &loop, DatabaseListener &listener,
80
				const ConfigBlock &block,
81 82 83 84
				Error &error);

	virtual bool Open(Error &error) override;
	virtual void Close() override;
85 86
	virtual const LightSong *GetSong(const char *uri_utf8,
					 Error &error) const override;
87
	void ReturnSong(const LightSong *song) const override;
88 89 90 91 92 93 94 95

	virtual bool Visit(const DatabaseSelection &selection,
			   VisitDirectory visit_directory,
			   VisitSong visit_song,
			   VisitPlaylist visit_playlist,
			   Error &error) const override;

	virtual bool VisitUniqueTags(const DatabaseSelection &selection,
96
				     TagType tag_type, tag_mask_t group_mask,
97
				     VisitTag visit_tag,
98 99 100 101 102
				     Error &error) const override;

	virtual bool GetStats(const DatabaseSelection &selection,
			      DatabaseStats &stats,
			      Error &error) const override;
103 104 105
	time_t GetUpdateStamp() const override {
		return 0;
	}
106 107

protected:
108
	bool Configure(const ConfigBlock &block, Error &error);
109 110

private:
111
	bool VisitServer(const ContentDirectoryService &server,
112
			 const std::list<std::string> &vpath,
113 114 115 116 117 118 119 120 121 122
			 const DatabaseSelection &selection,
			 VisitDirectory visit_directory,
			 VisitSong visit_song,
			 VisitPlaylist visit_playlist,
			 Error &error) const;

	/**
	 * Run an UPnP search according to MPD parameters, and
	 * visit_song the results.
	 */
123
	bool SearchSongs(const ContentDirectoryService &server,
124 125 126 127 128
			 const char *objid,
			 const DatabaseSelection &selection,
			 VisitSong visit_song,
			 Error &error) const;

129 130 131
	UPnPDirContent SearchSongs(const ContentDirectoryService &server,
				   const char *objid,
				   const DatabaseSelection &selection) const;
132

133 134
	UPnPDirObject Namei(const ContentDirectoryService &server,
			    const std::list<std::string> &vpath) const;
135 136 137 138

	/**
	 * Take server and objid, return metadata.
	 */
139 140
	UPnPDirObject ReadNode(const ContentDirectoryService &server,
			       const char *objid) const;
141 142 143 144 145 146

	/**
	 * Get the path for an object Id. This works much like pwd,
	 * except easier cause our inodes have a parent id. Not used
	 * any more actually (see comments in SearchSongs).
	 */
147 148
	std::string BuildPath(const ContentDirectoryService &server,
			      const UPnPDirObject& dirent) const;
149 150 151
};

Database *
152 153
UpnpDatabase::Create(gcc_unused EventLoop &loop,
		     gcc_unused DatabaseListener &listener,
154
		     const ConfigBlock &block, Error &error)
155 156
{
	UpnpDatabase *db = new UpnpDatabase();
157
	if (!db->Configure(block, error)) {
158
		delete db;
159
		return nullptr;
160
	}
161

162
	return db;
163 164
}

165
inline bool
166
UpnpDatabase::Configure(const ConfigBlock &, Error &)
167 168 169 170 171
{
	return true;
}

bool
172
UpnpDatabase::Open(gcc_unused Error &error)
173
{
174
	UpnpClientGlobalInit(handle);
175

176
	discovery = new UPnPDeviceDirectory(handle);
177 178 179
	try {
		discovery->Start();
	} catch (...) {
180
		delete discovery;
181
		UpnpClientGlobalFinish();
182
		throw;
183 184 185 186 187 188 189 190
	}

	return true;
}

void
UpnpDatabase::Close()
{
191
	delete discovery;
192
	UpnpClientGlobalFinish();
193 194 195
}

void
196
UpnpDatabase::ReturnSong(const LightSong *_song) const
197
{
198
	assert(_song != nullptr);
199

200 201
	UpnpSong *song = (UpnpSong *)const_cast<LightSong *>(_song);
	delete song;
202 203 204 205
}

// Get song info by path. We can receive either the id path, or the titles
// one
206
const LightSong *
207
UpnpDatabase::GetSong(const char *uri, gcc_unused Error &error) const
208 209
{
	auto vpath = stringToTokens(uri, "/", true);
210 211 212
	if (vpath.size() < 2)
		throw DatabaseError(DatabaseErrorCode::NOT_FOUND,
				    "No such song");
213

214
	auto server = discovery->GetServer(vpath.front().c_str());
215

216 217
	vpath.pop_front();

218
	UPnPDirObject dirent;
219
	if (vpath.front() != rootid) {
220
		dirent = Namei(server, vpath);
221
	} else {
222
		dirent = ReadNode(server, vpath.back().c_str());
223 224
	}

225
	return new UpnpSong(std::move(dirent), uri);
226 227 228 229 230 231 232 233
}

/**
 * Double-quote a string, adding internal backslash escaping.
 */
static void
dquote(std::string &out, const char *in)
{
234
	out.push_back('"');
235 236 237 238 239

	for (; *in != 0; ++in) {
		switch(*in) {
		case '\\':
		case '"':
240
			out.push_back('\\');
241 242
			break;
		}
243 244

		out.push_back(*in);
245 246
	}

247
	out.push_back('"');
248 249 250 251
}

// Run an UPnP search, according to MPD parameters. Return results as
// UPnP items
252
UPnPDirContent
253
UpnpDatabase::SearchSongs(const ContentDirectoryService &server,
254
			  const char *objid,
255
			  const DatabaseSelection &selection) const
256 257 258
{
	const SongFilter *filter = selection.filter;
	if (selection.filter == nullptr)
259
		return UPnPDirContent();
260

261
	const auto searchcaps = server.getSearchCapabilities(handle);
262
	if (searchcaps.empty())
263
		return UPnPDirContent();
264 265 266 267 268 269 270 271 272

	std::string cond;
	for (const auto &item : filter->GetItems()) {
		switch (auto tag = item.GetTag()) {
		case LOCATE_TAG_ANY_TYPE:
			{
				if (!cond.empty()) {
					cond += " and ";
				}
273
				cond += '(';
274 275 276 277 278 279 280 281 282 283 284 285
				bool first(true);
				for (const auto& cap : searchcaps) {
					if (first)
						first = false;
					else
						cond += " or ";
					cond += cap;
					if (item.GetFoldCase()) {
						cond += " contains ";
					} else {
						cond += " = ";
					}
286
					dquote(cond, item.GetValue());
287
				}
288
				cond += ')';
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
			}
			break;

		default:
			/* Unhandled conditions like
			   LOCATE_TAG_BASE_TYPE or
			   LOCATE_TAG_FILE_TYPE won't have a
			   corresponding upnp prop, so they will be
			   skipped */
			if (tag == TAG_ALBUM_ARTIST)
				tag = TAG_ARTIST;

			// TODO: support LOCATE_TAG_ANY_TYPE etc.
			const char *name = tag_table_lookup(upnp_tags,
							    TagType(tag));
			if (name == nullptr)
				continue;

			if (!cond.empty()) {
				cond += " and ";
			}
			cond += name;

			/* FoldCase doubles up as contains/equal
			   switch. UpNP search is supposed to be
			   case-insensitive, but at least some servers
			   have the same convention as mpd (e.g.:
			   minidlna) */
			if (item.GetFoldCase()) {
				cond += " contains ";
			} else {
				cond += " = ";
			}
322
			dquote(cond, item.GetValue());
323 324 325
		}
	}

326
	return server.search(handle, objid, cond.c_str());
327 328 329
}

static bool
330
visitSong(const UPnPDirObject &meta, const char *path,
331 332 333 334 335
	  const DatabaseSelection &selection,
	  VisitSong visit_song, Error& error)
{
	if (!visit_song)
		return true;
336

337 338
	LightSong song;
	song.directory = nullptr;
339
	song.uri = path;
340 341 342
	song.real_uri = meta.url.c_str();
	song.tag = &meta.tag;
	song.mtime = 0;
343
	song.start_time = song.end_time = SongTime::zero();
344

345
	return !selection.Match(song) || visit_song(song, error);
346 347 348 349 350 351 352
}

/**
 * Build synthetic path based on object id for search results. The use
 * of "rootid" is arbitrary, any name that is not likely to be a top
 * directory name would fit.
 */
353
static std::string
354 355 356 357 358 359 360
songPath(const std::string &servername,
	 const std::string &objid)
{
	return servername + "/" + rootid + "/" + objid;
}

bool
361
UpnpDatabase::SearchSongs(const ContentDirectoryService &server,
362 363 364 365 366 367 368 369
			  const char *objid,
			  const DatabaseSelection &selection,
			  VisitSong visit_song,
			  Error &error) const
{
	if (!visit_song)
		return true;

370
	for (auto &dirent : SearchSongs(server, objid, selection).objects) {
371 372 373 374
		if (dirent.type != UPnPDirObject::Type::ITEM ||
		    dirent.item_class != UPnPDirObject::ItemClass::MUSIC)
			continue;

375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
		// We get song ids as the result of the UPnP search. But our
		// client expects paths (e.g. we get 1$4$3788 from minidlna,
		// but we need to translate to /Music/All_Music/Satisfaction).
		// We can do this in two ways:
		//  - Rebuild a normal path using BuildPath() which is a kind of pwd
		//  - Build a bogus path based on the song id.
		// The first method is nice because the returned paths are pretty, but
		// it has two big problems:
		//  - The song paths are ambiguous: e.g. minidlna returns all search
		//    results as being from the "All Music" directory, which can
		//    contain several songs with the same title (but different objids)
		//  - The performance of BuildPath() is atrocious on very big
		//    directories, even causing timeouts in clients. And of
		//    course, 'All Music' is very big.
		// So we return synthetic and ugly paths based on the object id,
		// which we later have to detect.
391
		const std::string path = songPath(server.getFriendlyName(),
392
						  dirent.id);
393
		if (!visitSong(std::move(dirent), path.c_str(),
394
			       selection, visit_song,
395 396 397 398 399 400 401
			       error))
			return false;
	}

	return true;
}

402
UPnPDirObject
403
UpnpDatabase::ReadNode(const ContentDirectoryService &server,
404
		       const char *objid) const
405
{
406
	auto dirbuf = server.getMetadata(handle, objid);
407 408
	if (dirbuf.objects.size() != 1)
		throw std::runtime_error("Bad resource");
409

410
	return std::move(dirbuf.objects.front());
411 412
}

413
std::string
414
UpnpDatabase::BuildPath(const ContentDirectoryService &server,
415
			const UPnPDirObject& idirent) const
416
{
417
	const char *pid = idirent.id.c_str();
418
	std::string path;
419
	while (strcmp(pid, rootid) != 0) {
420
		auto dirent = ReadNode(server, pid);
421
		pid = dirent.parent_id.c_str();
422 423 424 425 426 427

		if (path.empty())
			path = dirent.name;
		else
			path = PathTraitsUTF8::Build(dirent.name.c_str(),
						     path.c_str());
428
	}
429

430
	return PathTraitsUTF8::Build(server.getFriendlyName(),
431
				     path.c_str());
432 433 434
}

// Take server and internal title pathname and return objid and metadata.
435
UPnPDirObject
436
UpnpDatabase::Namei(const ContentDirectoryService &server,
437
		    const std::list<std::string> &vpath) const
438
{
439
	if (vpath.empty())
440
		// looking for root info
441
		return ReadNode(server, rootid);
442

443 444
	std::string objid(rootid);

445
	// Walk the path elements, read each directory and try to find the next one
446
	for (auto i = vpath.begin(), last = std::prev(vpath.end());; ++i) {
447
		auto dirbuf = server.readDir(handle, objid.c_str());
448 449

		// Look for the name in the sub-container list
450
		UPnPDirObject *child = dirbuf.FindObject(i->c_str());
451 452 453
		if (child == nullptr)
			throw DatabaseError(DatabaseErrorCode::NOT_FOUND,
					    "No such object");
454

455 456
		if (i == last)
			return std::move(*child);
457

458 459 460
		if (child->type != UPnPDirObject::Type::CONTAINER)
			throw DatabaseError(DatabaseErrorCode::NOT_FOUND,
					    "Not a container");
461

462
		objid = std::move(child->id);
463 464 465
	}
}

466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
static bool
VisitItem(const UPnPDirObject &object, const char *uri,
	  const DatabaseSelection &selection,
	  VisitSong visit_song, VisitPlaylist visit_playlist,
	  Error &error)
{
	assert(object.type == UPnPDirObject::Type::ITEM);

	switch (object.item_class) {
	case UPnPDirObject::ItemClass::MUSIC:
		return !visit_song ||
			visitSong(object, uri,
				  selection, visit_song, error);

	case UPnPDirObject::ItemClass::PLAYLIST:
		if (visit_playlist) {
			/* Note: I've yet to see a
			   playlist item (playlists
			   seem to be usually handled
			   as containers, so I'll
			   decide what to do when I
			   see one... */
		}

		return true;

	case UPnPDirObject::ItemClass::UNKNOWN:
		return true;
	}

	assert(false);
	gcc_unreachable();
}

500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
static bool
VisitObject(const UPnPDirObject &object, const char *uri,
	    const DatabaseSelection &selection,
	    VisitDirectory visit_directory,
	    VisitSong visit_song,
	    VisitPlaylist visit_playlist,
	    Error &error)
{
	switch (object.type) {
	case UPnPDirObject::Type::UNKNOWN:
		assert(false);
		gcc_unreachable();

	case UPnPDirObject::Type::CONTAINER:
		return !visit_directory ||
			visit_directory(LightDirectory(uri, 0), error);

	case UPnPDirObject::Type::ITEM:
		return VisitItem(object, uri, selection,
				 visit_song, visit_playlist,
				 error);
	}

	assert(false);
	gcc_unreachable();
}

527 528 529
// vpath is a parsed and writeable version of selection.uri. There is
// really just one path parameter.
bool
530
UpnpDatabase::VisitServer(const ContentDirectoryService &server,
531
			  const std::list<std::string> &vpath,
532 533 534 535 536 537 538 539 540 541 542 543 544 545
			  const DatabaseSelection &selection,
			  VisitDirectory visit_directory,
			  VisitSong visit_song,
			  VisitPlaylist visit_playlist,
			  Error &error) const
{
	/* If the path begins with rootid, we know that this is a
	   song, not a directory (because that's how we set things
	   up). Just visit it. Note that the choice of rootid is
	   arbitrary, any value not likely to be the name of a top
	   directory would be ok. */
	/* !Note: this *can't* be handled by Namei further down,
	   because the path is not valid for traversal. Besides, it's
	   just faster to access the target node directly */
546
	if (!vpath.empty() && vpath.front() == rootid) {
547 548 549 550 551 552 553 554
		switch (vpath.size()) {
		case 1:
			return true;

		case 2:
			break;

		default:
555 556
			throw DatabaseError(DatabaseErrorCode::NOT_FOUND,
					    "Not found");
557 558
		}

559
		if (visit_song) {
560
			auto dirent = ReadNode(server, vpath.back().c_str());
561

562
			if (dirent.type != UPnPDirObject::Type::ITEM ||
563 564 565
			    dirent.item_class != UPnPDirObject::ItemClass::MUSIC)
				throw DatabaseError(DatabaseErrorCode::NOT_FOUND,
						    "Not found");
566

567
			std::string path = songPath(server.getFriendlyName(),
568
						    dirent.id);
569 570
			if (!visitSong(std::move(dirent), path.c_str(),
				       selection,
571 572 573 574 575 576 577
				       visit_song, error))
				return false;
		}
		return true;
	}

	// Translate the target path into an object id and the associated metadata.
578
	const auto tdirent = Namei(server, vpath);
579 580 581 582 583 584

	/* If recursive is set, this is a search... No use sending it
	   if the filter is empty. In this case, we implement limited
	   recursion (1-deep) here, which will handle the "add dir"
	   case. */
	if (selection.recursive && selection.filter)
585
		return SearchSongs(server, tdirent.id.c_str(), selection,
586 587
				   visit_song, error);

Max Kellermann's avatar
Max Kellermann committed
588 589 590 591
	const char *const base_uri = selection.uri.empty()
		? server.getFriendlyName()
		: selection.uri.c_str();

592
	if (tdirent.type == UPnPDirObject::Type::ITEM) {
593 594 595 596
		return VisitItem(tdirent, base_uri,
				 selection,
				 visit_song, visit_playlist,
				 error);
597 598 599 600 601
	}

	/* Target was a a container. Visit it. We could read slices
	   and loop here, but it's not useful as mpd will only return
	   data to the client when we're done anyway. */
602
	for (const auto &dirent : server.readDir(handle, tdirent.id.c_str()).objects) {
603 604
		const std::string uri = PathTraitsUTF8::Build(base_uri,
							      dirent.name.c_str());
605 606 607 608 609 610
		if (!VisitObject(dirent, uri.c_str(),
				 selection,
				 visit_directory,
				 visit_song, visit_playlist,
				 error))
			return false;
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
	}

	return true;
}

// Deal with the possibly multiple servers, call VisitServer if needed.
bool
UpnpDatabase::Visit(const DatabaseSelection &selection,
		    VisitDirectory visit_directory,
		    VisitSong visit_song,
		    VisitPlaylist visit_playlist,
		    Error &error) const
{
	auto vpath = stringToTokens(selection.uri, "/", true);
	if (vpath.empty()) {
626
		for (const auto &server : discovery->GetDirectories()) {
627
			if (visit_directory) {
628 629
				const LightDirectory d(server.getFriendlyName(), 0);
				if (!visit_directory(d, error))
630 631
					return false;
			}
632 633 634 635 636 637

			if (selection.recursive &&
			    !VisitServer(server, vpath, selection,
					 visit_directory, visit_song, visit_playlist,
					 error))
				return false;
638
		}
639

640 641 642 643
		return true;
	}

	// We do have a path: the first element selects the server
644
	std::string servername(std::move(vpath.front()));
645
	vpath.pop_front();
646

647
	auto server = discovery->GetServer(servername.c_str());
648
	return VisitServer(server, vpath, selection,
649 650 651 652 653
			   visit_directory, visit_song, visit_playlist, error);
}

bool
UpnpDatabase::VisitUniqueTags(const DatabaseSelection &selection,
654
			      TagType tag, gcc_unused tag_mask_t group_mask,
655
			      VisitTag visit_tag,
656 657
			      Error &error) const
{
658 659 660
	// TODO: use group_mask

	if (!visit_tag)
661 662 663
		return true;

	std::set<std::string> values;
664
	for (auto& server : discovery->GetDirectories()) {
665
		const auto dirbuf = SearchSongs(server, rootid, selection);
666

667 668 669 670 671
		for (const auto &dirent : dirbuf.objects) {
			if (dirent.type != UPnPDirObject::Type::ITEM ||
			    dirent.item_class != UPnPDirObject::ItemClass::MUSIC)
				continue;

672
			const char *value = dirent.tag.GetValue(tag);
673
			if (value != nullptr) {
674
#if CLANG_OR_GCC_VERSION(4,8)
675
				values.emplace(value);
676
#else
677
				values.insert(value);
678 679
#endif
			}
680 681 682
		}
	}

683 684 685 686
	for (const auto& value : values) {
		TagBuilder builder;
		builder.AddItem(tag, value.c_str());
		if (!visit_tag(builder.Commit(), error))
687
			return false;
688
	}
689 690 691 692 693 694 695 696 697 698

	return true;
}

bool
UpnpDatabase::GetStats(const DatabaseSelection &,
		       DatabaseStats &stats, Error &) const
{
	/* Note: this gets called before the daemonizing so we can't
	   reallyopen this would be a problem if we had real stats */
699
	stats.Clear();
700 701 702 703 704
	return true;
}

const DatabasePlugin upnp_db_plugin = {
	"upnp",
705
	0,
706 707
	UpnpDatabase::Create,
};