示例#1
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)
示例#2
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)
    def register_message_event(self, ac_id, who, msg, event_info):
        subject = Subject.new_for_values(
                uri="pidgin://%s/%s" % (ac_id, who),
                interpretation=unicode(Interpretation.IMMESSAGE),
                manifestation=unicode(Manifestation.SOFTWARE_SERVICE),
                origin="pidgin://%s" % (ac_id,),
                mimetype="text/plain",
                storage="local",
                text="%s" % (self._strip_tags(msg)))
        subjects = [subject]
        uris = URIS.findall(self._strip_tags(msg))
        for link in uris:
            if uris.count(link) == 1:
                subject = Subject.new_for_values(
                        uri=link,
                        interpretation=unicode(Interpretation.WEBSITE),
                        manifestation=unicode(#WEB if match http
                                              Manifestation.WEB_DATA_OBJECT  if HTTP.match(link)\
                                              #File if match file
                                              else Manifestation.FILE_DATA_OBJECT if FILE.match(link)\
                                              #something else
                                              else Manifestation.FILE_DATA_OBJECT.REMOTE_DATA_OBJECT
                                            ),
                        origin=origin_from_uri(link),
                        storage=storage_from_uri(link),
                        text=link)
                subjects.append(subject)
            else:
                uris.remove(link)
        event_info['subjects'] = subjects
        event_info['timestamp'] = int(time.time() * 1000)

        event_info['actor'] = 'application://pidgin.desktop'
        self.zclient.insert_event_for_values(**event_info)
        self.event_sent(ac_id, who, msg, event_info)
示例#4
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)
	def testFindEventIdsWithMultipleSubjects(self):
		subj1 = Subject.new_for_values(uri="file:///tmp/foo.txt")
		subj2 = Subject.new_for_values(uri="file:///tmp/loo.txt")
		event = new_event(subjects=[subj1, subj2])
		orig_ids = self.insertEventsAndWait([event])
		result_ids = self.findEventIdsAndWait([Event()], num_events=0,
			result_type=ResultType.LeastRecentEvents)
		self.assertEquals(orig_ids, list(result_ids))
示例#6
0
	def testFindEventIdsWithMultipleSubjects(self):
		subj1 = Subject.new_for_values(uri="file:///tmp/foo.txt")
		subj2 = Subject.new_for_values(uri="file:///tmp/loo.txt")
		event = new_event(subjects=[subj1, subj2])
		orig_ids = self.insertEventsAndWait([event])
		result_ids = self.findEventIdsAndWait([Event()], num_events=0,
			result_type=ResultType.LeastRecentEvents)
		self.assertEqual(orig_ids, list(result_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)
示例#8
0
	def testGetWithMultipleSubjects(self):
		subj1 = Subject.new_for_values(uri="file:///tmp/foo.txt")
		subj2 = Subject.new_for_values(uri="file:///tmp/loo.txt")
		event = new_event(subjects=[subj1, subj2])
		result = self.insertEventsAndWait([event])
		events = self.getEventsAndWait(result)
		self.assertEqual(2, len(events[0].subjects))
		self.assertEqual("file:///tmp/foo.txt", events[0].subjects[0].uri)
		self.assertEqual("file:///tmp/loo.txt", events[0].subjects[1].uri)
示例#9
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)
	def testGetWithMultipleSubjects(self):
		subj1 = Subject.new_for_values(uri="file:///tmp/foo.txt")
		subj2 = Subject.new_for_values(uri="file:///tmp/loo.txt")
		event = new_event(subjects=[subj1, subj2])
		result = self.insertEventsAndWait([event])
		events = self.getEventsAndWait(result)
		self.assertEquals(2, len(events[0].subjects))
		self.assertEquals("file:///tmp/foo.txt", events[0].subjects[0].uri)
		self.assertEquals("file:///tmp/loo.txt", events[0].subjects[1].uri)
示例#11
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)
示例#12
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)
示例#13
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)
示例#14
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)
示例#15
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)
示例#16
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)
示例#17
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)
示例#18
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)
示例#19
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)
示例#20
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)
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)
示例#22
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 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 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)
示例#25
0
	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)
