summaryrefslogtreecommitdiff
path: root/Zeitgeist/LogClient.cs
blob: a572f9352a827011d4ebc6a4724eabe5c5e9b6b5 (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
/******************************************************************************
 * The MIT/X11/Expat License
 * Copyright (c) 2010 Manish Sinha<mail@manishsinha.net>

 * 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.Collections.Generic;
using Zeitgeist.Datamodel;
using Zeitgeist.Client;
using DBus;
using System.Linq;
using org.freedesktop.DBus;

namespace Zeitgeist
{
	/// <summary>
	/// Primary interface to the Zeitgeist engine. 
	/// </summary>
	/// <remarks>
	/// Used to update and query the log. 
	/// It also provides means to listen for events matching certain criteria. 
	/// All querying is heavily based around an “event template”-concept.
	/// </remarks>
	public class LogClient
	{
		/// <summary>
		/// The constructor for LogClient
		/// </summary>
		/// <remarks>
		/// This constructor gets the DBus object for LogClient which the object's methods use
		/// </remarks>
		public LogClient()
		{
			this.setUpClient();
			
			listOfMonitors = new List<MonitorData>();
			
			// When bus name changes
			ZsUtils.SignalBus.NameOwnerChanged += NameOwnerChanged;
		}
		
		private void NameOwnerChanged(string name, string old_owner, string new_owner)
		{
			// If Engine is restarted, re-connect in case it does not get re-connected
			if(string.Equals(name, "org.gnome.zeitgeist.Engine", StringComparison.OrdinalIgnoreCase))
			   setUpClient();
			
			// Install the monitors which were lost after the Daemon was restarted
			foreach(MonitorData monData in listOfMonitors)
			{
				Console.Out.WriteLine("Restoring monitor for: "+ monData.Path.ToString());
				srcInterface.InstallMonitor(monData.Path, monData.Range, monData.Events.ToArray());
			}
		}
		
		private void setUpClient()
		{
			srcInterface = ZsUtils.GetDBusObject<ILog>(objectPath);
			dbusInterface = ZsUtils.GetDBusObject<IDBus>(objectPath);
		}
		
		#region Fetch, Insert and Delete Events
		
		/// <summary>
		/// Get full event data for a set of event IDs
		/// Each event which is not found in the event log is represented by the null in the resulting List.
		/// </summary>
		/// <param name="eventIds">
		/// An array of event IDs <see cref="T:System.Collection.Generic.List{System.UInt32}"/>
		/// </param>
		/// <returns>
		/// Full event data for all the requested IDs of type <see cref="T:System.Collection.Generic.List{Zeitgeist.Datamodel.Event}"/>
		/// </returns>
		public List<Event> GetEvents(List<uint> eventIds)
		{
			RawEvent[] rawEvents = srcInterface.GetEvents(eventIds.ToArray());
			
			return ZsUtils.FromRawEventList(rawEvents);
		}
		
		/// <summary>
		/// Inserts events into the log. Returns an array containing the IDs of the inserted events
		/// </summary>
		/// <remarks>
		/// Each event which failed to be inserted into the log (either by being blocked or because of an error) will be represented by 0 in the resulting array.
		/// One way events may end up being blocked is if they match any of the blacklist templates.
		/// Any monitors with matching templates will get notified about the insertion. 
		/// Note that the monitors are notified after the events have been inserted.
		/// </remarks>
		/// <param name="events">
		/// List of <see cref="T:System.Collection.Generic.List{Zeitgeist.Datamodel.Event}"/> events to be inserted in the log 
		/// </param>
		/// <returns>
		/// An array containing the event IDs (type <see cref="T:System.Collection.Generic.List{System.UInt32}"/> ) of the inserted events. 0 as ID means failed to insert 
		/// </returns>
		public List<uint> InsertEvents(List<Event> events)
		{
			List<RawEvent> rawEvents = ZsUtils.ToRawEventList(events);
			
			UInt32[] eventIds = srcInterface.InsertEvents(rawEvents.ToArray());
			
			return new List<uint>(eventIds);
		}
		
		/// <summary>
		/// Delete a set of events from the log given their IDs
		/// If all the Event ID provided does not exist, then null is returned
		/// </summary>
		/// <param name="eventIds">
		/// The eventId (of type <see cref="T:System.Collection.Generic.List{System.UInt32}"/> ) of the Events to be deleted 
		/// </param>
		/// <returns>
		/// The TimeRange <see cref="T:Zeitgeist.Datamodel.TimeRange"/>
		/// </returns>
		public TimeRange DeleteEvents(List<uint> eventIds)
		{
			RawTimeRange rawRange = srcInterface.DeleteEvents(eventIds.ToArray());
			
			if(rawRange.Begin < 0 &&  rawRange.End < 0)
				return null;
			else
				return new TimeRange(rawRange.Begin, rawRange.End);
		}
		
		#endregion
		
		#region Search
		
		/// <summary>
		/// Search for events matching a given set of templates and return the IDs of matching events.
		/// Use GetEvents() passing in the returned IDs to look up the full event data.
		/// The matching is done where unset fields in the templates are treated as wildcards. 
		/// If a template has more than one subject then events will match the template if any one of their subjects match any one of the subject templates.
		/// The fields uri, interpretation, manifestation, origin, and mimetype can be prepended with an exclamation mark ‘!’ in order to negate the matching.
		/// The fields uri, origin, and mimetype can be prepended with an asterisk ‘*’ in order to do truncated matching.
		/// </summary>
		/// <remarks>
		/// This method is intended for queries potentially returning a large result set. 
		/// It is especially useful in cases where only a portion of the results are to be displayed at the same time 
		/// (eg., by using paging or dynamic scrollbars), as by holding a list of IDs you keep a stable ordering 
		/// and you can ask for the details associated to them in batches, when you need them. 
		/// For queries yielding a small amount of results, or where you need the information about all results at once no matter how many of them there are, see FindEvents().
		/// </remarks>
		/// <param name="range">
		/// The TimeRange <see cref="T:Zeitgeist.Datamodel.TimeRange"/> for the query 
		/// </param>
		/// <param name="eventTemplates">
		/// An List of event templates <see cref="T:System.Collection.Generic.List{Zeitgeist.Datamodel.Event}"/> which the returned events should match at least one of. 
		/// </param>
		/// <param name="state">
		/// Value of type <see cref="T:Zeitgeist.Datamodel.StorageState"/> whether the item is currently known to be available 
		/// </param>
		/// <param name="maxEvents">
		/// Maximal amount of returned events <see cref="T:Zeitgeist.Datamodel.System.UInt32"/>
		/// </param>
		/// <param name="resType">
		/// The Order in which the result should be made available <see cref="T:Zeitgeist.Datamodel.ResultType"/>
		/// </param>
		/// <returns>
		/// An array of type <see cref="T:System.Collection.Generic.List{System.UInt32}"/> containing the IDs of all matching events, up to a maximum of num_events events. 
		/// Sorted and grouped as defined by the result_type parameter. 
		/// </returns>
		public List<uint> FindEventIds(TimeRange range, List<Event> eventTemplates, StorageState state, uint maxEvents, ResultType resType)
		{
			RawEvent[] rawEventTemplates = ZsUtils.ToRawEventList(eventTemplates).ToArray();
			
			RawTimeRange rawRange = new RawTimeRange();
			rawRange.Begin = (long)ZsUtils.ToTimestamp(range.Begin);
			rawRange.End = (long)ZsUtils.ToTimestamp(range.End);
			
			UInt32[] eventIds = srcInterface.FindEventIds(rawRange, rawEventTemplates, (uint)state, maxEvents, (uint) resType);
			
			return new List<uint>(eventIds);
		}
		
		/// <summary>
		/// Get events matching a given set of templates.
		/// The matching is done where unset fields in the templates are treated as wildcards. 
		/// If a template has more than one subject then events will match the template if any one of their subjects match any one of the subject templates.
		/// </summary>
		/// <remarks>
		/// The fields uri, interpretation, manifestation, origin, and mimetype can be prepended with an exclamation mark ‘!’ in order to negate the matching.
		/// The fields uri, origin, and mimetype can be prepended with an asterisk ‘*’ in order to do truncated matching.
		/// In case you need to do a query yielding a large (or unpredictable) result set and you only want to show some of the results at the same time (eg., by paging them), use FindEventIds().
		/// </remarks>
		/// <param name="range">
		/// The TimeRange <see cref="T:Zeitgeist.Datamodel.TimeRange"/> for the query 
		/// </param>
		/// <param name="eventTemplates">
		/// An array of event templates of type <see cref="T:System.Collection.Generic.List{Zeitgeist.Datamodel.Event}"/> which the returned events should match at least one of 
		/// </param>
		/// <param name="state">
		/// Value of type <see cref="T:Zeitgeist.Datamodel.StorageState"/> whether the item is currently known to be available 
		/// </param>
		/// <param name="maxEvents">
		/// Maximal amount of returned events <see cref="System.UInt32"/>
		/// </param>
		/// <param name="resType">
		/// The Order in which the result should be made available <see cref="T:Zeitgeist.Datamodel.ResultType"/>
		/// </param>
		/// <returns>
		/// Full event data of type <see cref="T:System.Collection.Generic.List{Zeitgeist.Datamodel.Event}"/> for all the requested IDs, up to a maximum of num_events events, sorted and grouped as defined by the result_type parameter. 
		/// </returns>
		public List<Event> FindEvents(TimeRange range, List<Event> eventTemplates, StorageState state, uint maxEvents, ResultType resType)
		{
			RawEvent[] rawEventTemplates = ZsUtils.ToRawEventList(eventTemplates).ToArray();
			
			RawTimeRange rawRange = new RawTimeRange();
			rawRange.Begin = (long)ZsUtils.ToTimestamp(range.Begin);
			rawRange.End = (long)ZsUtils.ToTimestamp(range.End);
			
			RawEvent[] events = srcInterface.FindEvents(rawRange, rawEventTemplates, (uint)state, maxEvents, (uint) resType);
			
			return ZsUtils.FromRawEventList(events);
		}
		
		/// <summary>
		/// Get a list of URIs of subjects which frequently occur together with events matching event_templates within time_range. 
		/// The resulting URIs must occur as subjects of events matching result_event_templates and have storage state storage_state.
		/// </summary>
		/// <remarks>
		/// Warning: This API is EXPERIMENTAL and is not fully supported yet.
		/// </remarks>
		/// <param name="range">
		/// The TimeRange <see cref="T:Zeitgeist.Datamodel.TimeRange"/> for the query  
		/// </param>
		/// <param name="eventTemplates">
		/// An List of event templates <see cref="T:System.Collection.Generic.List{Zeitgeist.Datamodel.Event}"/> which you want URIs that relate to. 
		/// </param>
		/// <param name="resultEventTemplates">
		/// An array of event templates <see cref="T:System.Collection.Generic.List{Zeitgeist.Datamodel.Event}"/> which the returned URIs must occur as subjects of. 
		/// </param>
		/// <param name="state">
		/// Value of type <see cref="T:Zeitgeist.Datamodel.StorageState"/> whether the item is currently known to be available 
		/// </param>
		/// <param name="maxEvents">
		/// Maximal amount of returned events <see cref="System.UInt32"/>
		/// </param>
		/// <param name="resType">
		/// The Order in which the result should be made available <see cref="T:Zeitgeist.Datamodel.ResultType"/>
		/// </param>
		/// <returns>
		/// A list of URIs <see cref="T:System.Collection.Generic.List{System.String}"/> matching the described criteria 
		/// </returns>
		public List<string> FindRelatedUris(TimeRange range, List<Event> eventTemplates, List<Event> resultEventTemplates, StorageState state, uint maxEvents, ResultType resType)
		{
			RawEvent[] rawEvents = ZsUtils.ToRawEventList(eventTemplates).ToArray();
			RawEvent[] rawEventTemplates = ZsUtils.ToRawEventList(resultEventTemplates).ToArray();
			
			RawTimeRange rawRange = new RawTimeRange();
			rawRange.Begin = (long)ZsUtils.ToTimestamp(range.Begin);
			rawRange.End = (long)ZsUtils.ToTimestamp(range.End);
			
			string[] uris = srcInterface.FindRelatedUris(rawRange, rawEvents, rawEventTemplates, (uint)state, maxEvents, (uint) resType);
			
			return new List<string>(uris);
		}
		
		#endregion
		
		#region Monitors
		
		/// <summary>
		/// Register a client side monitor object to receive callbacks when events matching time_range and event_templates are inserted or deleted.
		/// </summary>
		/// <param name="monitorPath">
		/// The path to be monitored <see cref="System.String"/>
		/// </param>
		/// <param name="range">
		/// The time range <see cref="T:Zeitgeist.Datamodel.TimeRange"/> under which Monitored events must fall within 
		/// </param>
		/// <param name="eventTemplates">
		/// Event templates <see cref="T:System.Collection.Generic.List{Zeitgeist.Datamodel.Event}"/> that events must match in order to trigger the monitor 
		/// </param>
		public void InstallMonitor(string monitorPath, TimeRange range, List<Event> eventTemplates)
		{
			RawTimeRange rawRange = new RawTimeRange();
			rawRange.Begin = (long)ZsUtils.ToTimestamp(range.Begin);
			rawRange.End = (long)ZsUtils.ToTimestamp(range.End);
			ObjectPath path = new ObjectPath(monitorPath);
			List<RawEvent> rawEvents = ZsUtils.ToRawEventList(eventTemplates);
			
			// Store all the monitors
			listOfMonitors.Add(new MonitorData(){Path=path, Range=rawRange, Events=rawEvents});
			
			srcInterface.InstallMonitor(path, rawRange, rawEvents.ToArray());
		}
		
		/// <summary>
		/// Remove a monitor installed with InstallMonitor()
		/// </summary>
		/// <param name="monitorPath">
		/// The path of the monitor to be removed <see cref="System.String"/>
		/// </param>
		public void RemoveMonitor(string monitorPath)
		{
			ObjectPath path = new ObjectPath(monitorPath);
			srcInterface.RemoveMonitor(path);
			
			// Find and remove the deleted Monitor
			MonitorData removedMonitor = listOfMonitors.Find(monitor => ObjectPath.Equals(monitor.Path,path));
			listOfMonitors.Remove(removedMonitor);
		}
		
		#endregion
		
		/// <summary>
		/// Delete the log file and all its content
		/// </summary>
		/// <remarks>
		/// This method is used to delete the entire log file and all its content in one go. 
		/// To delete specific subsets use FindEventIds() combined with DeleteEvents().
		/// </remarks>
		public void DeleteLog()
		{
			srcInterface.DeleteLog();
		}
		
		/// <summary>
		/// Terminate the running Zeitgeist engine process
		/// </summary>
		/// <remarks>
		/// Use with caution, this action must only be triggered with the user’s explicit consent, 
		/// as it will affect all applications using Zeitgeist
		/// </remarks>
		public void Quit()
		{
			srcInterface.Quit();
		}
		
		#region Properties
		
		/// <summary>
		/// The list of zeitgeist daemon extension loaded by the engine
		/// </summary>
		/// <remarks>
		/// Examples are Blacklist, DataSourceRegistry, Full-Text-Search, StorageMonitor etc
		/// </remarks>
		public List<string> Extensions
		{
			get
			{
				object exten = dbusInterface.Get("org.gnome.zeitgeist.Log", "extensions");
				if(exten != null && exten.GetType() == typeof(System.String[]))
				{
					return new List<string>((string[])exten);
				}
				else
					return new List<string>();
			}
		}
		
		#endregion
		
		private ILog srcInterface;
		
		private IDBus dbusInterface;
		
		private static string objectPath = "/org/gnome/zeitgeist/log/activity";
		
		private List<MonitorData> listOfMonitors;
	}
}