File: mpduser.cpp

package info (click to toggle)
cantata 3.3.1.ds1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 38,300 kB
  • sloc: cpp: 105,773; perl: 1,366; xml: 723; python: 139; lex: 110; sh: 105; yacc: 78; makefile: 8
file content (397 lines) | stat: -rw-r--r-- 10,268 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/*
 * Cantata
 *
 * Copyright (c) 2011-2022 Craig Drummond <craig.p.drummond@gmail.com>
 *
 * ----
 *
 * 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 det.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "mpduser.h"
#include "config.h"
#include "gui/settings.h"
#include "support/globalstatic.h"
#include "support/utils.h"
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QMutexLocker>
#include <QProcess>
#include <QSet>
#include <QTextStream>
#include <signal.h>

const QString MPDUser::constName = QLatin1String("-");

static const QString constDir = QLatin1String("mpd");
static const QString constConfigFile = QLatin1String("mpd.conf");
static const QString constMusicFolderKey = QLatin1String("music_directory");
static const QString constSocketKey = QLatin1String("bind_to_address");
static const QString constPlaylistsKey = QLatin1String("playlist_directory");
static const QString constPidKey = QLatin1String("pid_file");

QString MPDUser::translatedName()
{
	return QObject::tr("Personal");
}

GLOBAL_STATIC(MPDUser, instance)

#if !defined Q_OS_WIN && !defined Q_OS_MAC
static void moveConfig()
{
	QString oldName = QDir::homePath() + "/.config/cantata/" + constDir + "/" + constConfigFile;

	if (QFile::exists(oldName)) {
		QString newName = Utils::dataDir(constDir, true) + constConfigFile;
		if (QFile::exists(newName)) {
			QFile::remove(oldName);
		}
		else {
			QFile::rename(oldName, newName);
		}
	}
}
#endif

MPDUser::MPDUser()
{
#if !defined Q_OS_WIN && !defined Q_OS_MAC
	moveConfig();
#endif
// For now, per-user MPD support is disabled for windows builds
// - as I'm unsure how/if MPD works in windows!!!
// - If enable, also need to fix isRunning!!
#ifndef Q_OS_WIN
	mpdExe = Utils::findExe("mpd");
#endif
	det.name = constName;
	det.allowLocalStreaming = true;
}

bool MPDUser::isSupported()
{
	return !mpdExe.isEmpty();
}

bool MPDUser::isRunning()
{
#ifdef Q_OS_WIN
	return false;
#else
	int pid = getPid();
	return pid ? 0 == ::kill(pid, 0) : false;
#endif
}

static QString readValue(const QString& line)
{
	int start = line.indexOf("\"");
	int end = -1 == start ? -1 : line.indexOf("\"", start + 1);
	return -1 == end ? QString() : line.mid(start + 1, (end - start) - 1);
}

void MPDUser::start()
{
	if (isRunning() || mpdExe.isEmpty()) {
		return;
	}

	init(true);

	if (!det.dir.isEmpty() && !det.hostname.isEmpty()) {
		controlMpd(false);
	}
}

void MPDUser::stop()
{
	if (!isRunning() || mpdExe.isEmpty()) {
		return;
	}

	init(false);
	controlMpd(true);
}

void MPDUser::setMusicFolder(const QString& folder)
{
	if (folder == det.dir) {
		return;
	}
	init(true);

	bool mpdRunning = isRunning();
	if (mpdRunning) {
		controlMpd(true);
	}

	QFile cfgFile(Utils::dataDir(constDir, true) + constConfigFile);
	QStringList lines;
	if (cfgFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
		while (!cfgFile.atEnd()) {
			QString line = QString::fromUtf8(cfgFile.readLine());
			if (line.startsWith(constMusicFolderKey)) {
				lines.append(constMusicFolderKey + " \"" + folder + "\"\n");
			}
			else {
				lines.append(line);
			}
		}
		cfgFile.close();
	}

	if (!lines.isEmpty()) {
		if (cfgFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
			QTextStream out(&cfgFile);
			for (const QString& line : lines) {
				out << line;
			}
			cfgFile.close();
		}
	}
	det.dir = folder;
	det.setDirReadable();
	if (mpdRunning) {
		controlMpd(false);
	}
}

void MPDUser::setDetails(const MPDConnectionDetails& d)
{
	setMusicFolder(d.dir);
	bool dirReadable = det.dirReadable;
	det = d;
	det.dirReadable = dirReadable;
}

static void removeDir(const QString& d)
{
	if (d.isEmpty()) {
		return;
	}
	QDir dir(d);
	if (dir.exists()) {
		QString dirName = dir.dirName();
		if (!dirName.isEmpty()) {
			dir.cdUp();
			dir.rmdir(dirName);
		}
	}
}

void MPDUser::cleanup()
{
	QString cfgFileName(Utils::dataDir(constDir, false) + constConfigFile);
	QFile cfgFile(cfgFileName);
	QSet<QString> files;
	QSet<QString> dirs;
	QString playlistDir;

	if (cfgFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
		QStringList fileKeys = QStringList() << constPidKey << constSocketKey << QLatin1String("db_file")
											 << QLatin1String("state_file") << QLatin1String("sticker_file");
		QStringList dirKeys = QStringList() << constPlaylistsKey;
		while (!cfgFile.atEnd()) {
			QString line = QString::fromUtf8(cfgFile.readLine());
			for (const QString& key : fileKeys) {
				if (line.startsWith(key)) {
					QString file = readValue(line);
					if (!file.isEmpty()) {
						QString dir = Utils::getDir(file);
						if (!dir.isEmpty()) {
							dirs.insert(dir);
						}
						files.insert(file);
						fileKeys.removeAll(key);
					}
				}
			}
			if (playlistDir.isEmpty() && line.startsWith(constPlaylistsKey)) {
				playlistDir = readValue(line);
			}
		}
		files.insert(cfgFileName);
		dirs.insert(Utils::getDir(cfgFileName));
	}

	if (!dirs.isEmpty() && !files.isEmpty()) {
		for (const QString& f : files) {
			QFile::remove(f);
		}

		if (!playlistDir.isEmpty()) {
			QFileInfoList files = QDir(playlistDir).entryInfoList(QStringList() << "*.m3u", QDir::Files | QDir::NoDotAndDotDot);
			for (const QFileInfo& file : files) {
				QFile::remove(file.absoluteFilePath());
			}
			removeDir(playlistDir);
		}

		for (const QString& d : dirs) {
			removeDir(d);
		}
		removeDir(Utils::dataDir(constDir, false));
		removeDir(Utils::cacheDir(constDir, false));
	}
}

void MPDUser::init(bool create)
{
	if (create || det.dir.isEmpty() || det.hostname.isEmpty() || pidFileName.isEmpty()) {
		// Read coverFileName from Cantata settings...
		det.dirReadable = false;

		// Read music folder and socket from MPD conf file...
		QString cfgDir = Utils::dataDir(constDir, create);
		QString cfgName(cfgDir + constConfigFile);
		QString playlists;
		if (create && !QFile::exists(cfgName)) {
			// Conf file does not exist, so we need to create one...
			QFile cfgTemplate(":" + constConfigFile + ".template");

			if (cfgTemplate.open(QIODevice::ReadOnly | QIODevice::Text)) {
				QFile cfgFile(cfgName);
				if (cfgFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
					QString homeDir = QDir::homePath();
					QString cacheDir = Utils::cacheDir(constDir, create);
					QString dataDir = Utils::dataDir(constDir, create);
					QTextStream out(&cfgFile);
					while (!cfgTemplate.atEnd()) {
						QString line = cfgTemplate.readLine();
						line = line.replace(QLatin1String("${HOME}"), homeDir);
						line = line.replace(QLatin1String("${CONFIG_DIR}"), cfgDir);
						line = line.replace(QLatin1String("${DATA_DIR}"), dataDir);
						line = line.replace(QLatin1String("${CACHE_DIR}"), cacheDir);
						line = line.replace("//", "/");
						out << line;

						if (det.dir.isEmpty() && line.startsWith(constMusicFolderKey)) {
							det.dir = Utils::fixPath(readValue(line));
						}
						if (det.hostname.isEmpty() && line.startsWith(constSocketKey)) {
							det.hostname = readValue(line);
						}
						if (pidFileName.isEmpty() && line.startsWith(constPidKey)) {
							pidFileName = readValue(line);
						}
						// Create playlists dir...
						if (playlists.isEmpty() && line.startsWith(constPlaylistsKey)) {
							playlists = readValue(line);
							if (!playlists.isEmpty()) {
								Utils::createWorldReadableDir(playlists, QString());
							}
						}
					}
				}
			}
		}

		if (det.dir.isEmpty() || det.hostname.isEmpty() || pidFileName.isEmpty()) {
			QFile cfgFile(cfgName);
			if (cfgFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
				while (!cfgFile.atEnd() && (det.dir.isEmpty() || det.hostname.isEmpty() || pidFileName.isEmpty())) {
					QString line = QString::fromUtf8(cfgFile.readLine());
					if (det.dir.isEmpty() && line.startsWith(constMusicFolderKey)) {
						det.dir = Utils::fixPath(readValue(line));
					}
					if (det.hostname.isEmpty() && line.startsWith(constSocketKey)) {
						det.hostname = readValue(line);
					}
					if (pidFileName.isEmpty() && line.startsWith(constPidKey)) {
						pidFileName = readValue(line);
					}
				}
			}
			det.setDirReadable();
		}
		det.name = constName;
	}
}

int MPDUser::getPid()
{
	int pid = 0;

	init(false);
	if (!pidFileName.isEmpty()) {
		QFile pidFile(pidFileName);

		if (pidFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
			QTextStream str(&pidFile);
			str >> pid;
		}
	}
	return pid;
}

void MPDUser::killProcess()
{
	int pid = getPid();
	if (pid > 0) {
		::kill(pid, SIGKILL);
	}
}

bool MPDUser::controlMpd(bool stop)
{
	// Both the UI thread (from MainWindow) and MPD thread (from MPDConnection)
	// will stop MPDUser. Use a mutex to ensure thread safety...
	QMutexLocker locker(&mutex);
	QString confFile = Utils::dataDir(constDir, true) + constConfigFile;
	if (!QFile::exists(confFile) || (stop && (pidFileName.isEmpty() || !QFile::exists(pidFileName)))) {
		if (stop) {
			killProcess();
		}

		return false;
	}
	QStringList args = QStringList() << confFile;
	if (stop) {
		args += "--kill";
	}
	else {
		// Ensure cache dir exists before starting MPD
		Utils::cacheDir(constDir, true);
		if (!pidFileName.isEmpty() && QFile::exists(pidFileName)) {
			QFile::remove(pidFileName);
		}
	}
	bool started = QProcess::startDetached(mpdExe, args);
	if (stop) {
		// Wait (up to 2 seconds) for MPD to gracefully terminate
		for (int i = 0; i < 40; ++i) {
			Utils::msleep(50);
			if (!isRunning()) {
				return true;
			}
		}
		// MPD did not terminate, so kill process
		killProcess();
		return !isRunning();
	}
	else if (started) {
		for (int i = 0; i < 8; ++i) {
			Utils::msleep(250);
			if (0 != getPid()) {
				return true;
			}
		}
	}
	return started;
}