While trying to build a web application using the Sinch Instant Messaging SDK I ran into an issue of not being able receive instant messages using the latest Javascript Instant Messaging SDK found here. I have also been following along this tutorial to help build my app that I think uses a different version of the SDK where instant messages can be received. However, the SDK version in the tutorial does not let me use generated userTickets for authentication for my application, while the latest SDK version does.
So, I was wondering if there was a way to either use generated userTickets for the SDK found in the tutorial or receive instant messages using the latest SDK.
On the latest SDK I have tried setting supportActiveConnection to true during configuration in order to receive messages using the code in the tutorial with no success. Here are some of the relevant code snippets from the tutorial to receive messages:
sinchClient = new SinchClient({
applicationKey: 'APP_KEY',
capabilities: {
messaging: true
},
supportActiveConnection: true,
});
var loginObject = {
username: username,
password: password
};
sinchClient.start(loginObject, function() {
global_username = username;
showPickRecipient();
}).fail(handleError);
var messageClient = sinchClient.getMessageClient();
var eventListener = {
onIncomingMessage: function(message) {
if (message.senderId == global_username) {
$('div#chatArea').append('<div>' + message.textBody + '</div>');
} else {
$('div#chatArea').append('<div style="color:red;">' + message.textBody + '</div>');
}
}
}
messageClient.addEventListener(eventListener);
The authentication ticket is generated by a python back-end through the following function and handler:
def getAuthTicket(username):
userTicket = {
'identity': {'type': 'username', 'endpoint': username},
'expiresIn': 3600,
'applicationKey': APPLICATION_KEY,
'created': datetime.utcnow().isoformat()
}
userTicketJson = json.dumps(userTicket).replace(" ", "")
userTicketBase64 = base64.b64encode(userTicketJson)
# TicketSignature = Base64 ( HMAC-SHA256 ( ApplicationSecret, UTF8 ( UserTicketJson ) ) )
digest = hmac.new(base64.b64decode(
APPLICATION_SECRET), msg=userTicketJson, digestmod=hashlib.sha256).digest()
signature = base64.b64encode(digest)
# UserTicket = TicketData + ":" + TicketSignature
signedUserTicket = userTicketBase64 + ':' + signature
return {"userTicket": signedUserTicket}
class TicketHandler(BaseHandler):
def get(self):
self.response.write(getAuthTicket(self.username))
Then on the client side I call a get request on the ticket handler.
$.get('/ticket', function(authTicket) {
sinchClient.start(eval("(" + authTicket + ")"))
.then(function() {
console.log("success");
})
.fail(function(error) {
console.log("fail");
});
});
The error I get when I try to start the start the Sinch client using the sinch.min.js file found in the tutorial is a "no valid identity or authentication ticket".
Related
I am using javascript client by Twilio to make calls to any number.
But I am not able to find any solution for this.
How do we record an outbound call from browser to a phone, any server-side or client-side solution for this?
I was able to place call successfully using quickstart.js file
using below code
document.getElementById('button-call').onclick = function () {
try {
if (document.getElementById('CallTo').value != '') {
var params = {
To: "+" + document.getElementById('CallTo').value,
record: 'record-from-ringing-dual'
};
log('Calling ' + params.To + '...');
console.log('Calling ' + params.To + '...');
if (device) {
var outgoingConnection = device.connect(params);
outgoingConnection.on('ringing', function () {
log('Ringing...');
document.getElementById('hdnCallIDs').value = outgoingConnection.parameters.CallSid;
log(document.getElementById('hdnCallIDs').value);
});
}
} else {
log('Enter Dialing number...');
}
}
catch (err) {
log(err.message);
}
};
You will put the TwiML, for the Dial Verb, to Record the calls returned by the Voice URL of your TwiML Application. You instruct the Twilio clients to use a specific TwiML Application SID when creating their access tokens.
record
How I can use Swagger-generated API client source on client-site (normal browser application without NodeJs)?
In a first test I generated a javascript client for Swaggers' petstore API (https://petstore.swagger.io/v2) using editor.swagger.io
The generated code is containing a index.js which provides access to constructors for public API classes, which I try to embed and use in my web application.
The documentation describes the usage of the API like so:
var SwaggerPetstore = require('swagger_petstore');
var defaultClient = SwaggerPetstore.ApiClient.instance;
// Configure API key authorization: api_key
var api_key = defaultClient.authentications['api_key'];
api_key.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//api_key.apiKeyPrefix = 'Token';
var apiInstance = new SwaggerPetstore.PetApi();
var petId = 789; // Number | ID of pet to return
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.getPetById(petId, callback);
This works fine for NodeJs applications. But how I can use the API for conventional client-site web-apps inside the browser? For such applications the nodejs function require does not work.
From https://github.com/swagger-api/swagger-js
The example has cross origin problem, but it should work in your own project
<html>
<head>
<script src='//unpkg.com/swagger-client' type='text/javascript'></script>
<script>
var specUrl = '//petstore.swagger.io/v2/swagger.json'; // data urls are OK too 'data:application/json;base64,abc...'
SwaggerClient.http.withCredentials = true; // this activates CORS, if necessary
var swaggerClient = new SwaggerClient(specUrl)
.then(function (swaggerClient) {
return swaggerClient.apis.pet.addPet({id: 1, name: "bobby"}); // chaining promises
}, function (reason) {
console.error("failed to load the spec" + reason);
})
.then(function(addPetResult) {
console.log(addPetResult.obj);
// you may return more promises, if necessary
}, function (reason) {
console.error("failed on API call " + reason);
});
</script>
</head>
<body>
check console in browser's dev. tools
</body>
</html>
This is the first time I use Azure Storage JS API. I have followed instruction on this Microsoft tutorial.
I generate the SAS key on the node server with successful results but I still get the authentication failed error. I'm using the libraries provided by Microsoft Azure. How may I fix this?
function test() {
Restangular.all('cdn/sas').post({container: 'photos'}).then(function (sas) {
var blobUri = 'https://hamsar.blob.core.windows.net';
var blobService = AzureStorage.createBlobServiceWithSas(blobUri, sas.token);
blobService.listContainersSegmented(null, function (error, results) {
if (error) {
// List container error
} else {
// Deal with container object
}
});
}, function (error) {
console.log("Error generating SAS: ", error);
});
}
Error messages:
According to your error message, I found you create a Service SAS token. But if you want to list all the container name in your storage account. You need use account SAS token.
Notice: You could also use the blobService.listBlobsSegmented, you should make sure your service sas token has the permission to list the blob file and set the container name.
Like this:
blobService.listBlobsSegmented('mycontainer', null, function (error, results)
If you want to list all the container, I suggest you could follow these codes to generate the Account SAS.
Code like this :
var getPolicyWithFullPermissions = function(){
var startDate = new Date();
var expiryDate = new Date();
startDate.setTime(startDate.getTime() - 1000);
expiryDate.setTime(expiryDate.getTime() + 24*60*60*1000);
var sharedAccessPolicy = {
AccessPolicy: {
Services: AccountSasConstants.Services.BLOB +
AccountSasConstants.Services.FILE +
AccountSasConstants.Services.QUEUE +
AccountSasConstants.Services.TABLE,
ResourceTypes: AccountSasConstants.Resources.SERVICE +
AccountSasConstants.Resources.CONTAINER +
AccountSasConstants.Resources.OBJECT,
Permissions: AccountSasConstants.Permissions.READ +
AccountSasConstants.Permissions.ADD +
AccountSasConstants.Permissions.CREATE +
AccountSasConstants.Permissions.UPDATE +
AccountSasConstants.Permissions.PROCESS +
AccountSasConstants.Permissions.WRITE +
AccountSasConstants.Permissions.DELETE +
AccountSasConstants.Permissions.LIST,
Protocols: AccountSasConstants.Protocols.HTTPSORHTTP,
Start: startDate,
Expiry: expiryDate
}
};
return sharedAccessPolicy;
};
var sharedAccessSignature = azure.generateAccountSharedAccessSignature(environmentAzureStorageAccount, environmentAzureStorageAccessKey, getPolicyWithFullPermissions );
Then you could use the account SAS to list the account's container.
Result:
More details about the difference between service sas and account sas, you could refer to this article.
I'm making a request but it doesn't seem to work. If I copy code into my browser it works good, but in my console it shows up this :
{
"status" : "success",
"data" : {
"error_message" : "API access enabled, but unable to verify two-factor authentication code. If you need help with this, please contact support#bitskins.com."
}
}
What am I doing wrong? It's based on two-factor authentication that as I said works good while printing the url itself and when i'm copying it into my browser.
var url = 'https://bitskins.com/api/v1/get_item_price/?api_key='+bitskins.apikey+'&code='+bitskins.code+'&names='+encodeURIComponent(items[i].market_hash_name)+'&delimiter=!END!';
console.log(url);
request(url, function (error, response, body) {
if (!error) {
console.log(body)
}
});
In case you want, here is my api key module to generating it (api key deleted for security)
var TOTP = require('onceler').TOTP;
//Create a TOTP object with your secret
var totp = new TOTP('deleted');
// print out a code that's valid right now
// console.log(totp.now());
var code = totp.now();
module.exports = {
code: code,
apikey: 'deleted'
}
Founder of BitSkins, Inc. here. You need to have the following:
1) Your API Key
2) Your Secure Access Secret
You see the Secret when you enable Secure Access. If you do not have this, just disable/re-enable Secure Access and note the Secret down. The TOTP code you generate is with that Secret. Generate the TOTP code right before every API call and you'll be fine.
I think it should work. For me it works fine.
var API_KEY = ''; //It is very important
var SECRET_KEY = ''; //It is very important
var totp = new TOTP(SECRET_KEY);
var code = totp.now();
var options = {
url: 'https://bitskins.com/api/v1/get_item_price',
form: {
'api_key': API_KEY,
'names': 'Tec-9%20%7C%20Sandstorm%20(Minimal%20Wear)',
'delimiter': '!END!',
'code': code
}
};
function callback(error, response, body) {
if (!error) {
var info = JSON.parse(body);
console.log(info);
}
}
request.post(options, callback);
What npm package do you use to create 2FA code? I'm using "onceler" from example but I think it creates wrond codes. Here is my code:
var API_KEY = ''; //correct key from settings page
var SECRET_KEY = ''; // correct key which I copied from form with QR code.
var totp = new TOTP("SECRET_KEY");
var code = totp.now();
This code doesn't equal code which I can see in my mobile device and with this code I get error message like in author's question. But if I put code from my mobile in programm code - it works fine. So what package should I use to get correct codes?
I'm trying to send data between an Android application created with Cordova and an application running on a Windows machine; the application on the Windows machine requires TCP protocol. I've worked with Cordova before, but I haven't used many plugins for Cordova--and therefore I've had difficulty setting up plugins--and socket programming isn't familiar ground for me.
Anywho, I read that I could use chrome.socket with Cordova somewhere, so I've tried doing that, but I'm only receiving errors indicating that "chrome" is undefined.
I first installed the plugin via command line: cordova plugin add org.chromium.socket
It then appeared in the plugins directory of my Cordova application.
Then, I included the following code in my application:
var dataString = "Message to send";
var data = new Uint8Array(dataString.length);
for (var i = 0; i < data.length; i++) {
data[i] = dataString.charCodeAt(i);
}
try {
chrome.socket.create("tcp", function(createInfo) {
var socketId = createInfo.socketId;
try {
chrome.socket.connect(socketId, hostname, port, function(result) {
if (result === 0) {
chrome.socket.write(socketId, data, function(writeInfo) {
chrome.socket.read(socketId, 1000, function(readInfo) {
});
});
}
else
{
alert("CONNECT FAILED");
}
});
}
catch (err)
{
alert("ERROR! " + err);
}
});
}
catch (err)
{
alert("ERROR! " + err);
}
I get the error alert every time, because chrome.socket is undefined; this makes me think that I did not set this up correctly. At any rate, any advice would be greatly appreciated.