~activity-log-manager/activity-log-manager/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# -.- coding: utf-8 -.-
 
# Zeitgeist
#
# Copyright © 2011 J.P. Lacerda <jpaflacerda@gmail.com>
# Copyright © 2011 Seif Lotfy <seif@lotfy.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 2.1 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import os
import shlex
import subprocess
import urllib
import gio
import glib
import time

from zeitgeist.mimetypes import get_interpretation_for_mimetype, get_manifestation_for_uri
from zeitgeist.datamodel import Event, Subject, Interpretation, Manifestation, TimeRange, ResultType, StorageState
from zeitgeist.client import ZeitgeistClient


class Crawler:

	FILE_SCHEME = 'file://'
	APPLICATION_SCHEME = 'application://'

	_manifestation = get_manifestation_for_uri(FILE_SCHEME)
	_actor = APPLICATION_SCHEME + "activity-log-manager.desktop"
	_one_finished = False

	def __init__(self, progress, label, timerange):
		self.start = time.time()

		self.progress = progress
		self.label = label
		self.timerange = timerange

		self.events_created = 0
		self.zg = ZeitgeistClient()

		self._int_cache = {}
		self._sub_hash = []
		self._retrieved_subjects = {}

		self.label.set_text("Starting.")

		e = Event()
		s = Subject()
		s.uri = ""
		e.subjects = [s]

		self.zg.find_events_for_templates([e], self._hash_existing_subjects,
			TimeRange.always(), storage_state=StorageState.Any, num_events=0,
			result_type=ResultType.MostRecentSubjects)

		glib.idle_add(self._retrieve_subjects)

	# Our basic synchronization mechanism...
	# This could be left out, but at least it is explicit.
	def _finished(self):
		if self._one_finished:
			self._process()
		else:
			self._one_finished = True

	def _process(self):
		valid_files = set(self._retrieved_subjects) - set(self._sub_hash)
		valid_uris = []
		for key in valid_files:
			valid_uris.append(self._retrieved_subjects[key])

		self.progress.set_pulse_step(
			((1 - self.progress.get_fraction()) / (len(valid_uris) + 1)) * (2.0 / 3))

		events = map(self._create_new_event, valid_uris)
		events = [e for e in events if e]

		iterations = len(events) / 1000 + 1

		self.progress.set_pulse_step((1 - self.progress.get_fraction()) / iterations)

		for i in xrange(0, iterations):
			self.progress.pulse()
			lower = 1000 * i
			upper = lower + 999
			self.zg.insert_events(events[lower:upper])

		self.progress.set_fraction(1)
		self.label.set_text("Done: %d new events were inserted." % (len(events)))

	def _create_new_event(self, uri):
		self.progress.pulse()

		mimetype = gio.content_type_guess(uri)

		if not mimetype in self._int_cache.keys():
			self._int_cache[mimetype] = get_interpretation_for_mimetype(mimetype)

		interpretation = self._int_cache[mimetype]

		if interpretation:
			subject = Subject()
			subject.uri = uri
			subject.mimetype = mimetype
			subject.interpretation = interpretation.uri
			subject.manifestation = Crawler._manifestation.uri
			subject.text = subject.uri.split("/")[-1]
			subject.origin = subject.uri[0:len(subject.uri) - len(subject.text)]

			event = Event()
			event.interpretation = Interpretation.CREATE_EVENT
			event.manifestation = Manifestation.USER_ACTIVITY
			event.timestamp = str(int(1000 * os.path.getmtime(subject.uri[len(Crawler.FILE_SCHEME):])))
			if int(event.timestamp) >= self.timerange[0] and int(event.timestamp) <= self.timerange[1]:
				event.subjects = [subject]
				event.actor = Crawler._actor
				return event
			else:
				return None
		else:
			return None

	def _hash_existing_subjects(self, events):
		for event in events:
			for subject in event.subjects:
				uri = urllib.unquote(subject.uri)
				self._sub_hash.append(hash(uri))

		self.progress.set_fraction(self.progress.get_fraction() + 0.1)
		self._finished()

	def _retrieve_subjects(self):
		target_directory = os.path.expanduser('~')

		for (dirpath, dirnames, filenames) in os.walk(target_directory):
			dirnames = [d for d in dirnames if not d.startswith('.')]
			filenames = [f for f in filenames if not f.startswith('.')]
			for f in filenames:
				path = os.path.join(dirpath, f)
				if os.path.exists(path):
					uri = Crawler.FILE_SCHEME + path
					self._retrieved_subjects[hash(uri)] = uri

		self.progress.set_fraction(self.progress.get_fraction() + 0.1)
		self._finished()