Giter Club home page Giter Club logo

notifier's Introduction

build passed code-intelligence license downloads

Base concepts

You don't need socket.io, pusher.js, jQuery, bootstrap, node.js, vue.js to start using this package.

This package can be used for sending data synchronously to each user.

This package sends data ONLY to named routes declared as GET.

You will get your own socket server on back-end and your clients will connect to it directly, without any third-party requests to be send.

You will have pretty notifications from scratch.

To view available routes you can run php artisan notifier:init show command. It will display available routes in the table and initiate the socket server.

Code Description
event(new Notify($data)); - send to all routes.
event(new Notify($data, $routes)); - send to routes in $routes array.
event(new Notify($data, $routes, $users)); - send to routes in $routes and only to users in $users.

Installation

composer require matviib/notifier

For Laravel < 5.5 add provider to config/app.php

MatviiB\Notifier\NotifierServiceProvider::class,

For publish notifier config file and js file for notifications out of the box:

php artisan vendor:publish

and choose "Provider: MatviiB\Notifier\NotifierServiceProvider" if requested.

Starting server

Add worker daemon for php artisan notifier:init process with Supervisor,

OR

Just run php artisan notifier:init in terminal.

If you use SSL you need add to your nginx configuration file to server block:

    location /websocket {
        proxy_pass http://<your-domain>:<port>; #server host and port
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";

        # Timeout configuration.
        proxy_redirect off;
        proxy_connect_timeout  300;
        proxy_send_timeout     300;
        proxy_read_timeout     300;
   }

Usage

At first you need to add @include('notifier::connect') before using socket.addEventListener() in your view or main layout to use it on ALL pages.

If you want use notifications from the scratch you need to add @include('notifier::connect_and_show') to the view.

Anywhere in your back-end add next event:

event(new Notify($data));

On front-end part add event listener

<script>
    socket.addEventListener('message', function (event) {
        console.log('Message from server', event.data);
    });
</script>

Use built-in notifications.

Built-in notifications is a vue.js with vue-notifications plugin. If you already use vue.js in application you can just add this plugin yourself.

Mapping $data parameter.
Parameter Description
'note' => 1, - use notes true
`'type' => 'warn success
'title' => 'TEXT' - title of the note
'text' => 'Lorem ipsum' - note's body
Positioning.

In config/notifier.php you can modify position where notifications will be shown.

// Horizontal options: left, center, right
// Vertical options: top, bottom
'position' => [
        'vertical' => 'bottom',
        'horizontal' => 'right'
    ]

Security

This package allows one way messages - only from server to client.

All messages from client after connecting will be ignored.

From server side messages protected with socket_pass parameter from notifier config.

Channels to users protected with unique hash.

Example with charts

After installation add to web.php

Route::get('chart', function () {
    return view('chart');
})->name('chart');

create view /resources/views/chart.blade.php

<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Chart</title>
</head>
<body>
<canvas id="myChart"></canvas>
@include('notifier::connect')
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script type="text/javascript">

    var data = [12, 19, 3, 17, 6, 3, 7, 45, 60, 25];

    var myChart = new Chart(document.getElementById('myChart'), {
        type: 'line',
        data: {
            labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            datasets: [{
                label: 'example',
                data: data
            }]
        }
    });

    socket.addEventListener('message', function (event) {
        myChart.data.datasets[0].data.splice(0, 1);
        myChart.data.datasets[0].data.push(JSON.parse(event.data).data.value);
        myChart.update();
    });
</script>
</body>
</html>

In .env fix your APP_URL APP_URL=http://<<U APP URL>>

Create test command php artisan make:command Test

use MatviiB\Notifier\Events\Notify; 

...

protected $signature = 'test';

public function handle()
    {
        while ($i < 100) {
            $value = random_int(10, 100);
            $data['value'] = $value;
            event(new Notify($data, ['chart']));
            usleep(rand(100000, 500000));
        }
}

Run: php artisan notifier:init

Run in another shell: php artisan test

Open /chart page.

Usage Example

Send new values to chart on some page synchronously to each user:

event(new Notify($data, ['chart']));

Or to users with id 3 and 5: event(new Notify($data, ['chart'], [3, 5]));

laravel socket server

notifier's People

Contributors

matviib avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

notifier's Issues

Error Supervisor to run notifier:init

Hi again and sorry for my issues ^^
I'm trying to configure my supervisor but it fails !

error: <class 'socket.error'>, [Errno 2] No such file or directory: file: /usr/lib/python2.7/socket.py line: 228

Installation issue !

Hi,
I got this error during installation !
I'm using L5.6, PHP 7.2, Ubuntu 16.04

> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover

   ErrorException  : in_array() expects parameter 2 to be array, null given

  at /var/www/maktaba/vendor/matviib/notifier/src/NotifierServiceProvider.php: 29
  25:         if ($path !== '/') {
  26:             $path = '/' . $path;
  27:         }
  28: 
  29:         if (in_array($path, config('notifier.urls'))) {
  30:             $this->registerEvents();
  31:             $this->registerMiddleware(InjectConnector::class);
  32:         }
  33:     }
  34: 

  Exception trace:

  1   in_array("/")
      /var/www/maktaba/vendor/matviib/notifier/src/NotifierServiceProvider.php : 29

  2   MatviiB\Notifier\NotifierServiceProvider::boot()
      /var/www/maktaba/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php : 29

  Please use the argument -v to see more details.
Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

Usage issues !

Please, provide a sample tutorial to show how do we use it.
I found these issues when following your read-me.

event(new Notify($data));

Class 'App\Http\Controllers\Notify' not found

On front-end :

<script>
    socket.addEventListener('message', function (event) {
        console.log('Message from server', event.data);
    });
</script>

ReferenceError: socket is not defined

HTML component with live text

Can you extend your package to provide live information to a html component with text (label, input text ...) in a view?

It's very useful when you want to display weather info, status of a server in real-time, a live parameter ...

Send Notification to some users by ID

Hi,
Thank you so much for this nice package :)
Please, is there any way to send notification to users by ID ?
Something like this :
event(new Notify($users, $data, '/chart'));

Thanks :)

Disable receiving data with "message" key and "test" value

How to disable receiving data with message and test value?

In console log I see this:

Message from server: {"data":{"message":"test"}}

and this disrupts my personalized data sender, I have to put in this case conditions with:

if (data['message'] != 'test') { if (data['jdrac_temperature'] != null) { document.getElementById("jdrac_temperature").innerHTML = data['jdrac_temperature']; } }

Support for different internal socket host

I would like to see the possibility to configure a different internal socket hosts for internal communication.

Specifically just have the possibility to set a different host in the browser <script> tag generated by @include('notifier::connect').

Thanks!

Suggestion: Send to predefined users ID

I can send to predefined users ID by this way :

$userID = [1,2,3];
$data = ['id' => $userID, 'title' => 'Info :)', 'content' => 'Hi there !'];
event(new Notify($data));

And in the main blade :

<script>        
        socket.addEventListener('message', function (event) {
            if(JSON.parse(event.data).data.id.includes({!! Auth::id() !!}))
            {
                toastr.info(JSON.parse(event.data).data.content, JSON.parse(event.data).data.title);
            }
        });
</script>

So you may update it to get it works like this :
event(new Notify($usersID, $data));

Good Luck 😀

Popup notify example

Excellent package. I was able to start your chart example.

But, can you provide a full example with a popup notify message?

Have I to create a command console for this also, like for chart?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.