~snaggen/rhythmbox/bpm

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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
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
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/*
 *  Copyright (C) 2006 Jonathan Matthew <jonathan@kaolin.hn.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 St, Fifth Floor, Boston, MA 02110-1301  USA.
 *
 */

/*
 * Client for out-of-process metadata reader communicating via D-BUS.
 *
 * How this works:
 * - spawn rb-metadata process, with pipes
 * - child process sets up its dbus server or whatever
 * - if successful, child writes dbus server address to stdout; otherwise, dies.
 * - parent opens dbus connection
 *
 * For each request, the parent checks if the dbus connection is still alive,
 * and pings the child to see if it's still responding.  If the child has
 * exited or is not responding, the parent starts a new metadata helper as
 * described above.
 *
 * The child process exits after a certain period of inactivity (30s
 * currently), so the ping message serves two purposes - it checks that the
 * child is still capable of handling messages, and it ensures the child
 * doesn't time out between when we check the child is still running and when
 * we actually send it the request.
 */

#include <config.h>

#include "rb-metadata.h"
#include "rb-metadata-dbus.h"
#include "rb-debug.h"
#include "rb-util.h"

#include <dbus/dbus.h>
#include <dbus/dbus-glib.h>
#include <dbus/dbus-glib-lowlevel.h>
#include <glib/gi18n.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/signal.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>

static void rb_metadata_class_init (RBMetaDataClass *klass);
static void rb_metadata_init (RBMetaData *md);
static void rb_metadata_finalize (GObject *object);

static gboolean tried_env_address = FALSE;
static DBusConnection *dbus_connection = NULL;
static GPid metadata_child = 0;
static GMainContext *main_context = NULL;
static GStaticMutex conn_mutex = G_STATIC_MUTEX_INIT;

struct RBMetaDataPrivate
{
	char       *uri;
	char       *mimetype;
	char      **missing_plugins;
	char      **plugin_descriptions;
	GHashTable *metadata;
};

G_DEFINE_TYPE (RBMetaData, rb_metadata, G_TYPE_OBJECT)

static void
rb_metadata_class_init (RBMetaDataClass *klass)
{
	GObjectClass *object_class = G_OBJECT_CLASS (klass);

	object_class->finalize = rb_metadata_finalize;

	g_type_class_add_private (object_class, sizeof (RBMetaDataPrivate));

	main_context = g_main_context_new ();	/* maybe not needed? */
}

static void
rb_metadata_init (RBMetaData *md)
{
	md->priv = G_TYPE_INSTANCE_GET_PRIVATE (md, RB_TYPE_METADATA, RBMetaDataPrivate);
}

static void
rb_metadata_finalize (GObject *object)
{
	RBMetaData *md;

	md = RB_METADATA (object);

	g_free (md->priv->uri);
	g_free (md->priv->mimetype);
	if (md->priv->metadata)
		g_hash_table_destroy (md->priv->metadata);

	G_OBJECT_CLASS (rb_metadata_parent_class)->finalize (object);
}

RBMetaData *
rb_metadata_new (void)
{
	return RB_METADATA (g_object_new (RB_TYPE_METADATA, NULL));
}

static void
kill_metadata_service (void)
{
	if (dbus_connection) {
		if (dbus_connection_get_is_connected (dbus_connection)) {
			rb_debug ("closing dbus connection");
			dbus_connection_close (dbus_connection);
		} else {
			rb_debug ("dbus connection already closed");
		}
		dbus_connection_unref (dbus_connection);
		dbus_connection = NULL;
	}

	if (metadata_child) {
		rb_debug ("killing child process");
		kill (metadata_child, SIGINT);
		g_spawn_close_pid (metadata_child);
		metadata_child = 0;
	}
}

static gboolean
ping_metadata_service (GError **error)
{
	DBusMessage *message, *response;
	DBusError dbus_error = {0,};

	if (!dbus_connection_get_is_connected (dbus_connection))
		return FALSE;

	message = dbus_message_new_method_call (RB_METADATA_DBUS_NAME,
						RB_METADATA_DBUS_OBJECT_PATH,
						RB_METADATA_DBUS_INTERFACE,
						"ping");
	if (!message) {
		return FALSE;
	}
	response = dbus_connection_send_with_reply_and_block (dbus_connection,
							      message,
							      RB_METADATA_DBUS_TIMEOUT,
							      &dbus_error);
	dbus_message_unref (message);
	if (dbus_error_is_set (&dbus_error)) {
		/* ignore 'no reply': just means the service is dead */
		if (strcmp (dbus_error.name, DBUS_ERROR_NO_REPLY)) {
			dbus_set_g_error (error, &dbus_error);
		}
		dbus_error_free (&dbus_error);
		return FALSE;
	}
	dbus_message_unref (response);
	return TRUE;
}

