Reduce the amount of functions on the backend

Instead of using separate functions for each step (hex -> bytearray -> base64
and the opposite),
this commit merges the required functions into their uses.
This commit is contained in:
magmaus3 2023-07-24 18:53:22 +02:00
parent 206b295268
commit 97215d4265
Signed by: magmaus3
GPG key ID: 966755D3F4A9B251

View file

@ -7,58 +7,42 @@
<script> <script>
/* /*
* TODO: * TODO:
* - [ ] rewrite functions to not use copied functions * - [x] rewrite functions to not use copied functions
* - [x] add UI * - [x] add UI
* - [x] add style * - [x] add style
* - [ ] make everything not look like made at 0:41 on a phone * - [x] make everything not look like made at 0:41 on a phone
*/ */
function hexToBytes(hexdata) { function infohashToBase64(infohash) {
// https://stackoverflow.com/a/39396866 // Converts an hex infohash into base64.
var arr = hexdata.replace(/[^0-9a-fA-F]/g, '')
// Convert hex into an byte array
let byteArray = infohash.replace(/[^0-9a-fA-F]/g, '')
.match(/[0-9a-fA-F]{2}/g); .match(/[0-9a-fA-F]{2}/g);
for(var i = 0; i<arr.length; i++) { for(var i = 0; i<byteArray.length; i++) {
arr[i] = parseInt(arr[i], 16); byteArray[i] = parseInt(byteArray[i], 16);
} }
return arr; // Convert byteArray into base64
}
function bytesToBase64(byteArray) {
// https://stackoverflow.com/a/11562550
return btoa( return btoa(
String.fromCharCode.apply( String.fromCharCode.apply(
null, new Uint8Array(byteArray) null, new Uint8Array(byteArray)
) )
); );
} }
function base64ToInfohash(b64) {
function base64ToArray(base64) { // Converts a base64 value into a infohash (in a hex form)
// https://stackoverflow.com/a/21797381
var binaryString = atob(base64);
var bytes = new Uint8Array(binaryString.length);
for (var i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes;
}
function bytesToHex(byteArray) { // Convert base64 into an byteArray
// https://stackoverflow.com/a/34310051 let binaryString = atob(b64);
let byteArray = new Uint8Array(binaryString.length);
for (var i = 0; i < binaryString.length; i++) {
byteArray[i] = binaryString.charCodeAt(i);
}
// Convert byteArray into hex values
return Array.from(byteArray, function(byte) { return Array.from(byteArray, function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2); return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join(''); }).join('');
} }
function infohashToBase64(infohash) {
return bytesToBase64(
hexToBytes(infohash)
);
}
function base64ToInfohash(b64) {
return bytesToHex(
base64ToArray(b64)
);
}
// Everything for the UI itself // Everything for the UI itself