huawei api sms documentation - api

any one have the huawei SMS API documentation? (api/sms/sms-list)
I need to know how to talk with this API to get the SMS list:
It must be something like this:
<request>
<PageIndex>1</PageIndex>
<ReadCount>20</ReadCount>
<BoxType>1</BoxType>
<SortType>0</SortType>
<Ascending>0</Ascending>
<UnreadPreferred>0</UnreadPreferred>
</request>
But I got only a error code 100003 as answer. And I don't what that mean.
Thank You,
michel

I have done this on an Huawei E5221 with Python. The error you are getting is because you are not authenticated and need to login first. Then the list can be retrieved.
Also note that all API requests are POST's and not GET's.
Method to login:
def LoginToSMSGateway(sms_gateway_ip, username, password):
api_url = '/api/user/login'
post_data = '<request><Username>'+username+'</Username><Password>'+ base64.b64encode(password) +'</Password>'
r = requests.post(url='http://' + sms_gateway_ip + api_url, data=post_data)
if r.status_code == 200:
result = False
root = ET.fromstring(r.text)
for results in root.iter('response'):
if results.text == 'OK':
result = True
return result
else:
return False
Method to retrieve SMS List (The method will turn the XML results into a Python list of SMS's):
def GetSMSList(sms_gateway_ip):
class SMS:
Opened = False
Message = ''
api_url = '/api/sms/sms-list'
post_data = '<?xml version="1.0" encoding="UTF-8"?><request><PageIndex>1</PageIndex><ReadCount>20</ReadCount><BoxType>1</BoxType><SortType>0</SortType><Ascending>0</Ascending><UnreadPreferred>0</UnreadPreferred></request>'
headers = {'Referer': 'http://' + sms_gateway_ip + '/html/smsinbox.html'}
r = requests.post(url='http://' + sms_gateway_ip + api_url, data=post_data, headers=headers)
root = ET.fromstring(r.text)
resultsList = list()
for messages in root.iter('Messages'):
for message in messages:
sms = SMS()
sms.Message = message.find('Content').text
sms.Opened = False if message.find('SmsType').text == '1' else True
resultsList.append(sms)
return resultsList
To use it(The IP and credentials are the default values and need to be secured.) :
if LoginToSMSGateway('192.168.1.1', 'admin', 'admin'):
print 'Logged in.'
smsList = GetSMSList('192.168.1.1')
for sms in smsList:
print sms.Message

Since this the subject has been posted I think the API has changed a bit.
To get the SMS list, no need to login but you do need to get a sessionID and the corresponding Token. You can use that Method to get them.
def GetTokenAndSessionID(sms_gateway_ip):
url = '/html/smsinbox.html'
r = requests.get(sms_gateway_ip + url)
Setcookie = r.headers.get('set-cookie')
sessionID = Setcookie.split(';')[0]
token = re.findall(r'"([^"]*)"', r.text)[2]
return token, sessionID
And then the Method to get the sms list (It's using the first Method to wrap the sessionID and the Token in the headers).
def GetSmsList(sms_gateway_ip):
class SMS:
Opened = False
Message = ''
url = '/api/sms/sms-list'
token,sessionID = GetTokenAndSessionID(sms_gateway_ip)
post_data = '<request><PageIndex>1</PageIndex><ReadCount>20</ReadCount><BoxType>2</BoxType><SortType>0</SortType><Ascending>0</Ascending><UnreadPreferred>0</UnreadPreferred></request>'
headers = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'__RequestVerificationToken': token,
'Cookie': sessionID
}
r = requests.post(sms_gateway_ip + url, data = post_data, headers=headers)
root = ET.fromstring(r.text)
resultsList = list()
for messages in root.iter('Messages'):
for message in messages :
sms = SMS()
sms.Message = message.find('Content').text
sms.Opened = False if message.find('SmsType').text == '1' else True
resultsList.append(sms)
To use it you just need to call it with the ip of the sms gateway: 192.168.8.1
GetSmsList(sms_gateway_ip)

Similar Code in Java hereunder using Apache HTTP Client classes
CloseableHttpClient httpclient = HttpClients.createDefault();
// 1. Have apache HTTPClient manage the cookie containing the SessionID
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
// 2. Extract the token
String token = "";
HttpGet hget = new HttpGet("http://192.168.8.1/html/smsinbox.html");
CloseableHttpResponse getRespo = httpclient.execute(hget, httpContext);
try {
StatusLine statusLine = getRespo.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
HttpEntity entity = getRespo.getEntity();
if (entity == null) {
throw new ClientProtocolException("Get response contains no content");
}
long len = entity.getContentLength();
StringTokenizer st = null;
if (len != -1 && len > 250) {
st = new StringTokenizer(EntityUtils.toString(entity).substring(0, 250), "\"");
}
int i = 1;
while (st != null && st.hasMoreTokens()) {
if (i++ == 10) {
token = st.nextToken();
break;
} else {
st.nextToken();
}
}
} finally {
getRespo.close();
}
System.out.println("Token: " + token);
// 3. Get the SMS messages using the Token
HttpPost hpost = new HttpPost("http://192.168.8.1/api/sms/sms-list");
String xmlRequest = "<request><PageIndex>1</PageIndex><ReadCount>1</ReadCount><BoxType>1</BoxType><SortType>0</SortType><Ascending>0</Ascending><UnreadPreferred>1</UnreadPreferred></request>";
StringEntity reqEntity = new StringEntity(xmlRequest);
reqEntity.setContentType("text/xml");
hpost.setEntity(reqEntity);
hpost.addHeader("__RequestVerificationToken", token);
CloseableHttpResponse postRespo = httpclient.execute(hpost, httpContext);
try {
StatusLine statusLine = postRespo.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
HttpEntity entity = postRespo.getEntity();
if (entity == null) {
throw new ClientProtocolException("Response contains no content");
}
System.out.println(EntityUtils.toString(entity));
//Your further processing here.
} finally {
postRespo.close();
}

Related

can I generate listenKey binance in app script

I try a lot of think to create listenKey in app script but nothing work.
the binance URL: https://binance-docs.github.io/apidocs/spot/en/#user-data-streams
this is my code:
function generated_key() {
var aPIKEY = '*****'; // key.
var secretKey = '****'; // Secret key.
var api = "/api/v3/userDataStream";
var timestamp = Number(new Date().getTime()).toFixed(0);
var string = "timestamp="+timestamp;
var baseUrl = "https://api1.binance.com";
var signature = Utilities.computeHmacSha256Signature(string, secretKey);
signature = signature.map(function(e) {
var v = (e < 0 ? e + 256 : e).toString(16);
return v.length == 1 ? "0" + v : v;
}).join("");
var query = "?" + string + "&signature=" + signature;
var params = {
'method': 'POST',
'headers': {'X-MBX-APIKEY': aPIKEY},
'muteHttpExceptions': true
};
var data = UrlFetchApp.fetch(baseUrl + api + query, params);
var obj = JSON.parse(data); // To JSON
Logger.log(obj)
}
I get the result error: {code=-1101.0, msg=Too many parameters; expected '0' and received '2'.}
any suggestion to do it.

Django channels without redis

I have a django app based on this tutorial that works perfectly. It uses Redis in the Channel layers
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
The problem I have is that my web hosting provider will not allow Redis (unless I pay ££££).
Every example that I can find uses Redis in this role. Is there an alternative I could use?
there are a few options.
you can run your channel layer on a different service to were the main instance runs. AWS ElastiCache or many other redis hosts out there.
There is also a RabbitMQ channel layer but if your hosting provider charges a lot for reddis i expect they will also charge a lot for this ... https://github.com/CJWorkbench/channels_rabbitmq/
It turned out that channels is a non-starter on an affordable web-hosting platform. So I reverted to using Ajax and long polling. My application is based on this Django Tutorial.
models.py
class Message(models.Model):
room_name = models.CharField(null=False, blank=False, max_length=50)
sender = models.CharField(null=False, blank=False, max_length=50, default='Sender username')
datetime = models.DateTimeField(null=True, auto_now_add=True)
type = models.IntegerField(null=True, blank=True)
text = models.CharField(null=False, blank=False, max_length=250, default='message text')
context = models.TextField(null=True, blank=True)
urls.py
urlpatterns = [
path('<str:partner_pk>/check-message', views.CheckMessage.as_view(), name="check-message"),
path('<str:partner_pk>/send-message/<str:chat_text>', views.SendMessage.as_view(), name="send-message"),
]
views.py
class CheckMessage(View):
"""Duo check message."""
def get(self, request, partner_pk):
"""Render the GET request."""
pair, room_name = sort_pair(partner_pk, request.user.pk)
partner = User.objects.get(pk=partner_pk)
profile = get_object_or_404(Profile, user=request.user)
message = Message.objects.filter(room_name=room_name, sender=partner.username).earliest('datetime')
context = {'type': -1}
context = json.loads(message.context)
context['sender'] = message.sender
context['datetime'] = message.datetime
context['message_type'] = message.type
context['text'] = message.text
context['seat'] = profile.seat
message.delete()
return JsonResponse(context, safe=False)
class SendMessage(View):
def get(self, request, partner_pk, chat_text):
message_type = app.MESSAGE_TYPES['chat']
send_message(request, partner_pk, message_type, text=chat_text, context={})
return JsonResponse({}, safe=False)
chat.js
window.setInterval(checkMessage, 3000);
function checkMessage () {
$.ajax(
{
type:"GET",
url: "check-message",
cache: false,
success: function(message) {
processMessage(message);
}
}
)
}
// Take action when a message is received
function processMessage(context) {
switch (context.message_type) {
case 0:
sendMessage(context)
functionOne()
break;
case 1:
sendMessage(context)
functionTwo()
break;
case 2:
sendMessage(context)
functionThree()
break;
}
}
// Send a message to chat
function sendMessage (context) {
if (context.sender != username) {
var messageObject = {
'username': context.sender,
'text': context.text,
};
displayChat(context);
}
}
// Display a chat message in the chat box.
function displayChat(context) {
if (context.text !== '') {
var today = new Date();
var hours = pad(today.getHours(), 2)
var minutes = pad(today.getMinutes(), 2)
var seconds = pad(today.getSeconds(), 2)
var time = hours + ":" + minutes + ":" + seconds;
var chat_log = document.getElementById("chat-log");
chat_log.value += ('('+time+') '+context.sender + ': ' + context.text + '\n');
chat_log.scrollTop = chat_log.scrollHeight;
}
}
//pad string with leading zeros
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
// Call submit chat message if the user presses <return>.
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function (e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
// Submit the chat message if the user clicks on 'Send'.
document.querySelector('#chat-message-submit').onclick = function (e) {
var messageField = document.querySelector('#chat-message-input'), text = messageField.value, chat_log = document.getElementById("chat-log");
context = {sender: username, text: messageField.value}
displayChat(context)
sendChat(messageField.value)
chat_log.scrollTop = chat_log.scrollHeight;
messageField.value = '';
};
// Call the send-chat view
function sendChat(chat_text) {
$.ajax(
{
type:"GET",
url: "send-message/"+chat_text,
cache: false,
}
)
}

Missing user_metadata in userInfo of auth0

For authentication I am using Auth0 AuthenticationApi. In Account Controller, I need to fetch the user_metadata but it's missing. Any alternative to fetch the user_metadata?
AuthenticationApiClient client = new AuthenticationApiClient(new Uri($"https://{_auth0Options.Domain}/"));
var authenticateResponse = await client.GetTokenAsync(new ResourceOwnerTokenRequest
{
ClientId = _auth0Options.ClientId,
ClientSecret = _auth0Options.ClientSecret,
Scope = "openid",
Realm = _auth0Options.Connection,
Username = vm.EmailAddress,
Password = vm.Password
});
var user = await client.GetUserInfoAsync(authenticateResponse.AccessToken);
if (user.UserMetadata != null)
{
// Giving error...any alternative to access the userMetaData ?
}
Yes, as far as I see it now, the legacy call still works. However, I don't have a non-legacy solution yet :(
using (var client = GetClient())
{
var jObject = new JObject(new JProperty("id_token", id_token));
var response = await client.PostAsJsonAsync("tokeninfo", jObject);
if (response.IsSuccessStatusCode)
{
var userProfileJson = JObject.Parse(await response.Content.ReadAsStringAsync());
retVal.user_id = userProfileJson.Value<string>("user_id");
retVal.email = userProfileJson.Value<string>("email");
retVal.user_name = userProfileJson.Value<string>("nickname");
if (userProfileJson.Value<string>("created_at") != null)
{
retVal.created_at = userProfileJson.Value<DateTime>("created_at");
}
var exists = userProfileJson.TryGetValue("user_metadata", out JToken meta);

QuickBlox create user issue (bad request) without any error message

I want to create an user using the rest API. Rest API returns an error (bad request), when I made the request. There are not any other error messages.
JSON:
Required Parameters : login, password, email
http://quickblox.com/developers/Users#API_User_Sign_Up
{
"user":
{
"login":"user123456",
"password":"User11#2015",
"email":"xxx#ccc.com.tr",
"blob_id":null,
"external_user_id":null,
"facebook_id":null,
"twitter_id":null,
"full_name":null,
"phone":null,
"website":null,
"custom_data":null,
"tag_list":null
}
}
Rest API Result:
Response Status Code : BadRequest.
Response Content is empty. No error message.
I do not understand the error. Can you help me?
Code :
public NotificationUser CreateUser(string token, NotificationUser notificationUser)
{
var user = new QuickbloxUser()
{
email = notificationUser.Email,
password = notificationUser.Password,
login = notificationUser.Login
};
var jsonBody = JsonConvert.SerializeObject(user);
var request = new RestRequest("users.json", Method.POST);
request.AddHeader("QB-Token", token);
request.AddParameter("user", jsonBody);
var response = _restClient.Execute<RootUser<QuickbloxUserResponse>>(request);
if (response.StatusCode == HttpStatusCode.OK)
{
notificationUser.Id = response.Data.user.id;
notificationUser.Email = response.Data.user.email;
notificationUser.Login = response.Data.user.login;
return notificationUser;
}
return null;
}

azure active directory graph REST api call through SP.WebRequestInfo on SharePoint Online

Trying to make a REST call through SharePoint's SP.WebRequestInfo.
I'm getting the error "The remote server returned the following error while establishing a connection - 'Unauthorized'." trying to call https://graph.windows.net/[Client]/users?api-version=2013-11-0.
I've successfully retrieved a access token.
Can you help me out why i'm getting this error?
Here is the code i'm using:
var url = "https://graph.windows.net/xxx/users/?api-version=2013-11-08";
var context = SP.ClientContext.get_current();
var request = new SP.WebRequestInfo();
request.set_url(url);
request.set_method("GET");
request.set_headers({
"Authorization": token.token_type + " " + token.access_token,
"Content-Type": "application/json"
});
var response = SP.WebProxy.invoke(context, request);
context.executeQueryAsync(successHandler, errorHandler);
function successHandler() {
if (response.get_statusCode() == 200) {
var responseBody = JSON.parse(response.get_body());
deferred.resolve(responseBody);
} else {
var httpCode = response.get_statusCode();
var httpText = response.get_body();
deferred.reject(httpCode + ": " + httpText);
}
}
The code for retrieving the token is:
this.getToken = function (clientId, clientSecret) {
var deferred = $q.defer();
var resource = "https://graph.windows.net";
var formData = "grant_type=client_credentials&resource=" + encodeURIComponent(resource) + "&client_id=" + encodeURIComponent(clientId) + "&client_secret=" + encodeURIComponent(clientSecret);
var url = "https://login.windows.net/xxxxxx.onmicrosoft.com/oauth2/token?api-version=1.0";
var context = SP.ClientContext.get_current();
var request = new SP.WebRequestInfo();
request.set_url(url);
request.set_method("POST");
request.set_body(formData);
var response = SP.WebProxy.invoke(context, request);
context.executeQueryAsync(successHandler, errorHandler);
function successHandler() {
if (response.get_statusCode() == 200) {
var token = JSON.parse(response.get_body());
deferred.resolve(token);
} else {
var httpCode = response.get_statusCode();
var httpText = response.get_body();
deferred.reject(httpCode + ": " + httpText);
}
}
function errorHandler() {
deferred.reject(response.get_body());
}
return deferred.promise;
};
Erik, something is strange here - you are using the client credential flow from a JavaScript client - this reveals the secret issued to the client app to the user of the JS app.
The client credential flow also requires the directory admin to grant directory read permission to the client application - not sure if this was already configured - nevertheless it must only be used with a confidential client, not a public client like a JS app.
Azure AD does not yet implement the implicit_grant oauth flow using which a JS client app can acquire an access token on behalf of the user over redirect binding (in the fragment). This is a hugh-pro requirement that we're working on - stay tuned.