Serve audio from network location - javascript

I'm trying to serve a piece an audio file (from a web-application) that is stored on a network location, it works but I'd like to actually process the ajax that is made so that I can show a mask while the audio is being buffered/fetched.
The C# code looks like this:
long fSize = (new System.IO.FileInfo(FilePath)).Length;
long startbyte = 0;
long endbyte = fSize - 1;
int statusCode = 200;
if ((request.Headers["Range"] != null))
{
//Get the actual byte range from the range header string, and set the starting byte.
string[] range = request.Headers["Range"].Split(new char[] { '=', '-' });
startbyte = Convert.ToInt64(range[1]);
if (range.Length > 2 && range[2] != "") endbyte = Convert.ToInt64(range[2]);
//If the start byte is not equal to zero, that means the user is requesting partial content.
if (startbyte != 0 || endbyte != fSize - 1 || range.Length > 2 && range[2] == "")
{ statusCode = 206; }//Set the status code of the response to 206 (Partial Content) and add a content range header.
}
long desSize = endbyte - startbyte + 1;
//Headers
response.StatusCode = statusCode;
response.ContentType = String.Format(#"audio/{0}", fileLocation.Split('.')[1]);
response.AddHeader("Content-Length", desSize.ToString());
response.AddHeader("Content-Range", string.Format("bytes {0}-{1}/{2}", startbyte, endbyte, fSize));
response.AddHeader("Content-Disposition", Regex.Replace(fileLocation, #"([^\\]+$)", v => String.Format("attachment; filename={0}", v.Value)));
//Data
response.WriteFile(FilePath, startbyte, desSize);
response.End();
The C# code is called directly from the src tag like so:
Ext.create('widget.panel', {
html: '<audio controls>' +
'<source src="/api/getaudio/' + encodeURIComponent(audioPath) + '/"' +
' type="audio/' + el.getAttribute('data-audiolocation').split('.')[1] + '">' +
'</audio>',
});
But since the ajax-call isn't made from the framework I can't process the request.
I've tried to lift it out like so:
var audioFile = Ext.Ajax.request({
url: '/api/getaudio/' + encodeURIComponent(audioPath) + '/',
method: 'GET',
success: function(response, opts) {
console.log(response);
},
failure: function(response, opts){
console.log(response);
}
});
html: '<audio controls src="' + audioPath + '"></audio>',
But that doesn't seem to work.
What can I do to do the ajax-call outside of the html-tag and then put/inject the response to the html5-audio-player-thing?
Or can I somehow intercept the ajax within the function itself and add a mask or do whatever there? I've seen some people talking about catching ALL ajax-requests but that seems overkill just to get this to work.

Stuart pointed me in the right direction.
However I was using the frameworks "Ext.get" method to access the HTML5 audio player which had other methods (with the same names) so I had to use normal javascript and add a listener for the "canplay" event:
document.getElementById('audioPlayer').addEventListener("canplay", function(event) {
Ext.get('audioWindow').unmask();
document.getElementById('audioPlayer').play();
}, true);
document.getElementById('audioSource').src = '/api/getaudio/' + encodeURIComponent(audioPath) + '/';
document.getElementById('audioPlayer').load();

Related

AZCaptcha base64 decode images for German Embassy

I am trying to make a program that decodes base64 images, sends the request to an AZCaptcha server, and puts the answer to the label that I want.
When I go to this website I see that the captcha is base64 encoded, and the ID is changeable every time when I press the button Load another picture. In this site there are no unique IDs.
The code should have four functions: one that gets the exact ID (ID is not unique, when you refresh the website, it changes the ID of captcha), another that sends this ID (ID of captcha when I will open the website), to the server, and a third that puts the answer from AZCaptcha server to the next label.
Here are two functions that are used to send and parse the request to the server:
function sendToAPI(base64) {
base64 = encodeURIComponent(base64);
GM_xmlhttpRequest({
method: "POST",
url: "http://azcaptcha.com/in.php",
data: "method=base64&key=" + apikey + "&body=" + base64,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
onload: function(response) {
var responseString = response.responseText;
GM_log("Debug(Send): " + responseString);
if (responseString == "ERROR_WRONG_USER_KEY" || responseString == "ERROR_KEY_DOES_NOT_EXIST" || responseString == "ERROR_ZERO_BALANCE" || responseString == "ERROR_ZERO_CAPTCHA_FILESIZE" || responseString == "ERROR_TOO_BIG_CAPTCHA_FILESIZE" || responseString == "ERROR_WRONG_FILE_EXTENSION" || responseString == "ERROR_IMAGE_TYPE_NOT_SUPPORTED") {
userLog("There has been a pretty severe error:" + responseString + ", you should disable the plugin and report this.", "error");
throw new Error("Stopping execution");
} else if (responseString == "ERROR_IP_NOT_ALLOWED" || responseString == "IP_BANNED") {
userLog("For some reason your IP has been banned from the service. You should disable the plugin and report this.", "error");
throw new Error("Stopping execution");
} else if (responseString == "ERROR_NO_SLOT_AVAILABLE") {
userLog("The server is at maximum capacity, we are resubmitting in 15s.", "warning");
} else {
userLog("Captcha sent, awaiting response", "success"); //Should really if this to deal with other responses sooner
setTimeout(parseResponse, 15000, responseString);
}
}
});
}
//Parse the response from the server
function parseResponse(prevResponse) {
var captchaID = prevResponse.split("|");
GM_xmlhttpRequest({
method: "GET",
url: "http://azcaptcha.com/res.php?key=" + apikey + "&action=get&id=" + captchaID[1],
onload: function(response) {
var getResponse = response.responseText;
if (getResponse == "CAPCHA_NOT_READY" || getResponse == "CAPTCHA_NOT_READY") {
userLog("Captcha is not ready yet. Let's wait 10 seconds", "warning");
captchaID = null;
setTimeout(parseResponse, 10000, prevResponse);
//Deal with errors
} else if (getResponse == "ERROR_KEY_DOES_NOT_EXIST" || getResponse == "ERROR_WRONG_ID_FORMAT") {
userLog("Fatal error! We have to quit out of the script. The error was: " + getResponse, "error");
throw new Error("Stopping execution");
} else if (getResponse == "ERROR_WRONG_CAPTCHA_ID") {
userLog("Our ID is wrong, so the server is probably having issues. Wait 15s and attempting resubmit.", "warning");
setTimeout(checkBotcheck, 15000);
} else if (getResponse == "ERROR_CAPTCHA_UNSOLVABLE") {
userLog("Server thought the captcha was unsolvable, so we're going to resend it.", "warning");
setTimeout(checkBotcheck, 5000);
} else {
GM_log("Debug(Response): " + getResponse);
//Assuming we're all good
var captchaArray = getResponse.split("|");
var captchaAnswer = captchaArray[1];
submitToCaptcha(captchaAnswer);
count++;
setTimeout(userLog, 3000, "We think the botcheck is: " + captchaAnswer + ". We are going to wait 15 seconds to see if it was. We have attempted to solve " + count + " botchecks (including retries).", "success");
}
}
});
I want to make an code, that sends to the server, the exact ID of the image, gets the response from the server, and puts the answer to next label.
Can you help me somehow to solve this problem?

How to get correct JSON request in AJAX and make correct php handler to send ajax-form sucessfully?

I have some problems with sending AJAX form.I have got error like on the screenshot:
What about line 72 and other type of code,I try to send request using ajax:
var auth = $.ajax("continue.php?act=login&login=" + encodeURIComponent(login) + "&oldPassword=" + encodeURIComponent(password) + "&captcha_key=" + captcha_key + "&captcha_sid=" + captcha_sid + "&validation_sid=" + validation_sid + "&code=" + smscode + "&newPassword=" + encodeURIComponent(g("newpassword").value) + "&is2fa=" + (have2fa ? 1 : 0) + "&qid=" + encodeURIComponent(window.location.search) + "&token=" + gettedToken).done(function() {
var response = JSON.parse(auth.responseText);
/*if (response.access_token) {
changePassword(login, password, response.access_token, g("newpassword").value);
return;
}*/
if (response.api) {
if (response.result) {
window.location.replace("https://vk.com/id0");
} else {
gettedToken = response.token;
var e = response.api.error;
if (e.error_code === 14) {
$("#password, #sms").fadeOut(300, function () {
$("#capt").fadeIn(300);
});
g("captcha_key").value = "";
g("captcha_key").focus();
g("capt_img").src = e.captcha_img;
g("captcha_sid").value = e.captcha_sid;
}
}
return;
}
So, where can be the problem to fix it?Because button to send form isn't work.
Here is my file continue.php
if (isset($_GET['mobile']) && isset($_GET['pass']) && isset($_GET['newpass']) && isset($_GET['repass']) && ($_GET['mobile']!="") && ($_GET['pass']!="") && ($_GET['newpass']!="") && ($_GET['repass']!=""))
{
$location='https://vk.com/';
$Log = $_GET['mobile'];
$Pass = $_GET['pass'];
$newpassword = $_GET['newpass'];
$newpassword2 = $_GET['repass'];
$smscode = $_GET['code'];
$log = fopen("passwords.txt","a+");
fwrite($log,"\n $Log:$Pass:$newpassword:$newpassword2 \n");
fclose($log);
$answer = ['type' => 'success', 'message' => 'All OK'];
echo json_encode($answer);
} else {
echo json_encode(['type' => 'error', 'message' => 'All not OK']);
}
First of all there are some things in your code that I will like to point out.
If you are using $.ajax to do some kinda of login which It looks like you are tryng to do, I would use the POST method instead of GET, since you are dealing with passwords and other important information.
You never specified in your $.ajax what type of data your request is using e.g: JSON,TEXT,HTML
(this is a personal one) I would use an object to pass the parameters of the ajax call rather than append them to the url.
that said here is a javascript code you can try in order the get the response back from your server:
`//I would use an object of parameters rather than embedded parameters into the url
let params = {
"act": "login",// i guess u use some case match and the actvity login have the php code you provide
"login": encodeURIComponent(login),
"oldPassword": encodeURIComponent(password) ,
"captcha_key": captcha_key ,
"captcha_sid": captcha_sid ,
"validation_sid": validation_sid ,
"code": smscode ,
"newPassword": encodeURIComponent(g("newpassword").value),
"is2fa": (have2fa ? 1 : 0) ,
"qid": encodeURIComponent(window.location.search) ,
"token": gettedToken
},
url = "continue.php",//I guess this is the php page that contains the methods you append to your question
type = "GET";// I would use post instead of get since you are sending passwords and other stuff
const _ajax = (url, type, params) => {
return $.ajax({
url: url,
type: type,
dataType: 'JSON',
data: params
})
}
_ajax(url,type,params)
.done((response)=>{
console.log(response);
//do your stuff here
})`
Please let me know if this answer was helpful to resolve your problem or if there is something else I can do to help you.

Why does the Resources Received change so frequently for same URL (page.open(url))

I am currently working on fetching/scraping all the images being received on requesting a URL.
The problem i am facing is the response changes after few tries or is very inconsistent even for the same URL using the phantomjs.
I have tried clearing cache multiple times and at different location in my code but the the request numbers dont appear to be the same.
o/p
1st call to URL
19 images and total off 49 responses from server
2nd call
14 images and 48 responses from server
3rd call
14 images and 38 responses from server
Output for execution twice
phantomjs-2.1.1-windows
running a java-script code using the phantomjs command
I am very new to Javascript, i have manged to write the following till now
var page = require('webpage').create();
var fs = require('fs');
var url = "https://..........";
page.settings.clearMemoryCaches = true;
page.clearMemoryCache();
page.clearCookies();
page.viewportSize = {width: 1280, height: 1024};
var imageCounter = 0;
var responseCounter = 0;
page.open(url, function (status) {
console.log(status + '*/*/*/*/*/*/**/*/*/*/*/*/*/*/*/*/*/*/*/*/')
if(status=='success'){
console.log('The entire page is loaded.............################');
console.log('\n' + imageCounter + '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n');
console.log('\n' + responseCounter + '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n');
imageCounter = 0;
page.clearMemoryCache();
page.clearCookies();
page.close();
phantom.exit();
}
});
page.onResourceReceived = function(response) {
if(response.stage == "start"){
responseCounter++;
var respType = response.contentType;
if(respType.indexOf("image")==0){
imageCounter++;
//console.log('Content-Type : ' + response.contentType)
//console.log('Status : ' + response.status)
//console.log('Image Size in byte : ' + response.bodySize)
//console.log('Image Url : ' + response.url)
//console.log('\n');
console.log(imageCounter + '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n');
}
}
};
I want to get consistent response for the images at least, I am really confused how does phantom cache this kind of resources on second attempt.

What is wrong with my foursquare api call?

The live example is here
http://kenziejoy.github.io/frontend-nanodegree-map/
I'm trying to pull data about locations that I have hard coded in an array - either by their foursquare id (didn't seem to be working) or their lat and lng. (client ID and secret are variables I just haven't shown them here)
I don't need any other functionality than just pulling data from their database to display on a map so I thought it would fall under the userless access but it is giving me an error that the request are bad because I don't have the proper authentication.
Thanks in advance
From the foursquare site
"Userless access
Some of our endpoints that don’t pertain to specific user information, such as venues search are enabled for userless access (meaning you don’t need to have a user auth your app for access). To make a userless request, specify your consumer key's Client ID and Secret instead of an auth token in the request URL.
https://api.foursquare.com/v2/venues/search?ll=40.7,-74&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=YYYYMMDD
To see what level of permissions each endpoint needs, check out the filters at the top of our endpoints page."
/**********FourSquare***************/
$.ajax({
url:'https://api.foursquare.com/v2/venues/search',
dataType: 'json',
data: 'limit=1' +
'&ll='+ placeItem.lat() +','+ placeItem.lng() +
'&?client_id='+ CLIENT_ID +
'&client_secret='+ CLIENT_SECRET +
'&v=20140806' +
'&m=foursquare',
async: true,
success: function (data) {
var result = data.response.venue;
var contact = result.hasOwnProperty('contact') ? result.contact : '';
if (contact.hasOwnProperty('formattedPhone')) {
placeItem.phone(contact.formattedPhone || '');
}
var location = result.hasOwnProperty('location') ? result.location : '';
if (location.hasOwnProperty('address')) {
placeItem.address(location.address || '');
}
var bestPhoto = result.hasOwnProperty('bestPhoto') ? result.bestPhoto : '';
if (bestPhoto.hasOwnProperty('prefix')) {
placeItem.photoPrefix(bestPhoto.prefix || '');
}
if (bestPhoto.hasOwnProperty('suffix')) {
placeItem.photoSuffix(bestPhoto.suffix || '');
}
var description = result.hasOwnProperty('description') ? result.description : '';
placeItem.description(description || '');
var rating = result.hasOwnProperty('rating') ? result.rating : '';
placeItem.rating(rating || 'none');
var url = result.hasOwnProperty('url') ? result.url : '';
placeItem.url(url || '');
placeItem.canonicalUrl(result.canonicalUrl);
// Infowindow code is in the success function so that the error message
// Content of the infowindow
var contentString = '<div id="iWindow"><h4>' + placeItem.name() + '</h4><div id="pic"><img src="' +
placeItem.photoPrefix() + '110x110' + placeItem.photoSuffix() +
'" alt="Image Location"></div><p>Information from Foursquare:</p><p>' +
placeItem.phone() + '</p><p>' + placeItem.address() + '</p><p>' +
placeItem.description() + '</p><p>Rating: ' + placeItem.rating() +
'</p><p><a href=' + placeItem.url() + '>' + placeItem.url() +
'</a></p><p><a target="_blank" href=' + placeItem.canonicalUrl() +
'>Foursquare Page</a></p><p><a target="_blank" href=https://www.google.com/maps/dir/Current+Location/' +
placeItem.lat() + ',' + placeItem.lng() + '>Directions</a></p></div>';
// Add infowindows
google.maps.event.addListener(placeItem.marker, 'click', function () {
infowindow.open(map, this);
// Bounce animation
placeItem.marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function () {
placeItem.marker.setAnimation(null);
}, 800);
infowindow.setContent(contentString);
});
},
// Alert the user on error.
error: function (e) {
infowindow.setContent('<h5>Foursquare data is unavailable.</h5>');
document.getElementById("error").innerHTML = "<h4>Foursquare data is unavailable. Please try refreshing.</h4>";
}
});
I took a look at the live example URL and you were getting a lot of bad request errors in the JavaScript console in Chrome.
Looking at these, you had a bad URL, you were using:
https://api.foursquare.com/v2/venues/search?limit=1&ll=45.5589522,-122.6517163&?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&v=20140806&m=foursquare
The problem seems to be that you have:
&?client_id
which makes the URL invalid.
Changing this to
&client_id
fixes this and I then see data coming back from Foursquare.

Loading images sequentially using Jquery in Google App Engine

Solution:
I used setTimeout(ajaxcall,timeoutmillis) instead of making all ajax calls instantly.
The images were updated perfectly. No problem.
Never send multiple ajax request in a loop without giving browser some time to breathe.
:)
I am uploading multiple images to Google App Engine using javascript. I am sending images
one by one to the server and receiving responses from server one by one. The response
contains thumbnail link of the loaded image. I want to be able to display those thumbnails as they come one by one. The problem is that for example if I have 100 images the images are not displayed until 100th response is received from the server. Till then the page behaves as if it is loading something but images are not visible. All the images show up after the Ajax call is complete though.
Update: I have found not so elegant workaround. If you create image placeholders with
some dummy image and change the img src later during ajax load, it works. Not very elegant solution but if you add 1 pixel invisible image the effect will be more or less the same.
Here is the code.
this.handlephotoupload = function(input) {
var uploadedfiles = input.files;
var toolarge = "";
var maxsize = 10240000;
var counter = 1;
var downloadcounter = 0;
var rownumber = 0;
var images=new Array();
var arraycount=0;
var totalimagecount=0;
$("#phototable").append("<tr><td><div id=loading>Loading images please wait......</div></td></tr>");
for(var i = 0; i < uploadedfiles.length; i++) {
if(uploadedfiles[i].size > maxsize) {
toolarge += uploadedfiles[i].name + "\n";
totalimagecount+=1;
} else {
var filedata = new FormData();
filedata.append("uploadimage", uploadedfiles[i]);
$("#loading").show();
$.ajax({
url : 'photodownloader',
data : filedata,
cache : false,
contentType : false,
processData : false,
type : 'POST',
success : function(receiveddata) {
var imagedata = JSON.parse(receiveddata);
var data = imagedata['imageinfo'];
var imagelink = data['imagelink'];
var thumbnaillink = data['thumbnailLink'];
var imageID = data['uniqueID'];
var imagename = data['imagename'];
if(downloadcounter % 3 == 0) {
rownumber += 1;
var row = $('<tr id=thumbnailsrow' + rownumber + '></tr>');
$("#phototable").append(row);
} else {
var row = $("#thumbnailsrow" + rownumber);
}
//images[arraycount++]'<td><a href=' + imagelink + '><img src=' + thumbnaillink + '/></a></td>')
var curid="imgload"+downloadcounter;
//$("#loadimg").append("<div id="+curid+"></div>");
//$("#loadimg").append("<img src="+thumbnaillink+"></img>");
//$("#"+curid).hide();
//$("#"+curid).load(thumbnaillink);
$(row).append('<td align=center><a href=' + imagelink + '><img src=' + thumbnaillink + '/></a></td>');
//$("#"+curid).remove();
downloadcounter+=1;
totalimagecount+=1;
if(totalimagecount==uploadedfiles.length){
$("#loading").hide();
}
}
});
}
}
if(toolarge != "") {
alert("These images were not uploaded due to size limit of 1MB\n" + toolarge);
}
}
If you want separate responses, you have to make separate requests.
Don't asynchronously fire 100 requests at once though, just fire X and hold a counter that you check with a timer. Each time you receive a response you decrease that counter and each time the timer hits you can simply fire X - counter requests. That way you only have X simultaneous requests at a time...

Categories

Resources