示例#26
0
    def view_event (self, uri):
        ev = Event.new_for_values(timestamp=int(time.time()),
                                  interpretation=Interpretation.VISIT_EVENT.uri,
                                  manifestation=Manifestation.USER_ACTIVITY.uri,
                                  actor=APP_ID)
        subj = Subject.new_for_values(uri=uri,
                                      interpretation=Interpretation.DOCUMENT.uri,
                                      manifestation=Manifestation.FILE.uri)
        ev.append_subject(subj)

        self.iface.InsertEvents ([ev])
        print "VISIT event for <%s> " % (uri)
	def testFindEventsEventTemplate(self):
		import_events("test/data/five_events.js", self)
		subj = Subject.new_for_values(interpretation="stfu:Bee")
		subj1 = Subject.new_for_values(interpretation="stfu:Bar")
		event_template = Event.new_for_values(subjects=[subj, subj1])
		result = self.findEventIdsAndWait(
			[event_template, ],
			timerange = (0, 200),
			num_events=100,
			result_type=0)
		self.assertEquals(0, len(result)) # no subject with two different
										  # interpretations at the same time
		subj = Subject.new_for_values(uri="file:///tmp/foo.txt")
		subj1 = Subject.new_for_values(interpretation="stfu:Image")
		event_template = Event.new_for_values(subjects=[subj, subj1])
		result = self.findEventIdsAndWait(
			[event_template, ],
			timerange = (0, 200),
			num_events=100,
			result_type=0)
		self.assertEquals(1, len(result))
示例#28
0
	def testFindEventsEventTemplate(self):
		import_events("test/data/five_events.js", self)
		subj = Subject.new_for_values(interpretation="stfu:Bee")
		subj1 = Subject.new_for_values(interpretation="stfu:Bar")
		event_template = Event.new_for_values(subjects=[subj, subj1])
		result = self.findEventIdsAndWait(
			[event_template, ],
			timerange = (0, 200),
			num_events=100,
			result_type=0)
		self.assertEqual(0, len(result)) # no subject with two different
										  # interpretations at the same time
		subj = Subject.new_for_values(uri="file:///tmp/foo.txt")
		subj1 = Subject.new_for_values(interpretation="stfu:Image")
		event_template = Event.new_for_values(subjects=[subj, subj1])
		result = self.findEventIdsAndWait(
			[event_template, ],
			timerange = (0, 200),
			num_events=100,
			result_type=0)
		self.assertEqual(1, len(result))
示例#29
0
    def view_event(self, uri):
        ev = Event.new_for_values(
            timestamp=int(time.time()),
            interpretation=Interpretation.VISIT_EVENT.uri,
            manifestation=Manifestation.USER_ACTIVITY.uri,
            actor=APP_ID)
        subj = Subject.new_for_values(
            uri=uri,
            interpretation=Interpretation.DOCUMENT.uri,
            manifestation=Manifestation.FILE.uri)
        ev.append_subject(subj)

        self.iface.InsertEvents([ev])
        print "VISIT event for <%s> " % (uri)
示例#30
0
    def register_message_event(self, ac_id, who, msg, event_info):
        subject = Subject.new_for_values(
            uri="pidgin://%s/%s" % (ac_id, who),
            interpretation=unicode(Interpretation.IMMESSAGE),
            manifestation=unicode(Manifestation.SOFTWARE_SERVICE),
            origin="pidgin://%s" % (ac_id, ),
            mimetype="text/plain",
            storage="local",
            text="%s" % (self._strip_tags(msg)))
        subjects = [subject]
        uris = URIS.findall(self._strip_tags(msg))
        for link in uris:
            if uris.count(link) == 1:
                subject = Subject.new_for_values(
                        uri=link,
                        interpretation=unicode(Interpretation.WEBSITE),
                        manifestation=unicode(#WEB if match http
                                              Manifestation.WEB_DATA_OBJECT  if HTTP.match(link)\
                                              #File if match file

                                              else Manifestation.FILE_DATA_OBJECT if FILE.match(link)\
                                              #something else

                                              else Manifestation.FILE_DATA_OBJECT.REMOTE_DATA_OBJECT
                                            ),
                        origin=origin_from_uri(link),
                        storage=storage_from_uri(link),
                        text=link)
                subjects.append(subject)
            else:
                uris.remove(link)
        event_info['subjects'] = subjects
        event_info['timestamp'] = int(time.time() * 1000)

        event_info['actor'] = 'application://pidgin.desktop'
        self.zclient.insert_event_for_values(**event_info)
        self.event_sent(ac_id, who, msg, event_info)
 def _event_id_request_handler(uris):
     templates = []
     if len(uris) > 0:
         for i, uri in enumerate(uris):
             sub = Subject.new_for_values(uri=uri)
             templates += [
                 Event.new_for_values(subjects=[sub]),
             ]
         CLIENT.find_event_ids_for_templates(
             templates,
             _event_request_handler,
             TimeRange.until_now(),
             num_events=len(uris),
             storage_state=StorageState.Available,
             result_type=ResultType.MostRecentSubjects)
示例#32
0
文件: Zeitgeist.py 项目: csryan/pogo
    def send_to_zeitgeist(self, track, event_type):
        """
        Other players (e.g. Rhythmbox) log the playing of individual files, but
        we want to log albums.

        Maybe it would be better to log individual files, but then we would have
        to distinguish between Manifestation.USER_ACTIVITY and
        Manifestation.SCHEDULED_ACTIVITY.

        Another possible addition would be logging Interpretation.LEAVE_EVENT.
        """
        import mimetypes, os.path

        from zeitgeist.datamodel import Event, Subject, Interpretation, Manifestation

        mime, encoding = mimetypes.guess_type(track.getFilePath(), strict=False)

        title = track.getTitle()
        album = track.getAlbum()
        artist = track.getArtist()
        uri = track.getURI()
        origin = os.path.dirname(uri)

        # Handle "unknown" tags
        if 'unknown' in title.lower():
            title = track.getBasename()
        if 'unknown' in album.lower():
            album = ''
        if 'unknown' in artist.lower():
            artist = ''

        subject = Subject.new_for_values(
            uri            = origin,
            text           = ' - '.join([part for part in [artist, album] if part]),
            mimetype       = mime,
            manifestation  = unicode(Manifestation.FILE_DATA_OBJECT),
            interpretation = unicode(Interpretation.AUDIO),
            origin         = origin,
        )

        event = Event.new_for_values(
            actor          = "application://pogo.desktop",
            subjects       = [subject,],
            interpretation = unicode(event_type),
            timestamp      = int(time.time() * 1000),
        )

        self.client.insert_event(event)
	def testInsertSubjectOptionalAttributes(self):
		ev = Event.new_for_values(
			timestamp=123,
			interpretation=Interpretation.ACCESS_EVENT,
			manifestation=Manifestation.USER_ACTIVITY,
			actor="Freak Mamma"
		)
		subj = Subject.new_for_values(
			uri="void://foobar",
			interpretation=Interpretation.DOCUMENT,
			manifestation=Manifestation.FILE_DATA_OBJECT,
			)
		ev.append_subject(subj)

		ids = self.insertEventsAndWait([ev,])
		result = self.getEventsAndWait(ids)
		self.assertEquals(len(ids), len(result))
示例#34
0
	def testInsertSubjectOptionalAttributes(self):
		ev = Event.new_for_values(
			timestamp=123,
			interpretation=Interpretation.ACCESS_EVENT,
			manifestation=Manifestation.USER_ACTIVITY,
			actor="Freak Mamma"
		)
		subj = Subject.new_for_values(
			uri="void://foobar",
			interpretation=Interpretation.DOCUMENT,
			manifestation=Manifestation.FILE_DATA_OBJECT,
			)
		ev.append_subject(subj)

		ids = self.insertEventsAndWait([ev,])
		result = self.getEventsAndWait(ids)
		self.assertEqual(len(ids), len(result))
示例#35
0
    def log_udf_deleted(self, volume):
        """Log the udf deleted event."""
        folder = Subject.new_for_values(
            uri=URI_PROTOCOL_U1 + str(volume.node_id),
            interpretation=Interpretation.FOLDER,
            manifestation=Manifestation.DELETED_RESOURCE,
            origin="file:///" + volume.path,
            text=basename(volume.path),
            mimetype=DIRECTORY_MIMETYPE,
            storage=STORAGE_DELETED)

        event = Event.new_for_values(
            interpretation=EVENT_INTERPRETATION_U1_UDF_DELETED,
            manifestation=Manifestation.USER_ACTIVITY,
            actor=ACTOR_UBUNTUONE,
            subjects=[folder])

        self.zg.log(event)
示例#36
0
    def handle_FSM_DIR_CONFLICT(self, old_name, new_name):
        """A dir was renamed because of conflict."""
        folder_subject = Subject.new_for_values(
            uri="file:///" + new_name,
            interpretation=Interpretation.FOLDER,
            manifestation=Manifestation.FILE_DATA_OBJECT,
            origin="file:///" + old_name,
            text=basename(new_name),
            mimetype=DIRECTORY_MIMETYPE,
            storage=STORAGE_LOCAL)

        event = Event.new_for_values(
            interpretation=EVENT_INTERPRETATION_U1_CONFLICT_RENAME,
            manifestation=Manifestation.WORLD_ACTIVITY,
            actor=ACTOR_UBUNTUONE,
            subjects=[folder_subject])

        self.zg.log(event)
示例#37
0
    def handle_VM_UDF_CREATED(self, udf):
        """An udf was created. Log it into Zeitgeist."""
        folder = Subject.new_for_values(
            uri=URI_PROTOCOL_U1 + str(udf.node_id),
            interpretation=Interpretation.FOLDER,
            manifestation=Manifestation.REMOTE_DATA_OBJECT,
            origin="file:///" + udf.path,
            text=basename(udf.path),
            mimetype=DIRECTORY_MIMETYPE,
            storage=STORAGE_NETWORK)

        event = Event.new_for_values(
            interpretation=EVENT_INTERPRETATION_U1_UDF_CREATED,
            manifestation=Manifestation.USER_ACTIVITY,
            actor=ACTOR_UBUNTUONE,
            subjects=[folder])

        self.zg.log(event)
示例#38
0
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)
示例#39
0
    def handle_VM_UDF_UNSUBSCRIBED(self, udf):
        """An udf was unsubscribed."""

        folder = Subject.new_for_values(
            uri="file:///" + udf.path,
            interpretation=Interpretation.FOLDER,
            manifestation=Manifestation.DELETED_RESOURCE,
            origin=URI_PROTOCOL_U1 + str(udf.node_id),
            text=basename(udf.path),
            mimetype=DIRECTORY_MIMETYPE,
            storage=STORAGE_DELETED)

        event = Event.new_for_values(
            interpretation=EVENT_INTERPRETATION_U1_UDF_UNSUBSCRIBED,
            manifestation=Manifestation.USER_ACTIVITY,
            actor=ACTOR_UBUNTUONE,
            subjects=[folder])

        self.zg.log(event)
示例#40
0
    def __send_event(self, song, interpretation, manifestation):
        if not song:
            return

        print_d("event: interpretation=%s, manifestation=%s" %
                (interpretation.__name__, manifestation.__name__))

        subject = Subject.new_for_values(
            uri=song("~uri"),
            interpretation=Interpretation.AUDIO,
            manifestation=Manifestation.FILE_DATA_OBJECT,
        )

        event = Event.new_for_values(timestamp=int(time.time() * 1000),
                                     interpretation=interpretation,
                                     manifestation=manifestation,
                                     actor="application://quodlibet.desktop",
                                     subjects=[subject])

        self.client.insert_event(event)
示例#41
0
    def handle_FSM_FILE_CONFLICT(self, old_name, new_name):
        """A file was renamed because of conflict."""
        mime, interp = self.get_mime_and_interpretation_for_filepath(old_name)

        file_subject = Subject.new_for_values(
            uri="file:///" + new_name,
            interpretation=interp,
            manifestation=Manifestation.FILE_DATA_OBJECT,
            origin="file:///" + old_name,
            text=basename(new_name),
            mimetype=mime,
            storage=STORAGE_LOCAL)

        event = Event.new_for_values(
            interpretation=EVENT_INTERPRETATION_U1_CONFLICT_RENAME,
            manifestation=Manifestation.WORLD_ACTIVITY,
            actor=ACTOR_UBUNTUONE,
            subjects=[file_subject])

        self.zg.log(event)
