File: Query.cs

package info (click to toggle)
beagle 0.2.12-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 12,204 kB
  • ctags: 16,188
  • sloc: cs: 91,628; sh: 27,627; ansic: 10,646; makefile: 2,248; xml: 15
file content (401 lines) | stat: -rw-r--r-- 11,830 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
398
399
400
401
//
// Query.cs
//
// Copyright (C) 2004-2006 Novell, Inc.
//

//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

using System;
using System.IO;
using System.Collections;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;

using GLib;

using Beagle;
using Beagle.Util;
using Beagle.Daemon;

class QueryTool {

	private static int count = 0;
	private static Query query = null;
	private static DateTime queryStartTime;
	private static DateTime lastQueryTime = DateTime.Now;

	private static MainLoop main_loop = null;
	// CLI args
	private static bool keep_running = false;
	private static bool verbose = false;
	private static bool display_hits = true;
	private static bool flood = false;
	private static bool listener = false;
	private static DateTime start_date = DateTime.MinValue;
	private static DateTime end_date = DateTime.MinValue;

	private static void OnHitsAdded (HitsAddedResponse response)
	{
		lastQueryTime = DateTime.Now;

		if (count == 0 && verbose) {
			Console.WriteLine ("First hit returned in {0:0.000}s",
					   (lastQueryTime - queryStartTime).TotalSeconds);
		}

		if (! display_hits) {
			count += response.Hits.Count;
			return;
		}

		foreach (Hit hit in response.Hits) {
			if (verbose)
				Console.WriteLine ("  Uri: {0}", hit.Uri);
			else
				Console.WriteLine (hit.Uri);

			if (verbose) {
				SnippetRequest sreq = new SnippetRequest (query, hit);
				SnippetResponse sresp = (SnippetResponse) sreq.Send ();
				Console.WriteLine ("PaUri: {0}", hit.ParentUri != null ? hit.ParentUri.ToString () : "(null)");
				Console.WriteLine (" Snip: {0}", sresp.Snippet != null ? sresp.Snippet : "(null)");
				Console.WriteLine (" Type: {0}", hit.Type);
				Console.WriteLine ("MimeT: {0}", hit.MimeType == null ? "(null)" : hit.MimeType);
				Console.WriteLine ("  Src: {0}", hit.Source);
				Console.WriteLine ("Score: {0}", hit.Score);
				if (hit.ValidTimestamp)
					Console.WriteLine (" Time: {0}", hit.Timestamp.ToLocalTime ());
				
				foreach (Property prop in hit.Properties)
					Console.WriteLine ("    {0} = '{1}'", prop.Key, prop.Value);
				
				Console.WriteLine ();
			}

			++count;
		}
	}

	private static void OnHitsSubtracted (HitsSubtractedResponse response)
	{
		lastQueryTime = DateTime.Now;

		if (! display_hits)
			return;

		foreach (Uri uri in response.Uris) {
			Console.WriteLine ("Subtracted Uri '{0}'", uri);
			Console.WriteLine ();

			--count;
		}
	}

	private static void OnFinished (FinishedResponse response)
	{
		if (verbose) {
			Console.WriteLine ("Elapsed time: {0:0.000}s",
					   (DateTime.Now - queryStartTime).TotalSeconds);
			Console.WriteLine ("Total hits: {0}", count);
		}

		if (flood)
			SendQuery ();
		else
			main_loop.Quit ();
	}

