forked from mrworf/photoframe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathframe.py
executable file
·506 lines (454 loc) · 16.5 KB
/
frame.py
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
#!/usr/bin/env python
#
# This file is part of photoframe (https://github.com/mrworf/photoframe).
#
# photoframe 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.
#
# photoframe 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 photoframe. If not, see <http://www.gnu.org/licenses/>.
#
import json
import sys
import os
import random
import hashlib
import datetime
import time
import math
import subprocess
import logging
import socket
import threading
import argparse
import shutil
import traceback
from modules.remember import remember
from modules.shutdown import shutdown
from modules.timekeeper import timekeeper
from modules.settings import settings
from modules.helper import helper
from modules.display import display
from modules.oauth import OAuth
from modules.slideshow import slideshow
from modules.colormatch import colormatch
from modules.drivers import drivers
void = open(os.devnull, 'wb')
# Supercritical, since we store all photoframe files in a subdirectory, make sure to create it
if not os.path.exists(settings.CONFIGFOLDER):
try:
os.mkdir(settings.CONFIGFOLDER)
except:
logging.exception('Unable to create configuration directory, cannot start')
sys.exit(255)
elif not os.path.isdir(settings.CONFIGFOLDER):
logging.error('%s isn\'t a folder, cannot start', settings.CONFIGFOLDER)
sys.exit(255)
import requests
from requests_oauthlib import OAuth2Session
from flask import Flask, request, redirect, session, url_for, abort, flash
from flask.json import jsonify
from flask_httpauth import HTTPBasicAuth
from werkzeug.utils import secure_filename
from werkzeug.exceptions import HTTPException
# used if we don't find authentication json
class NoAuth:
def __init__(self):
pass
def login_required(self, fn):
def wrap(*args, **kwargs):
return fn(*args, **kwargs)
wrap.func_name = fn.func_name
return wrap
parser = argparse.ArgumentParser(description="PhotoFrame - A RPi3 based digital photoframe", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--logfile', default=None, help="Log to file instead of stdout")
parser.add_argument('--port', default=7777, type=int, help="Port to listen on")
parser.add_argument('--listen', default="0.0.0.0", help="Address to listen on")
parser.add_argument('--debug', action='store_true', default=False, help='Enable loads more logging')
cmdline = parser.parse_args()
if cmdline.debug:
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
else:
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.getLogger('werkzeug').setLevel(logging.ERROR)
logging.getLogger('oauthlib').setLevel(logging.ERROR)
logging.getLogger('urllib3').setLevel(logging.ERROR)
app = Flask(__name__, static_url_path='')
app.config['UPLOAD_FOLDER'] = '/tmp/'
user = None
userfiles = ['/boot/http-auth.json', settings.CONFIGFOLDER + '/http-auth.json']
for userfile in userfiles:
if os.path.exists(userfile):
logging.debug('Found "%s", loading the data' % userfile)
try:
with open(userfile, 'rb') as f:
user = json.load(f)
if 'user' not in user or 'password' not in user:
logging.warning("\"%s\" doesn't contain a user and password key" % userfile)
user = None
else:
break
except:
logging.exception('Unable to load JSON from "%s"' % userfile)
user = None
if user is None:
logging.info('No http-auth.json found, disabling http authentication')
auth = NoAuth()
if user is not None:
auth = HTTPBasicAuth()
@auth.get_password
def check_password(username):
if user['user'] == username:
return user['password']
return None
@app.after_request
def nocache(r):
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
r.headers['Cache-Control'] = 'public, max-age=0'
return r
@app.errorhandler(Exception)
def show_error(e):
if isinstance(e, HTTPException):
code = e.code
message = str(e)
else:
code = 500
#exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exc().splitlines()
issue = lines[-1]
message = '''
<html><head><title>Internal error</title></head><body style="font-family: Verdana"><h1>Uh oh, something went wrong...</h1>
Please go to <a href="https://github.com/mrworf/photoframe/issues">github</a>
and see if this is a known issue, if not, feel free to file a <a href="https://github.com/mrworf/photoframe/issues/new">new issue<a> with the
following information:
<pre style="margin: 15pt; padding: 10pt; border: 1px solid; background-color: #eeeeee">'''
for line in lines:
message += line + '\n'
message += '''</pre>
Thank you for your patience
</body>
</html>
'''
return message, code
@app.route('/update/force', methods=['GET'])
def force_update():
if os.path.exists('/root/photoframe/update.sh'):
p = subprocess.Popen('/bin/bash /root/photoframe/update.sh 2>&1 | logger -t forced_update', shell=True)
return 'Update in process', 200
else:
return 'Cannot find update tool', 404
@app.route('/debug', methods=['GET'], defaults={'all' : False})
@app.route('/debug/all', methods=['GET'], defaults={'all' : True})
def show_logs(all):
# Special URL, we simply try to extract latest 100 lines from syslog
# and filter out frame messages. These are shown so the user can
# add these to issues.
stats = os.stat('/var/log/syslog')
cmd = 'grep "photoframe\[" /var/log/syslog | tail -n 100'
title = 'Last 100 lines from the log'
if all:
title = 'Last 100 lines from the log (unfiltered)'
cmd = 'tail -n 100 /var/log/syslog'
lines = subprocess.check_output(cmd, shell=True)
message = '''
<html><head><title>Internal debugging</title></head><body style="font-family: Verdana"><h1>%s</h1>
<pre style="margin: 15pt; padding: 10pt; border: 1px solid; background-color: #eeeeee">''' % title
if lines:
for line in lines.splitlines():
message += line + '\n'
else:
message += 'Logs unavailable, perhaps it was archived recently (size will be less than 5000 bytes)'
message += '''</pre>
(size of logfile %d bytes, created %s)
</body>
</html>
''' % (stats.st_size, datetime.datetime.fromtimestamp(stats.st_ctime).strftime('%c'))
return message, 200
@app.route('/setting', methods=['GET'], defaults={'key':None,'value':None})
@app.route('/setting/<key>', methods=['GET'], defaults={'value':None})
@app.route('/setting/<key>/<value>', methods=['PUT'])
@auth.login_required
def cfg_keyvalue(key, value):
global powermanagement
# Depending on PUT/GET we will either change or read
# values. If key is unknown, then this call fails with 404
if key is not None:
if settings.getUser(key) is None:
abort(404)
return
if request.method == 'PUT':
status = True
if key == "keywords":
# Keywords has its own API
abort(404)
return
settings.setUser(key, value)
if key in ['display-driver']:
drv = settings.getUser('display-driver')
if drv == 'none':
drv = None
special = drivers.activate(drv)
if special is None:
settings.setUser('display-driver', 'none')
settings.setUser('display-special', None)
status = False
else:
settings.setUser('display-special', special)
if key in ['timezone']:
# Make sure we convert + to /
settings.setUser('timezone', value.replace('+', '/'))
helper.timezoneSet(settings.getUser('timezone'))
if key in ['resolution', 'tvservice']:
width, height, tvservice = display.setConfiguration(value, settings.getUser('display-special'))
settings.setUser('tvservice', tvservice)
settings.setUser('width', width)
settings.setUser('height', height)
display.enable(True, True)
if key in ['display-on', 'display-off']:
timekeeper.setConfiguration(settings.getUser('display-on'), settings.getUser('display-off'))
if key in ['autooff-lux', 'autooff-time']:
timekeeper.setAmbientSensitivity(settings.getUser('autooff-lux'), settings.getUser('autooff-time'))
if key in ['powersave']:
timekeeper.setPowermode(settings.getUser('powersave'))
if key in ['shutdown-pin']:
powermanagement.stopmonitor()
powermanagement = shutdown(settings.getUser('shutdown-pin'))
settings.save()
return jsonify({'status':status})
elif request.method == 'GET':
if key is None:
return jsonify(settings.getUser())
else:
return jsonify({key : settings.getUser(key)})
abort(404)
@app.route('/keywords', methods=['GET'])
@app.route('/keywords/add', methods=['POST'])
@app.route('/keywords/delete', methods=['POST'])
@auth.login_required
def cfg_keywords():
if request.method == 'GET':
return jsonify({'keywords' : settings.getUser('keywords')})
elif request.method == 'POST' and request.json is not None:
result = True
if 'id' not in request.json:
if settings.addKeyword(request.json['keywords']):
settings.save()
else:
if settings.removeKeyword(request.json['id']):
settings.save()
else:
result = False
return jsonify({'status':result})
abort(500)
@app.route('/has/token')
@app.route('/has/oauth')
@auth.login_required
def cfg_hasthis():
result = False
if '/token' in request.path:
if settings.get('oauth_token') is not None:
result = True
elif '/oauth' in request.path:
result = oauth.hasOAuth()
return jsonify({'result' : result})
@app.route('/oauth', methods=['POST'])
@auth.login_required
def cfg_oauth_info():
if request.json is None or 'web' not in request.json:
abort(500)
data = request.json['web']
oauth.setOAuth(data)
with open(settings.CONFIGFOLDER + '/oauth.json', 'wb') as f:
json.dump(data, f);
return jsonify({'result' : True})
@app.route('/reset')
@auth.login_required
def cfg_reset():
# Remove driver if active
drivers.activate(None)
# Delete configuration data
if os.path.exists(settings.CONFIGFOLDER):
shutil.rmtree(settings.CONFIGFOLDER, True)
# Reboot
subprocess.call(['/sbin/reboot'], stderr=void);
return jsonify({'reset': True})
@app.route('/reboot')
@auth.login_required
def cfg_reboot():
subprocess.call(['/sbin/reboot'], stderr=void);
return jsonify({'reboot' : True})
@app.route('/shutdown')
@auth.login_required
def cfg_shutdown():
subprocess.call(['/sbin/poweroff'], stderr=void);
return jsonify({'shutdown': True})
@app.route('/details/<about>')
@auth.login_required
def cfg_details(about):
if about == 'tvservice':
result = {}
result['resolution'] = display.available()
result['status'] = display.current()
return jsonify(result)
elif about == 'current':
image, mime = display.get()
response = app.make_response(image)
response.headers.set('Content-Type', mime)
return response
elif about == 'drivers':
result = drivers.list().keys()
return jsonify(result)
elif about == 'timezone':
result = helper.timezoneList()
return jsonify(result)
elif about == 'version':
output = subprocess.check_output(['git', 'log', '-n1'], stderr=void)
lines = output.split('\n')
return jsonify({'date':lines[2][5:].strip(),'commit':lines[0][7:].strip()})
elif about == 'color':
return jsonify(slideshow.getColorInformation())
elif about == 'sensor':
return jsonify({'sensor' : colormatch.hasSensor()})
elif about == 'display':
return jsonify({'display':display.isEnabled()})
abort(404)
@app.route('/upload/<item>', methods=['POST'])
@auth.login_required
def upload(item):
retval = {'status':200, 'return':{}}
if request.method == 'POST':
# check if the post request has the file part
if 'filename' not in request.files:
logging.error('No file part')
abort(405)
file = request.files['filename']
if item == 'driver':
# if user does not select file, browser also
# submit an empty part without filename
if file.filename == '' or not file.filename.lower().endswith('.zip'):
logging.error('No filename or invalid filename')
abort(405)
filename = os.path.join('/tmp/', secure_filename(file.filename))
file.save(filename)
if item == 'driver':
result = drivers.install(filename)
if result is not False:
# Check and see if this is the driver we're using
if result['driver'] == settings.getUser('display-driver'):
# Yes it is, we need to activate it and return info about restarting
special = drivers.activate(result['driver'])
if special is None:
settings.setUser('display-driver', 'none')
settings.setUser('display-special', None)
retval['status'] = 500
else:
settings.setUser('display-special', special)
retval['return'] = {'reboot' : True}
else:
retval['return'] = {'reboot' : False}
try:
os.remove(filename)
except:
pass
if retval['status'] == 200:
return jsonify(retval['return'])
abort(retval['status'])
abort(405)
@app.route("/link")
@auth.login_required
def oauth_step1():
return redirect(oauth.initiate())
@app.route("/callback", methods=["GET"])
@auth.login_required
def oauth_step3():
oauth.complete(request.url)
return redirect(url_for('.complete'))
@app.route("/complete", methods=['GET'])
@auth.login_required
def complete():
slideshow.start(True)
return redirect('/')
@app.route('/', defaults={'file':None})
@app.route('/<file>')
@auth.login_required
def web_main(file):
if file is None:
return app.send_static_file('index.html')
else:
return app.send_static_file(file)
@app.route('/template/<file>')
@auth.login_required
def web_template(file):
return app.send_static_file('template/' + file)
settings = settings()
drivers = drivers()
display = display()
if not settings.load():
# First run, grab display settings from current mode
current = display.current()
if current is not None:
logging.info('No display settings, using: %s' % repr(current))
settings.setUser('tvservice', '%s %s HDMI' % (current['mode'], current['code']))
settings.save()
else:
logging.info('No display attached?')
if settings.getUser('timezone') == '':
settings.setUser('timezone', helper.timezoneCurrent())
settings.save()
width, height, tvservice = display.setConfiguration(settings.getUser('tvservice'), settings.getUser('display-special'))
settings.setUser('tvservice', tvservice)
settings.setUser('width', width)
settings.setUser('height', height)
settings.save()
# Force display to desired user setting
display.enable(True, True)
# Spin until we have internet, check every 10s
while True:
settings.set('local-ip', helper.getIP())
if settings.get('local-ip') is None:
logging.error('You must have functional internet connection to use this app')
display.message('No internet')
time.sleep(10)
else:
break
def oauthGetToken():
return settings.get('oauth_token')
def oauthSetToken(token):
settings.set('oauth_token', token)
settings.save()
oauth = OAuth(settings.get('local-ip'), oauthSetToken, oauthGetToken)
if os.path.exists(settings.CONFIGFOLDER + '/oauth.json'):
try:
with open(settings.CONFIGFOLDER + '/oauth.json') as f:
data = json.load(f)
if 'web' in data: # if someone added it via command-line
data = data['web']
oauth.setOAuth(data)
except:
logging.exception('OAuth file is corrupt, do not use')
# Prep random
random.seed(long(time.clock()))
colormatch = colormatch(settings.get('colortemp-script'), 2700) # 2700K = Soft white, lowest we'll go
slideshow = slideshow(display, settings, oauth, colormatch)
timekeeper = timekeeper(display.enable, slideshow.start)
slideshow.setQueryPower(timekeeper.getDisplayOn)
timekeeper.setConfiguration(settings.getUser('display-on'), settings.getUser('display-off'))
timekeeper.setAmbientSensitivity(settings.getUser('autooff-lux'), settings.getUser('autooff-time'))
timekeeper.setPowermode(settings.getUser('powersave'))
colormatch.setUpdateListener(timekeeper.sensorListener)
powermanagement = shutdown(settings.getUser('shutdown-pin'))
if __name__ == "__main__":
# This allows us to use a plain HTTP callback
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
app.secret_key = os.urandom(24)
slideshow.start()
app.run(debug=False, port=cmdline.port, host=cmdline.listen )
sys.exit(0)