summaryrefslogtreecommitdiff
path: root/src/tracker/tracker-info.c
blob: 261d0906132900392a15f96a8e3cd4a04c5433e7 (plain)
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
/*
 * Copyright (C) 2006, Jamie McCracken <jamiemcc@gnome.org>
 * Copyright (C) 2008-2010, Nokia <ivan.frade@nokia.com>
 * Copyright (C) 2014, SoftAtHome <contact@softathome.com>
 * Copyright (C) 2014, Lanedo <martyn@lanedo.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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 Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301, USA.
 */

#include "config.h"

#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <locale.h>

#include <glib.h>
#include <glib/gi18n.h>

#include <libtracker-sparql/tracker-sparql.h>

#include "tracker-info.h"
#include "tracker-sparql.h"

#define INFO_OPTIONS_ENABLED() \
	(filenames && g_strv_length (filenames) > 0);

static gchar **filenames;
static gboolean full_namespaces;
static gboolean plain_text_content;
static gboolean resource_is_iri;
static gboolean turtle;

static GOptionEntry entries[] = {
	{ "full-namespaces", 'f', 0, G_OPTION_ARG_NONE, &full_namespaces,
	  N_("Show full namespaces (i.e. don’t use nie:title, use full URLs)"),
	  NULL,
	},
	{ "plain-text-content", 'c', 0, G_OPTION_ARG_NONE, &plain_text_content,
	  N_("Show plain text content if available for resources"),
	  NULL,
	},
	{ "resource-is-iri", 'i', 0, G_OPTION_ARG_NONE, &resource_is_iri,
	  /* To translators:
	   * IRI (International Resource Identifier) is a generalization
	   * of the URI. While URI supports only ASCI encoding, IRI
	   * fully supports international characters. In practice, UTF-8
	   * is the most popular encoding used for IRI.
	   */
	  N_("Instead of looking up a file name, treat the FILE arguments as actual IRIs (e.g. <file:///path/to/some/file.txt>)"),
	  NULL,
	},
	{ "turtle", 't', 0, G_OPTION_ARG_NONE, &turtle,
	  N_("Output results as RDF in Turtle format"),
	  NULL,
	},
	{ G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &filenames,
	  N_("FILE"),
	  N_("FILE")},
	{ NULL }
};

static gboolean
has_valid_uri_scheme (const gchar *uri)
{
	const gchar *s;

	s = uri;

	if (!g_ascii_isalpha (*s)) {
		return FALSE;
	}

	do {
		s++;
	} while (g_ascii_isalnum (*s) || *s == '+' || *s == '.' || *s == '-');

	return (*s == ':');
}

static inline void
print_key_and_value (GHashTable  *prefixes,
                     const gchar *key,
                     const gchar *value)
{
	if (G_UNLIKELY (full_namespaces)) {
		g_print ("  '%s' = '%s'\n", key, value);
	} else {
		gchar *shorthand;

		shorthand = tracker_sparql_get_shorthand (prefixes, key);
		g_print ("  '%s' = '%s'\n", shorthand, value);
		g_free (shorthand);
	}
}

static void
print_plain (gchar               *urn_or_filename,
             gchar               *urn,
             TrackerSparqlCursor *cursor,
             GHashTable          *prefixes,
             gboolean             full_namespaces)
{
	gchar *fts_key = NULL;
	gchar *fts_value = NULL;

	while (tracker_sparql_cursor_next (cursor, NULL, NULL)) {
		const gchar *key = tracker_sparql_cursor_get_string (cursor, 0, NULL);
		const gchar *value = tracker_sparql_cursor_get_string (cursor, 1, NULL);

		if (!key || !value) {
			continue;
		}

		/* Don't display nie:plainTextContent */
		if (strcmp (key, "http://www.semanticdesktop.org/ontologies/2007/01/19/nie#plainTextContent") == 0) {
			if (plain_text_content) {
				fts_key = g_strdup (key);
				fts_value = g_strdup (value);
			}

			/* Always print FTS data at the end because of it's length */
			continue;
		}

		print_key_and_value (prefixes, key, value);
	}

	if (fts_key && fts_value) {
		print_key_and_value (prefixes, fts_key, fts_value);
	}

	g_free (fts_key);
	g_free (fts_value);
}

