update upload logic

This commit is contained in:
Kieran 2018-10-23 00:48:11 +08:00
parent 958bd7d300
commit f55397e728
20 changed files with 356 additions and 150 deletions

3
.gitignore vendored
View File

@ -3,4 +3,5 @@ bin/
obj/
*.csproj.user
*.min.*
dist/
dist/
.vscode/

View File

@ -9,19 +9,21 @@
<template id="tmpl-upload">
<div class="upload">
<div class="file-info">
<div class="file-info-name"></div>
<div class="file-info-speed"></div>
<div class="file-info-size"></div>
<div class="file-info-name">...</div>
<div class="file-info-speed">0 B/s</div>
<div class="file-info-size">0 B</div>
</div>
<div class="status">
<div class="status-state"></div>
<div class="status-speed"></div>
<div class="status-key"></div>
<div class="status-state">Starting...</div>
<div class="status-key">Key: 000000000000000000000000000000:00000000000000000000000000</div>
</div>
<div class="upload-progress">
<span></span>
<span>0%</span>
<div></div>
</div>
<div class="links" style="display: none">
</div>
</div>
</template>
</head>
@ -30,13 +32,11 @@
<div class="page">
<div class="page-left">
<div id="dropzone">Click me!</div>
<div id="stats">asdf</div>
</div>
<div id="uploads" class="page-right">
</div>
<div id="stats"></div>
</div>
<div id="uploads" class="page-right"></div>
</div>
<script type="text/javascript" src="src/js/script.js" async></script>
<script type="text/javascript" src="src/js/ripemd160.js" async></script>
</body>
</html>

9
src/admin/index.html Normal file
View File

@ -0,0 +1,9 @@
<!doctype html>
<html>
<head>
<title>Admin</title>
</head>
<body>
This is the admin page
</body>
</html>

View File

