Skip to content

Commit

Permalink
Migrate user profile backgrounds from MediaCrush
Browse files Browse the repository at this point in the history
  • Loading branch information
ddevault committed Feb 8, 2015
1 parent f701aa1 commit dd8e9df
Show file tree
Hide file tree
Showing 6 changed files with 110 additions and 56 deletions.
27 changes: 27 additions & 0 deletions KerbalStuff/blueprints/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,33 @@ def update_mod_background(mod_id):
mod.background = os.path.join(base_path, filename)
return { 'path': '/content/' + mod.background }

@api.route('/api/user/<username>/update-bg', methods=['POST'])
@with_session
@json_output
def update_user_background(username):
if current_user == None:
return { 'error': True, 'reason': 'You are not logged in.' }, 401
user = User.query.filter(User.username == username).first()
if not current_user.admin and current_user.username != user.username:
return { 'error': True, 'reason': 'You are not authorized to edit this user\'s background' }, 403
f = request.files['image']
filetype = os.path.splitext(os.path.basename(f.filename))[1]
if not filetype in ['.png', '.jpg']:
return { 'error': True, 'reason': 'This file type is not acceptable.' }, 400
filename = secure_filename(user.username) + filetype
base_path = os.path.join(secure_filename(user.username) + '-' + str(time.time()) + '_' + str(user.id))
full_path = os.path.join(_cfg('storage'), base_path)
if not os.path.exists(full_path):
os.makedirs(full_path)
path = os.path.join(full_path, filename)
try:
os.remove(os.path.join(_cfg('storage'), user.backgroundMedia))
except:
pass # who cares
f.save(path)
user.backgroundMedia = os.path.join(base_path, filename)
return { 'path': '/content/' + user.backgroundMedia }

@api.route('/api/mod/<mod_id>/grant', methods=['POST'])
@with_session
@json_output
Expand Down
2 changes: 1 addition & 1 deletion KerbalStuff/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class User(Base):
confirmation = Column(String(128))
passwordReset = Column(String(128))
passwordResetExpiry = Column(DateTime)
backgroundMedia = Column(String(32))
backgroundMedia = Column(String(512))
bgOffsetX = Column(Integer)
bgOffsetY = Column(Integer)
mods = relationship('Mod', order_by='Mod.created')
Expand Down
30 changes: 30 additions & 0 deletions migrate-profiles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import requests
import os
import sys
import subprocess
from werkzeug.utils import secure_filename
from KerbalStuff.objects import User
from KerbalStuff.config import _cfg
from KerbalStuff.database import db

def download_bg(url, path):
sys.stdout.write("\rDownloading {0}...".format(path))
subprocess.call(['wget', '--output-document=' + path, url])
sys.stdout.write("\n")

total = User.query.count()
for index, user in enumerate(User.query.all()):
if user.backgroundMedia:
print("Handling {} ({} of {})".format(user.username, index + 1, total))

filetype = os.path.splitext(os.path.basename(user.backgroundMedia))[1]
filename = secure_filename(user.username) + filetype
base_path = os.path.join(secure_filename(user.username) + '_' + str(user.id))
full_path = os.path.join(_cfg('storage'), base_path)
if not os.path.exists(full_path):
os.makedirs(full_path)
path = os.path.join(full_path, filename)

download_bg('https://vox.mediacru.sh/' + user.backgroundMedia, path)
user.backgroundMedia = os.path.join(base_path, filename)
db.commit()
46 changes: 22 additions & 24 deletions scripts/profile.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,27 @@ window.upload_bg = (files, box) ->
box.querySelector('a').classList.add('hidden')
progress = box.querySelector('.upload-progress')