	public static void PrintUsageAndExit () 
	{
		string usage =
			"beagle-query: Command-line interface to the Beagle search system.\n" +
			"Web page: http://www.gnome.org/projects/beagle\n" +
			"Copyright (C) 2004-2006 Novell, Inc.\n\n";
		usage +=
			"Usage: beagle-query [OPTIONS] <query string>\n\n" +
			"Options:\n" +
			"  --verbose\t\t\tPrint detailed information about each hit.\n" +
			"  --mime <mime type>\t\tConstrain search results to the specified mime\n" +
			"                    \t\ttype. Can be used multiply.\n" +
			"  --type <hit type>\t\tConstrain search results to the specified hit\n" +
			"                    \t\ttype. Can be used multiply.\n" +
			"  --source <source>\t\tConstrain query to the specified source.\n" +
			"                   \t\tSources list available from beagle-status.\n" +
			"  --start <date>\t\tConstrain query to items after specified date.\n" +
			"                \t\tDate must be in the form \"yyyyMMdd\" or \"yyyyMMddHHmmss\"\n" +
			"  --end <date>\t\t\tConstrain query to items before specified date.\n" +
			"              \t\t\tDate must be in the form \"yyyyMMdd\" or \"yyyyMMddHHmmss\"\n" +
			"  --keywords\t\t\tLists the keywords allowed in 'query string'.\n" +
			"            \t\t\tKeyword queries can be specified as keywordname:value e.g. ext:jpg\n" +
			"  --live-query\t\t\tRun continuously, printing notifications if a\n" +
			"              \t\t\tquery changes.\n" +
			"  --stats-only\t\t\tOnly display statistics about the query, not\n" +
			"              \t\t\tthe actual results.\n" +
			"  --max-hits\t\t\tLimit number of search results per backend\n" +
			"            \t\t\t(default = 100, max = 100)\n" +
			"  --flood\t\t\tExecute the query over and over again.  Don't do that.\n" +
			"  --listener\t\t\tExecute an index listener query.  Don't do that either.\n" +
			"  --help\t\t\tPrint this usage message.\n";

		Console.WriteLine (usage);

		System.Environment.Exit (0);
	}

	private static void ReadBackendMappings ()
	{
		ArrayList assemblies = ReflectionFu.ScanEnvironmentForAssemblies ("BEAGLE_BACKEND_PATH", PathFinder.BackendDir);

		// Add BeagleDaemonLib if it hasn't already been added.
		bool found_daemon_lib = false;
		foreach (Assembly assembly in assemblies) {
			if (assembly.GetName ().Name == "BeagleDaemonLib") {
				found_daemon_lib = true;
				break;
			}
		}

		if (!found_daemon_lib) {
			try {
				assemblies.Add (Assembly.LoadFrom (Path.Combine (PathFinder.PkgLibDir, "BeagleDaemonLib.dll")));
			} catch (FileNotFoundException) {
				Console.WriteLine ("WARNING: Could not find backend list.");
				Environment.Exit (1);
			}
		}

		foreach (Assembly assembly in assemblies) {
			foreach (Type type in ReflectionFu.GetTypesFromAssemblyAttribute (assembly, typeof (IQueryableTypesAttribute))) {
				object[] attributes = type.GetCustomAttributes (false);
				foreach (object attribute in attributes) {
					PropertyKeywordMapping mapping = attribute as PropertyKeywordMapping;
					if (mapping == null)
						continue;
					//Logger.Log.Debug (mapping.Keyword + " => " 
					//		+ mapping.PropertyName + 
					//		+ " is-keyword=" + mapping.IsKeyword + " (" 
					//		+ mapping.Description + ") "
					//		+ "(" + type.FullName + ")");
					PropertyKeywordFu.RegisterMapping (mapping);
				}
			}
		}
	}

	private static void OnClosed ()
	{
		if (flood)
			SendQuery ();
		else
			main_loop.Quit ();
	}

	private static int query_counter = 0;
	private static void SendQuery ()
	{
		++query_counter;
		if (flood) {
			if (query_counter > 1)
				Console.WriteLine ();
			Console.WriteLine ("Sending query #{0}", query_counter);
		}

		queryStartTime = DateTime.Now;
		try {
			query.SendAsync ();
		} catch (Exception ex) {
			Console.WriteLine ("Could not connect to the Beagle daemon.  The daemon probably isn't running.");
			Console.WriteLine (ex);
			System.Environment.Exit (-1);
		}
	}
	
	[DllImport("libgobject-2.0.so.0")]
	static extern void g_type_init ();