static gboolean
start_metadata_service (GError **error)
{
	DBusError dbus_error = {0,};
	GIOChannel *stdout_channel;
	GIOStatus status;
	gchar *dbus_address = NULL;

	if (dbus_connection) {
		if (ping_metadata_service (error))
			return TRUE;

		/* Metadata service is broken.  Kill it, and if we haven't run
		 * into any errors yet, we can try to restart it.
		 */
		kill_metadata_service ();

		if (*error)
			return FALSE;
	}

	if (!tried_env_address) {
		const char *addr = g_getenv ("RB_DBUS_METADATA_ADDRESS");
		tried_env_address = TRUE;
		if (addr) {
			rb_debug ("trying metadata service address %s (from environment)", addr);
			dbus_address = g_strdup (addr);
			metadata_child = 0;
		}
	}

	if (dbus_address == NULL) {
		gint metadata_stdout;
		GPtrArray *argv;
		gboolean res;
		char **debug_args;
		GError *local_error;
		int i;

		argv = g_ptr_array_new ();
		/*
		 * Normally, we find the metadata helper in the libexec dir,
		 * but when --enable-uninstalled-build is specified, we look
		 * in the directory it's built in.
		 */
#ifdef METADATA_UNINSTALLED_DIR
		g_ptr_array_add (argv, METADATA_UNINSTALLED_DIR "/rhythmbox-metadata");
#else
		g_ptr_array_add (argv, LIBEXEC_DIR G_DIR_SEPARATOR_S INSTALLED_METADATA_HELPER);
#endif
		debug_args = rb_debug_get_args ();
		i = 0;
		while (debug_args[i] != NULL) {
			g_ptr_array_add (argv, debug_args[i]);
			i++;
		}

		g_ptr_array_add (argv, "unix:tmpdir=/tmp");
		g_ptr_array_add (argv, NULL);

		local_error = NULL;
		res = g_spawn_async_with_pipes (NULL,
						(char **)argv->pdata,
						NULL,
						0,
						NULL, NULL,
						&metadata_child,
						NULL,
						&metadata_stdout,
						NULL,
						&local_error);
		g_ptr_array_free (argv, TRUE);
		g_strfreev (debug_args);

		if (res == FALSE) {
			g_propagate_error (error, local_error);
			return FALSE;
		}

		stdout_channel = g_io_channel_unix_new (metadata_stdout);
		status = g_io_channel_read_line (stdout_channel, &dbus_address, NULL, NULL, error);
		g_io_channel_unref (stdout_channel);
		if (status != G_IO_STATUS_NORMAL) {
			kill_metadata_service ();
			return FALSE;
		}

		g_strchomp (dbus_address);
		rb_debug ("Got metadata helper D-BUS address %s", dbus_address);
	}

	dbus_connection = dbus_connection_open_private (dbus_address, &dbus_error);
	g_free (dbus_address);
	if (!dbus_connection) {
		kill_metadata_service ();

		dbus_set_g_error (error, &dbus_error);
		dbus_error_free (&dbus_error);
		return FALSE;
	}
	dbus_connection_set_exit_on_disconnect (dbus_connection, FALSE);

	dbus_connection_setup_with_g_main (dbus_connection, main_context);

	rb_debug ("Metadata process %d started", metadata_child);
	return TRUE;
}

static void
handle_dbus_error (RBMetaData *md, DBusError *dbus_error, GError **error)
{
	/*
	 * If the error is 'no reply within the specified time',
	 * then we assume that either the metadata process died, or
	 * it's stuck in a loop and needs to be killed.
	 */
	if (strcmp (dbus_error->name, DBUS_ERROR_NO_REPLY) == 0) {
		kill_metadata_service ();

		g_set_error (error,
			     RB_METADATA_ERROR,
			     RB_METADATA_ERROR_INTERNAL,
			     _("Internal GStreamer problem; file a bug"));
	} else {
		dbus_set_g_error (error, dbus_error);
		dbus_error_free (dbus_error);
	}
}

static void
read_error_from_message (RBMetaData *md, DBusMessageIter *iter, GError **error)
{
	guint32 error_code;
	gchar *error_message;

	if (!rb_metadata_dbus_get_uint32 (iter, &error_code) ||
	    !rb_metadata_dbus_get_string (iter, &error_message)) {
		g_set_error (error,
			     RB_METADATA_ERROR,
			     RB_METADATA_ERROR_INTERNAL,
			     _("D-BUS communication error"));
		return;
	}

	g_set_error (error, RB_METADATA_ERROR,
		     error_code,
		     "%s", error_message);
	g_free (error_message);
}

