-
Notifications
You must be signed in to change notification settings - Fork 7
/
admin.py
executable file
·231 lines (198 loc) · 7.19 KB
/
admin.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Planeteria admin interface
Copyright 2011 James Vasile <[email protected]>
Released under AGPL, version 3 or later <http://www.fsf.org/licensing/licenses/agpl-3.0.html>
Version 0.2
"""
__authors__ = [ "James Vasile <[email protected]>"]
__license__ = "AGPLv3"
import simplejson as json
from util import merge_dict
import os, sys
sys.path.insert(0,"..")
#os.chdir('..')
from config import *
log = logging.getLogger('planeteria')
if __name__ == "__main__":
try:
opt['planet_dir'] = os.sep.join(os.environ['SCRIPT_FILENAME'].split(os.sep)[:-1])
except KeyError:
try:
opt['planet_dir'] = os.sep.join((os.getcwd() + os.environ['SCRIPT_NAME']).split(os.sep)[:-1])
except:
opt['planet_dir'] = os.getcwd()
global debug
debug = True
opt['planet_subdir'] = opt['planet_dir'].split(os.sep)[-1]
output_dir = opt['planet_dir']
#######################
##
## Utility Functions
##
########################
error=''
def err(msg):
"""Add msg to the error string, which can be displayed via template."""
global error
error = error + "<p>%s</p>\n" % msg
log.debug(msg)
#########################
##
## TEMPLATE FUNCTIONS
##
##########################
def render_text_input (id, label, default="", size = 25):
"Return html for a text input field"
default = default.encode('utf-8', 'ignore')
return ('<label for="%s">%s:</label>' % (id, label)
+ '<input type="text" size="%d" name="%s" id="%s" value="%s">' % (size, id, id, default)
+ "\n")
def render_pass_input (id, label, default="", size = 25):
"Return html for a password input field"
return ('<label for="%s">%s:</label>' % (id, label)
+ '<input type="password" size="%d" name="%s" id="%s" value="%s">' % (size, id, id, default)
+ "\n")
def render_push_feed(planet):
"Return javascript for pushing feeds into array"
ret = ''
for url, feed in planet.feeds.items():
ret = (ret + " new_feed('%s', '%s', %s, '%s', '%s', '%s', '%s');\n"
% (url, url, json.dumps(feed['name']), '', feed['image'], '', ''))
return ret
def template_vars(planet, config):
"Returns a dict with the template vars in it"
doc = opt.copy()
global error
doc['admin']=1
doc['error'] = error
doc['name'] = planet.name
doc['title'] = planet.name
doc = dict(doc.items() + planet.__dict__.items() + [(c, config[c]) for c in config])
if doc['password'] == 'passme':
doc['passme'] = 1
doc['planet_name_input'] = render_text_input("PlanetName", "Planet name", doc['name'], 40)
doc['owner_name_input'] = render_text_input("OwnerName", "Your name", doc['user'], 40)
doc['owner_email_input']=render_text_input("OwnerEmail", "Your email", doc['email'], 40)
doc['change_pass_input'] = render_text_input("ChangePass", "New Password", Form.getvalue('ChangePass',''))
doc['pass_input'] = render_pass_input("Pass", "Password", Form.getvalue('Pass', ''))
doc['push_feeds'] = render_push_feed(planet)
doc['timestamp'] = planet.last_config_change
doc['Feeds']=[]
count = 0
for url, feed in planet.feeds.items():
f={}
f['idx'] = count
f['row_class'] = "face%d" % (count % 2)
f['image'] = feed['image']
if not f['image'] and 'faceurl' in feed:
f['image'] = feed['faceurl']
log.debug("Pulled url from feed['faceurl'].")
f['feedurl'] = url
f['facewidth'] = ''
f['faceheight'] = ''
f['section'] = url
f['name'] = feed['name']
doc['Feeds'].append(f)
count += 1;
from operator import itemgetter, attrgetter
doc['Feeds'] = sorted(doc['Feeds'], key=itemgetter('name'))
return doc
############################
##
## Config.ini Stuff
##
############################
# Helper function to prevent duplicate key values for new feeds.
def good_field(x):
"""Forms sometimes have duplicate fields; when they do, it turns into an array.
Error cases always had a blank string and a real string.
This function returns the real string. """
if isinstance(x,str):
return x
else:
for value in x:
if len(value) > 1:
return value
# Main function for config.ini
def update_config(planet):
"""Grab new values from the form and stick them in config.
Modifies config in place. Does not save to file."""
for k,v in {'PlanetName':'name', 'OwnerName':'user', 'OwnerEmail':'email',
'Pass':'password', 'Sidebar':'sidebar'}.items():
planet.__dict__[v] = Form.getvalue(k,'')
if Form.getvalue('ChangePass','') != '':
planet.password = Form.getvalue('ChangePass','')
feed_count = 0;
form_field = ['feedurl', 'name', 'image'] #, 'facewidth', 'faceheight']
urls_seen = []
while (Form.has_key('section%d' % feed_count)):
url = good_field(Form.getvalue('feedurl%d' % feed_count,'')).strip()
urls_seen.append(url)
if not url:
err("Ignoring feed with no url specified.")
feed_count += 1;
continue
if good_field(Form.getvalue('delete%d' % feed_count)) == '1':
del planet.feeds[url]
else:
if not url in planet.feeds:
planet.add_feed(url,
good_field(Form.getvalue('name%d' % feed_count, '').strip()),
Form.getvalue('image%d' % feed_count, '').strip())
else:
# Copy the values from the form into planet
for field in form_field:
planet.feeds[url][field] = good_field(Form.getvalue('%s%d' % (field, feed_count),'')).strip()
log.debug(str(type(good_field(Form.getvalue('%s%d' % (field, feed_count),'')))))
feed_count += 1;
# handle edited url
to_delete=[]
for url in planet.feeds:
if not url in urls_seen:
to_delete.append(url)
for url in to_delete:
del planet.feeds[url]
log.debug("%s has changed. Deleting old feed record." % url)
return planet
############################
##
## Setup and Prep
##
############################
import shutil, planet
## Setup and globals
VERSION = "0.2";
Form=''
def main():
import cgi
import cgitb
cgitb.enable()
# opt['planet_subdir'] = 'wfs'
global Form
Form = cgi.FieldStorage()
from planet import Planet
planet = Planet(direc=opt['planet_subdir'])
## Handle form input
if Form.has_key('PlanetName'):
orig_pass = planet.password
planet = update_config(planet)
if Form.getvalue('Timestamp') != str(planet.last_config_change):
err("Admin page has expired! Perhaps somebody else is " +
"editing this planet at the same time as you? Please " +
"reload this page and try again.")
#if debug: err("%s != %s" % (Form.getvalue('Timestamp'), planet.last_config_change))
elif Form.getvalue('Pass','') == '':
err("Please enter your password at the bottom of the page.")
elif Form.getvalue('Pass') != orig_pass:
err("Invalid password")
else:
planet.save(update_config_timestamp=True)
## Template
from templates import Admin
print "Content-type: text/html\n\n"
a = Admin(template_vars(planet, Form)).render()
sys.stdout.write(a)
if __name__ == "__main__":
main()