Safari issue with HttpContext.User.Identity - javascript

I try to play mp3 file, which is returned by MyAudio method from ContentController, through html5 audio tag. Following code:
[Authorize]
public class ContentController : Controller
{
private ContentServices Content { get; set; }
protected override void Initialize(RequestContext requestContext)
{
if (requestContext.HttpContext.User.Identity.isAuthenticated)
{
base.Initialize(requestContext);
}
}
public ActionResult MyAudio(string name)
{
var file = Server.MapPath("~/" + name);
return File(file, "audio/mp3");
}
Common html code
When the user is Authorized all works perfect in Chrome. But when I have tested it in Safari there is a strange mystery. The HttpContext.User.Identity.isAuthenticated returns false and of course code doesn't execute further.
The interesting thing is that when I use for example #Html.Action or #Html.RouteLink, HttpContext.User.Identity.isAuthenticated will return true.
I've tried to use javascript and jquery to solve the problem, but I also had wierd things at Safari.
<script type="text/javascript">
function getAudio() {
if (audio.src == "" || audio.src == null) {
// (1) audio.src = '#Url.Content("~/Content/MyAudio")' + "hello.mp3";
// (2) audio.src = '#Url.Action("MyAudio", "Content", new { name = "hello.mp3" } )';
/* (3) $.get('#Url.Content("~/Content/MyAudio")', {"name": "hello.mp3"},
function(data) {
alert("hello");
});
*/
audio.load();
audio.play();
}
}
</script>
Both (1) and (2) have the same problem. But when I use (3), HttpContext.User.Identity.isAuthenticated returns true at Safary. But I guess u can't give file stream through jquery.
Have anyone have an idea what's is go on nad how I can fix the problem?
PS I use ASP.NET Development Server and Safari 5.1.7 Win32 7.

Related

How to get real time notification with sound using laravel pusher?

I want to get real-time notifications with sound when an order is placed into my app. I'm using laravel 8 and pusher to that. I get real-time alerts but the sound does not work perfectly. When an order is placed first time sound does not play, after that sound is played perfectly. Here is my code structure ...
My event class
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class MyEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public function __construct($message)
{
$this->message = $message;
}
public function broadcastOn()
{
return ['my-channel'];
}
public function broadcastAs()
{
return 'my-event';
}
}
Here is the js code
Pusher.logToConsole = true;
var pusher = new Pusher('***pusher key***', {
cluster: 'ap2'
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
alert(data.message)
playAudio();
});
function playAudio() {
var x = new Audio('http://127.0.0.1:8000/backend/assets/notification.mp3');
// Show loading animation.
var playPromise = x.play();
if (playPromise !== undefined) {
playPromise.then(_ => {
x.play();.
})
.catch(error => {
});
}
}
Here is my controller
public function store(){
event(new MyEvent('1 new order has been placed'));
return 'Success';
}
When I hit this route for the first time, real-time alert message is shown but the sound does not play. It shows this error
DOMException: play() failed because the user didn't interact with the document first.
https://some link
And it works perfectly after first time
I would like to give a sound notification to the admin if the order is placed, now how can I do that?
With the latest updates of browsers, it is now impossible to start a sound with the code without the user clicking a button.

Meteor DOMException: Unable to decode audio data

