Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Push notifications isn´t working #1

Closed
jaullo opened this issue Jan 18, 2015 · 39 comments
Closed

Push notifications isn´t working #1

jaullo opened this issue Jan 18, 2015 · 39 comments
Assignees
Labels

Comments

@jaullo
Copy link
Owner

jaullo commented Jan 18, 2015

Push notifications are not working on android or IOS.

@jaullo jaullo added the bug label Jan 18, 2015
@jaullo
Copy link
Owner Author

jaullo commented Feb 11, 2015

First of all sorry for my English but I speak Spanish as my native language.
As you all know, spika is offered like an open source application with great features. But....precisely the most important features are not working and there are no support for the community (al most not for free).

So I decide to start a new project called Snappy.
The main idea is to correct these errors and add new features to the software, until we can release it on Google Play.

As u know notifications are not working, so we start solving this bug and here are the steps to make it work.

With this fix recent activities screen and notification ballon counter will start working. Of course the chats will reload automatically.

I should clarify that this fix does not solve the problem that notifications are not shown in status bar (i`m working on this)

So let's start

IOS PUSH NOTIFICATIONS SETUP
Please refer to this link
https://blog.serverdensity.com/how-to-build-an-apple-push-notification-provider-server-tutorial/

GOOGLE CLOUD MESSAGING SETUP (ANDROID)
1-Go to http://console.developers.google.com
2-Create a new Project
3-Nativgate to APIs & auth -> API [On] for (Google Cloud Messaging for Android) and (Google Maps Android API v2).
4-If you have eclipse go to (Windows -> Preferences -> Android -> Build) copy SHA1 fingerprint.
5- Go to APIs & auth -> Credentials (Create new key [Android key]) add your SHA1 fingerprint and your project name example:
45:B5:E4:6F:36:AD:0A:98:94:B4:02:66:2B:12:17:F2:56:26:A0:E0;com.snappy
6-Copy your Google Cloud Messaging project numer and go to /com/snappy/utils/Const.java in your android project and search the var PUSH_SENDER_ID = Project Number
7-Go to /config/init.php in your snappy backend(server) and set GCM_API_KEY = Project Number

BACKEND MODIFICATIONS (thanks to sbhaskar for his help)
If you have your push certificates & gcm api key correct, it works.

1-Replace "sendMessageToUser" method to this one on file src/Spika/Controllers/MessageController.php from line 165.

$controllers->post('/sendMessageToUser',
function (Request $request)use($app,$self) {

        $currentUser = $app['currentUser'];
        $messageData = $request->getContent();

        if(!$self->validateRequestParams($messageData,array(
            'to_user_id'
        ))){
            return $self->returnErrorResponse("insufficient params");
        }

        $messageDataArray=json_decode($messageData,true);


        $fromUserId = $currentUser['_id'];
        $toUserId = trim($messageDataArray['to_user_id']);

        if(isset($messageDataArray['body']))
            $message = $messageDataArray['body'];
        else
            $message = "";

        if(isset($messageDataArray['message_type'])){
            $messageType = $messageDataArray['message_type'];
        } else {
            $messageType = 'text';
        }

        $additionalParams = array();

        // emoticon message
        if(isset($messageDataArray['emoticon_image_url'])){
            $additionalParams['emoticon_image_url'] = $messageDataArray['emoticon_image_url'];
        }else{

            // search emoticon id 
            $emoticon = $app['spikadb']->getEmoticonByIdentifier($message);

            if(isset($emoticon['_id'])){
                $additionalParams['emoticon_image_url'] = ROOT_URL . "/api/Emoticon/{$emoticon['_id']}";                    
            }


        }

        // pitcure message
        if(isset($messageDataArray['picture_file_id'])){
            $additionalParams['picture_file_id'] = $messageDataArray['picture_file_id'];
        }
        if(isset($messageDataArray['picture_thumb_file_id'])){
            $additionalParams['picture_thumb_file_id'] = $messageDataArray['picture_thumb_file_id'];
        }

        // voice message
        if(isset($messageDataArray['voice_file_id'])){
            $additionalParams['voice_file_id'] = $messageDataArray['voice_file_id'];
        }

        // video message
        if(isset($messageDataArray['video_file_id'])){
            $additionalParams['video_file_id'] = $messageDataArray['video_file_id'];
        }

        // location message
        if(isset($messageDataArray['longitude'])){
            $additionalParams['longitude'] = $messageDataArray['longitude'];
        }
        if(isset($messageDataArray['latitude'])){
            $additionalParams['latitude'] = $messageDataArray['latitude'];
        }

        $result = $app['spikadb']->addNewUserMessage($messageType,$fromUserId,$toUserId,$message,$additionalParams);

        if($result == null)
             return $self->returnErrorResponse("failed to send message");

        $newMessageId = $result['id'];            

        // send async request
        //$self->doAsyncRequest($app,$request,"notifyNewDirectMessage",array('messageId' => $newMessageId));

        /************************/



    $message = $app['spikadb']->findMessageById($newMessageId);

    $app['monolog']->addDebug("----------- Message ID ".$newMessageId." and response ".var_dump($message)." ------------");

    // send push notification
    $fromUserId = $message['from_user_id'];
    $toUserId = $message['to_user_id'];

    $fromUser = $app['spikadb']->getUserById($fromUserId);
    $toUser = $app['spikadb']->getUserById($toUserId);
    $app['spikadb']->updateActivitySummaryByDirectMessage($message['to_user_id'],$message['from_user_id']);
    $pushnotificationMessage = $self->generatePushNotificationMessage($fromUser,$toUser);


    // send iOS push notification
    if(!empty($toUser['ios_push_token'])){
         $app['monolog']->addDebug("----------- Sending to {$toUser['ios_push_token']} via Apple  ------------");
        $body = array();
        $body['aps'] = array('alert' => $pushnotificationMessage, 'badge' => 0, 'sound' => 'default', 'value' => "");
        $body['data'] =array('from' => $fromUserId);
        $payload = json_encode($body);

        $app['sendProdAPN'](array($toUser['ios_push_token']),$payload);
        $app['sendDevAPN'](array($toUser['ios_push_token']),$payload);
    }


    // send Android push notification
    if(!empty($toUser['android_push_token'])){
         $app['monolog']->addDebug("----------- Sending to {$toUser['android_push_token']} via  Android ------------");
        $registrationIDs = array($toUser['android_push_token']);

        $fields = array(
                        'registration_ids' => $registrationIDs,
                        'data' => array( 
                                "message" => $pushnotificationMessage, 
                                "fromUser" => $fromUserId,
                                "fromUserName"=>$fromUser['name'],
                                "type" => "user", 
                                "groupId" => ""
                                ),
                       );

        $payload = json_encode($fields);
        $app['sendGCM']($payload,$app);
    }  



        /*********************/


        return json_encode($result);
    }

)->before($app['beforeApiGeneral'])->before($app['beforeTokenChecker']);

2-Add this new method on file src/Spika/Controllers/MessageController.php

function generatePushNotificationMessage($fromUser,$toUser){

$message = sprintf(DIRECTMESSAGE_NOTIFICATION_MESSAGE, $fromUser['name']);

return $message;

}

3-Save and restart your server.

Notifications are now working.

Good Luck!
Jason

@jaullo
Copy link
Owner Author

jaullo commented Feb 11, 2015

Did u follow the instructions?

@jaullo jaullo reopened this Feb 11, 2015
@jaullo
Copy link
Owner Author

jaullo commented Feb 13, 2015

I will upload the project on weekend!

@cyberbeast
Copy link

thank you! update here when you upload? :)

@kiranme
Copy link

kiranme commented Feb 17, 2015

Please send modified " MessageController.php" to my gmail account - kiranalright@gmail.com

@srshkmr
Copy link

srshkmr commented Feb 24, 2015

With this the Push notifications inside chat is working ?

@bafplus
Copy link
Contributor

bafplus commented Feb 24, 2015

Could you please privide the full source code of MessageController.php ?
You're instructions are not quite clear.
Posting the full code so one can just copy paste it complete would be great!

@bafplus
Copy link
Contributor

bafplus commented Feb 24, 2015

I'm stuck...
Using youre changes i got it partly working.

  • "New message" tab works, balloon is updated on new message
  • Still have to manualy reload the chat to see the new message
  • Sending from webinterface keeps hanging on reloading after sending message, have to manualy refresh to see own message. Messages send from device are reloaded.
  • Still no actual push messages (app doesent produce sound or message on new messages, Google api showes no messages send....

@jaullo
Copy link
Owner Author

jaullo commented Feb 24, 2015

Hello Bafplus, i will upload the code soon with the changes described above.
You're right, it works partially, at least the balloon, which does'nt work on the original version.

Are u using linux as your backend server?

Push notifications working at 100% are not so simple to implement, I'm working on it, but this requires changes over 7 different files and changes are not ready yet.
I'm doing this in my spare time :)

Similarly if anyone has developed a new feature you want to share, I'd like to see it.

@jaullo
Copy link
Owner Author

jaullo commented Feb 24, 2015

For now, u need to check AsyncTaskController.php in your server and change the validation for localhost and set your server public ip address

@bafplus
Copy link
Contributor

bafplus commented Feb 24, 2015

Hy @jaullo , thanks for the reply and you're great work so far. I'm a newby on android development so at this point i need point to point instructions. I was hoping that Spika would "work" that way, sadly it didnt so i'm very glad i found you're project. I figured to getting the push working you "only" have to setup the api key and put them in the according files since the code was already implemented...guess that is not the case. Having it working thus far is great already! Many kuddo's to you. If we can manage to get the google push working also then i am 100% sattisfied! I will be keeping my eye out at this project and if i can help in any way, please let me know. FYI, running server on Ubuntu 14.10 server.

@jaullo
Copy link
Owner Author

jaullo commented Mar 3, 2015

Hello people and good night!
I've uploaded the latest source code for android application that i'm using. As well as instructions to setup the changes for the backend to make it work.

This version is fully functionally. Howhever the push notifications isn't working, we found that the problem is from server side.

If some one wants to help me with development or be a tester. Please let me know.

Thanks

@bafplus
Copy link
Contributor

bafplus commented Mar 3, 2015

Hy Jaullo,
Thanks and thanks again for you're work this far!
I'm no coder, so i cant be of big help on that, but i am however willing to test.
I'm running a server on ubuntu 14.10.

@bafplus
Copy link
Contributor

bafplus commented Mar 3, 2015

Jaullo, Why not also put the server files on Ghithub?
That way changes to the server code are available.

@aloknnikhil
Copy link

The reason push notifications fail is the $apiKey actually has no key. Also, the gcm message configuration in broken.

Replace the sendGCM in PushNotificationProvider.php with this

function sendGCM($apiKey, $json, $app = null) {
// API access key from Google API's Console
define( 'API_ACCESS_KEY', '<insert your API key here' );

    $headers = array
    (
        'Authorization: key=' . API_ACCESS_KEY,
        'Content-Type: application/json'
    );

    $ch = curl_init();

    curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
            curl_setopt( $ch,CURLOPT_POST, true );
            curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers);
            curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
            curl_setopt( $ch,CURLOPT_POSTFIELDS, $json);
            curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );

    $result = curl_exec($ch );
    curl_close( $ch );

            return $result;
}

Don't make any other changes.

@aloknnikhil
Copy link

@aloknnikhil
Copy link

Works with the original Spika project. Haven't tried it with this.

@srshkmr
Copy link

srshkmr commented Mar 4, 2015

so @nikhil93uf without anychanges provided by @jaullo in this(snappy), only changing the PushNotificationProvider.php will fix the whole issue of no push notifications?

@aloknnikhil
Copy link

Yes. Remember to update your API key in the sendGCM function of the new PushNotificationProvider

@bafplus
Copy link
Contributor

bafplus commented Mar 4, 2015

What Type of key? Browser, server or android appliciation?

@aloknnikhil
Copy link

The browser and server key types, both work.

@bafplus
Copy link
Contributor

bafplus commented Mar 4, 2015

Replace with the key.

Van: naveedrocks1 [mailto:notifications@github.com]
Verzonden: woensdag 4 maart 2015 08:16
Aan: jaullo/Snappy
CC: bafplus
Onderwerp: Re: [Snappy] Push notifications isn´t working (#1)

do i need to replace GCM_API_Key with my browser api key?


Reply to this email directly or view it on GitHub #1 (comment) . https://github.com/notifications/beacon/AGIo2ufaLYCc6nHLhm1nSm9dgFaY01Joks5nxqimgaJpZM4DTytk.gif

@aloknnikhil
Copy link

Not the GCM_API_Key. In the new PushNotificationProvider, insert your api key where I marked

@bafplus
Copy link
Contributor

bafplus commented Mar 4, 2015

So the api key in Init.php is depricated?

Van: nikhil93uf [mailto:notifications@github.com]
Verzonden: woensdag 4 maart 2015 08:18
Aan: jaullo/Snappy
CC: bafplus
Onderwerp: Re: [Snappy] Push notifications isn´t working (#1)

Not the GCM_API_Key. In the new PushNotificationProvider, insert your api key where I marked


Reply to this email directly or view it on GitHub #1 (comment) . https://github.com/notifications/beacon/AGIo2tCYIFvh2oMQFeB0JdNVZ7k_WQTiks5nxqkWgaJpZM4DTytk.gif

@aloknnikhil
Copy link

Yes. Until I can figure out why the $apikey passed to the sendGCM is not set correctly. For now, it is deprecated.

@bafplus
Copy link
Contributor

bafplus commented Mar 4, 2015

hmmm...i have reinstalled the server, changed the pushnotificationprovider but still nothing changes. Tried it with the original spikaapp and with my own. Tried the server and browser key. When i log in to dev google i also see no api hits....what am i doing wrong here? I'm no coder. Any change someone is willing to check my server setup?
I will make a new thread for this.

@jaullo
Copy link
Owner Author

jaullo commented Mar 4, 2015

Hello @naveedrocks1, @sureshvaavel and @bafplus there is no need to change
'Authorization: key=' . API_ACCESS_KEY in PushNotificationProvider.php
This value is readed correctly from the init.php

Have proven my code?

Maybe in future (because is so expensive) i could setup a VPS on linux.

@aloknnikhil
Copy link

Also, in the pushnotificationprovider, there is a condition that checks if the server is not 'localhost' then return an error

@jaullo I don't know about your implementation, but I was talking about the original code. In any case I made a few changes to the code again.

You can try the new code here.

http://pastebin.com/aHV97w32

The reason it wasn't working was the original code automatically returned an error if the server ip was NOT 'localhost'. Pretty unwarranted exit condition

@jaullo
Copy link
Owner Author

jaullo commented Mar 4, 2015

Yes. That code (the validation) needs to be adjusted to match your server.

@bafplus
Copy link
Contributor

bafplus commented Mar 4, 2015

@nikhil93uf Tried youre code but no succes...

@flavio66
Copy link

Thanks jaullo, you saved my life! :)
Seems everything is working, except a toast with message "failed" sending msg from chat in android app.
But message is sent anyway, I'll check more.
Also chat web<->android seems working.

@jaullo
Copy link
Owner Author

jaullo commented Apr 29, 2015

Hello @flavio66 ,
Yes there are other minor bugs that has to be fixed, we are on the way :)
Best regards

@jaullo
Copy link
Owner Author

jaullo commented Jul 3, 2015

Push notificacions for thw new snappy version was fixed

@jaullo jaullo closed this as completed Jul 3, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

8 participants
@cyberbeast @bafplus @jaullo @aloknnikhil @srshkmr @flavio66 @kiranme and others