Push Notification in Blackberry - blackberry

Hi I want to have push notification in blackberry.I have already googled for the answer and got the Push Services Guide.i read this guide .This guide does not give any code information for the client side application.It talks push server sdk and its installation but does not give any idea of how to write client code to have push notification. So is there any sample code that provides the concept of push notification.
thanks

For client side code, refer this link Blackberry push.
Use this as server side code -
<?php
ini_set('display_errors','1');
error_reporting(E_ALL);
// APP ID provided by RIM
$appid = '';
// Password provided by RIM
$password = '';
//Deliver before timestamp
$deliverbefore = gmdate('Y-m-d\TH:i:s\Z', strtotime('+15 minutes'));
//An array of address must be in PIN format or "push_all"
$addresstosendto[] = 'push_all';
$addresses = '';
foreach ($addresstosendto as $value) {
$addresses .= '<address address-value="' . $value . '"/>';
}
// create a new cURL resource
$err = false;
$ch = curl_init();
$messageid = microtime(true);
$data = '--mPsbVQo0a68eIL3OAxnm'. "\r\n" .
'Content-Type: application/xml; charset=UTF-8' . "\r\n\r\n" .
'<?xml version="1.0"?>
<!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2.1//EN" "http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd">
<pap>
<push-message push-id="' . $messageid . '" deliver-before-timestamp="' . $deliverbefore . '" source-reference="' . $appid . '">'
. $addresses .
'<quality-of-service delivery-method="confirmed"/>
</push-message>
</pap>' . "\r\n" .
'--mPsbVQo0a68eIL3OAxnm' . "\r\n" .
'Content-Type: text/plain' . "\r\n" .
'Push-Message-ID: ' . $messageid . "\r\n\r\n" .
stripslashes('This is my message') . "\r\n" .
'--mPsbVQo0a68eIL3OAxnm--' . "\n\r";
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "https://pushapi.eval.blackberry.com/mss/PD_pushRequest");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_USERAGENT, "Hallgren Networks BB Push Server/1.0");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $appid . ':' . $password);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: multipart/related; boundary=mPsbVQo0a68eIL3OAxnm; type=application/xml", "Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2", "Connection: keep-alive"));
// grab URL and pass it to the browser
echo $xmldata = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
//Start parsing response into XML data that we can read and output
$p = xml_parser_create();
xml_parse_into_struct($p, $xmldata, $vals);
$errorcode = xml_get_error_code($p);
if ($errorcode > 0) {
echo xml_error_string($errorcode);
$err = true;
}
xml_parser_free($p);
echo 'Our PUSH-ID: ' . $messageid . "<br \>\n";
if (!$err && $vals[1]['tag'] == 'PUSH-RESPONSE') {
echo 'PUSH-ID: ' . $vals[1]['attributes']['PUSH-ID'] . "<br \>\n";
echo 'REPLY-TIME: ' . $vals[1]['attributes']['REPLY-TIME'] . "<br \>\n";
echo 'Response CODE: ' . $vals[2]['attributes']['CODE'] . "<br \>\n";
echo 'Response DESC: ' . $vals[2]['attributes']['DESC'] . "<br \> \n";
} else {
echo '<p>An error has occured</p>' . "\n";
echo 'Error CODE: ' . $vals[1]['attributes']['CODE'] . "<br \>\n";
echo 'Error DESC: ' . $vals[1]['attributes']['DESC'] . "<br \>\n";
}
?>

Related

Sending voice to Telegram through PHP app