EDIT : I just created a new Meteor Project and it worked :D wow.But it still doesnt work on my core project..looks like i have different settings.
In my Meteor.js project i have 4 .mp3-files located in public/sounds/xyz.mp3.
I load these .mp3 with :
let soundRequest = new XMLHttpRequest();
soundRequest.open('GET', this._soundPath, true);
soundRequest.responseType = 'arraybuffer';
let $this = this;
soundRequest.onload = function () {
Core.getAudioContext().decodeAudioData(soundRequest.response, function (buffer) {
$this.source.buffer = buffer;
$this.source.loop = true;
$this.source.connect($this.panner);
});
};
soundRequest.send();
This WORKS on google Chrome, but when i build the app via meteor run android-device, i get the following error message : DOMException: Unable to decode audio data
I wonder if this is a bug because loading .png or .jpg works just fine in the mobile version. I have not installed any packages beside meteor add crosswalk but deinstalling this doesnt help either.
You shouldn't need to do a http request to get a local resource. You can just refer to a local url. On the Android device the path is different. See this code:
function getSound(file) {
var sound = "/sounds/"+file;
if (Meteor.isCordova) {
var s;
if (device.platform.toLowerCase() === "android") {
sfile = cordova.file.applicationDirectory.replace('file://', '') + 'www/application/app' + sound;
}
else {
sfile = cordova.file.applicationDirectory.replace('file://', '') + sound;
}
var s = new Media(
sfile,
function (success) {
console.log("Got sound "+file+" ok ("+sfile+")");
s.play();
},
function (err) {
console.log("Get sound "+file+" ("+sfile+") failed: "+err);
}
);
} else {
var a = new Audio(sound);
a.play();
}
}
On a device it loads the sound file asynchronously and then plays it. In the browser it just loads and plays it synchronously.
This web API is not supported on android device but works on chrome browser of android
Check browser specification in this link
https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/decodeAudioData

Redirect to a page after a pop up opens

I am trying to redirect a web page after a condition is returned as true but I can't seem to get it work. In theory this should, shouldn't it. What am I missing, is it even possible!
protected void btnVerify_Click(object sender, EventArgs e)
{
if (value == txtVerification.Text || txtVerification.Text == "****")
{
//defines a bool to tell if the popup window has been shown, this will only ever return true
bool PopupShown = doRedirect();
if(PopupShown)
{
Response.Redirect("somewebpage.aspx");
}
}
else
{
lblVerificationFailed.Visible = true;
}
}
//Opens the popup window to fire off the download and returns true
bool doRedirect()
{
string url = "GetDocs.aspx";
string s = "window.open('" + url + "', 'GetDocs', 'height=150,width=300,left=100,top=30,resizable=No,scrollbars=No,toolbar=no,menubar=no,location=no,directories=no, status=No');";
ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);
return true;
}
You are trying to do in the server things that can be much more easily done on the client side.
You're using a server event to catch the click of a button on your view, launch a client popup and later redirect your page execution.
Try with something like this on javascript:
var btnVerify = document.getElementById("btnVerify");
btnVerify.addEventListener("click", function() {
window.open('GetDocs.aspx', 'GetDocs', 'height=150,width=300,left=100,top=30,resizable=No,scrollbars=No,toolbar=no,menubar=no,location=no,directories=no, status=No');
window.location.href = "somewebpage.aspx";
});
Sussed it, if I use window.location.replace instead of window.location it works exactly like I want it to. Many thanks all :)

ClientScript not working properly on class C#

I want to deploy a script on C# which usually uses methods like:
ClientScript.RegisterStartupScript(GetType(), "script", "Details('" + hdnId.Value + "');", true);
However I wanted to make a class that runs that code:
public class WebUtilities
{
public static void CustomScript(Page objPage, string strScript)
{
objPage.ClientScript.RegisterStartupScript(objPage.GetType(), "script", strScript, true);
}
}
When I call WebUtilities.CustomScript, sometimes it works, but leaves a //]]> at the bottom of the page.
And there is one occasion that it does not work at all. I only noticed that the first method works, and the second one doesn't.
How can I make the class version to work properly?
I have this function, and it always works, try it
public static void callJavascriptFunction(string strScript)
{
if (HttpContext.Current == null && HttpContext.Current.Handler is Page) { return; }
Page currentPage = (Page)HttpContext.Current.Handler;
ScriptManager.RegisterStartupScript(currentPage,
currentPage.GetType(),
"Funct",
strScript,
true);
}

Bypass SSL Error in InAppBrowser Cordova Plugin

