Skip to content

Instantly share code, notes, and snippets.

@cbiggins
Last active December 14, 2015 16:19
Show Gist options
  • Save cbiggins/5113812 to your computer and use it in GitHub Desktop.
Save cbiggins/5113812 to your computer and use it in GitHub Desktop.
broken plupload
<% content_for :plupload do %>
<%= javascript_include_tag 'jquery-ui', 'plupload/plupload.full.min', 'jquery.progressbar.min', 'json2' -%>
<%
@config = @config || CastasugarConfig.first
app_name = @config['application_name'].parameterize
@aws_config = YAML::load(File.open("#{RAILS_ROOT}/config/aws.yml"))
access_key_id = @aws_config['aws_key']
secret_access_key = @aws_config['aws_secret']
acl = "public-read"
expired_date ||= 10.hours.from_now.utc.iso8601
s3_bucket = @aws_config['aws_bucket']
policy_json = '{"expiration": "' + expired_date + '",
"conditions": [
{"bucket": "' + s3_bucket + '"},
{"acl": "' + acl + '"},
{"success_action_status": "201"},
["content-length-range", 0, ' + @size_limit_b.to_s + '],
["starts-with", "$key", ""],
["starts-with", "$Content-Type", ""],
["starts-with", "$name", ""],
["starts-with", "$Filename", ""],
]
}'
policy = Base64.encode64(policy_json).gsub(/\n|\r/, '')
s3_path = app_name + '/media/user-' + @user.id.to_s + '/video/'
%>
<script type="text/javascript">
var video_too_large_message = '<%=@video_too_large_message%>'
$(document).ready(function(){
uploader = new plupload.Uploader({
runtimes: 'html5,flash,silverlight,html4',
container: 'files-container',
browse_button: 'pickfiles',
max_file_size: '<%= @size_limit_mb %>',
flash_swf_url: '/javascripts/plupload/Moxie.swf',
silverlight_xap_url: '/javascripts/plupload/Moxie.xap',
url: 'http://<%=@aws_config["aws_bucket"]%>.s3-ap-southeast-2.amazonaws.com',
multipart: true,
multipart_params:{
'key': '<%= s3_path %>${filename}',
'Filename': '${filename}',
'acl': '<%=acl%>',
'Content-Type': 'binary/octet-stream',
'AWSAccessKeyId' : '<%=access_key_id%>',
'success_action_status': '201',
'policy': '<%= policy %>',
'signature': '<%= Base64.encode64(
OpenSSL::HMAC.digest(
OpenSSL::Digest::Digest.new("sha1"),
secret_access_key, policy
)
).gsub("\n","") %>'
},
file_data_name: 'file',
filters: [
{title: "Video clips", extensions: "mov,mpg,avi,m4v,ogv,mp4,wmv"}
]
});
$('#uploadfiles').click(function(e) {
uploader.start();
e.preventDefault();
});
uploader.init();
uploader.bind('FilesAdded', function(up, files) {
// Disable the next button until the files have been uploaded
$('#next').removeAttr('href');
// Remove any existing errors.
$('#content').find('.error').remove();
$('#content').find('.notice').remove();
max = <%= @config.video_upload_limit %>;
// Combine the newly added files with the already loaded files to get a total count of files
total_files = up.files.length + $('.files_item').length;
up.refresh()
if (total_files > max) {
display_error('You are allowed to add only ' + max + ' files.')
up.splice();
// Re-enable our button.
$('#next').attr('href', '/terms/edit');
}
else {
for (var i in files) {
file_name = files[i].name + ' (' + plupload.formatSize(files[i].size) + ')'
$('#filelist').append(' \
<div class="files_item" id="' + files[i].id + '"> \
<span class="file_name"><span class="remove_file">[X]</span> ' + file_name + '</span> \
<span class="error"></span> \
<span class="files_progress"></span> \
</div> \
');
$('.remove_file').bind('click', function(e) {
removeFile(e.target, uploader);
});
initProgressBar(files[i].id);
}
}
});
uploader.bind('Error', function(uploader, error) {
// Remove any existing errors.
delete_error();
if (typeof error.file != 'undefined') {
if (error.code == plupload.FILE_SIZE_ERROR && video_too_large_message.length) {
message = video_too_large_message;
}
else {
message = pluploadError(error);
}
if ($('#'+error.file.id).length) {
$('#'+error.file.id).find('.files_progress').remove();
}
display_error(message);
}
});
uploader.bind('UploadProgress', function(up, file) {
$('#' + file.id).find('.files_progress').progressBar(file.percent);
debug_file(file)
});
// Confirm that the uploads are all done and re-enable the next link.
uploader.bind('UploadComplete', function(uploader, files) {
$(files).each(function(idx, file) {
if (file.status == plupload.DONE) {
video = {
user : <%= @user.id.to_s %>,
s3_path : '<%= s3_path %>' + file.name
}
$.get('/profile_video/ajaxadd', video, function(data) {
data = JSON.parse(data)
if (data.success === false) {
display_error('Some uploads failed: ' + data.error);
}
else {
if (typeof files_uploaded == 'undefined') {
files_uploaded = [];
}
files_uploaded.push({'from' : file.id, 'to' : data.video_id})
if (files_uploaded.length > 0) {
if (!$('#content').find('.notice').length) {
$('#content').prepend('<div class="notice">Uploads complete</div>');
}
$('#next').attr('href', '/next');
}
}
});
}
else {
// Error handling.
}
})
});
});
</script>
<script type="text/javascript">
function debug_file(file) {
console.log(file)
$.each(file, function(idx, val) {
console.log(idx + ' : ' + val);
})
}
function delete_error() {
$('#content').find('.error').remove();
}
function display_error(message) {
if (!message) {
message = 'An Error Occurred.';
}
$('#content').prepend('<div class="error">' + message + '</div>');
}
$('.remove_file').bind('click', function(e) {
removeFile(e.target, uploader);
});
function removeFile(element, uploader) {
// Snip
}
<%= complete_files_js %>
</script>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment