forked from Scifabric/pybossa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.py
executable file
·294 lines (260 loc) · 12.2 KB
/
cli.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
#!/usr/bin/env python
import os
import sys
import optparse
import inspect
#import pybossa.model as model
from pybossa.core import db, create_app
from pybossa.model.app import App
from pybossa.model.user import User
from pybossa.model.category import Category
from alembic.config import Config
from alembic import command
from html2text import html2text
from sqlalchemy.sql import text
app = create_app()
def setup_alembic_config():
if "DATABASE_URL" not in os.environ:
alembic_cfg = Config("alembic.ini")
else:
dynamic_filename = "alembic-heroku.ini"
with file("alembic.ini.template") as f:
with file(dynamic_filename, "w") as conf:
for line in f.readlines():
if line.startswith("sqlalchemy.url"):
conf.write("sqlalchemy.url = %s\n" %
os.environ['DATABASE_URL'])
else:
conf.write(line)
alembic_cfg = Config(dynamic_filename)
command.stamp(alembic_cfg, "head")
def db_create():
'''Create the db'''
with app.app_context():
db.create_all()
# then, load the Alembic configuration and generate the
# version table, "stamping" it with the most recent rev:
setup_alembic_config()
# finally, add a minimum set of categories: Volunteer Thinking, Volunteer Sensing, Published and Draft
categories = []
categories.append(Category(name="Thinking",
short_name='thinking',
description='Volunteer Thinking projects'))
categories.append(Category(name="Volunteer Sensing",
short_name='sensing',
description='Volunteer Sensing projects'))
db.session.add_all(categories)
db.session.commit()
def db_rebuild():
'''Rebuild the db'''
with app.app_context():
db.drop_all()
db.create_all()
# then, load the Alembic configuration and generate the
# version table, "stamping" it with the most recent rev:
setup_alembic_config()
def fixtures():
'''Create some fixtures!'''
with app.app_context():
user = User(
name=u'tester',
email_addr=u'tester@tester.org',
api_key='tester'
)
user.set_password(u'tester')
db.session.add(user)
db.session.commit()
def markdown_db_migrate():
'''Perform a migration of the app long descriptions from HTML to
Markdown for existing database records'''
with app.app_context():
query = 'SELECT id, long_description FROM "app";'
query_result = db.engine.execute(query)
old_descriptions = query_result.fetchall()
for old_desc in old_descriptions:
if old_desc.long_description:
new_description = html2text(old_desc.long_description)
query = text('''
UPDATE app SET long_description=:long_description
WHERE id=:id''')
db.engine.execute(query, long_description = new_description, id = old_desc.id)
def bootstrap_avatars():
"""Download current links from user avatar and projects to real images hosted in the
PyBossa server."""
import requests
import os
import time
from urlparse import urlparse
from PIL import Image
def get_gravatar_url(email, size):
# import code for encoding urls and generating md5 hashes
import urllib, hashlib
# construct the url
gravatar_url = "http://www.gravatar.com/avatar/" + hashlib.md5(email.lower()).hexdigest() + "?"
gravatar_url += urllib.urlencode({'d':404, 's':str(size)})
return gravatar_url
with app.app_context():
if app.config['UPLOAD_METHOD'] == 'local':
users = User.query.order_by('id').all()
print "Downloading avatars for %s users" % len(users)
for u in users[0:10]:
print "Downloading avatar for %s ..." % u.name
container = "user_%s" % u.id
path = os.path.join(app.config.get('UPLOAD_FOLDER'), container)
try:
print get_gravatar_url(u.email_addr, 100)
r = requests.get(get_gravatar_url(u.email_addr, 100), stream=True)
if r.status_code == 200:
if not os.path.isdir(path):
os.makedirs(path)
prefix = time.time()
filename = "%s_avatar.png" % prefix
with open(os.path.join(path, filename), 'wb') as f:
for chunk in r.iter_content(1024):
f.write(chunk)
u.info['avatar'] = filename
u.info['container'] = container
db.session.commit()
print "Done!"
else:
print "No Gravatar, this user will use the placeholder."
except:
raise
print "No gravatar, this user will use the placehoder."
apps = App.query.all()
print "Downloading avatars for %s projects" % len(apps)
for a in apps[0:1]:
if a.info.get('thumbnail') and not a.info.get('container'):
print "Working on project: %s ..." % a.short_name
print "Saving avatar: %s ..." % a.info.get('thumbnail')
url = urlparse(a.info.get('thumbnail'))
if url.scheme and url.netloc:
container = "user_%s" % a.owner_id
path = os.path.join(app.config.get('UPLOAD_FOLDER'), container)
try:
r = requests.get(a.info.get('thumbnail'), stream=True)
if r.status_code == 200:
prefix = time.time()
filename = "app_%s_thumbnail_%i.png" % (a.id, prefix)
if not os.path.isdir(path):
os.makedirs(path)
with open(os.path.join(path, filename), 'wb') as f:
for chunk in r.iter_content(1024):
f.write(chunk)
a.info['thumbnail'] = filename
a.info['container'] = container
db.session.commit()
print "Done!"
except:
print "Something failed, this project will use the placehoder."
if app.config['UPLOAD_METHOD'] == 'rackspace':
import pyrax
import tempfile
pyrax.set_setting("identity_type", "rackspace")
pyrax.set_credentials(username=app.config['RACKSPACE_USERNAME'],
api_key=app.config['RACKSPACE_API_KEY'],
region=app.config['RACKSPACE_REGION'])
cf = pyrax.cloudfiles
users = User.query.all()
print "Downloading avatars for %s users" % len(users)
dirpath = tempfile.mkdtemp()
for u in users:
try:
r = requests.get(get_gravatar_url(u.email_addr, 100), stream=True)
if r.status_code == 200:
print "Downloading avatar for %s ..." % u.name
container = "user_%s" % u.id
try:
cf.get_container(container)
except pyrax.exceptions.NoSuchContainer:
cf.create_container(container)
cf.make_container_public(container)
prefix = time.time()
filename = "%s_avatar.png" % prefix
with open(os.path.join(dirpath, filename), 'wb') as f:
for chunk in r.iter_content(1024):
f.write(chunk)
chksum = pyrax.utils.get_checksum(os.path.join(dirpath,
filename))
cf.upload_file(container,
os.path.join(dirpath, filename),
obj_name=filename,
etag=chksum)
u.info['avatar'] = filename
u.info['container'] = container
db.session.commit()
print "Done!"
else:
print "No Gravatar, this user will use the placeholder."
except:
print "No gravatar, this user will use the placehoder."
apps = App.query.all()
print "Downloading avatars for %s projects" % len(apps)
for a in apps:
if a.info.get('thumbnail') and not a.info.get('container'):
print "Working on project: %s ..." % a.short_name
print "Saving avatar: %s ..." % a.info.get('thumbnail')
url = urlparse(a.info.get('thumbnail'))
if url.scheme and url.netloc:
container = "user_%s" % a.owner_id
try:
cf.get_container(container)
except pyrax.exceptions.NoSuchContainer:
cf.create_container(container)
cf.make_container_public(container)
try:
r = requests.get(a.info.get('thumbnail'), stream=True)
if r.status_code == 200:
prefix = time.time()
filename = "app_%s_thumbnail_%i.png" % (a.id, prefix)
with open(os.path.join(dirpath, filename), 'wb') as f:
for chunk in r.iter_content(1024):
f.write(chunk)
chksum = pyrax.utils.get_checksum(os.path.join(dirpath,
filename))
cf.upload_file(container,
os.path.join(dirpath, filename),
obj_name=filename,
etag=chksum)
a.info['thumbnail'] = filename
a.info['container'] = container
db.session.commit()
print "Done!"
except:
print "Something failed, this project will use the placehoder."
## ==================================================
## Misc stuff for setting up a command line interface
def _module_functions(functions):
local_functions = dict(functions)
for k,v in local_functions.items():
if not inspect.isfunction(v) or k.startswith('_'):
del local_functions[k]
return local_functions
def _main(functions_or_object):
isobject = inspect.isclass(functions_or_object)
if isobject:
_methods = _object_methods(functions_or_object)
else:
_methods = _module_functions(functions_or_object)
usage = '''%prog {action}
Actions:
'''
usage += '\n '.join(
[ '%s: %s' % (name, m.__doc__.split('\n')[0] if m.__doc__ else '') for (name,m)
in sorted(_methods.items()) ])
parser = optparse.OptionParser(usage)
# Optional: for a config file
# parser.add_option('-c', '--config', dest='config',
# help='Config file to use.')
options, args = parser.parse_args()
if not args or not args[0] in _methods:
parser.print_help()
sys.exit(1)
method = args[0]
if isobject:
getattr(functions_or_object(), method)(*args[1:])
else:
_methods[method](*args[1:])
__all__ = [ '_main' ]
if __name__ == '__main__':
_main(locals())