I have added an InAppBrowser plugin into a Cordova project to access a site and get token but while the site is opening normally in desktop browsers the same is giving error while opening from mobile browser.
Also the default native browser will ask to continue in case of SSL error but the Cordova InAppBrowser is not asking for such option and instead showing an error page. I am opening the IAB using the following code :
var iab = window.open('http://www.example.com', '_blank', 'location=yes');
Any idea on how to bypass SSL erros in InAppBrowser ?
I'm going to expand on the answer to the related question (phonegap inappbrowser https pages not loading). This pertains only to Android, sorry still working on iOS.
Add this code:
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
Log.e("Error", "Received SSL error"+ error.toString());
handler.proceed();
}
to the InAppBrower.java file from the plugin. Specifically, it should be under the InAppBrowserClient class.
Hope this helps!
Insert Proper Code from below InAppBrowser.java in to your plugin
LOCATED IN platforms\android\src\org\apache\cordova\inappbrowser\InAppBrowser.java
Filtered code from below java code:
import android.net.http.SslError;
import android.webkit.SslErrorHandler;
#SuppressLint("SetJavaScriptEnabled")
public class InAppBrowser extends CordovaPlugin {
private boolean ignoreSSLError = false;
private HashMap<String, Boolean> parseFeature(String optString) {
if (optString.equals(NULL)) {
return null;
} else {
HashMap<String, Boolean> map = new HashMap<String, Boolean>();
StringTokenizer features = new StringTokenizer(optString, ",");
StringTokenizer option;
while(features.hasMoreElements()) {
option = new StringTokenizer(features.nextToken(), "=");
if (option.hasMoreElements()) {
String key = option.nextToken();
if(key.equalsIgnoreCase(IGNORE_SSL_ERROR)) {
Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
map.put(key, value);
}
else {
Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
map.put(key, value);
}
}
}
return map;
}
}
public String showWebPage(final String url, HashMap<String, Boolean> features) {
// Determine if we should hide the location bar.
showLocationBar = true;
showZoomControls = true;
openWindowHidden = false;
ignoreSSLError = false;
if (features != null) {
Boolean show = features.get(LOCATION);
if (show != null) {
showLocationBar = show.booleanValue();
}
Boolean SSLError = features.get(IGNORE_SSL_ERROR);
if(SSLError != null){
ignoreSSLError = SSLError.booleanValue();
}
Boolean zoom = features.get(ZOOM);
if (zoom != null) {
showZoomControls = zoom.booleanValue();
}
Boolean hidden = features.get(HIDDEN);
if (hidden != null) {
openWindowHidden = hidden.booleanValue();
}
Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON);
if (hardwareBack != null) {
hadwareBackButton = hardwareBack.booleanValue();
}
Boolean cache = features.get(CLEAR_ALL_CACHE);
if (cache != null) {
clearAllCache = cache.booleanValue();
} else {
cache = features.get(CLEAR_SESSION_CACHE);
if (cache != null) {
clearSessionCache = cache.booleanValue();
}
}
}
#SuppressLint("NewApi")
public void run() {
((InAppBrowserClient) client).setSSLErrorFlag(ignoreSSLError);
}
};
this.cordova.getActivity().runOnUiThread(runnable);
return "";
}
public class InAppBrowserClient extends WebViewClient {
EditText edittext;
CordovaWebView webView;
boolean ignoreSSLError = false;
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
if(this.ignoreSSLError) {
handler.proceed();
return;
}
else{
super.onReceivedSslError(view, handler, error);
}
}
public void setSSLErrorFlag(boolean flag) {
this.ignoreSSLError = flag;
}
}
}
THEN ADD THIS LINE IN JAVASCRIPT
var options = {
location: 'yes',
//clearcache: 'no',
toolbar: 'yes',
//clearsessioncache:'no',
zoom:'no',
ignoresslerror:'yes'
};
$scope.init = function () {
$ionicPlatform.ready(function() {
$cordovaInAppBrowser.open('https://192.168.1.80', '_blank', options)
.then(function(event) {
})
.catch(function(event) {
});
});
AFTER DONE THIS COMPILE AND EXECUTE THAT'S IT
FULL VERSION CODE
Local https links are blocked by default in InAppBrowser (links using fake SSL certificate which can't be verified by a 3rd party). Ideally, user should be given an option to proceed or cancel the request like the default desktop browsers do.
Right now, we have to additional method for accessing fake ssl in the InAppBrowser like location,zoom,hardwareback

Categories

Resources