	public static void Main (string[] args) 
	{
		// Initialize GObject type system
		g_type_init ();

		main_loop = new MainLoop ();

		if (args.Length == 0 || Array.IndexOf (args, "--help") > -1 || Array.IndexOf (args, "--usage") > -1)
			PrintUsageAndExit ();

		StringBuilder query_str =  new StringBuilder ();

		string[] formats = {
			"yyyyMMdd",
			"yyyyMMddHHmmss"
		};

		query = new Query ();

		// Parse args
		int i = 0;
		while (i < args.Length) {
			switch (args [i]) {

			case "--mime":
			        if (++i >= args.Length) PrintUsageAndExit ();
				query.AddMimeType (args [i]);
				break;
			case "--type":
			        if (++i >= args.Length) PrintUsageAndExit ();
				query.AddHitType (args [i]);
				break;
			case "--source":
			        if (++i >= args.Length) PrintUsageAndExit ();
				query.AddSource (args [i]);
				break;
			case "--live-query":
				keep_running = true;
				break;
			case "--verbose":
				verbose = true;
				break;
			case "--stats-only":
				verbose = true;
				display_hits = false;
				break;
			case "--max-hits":
			    if (++i >= args.Length) PrintUsageAndExit ();
				query.MaxHits = Int32.Parse (args[i]);
				break;
			case "--flood":
				flood = true;
				break;
			case "--listener":
				listener = true;
				keep_running = true;
				break;
			case "--start":
				if (++i >= args.Length) PrintUsageAndExit ();
				try {
					start_date = DateTime.ParseExact (args[i], formats,
									  CultureInfo.InvariantCulture,
									  DateTimeStyles.None);
				} catch (FormatException) {
					Console.WriteLine ("Invalid start date");
					System.Environment.Exit (-1);
				}
				start_date = start_date.ToUniversalTime ();
				break;

			case "--end":
				if (++i >= args.Length) PrintUsageAndExit ();
				try {
					end_date = DateTime.ParseExact (args[i], formats,
									CultureInfo.InvariantCulture,
									DateTimeStyles.None);
				} catch (FormatException) {
					Console.WriteLine ("Invalid end date");
					System.Environment.Exit (-1);
				}
				end_date = end_date.ToUniversalTime ();
				break;

			case "--keywords":
				ReadBackendMappings ();
				QueryDriver.ReadKeywordMappings ();

				Console.WriteLine ("Supported query keywords are:");

				IDictionaryEnumerator property_keyword_enum = PropertyKeywordFu.MappingEnumerator;
				while (property_keyword_enum.MoveNext ()) {
					PropertyDetail prop = property_keyword_enum.Value as PropertyDetail;
					if (prop.Description != null)
						Console.WriteLine ("  {0,-20} for {1}", property_keyword_enum.Key, prop.Description);
					else
						Console.WriteLine ("  {0,-20}", property_keyword_enum.Key);
				}

				System.Environment.Exit (0);
				break;

			default:
				
				// We have to do some nastiness here to deal with shell quoting.
				// See beagled/QueryStringParser.cs for an idea of how this works.
				string Pattern = "(?<pm>[+-]?) (?<key>\\w+:)? (?<expr>.*)";
				Regex r = new Regex (Pattern, RegexOptions.IgnorePatternWhitespace);
				Match m = r.Match (args [i]);
				
				string quoted_query = m.Groups ["pm"].ToString () +
					m.Groups ["key"].ToString () +
					"\"" + m.Groups ["expr"].ToString () + "\"";
				
				if (query_str.Length > 0)
					query_str.Append (' ');
				query_str.Append (quoted_query);
				
				break;
				
			}

			++i;
		}

		if (listener) {

			query.IsIndexListener = true;

		} else {
		
			if (query_str.Length > 0)
				query.AddText (query_str.ToString ());

			if (start_date != DateTime.MinValue || end_date != DateTime.MinValue) {
				QueryPart_DateRange part = new QueryPart_DateRange ();
				
				if (start_date != DateTime.MinValue)
					part.StartDate = start_date;

				if (end_date != DateTime.MinValue)
					part.EndDate = end_date;
				
				query.AddPart (part);
			}
		}

		query.HitsAddedEvent += OnHitsAdded;
		query.HitsSubtractedEvent += OnHitsSubtracted;


		if (! keep_running)
			query.FinishedEvent += OnFinished;
		else
			query.ClosedEvent += OnClosed;

		SendQuery ();

		main_loop.Run ();
	}


}