~lore-mattei/onehundredscopes/flickr-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
#! /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
import socket
import simplejson
import time

socket.setdefaulttimeout(4)
BUS_NAME = "net.launchpad.scope.image.flickr"

import flickrapi
api_key = 'b1bc128796e2f2c7896ec7e30cb8c20c'
api_secret = '9c949c35d2485545'

flickr = flickrapi.FlickrAPI(api_key, api_secret)
if flickr.token_cache.token:
	has_token = True
else:
	has_token = False
clicked = False


class Daemon:
	def __init__ (self):
		self.scope = Unity.Scope.new ("/net/launchpad/scope/image/flickr")
		self.scope.search_in_global = False
		self.scope.connect ("search-changed", self.on_search_changed)
		self.scope.connect ("filters-changed", self.on_filtering_changed)
		self.scope.connect ("activate-uri", self.on_activate_uri);
		self.scope.connect("notify::active", self.on_lens_active)
		self.scope.props.sources.connect("notify::filtering",
            self.on_filtering_changed)
		self.scope.export()

	def on_activate_uri (self, scope, uri):
		if uri.startswith("more"):
			page = uri.split('__')[2]
			search = uri.split('__')[1]
			results = self.scope.props.results_model
			results.remove(results.get_iter_at_row(results.get_n_rows()-1))
			self.update_results_model (search, results, page, has_token)
			return Unity.ActivationResponse(handled=Unity.HandledType.SHOW_DASH, goto_uri="")
		elif uri.startswith("connect"):
			self.flickr_connect()
			return Unity.ActivationResponse(handled=Unity.HandledType.HIDE_DASH, goto_uri="")

		else:
#		GLib.spawn_command_line_async("eog %s" % uri)
			return Unity.ActivationResponse(Unity.HandledType.HIDE_DASH, uri=uri)

	def flickr_connect(self):
		global frob
		global token
		(token, frob) = flickr.get_token_part_one(perms='write')
		global clicked
		clicked = True

	def on_filtering_changed(self, *_):
		"""Run another search when a filter change is notified."""
		self.scope.queue_search_changed(Unity.SearchType.DEFAULT)
        
	def on_lens_active(self, *_):
		""" Run a search when the lens is opened """
		if self.scope.props.active:
			self.scope.queue_search_changed(Unity.SearchType.DEFAULT)
            
	def on_search_changed (self, scope, search, search_type, _):
			search_string = search.props.search_string.strip()
			model = search.props.results_model
			model.clear()
			print "Search changed to: '%s'" % search_string
			
			if flickr.token_cache.token:
				has_token = True
			else:
				has_token = False
				if clicked:
					flickr.get_token_part_two((token, frob))
			if search_type is Unity.SearchType.DEFAULT:
				if search_string == '':
					print "Global view without search string : hide"
				else:
					self.update_results_model(search_string, model, '1', has_token)
			if search:
				search.finished()

	def update_results_model(self, search, model, page, has_token):
		i = ''
		counter = 0
		cat = 0
		if len(search) > 0:
			cat = 2
		else:
			cat = 0
		if not has_token:
			model.append ("connect", "goa-panel", cat,"text/html", "Authorize with Flickr", '', '')
		else:
			taken_by = self.check_filters("taken_by")
			date = self.check_filters("date")
			for i in self.flickr(search, page, taken_by, date):
				counter = counter + 1
				title = i[0]
				comment = i[1]
				uri = i[2]
				icon_hint = i[3]
				model.append (uri, icon_hint, cat,"text/html", title, comment, uri)
			if i and counter > 49:
				if not search:
					search = ''
				page = int(page)+1
				model.append ("more__"+search+"__"+str(page), "add", cat,"text/html", "More results", '', '')


	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 flickr(self, search, page, taken_by, date):
		if date:
			date = int(date)*86400
			now = time.time()
			date = now - date
#			print date
		if search is '' or search == 'None':
			search = None

		if search:
			if taken_by == 'me':
				data_flickr = flickr.photos_search(format='json', text=search, user_id='me', extras='url_sq, url_t', page=page,min_taken_date=date, safe_search='3', per_page='50')
			elif taken_by == 'contacts':
				data_flickr = flickr.photos_search(format='json', text=search, contacts='all', extras='url_sq, url_t',  page=page,min_taken_date=date, safe_search='3', per_page='50')
			else:
				data_flickr = flickr.photos_search(format='json', text=search, extras='url_sq, url_t',  page=page,min_taken_date=date, safe_search='3', per_page='50')
		else:
			if taken_by == 'me':
				if date:
					data_flickr = flickr.photos_recentlyUpdated(format='json', extras='url_sq, url_t',min_date=date,  page=page, safe_search='3', per_page='50')
				else:
					data_flickr = flickr.photos_recentlyUpdated(format='json', extras='url_sq, url_t', min_date=1, page=page, safe_search='3', per_page='50')
			elif taken_by == 'contacts':
				if date:
					data_flickr = flickr.photos_getContactsPhotos(format='json', extras='url_sq, url_t',  page=page,min_taken_date=date, safe_search='3', per_page='50', count='49')
				else:
					data_flickr = flickr.photos_getContactsPhotos(format='json', extras='url_sq, url_t',  page=page, safe_search='3', per_page='50', count='49')
			else:
				if date:
					data_flickr = flickr.photos_recentlyUpdated(format='json', extras='url_sq, url_t',min_date=date,  page=page, safe_search='3', per_page='50')
				else:
					data_flickr = flickr.photos_recentlyUpdated(format='json', extras='url_sq, url_t', min_date=1, page=page, safe_search='3', per_page='50')

		data_flickr = data_flickr.strip('jsonFlickrApi(').strip(')')
		data_flickr = simplejson.loads(data_flickr)
		data_list = []
#		print data_flickr
		if data_flickr:
			for i in data_flickr['photos']['photo']:
				item_list = []

				uri = "http://www.flickr.com/photos/%s/%s/" % (i['owner'], i['id'])
				icon_hint = i['url_t']
				title = i['title']
				item_list.append(title)
				item_list.append('')
				item_list.append(uri)
				item_list.append(icon_hint)
				data_list.append(item_list)
			return data_list
		else:
			return []


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()