What is the Alternative to "Remote Address" header in FireFox? - firefox

In Google chrome there is a header called, Remote Address.
I'm writing an add-on for Firefox and I need to decide something based on the remote host but it looks like there is no such header in Firefox.
If you know how to access remote host from the observer object please tell me.
observe : function(aSubject, aTopic, aData) {
//I need remote host here
}
her is the screen shot to the header in Google chrome

If the header is not there it throws excetption NS_ERROR_NOT_AVAILABLE
var {classes: Cc, interfaces: Ci, utils: Cu} = Components;
Cu.import('resource://gre/modules/Services.jsm');
var httpRequestObserver =
{
observe: function(subject, topic, data)
{
var httpChannel, requestURL;
httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
requestURL = httpChannel.URI.spec;
if (topic == "http-on-modify-request") {
//if (requestURL.indexOf('google.com') > -1) {
//httpChannel.setRequestHeader('MyCustomRequestHeader', 'hiiii', false);
try {
var Host = httpChannel.getRequestHeader('Host');
} catch (ex) {
var Host = 'NULL';
}
console.log('REQUEST Header "Host" = ' + Host);
//}
} else if (topic == "http-on-examine-response") {
try {
var Host = httpChannel.getResponseHeader('Host');
} catch (ex) {
var Host = 'NULL';
}
console.log('RESPONSE Header "Host" = ' + Host);
}
}
};
Services.obs.addObserver(httpRequestObserver, "http-on-modify-request", false);
Services.obs.addObserver(httpRequestObserver, "http-on-examine-response", false);
//Services.obs.removeObserver(httpRequestObserver, "http-on-modify-request", false); //run this on shudown of your addon otherwise the observer stags registerd
//Services.obs.removeObserver(httpRequestObserver, "http-on-examine-response", false); //run this on shudown of your addon otherwise the observer stags registerd
Useful articles used to make this snippet:
https://developer.mozilla.org/en-US/docs/Observer_Notifications#HTTP_requests
https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIHttpChannel#getRequestHeader%28%29

Related

Chromecast v3 receiver application not working