Here is the situation.
I have an Android app, which can send voice file with HTTP POST anywhere I specify. Also I would like to download these voice files to Telegram bot automatically. I wrote a PHP bot and I can accept and translate to Telegram any fields that come in said POST. One thing I miss is the file itself.
I don't know how to "say" to telegram API I download a file.
So what do I have: present file in $_FILE stream (I can read the name of it), I throw it in sendVoice function as $voice, also I do know I have to use simple multipart/form-data POST method to send file.
My question is: is it possible to use something but CURL to POST right from PHP? If not, what am I missing then? Other methods I use are messages and photo sending via file_get_contents(), I wonder if it's still suitable for voice file?
Here is the code I have now, which I found somewhere (I have 0 cURL knowledge):
function sendVoice($chat_id, $voice, $caption) {
$boundary = uniqid();
$delimiter = '-------------' . $boundary;
$fields = array(
"chat_id" => $chat_id,
"caption" => $caption
);
$post_data = build_data_files($boundary, $fields, $voice);
$ch = curl_init($GLOBALS['api'].'/sendVoice');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
//"Authorization: Bearer $TOKEN",
"Content-Type: multipart/form-data; boundary=" . $delimiter,
"Content-Length: " . strlen($post_data))
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_exec($ch);
curl_close($ch);
}
function build_data_files($boundary, $fields, $files){
$data = '';
$eol = "\r\n";
$delimiter = '-------------' . $boundary;
foreach ($fields as $name => $content) {
$data .= "--" . $delimiter . $eol
. 'Content-Disposition: form-data; name="' . $name . "\"".$eol.$eol
. $content . $eol;
}
foreach ($files as $name => $content) {
$data .= "--" . $delimiter . $eol
. 'Content-Disposition: form-data; name="' . $name . '"; filename="' . $name . '"' . $eol
//. 'Content-Type: image/png'.$eol
. 'Content-Transfer-Encoding: binary'.$eol
;
$data .= $eol;
$data .= $content . $eol;
}
$data .= "--" . $delimiter . "--".$eol;
return $data;
}
This was actally much easier. Since we have file present in $_FILES, we can do all of the cURL in just sendVoice() function without any hassle of rebinding boundaries or specifying content types.
Here is the final code which worked for me:
function sendVoice($chat_id, $voice, $caption) {
$filepath = realpath($_FILES['file']['tmp_name']);
$post_data = array(
'chat_id' => $chat_id,
'voice' => new CURLFile($filepath),
'caption' => $caption
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GLOBALS['api'].'/sendVoice');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_exec($ch);
curl_close($ch);
}
That will download an .OGG file as voice message (because I do not want any files to appear in my music player). Later it is possible to just add more fields such as duration in $post_data array and Telegram would eat them accordingly.

push notification not working on ios 9 devices

Ever since iOS 9.0 - 9.2 was implemented users of my app that are using it no longer receive push notifications.
My code works fine when sending to Android devices as I am separating the two platforms (iOS and Android) into 2 different arrays and processing them accordingly.
The result from the APNs server does not return an error at all.
Are there known issues documented on what could have changed on the push notification server? If so please provide links to them.
Below is the code that i am using to send the push notifications(PHP):
public function send_notification($message) {
$title = 'My App';
$platform = '';
$users = mysql_query("select * FROM push_devices");
$no_of_users = mysql_num_rows($users);
// Initialize the array for storing the platform specific tokens
$iOSusers = array();
$androidUsers = array();
if($no_of_users > 0){
// Seperate the tokens
while ($row = mysql_fetch_array($users)) {
$platform = $row['platform'];
if($platform == 'Android' || $platform == 'android'){
// Add to android list
$androidUsers[] = $row['push_id'];
}
if($platform == 'iOS' || $platform == 'ios'){
$iOSusers[] = $row['push_id'];
}
}// endwhile
}
if(!empty($androidUsers)){
$messageAndTitle = array(
'message' => $message,
'title' => $title
);
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $androidUsers,
'data' => $messageAndTitle,
);
$headers = array(
'Authorization: key=' . ***GOOGLE_API_KEY***,
'Content-Type: application/json'
);
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSLVERSION, 3);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
// Increase the timeout
curl_setopt($ch, CUROPT_CONNECTTIMEOUT, 1000);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
echo $result . '<br/>';
// close the connection
curl_close($ch);
}
// Handle iOS push
if(!empty($iOSusers)){
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', **PUSH_CERT_FILE**);
stream_context_set_option($ctx, 'ssl', 'passphrase', **PUSH_PARAPHRASE**);
// Open a connection to the APNS server
$fp = stream_socket_client(
PUSH_SERVER, $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
//echo 'Connected to APNS' . PHP_EOL;
$badgeCount = 2;
$badge = (int)$badge;
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'badge' => $badge,
'sound' => 'default'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
//Note: $deviceToken is an array for android push
foreach ($iOSusers as $token) {
$msg = chr(0) . pack('n', 32) . pack('H*', $token) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
//echo 'Device token: ' .$deviceToken[0];
if (!$result)
echo 'Message not delivered' . PHP_EOL . $token . '<br/>';
else
echo 'Message successfully delivered' . PHP_EOL . $token . '<br/>';
}
fclose($fp);
} // iOS
}
There are hundreds of thread over the Internet about notifications not working on iOS 9, but I think that the problem is server-side.
I noticed an issue with Push notifications on my iPhone 5 (iOS 7.1.2) in the last couple of weeks, and I discovered that the problem is originating from the Apple Push Notification Server.
I am now receiving about 10% of notifications on Whatsapp and 0% on Facebook Messenger, but I am sure other apps are involved too.
With another app (Bspotted), installed more recently, I'm receiving 100% of notifications.
So I've downloaded the profile PersistentConnectionLogging.mobileconfig in order to enable logging for push notifications.
Turns out that the Apple Push Server is sending notifications with TOKEN (null), so of course the apps can't handle them:
copyTokenForDomain push.apple.com (null)
Moreover, it seems that all notifications I received with token null (on Whatsapp and Messenger) came from Android devices. I received a message on Whatsapp from an iPhone, and it was the first notification I received in two weeks.
Maybe is a coincidence, because now I managed to receive 10% of notifications on Whatsapp also from Android devices (for two weeks it was 0%).
I tried all of this:
Reset in-app notifications
Reset iOS app notifications
Reinstall the app
Reset iOS network configuration
Forced iPhone restart
Uninstall the app, set the date 2 days forward, reinstall the app (in order to force the app to ask for permission on notifications)
I hope this will help.
Best Regards