/* print a URI prefix in Turtle format */
static void
print_prefix (gpointer key,
              gpointer value,
              gpointer user_data)
{
	g_print ("@prefix %s: <%s#> .\n", (gchar *) value, (gchar *) key);
}

/* format a URI for Turtle; if it has a prefix, display uri
 * as prefix:rest_of_uri; if not, display as <uri>
 */
inline static gchar *
format_urn (GHashTable  *prefixes,
            const gchar *urn,
            gboolean     full_namespaces)
{
	gchar *urn_out;

	if (full_namespaces) {
		urn_out = g_strdup_printf ("<%s>", urn);
	} else {
		gchar *shorthand = tracker_sparql_get_shorthand (prefixes, urn);

		/* If the shorthand is the same as the urn passed, we
		 * assume it is a resource and pass it in as one,
		 *
		 *   e.g.: http://purl.org/dc/elements/1.1/date
		 *     to: http://purl.org/dc/elements/1.1/date
		 *
		 * Otherwise, we use the shorthand version instead.
		 *
		 *   e.g.: http://www.w3.org/1999/02/22-rdf-syntax-ns
		 *     to: rdf
		 */
		if (g_strcmp0 (shorthand, urn) == 0) {
			urn_out = g_strdup_printf ("<%s>", urn);
			g_free (shorthand);
		} else {
			urn_out = shorthand;
		}
	}

	return urn_out;
}

/* Print triples for a urn in Turtle format */
static void
print_turtle (gchar               *urn,
              TrackerSparqlCursor *cursor,
              GHashTable          *prefixes,
              gboolean             full_namespaces)
{
	gchar *subject;
	gchar *predicate;
	gchar *object;

	if (G_UNLIKELY (full_namespaces)) {
		subject = g_strdup (urn);
	} else {
		/* truncate subject */
		subject = tracker_sparql_get_shorthand (prefixes, urn);
	}

	while (tracker_sparql_cursor_next (cursor, NULL, NULL)) {
		const gchar *key = tracker_sparql_cursor_get_string (cursor, 0, NULL);
		const gchar *value = tracker_sparql_cursor_get_string (cursor, 1, NULL);
		const gchar *is_resource = tracker_sparql_cursor_get_string (cursor, 2, NULL);

		if (!key || !value || !is_resource) {
			continue;
		}

		/* Don't display nie:plainTextContent */
		if (!plain_text_content && strcmp (key, "http://www.semanticdesktop.org/ontologies/2007/01/19/nie#plainTextContent") == 0) {
			continue;
		}

		predicate = format_urn (prefixes, key, full_namespaces);

		if (g_ascii_strcasecmp (is_resource, "true") == 0) {
			object = g_strdup_printf ("<%s>", value);
		} else {
			gchar *escaped_value;

			/* Escape value and make sure it is encapsulated properly */
			escaped_value = tracker_sparql_escape_string (value);
			object = g_strdup_printf ("\"%s\"", escaped_value);
			g_free (escaped_value);
		}

		/* Print final statement */
		g_print ("<%s> %s %s .\n", subject, predicate, object);

		g_free (predicate);
		g_free (object);
	}

	g_free (subject);
}

static int
info_run (void)
{
	TrackerSparqlConnection *connection;
	GError *error = NULL;
	GHashTable *prefixes;
	gchar **p;

	connection = tracker_sparql_connection_get (NULL, &error);

	if (!connection) {
		g_printerr ("%s: %s\n",
		            _("Could not establish a connection to Tracker"),
		            error ? error->message : _("No error given"));
		g_clear_error (&error);
		return EXIT_FAILURE;
	}

	prefixes = tracker_sparql_get_prefixes ();

	/* print all prefixes if using turtle format and not showing full namespaces */
	if (turtle && !full_namespaces) {
		g_hash_table_foreach (prefixes, (GHFunc) print_prefix, NULL);
		g_print ("\n");
	}

	for (p = filenames; *p; p++) {
		TrackerSparqlCursor *cursor = NULL;
		GError *error = NULL;
		gchar *uri = NULL;
		gchar *query;
		gchar *urn = NULL;

		if (!turtle && !resource_is_iri) {
			g_print ("%s: '%s'\n", _("Querying information for entity"), *p);
		}

		/* support both, URIs and local file paths */
		if (has_valid_uri_scheme (*p)) {
			uri = g_strdup (*p);
		} else if (resource_is_iri) {
			uri = g_strdup (*p);
		} else {
			GFile *file;

			file = g_file_new_for_commandline_arg (*p);
			uri = g_file_get_uri (file);
			g_object_unref (file);
		}

		if (!resource_is_iri) {
			/* First check whether there's some entity with nie:url like this */
			query = g_strdup_printf ("SELECT ?urn WHERE { ?urn nie:url \"%s\" }", uri);
			cursor = tracker_sparql_connection_query (connection, query, NULL, &error);
			g_free (query);

			if (error) {
				g_printerr ("  %s, %s\n",
				            _("Unable to retrieve URN for URI"),
				            error->message);
				g_clear_error (&error);
				continue;
			}
		}

		if (!cursor || !tracker_sparql_cursor_next (cursor, NULL, &error)) {
			if (error) {
				g_printerr ("  %s, %s\n",
				            _("Unable to retrieve data for URI"),
				            error->message);
				g_object_unref (cursor);
				g_clear_error (&error);

				continue;
			}

			/* No URN matches, use uri as URN */
			urn = g_strdup (uri);
		} else {
			urn = g_strdup (tracker_sparql_cursor_get_string (cursor, 0, NULL));

			if (!turtle) {
				g_print ("  '%s'\n", urn);
			}

			g_object_unref (cursor);
		}

		query = g_strdup_printf ("SELECT ?predicate ?object"
		                         "  ( EXISTS { ?predicate rdfs:range [ rdfs:subClassOf rdfs:Resource ] } )"
		                         "WHERE {"
		                         "  <%s> ?predicate ?object "
		                         "}",
		                         urn);

		cursor = tracker_sparql_connection_query (connection, query, NULL, &error);

		g_free (uri);
		g_free (query);

		if (error) {
			g_printerr ("  %s, %s\n",
			            _("Unable to retrieve data for URI"),
			            error->message);

			g_clear_error (&error);
			continue;
		}

		if (!cursor) {
			g_print ("  %s\n",
			         _("No metadata available for that URI"));
		} else {
			if (turtle) {
				print_turtle (urn, cursor, prefixes, full_namespaces);
			} else {
				g_print ("%s:\n", _("Results"));

				print_plain (*p, urn, cursor, prefixes, full_namespaces);
			}

			g_print ("\n");

			g_object_unref (cursor);
		}

		g_print ("\n");

		g_free (urn);
	}

	g_hash_table_unref (prefixes);
	g_object_unref (connection);

	return EXIT_SUCCESS;
}

static int
info_run_default (void)
{
	GOptionContext *context;
	gchar *help;

	context = g_option_context_new (NULL);
	g_option_context_add_main_entries (context, entries, NULL);
	help = g_option_context_get_help (context, TRUE, NULL);
	g_option_context_free (context);
	g_printerr ("%s\n", help);
	g_free (help);

	return EXIT_FAILURE;
}

static gboolean
info_options_enabled (void)
{
	return INFO_OPTIONS_ENABLED ();
}

int
tracker_info (int argc, const char **argv)
{
	GOptionContext *context;
	GError *error = NULL;

	context = g_option_context_new (NULL);
	g_option_context_add_main_entries (context, entries, NULL);

	argv[0] = "tracker info";

	if (!g_option_context_parse (context, &argc, (char***) &argv, &error)) {
		g_printerr ("%s, %s\n", _("Unrecognized options"), error->message);
		g_error_free (error);
		g_option_context_free (context);
		return EXIT_FAILURE;
	}

	g_option_context_free (context);

	if (info_options_enabled ()) {
		return info_run ();
	}

	return info_run_default ();
}