示例#42
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)
示例#43
0
    def __send_event(self, song, interpretation, manifestation):
        if not song:
            return

        print_d("event: interpretation=%s, manifestation=%s" %
                (interpretation.__name__, manifestation.__name__))

        subject = Subject.new_for_values(
            uri=song("~uri"),
            interpretation=Interpretation.AUDIO,
            manifestation=Manifestation.FILE_DATA_OBJECT,
        )

        event = Event.new_for_values(
            timestamp=int(time.time() * 1000),
            interpretation=interpretation,
            manifestation=manifestation,
            actor="application://quodlibet.desktop",
            subjects=[subject]
        )

        self.client.insert_event(event)
示例#44
0
    def handle_SV_DIR_NEW(self, volume_id, node_id, parent_id, name):
        """A file finished downloading from the server."""

        mdo = self.fsm.get_by_node_id(volume_id, node_id)
        path = self.fsm.get_abspath(volume_id, mdo.path)

        file_subject = Subject.new_for_values(
            uri="file:///" + path,
            interpretation=Interpretation.FOLDER,
            manifestation=Manifestation.FILE_DATA_OBJECT,
            origin=URI_PROTOCOL_U1 + str(node_id),
            text=basename(path),
            mimetype=DIRECTORY_MIMETYPE,
            storage=STORAGE_LOCAL)

        event = Event.new_for_values(
            interpretation=Interpretation.CREATE_EVENT,
            manifestation=Manifestation.WORLD_ACTIVITY,
            actor=ACTOR_UBUNTUONE,
            subjects=[file_subject])

        self.zg.log(event)
示例#45
0
    def handle_AQ_DIR_NEW_OK(self, volume_id, marker, new_id, new_generation):
        """A dir was created on the server."""

        mdo = self.fsm.get_by_node_id(volume_id, new_id)
        path = self.fsm.get_abspath(volume_id, mdo.path)

        file_subject = Subject.new_for_values(
            uri=URI_PROTOCOL_U1 + str(new_id),
            interpretation=Interpretation.FOLDER,
            manifestation=Manifestation.REMOTE_DATA_OBJECT,
            origin="file:///" + path,
            text=basename(path),
            mimetype=DIRECTORY_MIMETYPE,
            storage=STORAGE_NETWORK)

        event = Event.new_for_values(
            interpretation=Interpretation.CREATE_EVENT,
            manifestation=Manifestation.SCHEDULED_ACTIVITY,
            actor=ACTOR_UBUNTUONE,
            subjects=[file_subject])

        self.zg.log(event)
示例#46
0
    def testMonitorInsertEventsWithSubjectTemplate(self):
        result = []
        mainloop = self.create_mainloop()
        tmpl = Event.new_for_values(
            subjects=[Subject.new_for_values(uri="file:///tmp/bar.txt")])
        events = parse_events("test/data/five_events.js")

        @asyncTestMethod(mainloop)
        def notify_insert_handler(time_range, events):
            result.extend(events)
            mainloop.quit()

        @asyncTestMethod(mainloop)
        def notify_delete_handler(time_range, event_ids):
            mainloop.quit()
            self.fail("Unexpected delete notification")

        self.client.install_monitor([153, 166], [tmpl], notify_insert_handler,
                                    notify_delete_handler)
        self.client.insert_events(events)
        mainloop.run()

        self.assertEqual(1, len(result))
	def testMonitorInsertEventsOutOfTimeRange(self):
		result = []
		mainloop = self.create_mainloop()
		tmpl = Event.new_for_values(
			subjects=[Subject.new_for_values(uri="file:///tmp/*")])
		events = parse_events("test/data/five_events.js")
		
		@asyncTestMethod(mainloop)
		def notify_insert_handler(time_range, events):
			result.extend(events)
			mainloop.quit()
		
		@asyncTestMethod(mainloop)
		def notify_delete_handler(time_range, event_ids):
			mainloop.quit()
			self.fail("Unexpected delete notification")
			
		self.client.install_monitor([0,155], [tmpl],
			notify_insert_handler, notify_delete_handler)
		self.client.insert_events(events)
		mainloop.run()
		
		self.assertEquals(3, len(result))