Can I schedule a Jenkins Build without CRON or REST API?

To schedule a build in Jenkins I need to add a "cron" parameter then all works well. But I have a lot of donkey users and they didn't know how to schedule with cron.
Is there a way to schedule a Jenkins build without the API itself (http://jenkins/job/jobname/build?delay=4000 I don't want this) or cron? Maybe some Jenkins Plugin...
Solved it this way:
<?php
if($_POST) {
$fields = array(
"POST_PARAMETERS" => $_POST['params']
);
$delay = (int) $_POST['delay'];
$username = "my_username";
$password = "my_password";
$token = "MY_JENKINS_TOKEN_NAME";
$job = "JOB_NAME";
$url = "http://jenkins_host/jenkins/job/".$job."/buildWithParameters?token=".$token."&delay=".$delay;
$process = curl_init($url);
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($process, CURLOPT_POST, count($fields));
$return = curl_exec($process);
echo http_build_query($fields);
echo curl_error($process);
curl_close($process);
die;
}
?>
I give the JOB_NAME and the build parameters and it work well. cURL did the trick for me with the authorization token.
Thanks everyone who tried to help.

Batch / multiple iOS Push Notification code - works for 2 devices, but not for 100

The following code works fine if the number of devices I send to is 2 - i.e., they both receive the push notifications. But if I raise that limit to 100, no push notifications are received.
I have read up on this and it looks like I am sending the batch notifications correctly (i.e., multiple requests via a single connection); the timeout of the connection is set nice and high (60 seconds); the output of the code all looks in order; nothing in the apache error log, so I don't see where the problem is.
My customer's getting really hacked off. Can anyone help??
function sendIosPushes() {
$payload['aps'] = array('alert' => pushMessage, 'badge' => badgeNumber, 'sound' => 'default');
$payload = json_encode($payload);
//$statement = "SELECT * FROM push_ios WHERE device_token = 'device token of my iphone" OR device_token = 'device token of my ipod'; //works selecting my two devices from table
$statement = "SELECT * FROM push_ios"; //doesn't work when selecting all devices from table
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', apnsCert);
$connectTimeout = 60;
$apns = stream_socket_client('ssl://' . apnsHost . ':' . apnsPort, $error, $errorString, $connectTimeout, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $streamContext);
$numDevices = 0;
$numRequestsSent = 0;
$result = mysql_query($statement);
while ($row = mysql_fetch_assoc($result)) {
$numDevices++;
try {
$deviceToken = $row['device_token'];
//$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', $deviceToken) . chr(0) . chr(strlen($payload)) . $payload;
$apnsMessage = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload; //from http://stackoverflow.com/questions/1642411/sending-multiple-iphone-notifications
$fwriteRes = fwrite($apns, $apnsMessage, strlen($apnsMessage));
echo "Push sent to " . $deviceToken . "<br />\n";
$numRequestsSent++;
}
catch(Exception $e) {
echo "1. Exception: " . $e->getMessage() . "<br />\n";
}
}
fclose($apns);
if ($error != 0 || (isset($errorString) && strlen($errorString) > 0 )) {
echo "ERROR: " . $error . " - ". $errorString . "<br />\n";
}
return $numDevices . " iOS devices. " . $numRequestsSent . " requests sent.";
}
You probably have some invalid device tokens in your DB.
In case of an invalid device token, Apple will return an error response if you use the newer binary format (in which you send a message id and message expiry), which you don't. In your case an invalid token will simply close the socket, but you'll have no way to know which message caused the problem.
You should read about error checking here. You should read about the format here.

How do I get a LinkedIn request token?

Hey I'm trying to use LinkedIn's OAuth in PHP. I'm stuck at the first step of getting a request token. All I know is you post some values to their server and get your token back. So i post the documented args to 'https://api.linkedin.com/uas/oauth/requestToken' and I get slapped with a 400 error.
here's the request:
$postArr = array();
//$postArr["oauth_callback"] = ""; idk they said this was optional...
$postArr["oauth_consumer_key"] = "ForBritishEyesOnly"; //is this the application secret key or the api key?
$postArr["oauth_nonce"] = "UltraRandomNonceFTW";
$postArr["oauth_timestamp"] = time();
$postArr["oauth_signature_method"] = "HMAC-SHA1"; //lolwut
$postArr["oauth_version"] = "1.0";
$params = array('http'=>array('method'=>'post','content'=>http_build_query($postArr)));
$context = stream_context_create($params);
$stream = file_get_contents('https://api.linkedin.com/uas/oauth/requestToken', false, $context);
I don't think my POST args are correct but ANY help is very appreciated -- I just don't want resort to use someone else's library to solve this.
-------EDIT: ATTEMPT 2 per James' input ---------
ok so here im making a call to the test link you sent me. i'm actually able to get a response back, but it doesnt like my signature (big surprise, i know). So just how bad did I screw up the encryption?
//setup GET args
$url = "http://term.ie/oauth/example/request_token.php?";
$url .= "oauth_version=1.0&";
$url .= "oauth_nonce=" . rand(0, 100000) . "&";
$url .= "oauth_timestamp=" . time() . "&";
$url .= "oauth_consumer_key=key&";
$url .= "oauth_signature_method=HMAC-SHA1&";
//encrypt the request according to 'secret'
$sig = urlencode(base64_encode(hash_hmac("sha1", $url, "secret")));
//append the url encoded signature as the final GET arg
$url .= "oauth_signature=" . $sig;
//do it to it
echo file_get_contents($url);
EDIT by James
Try:
//setup GET args
$url = "http://term.ie/oauth/example/request_token.php?";
$url .= "oauth_consumer_key=key&";
$url .= "oauth_nonce=" . rand(0, 100000) . "&";
$url .= "oauth_signature_method=HMAC-SHA1&";
$url .= "oauth_timestamp=" . time() . "&";
$url .= "oauth_version=1.0&";
I'm on cloud nine. Decided to revisit this problem and got it to work. Here is some very bare bones PHP to build a token request for LinkedIn (it outputs an anchor tag)
<?php
$endpoint = "https://api.linkedin.com/uas/oauth/requestToken";
$key = "YourAPIKey";
$secret = "YourAPISecret";
$params = array(
"oauth_version" => "1.0",
"oauth_nonce" => time(),
"oauth_timestamp" => time(),
"oauth_consumer_key" => $key,
"oauth_signature_method" => "HMAC-SHA1"
);
function SortedArgumentString($inKV)
{
uksort($inKV, 'strcmp');
foreach ($inKV as $k => $v)
$argument[] = $k."=".$v;
return implode('&', $argument);
}
$baseString = "GET&" . urlencode($endpoint) . "&" . urlencode(SortedArgumentString($params));
$params['oauth_signature'] = urlencode(base64_encode(hash_hmac('sha1', $baseString, $secret."&", TRUE)));
echo "<a href=\"" . $endpoint . "?" . SortedArgumentString($params) . "\">Get Token<a/><br/>";
?>
oauth_consumer_key is a value that LinkedIn should have assigned to your app. Did you register with them?
oauth_nonce should be different for each request to prevent replay-attacks.
If you're using HMAC-SHA1 you'll need to add the oauth_signature field yourself. Creating the signature manually is a total PITA.
There's also a lot of Base64 encoding to do (with the added bonus of some special OAuth quirks). I suggest you read the spec.
There is a test server and client at this link. It's quite useful when you're struggling to get the protocol right.

Resources