void
rb_metadata_load (RBMetaData *md,
		  const char *uri,
		  GError **error)
{
	DBusMessage *message = NULL;
	DBusMessage *response = NULL;
	DBusMessageIter iter;
	DBusError dbus_error = {0,};
	gboolean ok;
	GError *fake_error = NULL;

	if (error == NULL)
		error = &fake_error;

	g_free (md->priv->mimetype);
	md->priv->mimetype = NULL;

	g_free (md->priv->uri);
	md->priv->uri = g_strdup (uri);
	if (uri == NULL)
		return;

	if (md->priv->metadata)
		g_hash_table_destroy (md->priv->metadata);
	md->priv->metadata = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, (GDestroyNotify)rb_value_free);

	g_static_mutex_lock (&conn_mutex);

	start_metadata_service (error);

	if (*error == NULL) {
		message = dbus_message_new_method_call (RB_METADATA_DBUS_NAME,
							RB_METADATA_DBUS_OBJECT_PATH,
							RB_METADATA_DBUS_INTERFACE,
							"load");
		if (!message) {
			g_set_error (error,
				     RB_METADATA_ERROR,
				     RB_METADATA_ERROR_INTERNAL,
				     _("D-BUS communication error"));
		} else if (!dbus_message_append_args (message, DBUS_TYPE_STRING, &uri, DBUS_TYPE_INVALID)) {
			g_set_error (error,
				     RB_METADATA_ERROR,
				     RB_METADATA_ERROR_INTERNAL,
				     _("D-BUS communication error"));
		}
	}

	if (*error == NULL) {
		rb_debug ("sending metadata load request");
		response = dbus_connection_send_with_reply_and_block (dbus_connection,
								      message,
								      RB_METADATA_DBUS_TIMEOUT,
								      &dbus_error);

		if (!response)
			handle_dbus_error (md, &dbus_error, error);
	}

	if (*error == NULL) {
		if (!dbus_message_iter_init (response, &iter)) {
			g_set_error (error,
				     RB_METADATA_ERROR,
				     RB_METADATA_ERROR_INTERNAL,
				     _("D-BUS communication error"));
			rb_debug ("couldn't read response message");
		}
	}
	
	if (*error == NULL) {
		if (!rb_metadata_dbus_get_strv (&iter, &md->priv->missing_plugins)) {
			g_set_error (error,
				     RB_METADATA_ERROR,
				     RB_METADATA_ERROR_INTERNAL,
				     _("D-BUS communication error"));
			rb_debug ("couldn't get missing plugin data from response message");
		}
	}

	if (*error == NULL) {
		if (!rb_metadata_dbus_get_strv (&iter, &md->priv->plugin_descriptions)) {
			g_set_error (error,
				     RB_METADATA_ERROR,
				     RB_METADATA_ERROR_INTERNAL,
				     _("D-BUS communication error"));
			rb_debug ("couldn't get missing plugin descriptions from response message");
		}
	}

	/* if we're missing some plugins, we'll need to make sure the
	 * metadata helper rereads the registry before the next load.
	 * the easiest way to do this is to kill it.
	 */
	if (*error == NULL && md->priv->missing_plugins != NULL) {
		rb_debug ("missing plugins; killing metadata service to force registry reload");
		kill_metadata_service ();
	}

	if (*error == NULL) {
		if (!rb_metadata_dbus_get_boolean (&iter, &ok)) {
			g_set_error (error,
				     RB_METADATA_ERROR,
				     RB_METADATA_ERROR_INTERNAL,
				     _("D-BUS communication error"));
			rb_debug ("couldn't get success flag from response message");
		} else if (ok == FALSE) {
			read_error_from_message (md, &iter, error);
		}
	}

	if (ok && *error == NULL) {
		if (!rb_metadata_dbus_get_string (&iter, &md->priv->mimetype)) {
			g_set_error (error,
				     RB_METADATA_ERROR,
				     RB_METADATA_ERROR_INTERNAL,
				     _("D-BUS communication error"));
		} else {
			rb_debug ("got mimetype: %s", md->priv->mimetype);
		}
	}

	if (ok && *error == NULL) {
		rb_metadata_dbus_read_from_message (md, md->priv->metadata, &iter);
	}

	if (message)
		dbus_message_unref (message);
	if (response)
		dbus_message_unref (response);
	if (fake_error)
		g_error_free (fake_error);

	g_static_mutex_unlock (&conn_mutex);
}

const char *
rb_metadata_get_mime (RBMetaData *md)
{
	return md->priv->mimetype;
}

gboolean
rb_metadata_has_missing_plugins (RBMetaData *md)
{
	return (md->priv->missing_plugins != NULL);
}

