Skip to content

Instantly share code, notes, and snippets.

@sharad-s
Last active December 18, 2017 19:24
Show Gist options
  • Save sharad-s/d7a9b45c83aedfa99a31ab1adc9f3c30 to your computer and use it in GitHub Desktop.
Save sharad-s/d7a9b45c83aedfa99a31ab1adc9f3c30 to your computer and use it in GitHub Desktop.
//TODO: Create json hash as a global variable that can be changed
//TODO: On file upload, update the new JSONDB hash
var ipfs = window.IpfsApi();
const Buffer = window.IpfsApi().Buffer;
function validateFormOnSubmit(form) {
var reason = "";
reason += validateAudio(form.audio.value);
reason += validateName(form.name.value);
reason += validateArtist(form.artist.value);
//Some fields are empty
if (reason != "") {
alert("Some fields need correction:\n" + reason);
}
//All fields are input
else {
var reader = getReader();
reader.onloadend = e => {
//Get raw data from FileReader
var rawData = reader.result;
//Ipfs Add Audio File
ipfs.add(Buffer.from(rawData), (err, result) => {
if (err || !result) {
console.log(`Unable to upload to IPFS API: ${err}`);
}
else {
const resultHash = result[0].hash;
alert("Success! Hash: " + resultHash);
//Add new JSON entry
var newJSON = newJSON(form.name.value, form.artist.value, resultHash)
//Add JSON entry to current JSON File
//TODO: Get the JSON file from url.
}
})
}
}
return false;
}
function getReader() {
var file = document.getElementById('fileuploader');
if(file.files.length) {
var reader = new FileReader();
reader.readAsArrayBuffer(file.files[0]);
return reader
}
}
function newJSON(name, artist, hash) {
var newJSON = JSON.stringify({
"name": name,
"artist": artist,
"src": resultHash
});
return newJSON;
}
function validateName(name) {
if (!name) {
return "Name ";
} else {
return "";
}
}
function validateArtist(artist) {
if (!artist) {
return "Artist ";
} else {
return "";
}
}
function validateAudio(file) {
if (!file) {
return "Audio File ";
} else {
console.log(file);
return "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment