Отправка push-уведомлений через Codeigniter в качестве бэкэнда - PullRequest
0 голосов
/ 12 сентября 2018

Это мой контроллер

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends OK_Controller {

function accept_friend()
{
    $user_id = $this->input->post('user_id');
    $this->load->model('user_model');
    $this->load->model('site_model');

    $settings = $this->site_model->get_website_settings()->result_array();
    $settings = $settings[0];

    $user_lng = $this->user_model->get_user_language($this->session->userdata('user_id'))->result_array();

    if(sizeof($user_lng) > 0) {
        $lng_opt = $user_lng[0]["language"];
    } else {
        $lng_opt = $settings["default_language"];
    }

    $this->lang->load('user_lang', $lng_opt);

    if(!$this->session->userdata("user_id")) {  
        // Not logged in
        $result = 999;
    } else {

        // Check if the poke exists
        if(!$this->user_model->has_already_requested($user_id, $this->session->userdata("user_id"))) {
            $result = 998;
        } else {

            $from_user = $this->user_model->get($user_id)->result_array();
            $from_user = $from_user[0];

            // Set as friend
            $this->user_model->update_request_to_friend($user_id, $this->session->userdata("user_id"));

            // Add the action
            $this->load->model('action_model', 'actionModel');

            $became_friends_one = sprintf($this->lang->line("became_friends_action"), base_url("user/profile/" . $this->session->userdata("user_id")), $this->session->userdata("user_username"), base_url("user/profile/" . $user_id), $from_user["username"]);                
            $became_friends_two = sprintf($this->lang->line("became_friends_action"), base_url("user/profile/" . $user_id), $from_user["username"], base_url("user/profile/" . $this->session->userdata("user_id")), $this->session->userdata("user_username"));

            $this->actionModel->add($user_id, $this->session->userdata("user_id"), $became_friends_one, base_url("user/profile/" . $this->session->userdata("user_id")), "fa-users");
            $this->actionModel->add($this->session->userdata("user_id"), $user_id, $became_friends_two, base_url("user/profile/" . $user_id), "fa-users");

            // Add friend notif
            $this->user_model->add_friend_notif($user_id);
            $this->user_model->add_friend_notif($this->session->userdata("user_id"));

            $this->notify(User::NOTIFY_FRIENDSHIP_ACCCEPT, $user_id, $this->session->userdata("user_username"));

            $result = 1;
        }
    }

    private function installation_link($userId)
    {
        if($this->input->cookie('installation')) {
            $this->load->driver('push');
            $this->push->link($userId, $this->input->cookie('installation'));
        }
    }

    /**
     * Prepares and sends push and email notifications.
     * 
     * @param string $type
     * @param string $receiver_user_id
     * @param string $sender_username
     */
    private function notify($type, $receiver_user_id, $sender_username) {
        $language = $this->get_language_setting($receiver_user_id);
        $this->lang->load('notify_lang', $language);
        $this->load->driver('notification');

        $this->notification->subject = $this->lang->line('notify_' . $type . '_subject');
        $this->notification->message = sprintf($this->lang->line('notify_' . $type . '_message'), $sender_username);
        $this->notification->push = sprintf($this->lang->line('notify_' . $type . '_push'), $sender_username);

        $this->notification->send($receiver_user_id);
    }

    //Check for user access 
    public function user_access_role($page)
    {
        $this->load->model('action_model');
        return $this->action_model->userAccess($page);
    }
}

Библиотека, которую я создал для Parse php: Push / Push.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');


class Push extends CI_Driver_Library {
    /**
     * Valid drivers
     *
     * @var array
     */
    protected $valid_drivers = array(
        'parse'
    );

    /**
     * Reference to the driver
     *
     * @var mixed
     */
    protected $_adapter = 'parse';

    /**
     * Constructor
     *
     * Initialize class properties based on the configuration array.
     *
     * @param   array   $config = array()
     * @return  void
     */
    public function __construct($config = array()) {

    }

    public function link($userId, $externalId) {
        if ($this->is_supported($this->_adapter)) {
            return $this->{$this->_adapter}->link($userId, $externalId);
        } else {
            log_message('error', 'Link ignored due to unsupported driver.');
            return false;
        }
    }

    public function push($userId, $message) {
        if ($this->is_supported($this->_adapter)) {
            return $this->{$this->_adapter}->push($userId, $message);
        } else {
            log_message('error', 'Push ignored due to unsupported driver.');
            return false;
        }
    }

    public function is_supported($driver) {
        return $this->{$driver}->is_supported();
    }

}

и Push_parse.php в файле драйверов

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');


class CI_Push_parse extends CI_Driver {

    const PARSE_API_ENDPOINT = 'https://parseapi.back4app.com/';

    protected $app_id;
    protected $rest_key;

    public function __construct() {
        $CI = & get_instance();
        $CI->config->load('parse', FALSE, TRUE);

        $this->app_id = $CI->config->item('parse_app_id');
        $this->rest_key = $CI->config->item('parse_rest_key');
    }

    public function link($userId, $installationId) {
        $handle = curl_init(CI_Push_parse::PARSE_API_ENDPOINT . "classes/_Installation/" . $installationId);
        $parameters = array('userId' => strval($userId));
        $json = json_encode($parameters);
        $headers = array('Content-Type: application/json',
            'Content-Length: ' . strlen($json),
            'X-Parse-Application-Id: ' . $this->app_id,
            'X-Parse-REST-API-Key: ' . $this->rest_key);

        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($handle, CURLOPT_POSTFIELDS, $json);
        curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($handle);
        log_message('debug', 'Link ' . $userId . '/' . $installationId . ' response: (' . curl_getinfo($handle, CURLINFO_HTTP_CODE) . ') ' . $response);

        curl_close($handle);

        return true;
    }

    public function push($userId, $message) {
        $handle = curl_init(CI_Push_parse::PARSE_API_ENDPOINT . "push");
        $parameters = array('where' => array('userId' => strval($userId)), 'data' => array('alert' => $message));
        $json = json_encode($parameters);
        $headers = array('Content-Type: application/json',
            'Content-Length: ' . strlen($json),
            'X-Parse-Application-Id: ' . $this->app_id,
            'X-Parse-REST-API-Key: ' . $this->rest_key);

        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($handle, CURLOPT_POST, 1);
        curl_setopt($handle, CURLOPT_POSTFIELDS, $json);
        curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($handle);
        log_message('debug', 'Push to ' . $userId . ' response: (' . curl_getinfo($handle, CURLINFO_HTTP_CODE) . ') ' . $response);

        curl_close($handle);

        return true;
    }

    public function is_supported() {
        return (isset($this->app_id) && isset($this->rest_key));
    }

}

По сути, у меня есть проект, в котором есть система друзей, я хочу предоставить push-уведомление, когда user1 запрашивает дружбу с user2.

Я создал приложение для веб-просмотра с загрузкой URL и установленным в нем Parse (Back4App).

Панель Back4App показывает Установку, однако она не создает push-уведомления. Что не так в облачном коде? Должен ли я перейти на более поздние push-провайдеры, такие как Onesignal? Если да, как должен работать мой код?

...