Initial commit
[kiosk.git] / picasa_renderer.py
1 import httplib
2 import gdata_oauth
3 import file_writer
4 import renderer
5 import gdata
6 import secrets
7 import sets
8 import random
9 from oauth2client.client import AccessTokenRefreshError
10
11 class picasa_renderer(renderer.debuggable_abstaining_renderer):
12     """A renderer to fetch photos from picasaweb.google.com"""
13
14     album_whitelist = sets.ImmutableSet([
15         'Alex',
16         'Alex 6.0..8.0 years old',
17         'Alex 3.0..4.0 years old',
18         'Barn',
19         'Bangkok and Phukey, 2003',
20         'Blue Angels... Seafair',
21         'Carol Ann and Owen',
22         'Chahuly Glass',
23         'Dunn Gardens',
24         'East Coast, 2011',
25         'East Coast, 2013',
26         'Friends',
27         'Gasches',
28         'Gasch Wedding',
29         'Hiking and Ohme Gardens',
30         'Hiking',
31         'Karen\'s Wedding',
32         'Key West 2019',
33         'Krakow 2009',
34         'Munich, July 2018',
35         'NJ 2015',
36         'NW Trek',
37         'Oahu 2010'
38         'Ocean Shores 2009',
39         'Ohme Gardens',
40         'Olympic Sculpture Park',
41         'Paintings',
42         'Puerto Vallarta',
43         'Photos from posts',
44         'Random',
45         'SFO 2014',
46         'Soccer',
47         'Skiing with Alex',
48         'Tuscany 2008',
49         "Trip to California '16",
50         "Trip to East Coast '16",
51         'Yosemite 2010',
52         'Zoo',
53     ])
54
55     def __init__(self, name_to_timeout_dict, oauth):
56         super(picasa_renderer, self).__init__(name_to_timeout_dict, False)
57         self.oauth = oauth
58         self.photo_urls = {}
59         self.width = {}
60         self.height = {}
61         self.is_video = {}
62
63     def debug_prefix(self):
64         return "picasa"
65
66     def periodic_render(self, key):
67         if (key == 'Fetch Photos'):
68             return self.fetch_photos()
69         elif (key == 'Shuffle Cached Photos'):
70             return self.shuffle_cached()
71         else:
72             raise error('Unexpected operation')
73
74     # Just fetch and cache the photo URLs in memory.
75     def fetch_photos(self):
76         try:
77             temp_photo_urls = {}
78             temp_width = {}
79             temp_height = {}
80             temp_is_video = {}
81             conn = httplib.HTTPSConnection("photoslibrary.googleapis.com")
82             conn.request("GET",
83                          "/v1/albums",
84                          None,
85                          { "Authorization": "%s %s" % (self.oauth.token['token_type'], self.oauth.token['access_token'])
86                          })
87             response = conn.getresponse()
88             if response.status != 200:
89                 print("Failed to fetch albums, status %d\n" % response.status)
90             print response.read()
91             albums = self.pws.GetUserFeed().entry
92             for album in albums:
93                 if (album.title.text not in picasa_renderer.album_whitelist):
94                     continue
95                 photos = self.pws.GetFeed(
96                     '/data/feed/api/user/%s/albumid/%s?kind=photo&imgmax=1024u' %
97                     (secrets.google_username, album.gphoto_id.text))
98                 for photo in photos.entry:
99                     id = '%s/%s' % (photo.albumid.text, photo.gphoto_id.text)
100                     temp_is_video[id] = False
101                     resolution = 999999
102                     for x in photo.media.content:
103                         if "video" in x.type and int(x.height) < resolution:
104                             url = x.url
105                             resolution = int(x.height)
106                             temp_width[id] = x.width
107                             temp_height[id] = x.height
108                             temp_is_video[id] = True
109                         else:
110                             if resolution == 999999:
111                                 url = x.url
112                                 temp_width[id] = x.width
113                                 temp_height[id] = x.height
114                                 temp_is_video[id] = False
115                     temp_photo_urls[id] = url
116             self.photo_urls = temp_photo_urls
117             self.width = temp_width
118             self.height = temp_height
119             self.is_video = temp_is_video
120             return True
121         except (gdata.service.RequestError,
122                 gdata.photos.service.GooglePhotosException,
123                 AccessTokenRefreshError):
124             print("******** TRYING TO REFRESH PHOTOS CLIENT *********")
125             self.oauth.refresh_token()
126             self.client = self.oauth.photos_service()
127             return False
128
129     # Pick one of the cached URLs and build a page.
130     def shuffle_cached(self):
131         if len(self.photo_urls) == 0:
132             print("No photos!")
133             return False
134         pid = random.sample(self.photo_urls, 1)
135         id = pid[0]
136         refresh = 15
137         if (self.is_video[id]): refresh = 60
138
139         f = file_writer.file_writer('photo_23_none.html')
140         f.write("""
141 <style>
142 body{background-color:#303030;}
143 div#time{color:#dddddd;}
144 div#date{color:#dddddd;}
145 </style>
146 <center>""")
147         if self.is_video[id]:
148             f.write('<iframe src="%s" seamless width=%s height=%s></iframe>' % (self.photo_urls[id], self.width[id], self.height[id]))
149         else:
150             f.write('<img src="%s" width=%s alt="%s">' % (self.photo_urls[id], self.width[id], self.photo_urls[id]))
151         f.write("</center>")
152         f.close()
153         return True
154
155 # Test code
156 oauth = gdata_oauth.OAuth(secrets.google_client_id,
157                           secrets.google_client_secret)
158 oauth.get_new_token()
159 if not oauth.has_token():
160     user_code = oauth.get_user_code()
161     print('------------------------------------------------------------')
162     print('Go to %s and enter the code "%s" (no quotes, case-sensitive)' % (
163         oauth.verification_url, user_code))
164     oauth.get_new_token()
165 x = picasa_renderer({"Fetch Photos": (60 * 60 * 12),
166                      "Shuffle Cached Photos": (1)},
167                     oauth)
168 x.fetch_photos()
169