MediaCrush.upload(file, (media) ->
progress.classList.add('fade-out')
progress.style.width = '100%'
p.textContent = 'Processing...'
media.wait(() ->
MediaCrush.get(media.hash, (media) ->
p.textContent = 'Done'
path = null
for file in media.files
if file.type == 'image/png' or file.type == 'image/jpeg'
path = file
if path == null
p.textContent = 'Please upload images only.'
else
document.getElementById('backgroundMedia').value = path.file
document.getElementById('header-well').style.backgroundImage = 'url("https://mediacru.sh/' + path.file + '")'
setTimeout(() ->
box.removeChild(p)
box.querySelector('a').classList.remove('hidden')
, 3000)
)
)
, (e) ->
xhr = new XMLHttpRequest()
xhr.open('POST', "/api/user/#{window.username}/update-bg")
xhr.upload.onprogress = (e) ->
if e.lengthComputable
progress.style.width = (e.loaded / e.total) * 100 + '%'
)
xhr.onload = (e) ->
if xhr.status != 200
p.textContent = 'Please upload JPG or PNG only.'
setTimeout(() ->
box.removeChild(p)
box.querySelector('a').classList.remove('hidden')
, 3000)
else
resp = JSON.parse(xhr.responseText)
p.textContent = 'Done!'
document.getElementById('backgroundMedia').value = resp.path
document.getElementById('header-well').style.backgroundImage = 'url("' + resp.path + '")'
setTimeout(() ->
box.removeChild(p)
box.querySelector('a').classList.remove('hidden')
, 3000)
formdata = new FormData()
formdata.append('image', file)
xhr.send(formdata)
58 changes: 27 additions & 31 deletions static/profile.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,42 @@
(function() {
window.upload_bg = function(files, box) {
var file, p, progress;
var file, formdata, p, progress, xhr;
file = files[0];
p = document.createElement('p');
p.textContent = 'Uploading...';
p.className = 'status';
box.appendChild(p);
box.querySelector('a').classList.add('hidden');
progress = box.querySelector('.upload-progress');
return MediaCrush.upload(file, function(media) {
progress.classList.add('fade-out');
progress.style.width = '100%';
p.textContent = 'Processing...';
return media.wait(function() {
return MediaCrush.get(media.hash, function(media) {
var path, _i, _len, _ref;
p.textContent = 'Done';
path = null;
_ref = media.files;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
file = _ref[_i];
if (file.type === 'image/png' || file.type === 'image/jpeg') {
path = file;
}
}
if (path === null) {
return p.textContent = 'Please upload images only.';
} else {
document.getElementById('backgroundMedia').value = path.file;
document.getElementById('header-well').style.backgroundImage = 'url("https://mediacru.sh/' + path.file + '")';
return setTimeout(function() {
box.removeChild(p);
return box.querySelector('a').classList.remove('hidden');
}, 3000);
}
});
});
}, function(e) {
xhr = new XMLHttpRequest();
xhr.open('POST', "/api/user/" + window.username + "/update-bg");
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
return progress.style.width = (e.loaded / e.total) * 100 + '%';
}
});
};
xhr.onload = function(e) {
var resp;
if (xhr.status !== 200) {
p.textContent = 'Please upload JPG or PNG only.';
return setTimeout(function() {
box.removeChild(p);
return box.querySelector('a').classList.remove('hidden');
}, 3000);
} else {
resp = JSON.parse(xhr.responseText);
p.textContent = 'Done!';
document.getElementById('backgroundMedia').value = resp.path;
document.getElementById('header-well').style.backgroundImage = 'url("' + resp.path + '")';
return setTimeout(function() {
box.removeChild(p);
return box.querySelector('a').classList.remove('hidden');
}, 3000);
}
};
formdata = new FormData();
formdata.append('image', file);
return xhr.send(formdata);
};

}).call(this);
3 changes: 3 additions & 0 deletions templates/profile.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='mod.css') }}" />
{% endblock %}
{% block scripts %}
<script>
window.username = "{{profile.username}}";
</script>
<script src="/static/profile.js"></script>
{% endblock %}
{% block title %}
Expand Down

0 comments on commit dd8e9df

Please sign in to comment.