gboolean
rb_metadata_get_missing_plugins (RBMetaData *md,
				 char ***missing_plugins,
				 char ***plugin_descriptions)
{
	if (md->priv->missing_plugins == NULL) {
		return FALSE;
	}

	*missing_plugins = g_strdupv (md->priv->missing_plugins);
	*plugin_descriptions = g_strdupv (md->priv->plugin_descriptions);
	return TRUE;
}


gboolean
rb_metadata_get (RBMetaData *md, RBMetaDataField field,
		 GValue *ret)
{
	GValue *val;
	if (!md->priv->metadata)
		return FALSE;

	if ((val = g_hash_table_lookup (md->priv->metadata,
					GINT_TO_POINTER (field)))) {
		g_value_init (ret, G_VALUE_TYPE (val));
		g_value_copy (val, ret);
		return TRUE;
	}
	return FALSE;
}

gboolean
rb_metadata_set (RBMetaData *md, RBMetaDataField field,
		 const GValue *val)
{
	GValue *newval;
	GType type;

	type = rb_metadata_get_field_type (field);
	g_return_val_if_fail (type == G_VALUE_TYPE (val), FALSE);

	newval = g_slice_new0 (GValue);
	g_value_init (newval, type);
	g_value_copy (val, newval);

	g_hash_table_insert (md->priv->metadata, GINT_TO_POINTER (field),
			     newval);
	return TRUE;
}

gboolean
rb_metadata_can_save (RBMetaData *md, const char *mimetype)
{
	GError *error = NULL;
	DBusMessage *message = NULL;
	DBusMessage *response = NULL;
	gboolean can_save = FALSE;
	DBusError dbus_error = {0,};
	DBusMessageIter iter;
	gboolean ok = TRUE;

	g_static_mutex_lock (&conn_mutex);

	if (start_metadata_service (&error) == FALSE) {
		g_error_free (error);
		ok = FALSE;
	}

	if (ok) {
		message = dbus_message_new_method_call (RB_METADATA_DBUS_NAME,
							RB_METADATA_DBUS_OBJECT_PATH,
							RB_METADATA_DBUS_INTERFACE,
							"canSave");
		if (!message) {
			ok = FALSE;
		} else if (!dbus_message_append_args (message, DBUS_TYPE_STRING, &mimetype, DBUS_TYPE_INVALID)) {
			ok = FALSE;
		}
	}

	if (ok) {
		response = dbus_connection_send_with_reply_and_block (dbus_connection,
								      message,
								      RB_METADATA_DBUS_TIMEOUT,
								      &dbus_error);
		if (!response) {
			dbus_error_free (&dbus_error);
			ok = FALSE;
		} else if (dbus_message_iter_init (response, &iter)) {
			rb_metadata_dbus_get_boolean (&iter, &can_save);
		}
	}

	if (message)
		dbus_message_unref (message);
	if (response)
		dbus_message_unref (response);
	g_static_mutex_unlock (&conn_mutex);

	return can_save;
}

void
rb_metadata_save (RBMetaData *md, GError **error)
{
	GError *fake_error = NULL;
	DBusMessage *message = NULL;
	DBusMessage *response = NULL;
	DBusError dbus_error = {0,};
	DBusMessageIter iter;

	if (error == NULL)
		error = &fake_error;

	g_static_mutex_lock (&conn_mutex);

	start_metadata_service (error);

	if (*error == NULL) {
		message = dbus_message_new_method_call (RB_METADATA_DBUS_NAME,
							RB_METADATA_DBUS_OBJECT_PATH,
							RB_METADATA_DBUS_INTERFACE,
							"save");
		if (!message) {
			g_set_error (error,
				     RB_METADATA_ERROR,
				     RB_METADATA_ERROR_INTERNAL,
				     _("D-BUS communication error"));
		}
	}

	if (*error == NULL) {
		dbus_message_iter_init_append (message, &iter);
		if (!rb_metadata_dbus_add_to_message (md, &iter)) {
			g_set_error (error,
				     RB_METADATA_ERROR,
				     RB_METADATA_ERROR_INTERNAL,
				     _("D-BUS communication error"));
		}
	}

	if (*error == NULL) {
		response = dbus_connection_send_with_reply_and_block (dbus_connection,
								      message,
								      RB_METADATA_DBUS_TIMEOUT,
								      &dbus_error);
		if (!response) {
			handle_dbus_error (md, &dbus_error, error);
		} else if (dbus_message_iter_init (response, &iter)) {
			/* if there's any return data at all, it'll be an error */
			read_error_from_message (md, &iter, error);
		}
	}

	if (message)
		dbus_message_unref (message);
	if (response)
		dbus_message_unref (response);
	if (fake_error)
		g_error_free (fake_error);

	g_static_mutex_unlock (&conn_mutex);
}