@ -4,7 +4,6 @@ $page-padding: 10px;
$page-margin-top: 20px;
$dropzone-border-width: 2px;
$dropzone-height: ($page-height - ($dropzone-border-width * 2)) / 2;
$dropzone-width: ($page-width / 2) - ($dropzone-border-width * 2);
$upload-progress-padding: 2px;
$upload-progress-height: 20px;
@ -30,19 +29,15 @@ html, body {
background-color: rgb(233, 252, 255);
box-shadow: 0px 0px 15px 5px #000;
user-select: none;
display: flex;
}
.page-left{
flex-grow: 1;
display: flex;
flex-direction: column;
.page-left {
width: 50%;
float:left;
}
.page-right{
flex-grow: 1;
display: flex;
flex-direction: column;
.page-right {
width: 50%;
float:left;
}
#dropzone {
@ -57,8 +52,6 @@ html, body {
border: $upload-border;
margin: $upload-padding;
margin-top: 0;
display: flex;
flex-direction: column;
}
.upload .upload-progress {
@ -69,27 +62,20 @@ html, body {
}
.upload .status {
display: flex;
display: grid;
grid-template-columns: 40% 60%;
margin: 10px;
}
.upload .status-state {
order: 1;
flex-grow: 3;
}
.upload .status-speed {
order: 2;
flex-grow: 1;
}
.upload .status-key {
order: 3;
flex-grow: 1;
.upload .status div {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.upload .file-info {
display: flex;
display: grid;
grid-template-columns: 60% 20% 20%;
background-color: rgb(96, 136, 146);
color: #eee;
}
@ -99,19 +85,19 @@ html, body {
}
.upload .file-info .file-info-name {
order: 1;
flex-grow: 4;
}
.upload .file-info .file-info-speed {
order: 2;
flex-grow: 1;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
.upload .file-info .file-info-size {
order: 2;
flex-grow: 1;
background-color: rgb(0, 113, 133);
text-align: center;
}
.upload .file-info .file-info-speed {
background-color: rgb(0, 84, 99);
text-align: center;
}
.upload .upload-progress div {
@ -120,4 +106,17 @@ html, body {
line-height: $upload-progress-height;
font-size: $upload-progress-height * 0.8;
background-color: rgb(10, 161, 10);
}
.links {
display: grid;
}
.links a {
margin: 10px;
line-height: 40px;
border: 1px solid;
color: white;
text-align: center;
background-color: #569a59;
}

View File

@ -1,29 +0,0 @@
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
/*
(c) 2012 by C?dric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var CryptoJS=CryptoJS||function(j,k){var e={},l=e.lib={},z=function(){},t=l.Base={extend:function(a){z.prototype=this;var c=new z;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},
u=l.WordArray=t.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=k?c:4*a.length},toString:function(a){return(a||D).stringify(this)},concat:function(a){var c=this.words,h=a.words,d=this.sigBytes;a=a.sigBytes;this.clamp();if(d%4)for(var b=0;b<a;b++)c[d+b>>>2]|=(h[b>>>2]>>>24-8*(b%4)&255)<<24-8*((d+b)%4);else if(65535<h.length)for(b=0;b<a;b+=4)c[d+b>>>2]=h[b>>>2];else c.push.apply(c,h);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<<
32-8*(c%4);a.length=j.ceil(c/4)},clone:function(){var a=t.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],b=0;b<a;b+=4)c.push(4294967296*j.random()|0);return new u.init(c,a)}}),w=e.enc={},D=w.Hex={stringify:function(a){var c=a.words;a=a.sigBytes;for(var b=[],d=0;d<a;d++){var g=c[d>>>2]>>>24-8*(d%4)&255;b.push((g>>>4).toString(16));b.push((g&15).toString(16))}return b.join("")},parse:function(a){for(var c=a.length,b=[],d=0;d<c;d+=2)b[d>>>3]|=parseInt(a.substr(d,
2),16)<<24-4*(d%8);return new u.init(b,c/2)}},A=w.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var b=[],d=0;d<a;d++)b.push(String.fromCharCode(c[d>>>2]>>>24-8*(d%4)&255));return b.join("")},parse:function(a){for(var b=a.length,h=[],d=0;d<b;d++)h[d>>>2]|=(a.charCodeAt(d)&255)<<24-8*(d%4);return new u.init(h,b)}},g=w.Utf8={stringify:function(a){try{return decodeURIComponent(escape(A.stringify(a)))}catch(b){throw Error("Malformed UTF-8 data");}},parse:function(a){return A.parse(unescape(encodeURIComponent(a)))}},
v=l.BufferedBlockAlgorithm=t.extend({reset:function(){this._data=new u.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=g.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var b=this._data,h=b.words,d=b.sigBytes,g=this.blockSize,v=d/(4*g),v=a?j.ceil(v):j.max((v|0)-this._minBufferSize,0);a=v*g;d=j.min(4*a,d);if(a){for(var e=0;e<a;e+=g)this._doProcessBlock(h,e);e=h.splice(0,a);b.sigBytes-=d}return new u.init(e,d)},clone:function(){var a=t.clone.call(this);
a._data=this._data.clone();return a},_minBufferSize:0});l.Hasher=v.extend({cfg:t.extend(),init:function(a){this.cfg=this.cfg.extend(a);this.reset()},reset:function(){v.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(b,g){return(new a.init(g)).finalize(b)}},_createHmacHelper:function(a){return function(c,g){return(new b.HMAC.init(a,
g)).finalize(c)}}});var b=e.algo={};return e}(Math);
(function(){var j=CryptoJS,k=j.lib,e=k.WordArray,l=k.Hasher,k=j.algo,z=e.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),t=e.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),u=e.create([11,14,15,12,
5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),w=e.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),D=e.create([0,1518500249,1859775393,2400959708,2840853838]),A=e.create([1352829926,1548603684,1836072691,
2053994217,0]),k=k.RIPEMD160=l.extend({_doReset:function(){this._hash=e.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(g,e){for(var b=0;16>b;b++){var a=e+b,c=g[a];g[a]=(c<<8|c>>>24)&16711935|(c<<24|c>>>8)&4278255360}var a=this._hash.words,c=D.words,h=A.words,d=z.words,j=t.words,k=u.words,l=w.words,B,m,n,p,x,C,q,r,s,y;C=B=a[0];q=m=a[1];r=n=a[2];s=p=a[3];y=x=a[4];for(var f,b=0;80>b;b+=1)f=B+g[e+d[b]]|0,f=16>b?f+((m^n^p)+c[0]):32>b?f+((m&n|~m&p)+c[1]):48>b?
f+(((m|~n)^p)+c[2]):64>b?f+((m&p|n&~p)+c[3]):f+((m^(n|~p))+c[4]),f|=0,f=f<<k[b]|f>>>32-k[b],f=f+x|0,B=x,x=p,p=n<<10|n>>>22,n=m,m=f,f=C+g[e+j[b]]|0,f=16>b?f+((q^(r|~s))+h[0]):32>b?f+((q&s|r&~s)+h[1]):48>b?f+(((q|~r)^s)+h[2]):64>b?f+((q&r|~q&s)+h[3]):f+((q^r^s)+h[4]),f|=0,f=f<<l[b]|f>>>32-l[b],f=f+y|0,C=y,y=s,s=r<<10|r>>>22,r=q,q=f;f=a[1]+n+s|0;a[1]=a[2]+p+y|0;a[2]=a[3]+x+C|0;a[3]=a[4]+B+q|0;a[4]=a[0]+m+r|0;a[0]=f},_doFinalize:function(){var g=this._data,e=g.words,b=8*this._nDataBytes,a=8*g.sigBytes;
e[a>>>5]|=128<<24-a%32;e[(a+64>>>9<<4)+14]=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360;g.sigBytes=4*(e.length+1);this._process();g=this._hash;e=g.words;for(b=0;5>b;b++)a=e[b],e[b]=(a<<8|a>>>24)&16711935|(a<<24|a>>>8)&4278255360;return g},clone:function(){var e=l.clone.call(this);e._hash=this._hash.clone();return e}});j.RIPEMD160=l._createHelper(k);j.HmacRIPEMD160=l._createHmacHelper(k)})(Math);

View File

@ -153,8 +153,8 @@ const XHR = function (method, url, data, headers, progress) {
resolve(ev.target);
}
};
x.upload.onprogress = function(ev){
if(typeof progress === "function"){
x.upload.onprogress = function (ev) {
if (typeof progress === "function") {
progress(ev);
}
};
@ -164,8 +164,8 @@ const XHR = function (method, url, data, headers, progress) {
x.open(method, url, true);
//set headers if they are passed
if(typeof headers === "object"){
for(let x in headers){
if (typeof headers === "object") {
for (let x in headers) {
x.setRequestHeader(x, headers[x]);
}
}
@ -212,6 +212,9 @@ const FileUpload = function (file) {
this.key = null;
this.iv = new Uint32Array(16);
/**
* Track uplaod stats
*/
this.uploadStats = {
lastRate: 0,
lastLoaded: 0,
@ -219,19 +222,29 @@ const FileUpload = function (file) {
};
/**
*
* Get the encryption key as hex
* @returns {Promise<string>} The encryption get in hex
*/
this.HexKey = async () => {
return App.Utils.ArrayToHex(await crypto.subtle.exportKey('raw', this.key));
};
/**
*
* Get the IV as hex
* @returns {string} The IV for envryption has hex
*/
this.HexIV = () => {
return App.Utils.ArrayToHex(this.iv);
};
/**
* Returns the formatted key and iv as hex
* @returns {Promise<string>} The key:iv as hex
*/
this.TextKey = async () => {
return `${await this.HexKey()}:${this.HexIV()}`;
};
/**
* Loads the file and SHA256 hashes it
* @return {Promise<ArrayBuffer>}
@ -291,6 +304,13 @@ const FileUpload = function (file) {
this.domNode.state.textContent = `Status: ${value}`;
};
/**
* Sets the speed value on the UI
*/
this.SetSpeed = function (value) {
this.domNode.filespeed.textContent = value;
};
/**
* Handles progress messages from the upload process and updates the UI
* @param {string} type - The progress event type
@ -341,6 +361,7 @@ const FileUpload = function (file) {
}
case 'state-upload-end': {
this.SetProgressBar(1);
this.SetSpeed("Done");
break;
}
case 'progress': {
@ -368,17 +389,20 @@ const FileUpload = function (file) {
*/
this.CreateNode = function () {
let nelm = document.importNode(App.Templates.Upload.content, true);
nelm.filename = nelm.querySelector('.file-info .file-info-name');
nelm.filesize = nelm.querySelector('.file-info .file-info-size');
nelm.filespeed = nelm.querySelector('.file-info .file-info-speed');
nelm.progress = nelm.querySelector('.upload-progress span');
nelm.progressBar = nelm.querySelector('.upload-progress div');
nelm.state = nelm.querySelector('.status .status-state');
nelm.speed = nelm.querySelector('.status .status-speed');
nelm.key = nelm.querySelector('.status .status-key');
nelm.links = nelm.querySelector('.links');
nelm.filename.textContent = this.file.name;
nelm.filesize.textContent = App.Utils.FormatBytes(this.file.size, 2);
this.domNode = nelm;
$('#uploads').appendChild(nelm);
};
@ -386,12 +410,11 @@ const FileUpload = function (file) {
* Generates a new key to use for encrypting the file
* @returns {Promise<CryptoKey>} The new key
*/
this.GerneteKey = async function () {
this.GenerateKey = async function () {
this.key = await crypto.subtle.generateKey({ name: EncryptionAlgo, length: 128 }, true, ['encrypt', 'decrypt']);
crypto.getRandomValues(this.iv);
this.domNode.key.textContent = "Key: " + await this.HexKey() + ":" + this.HexIV();
this.domNode.key.textContent = `Key: ${await this.TextKey()}`;
return this.key;
};
@ -415,10 +438,10 @@ const FileUpload = function (file) {
* @param {Blob|BufferSource} fileData - The encrypted file data to upload
* @returns {Promise<object>} The json result
*/
this.UploadData = async function (fileData){
this.UploadData = async function (fileData) {
this.uploadStats.lastProgress = new Date().getTime();
this.HandleProgress('state-upload-start');
let uploadResult = await XHR("POST", "https://upload.void.cat/src/php/upload.php?filename=" + this.file.name, fileData, undefined, function(ev){
let uploadResult = await XHR("POST", "/upload", fileData, undefined, function (ev) {
let now = new Date().getTime();
let dxLoaded = ev.loaded - this.uploadStats.lastLoaded;
let dxTime = now - this.uploadStats.lastProgress;
@ -426,12 +449,24 @@ const FileUpload = function (file) {
this.uploadStats.lastLoaded = ev.loaded;
this.uploadStats.lastProgress = now;
this.domNode.speed.textContent = App.Utils.FormatBytes(dxLoaded / (dxTime / 1000.0), 2) + "/s";
this.SetSpeed(`${App.Utils.FormatBytes(dxLoaded / (dxTime / 1000.0), 2)}/s`);
this.HandleProgress('progress', ev.loaded / parseFloat(ev.total));
}.bind(this));
this.HandleProgress('state-upload-end');
return uploadResult;
return JSON.parse(uploadResult.response);
};
/**
* Creates a header object to be prepended to the file for encrypting
* @returns {any}
*/
this.CreateHeader = function() {
return {
name: this.file.name,
mime: this.file.type,
len: this.file.size
};
};
/**
@ -442,22 +477,52 @@ const FileUpload = function (file) {
Log.I(`Starting upload for ${this.file.name}`);
this.CreateNode();
await this.GerneteKey();
await this.GenerateKey();
let header = JSON.stringify(this.CreateHeader());
let hash_data = await this.HashFile();
let h256 = App.Utils.ArrayToHex(hash_data.h256);
let h160 = CryptoJS.RIPEMD160(h256);
Log.I(`${this.file.name} hash is: ${h256} (${h160})`);
Log.I(`${this.file.name} hash is: ${h256}`);
//check file params are ok
//TODO: call to api to check file info
//create blob for encryption
Log.I(`Using header: ${header}`);
let header_data = new TextEncoder().encode(header);
let encryption_payload = new Uint8Array(2 + header_data.byteLength + hash_data.data.byteLength);
let header_length_data = new Uint16Array(1);
header_length_data[0] = header_data.byteLength; //header length
encryption_payload.set(header_length_data, 0);
encryption_payload.set(new Uint8Array(header_data), 2); //the file info header
encryption_payload.set(new Uint8Array(hash_data.data), 2 + header_data.byteLength);
//encrypt with the key
Log.I(`Encrypting ${this.file.name} with key ${await this.HexKey()} and IV ${this.HexIV()}`)
let encryptedData = await this.EncryptFile(hash_data.data);
let encryptedData = await this.EncryptFile(encryption_payload);
//upload the encrypted file data
Log.I(`Uploading file ${this.file.name}`);
let uploadResult = await this.UploadData(encryptedData);
let upload_payload = new Uint8Array(1 + hash_data.h256.byteLength + encryptedData.byteLength);
upload_payload[0] = 1; //blob version
upload_payload.set(new Uint8Array(hash_data.h256), 1);
upload_payload.set(new Uint8Array(encryptedData), 1 + hash_data.h256.byteLength);
let uploadResult = await this.UploadData(upload_payload);
Log.I(`Got response for file ${this.file.name}: ${JSON.stringify(uploadResult)}`);
if (uploadResult.status === 200) {
this.domNode.state.parentNode.style.display = "none";
this.domNode.progress.parentNode.style.display = "none";
this.domNode.links.style.display = "";
let nl = document.createElement("a");
nl.target = "_blank";
nl.href = `${window.location.protocol}//${window.location.host}/#${uploadResult.pub_hash}:${await this.TextKey()}`;
nl.textContent = this.file.name;
this.domNode.links.appendChild(nl);
}
};
};
App.Init();

9
src/php/admin.php Normal file
View File

@ -0,0 +1,9 @@
<?php
class Admin implements RequestHandler {
public function HandleRequest() : void {
include(dirname(__FILE__) . "/../admin/index.html");
}
}
?>

View File

@ -1,8 +1,22 @@
<?php
class ApiResponse {
public $ok = false;
public $msg;
public $data;
}
class Api implements RequestHandler {
public function HandleRequest() {
public function __construct(){
ini_set('enable_post_data_reading', 0);
}
public function HandleRequest() : void {
$cmd = json_decode(file_get_contents("php://input"));
$rsp = new ApiResponse();
header('Content-Type: application/json');
echo json_encode($rsp);
}
public function GetStats() {

21
src/php/blobfile.php Normal file
View File

@ -0,0 +1,21 @@
<?php
class BlobFile {
public $Version;
public $Hash;
public static function LoadHeader($stream) : ?BlobFile {
$header = fread($stream, 33); //1 version byte + 32 byte hash (64 hex digits)
rewind($stream);
$header_data = unpack("C1version/H64hash256", $header);
if($header_data["version"] == 1){
$bf = new BlobFile();
$bf->Version = $header_data["version"];
$bf->Hash = $header_data["hash256"];
return $bf;
}
return null;
}
}
?>

View File

@ -1,9 +1,13 @@
<?php
class Config {
public static $Instance = NULL;
public static function LoadConfig() {
self::$Instance = json_decode(file_get_contents("settings.json"));
public static function GetConfig($config_name) {
$redis = StaticRedis::$Instance;
return $redis->hGet(REDIS_PREFIX . 'config', $config_name);
}
public static function MGetConfig($config_name) {
$redis = StaticRedis::$Instance;
return $redis->hMGet(REDIS_PREFIX . 'config', $config_name);
}
}
?>

View File

@ -1,18 +0,0 @@
<?php
class Db {
public static $Instance = NULL;
public static $Error = NULL;
public static function Connect() {
$cfg = Config::$Instance;
self::$Instance = new mysqli($cfg->db_host, $cfg->db_user, $cfg->db_password, $cfg->db_database);
if (mysqli_connect_errno()) {
self::$Error = mysqli_connect_error();
return FALSE;
}
return TRUE;
}
}
?>

View File

@ -2,30 +2,30 @@
class Download implements RequestHandler {
function __construct(){
$this->Redis = StaticRedis::$Instance;
$this->Config = Config::$Instance;
$this->Db = Db::$Instance;
$this->Abuse = new Abuse();
$this->Tracking = new Tracking();
$this->FileStore = new FileStore();
$this->Redis->pconnect($this->Config->Redis);
}
public function HandleRequest() {
public function HandleRequest() : void {
if(isset($_REQUEST["hash"])){
$hash = $_REQUEST["hash"];
$fi = $this->FileStore->GetFileInfo($hash);
$file_info = $this->FileStore->GetPublicFileInfo($hash);
if($file_info != NULL){
var_dump($file_info);
} else {
http_response_code(404);
exit();
}
} else {
http_response_code(404);
exit();
}
}
function StartDownload($req){
function StartDownload(){
}
}
?>

9
src/php/fileinfo.php Normal file
View File

@ -0,0 +1,9 @@
<?php
class FileInfo {
public $Path;
public $Views;
public $Uploaded;
public $LastView;
public $Size;
}
?>

View File

@ -1,13 +1,28 @@
<?php
class FileStore {
function __construct(){
$this->Redis = StaticRedis::$Instance;
$this->Db = Db::$Instance;
public function GetPublicFileInfo($public_hash) : FileInfo {
$redis = StaticRedis::$Instance;
$file_key = REDIS_PREFIX . $public_hash;
$public_file_info = $redis->hMGet($file_key, array('path', 'views', 'uploaded', 'lastview', 'size'));
if($public_file_info['path'] != False){
$file = new FileInfo();
$file->Path = $public_file_info['path'];
$file->Views = $public_file_info['views'];
$file->Uploaded = $public_file_info['uploaded'];
$file->LastView = $public_file_info['lastview'];
$file->Size = $public_file_info['size'];
return $file;
}
return NULL;
}
public function GetFileInfo($h160) {
public function FileExists($public_hash) {
$redis = StaticRedis::$Instance;
$file_key = REDIS_PREFIX . $public_hash;
return $redis->hExists($file_key, 'path');
}
}
?>

View File

@ -1,16 +1,27 @@
<?php
//Startup
Config::LoadConfig();
StaticRedis::Connect();
Db::Connect();
define('REDIS_CONFIG', '127.0.0.1');
define('REDIS_PREFIX', 'vc:');
if(isset($_REQUEST["h"])) {
$hf = $_REQUEST["h"];
if(file_exists($h)){
$hc = new $hf();
if($hc instanceof RequestHandler){
$hc->HandleRequest();
spl_autoload_register(function ($class_name) {
include dirname(__FILE__) . '/' . strtolower($class_name) . '.php';
});
//Startup
if(StaticRedis::Connect() == True) {
if(isset($_REQUEST["h"])) {
$handler_name = $_REQUEST["h"];
if(file_exists($handler_name . '.php')){
$handler = new $handler_name();
if($handler instanceof RequestHandler){
$handler->HandleRequest();
exit();
}
}
}
http_response_code(400);
exit();
} else {
http_response_code(500);
exit();
}
?>

7
src/php/info.php Normal file
View File

@ -0,0 +1,7 @@
<?php
class Info implements RequestHandler {
public function HandleRequest() : void {
phpinfo();
}
}
?>

View File

@ -1,5 +1,5 @@
<?php
interface RequestHandler {
public function HandleRequest();
public function HandleRequest() : void;
}
?>

View File

@ -4,9 +4,8 @@
public static $Instance = NULL;
public static function Connect(){
$cfg = Config::$Instance;
self::$Instance = new Redis();
return self::$Instance->pconnect($cfg->redis);
return self::$Instance->pconnect(REDIS_CONFIG);
}
}
?>

12
src/php/sync.php Normal file
View File

@ -0,0 +1,12 @@
<?php
class Sync implements RequestHandler {
public function __construct(){
ini_set('enable_post_data_reading', 0);
}
public function HandleRequest() : void {
}
}
?>

78
src/php/upload.php Normal file
View File

@ -0,0 +1,78 @@
<?php
class UploadResponse {
public $status = 0;
public $msg;
public $pub_hash;
}
class Upload implements RequestHandler {
private $isMultipart = False;
private $MaxUploadSize = 104857600; //100MiB is the default upload size
private $UploadPath = NULL;
private $PublicHashAlgo = "ripemd160";
public function __construct(){
$cfg = Config::MGetConfig(array('max_size', 'upload_path', 'public_hash_algo'));
if($cfg["max_size"] != False){
$this->MaxUploadSize = $cfg["max_size"];
}
if($cfg["upload_path"] != False){
$this->UploadPath = $cfg["upload_path"];
} else {
$this->UploadPath = $_SERVER["DOCUMENT_ROOT"] . "/out";
}
if($cfg["public_hash_algo"] != False){
$this->PublicHashAlgo = $cfg["public_hash_algo"];
}
//set php params
set_time_limit(1200);
ini_set('post_max_size', $this->MaxUploadSize);
ini_set('upload_max_filesize', $this->MaxUploadSize);
ini_set('memory_limit', $this->MaxUploadSize);
ini_set('enable_post_data_reading', 0);
//check upload dir exists
if(!file_exists($this->UploadPath)){
mkdir($this->UploadPath);
}
}
public function HandleRequest() : void {
$rsp = new UploadResponse();
$file_size = $_SERVER["CONTENT_LENGTH"];
if($file_size > $this->MaxUploadSize){
$rsp->status = 1;
$rsp->msg = "File is too large";
} else {
$input = fopen("php://input", "rb");
$bf = BlobFile::LoadHeader($input);
if($bf != null){
//generate public hash
$pub_hash = hash($this->PublicHashAlgo, $bf->Hash);
//sync to other servers
$this->SyncFileUpload($input);
$rsp->status = 200;
$rsp->pub_hash = $pub_hash;
} else {
$rsp->status = 2;
$rsp->msg = "Invalid file header";
}
}
header('Content-Type: application/json');
echo json_encode($rsp);
}
function SyncFileUpload() {
}
}
?>