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))
示例#2
0
	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 __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 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))
示例#5
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()
示例#6
0
 def _on_view_pages(self, widget):
     self.home.reset()
     uris = []
     for pIndex in xrange(self.pages.get_n_pages()):
         self.pages.set_current_page(pIndex)
         page = self.pages.get_nth_page(pIndex)
         overviewPage = PageOverviewWidget(page)
         overviewPage.connect("clicked", self._on_page_clicked)
         self.home.add_page(overviewPage)
         uris.append(page.webview.get_uri())
     self.home.show_all()
     self.box.set_current_page(0)
     
     def callback(events):
         self.home.recentDashboard.recentPages.reset()
         for event in events:
             page = PageButton(event.subjects[0])
             print event.subjects[0].uri
             self.home.recentDashboard.recentPages.add_page(page)
         self.home.show_all()
     event = Event()
     event.actor = "application://web.desktop"
     event.subjects = []
     for uri in uris:
         if uri:
             subject = Subject()
             subject.uri = "!"+uri
             event.subjects.append(subject)
     print event
     ZG.find_events_for_template(event, callback, result_type=2)
    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 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)
示例#9
0
 def assertEventsEqual(self, ev1, ev2):
     ev1 = self.get_plain_event(Event(ev1))
     ev2 = self.get_plain_event(Event(ev2))
     if ev1 is not NULL_EVENT and ev2 is not NULL_EVENT:
         if (ev1[0][0] and not ev2[0][0]) or (ev2[0][0] and not ev1[0][0]):
             ev1[0][0] = ev2[0][0] = ""  # delete IDs
     self.assertEqual(ev1, ev2)
 def _on_uri_changed(self, webview, load_status):
     if self.webview.get_property("load-status") ==\
         WebKit.LoadStatus.FINISHED:
         if self.current_uri != self.webview.get_uri():
             if self.current_uri:
                 event = Event()
                 event.interpretation = Interpretation.LEAVE_EVENT
                 event.manifestation = Manifestation.USER_ACTIVITY
                 event.actor = "application://web.desktop"
                 subject = Subject()
                 subject.uri = self.current_uri
                 subject.mimetype = "text/html"
                 subject.text = self.current_title
                 subject.interpretation = Interpretation.WEBSITE
                 subject.manifestation = Manifestation.REMOTE_PORT_ADDRESS
                 event.subjects = [subject]
                 ZG.insert_event(event)
             self.current_uri = self.webview.get_uri()
             self.current_title = self.webview.get_title()
             print "===>", self.current_title 
             event = Event()
             event.interpretation = Interpretation.ACCESS_EVENT
             event.manifestation = Manifestation.USER_ACTIVITY
             event.actor = "application://web.desktop"
             subject = Subject()
             subject.uri = self.current_uri
             subject.mimetype = "text/html"
             subject.text = self.current_title
             subject.interpretation = Interpretation.WEBSITE
             subject.manifestation = Manifestation.REMOTE_PORT_ADDRESS
             event.subjects = [subject]
             ZG.insert_event(event)
示例#11
0
    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])
示例#12
0
	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))
示例#13
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()
		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()
示例#14
0
	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)
示例#15
0
	def _get_base_template(self):
		base_template = Event()
		if self.has_uri:
			subj = Subject()
			subj.set_uri(self.uri+"/*")
			base_template.set_subjects([subj])
		else:
			base_template.set_actor(self.uri)
		return base_template
	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)
示例#17
0
	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])
示例#18
0
	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])
示例#19
0
	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])
示例#20
0
	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])
示例#21
0
	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])
示例#22
0
	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 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))
示例#24
0
	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])
示例#25
0
	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])
示例#26
0
    def get_rss_by_usage(self):
        print "Events: ",
        event_template = Event.new_for_values(
            actor=APP_ID, interpretation=Interpretation.VISIT_EVENT.uri)

        results = []

        ids = self.iface.FindEventIds((0, 0), [event_template], 0, 0, 5)
        for event in self.iface.GetEvents(ids):
            for subject in Event(event).subjects:
                results.append(str(subject.uri))
        return results
示例#27
0
	def testDeleteTwoSimilarEvents(self):
		# Insert a couple similar events
		event1 = parse_events("test/data/single_event.js")[0]
		event2 = Event(event1)
		event2.timestamp = int(event1.timestamp) + 1
		ids = self.insertEventsAndWait([event1, event2])

		# Try deleting one of them
		self.deleteEventsAndWait([ids[0]])

		# Make sure it's gone, but the second one is still there
		retrieved_events = self.getEventsAndWait(ids)
		self.assertEqual(retrieved_events[0], None)
		self.assertEventsEqual(retrieved_events[1], event2)
示例#28
0
	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])
示例#29
0
	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])
示例#30
0
	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 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())
示例#32
0
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)
示例#33
0
    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)
示例#34
0
	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 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 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)
示例#37
0
    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)
示例#38
0
    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)
示例#39
0
        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 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 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)
示例#42
0
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)
示例#43
0
	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)
示例#44
0
    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)
示例#45
0
	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))
示例#46
0
    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)
示例#47
0
    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))
示例#48
0
    def run(self, keywords, path, regex=False):
        """Run the Zeitgeist SearchMethod."""
        self.stop_search = False
        event_template = Event()
        time_range = TimeRange.from_seconds_ago(60 * 3600 * 24)
        # 60 days at most

        results = iface.FindEvents(
            time_range,  # (min_timestamp, max_timestamp) in milliseconds
            [event_template, ],
            datamodel.StorageState.Any,
            1000,
            datamodel.ResultType.MostRecentSubjects
        )

        results = (datamodel.Event(result) for result in results)
        uniques = []

        for event in results:
            if self.stop_search:
                break
            for subject in event.get_subjects():
                uri = str(subject.uri)
                if uri.startswith('file://'):
                    fullname = str(uri[7:])
                    filepath, filename = os.path.split(fullname)
                    if keywords.lower() in filename and \
                            uri not in uniques and \
                            path in filepath:
                        uniques.append(uri)
                        yield fullname
        self.stop_search = True
示例#49
0
    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)
示例#50
0
	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)
示例#51
0
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)
示例#52
0
    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)
示例#53
0
    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)
示例#54
0
    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)
示例#55
0
 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 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 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)
示例#59
0
	def load_events(self, start=0, end=0, actor=None):
		self.set_title("Journal for "+actor)
		def exists(uri):
			return not uri.startswith("file://") or os.path.exists(urllib.unquote(str(uri[7:])))

		def _handle_find_events(ids):
			self._zg.get_events(ids, _handle_get_events)

		def _handle_get_events(events):
			uris = []
			for event in events:
				for subject in event.subjects:
					if exists(subject.uri):
						self.view.append_object(event)
		
		event = Event()
		event.set_actor(actor)
		self._zg.find_events_for_templates([event],_handle_get_events, [start, end], StorageState.Any, 0, 4)