def __init__(self): self[0] = all_events template2 = Event.new_for_values(interpretation = \ Interpretation.ACCESS_EVENT) self[1] = ["Access Events", \ "Fetch all the access events", \ template2, \ TimeRange.always(), \ ResultType.MostRecentEvents] template3 = Event.new_for_values(interpretation = \ Interpretation.LEAVE_EVENT) self[2] = ["Leave Events", \ "Fetch all the leave events", \ template3, \ TimeRange.always(), \ ResultType.MostRecentEvents] template4 = Event.new_for_values(interpretation = \ Interpretation.MODIFY_EVENT) self[3] = ["Modify Events", \ "Fetch all the modify events", \ template4, \ TimeRange.always(), \ ResultType.MostRecentEvents] template5 = Event.new_for_values(actor = "application://banshee.desktop") self[4] = ["Banshee events", \ "All the Banshee related events", \ template5, \ TimeRange.always(), \ ResultType.MostRecentEvents]
def testFindEventTwoInterpretations(self): import_events("test/data/twenty_events.js", self) result = self.findEventIdsAndWait([ Event.new_for_values(interpretation="stfu:OpenEvent"), Event.new_for_values(interpretation="stfu:EvilEvent")], timerange = (102, 117), num_events=0, result_type=0) self.assertEqual(15, len(result))
def testMoving(self): import_events("test/data/five_events.js", self) import_events("test/data/five_events_ext_move.js", self) template = Event.new_for_values(subject_current_uri='file:///*') ids = self.findEventIdsAndWait([template], num_events = 0, result_type = ResultType.MostRecentCurrentUri) self.assertEqual(2, len(ids)) ids = self.findEventIdsAndWait([template], num_events = 0, result_type = ResultType.MostRecentCurrentUri) self.assertEqual(2, len(ids)) ids = self.findEventIdsAndWait([template], num_events = 0, result_type = ResultType.MostRecentEvents) self.assertEqual(5, len(ids)) template = Event.new_for_values(subject_current_origin='file:///*') ids = self.findEventIdsAndWait([template], num_events = 0, result_type = ResultType.MostRecentEvents) self.assertEqual(4, len(ids))
def get_usage_counter(self, application, callback, timerange=None): """Request the usage count as integer for the given application. When the request is there, "callback" is called. A optional timerange like [time.time(), time.time() - 30*24*60*60] can also be specified """ # helper def _callback(event_ids): callback(len(event_ids)) # no client or empty query -> empty result if not self.zg_client or not application: callback(0) return # the app we are looking for application = "application://" + application.split("/")[-1] # the event_templates e1 = Event.new_for_values( actor=application, interpretation=Interpretation.MODIFY_EVENT.uri) e2 = Event.new_for_values( actor=application, interpretation=Interpretation.CREATE_EVENT.uri) # run it self.zg_client.find_event_ids_for_templates([e1, e2], _callback, timerange=timerange, num_events=0)
def __init__(self, date): next_date = date + datetime.timedelta(days=1) # time.mktime coverts from date to secs since epoch day_start = time.mktime(date.timetuple()) # day_end really is the start of the next day day_end = time.mktime(next_date.timetuple()) DayWidget.__init__(self, day_start, day_end) day_part_widgets = self.view.get_children() day_part = day_part_widgets[1] day_part.get_events() #self.vbox.remove(self.daylabel) self.event_timerange = [day_start * 1000, day_end * 1000] self.event_templates = ( Event.new_for_values( interpretation=Interpretation.VISIT_EVENT.uri), Event.new_for_values( interpretation=Interpretation.MODIFY_EVENT.uri), Event.new_for_values( interpretation=Interpretation.CREATE_EVENT.uri), Event.new_for_values(interpretation=Interpretation.OPEN_EVENT.uri), ) CLIENT.install_monitor(self.event_timerange, self.event_templates, self.notify_insert_handler, self.notify_delete_handler) self.get_events()
def request_last_n_days_events(self, n=90, func=None): """ Find the events for 'n' days and packs them into the store Optionally calls func upon completion """ subject = Subject() subject.uri = "!application://*" event_templates = ( Event.new_for_values( interpretation=Interpretation.ACCESS_EVENT.uri, subjects=[subject]), Event.new_for_values( interpretation=Interpretation.MODIFY_EVENT.uri, subjects=[subject]), Event.new_for_values( interpretation=Interpretation.CREATE_EVENT.uri, subjects=[subject]), Event.new_for_values( interpretation=Interpretation.RECEIVE_EVENT.uri, subjects=[subject]), Event.new_for_values( actor="!application://activity-log-manager.desktop")) def callback(events): def _thread_fn(events): event_chunks = [] chunk = [] for i, event in enumerate(events): chunk.append(event) if i % 20 == 0: event_chunks.append(chunk) chunk = [] map(self.add_events, event_chunks) if func: func() return False thread = threading.Thread(target=_thread_fn, args=(events, )) thread.start() end = time.time() - 3 * 86400 start = end - n * 86400 if n >= 60: inc = (end - start) / (n / 30) for i in range(n / 30): a = end - (inc * (i + 1)) + 1 b = end - (inc * (i)) CLIENT.find_events_for_templates( event_templates, callback, [a * 1000, b * 1000], num_events=50000, storage_state=StorageState.Available) else: CLIENT.find_events_for_templates( event_templates, callback, [start * 1000, end * 1000], num_events=50000, storage_state=StorageState.Available) return False
def testFindEventTwoInterpretations(self): import_events("test/data/twenty_events.js", self) result = self.findEventIdsAndWait([ Event.new_for_values(interpretation="stfu:OpenEvent"), Event.new_for_values(interpretation="stfu:EvilEvent")], timerange = (102, 117), num_events=0, result_type=0) self.assertEquals(15, len(result))
def __init__(self, date): next_date = date + datetime.timedelta(days=1) # time.mktime coverts from date to secs since epoch day_start = time.mktime(date.timetuple()) # day_end really is the start of the next day day_end = time.mktime(next_date.timetuple()) DayWidget.__init__(self, day_start, day_end) day_part_widgets = self.view.get_children() day_part = day_part_widgets[1] day_part.get_events() print day_part.events #self.vbox.remove(self.daylabel) self.event_timerange = [day_start * 1000, day_end * 1000] self.event_templates = ( Event.new_for_values(interpretation=Interpretation.VISIT_EVENT.uri), Event.new_for_values(interpretation=Interpretation.MODIFY_EVENT.uri), Event.new_for_values(interpretation=Interpretation.CREATE_EVENT.uri), Event.new_for_values(interpretation=Interpretation.OPEN_EVENT.uri), ) CLIENT.install_monitor(self.event_timerange, self.event_templates, self.notify_insert_handler, self.notify_delete_handler) self.get_events()
def testResultTypesOldestActorBug641968(self): events = [ new_event(timestamp=1, actor="boo", subject_uri="tmp/boo"), new_event(timestamp=2, actor="boo", subject_uri="home/boo"), new_event(timestamp=3, actor="bar", subject_uri="tmp/boo"), new_event(timestamp=4, actor="baz", subject_uri="tmp/boo"), ] self.insertEventsAndWait(events) # Get the least recent actors ids = self.findEventIdsAndWait([], num_events=0, result_type=ResultType.OldestActor) events = self.getEventsAndWait(ids) self.assertEqual(list(ids), [1, 3, 4]) # Get the least recent actors for "home/boo" template = Event.new_for_values(subject_uri="home/boo") ids = self.findEventIdsAndWait([template], num_events=0, result_type=ResultType.OldestActor) self.assertEqual(list(ids), [2]) # Let's also try the same with MostRecentActor... Although there # should be no problem here. template = Event.new_for_values(subject_uri="home/boo") ids = self.findEventIdsAndWait([template], num_events=0, result_type=ResultType.OldestActor) self.assertEqual(list(ids), [2])
def testMoving(self): import_events("test/data/five_events.js", self) import_events("test/data/five_events_ext_move.js", self) template = Event.new_for_values(subject_current_uri='file:///*') ids = self.findEventIdsAndWait([template], num_events = 0, result_type = ResultType.MostRecentCurrentUri) self.assertEquals(2, len(ids)) ids = self.findEventIdsAndWait([template], num_events = 0, result_type = ResultType.MostRecentCurrentUri) self.assertEquals(2, len(ids)) ids = self.findEventIdsAndWait([template], num_events = 0, result_type = ResultType.MostRecentEvents) self.assertEquals(5, len(ids)) template = Event.new_for_values(subject_current_origin='file:///*') ids = self.findEventIdsAndWait([template], num_events = 0, result_type = ResultType.MostRecentEvents) self.assertEquals(4, len(ids))
def testFindMultipleEvents(self): import_events("test/data/five_events.js", self) subj1 = Subject.new_for_values(uri="file:///home/foo.txt") event_template1 = Event.new_for_values(subjects=[subj1]) subj2 = Subject.new_for_values(uri="file:///tmp/foo.txt") event_template2 = Event.new_for_values(subjects=[subj2]) result = self.findEventIdsAndWait([event_template1, event_template2], num_events=0, result_type=4) self.assertEquals(2, len(result)) events = self.getEventsAndWait(result)
def testFindMultipleEvents(self): import_events("test/data/five_events.js", self) subj1 = Subject.new_for_values(uri="file:///home/foo.txt") event_template1 = Event.new_for_values(subjects=[subj1]) subj2 = Subject.new_for_values(uri="file:///tmp/foo.txt") event_template2 = Event.new_for_values(subjects=[subj2]) result = self.findEventIdsAndWait([event_template1, event_template2], num_events=0, result_type=4) self.assertEqual(2, len(result)) events = self.getEventsAndWait(result)
def testFindEventIdsForSubjectCurrentUri(self): # Retrieve events for a particular current URI template = Event.new_for_values(subject_current_uri='http://www.google.de') ids = self.findEventIdsAndWait([template]) self.assertEqual(ids, [1]) # Now let's try with wildcard and negation template = Event.new_for_values(subject_current_uri='!http:*') ids = self.findEventIdsAndWait([template]) self.assertEqual(list(map(int, ids)), [5, 4, 2, 3])
def testFindWithSubjectText(self): import_events("test/data/five_events.js", self) result = self.findEventIdsAndWait([Event.new_for_values(subject_text='this is not real')]) self.assertEqual(0, len(result)) result = self.findEventIdsAndWait([Event.new_for_values(subject_text='some text')]) self.assertEqual(1, len(result)) result = self.findEventIdsAndWait([Event.new_for_values(subject_text='this *')]) self.assertEqual(0, len(result)) # We don't support wildcards for text result = self.findEventIdsAndWait([Event.new_for_values(subject_text='this item *')]) self.assertEqual(1, len(result))
def testFindEventIdsForSubjectMimeType(self): # Retrieve events for a particular mime-type template = Event.new_for_values(subject_mimetype='text/plain') ids = self.findEventIdsAndWait([template]) self.assertEqual(ids, [4, 2, 3]) # Now let's try with wildcard and negation template = Event.new_for_values(subject_mimetype='!meat/*') ids = self.findEventIdsAndWait([template]) self.assertEqual(list(map(int, ids)), [5, 4, 2, 3])
def testFindEventIdsForSubjectOrigin(self): # Retrieve events for a particular origin template = Event.new_for_values(subject_origin='file:///tmp') ids = self.findEventIdsAndWait([template]) self.assertEqual(ids, [4, 2, 3]) # Now let's try with wildcard and negation template = Event.new_for_values(subject_origin='!file:*') ids = self.findEventIdsAndWait([template]) self.assertEqual(list(map(int, ids)), [5, 1])
def testFindEventIdsForEventOrigin(self): # Retrieve events for a particular actor template = Event.new_for_values(origin='big bang') ids = self.findEventIdsAndWait([template]) self.assertEqual(ids, [5, 3]) # Now let's try with wildcard and negation template = Event.new_for_values(origin='!big *') ids = self.findEventIdsAndWait([template]) self.assertEqual(list(map(int, ids)), [4, 2, 1])
def testFindWithSubjectText(self): import_events("test/data/five_events.js", self) result = self.findEventIdsAndWait([Event.new_for_values(subject_text='this is not real')]) self.assertEquals(0, len(result)) result = self.findEventIdsAndWait([Event.new_for_values(subject_text='some text')]) self.assertEquals(1, len(result)) result = self.findEventIdsAndWait([Event.new_for_values(subject_text='this *')]) self.assertEquals(0, len(result)) # We don't support wildcards for text result = self.findEventIdsAndWait([Event.new_for_values(subject_text='this item *')]) self.assertEquals(1, len(result))
def testFindEventIdsForInterpretation(self): # Retrieve events for a particular interpretation template = Event.new_for_values(interpretation='stfu:OpenEvent') ids = self.findEventIdsAndWait([template]) self.assertEqual(ids, [5, 1]) # Retrieve events excluding a particular interpretation template = Event.new_for_values(interpretation='!stfu:OpenEvent') ids = self.findEventIdsAndWait([template]) self.assertEqual(list(map(int, ids)), [4, 2, 3])
def testFindEventIdsForSubjectManifestation(self): # Retrieve events for a particular subject manifestation template = Event.new_for_values(subject_manifestation='stfu:File') ids = self.findEventIdsAndWait([template]) self.assertEqual(ids, [5, 4, 3, 1]) # Retrieve events excluding a particular subject interpretation template = Event.new_for_values(subject_manifestation='!stfu:File') ids = self.findEventIdsAndWait([template]) self.assertEqual(list(map(int, ids)), [2])
def testFindEventIdsForManifestation(self): # Retrieve events for a particular manifestation template = Event.new_for_values(manifestation='stfu:BooActivity') ids = self.findEventIdsAndWait([template]) self.assertEqual(ids, [2]) # Retrieve events excluding a particular manifestation template = Event.new_for_values(manifestation='!stfu:BooActivity') ids = self.findEventIdsAndWait([template]) self.assertEqual(list(map(int, ids)), [5, 4, 3, 1])
def testFindEventIdsForSubjectUri(self): # Retrieve events for a particular URI template = Event.new_for_values(subject_uri='file:///tmp/foo.txt') ids = self.findEventIdsAndWait([template]) self.assertEqual(ids, [2, 3]) # Now let's try with wildcard... template = Event.new_for_values(subject_uri='http://*') ids = self.findEventIdsAndWait([template]) self.assertEqual(list(map(int, ids)), [1]) # ... and negation template = Event.new_for_values(subject_uri='!file:///tmp/foo.txt') ids = self.findEventIdsAndWait([template]) self.assertEqual(list(map(int, ids)), [5, 4, 1])
def testFindEventIdsForActor(self): # Retrieve events for a particular actor template = Event.new_for_values(actor='gedit') ids = self.findEventIdsAndWait([template]) self.assertEqual(ids, [3]) # Retrieve events excluding a particular actor template = Event.new_for_values(actor='!gedit') ids = self.findEventIdsAndWait([template]) self.assertEqual(list(map(int, ids)), [5, 4, 2, 1]) # Retrieve events with actor matching a prefix template = Event.new_for_values(actor='g*') ids = self.findEventIdsAndWait([template]) self.assertEqual(list(map(int, ids)), [2, 3])
def post_commit(local, master, old_revno, old_revid, new_revno, new_revid): client = get_client() if client is None: return from zeitgeist.datamodel import Event, Interpretation, Manifestation revision = master.repository.get_revision(new_revid) if new_revno == 1: interpretation = Interpretation.CREATE_EVENT else: interpretation = Interpretation.MODIFY_EVENT _text = _("Revision: ") _text += str(new_revno) + "\n" _text += revision.message.rstrip() subjects = subjects_for_branch(master, new_revno, old_revno, None, revision.message.rstrip()) #subjects.set_text(_text) event = Event.new_for_values( timestamp=int(revision.timestamp*1000), interpretation=unicode(interpretation), manifestation=unicode(Manifestation.USER_ACTIVITY), actor=get_actor(), subjects=subjects, ) client.insert_event(event)
def buildQuery(chromosome): storage = StorageState.Any numResults = 10 if chromosome[0] == 0 or chromosome[1] == 0: timerange = TimeRange.always() else: timerange = (chromosome[0]*60*60*24, chromosome[1]*60*60*24) if timerange[0] > timerange[1]: timerange = (timerange[1], timerange[0]) searchType = chromosome[2]%30 eventTemplate = {} subjectTemplate = {} if chromosome[3]%2 == 0: subjectTemplate['interpretation'] = random.choice(list(Interpretation.EVENT_INTERPRETATION.get_children())) if chromosome[4]%2 == 0: subjectTemplate['manifestation'] = random.choice(list(Manifestation.EVENT_MANIFESTATION.get_children())) if chromosome[5]%2 == 0: eventTemplate['actor'] = "application://google-chrome.desktop" if chromosome[6]%2 == 0: subjectTemplate['origin'] = "http://google.com" if chromosome[7]%2 == 0: subjectTemplate['uri'] = "http://google.com" if chromosome[8]%2 == 0: subjectTemplate['mimetype'] = "text/html" if chromosome[9]%2 == 0: subjectTemplate['text'] = "fish" if chromosome[10]%2 == 0: eventTemplate['manifestation'] = random.choice(list(Manifestation.EVENT_MANIFESTATION.get_children())) if chromosome[11]%2 == 0: eventTemplate['interpretation'] = random.choice(list(Interpretation.EVENT_INTERPRETATION.get_children())) templates = [Event.new_for_values(subjects=[Subject.new_for_values(**subjectTemplate)], **eventTemplate)] return (timerange, templates, storage, numResults, searchType)
def testFindFilteredByEventButNotSubject(self): # revision [email protected] (1185) # Fix _build_templates so that it works when the Subject is empty. self.testSingleInsertGet() result = self.findEventIdsAndWait([Event.new_for_values( interpretation=Interpretation.LEAVE_EVENT)]) self.assertEquals(0, len(result))
def testFindFilteredByEventButNotSubject(self): # revision [email protected] (1185) # Fix _build_templates so that it works when the Subject is empty. self.testSingleInsertGet() result = self.findEventIdsAndWait([Event.new_for_values( interpretation=Interpretation.LEAVE_EVENT)]) self.assertEqual(0, len(result))
def create_and_send_event(self, page, event_type): if not self.zeitgeist_client: return if not hasattr(page, 'source') \ or not isinstance(page.source, File): return uri = page.source.uri origin = gio.File(uri).get_parent().get_uri() text = _('Wiki page: %s') % page.name # T: label for how zim pages show up in the recent files menu, %s is the page name subject = Subject.new_for_values(mimetype='text/x-zim-wiki', uri=uri, origin=origin, interpretation=Interpretation.TEXT_DOCUMENT, manifestation=Manifestation.FILE_DATA_OBJECT, text=text) event = Event.new_for_values(actor='application://zim.desktop', interpretation=event_type, manifestation=Manifestation.USER_ACTIVITY, subjects=[subject,]) self.zeitgeist_client.insert_event(event)
def log_folder_shared(self, share, share_id): """Log the 'directory shared' event.""" fullpath = share.path folder_name = basename(fullpath) folder = Subject.new_for_values( uri=URI_PROTOCOL_U1 + str(share.node_id), interpretation=Interpretation.FOLDER, manifestation=Manifestation.REMOTE_DATA_OBJECT, origin="file:///" + fullpath, text=folder_name, mimetype=DIRECTORY_MIMETYPE, storage=STORAGE_NETWORK) other_username = share.other_username other_user = Subject.new_for_values( uri="mailto:" + other_username, interpretation=INTERPRETATION_U1_CONTACT, text=other_username, manifestation=MANIFESTATION_U1_CONTACT_DATA_OBJECT) event = Event.new_for_values( interpretation=EVENT_INTERPRETATION_U1_FOLDER_SHARED, manifestation=Manifestation.USER_ACTIVITY, actor=ACTOR_UBUNTUONE, subjects=[folder, other_user]) self.zg.log(event)
def testMonitorInstallRemoval(self): result = [] mainloop = self.create_mainloop() tmpl = Event.new_for_values(interpretation="stfu:OpenEvent") @asyncTestMethod(mainloop) def notify_insert_handler(notification_type, events): pass @asyncTestMethod(mainloop) def notify_delete_handler(time_range, event_ids): mainloop.quit() self.fail("Unexpected delete notification") mon = self.client.install_monitor(TimeRange.always(), [tmpl], notify_insert_handler, notify_delete_handler) @asyncTestMethod(mainloop) def removed_handler(result_state): result.append(result_state) mainloop.quit() self.client.remove_monitor(mon, removed_handler) mainloop.run() self.assertEquals(1, len(result)) self.assertEquals(1, result.pop())
def handle_AQ_DOWNLOAD_FINISHED(self, share_id, node_id, server_hash): """A file finished downloading from the server.""" mdo = self.fsm.get_by_node_id(share_id, node_id) path = self.fsm.get_abspath(share_id, mdo.path) if (share_id, node_id) in self.newly_created_local_files: self.newly_created_local_files.remove((share_id, node_id)) event_interpretation = Interpretation.CREATE_EVENT else: event_interpretation = Interpretation.MODIFY_EVENT mime, interp = self.get_mime_and_interpretation_for_filepath(path) file_subject = Subject.new_for_values( uri="file:///" + path, interpretation=interp, manifestation=Manifestation.FILE_DATA_OBJECT, origin=URI_PROTOCOL_U1 + str(node_id), text=basename(path), mimetype=mime, storage=STORAGE_LOCAL) event = Event.new_for_values( interpretation=event_interpretation, manifestation=Manifestation.WORLD_ACTIVITY, actor=ACTOR_UBUNTUONE, subjects=[file_subject]) self.zg.log(event)
def file_info_complete(obj, res, user_data): try: fi = obj.query_info_finish(res) except: return uri_mimetype = fi.get_content_type() subject = Subject.new_for_values( uri=song["location"], interpretation=unicode(Interpretation.AUDIO), manifestation=unicode(Manifestation.FILE_DATA_OBJECT), origin=song["location"].rpartition("/")[0], mimetype=uri_mimetype, text=" - ".join([song["title"], song["artist"], song["album"]])) event = Event.new_for_values( timestamp=int(time.time() * 1000), interpretation=unicode(event_type), manifestation=unicode(manifest), actor="application://rhythmbox.desktop", subjects=[ subject, ]) IFACE.insert_event(event)
def insert_event_for_values(self, **values): """ Send an event to the Zeitgeist event log. The keyword arguments must match those as provided to Event.new_for_values(). The insertion will be done via an asynchronous DBus call and this method will return immediately. This means that the Zeitgeist engine will most likely not have inserted the event when this method returns. There will be a short delay. If the ids_reply_handler argument is set to a callable it will be invoked with a list containing the ids of the inserted events when they have been registered in Zeitgeist. In case of errors a message will be printed on stderr, and an empty result passed to ids_reply_handler (if set). To override this default set the error_handler named argument to a callable that takes a single exception as its sole argument. In order to use this method there needs to be a mainloop runnning. Both Qt and GLib mainloops are supported. """ ev = Event.new_for_values(**values) self.insert_events([ev], values.get("ids_reply_handler", None), values.get("error_handler", None))
def testSetDataSourceDisabled(self): # Insert a data-source -- it should be enabled by default self.client._registry.RegisterDataSource(*self._ds1) ds = list(self.client._registry.GetDataSources())[0] self.assertEquals(ds[DataSource.Enabled], True) # Now we can choose to disable it... self.client._registry.SetDataSourceEnabled(self._ds1[0], False) ds = list(self.client._registry.GetDataSources())[0] self.assertEquals(ds[DataSource.Enabled], False) event = Event.new_for_values( interpretation="interpretation", manifestation="manifestation", actor="actor", subject_uri="some uri", subject_manifestation="!stfu:File") # ... which will block its events from being inserted ids = self.insertEventsAndWait([event]) self.assertEquals(ids[0], 0) # And enable it again! self.client._registry.SetDataSourceEnabled(self._ds1[0], True) ds = list(self.client._registry.GetDataSources())[0] self.assertEquals(ds[DataSource.Enabled], True) ids = self.insertEventsAndWait([event]) self.assertEquals(ids[0], 1)
def testFindOneOfThreeEvents(self): events = parse_events("test/data/three_events.js") ids = self.insertEventsAndWait(events) self.assertEqual(3, len(ids)) events = self.getEventsAndWait(ids) self.assertEqual(3, len(events)) for event in events: self.assertTrue(isinstance(event, Event)) self.assertEqual(Manifestation.USER_ACTIVITY, event.manifestation) self.assertTrue(event.actor.startswith("Boogaloo")) # Search for everything ids = self.findEventIdsAndWait([], num_events=3) self.assertEqual(3, len(ids)) # Search for some specific templates subj_templ1 = Subject.new_for_values(interpretation="!"+Interpretation.AUDIO) subj_templ2 = Subject.new_for_values(interpretation="!"+Interpretation.IMAGE) event_template = Event.new_for_values( actor="Boogaloo*", interpretation=Interpretation.ACCESS_EVENT, subjects=[subj_templ1, subj_templ2]) ids = self.findEventIdsAndWait([event_template], num_events=10) self.assertEqual(1, len(ids)) events = self.getEventsAndWait(ids) event = events[0] self.assertEqual(event.subjects[0].interpretation, Interpretation.DOCUMENT)
def find_related_uris_for_uris(self, subject_uris, uris_reply_handler, time_range=None, result_event_templates=[], storage_state=StorageState.Any, num_events=10, result_type=0, error_handler=None): """ Warning: This API is EXPERIMENTAL and is not fully supported yet. Same as :meth:`find_related_uris_for_events`, but taking a list of subject URIs instead of event templates. """ event_template = Event.new_for_values( subjects=[Subject.new_for_values(uri=uri) for uri in subject_uris]) self.find_related_uris_for_events( [event_template], uris_reply_handler, time_range=time_range, result_event_templates=result_event_templates, storage_state=storage_state, num_events=num_events, result_type=result_type, error_handler=error_handler)
class OldBlacklistInterface: INCOGNITO = Event.new_for_values() def __init__(self): self._blacklist = CLIENT._iface.get_extension('Blacklist', 'blacklist') def _get_blacklist_templates(self): return map(Event.new_for_struct, self._blacklist.GetBlacklist()) def _add_blacklist_template(self, template): templates = self._get_blacklist_templates() templates.append(template) self._blacklist.SetBlacklist(templates) def _remove_blacklist_template(self, template): templates = self._get_blacklist_templates() updated_templates = list(templates) for template in templates: if self.INCOGNITO.matches_template(template): updated_templates.remove(template) self._blacklist.SetBlacklist(updated_templates) def get_incognito(self): templates = self._get_blacklist_templates() return any(imap(self.INCOGNITO.matches_template, templates)) def toggle_incognito(self): if not self.get_incognito(): self._add_blacklist_template(self.INCOGNITO) else: self._remove_blacklist_template(self.INCOGNITO)
def handle_VM_SHARE_CREATED(self, share_id): """Log the share accepted event.""" share = self.vm.shares[share_id] folder = Subject.new_for_values( uri=URI_PROTOCOL_U1 + str(share.node_id), interpretation=Interpretation.FOLDER, manifestation=Manifestation.REMOTE_DATA_OBJECT, origin="file:///" + share.path, text=basename(share.path), mimetype=DIRECTORY_MIMETYPE, storage=STORAGE_NETWORK) other_username = share.other_username other_user = Subject.new_for_values( uri="mailto:" + other_username, interpretation=INTERPRETATION_U1_CONTACT, text=other_username, manifestation=MANIFESTATION_U1_CONTACT_DATA_OBJECT) event = Event.new_for_values( interpretation=EVENT_INTERPRETATION_U1_SHARE_ACCEPTED, manifestation=Manifestation.USER_ACTIVITY, actor=ACTOR_UBUNTUONE, subjects=[folder, other_user]) self.zg.log(event)
def testUnicodeEventInsert(self): # Insert and get a unicode event ids = import_events("test/data/unicode_event.js", self) self.assertEquals(len(ids), 1) result = self.getEventsAndWait(ids) self.assertEquals(1, len(result)) event = result[0] self.assertEquals(1, len(event.subjects)) self.assertEquals(u"hällö, I'm gürmen - åge drikker øl - ☠", event.subjects[0].text) self.assertEquals(u"http://live.gnome.org/☠", event.subjects[0].uri) # Update the event we got from the DB's timestamp and insert # it again, we want to to test some ping-pong back and forth event[0][Event.Id] = "" event.timestamp = "243" ids = self.insertEventsAndWait([event]) result = self.getEventsAndWait(ids) self.assertEquals(1, len(result)) event = result[0] self.assertEquals(1, len(event.subjects)) self.assertEquals(u"hällö, I'm gürmen - åge drikker øl - ☠", event.subjects[0].text) self.assertEquals(u"http://live.gnome.org/☠", event.subjects[0].uri) # Try and find a unicode event subj = Subject.new_for_values(text="hällö, I'm gürmen - åge drikker øl - ☠", origin="file:///åges_øl í", uri=u"http://live.gnome.org/☠") event_template = Event.new_for_values(subjects=[subj,]) result = self.findEventIdsAndWait([event_template], timerange=(0,200), num_events=100, result_type=0) self.assertEquals(len(result), 1)
def handle_AQ_UNLINK_OK(self, share_id, parent_id, node_id, new_generation, was_dir, old_path): """A file or folder was deleted on the server by Syncdaemon,""" if was_dir: mime, interp = DIRECTORY_MIMETYPE, Interpretation.FOLDER else: mime, interp = self.get_mime_and_interpretation_for_filepath( old_path) file_subject = Subject.new_for_values( uri=URI_PROTOCOL_U1 + str(node_id), interpretation=interp, manifestation=Manifestation.DELETED_RESOURCE, origin="file:///" + old_path, text=basename(old_path), mimetype=mime, storage=STORAGE_DELETED) event = Event.new_for_values( interpretation=Interpretation.DELETE_EVENT, manifestation=Manifestation.SCHEDULED_ACTIVITY, actor=ACTOR_UBUNTUONE, subjects=[file_subject]) self.zg.log(event)
def testSetDataSourceDisabled(self): # Insert a data-source -- it should be enabled by default self.client._registry.RegisterDataSource(*self._ds1) ds = list(self.client._registry.GetDataSources())[0] self.assertEqual(ds[DataSource.Enabled], True) # Now we can choose to disable it... self.client._registry.SetDataSourceEnabled(self._ds1[0], False) ds = list(self.client._registry.GetDataSources())[0] self.assertEqual(ds[DataSource.Enabled], False) event = Event.new_for_values(interpretation="interpretation", manifestation="manifestation", actor="actor", subject_uri="some uri", subject_manifestation="!stfu:File") # ... which will block its events from being inserted ids = self.insertEventsAndWait([event]) self.assertEqual(ids[0], 0) # And enable it again! self.client._registry.SetDataSourceEnabled(self._ds1[0], True) ds = list(self.client._registry.GetDataSources())[0] self.assertEqual(ds[DataSource.Enabled], True) ids = self.insertEventsAndWait([event]) self.assertEqual(ids[0], 1)
def send_to_zeitgeist(self, db, entry, event_type): song = self.get_song_info(db, entry) if self.__manual_switch: manifest = Manifestation.USER_ACTIVITY else: manifest = Manifestation.SCHEDULED_ACTIVITY subject = Subject.new_for_values( uri=song["location"], interpretation=unicode(Interpretation.AUDIO), manifestation=unicode(Manifestation.FILE_DATA_OBJECT), #~ origin="", #TBD mimetype=song["mimetype"], text=" - ".join([song["title"], song["artist"], song["album"]]) ) event = Event.new_for_values( timestamp=int(time.time()*1000), interpretation=unicode(event_type), manifestation=unicode(manifest), actor="application://rhythmbox.desktop", subjects=[subject,] ) #print event IFACE.insert_event(event)
def testMonitorInstallRemoval(self): result = [] mainloop = self.create_mainloop() tmpl = Event.new_for_values(interpretation="stfu:OpenEvent") @asyncTestMethod(mainloop) def notify_insert_handler(notification_type, events): pass @asyncTestMethod(mainloop) def notify_delete_handler(time_range, event_ids): mainloop.quit() self.fail("Unexpected delete notification") mon = self.client.install_monitor(TimeRange.always(), [tmpl], notify_insert_handler, notify_delete_handler) @asyncTestMethod(mainloop) def removed_handler(result_state): result.append(result_state) mainloop.quit() self.client.remove_monitor(mon, removed_handler) mainloop.run() self.assertEqual(1, len(result)) self.assertEqual(1, result.pop())
def insert_event_for_values (self, **values): """ Send an event to the Zeitgeist event log. The keyword arguments must match those as provided to Event.new_for_values(). The insertion will be done via an asynchronous DBus call and this method will return immediately. This means that the Zeitgeist engine will most likely not have inserted the event when this method returns. There will be a short delay. If the ids_reply_handler argument is set to a callable it will be invoked with a list containing the ids of the inserted events when they have been registered in Zeitgeist. In case of errors a message will be printed on stderr, and an empty result passed to ids_reply_handler (if set). To override this default set the error_handler named argument to a callable that takes a single exception as its sole argument. In order to use this method there needs to be a mainloop runnning. Both Qt and GLib mainloops are supported. """ ev = Event.new_for_values(**values) self.insert_events([ev], values.get("ids_reply_handler", None), values.get("error_handler", None))
def testUnicodeEventInsert(self): # Insert and get a unicode event ids = import_events("test/data/unicode_event.js", self) self.assertEqual(len(ids), 1) result = self.getEventsAndWait(ids) self.assertEqual(1, len(result)) event = result[0] self.assertEqual(1, len(event.subjects)) self.assertEqual("hällö, I'm gürmen - åge drikker øl - ☠", event.subjects[0].text) self.assertEqual("http://live.gnome.org/☠", event.subjects[0].uri) # Update the event we got from the DB's timestamp and insert # it again, we want to to test some ping-pong back and forth event[0][Event.Id] = "" event.timestamp = "243" ids = self.insertEventsAndWait([event]) result = self.getEventsAndWait(ids) self.assertEqual(1, len(result)) event = result[0] self.assertEqual(1, len(event.subjects)) self.assertEqual("hällö, I'm gürmen - åge drikker øl - ☠", event.subjects[0].text) self.assertEqual("http://live.gnome.org/☠", event.subjects[0].uri) # Try and find a unicode event subj = Subject.new_for_values(text="hällö, I'm gürmen - åge drikker øl - ☠", origin="file:///åges_øl í", uri="http://live.gnome.org/☠") event_template = Event.new_for_values(subjects=[subj,]) result = self.findEventIdsAndWait([event_template], timerange=(0,200), num_events=100, result_type=0) self.assertEqual(len(result), 1)
def main(argv): interpretation = Interpretation.MODIFY_EVENT.uri # FIXME: I'd be great if zeitgeist would allow for more detail: # * branch # * log summary (git log -1 --format=%s HEAD) curdir = os.path.abspath(os.curdir).decode(sys.getfilesystemencoding()) uri = u"file://%s" % curdir repo, origin = get_repo() if not repo: repo = unicode(curdir.rsplit('/', 1)[1]) origin = uri subject = Subject.new_for_values( uri=uri, interpretation=Interpretation.DOCUMENT.TEXT_DOCUMENT.PLAIN_TEXT_DOCUMENT.SOURCE_CODE.uri, manifestation=Manifestation.FILE_DATA_OBJECT.uri, text=repo, origin=origin) event = Event.new_for_values( timestamp=int(time.time() * 1000), interpretation=interpretation, manifestation=Manifestation.USER_ACTIVITY.uri, actor="application://gitg.desktop", subjects=[subject]) CLIENT.insert_event(event)
def create_and_send_event(self, page, event_type): if not self.zeitgeist_client: return if not hasattr(page, 'source') \ or not isinstance(page.source, File): return uri = page.source.uri origin = gio.File(uri).get_parent().get_uri() text = _('Wiki page: %s') % page.name # T: label for how zim pages show up in the recent files menu, %s is the page name subject = Subject.new_for_values( mimetype='text/x-zim-wiki', uri=uri, origin=origin, interpretation=Interpretation.TEXT_DOCUMENT, manifestation=Manifestation.FILE_DATA_OBJECT, text=text) event = Event.new_for_values(actor='application://zim.desktop', interpretation=event_type, manifestation=Manifestation.USER_ACTIVITY, subjects=[ subject, ]) self.zeitgeist_client.insert_event(event)
def onNewTrack(self, track): """ Send track information to Zeitgeist """ import mimetypes, os.path from zeitgeist.datamodel import Event, Subject, Interpretation, Manifestation mime, encoding = mimetypes.guess_type(track.getFilePath(), strict=False) subject = Subject.new_for_values( uri = os.path.dirname(track.getURI()), text = track.getTitle() + ' - ' + track.getArtist() + ' - ' + track.getExtendedAlbum(), mimetype = mime, manifestation = unicode(Manifestation.FILE), interpretation = unicode(Interpretation.AUDIO), ) if hasattr(Interpretation, 'ACCESS_EVENT'): eventType = Interpretation.ACCESS_EVENT else: eventType = Interpretation.OPEN_EVENT event = Event.new_for_values( actor = "application://decibel-audio-player.desktop", subjects = [subject,], interpretation = eventType, ) self.client.insert_event(event)
def create_and_send_event(self, page, path, event_type): if not self.zeitgeist_client: return #FIXME: Assumes file store store = self.ui.notebook.get_store(page.name) if path is not None: fileobj = store._get_file(path) else: fileobj = store._get_file(page) uri = fileobj.uri origin = gio.File(uri).get_parent().get_uri() text = _('Wiki page: %s') % page.name # T: label for how zim pages show up in the recent files menu, %s is the page name subject = Subject.new_for_values(mimetype='text/x-zim-wiki', uri=uri, origin=origin, interpretation=Interpretation.TEXT_DOCUMENT, manifestation=Manifestation.FILE_DATA_OBJECT, text=text) event = Event.new_for_values(actor='application://zim.desktop', interpretation=event_type, manifestation=Manifestation.USER_ACTIVITY, subjects=[subject,]) self.zeitgeist_client.insert_event(event)
def templates(self): subject = Subject() subject.uri = "!application://*" return [ Event.new_for_values( subjects=[subject], actor="!application://activity-log-manager.desktop") ]
def testFindWithEventOrigin(self): import_events("test/data/twenty_events.js", self) event_template = Event.new_for_values(origin="origin3") result = self.findEventIdsAndWait([event_template], num_events=0, result_type=1) events = self.getEventsAndWait(result) self.assertTrue(len(events) > 0) self.assertTrue(all(ev.origin == "origin3" for ev in events))
def testFindWithSubjectOrigin(self): import_events("test/data/five_events.js", self) subj = Subject.new_for_values(origin="file:///tmp") event_template = Event.new_for_values(subjects=[subj]) result = self.findEventIdsAndWait([event_template], num_events=0, result_type=1) events = self.getEventsAndWait(result) for event in events: test = any(subj.origin == "file:///tmp" for subj in event.subjects) self.assertTrue(test)
def testFindWithInterpretation(self): import_events("test/data/five_events.js", self) subj = Subject() event_template = Event.new_for_values(interpretation="stfu:OpenEvent", subjects=[subj]) result = self.findEventIdsAndWait([event_template], num_events=0, result_type=1) self.assertEquals(2, len(result)) events = self.getEventsAndWait(result) for event in events: self.assertEqual(event.interpretation, "stfu:OpenEvent")
def testFindWithEventOriginNegatedWildcard(self): import_events("test/data/twenty_events.js", self) event_template = Event.new_for_values(origin="!origin*") result = self.findEventIdsAndWait([event_template], num_events=0, result_type=1) events = self.getEventsAndWait(result) self.assertTrue(len(events) > 0) self.assertFalse(any(ev.origin.startswith("origin") for ev in events))
def testFindWithSubjectOrigin(self): import_events("test/data/five_events.js", self) subj = Subject.new_for_values(origin="file:///tmp") event_template = Event.new_for_values(subjects=[subj]) result = self.findEventIdsAndWait([event_template], num_events=0, result_type=1) events = self.getEventsAndWait(result) for event in events: test = any(subj.origin == "file:///tmp" for subj in event.subjects) self.assertTrue(test)
def clean_events (self): event_template = Event.new_for_values( actor=APP_ID, interpretation=Interpretation.VISIT_EVENT.uri) ids = self.iface.FindEventIds((0,0), [event_template], 0, 10, 0) print "Deleting", map (int, ids) self.iface.DeleteEvents (ids)
def testFindWithActor(self): test_event_1 = parse_events("test/data/one_event.js")[0] self.testSingleInsertGet() subj = Subject() event_template = Event.new_for_values( actor="application://gnome-about.desktop", subjects=[subj,]) result = self.findEventIdsAndWait([event_template], num_events=0, result_type=1) self.assertEquals(1, len(result)) test_event_1[0][0] = 1 self.assertEqual(result[0], test_event_1.id)
def testFindWithManifestation(self): import_events("test/data/five_events.js", self) subj = Subject() event_template = Event.new_for_values(manifestation="stfu:EpicFailActivity", subjects=[subj]) result = self.findEventIdsAndWait([event_template], num_events=0, result_type=1) self.assertEquals(1, len(result)) events = self.getEventsAndWait(result) for event in events: self.assertEqual(event.manifestation, "stfu:EpicFailActivity")
def testQueryByParent(self): ev = new_event(subject_interpretation=Interpretation.AUDIO) _ids = self.insertEventsAndWait([ev]) tmpl = Event.new_for_values(subject_interpretation=Interpretation.MEDIA) ids = self.findEventIdsAndWait([tmpl], num_events=10, result_type=ResultType.MostRecentEvents) self.assertEquals(1, len(ids)) self.assertEquals(_ids, list(ids))