I ran the sample custom receiver. I am running it using ngrok but i see in the console that its not connecting to web socket. Any help is appreciated: Here is my receiver code and screenshot
const context = cast.framework.CastReceiverContext.getInstance();
const playerManager = context.getPlayerManager();
const playbackConfig = new cast.framework.PlaybackConfig();
// Customize the license url for playback
playbackConfig.licenseUrl = 'https://wv-keyos.licensekeyserver.com/';
playbackConfig.protectionSystem = cast.framework.ContentProtection.WIDEVINE;
playbackConfig.licenseRequestHandler = requestInfo => {
requestInfo.withCredentials = true;
requestInfo.headers = {
'customdata': '<custom data>'
};
};
// Update playback config licenseUrl according to provided value in load request.
context.getPlayerManager().setMediaPlaybackInfoHandler((loadRequest, playbackConfig) => {
if (loadRequest.media.customData && loadRequest.media.customData.licenseUrl) {
playbackConfig.licenseUrl = loadRequest.media.customData.licenseUrl;
}
return playbackConfig;
});
function makeRequest (method, url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(JSON.parse(xhr.response));
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
playerManager.setMessageInterceptor(
cast.framework.messages.MessageType.LOAD,
request => {
castDebugLogger.info('MyAPP.LOG', 'Intercepting LOAD request');
if (request.media && request.media.entity) {
request.media.contentId = request.media.entity;
}
return new Promise((resolve, reject) => {
if(request.media.contentType == 'video/mp4') {
return resolve(request);
}
// Fetch content repository by requested contentId
makeRequest('GET', 'https://tse-summit.firebaseio.com/content.json?orderBy=%22$key%22&equalTo=%22'+ request.media.contentId + '%22')
.then(function (data) {
var item = data[request.media.contentId];
if(!item) {
// Content could not be found in repository
castDebugLogger.error('MyAPP.LOG', 'Content not found');
reject();
} else {
// Adjusting request to make requested content playable
request.media.contentId = item.stream.hls;
request.media.contentType = 'application/x-mpegurl';
castDebugLogger.warn('MyAPP.LOG', 'Playable URL:', request.media.contentId);
// Add metadata
var metadata = new cast.framework.messages.MovieMediaMetadata();
metadata.metadataType = cast.framework.messages.MetadataType.MOVIE;
metadata.title = item.title;
metadata.subtitle = item.author;
request.media.metadata = metadata;
resolve(request);
}
});
});
});
/** Debug Logger **/
const castDebugLogger = cast.debug.CastDebugLogger.getInstance();
// Enable debug logger and show a warning on receiver
// NOTE: make sure it is disabled on production
castDebugLogger.setEnabled(true);
playerManager.addEventListener(
cast.framework.events.category.CORE,
event => {
castDebugLogger.info('ANALYTICS', 'CORE EVENT:', event);
});
// Set verbosity level for custom tags
castDebugLogger.loggerLevelByTags = {
'MyAPP.LOG': cast.framework.LoggerLevel.WARNING,
'ANALYTICS': cast.framework.LoggerLevel.INFO,
};
/** Optimizing for smart displays **/
const playerData = new cast.framework.ui.PlayerData();
const playerDataBinder = new cast.framework.ui.PlayerDataBinder(playerData);
const touchControls = cast.framework.ui.Controls.getInstance();
let browseItems = getBrwoseItems();
function getBrwoseItems() {
let data = '"video": { \
"author": "The Blender Project", \
"description": "Grumpy Bunny is grumpy", \
"poster": "https://storage.googleapis.com/tse-summit.appspot.com/bbb/poster.png", \
"prog": "https://storage.googleapis.com/tse-summit.appspot.com/bbb/bbb-prog.mp4", \
"stream": { \
"dash": "https://d8dbsji255dut.cloudfront.net/drm-test/4K-Gaming-Sample.mpd", \
"hls": "https://d8dbsji255dut.cloudfront.net/drm-test/4K-Gaming-Sample.m3u8" \
}, \
"title": "Big Buck Bunny" \
}';
let browseItems = [];
for (let key in data) {
let item = new cast.framework.ui.BrowseItem();
item.entity = key;
item.title = data[key].title;
item.subtitle = data[key].description;
item.image = new cast.framework.messages.Image(data[key].poster);
item.imageType = cast.framework.ui.BrowseImageType.MOVIE;
browseItems.push(item);
}
return browseItems;
}
let browseContent = new cast.framework.ui.BrowseContent();
browseContent.title = 'Up Next';
browseContent.items = browseItems;
browseContent.targetAspectRatio =
cast.framework.ui.BrowseImageAspectRatio.LANDSCAPE_16_TO_9;
playerDataBinder.addEventListener(
cast.framework.ui.PlayerDataEventType.MEDIA_CHANGED,
(e) => {
if (!e.value) return;
// Clear default buttons and re-assign
touchControls.clearDefaultSlotAssignments();
touchControls.assignButton(
cast.framework.ui.ControlsSlot.SLOT_1,
cast.framework.ui.ControlsButton.SEEK_BACKWARD_30
);
// Media browse
touchControls.setBrowseContent(browseContent);
});
// context.start({ touchScreenOptimizedApp: true });
context.start({playbackConfig: playbackConfig});
I have already registered for Google Cast SDK Developer Console and created a unpublished app and added my chrome cast device as well.
You are seeing these errors because you are loading the receiver through a web browser directly. The usual flow of a cast session is that a "sender" (web browser, iOS device, android device) will initiate a cast session with the hosted receiver, and thereby beginning the socket connection. Right now, you only have a receiver loading, nothing has initiated the session.
One way to test this is to plug in a Chromecast or cast enabled device (most Android TV's have Chromecast built-in too!), and use a valid sender to connect to your receiver.
Google have built an awesome tool to help with Chromecast development, it's a shame it's not publicised more. You can find it here: https://casttool-1287.appspot.com/cactesttool/index.html
If you're wanting to really nail down your Chromecast development skills, I personally recommend that you checkout:
Google Codelabs for Cast, these have some really helpful walkthroughs. https://codelabs.developers.google.com/?cat=Cast
The Google Cast github repo, has some great examples. https://github.com/googlecast
Note: This is by no means a detailed explanation of how cast sessions are actually initiated, some very smart people have done some digging into how Chromecast sessions work, and if you're interested checkout Romain Picard's writeup at https://blog.oakbits.com/google-cast-protocol-overview.html

how to connect to specific wifi in xamarin ios?

I want to connect to wifi....................................................................
Here is my code:
NEHotspotConfigurationManager wifiManager = new NEHotspotConfigurationManager();
var wifiConfig = new NEHotspotConfiguration(ssid, password, false) { JoinOnce = true };
wifiManager.RemoveConfiguration(ssid);
wifiManager.ApplyConfigurationAsync(wifiConfig);
wifiManager.ApplyConfiguration(wifiConfig, (error) =>
{
if (error != null)
{
Console.WriteLine($"Error while connecting to WiFi network {ssid}: {error.Description}");
}
});
return true;
Just like #cole-xia-msft mentioned the link for the configuration work, the C# code would look like this.
var configuration = new NetworkExtension.NEHotspotConfiguration("SSID", "Password", false);
configuration.JoinOnce = true;
NetworkExtension.NEHotspotConfigurationManager.SharedManager.ApplyConfiguration(configuration, (NSError error) =>
{
if (error != null) {
if (error?.LocalizedDescription == "already associated.")
Console.WriteLine("Connected");
else
Console.WriteLine("No Connected");
}
else
Console.WriteLine("Connected");
});
If your function enclosing the ApplyConfiguration call is asynchronous, you should consider using ApplyConfigurationAsync instead

firefox addon change response code

I have an extension that is checking response in http-on-examine-response listener. In the listener it is possible change the headers via httpChannel, and via nsITraceableChannel we can change response content.
But how to change response code (for example from 407 to 200) in the http-on-examine-response listener?
Some code:
const { Ci, Cu, Cc, Cr } = require('chrome');
Cu.import('resource://gre/modules/Services.jsm');
var observer = {
observe: function(aSubject, aTopic, aData) {
if (aTopic == 'http-on-examine-response') {
console.log('we are in observer http-on-examine-response');
var httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
if(httpChannel.responseStatus == 407){
httpChannel.responseStatus = 200; // <-- this is not working
}
}
}
};
Services.obs.addObserver(observer, 'http-on-examine-response', false);
exports.onUnload = function (aData, aReason) {
Services.obs.removeObserver(observer, 'http-on-examine-response');
};

Node.js proxy server with https support

I'm trying to write proxy server that will proxy (almost) all http/s requests. Almost all because I need catch requests for some specific https url's and as response send the file from hdd instead of real response from the web.
Whole solution should works as proxy in the browser and have to work on windows 7. I started with my own proxy based on express.js. It works great ... but unfortunately not via https. Then I was trying to use several existing node.js proxy servers from github (https://github.com/horaci/node-mitm-proxy, https://github.com/Hypermediaisobar/hyperProxy and few other) but any of them worked in windows environment on https (or I don't know how to congiure them).
Finally I found somewhere in internet code (don't have the link to source) which works via https (see code below). The problems with this code is, that I can't find right way to check the incoming request url and depending on the request url handle them in different ways.
I will be grateful if someone could help me with that.
var http = require('http');
var net = require('net');
var debugging = 0;
var regex_hostport = /^([^:]+)(:([0-9]+))?$/;
function getHostPortFromString(hostString, defaultPort) {
var host = hostString;
var port = defaultPort;
var result = regex_hostport.exec(hostString);
if (result != null) {
host = result[1];
if (result[2] != null) {
port = result[3];
}
}
return( [ host, port ] );
}
// handle a HTTP proxy request
function httpUserRequest(userRequest, userResponse) {
var httpVersion = userRequest['httpVersion'];
var hostport = getHostPortFromString(userRequest.headers['host'], 80);
// have to extract the path from the requested URL
var path = userRequest.url;
result = /^[a-zA-Z]+:\/\/[^\/]+(\/.*)?$/.exec(userRequest.url);
if (result) {
if (result[1].length > 0) {
path = result[1];
} else {
path = "/";
}
}
var options = {
'host': hostport[0],
'port': hostport[1],
'method': userRequest.method,
'path': path,
'agent': userRequest.agent,
'auth': userRequest.auth,
'headers': userRequest.headers
};
var proxyRequest = http.request(
options,
function (proxyResponse) {
userResponse.writeHead(proxyResponse.statusCode, proxyResponse.headers);
proxyResponse.on('data', function (chunk) {
userResponse.write(chunk);
}
);
proxyResponse.on('end',
function () {
userResponse.end();
}
);
}
);
proxyRequest.on('error', function (error) {
userResponse.writeHead(500);
userResponse.write(
"<h1>500 Error</h1>\r\n<p>Error was <pre>" + error + "</pre></p>\r\n</body></html>\r\n";
);
userResponse.end();
}
);
userRequest.addListener('data', function (chunk) {
proxyRequest.write(chunk);
}
);
userRequest.addListener('end', function () {
proxyRequest.end();
}
);
}
function main() {
var port = 5555; // default port if none on command line
// check for any command line arguments
for (var argn = 2; argn < process.argv.length; argn++) {
if (process.argv[argn] === '-p') {
port = parseInt(process.argv[argn + 1]);
argn++;
continue;
}
if (process.argv[argn] === '-d') {
debugging = 1;
continue;
}
}
if (debugging) {
console.log('server listening on port ' + port);
}
// start HTTP server with custom request handler callback function
var server = http.createServer(httpUserRequest).listen(port);
server.addListener('checkContinue', function (request, response){
console.log(request);
response.writeContinue();
});
// add handler for HTTPS (which issues a CONNECT to the proxy)
server.addListener(
'connect',
function (request, socketRequest, bodyhead) {
var url = request['url'];
var httpVersion = request['httpVersion'];
var hostport = getHostPortFromString(url, 443);
// set up TCP connection
var proxySocket = new net.Socket();
proxySocket.connect(
parseInt(hostport[1]), hostport[0],
function () {
console.log("ProxySocket: " + hostport[1] + " | " + hostport[0]);
proxySocket.write(bodyhead);
// tell the caller the connection was successfully established
socketRequest.write("HTTP/" + httpVersion + " 200 Connection established\r\n\r\n");
}
);
proxySocket.on('data', function (chunk) {
socketRequest.write(chunk);
}
);
proxySocket.on('end', function () {
socketRequest.end();
}
);
socketRequest.on('data', function (chunk) {
proxySocket.write(chunk);
}
);
socketRequest.on('end', function () {
proxySocket.end();
}
);
proxySocket.on('error', function (err) {
socketRequest.write("HTTP/" + httpVersion + " 500 Connection error\r\n\r\n");
socketRequest.end();
}
);
socketRequest.on('error', function (err) {
proxySocket.end();
}
);
}
); // HTTPS connect listener
}
main();
are you asking for
http://expressjs.com/4x/api.html#req.secure
req.secure -> https
http://expressjs.com/4x/api.html#req.protocol
req.protocol -> http
http://expressjs.com/4x/api.html#req.host
req.host
req.url
this should all be on your userRequest
I probably did not understand your question correctly.
Just add this line:
var https = require('https');
And when you are making regular http requests, use http.request, and for the ssl requests, https.request.

How to register Window phone with notification hub in app-backend

Hello friends i am trying to implement the app-backend registration of app with notification hub.for implementing it i am following this notify user with notification hub but i wanted to do registration for windows phone so i have tried to do it and write this code in mobile service Api
exports.post = function(request, response) {
// Use "request.service" to access features of your mobile service, e.g.:
// var tables = request.service.tables;
// var push = request.service.push;
var azure = require('azure');
var hub = azure.createNotificationHubService('samplenotificationhub',
'full access key');
var platform = request.body.platform;
var installationId = request.header('X-ZUMO-INSTALLATION-ID');
var registrationComplete = function(error, registration) {
if (!error) {
// Return the registration.
response.send(200, registration);
} else {
response.send(500, 'Registration failed!');
}
}
// Function called to log errors.
var logErrors = function(error) {
if (error) {
console.error(error)
}
}
hub.listRegistrationsByTag(installationId, function(error, existingRegs) {
var firstRegistration = true;
if (existingRegs.length > 0) {
for (var i = 0; i < existingRegs.length; i++) {
if (firstRegistration) {
// Update an existing registration.
if (platform === 'wp') {
existingRegs[i].ChannelUri = request.body.channelUri;
hub.updateRegistration(existingRegs[i], registrationComplete);
} else {
response.send(500, 'Unknown client.');
}
firstRegistration = false;
} else {
// We shouldn't have any extra registrations; delete if we do.
hub.deleteRegistration(existingRegs[i].RegistrationId, logErrors);
}
}
} else {
// Create a new registration.
if (platform === 'wp') {
hub.mpns.createNativeRegistration(request.body.channelUri,
[request.body.CurrentDate], registrationComplete);
}
else {
response.send(500, 'Unknown client.');
}
}
});
};
i am able to get the api call from this code in my app..
private async Task AcquirePushChannel()
{
CurrentChannel = HttpNotificationChannel.Find("mychannel");
string message;
if (CurrentChannel == null)
{
CurrentChannel = new HttpNotificationChannel("mychannel");
CurrentChannel.Open();
CurrentChannel.BindToShellTile();
CurrentChannel.BindToShellToast();
}
var body = new NotificationRequest
{
channelUri = CurrentChannel.ChannelUri.ToString(),
platform = "wp",
CurrentDate = "1",
};
try
{
// Call the custom API POST method with the supplied body.
var result = await App.MobileService
.InvokeApiAsync<NotificationRequest,
RegistrationResult>("registrationapi", body,
System.Net.Http.HttpMethod.Post, null);
// Set the response, which is the ID of the registration.
message = string.Format("Registration ID: {0}", result.RegistrationId);
registrationid = result.RegistrationId;
}
catch (MobileServiceInvalidOperationException ex)
{
message = ex.Message;
}
i have seen an active api call on mobile service dashboard but not able to get response from API..
i have written this code in my table scripts so that i can send push notification to my phone it..also take a look if anything is wrong in it.
function insert(item, user, request) {
var azure = require('azure');
var hub = azure.createNotificationHubService('samplenotificationhub',
'listen signature string');
// Create the payload for a Windows Store app.
var wnsPayload = '<toast><visual><binding template="ToastText02"><text id="1">New item added:</text><text id="2">' + "tanuj" + '</text></binding></visual></toast>';
var Toasttemplate = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<wp:Notification xmlns:wp=\"WPNotification\">" +"<wp:Toast>" +"<wp:Text1>$(" + "1" + ")</wp:Text1>" +"</wp:Toast> " +"</wp:Notification>";
// Execute the request and send notifications.
request.execute({
success: function() {
// Write the default response and send a notification
// to the user on all devices by using the userId tag.
request.respond();
hub.wpns.send("1", Toasttemplate, 'wpns/toast', function(error) {
if (error) {
console.log(error);
}
});
}
});
i know this is lot of code i am putting this because the link is not mentioned for wp so just wanted to make sure i am doing right.
also please let me know first what is INSTALATIONID in var installationId = request.header('X-ZUMO-INSTALLATION-ID'); hope to get some response. any help ,idea or suggestion is appreciated.

Resources