示例#48
0
	def testInsertGetWithoutTimestamp(self):
		# We test two things, that Event creates a default timestamp
		# and that the engine provides one for us if necessary

		subj = Subject.new_for_values(interpretation="foo://interp",
					manifestation="foo://manif",
					uri="nowhere")
		ev = Event.new_for_values(interpretation="foo://bar",
					manifestation="foo://quiz",
					actor="actor://myself",
					subjects=[subj])

		# Assert that timestamp is set
		self.assertTrue(ev.timestamp)

		# Clear the timestamp and insert event
		ev.timestamp = ""
		ids = self.insertEventsAndWait([ev])
		result = self.getEventsAndWait(ids)

		self.assertEqual(1, len(result))
		resulting_event = Event(result.pop())
		self.assertEqual("foo://bar", resulting_event.interpretation)
		self.assertTrue(resulting_event.timestamp) # We should have a timestamp again
示例#49
0
 def register_media_event(self, media, interpretation, *args, **kw):
     """ Called as last in line to register event.
     This function was designed to not require overrided
     
     :param media: mpris2.types.Metadata_Map, media metadata
     :param interpretation: event interpretation
     :param *args: *args from property_changed (player mpris signal)
     :param event: to override event to be registered
     :param subject: to override subject of event to be registered
     :param actor: event actor, default is self.app_uri
     :param event_interpretation:  event interpretation, default is interpretation param
     :param event_manifestation: event manifestation, default is Manifestation.SCHEDULED_ACTIVITY
     :param subject_interpretation: subject interpretation, default is self.interpretation
     :param uri: media uri, default is media Metadata_Map.URL
     :param origin: media folder uri, default is media Metadata_Map.URL without filename
     :param minetype: minetype of media, deafult is self.minetype
     :param text: register description, default is track - title - artist - album
     :param storage: storage of media, defaul is self.storage
     """
     self.log(logging.DEBUG, 'sending info %s:%s to zeitgeist', media,
              interpretation)
     #subject
     subject_values = kw.get(
         "subject_values",
         {
             "interpretation":
             kw.get("subject_interpretation",
                    self.interpretation),  #FIXME get information from file
             "manifestation":
             kw.get("subject_manifestation",
                    unicode(Manifestation.FILE_DATA_OBJECT)),
             "uri":
             kw.get("uri", media.get(Metadata_Map.URL)),
             "current_uri":
             kw.get("current_uri", media.get(Metadata_Map.URL)),
             "origin":
             kw.get("origin",
                    media.get(Metadata_Map.URL, "").replace(".\/+", "\/")),
             "mimetype":
             kw.get("mimetype",
                    self.minetype),  #FIXME get information from file
             "text":
             kw.get(
                 "text", "%s - %s - %s - %s" %
                 (media.get(Metadata_Map.TRACK_NUMBER,
                            ""), media.get(Metadata_Map.TITLE, ""), "".join(
                                media.get(Metadata_Map.ARTIST, [])),
                  media.get(Metadata_Map.ALBUM, ""))),
             "storage":
             kw.get("storage",
                    self.storage),  #FIXME get information from file
         })
     subject = kw.get("subject", Subject.new_for_values(**subject_values))
     #event
     event_values = kw.get(
         "event_values", {
             "timestamp":
             int(time.time() * 1000),
             "actor":
             kw.get("actor", self.app_uri),
             "interpretation":
             kw.get("event_interpretation", interpretation),
             "manifestation":
             kw.get("event_manifestation",
                    Manifestation.EVENT_MANIFESTATION.SCHEDULED_ACTIVITY),
         })
     event = kw.get("event", Event.new_for_values(**event_values))
     event.append_subject(subject)
     #send this to zeitgeist
     self.client.insert_event(event)
     self.event_sent(event)
     self.log(logging.DEBUG, 'info %s:%s, was sent to zeitgeist', media,
              interpretation)