~lore-mattei/onehundredscopes/shotwell-precise

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#! /usr/bin/python
# -*- coding: latin-1 -*-

#    Copyright (c) 2011 David Calle <davidc@framli.eu>

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 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 General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
import sys, os
from gi.repository import GLib, GObject, Gio
from gi.repository import Dee
_m = dir(Dee.SequenceModel)
from gi.repository import Unity
from datetime import date
import time
import pyexiv2
import shutil

shotwell_db = "/home/"+ os.getenv('USER') +"/.shotwell/data/photo.db"
shutil.copy2(shotwell_db, shotwell_db+'_backup')
print "Shotwell database backup: OK"

BUS_NAME = "net.launchpad.scope.image.shotwell"

class Daemon:
	def __init__ (self):
		self.scope = Unity.Scope.new ("/net/launchpad/scope/image/shotwell")
		self.scope.search_in_global = False
		self.scope.connect ("notify::active-search", self.on_search_changed)
		self.scope.connect ("notify::active", self.on_search_changed)
		self.scope.connect ("notify::active-global-search", self.on_global_search_changed)
		self.scope.connect ("filters-changed", self.on_search_changed);
		self.scope.connect ("activate-uri", self.on_activate_uri);
		self.scope.export()

	def on_activate_uri (self, scope, uri):
		GLib.spawn_command_line_async("xdg-open %s" % uri.replace(' ', '\ '))
		return Unity.ActivationResponse(handled=Unity.HandledType.HIDE_DASH, goto_uri='')


	def get_search_string (self):
		search = self.scope.props.active_search
		return search.props.search_string if search else None
		
	def get_global_search_string (self):
		search = self.scope.props.active_global_search
		return search.props.search_string if search else None

	def on_search_changed (self, scope, param_spec=None):
			search = self.get_search_string()
			print "Search changed to: '%s'" % search
			results = self.scope.props.results_model
			results.clear()
			self.update_results_model (search, results)
			results.flush_revision_queue ()
			
	def on_global_search_changed (self, scope, param_spec=None):
			search = self.get_global_search_string()
			print "Global search changed to: '%s'" % search
			results = self.scope.props.global_results_model
			results.clear()
			self.update_results_model (search, results)
			results.flush_revision_queue ()


	def update_results_model(self, search, model):
		date = self.check_filters("date")
		if self.check_filters("taken_by") != 'contacts':
			if not search or search == '' or search == 'None':
				for i in self.shotwell(search, date):
					title = i[0]
					comment = i[3]
					uri = i[1]
					icon_hint = i[2]
					model.append (uri, icon_hint, 0,"text/html", title, comment, uri)
			else:
				for i in self.shotwell(search, date):
					title = i[0]
					comment = i[3]
					uri = i[1]
					icon_hint = i[2]
					model.append (uri, icon_hint, 1,"text/html", title, comment, uri)

		if self.scope.props.active_search:
			self.scope.props.active_search.emit("finished")

	def check_filters(self, filter_name):
		try:
			filter = self.scope.get_filter(filter_name).get_active_option().props.id
		except (AttributeError):
			filter = None
		return filter

	def shotwell(self, search, date):
		if search is None or search == 'None':
			search = ''
		if date:
			date = int(date)*86400
			now = time.time()
			date = now - date
		search = search.decode('utf-8')
		import sqlite3
		data_list = []
		shotwell_path = ''
		#Check the db path
		shotwell_desktop = "/usr/share/applications/shotwell.desktop"
#		if os.path.exists(shotwell_desktop):
		shotwell_db = "/home/"+ os.getenv('USER') +"/.shotwell/data/photo.db"
		if os.path.exists(shotwell_db):
			conn = sqlite3.connect(shotwell_db)
			# Initiate cursors
			c = conn.cursor()
			d = conn.cursor()
			i = 0
			# Go explore
			if date:
				c.execute('select * from PhotoTable where exposure_time > '+str(date)+' order by id desc')
			else:
				c.execute('select * from PhotoTable order by id desc')
			for row in c:
				item_list = []
				event_id = str(row[10])
				uri = row[1]
				genre = ''
				exif_tags = ''
				title = uri.split('/')[-1]
				metadata = pyexiv2.ImageMetadata(uri)
				metadata.read()
				
				try:
					event = d.execute('select name from EventTable where id='+event_id).fetchone()[0].encode('utf-8')
				except:
					event = ''
				try:
#						date_taken = str(date.fromtimestamp(row[5]))
					date_taken = str(metadata['Exif.Photo.DateTimeOriginal'].value)
					year_taken = date_taken.split('-')[0]
					month_taken = date_taken.split('-')[1]
					day_taken = date_taken.split('-')[2].split(' ')[0]
					hour_taken = date_taken.split(':')[0].split(' ')[1]
					if int(hour_taken) < 10 and int(hour_taken) > 0:
						hour_taken = hour_taken.split('0')[1]
				except:
					date_taken = ''
					year_taken = ''
					month_taken = ''
					day_taken = ''
					hour_taken = ''
				try:
					exif_model =  str(metadata['Exif.Image.Model'].value)
				except:
					exif_model = ''
				try:
					exif_make =  str(metadata['Exif.Image.Make'].value)
				except:
					exif_make = ''
				try:
					for tag in metadata['Iptc.Application2.Keywords'].value:
						exif_tags = exif_tags + '__' + str(tag).decode('utf-8')
				except:
					exif_tags = ''

				icon_hint = row[1]

				if (not search 
					or title.lower().find(search.lower())  > -1
					or event.lower().find(search.lower())  > -1
					or date_taken.lower().find(search.lower())  > -1
					or exif_make.lower().find(search.lower())  > -1
					or exif_model.lower().find(search.lower())  > -1
					or exif_tags.lower().find(search.lower())  > -1
					or genre.lower().find(search.lower())  > -1):
					if i < 100:
#								print hour_taken
#								print time
						item_list.append(title)
						item_list.append(uri)
						item_list.append(icon_hint)
						item_list.append(genre)
						data_list.append(item_list)
						i = i + 1
		return data_list
		c.close()
		d.close()
		conn.close()


if __name__ == "__main__":
	session_bus_connection = Gio.bus_get_sync (Gio.BusType.SESSION, None)
	session_bus = Gio.DBusProxy.new_sync (session_bus_connection, 0, None,
	                                      'org.freedesktop.DBus',
	                                      '/org/freedesktop/DBus',
	                                      'org.freedesktop.DBus', None)
	result = session_bus.call_sync('RequestName',
	                               GLib.Variant ("(su)", (BUS_NAME, 0x4)),
	                               0, -1, None)
	                               
	# Unpack variant response with signature "(u)". 1 means we got it.
	result = result.unpack()[0]
	
	if result != 1 :
		print >> sys.stderr, "Failed to own name %s. Bailing out." % BUS_NAME
		raise SystemExit (1)
	
	daemon = Daemon()
	GObject.MainLoop().run()