/
main.py
1502 lines (1337 loc) · 55.4 KB
/
main.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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2015 Mark Spurgeon
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import flask
from flask import Flask
from flask import g, make_response, request, current_app,send_from_directory,render_template,redirect,url_for, Markup, Response, session, Markup
from werkzeug import parse_options_header
from flask.ext.cache import Cache
from flask.ext.mobility import Mobility
from flask.ext.mobility.decorators import mobile_template
from traceback import print_exc
from google.appengine.api import users
from google.appengine.ext import ndb
from google.appengine.ext import blobstore
from google.appengine.ext.blobstore.blobstore import BlobKey
from google.appengine.api import images
from google.appengine.api import mail
from apiclient import discovery
from oauth2client import client
import httplib2
import json
import uuid
from authomatic.adapters import WerkzeugAdapter
from authomatic import Authomatic
import app_list
from plugins import plugins1 as plugins
from plugins import browsers as sp_browsers
from plugins import apikeys
import sp_data
from plugins.auth_config import CONFIG
app = Flask(__name__)
app.config['DEBUG'] = False
app.secret_key = str(uuid.uuid4())
cache = Cache(app,config={'CACHE_TYPE': 'gaememcached'})
Mobility(app)
authomatic = Authomatic(CONFIG, 'your secret string', report_errors=False)
# Note: We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.
def checkUserLoggedIn():
user=False
user_type=''
user_info=None
#print flask.session['ext-user']
cookieAdd = "&key=" + apikeys.keys['self']
if request.cookies.has_key("sp-user"):
ext = request.cookies.get('sp-user').replace(cookieAdd,'')
try :
sp_item = sp_data.ExternalUser.get_by_id(int(ext))
if sp_item:
user = True
user_info = sp_item.to_dict()
user_info['user-id']=sp_item.key.id()
except:pass
else: pass
return (user, user_info)
def jsonResponse(json_dict):
resp = Response(json.dumps(json_dict,indent=4, separators=(',', ': ')), mimetype="application/json")
resp.headers['Access-Control-Allow-Origin']="*"
return resp
@app.route('/')
def index():
return redirect(url_for("presentation"))
#return render_template('index.html')
@app.route('/home/')
def homepage():
return render_template('index.html')
@app.route('/more/')
def presentation():
#return redirect(url_for("signup"))
return render_template('presentation.html')
@app.route('/robots.txt')
def bots():
return render_template('robots.txt')
@app.route('/_data_info/')
@cache.cached(timeout=7200)
def info():
l = [ i for i in sp_data.ExternalUser.query()]
count = len(l)
l2 = [ i for i in sp_data.appIconProposed.query()]
count2 = len(l2)
return render_template('data.html', userCount=count,iconCount=count2 )
@app.route('/sitemap/')
def index_sitemap():
return render_template('sitemap.html')
@app.route('/terms/')
def tos():
return render_template("tos.html")
@app.route('/privacy/')
def privacy():
return render_template("privacy.html")
@app.route('/features/')
def features():
return redirect(url_for("index"))
@app.route('/features/search')
def features_searcj():
return render_template('feature-search.html')
@app.route('/browsers/')
def browsers():
return render_template('browsers.html')
@app.route('/browsers/firefox')
def browsers_f():
return render_template('browsers/firefox.html')
@app.route('/browsers/chrome')
def browsers_c():
return render_template('browsers/chrome.html')
@app.route('/browsers/safari')
def browsers_s():
return render_template('browsers/safari.html')
@app.route('/browsers/ie')
def browsers_e():
return render_template('browsers/ie.html')
@app.route('/browsers/opera')
def browsers_o():
return render_template('browsers/opera.html')
@app.route('/browsers/other')
def browsers_other():
return render_template('browsers/other.html')
@app.route('/login/')
def login():
u, u_i = checkUserLoggedIn()
if u and u_i:
return redirect(url_for('edit'))
else:
return render_template('login.html')
@app.route('/signup/')
def signup():
u, u_i = checkUserLoggedIn()
if u and u_i:
return redirect(url_for('edit'))
else:
return render_template('signup.html')
#blobstore image
@app.route("/image/<bkey>")
def imag(bkey):
blob_info = blobstore.get(bkey)
response = make_response(blob_info.open().read())
response.headers['Content-Type'] = blob_info.content_type
return response
###
# Main Startpage
###
@app.route('/sp/<source>/<user>')
def sp(source,user):
return redirect(url_for('edit'))
@app.route('/<id_>')
def sp_short(id_):
#sp_l = sp_data.ExternalUser.query()
sp_item = sp_data.ExternalUser.get_by_id(int(id_))
if sp_item:
user = sp_item
theme = user.themeName
apps = user.linksList
apps = sorted(apps, key=lambda k: k['position'])
a_list = []
for a in apps :
if a['icon'].startswith('icon:'):
ur = a['icon'].replace('icon:','')
a['icon']='/icons/get?url='+ur
img_url = str(user.backgroundImageURL)+"=s0"#"http://startpage-1072.appspot.com/image/"+str(u[0].backgroundImageKey)
#md = markdown.Markdown()
title = user.spTitle #Markup(md.convert(u[0].spTitle))
manifest_url = "http://startpage-1072.appspot.com/manifest/{0}/{1}".format(user.source,user.userID)
#search browser
if not user.searchBrowser:
user.searchBrowser = 'google'
user.put()
if user.searchBrowser in sp_browsers.browserOptions:
se = user.searchBrowser
else:
se = sp_browsers.defaultBrowser
se_info = sp_browsers.browsers[se]
searchEngine = user.searchBrowser
searchEngineURL = se_info['url']
searchEngineArg_search = se_info['#search']
resp = make_response(render_template('sp.html',title=title,apps=apps, theme=theme,img=img_url,manifest=manifest_url,searchEngine = searchEngine,searchEngineURL =searchEngineURL,searchEngineArg_search=searchEngineArg_search))
resp.set_cookie('first-login',str(False))
return resp
else:
abort(404)
@app.route('/firefox_addon/<id_>')
def sp_firefox_addon(id_):
sp_item = sp_data.ExternalUser.get_by_id(int(id_))
if sp_item:
user=sp_item
theme = user.themeName
apps = user.linksList
apps = sorted(apps, key=lambda k: k['position'])
a_list = []
for a in apps :
if a['icon'].startswith('icon:'):
ur = a['icon'].replace('icon:','')
a['icon']='/icons/get?url='+ur
if user.backgroundImageURL:
img_url = str(user.backgroundImageURL)+"=s0"#"http://startpage-1072.appspot.com/image/"+str(u[0].backgroundImageKey)
else:
img_url=''
#md = markdown.Markdown()
title = user.spTitle #Markup(md.convert(u[0].spTitle))
manifest_url = "http://startpage-1072.appspot.com/manifest/{0}/{1}".format(user.source,user.userID)
resp = make_response(render_template('sp_firefox_addon.html',title=title,apps=apps, theme=theme,img=img_url,manifest=manifest_url))
resp.set_cookie('first-login',str(False))
return resp
else:
abort(404)
@app.route('/resources/zipfile/<id_>')
def sp_zip(id_):
sp_item = sp_data.ExternalUser.get_by_id(int(id_))
if sp_item:
import zipfile
import urllib2
import StringIO
##create zip file object
output = StringIO.StringIO()
z = zipfile.ZipFile(output,'w')
## add static files
# -> js
jq = urllib2.urlopen('http://that.startpage.rocks/static/js/jquery.js').read()
z.writestr("js/jquery.min.js",jq)
js = urllib2.urlopen('http://that.startpage.rocks/static/js/main-local.js').read()
z.writestr("js/main.js",js)
# -> css
css = urllib2.urlopen('http://that.startpage.rocks/static/styles/main.css').read()
z.writestr("css/main.css",css)
if sp_item.themeName !="white":
css2 = urllib2.urlopen('http://that.startpage.rocks/static/styles/{}Theme.css'.format(sp_item.themeName)).read()
else:
css2=""
z.writestr("css/theme.css",css2)
# -> background image
bg = urllib2.urlopen(sp_item.backgroundImageURL+"=s0").read()
z.writestr("image.png",bg)
## generate html
user = sp_item
theme = user.themeName
apps = user.linksList
apps = sorted(apps, key=lambda k: k['position'])
a_list = []
for a in apps :
if a['icon'].startswith('icon:'):
ur = a['icon'].replace('icon:','')
a['icon']='http://that.startpage.rocks/icons/get?url='+ur
img_url = str(user.backgroundImageURL)+"=s0"#"http://startpage-1072.appspot.com/image/"+str(u[0].backgroundImageKey)
#md = markdown.Markdown()
title = user.spTitle #Markup(md.convert(u[0].spTitle))
#manifest_url = "http://that.startpage.rocks/resources/manifest/{}".format(int(id_))
#search browser
if not user.searchBrowser:
user.searchBrowser = 'google'
user.put()
if user.searchBrowser in sp_browsers.browserOptions:
se = user.searchBrowser
else:
se = sp_browsers.defaultBrowser
se_info = sp_browsers.browsers[se]
searchEngine = user.searchBrowser
searchEngineURL = se_info['url']
searchEngineArg_search = se_info['#search']
html = render_template('sp-local.html',
title=title,
apps=apps,
theme=theme,
img=img_url,
searchEngine = searchEngine,
searchEngineURL =searchEngineURL,
searchEngineArg_search=searchEngineArg_search)
html = html.encode('utf-8')
z.writestr("index.html",html)
z.close()
#response
resp = Response(output.getvalue())
resp.headers['Content-Type'] = 'application/zip'
resp.headers['Content-Disposition'] = 'attachment; filename=startpage.zip'
return resp
else:
abort(404)
@app.route('/resources/manifest/<id_>')
def sp_manifest(id_):
sp_item = sp_data.ExternalUser.get_by_id(int(id_))
if sp_item:
user=sp_item
img = str(user.backgroundImageURL)+"=s0"
apps = user.to_dict()['linksList']
theme = user.themeName
resp = Response(render_template('manifest.html', img=img,apps=apps,theme=theme))
resp.headers["Content-Type"]="text/cache-manifest"
resp.headers["Cache-Control"]="max-age=0, no-cache, public"
return resp
else:
abort(404)
@app.route('/resources/json/<id_>')
def sp_debug(id_):
sp_item = sp_data.ExternalUser.get_by_id(int(id_))
if sp_item:
theme = u[0].themeName
apps = u[0].linksList
img_url = u[0].backgroundImageURL
manifest_url = "http://startpage-1072.appspot.com/manifest/{0}/{1}".format(u[0].source,u[0].userID)
return jsonResponse({'apps':apps, 'theme':theme,'img':img_url,'manifest':manifest_url})
else:
abort(404)
#####
## First Setup
#####
#Give a title
@app.route('/setup/1')
def setup_one():
u, u_i = checkUserLoggedIn()
if u and u_i:
return render_template('setup/1.html')
else:
return redirect(url_for('login'))
#Upload a background url
@app.route('/setup/2')
def setup_two():
u, u_i = checkUserLoggedIn()
if u and u_i:
uploadUri = blobstore.create_upload_url('/config/upload-bg')
return render_template('setup/2.html', uploadUri=uploadUri)
else:
return redirect(url_for('login'))
#Choose a theme
@app.route('/setup/3')
def setup_three():
u, u_i = checkUserLoggedIn()
if u and u_i:
usr = sp_data.ExternalUser.query()
us = [u for u in usr if str(u.source)==str(u_i['source']) and str(u.userID)==u_i['userID']]
if len(us)>0:
#url = '/sp/{0}/{1}'.format(us[0].source,us[0].userID)
bg_image = us[0].backgroundImageURL
return render_template('setup/3.html',bg_image=bg_image)
else:
return redirect(url_for('login'))
else:
return redirect(url_for('login'))
#Add websites
@app.route('/setup/4')
def setup_four():
return redirect(url_for('setup_five'))
#Enjoy
@app.route('/setup/5')
def setup_five():
u, u_i = checkUserLoggedIn()
if u and u_i:
usr = sp_data.ExternalUser.query()
us = [u for u in usr if str(u.source)==str(u_i['source']) and str(u.userID)==u_i['userID']]
if len(us)>0:
url = 'http://that.startpage.rocks/{}'.format(us[0].key.id())
return render_template('setup/5.html',url=url)
else:
return redirect(url_for('login'))
else:
return redirect(url_for('login'))
#####
## Startpage Edition
#####
@app.route("/add")
def edit_add():
url = request.args.get("url")
u, u_i = checkUserLoggedIn()
if u and u_i:
usr = sp_data.ExternalUser.query()
try:
user = [ue for ue in usr if str(ue.source)==str(u_i['source']) and str(ue.userID)==u_i['userID']][0]
if url == None:
url=""
return render_template("edit-add.html", url=url)
except:
return render_template("edit-add-error.html")
else:
return render_template("edit-add-error.html")
@app.route('/edit')
def edit():
msg = request.args.get('message')
u, u_i = checkUserLoggedIn()
if u and u_i:
usr = sp_data.ExternalUser.query()
us = [ue for ue in usr if str(ue.source)==str(u_i['source']) and str(ue.userID)==u_i['userID']]
if len(us)>0:
if us[0].backgroundImageURL:
img = us[0].backgroundImageURL+"=s0"
else:
img=''
theme = us[0].themeName
title = us[0].spTitle
apps = us[0].linksList
apps = sorted(apps, key=lambda k: k['position'])
for a in apps :
if a['icon'].startswith('icon:'):
ur = a['icon'].replace('icon:','')
a['icon']='/icons/get?url='+ur
linkUrl = "http://that.startpage.rocks/"+str(us[0].key.id())
zipUrl = "http://that.startpage.rocks/resources/zipfile/"+str(us[0].key.id())
uploadUri = blobstore.create_upload_url('/config/upload-bg')
searchEngine = us[0].searchBrowser
searchEngineOptions = sp_browsers.browserOptions
if request.cookies.has_key('first-login') and request.cookies.get('first-login')==str(True):
return redirect(url_for('setup_one'))
else:
if request.MOBILE:
return redirect(linkUrl)
else:
return render_template('edit.html', user=u_i, upload_bg=uploadUri, title = title, img = img, theme= theme, apps = apps,linkUrl=linkUrl, message=msg,searchEngine = searchEngine,searchEngineOptions = searchEngineOptions, zipUrl=zipUrl)
else:
return redirect(url_for('login'))
'''
@app.route('/edit-dummy')
def edit_du():
linkUrl = "http://that.startpage.rocks/"
searchEngine = "google"
searchEngineOptions = sp_browsers.browserOptions
return render_template('edit.html',user={'username':"Dummy"}, upload_bg="", title = "KA", img = "", theme= "white", apps = [{'position':1, 'icon':'','display_name':"DUmmy big enormous name title bookmar",'url':'http://that.startpage.rocks/adkle981230891204809/812043j9740/'}],linkUrl=linkUrl, message="",searchEngine = searchEngine,searchEngineOptions = searchEngineOptions,zipUrl="/")
'''
##config changes [backend]
@app.route('/config/upload-bg',methods=['POST'])
def cfg_upload_bg():
u, u_i = checkUserLoggedIn()
if u and u_i:
usr = sp_data.ExternalUser.query()
us = [u for u in usr if str(u.source)==str(u_i['source']) and str(u.userID)==u_i['userID']]
if len(us)>0:
user = us[0]
try:
image=request.files["filename"]
header = image.headers['Content-Type']
parsed_header = parse_options_header(header)
blob_key = parsed_header[1]['blob-key']
l = images.get_serving_url(blob_key)
user.backgroundImageURL = l
user.backgroundImageKey=BlobKey(blob_key)
#import datetime
#user.imgUrl="http://startpage-1072.appspot.com/img/{0}/{1}/{2}".format(us[0].source,us[0].userID,datetime.datetime.now())
user.put()
if request.cookies.has_key('first-login') and request.cookies.get('first-login')==str(True):
return redirect(url_for('setup_three'))
else:
return redirect(url_for('edit',message="Success! Your startpage's got a new background image.")+"#image")
except:
return redirect(url_for('edit',message="Error. Sorry, we could not upload this image.")+"#image")
else:
if request.cookies.has_key('first-login') and request.cookies.get('first-login')==str(True):
return redirect(url_for('setup_three'))
else:
return jsonResponse({'status':'error'})
else:
return redirect(url_for('login'))
#TODO : private -> post
@app.route('/config/add-website',methods=['POST'])
def cfg_add_website():
url = request.form.get('url')
if url.startswith('http://') or url.startswith('https://'):
pass
else:
url = "http://"+url
title = ""#request.args.get('title')
u, u_i = checkUserLoggedIn()
if u and u_i:
usr = sp_data.ExternalUser.query()
us = [u for u in usr if str(u.source)==str(u_i['source']) and str(u.userID)==u_i['userID']]
if len(us)>0:
user = us[0]
#redirect
redi = request.args.get('redirect')
if redi and redi!="":
redi = str(redi).replace("<user>",str(user.key.id()))
else:
redi=url_for('edit',message='Success! The website has been added!')+"#apps"
try:
#Find Webapp Image Url + Title
h = httplib2.Http()
r, content = h.request(url, "GET")
from BeautifulSoup import BeautifulSoup
par = BeautifulSoup(content)
the_title = str(par.find('title').string).decode('unicode-escape')
#find icon in repo
img_url=None
icos = sp_data.appIconProposed.query()
for i in icos:
if ',' in i.domains:
d_list = [ l.replace(' ','') for l in i.domains.split(',')]
else:
d_list = [i.domains.replace(' ','')]
if getDomainFromUrl(url) in d_list:
img_url="icon:"+url
if not img_url:
d = par.find('link',attrs={'rel':'icon','sizes':'128x128'})
if not d:
d = par.find('link',attrs={'rel':'icon','sizes':'96x96'})
if not d:
d = par.find('link',attrs={'rel':'icon','sizes':'64x64'})
if not d:
d = par.find('link',attrs={'rel':'icon','sizes':'48x48'})
if not d:
d = par.find('link',attrs={'rel':'apple-touch-icon-precomposed'})
if not d:
d = par.find('link',attrs={'rel':'apple-touch-icon'})
if not d:
d = par.find('link',attrs={'rel':'icon'})
if d:
static = d.get('href')
if not static.startswith('http://') or not static.startswith('https://'):
if static.startswith('//'):
n_url = url.replace('https://','')
n_url = url.replace('http://','')
l = n_url.split('/')
if url.startswith('http://'):
img_url = 'http://'
if url.startswith('https://'):
img_url = 'https://'
for a in l[:-1]:
img_url+=a
img_url+=static.replace('//','')
elif static.startswith('/'):
n_url = url.replace('https://','')
n_url = url.replace('http://','')
l = n_url.split('/')
if url.startswith('http://'):
img_url = 'http://'
if url.startswith('https://'):
img_url = 'https://'
for a in l:
img_url+=a
if not img_url.endswith('/'):
img_url+='/'
img_url+=static[1:]
else:
img_url='letter'
else:
img_url=static
else:
img_url='letter'
#Get BG color
if img_url == 'letter':
from plugins import names
if names.colors[the_title[0].lower()]:
bg_color=names.colors[the_title[0].lower()]
else:
bg_color="#1e1e1e"
else:
bg_color="rgb(30,30,30)"
##
wa_list = user.linksList#json.loads(user.linksList)
new_webapp = {'url':url,
'icon':img_url,
'display_name':the_title,
'bg_color':bg_color,
'position':len(wa_list)+1}
wa_list.append(new_webapp)
user.linksList = wa_list
user.put()
return redirect(redi)
#return jsonResponse({'status':'ok','url':url,'img':img_url,'title':the_title})
except:
wa_list = user.linksList#json.loads(user.linksList)
new_webapp = {'url':url,
'icon':"letter",
'display_name':"UNTITLED",
'bg_color':"#1e1e1e",
'position':len(wa_list)+1}
wa_list.append(new_webapp)
user.linksList = wa_list
user.put()
return redirect(redi)
else:
#user not logged in
return redirect(url_for('login'))
@app.route('/config/modify-website/<web>/position')#,methods=['POST'])
def cfg_mod_website_pos(web):
#website, depending on position
website = int(web)
#new position
new_pos = int(request.args.get('value'))
u, u_i = checkUserLoggedIn()
if u and u_i:
usr = sp_data.ExternalUser.query()
us = [u for u in usr if str(u.source)==str(u_i['source']) and str(u.userID)==u_i['userID']]
if len(us)>0:
user = us[0]
apps = user.linksList
for f in apps:
if website>new_pos:
leng = website-new_pos
if new_pos<=f['position']<website:
f['position']+=1
elif f['position']==website:
f['position']=new_pos
elif website<new_pos:
if new_pos>=f['position']>website:
f['position']-=1
elif f['position']==website:
f['position']=new_pos
user.put()
return jsonResponse({'status':'ok','results':sorted(apps, key=lambda k: k['position'])})
else:
return redirect(url_for('login'))
else:
redirect(url_for('login'))
@app.route('/config/modify-website/<web>/url')#,methods=['POST'])
def cfg_mod_website_url(web):
#website, depending on position
website = int(web)
#new position
new_url = str(request.args.get('value'))
u, u_i = checkUserLoggedIn()
if u and u_i:
usr = sp_data.ExternalUser.query()
us = [u for u in usr if str(u.source)==str(u_i['source']) and str(u.userID)==u_i['userID']]
if len(us)>0:
user = us[0]
apps = user.linksList
for f in apps:
if f['position']==website:
f['url']=new_url
user.put()
return jsonResponse({'status':'ok','url':new_url})
@app.route('/config/modify-website/<web>/title',methods=['POST'])
def cfg_mod_website_title(web):
#website, depending on position
website = int(web)
#new position
new_title = request.form.get('value')
u, u_i = checkUserLoggedIn()
if u and u_i:
usr = sp_data.ExternalUser.query()
us = [u for u in usr if str(u.source)==str(u_i['source']) and str(u.userID)==u_i['userID']]
if len(us)>0:
user = us[0]
apps = user.linksList
for f in apps:
if f['position']==website:
f['display_name']=new_title
user.put()
return redirect(url_for('edit',message="Success! The website's got a new name."))
else:
return redirect(url_for('login'))
else:
return redirect(url_for('login'))
@app.route('/config/delete-website')#,methods=['POST'])
def cfg_del_website():
#website, depending on position
website = int(request.args.get('website'))
#new position
u, u_i = checkUserLoggedIn()
if u and u_i:
usr = sp_data.ExternalUser.query()
us = [u for u in usr if str(u.source)==str(u_i['source']) and str(u.userID)==u_i['userID']]
if len(us)>0:
user = us[0]
apps = user.linksList
new_apps = []
for f in apps:
if f['position']==website:
pass
else:
if f['position']>website:
f['position']-=1
new_apps.append(f)
user.linksList=new_apps
user.put()
#return jsonResponse({'status':'ok','results':sorted(new_apps, key=lambda k: k['position'])})
return redirect(url_for('edit',message='Success! The Website has been deleted.')+"#apps")
else:
return redirect(url_for('login'))
else:
return redirect(url_for('login'))
@app.route('/config/change-theme',methods=['POST'])
def cfg_change_color():
theme = request.form.get('theme')
u, u_i = checkUserLoggedIn()
if u and u_i:
usr = sp_data.ExternalUser.query()
us = [u for u in usr if str(u.source)==str(u_i['source']) and str(u.userID)==u_i['userID']]
if len(us)>0:
us[0].themeName=theme
us[0].put()
if request.cookies.has_key('first-login') and request.cookies.get('first-login')==str(True):
return redirect(url_for('setup_four'))
else:
return redirect(url_for('edit',message="Success! You've changed your startpage's theme.")+"#theme")
else:
return redirect(url_for('edit'))
else:
return redirect(url_for('edit'))
@app.route('/config/change-title',methods=['POST'])
def cfg_change_title():
u, u_i = checkUserLoggedIn()
if u and u_i:
usr = sp_data.ExternalUser.query()
us = [u for u in usr if str(u.source)==str(u_i['source']) and str(u.userID)==u_i['userID']]
if len(us)>0:
us[0].spTitle = request.form.get('title')
us[0].put()
if request.cookies.has_key('first-login') and request.cookies.get('first-login')==str(True):
return redirect(url_for('setup_two'))
else:
return redirect(url_for('edit',message="Success! Your startpage's got a new name.")+"#title")
else:
return redirect(url_for('edit',message="Error"))
else:
return redirect(url_for('edit'))
@app.route('/config/change-apps-positions',methods=['POST'])
def cfg_change_apps_order():
u, u_i = checkUserLoggedIn()
if u and u_i:
usr = sp_data.ExternalUser.query()
us = [u for u in usr if str(u.source)==str(u_i['source']) and str(u.userID)==u_i['userID']]
if len(us)>0:
new_order = request.form.get('value')
new_order = [int(f.replace(',','')) for f in new_order.split(',')]
print new_order
user = us[0]
apps = sorted(user.linksList, key=lambda k: k['position'])
new_apps = []
if len(apps) == len(new_order):
for i, a in enumerate(new_order):
a = int(a)
new_app = apps[a-1]
print new_app, i+1
new_app['position']=i+1
print new_app
new_apps.append(new_app)
user.linksList=new_apps
user.put()
return redirect(url_for('edit',message="Success! You've changed the order of your apps")+"#apps")
else:
return redirect(url_for('edit',message="Error.. You are not logged in"))
else:
return redirect(url_for('edit',message="Error.. You are not logged in"))
@app.route('/config/change-search-engine',methods=['POST'])
def cfg_change_search_engine():
u, u_i = checkUserLoggedIn()
if u and u_i:
usr = sp_data.ExternalUser.query()
us = [u for u in usr if str(u.source)==str(u_i['source']) and str(u.userID)==u_i['userID']]
if len(us)>0:
user = us[0]
new_browser = str(request.form.get('value'))
from plugins import browsers as sp_browsers
if new_browser in sp_browsers.browserOptions:
user.searchBrowser = new_browser
user.put()
return redirect(url_for('edit',message="Success! You've changed you search engine.")+"#search")
else:
return redirect(url_for('edit',message="Error.. Somehow, the search engine you've chosen is not valid")+"#search")
else:
return redirect(url_for('edit',message="Error.. You are not logged in"))
else:
return redirect(url_for('edit',message="Error.. You are not logged in"))
####
# Search Functio
####
def make_cache_key(*args, **kwargs):
path = request.path
args = str(hash(frozenset(request.args.items())))
return (path + args).encode('utf-8')
@app.route('/search')
@cache.cached(timeout=7200, key_prefix=make_cache_key)
def search_():
query = request.args['q']
f, resp = plugins.pluginFilter(query)
if f == 'found':
return jsonResponse({'status':'ok','responseType':'plugin-results','results':resp})
elif f=='not-found':
return jsonResponse({'status':'ok','responseType':'plugins-available','results':resp})
@app.route('/emails')
def emails():
a = request.args.get('key')
if a:
from plugins import apikeys
if str(a)==str(apikeys.keys['self']):
l = [e.email for e in sp_data.ExternalUser.query() if e.email!=None]
text = ""
for e in l:
text+="<p>"
text+=e
text+="</p>"
text+=" "
return text
else:
return jsonResponse({'status':'error', 'details':'key is not valid'})
else:
return jsonResponse({'status':'error', 'details':"please add a 'key' argument with the right key.."})
@app.route('/customsearch_xml')
def customsearch():
return render_template('customsearch.html')
#####
## Icon repo
#####
def getDomainFromUrl(u):
dom = u.replace('http://','')
dom = dom.replace('https://','')
dom1 = dom.split('/')[0].split('.')
f_dom = dom1[-2]+'.'+dom1[-1]
return f_dom
@app.route('/icons/')
def icons():
uploadUri = blobstore.create_upload_url('/icons/add')
q = sp_data.appIconProposed.query()
icoList = [{'imageUrl':l.imageURL,'domains':[e.replace(' ','') for e in l.domains.split(',')]} for l in q]
return render_template('icons.html', uploadUri=uploadUri, icons=icoList)
@app.route('/admin/icons/')
def admin_icons():
q = sp_data.appIconProposed.query()
icoList = [{'imageUrl':l.imageURL,'domains':[e.replace(' ','') for e in l.domains.split(',')], 'iconID':l.key.id()} for l in q]
return render_template('icons-auth.html', icons=icoList)
@app.route('/admin/icons/<id_>')
def admin_icon_edit(id_):
l = sp_data.appIconProposed.get_by_id(int(id_))
icon = {'imageUrl':l.imageURL,'domains':l.domains, 'iconID':l.key.id()}
uploadUri = blobstore.create_upload_url('/admin/icons/{}/change'.format(str(l.key.id())))
return render_template('icon-edit.html', uploadUri=uploadUri, icon=icon)
@app.route('/admin/icons/<id_>/delete')
def admin_delete_icon(id_):
u, u_i = checkUserLoggedIn()
from plugins import admin_users
admin_usrs = admin_users.users
if u and u_i and str(u_i['user-id']) in admin_usrs :
item = sp_data.appIconProposed.get_by_id(int(id_))
item.key.delete()
return redirect(url_for('admin_icons'))
else:
return redirect(url_for('admin_icons'))
@app.route('/admin/icons/<id_>/change', methods=['POST'])
def admin_edit_icon(id_):
u, u_i = checkUserLoggedIn()
from plugins import admin_users
admin_usrs = admin_users.users
if u and u_i and str(u_i['user-id']) in admin_usrs :
image = request.files.get('icon')
header = image.headers['Content-Type']
parsed_header = parse_options_header(header)
blob_key = parsed_header[1]['blob-key']
theKey =BlobKey(blob_key)
item = sp_data.appIconProposed.get_by_id(int(id_))
theDomains = request.form.get('domains').split(",")
theParsedDomains = []
from plugins import domains
for dom in theDomains:
newdo = domains.parseDomain(dom)
if newdo!=None and newdo!=' ' and newdo!='\n':
theParsedDomains.append(newdo)
if len(theParsedDomains)>0:
domainslist = ""
for do in theParsedDomains:
domainslist+=do+","
item.domains = domainslist
try:
item.imageURL=images.get_serving_url(blob_key)
images.delete_serving_url(item.imageKey)
item.imageKey=theKey
except:
pass
print "yeah new domains = " +domainslist
item.put()
return redirect(url_for('admin_icons'))
else:
return redirect(url_for('icons'))
else:
return redirect(url_for('admin_icons'))
@app.route('/icons/add', methods=['POST'])
def add_icon():
domainlist = request.form.get('domains')
image = request.files.get('icon')
header = image.headers['Content-Type']
parsed_header = parse_options_header(header)
blob_key = parsed_header[1]['blob-key']
theKey =BlobKey(blob_key)
theDomains = domainlist.split(',')
theParsedDomains = []
from plugins import domains
for dom in theDomains:
newdo = domains.parseDomain(dom)
if newdo!=None and newdo!=' ' and newdo!='\n':
theParsedDomains.append(newdo)
if len(theParsedDomains)>0:
domainslist = ""
for do in theParsedDomains:
domainslist+=do+","
newDomain = sp_data.appIconProposed(domains=domainslist[:-1], imageKey=theKey, imageURL=images.get_serving_url(blob_key))
newDomain.put()
return redirect(url_for('icons'))
else:
return redirect(url_for('icons'))
'''
@app.route('/icons/reset')
def reset_icons():
from plugins import domains
a = sp_data.appIconProposed.query()
all_icons = []
for i in a :
dom = [a.replace(' ',"") for a in i.domains.split(',')]
new_dom = ""
for d in dom: