Browse Source

Broke out File Upload javascript functions more. Also changed download CSP to allow self.

tags/3.0.0
Teknikode 2 years ago
parent
commit
08f9535092

+ 1
- 1
Teknik/Areas/Upload/Controllers/UploadController.cs View File

@@ -287,7 +287,7 @@ namespace Teknik.Areas.Upload.Controllers
Response.AddHeader("Content-Disposition", cd.ToString());

// Apply content security policy for downloads
Response.AddHeader("Content-Security-Policy", "default-src 'none'; script-src 'none'; style-src 'self'; img-src 'self'; font-src 'self'; connect-src 'self'; media-src 'self'; child-src 'self'; form-action 'none';");
Response.AddHeader("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'; font-src *; connect-src 'self'; media-src 'self'; child-src 'self'; form-action 'none';");

// Read in the file
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);

+ 52
- 41
Teknik/Areas/Upload/Scripts/Upload.js View File

@@ -128,8 +128,6 @@ function linkAddToVault(element) {
});
}

var fileCount = 0;

var dropZone = new Dropzone(document.body, {
url: uploadFileURL,
maxFilesize: maxUploadSize, // MB
@@ -138,49 +136,63 @@ var dropZone = new Dropzone(document.body, {
clickable: "#uploadButton",
previewTemplate: function () { },
addedfile: function (file) {
// Create the UI element for the new item
var fileID = fileCount;
fileCount++;

$("#upload-links").css('display', 'inline', 'important');
// Convert file to blob
var blob = file.slice(0, file.size);

// Create the Upload
var fileID = createUpload(file.name);

var itemDiv = $('#upload-template').clone();
itemDiv.attr('id', 'upload-panel-' + fileID);
// Process the file
processFile(blob, file.name, file.type, file.size, fileID);

// Hide Upload Details
itemDiv.find('#upload-link-panel').hide();
// Remove this file from the dropzone set
this.removeFile(file);
}
});

// Assign buttons
linkRemove(itemDiv.find('#upload-close'), fileID);
var fileCount = 0;

// Set the info
itemDiv.find('#upload-title').html(file.name);
function createUpload(fileName) {
// Create the UI element for the new item
var fileID = fileCount;
fileCount++;

// Add the upload panel to the list
$("#upload-links").prepend(itemDiv);
$("#upload-links").css('display', 'inline', 'important');

// save ID to the file object
file.ID = fileID;
var itemDiv = $('#upload-template').clone();
itemDiv.attr('id', 'upload-panel-' + fileID);

// Check the file size
if (file.size <= maxUploadSize) {
// Encrypt the file and upload it
encryptFile(file, uploadFile);
}
else
{
// An error occured
setProgress(fileID, 100, 'progress-bar-danger', '', 'File Too Large');
}
this.removeFile(file);
// Hide Upload Details
itemDiv.find('#upload-link-panel').hide();

// Assign buttons
linkRemove(itemDiv.find('#upload-close'), fileID);

// Set the info
itemDiv.find('#upload-title').html(fileName);

// Add the upload panel to the list
$("#upload-links").prepend(itemDiv);

return fileID;
}

function processFile(fileBlob, fileName, contentType, contentSize, fileID) {
// Check the file size
if (contentSize <= maxUploadSize) {
// Encrypt the file and upload it
encryptFile(fileBlob, fileName, contentType, fileID, uploadFile);
}
});
else {
// An error occured
setProgress(fileID, 100, 'progress-bar-danger', '', 'File Too Large');
}
}

// Function to encrypt a file, overide the file's data attribute with the encrypted value, and then call a callback function if supplied
function encryptFile(file, callback) {
var filetype = file.type;
var fileID = file.ID;
var fileExt = getFileExtension(file.name);
function encryptFile(blob, fileName, contentType, ID, callback) {
var fileExt = getFileExtension(fileName);

// Get session settings
var encrypt = $('#encrypt').is(':checked');
@@ -194,7 +206,7 @@ function encryptFile(file, callback) {

// Just send straight to server if they don't want to encrypt it
if (!encrypt) {
callback(e.target.result, null, null, filetype, fileExt, fileID, encrypt);
callback(e.target.result, null, null, contentType, fileExt, ID, encrypt);
}
else {
// Set variables for tracking
@@ -217,13 +229,13 @@ function encryptFile(file, callback) {
lastTime = curTime;
lastData = e.data.processed;
var percentComplete = Math.round(e.data.processed * 100 / e.data.total);
setProgress(fileID, percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Encrypting [' + getReadableFileSizeString(e.data.processed) + ' / ' + getReadableFileSizeString(e.data.total) + ' @ ' + getReadableBandwidthString(speed * 8) + ']');
setProgress(ID, percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Encrypting [' + getReadableFileSizeString(e.data.processed) + ' / ' + getReadableFileSizeString(e.data.total) + ' @ ' + getReadableBandwidthString(speed * 8) + ']');
}
break;
case 'finish':
if (callback != null) {
// Finish
callback(e.data.buffer, keyStr, ivStr, filetype, fileExt, fileID, encrypt);
callback(e.data.buffer, keyStr, ivStr, contentType, fileExt, ID, encrypt);
}
break;
}
@@ -231,8 +243,8 @@ function encryptFile(file, callback) {

worker.onerror = function (err) {
// An error occured
setProgress(fileID, 100, 'progress-bar-danger', '', 'Error Occured');
$('#upload-panel-' + fileID).find('.panel').addClass('panel-danger');
setProgress(ID, 100, 'progress-bar-danger', '', 'Error Occured');
$('#upload-panel-' + ID).find('.panel').addClass('panel-danger');
}

// Generate the script to include as a blob
@@ -256,12 +268,11 @@ function encryptFile(file, callback) {
reader.onprogress = function (data) {
if (data.lengthComputable) {
var progress = parseInt(((data.loaded / data.total) * 100), 10);
setProgress(fileID, progress, 'progress-bar-success progress-bar-striped active', progress + '%', 'Loading');
setProgress(ID, progress, 'progress-bar-success progress-bar-striped active', progress + '%', 'Loading');
}
}

// Start async read
var blob = file.slice(0, file.size);
reader.readAsArrayBuffer(blob);
}


+ 304
- 0
Teknik/Scripts/common.js View File

@@ -0,0 +1,304 @@
$(document).ready(function () {
$("#top_msg").css('display', 'none', 'important');

// Opt-in for tooltips
$('[data-toggle="tooltip"]').tooltip();

$('#loginButton').removeClass('hide');

$('#loginModal').on('shown.bs.modal', function (e) {
$("#loginStatus").css('display', 'none', 'important');
$("#loginStatus").html('');
$('#loginUsername').focus();
});

$("#loginSubmit").click(function () {
var form = $('#loginForm');
$.ajax({
type: "POST",
url: form.attr('action'),
data: form.serialize(),
headers: {'X-Requested-With': 'XMLHttpRequest'},
xhrFields: {
withCredentials: true
},
success: function (html) {
if (html.result) {
window.location = html.result;
}
else {
var errMsg = html;
if (html.error) {
errMsg = html.error;
if (html.error.message) {
errMsg = html.error.message;
}
}
$("#loginStatus").css('display', 'inline', 'important');
$("#loginStatus").html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + errMsg + '</div>');
}
}
});
return false;
});

$('#registerButton').removeClass('hide');

$('#registerModal').on('shown.bs.modal', function (e) {
$("#registerStatus").css('display', 'none', 'important');
$("#registerStatus").html('');
$('#registerUsername').focus();
});

$("#registerSubmit").click(function () {
var form = $('#registrationForm');
$.ajax({
type: "POST",
url: form.attr('action'),
data: form.serialize(),
headers: {'X-Requested-With': 'XMLHttpRequest'},
xhrFields: {
withCredentials: true
},
success: function (html) {
if (html.result) {
window.location.reload();
}
else {
var errMsg = html;
if (html.error) {
errMsg = html.error;
if (html.error.message) {
errMsg = html.error.message;
}
}
$("#registerStatus").css('display', 'inline', 'important');
$("#registerStatus").html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + errMsg + '</div>');
}
}
});
return false;
});
});

$(function () {
// Setup drop down menu
$('.dropdown-toggle').dropdown();

$(".alert").alert();

$("#blocker").hide();

// Fix input element click problem
$('.dropdown input, .dropdown label').click(function (e) {
e.stopPropagation();
});

// for bootstrap 3 use 'shown.bs.tab', for bootstrap 2 use 'shown' in the next line
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
// save the latest tab; use cookies if you like 'em better:
localStorage.setItem('lastTab', $(this).attr('href'));
});

// go to the latest tab, if it exists:
var lastTab = localStorage.getItem('lastTab');
if (lastTab) {
$('[href="' + lastTab + '"]').tab('show');
}

// Auo-select bitcoin address
$('#bitcoin_address_footer').on('click', 'input[type=text]', function () { this.select(); });

// Setup anti-forgery functions
$.appendAntiForgeryToken = function (data, token) {
// Converts data if not already a string.
if (data && typeof data !== "string") {
data = $.param(data);
}

// Gets token from current window by default.
token = token ? token : $.getAntiForgeryToken(); // $.getAntiForgeryToken(window).

data = data ? data + "&" : "";
// If token exists, appends {token.name}={token.value} to data.
return token ? data + encodeURIComponent(token.name) + "=" + encodeURIComponent(token.value) : data;
};

$.getAntiForgeryToken = function (tokenWindow, appPath) {
// HtmlHelper.AntiForgeryToken() must be invoked to print the token.
tokenWindow = tokenWindow && typeof tokenWindow === typeof window ? tokenWindow : window;

appPath = appPath && typeof appPath === "string" ? "_" + appPath.toString() : "";
// The name attribute is either __RequestVerificationToken,
// or __RequestVerificationToken_{appPath}.
var tokenName = "__RequestVerificationToken" + appPath;

// Finds the <input type="hidden" name={tokenName} value="..." /> from the specified window.
// var inputElements = tokenWindow.$("input[type='hidden'][name=' + tokenName + "']");
var inputElements = tokenWindow.document.getElementsByTagName("input");
for (var i = 0; i < inputElements.length; i++) {
var inputElement = inputElements[i];
if (inputElement.type === "hidden" && inputElement.name === tokenName) {
return {
name: tokenName,
value: inputElement.value
};
}
}
};
});

function removeAmp(code) {
code = code.replace(/&amp;/g, '&');
return code;
}

String.prototype.hashCode = function () {
var hash = 0, i, chr, len;
if (this.length == 0) return hash;
for (i = 0, len = this.length; i < len; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};

function randomString(length, chars) {
var mask = '';
if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (chars.indexOf('#') > -1) mask += '0123456789';
if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
var result = '';
for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
return result;
}

function getFileExtension(fileName) {
var index = fileName.lastIndexOf('.');
if (index >= 0 && fileName.length > 0) {
return '.' + fileName.substr(index + 1);
}
return '';
}

function SelectAll(id) {
document.getElementById(id).focus();
document.getElementById(id).select();
}

function getAnchor() {
var currentUrl = document.URL,
urlParts = currentUrl.split('#');

return (urlParts.length > 1) ? urlParts[1] : null;
}

function GenerateBlobURL(url) {
var cachedBlob = null;
jQuery.ajax({
url: url,
success: function (result) {
var workerJSBlob = new Blob([result], {
type: "text/javascript"
});
cachedBlob = window.URL.createObjectURL(workerJSBlob);
},
async: false
});
return cachedBlob;
}

AddAntiForgeryToken = function (data) {
data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
return data;
};

function copyTextToClipboard(text) {
var copyFrom = document.createElement("textarea");
copyFrom.textContent = text;
var body = document.getElementsByTagName('body')[0];
body.appendChild(copyFrom);
copyFrom.select();
document.execCommand('copy');
body.removeChild(copyFrom);
}

function getReadableBandwidthString(bandwidth) {

var i = -1;
var byteUnits = [' Kbps', ' Mbps', ' Gbps', ' Tbps', 'Pbps', 'Ebps', 'Zbps', 'Ybps'];
do {
bandwidth = bandwidth / 1024;
i++;
} while (bandwidth > 1024);

return Math.max(bandwidth, 0.1).toFixed(1) + byteUnits[i];
}

function getReadableFileSizeString(fileSizeInBytes) {

var i = -1;
var byteUnits = [' KB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
do {
fileSizeInBytes = fileSizeInBytes / 1024;
i++;
} while (fileSizeInBytes > 1024);

return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
};

function moveUp(item) {
var prev = item.prev();
if (prev.length == 0)
return;
prev.css('z-index', 999).css('position', 'relative').animate({ top: item.height() }, 250);
item.css('z-index', 1000).css('position', 'relative').animate({ top: '-' + prev.height() }, 300, function () {
prev.css('z-index', '').css('top', '').css('position', '');
item.css('z-index', '').css('top', '').css('position', '');
item.insertBefore(prev);
});
}

function moveDown(item) {
var next = item.next();
if (next.length == 0)
return;
next.css('z-index', 999).css('position', 'relative').animate({ top: '-' + item.height() }, 250);
item.css('z-index', 1000).css('position', 'relative').animate({ top: next.height() }, 300, function () {
next.css('z-index', '').css('top', '').css('position', '');
item.css('z-index', '').css('top', '').css('position', '');
item.insertAfter(next);
});
}

function addParamsToUrl(origUrl, params) {
var paramStr = $.param(params);
var hasQuery = origUrl.indexOf("?") + 1;
var hasHash = origUrl.indexOf("#") + 1;
var appendix = (hasQuery ? "&" : "?") + paramStr;
return hasHash ? origUrl.replace("#", appendix + "#") : origUrl + appendix;
}
/***************************** TIMER Page Load *******************************/
var loopTime;
var startTime = new Date();
var pageGenerationTime = "0.0";

function pageloadTimerCount() {
loopTime = setTimeout("pageloadTimerCount()", 100);
}

function pageloadDoTimer() {
pageloadTimerCount();
}

function pageloadStopTimer() {
var timeMs = Math.floor((new Date() - startTime));

$('#loadtime').html(timeMs);
$('#generatetime').html(pageGenerationTime);
$('#pagetime').show();

clearTimeout(loopTime);
}

+ 7
- 0
Teknik/Web.config View File

@@ -30,6 +30,13 @@
<httpRuntime targetFramework="4.6.2" />
</system.Web>
-->
<system.net>
<settings>
<httpListener>
<timeouts minSendBytesPerSecond="4294967295" />
</httpListener>
</settings>
</system.net>
<system.web>
<machineKey configSource="App_Data\MachineKey.config" />
<!-- Create MachineKey.config and add your machine keys-->

Loading…
Cancel
Save