Pusher integration
legalgates opened this issue · comments
Hello!
First of all, I would like to thank you for this package. I am trying to integrate Pusher but is seems like I can not figure out how to properly do it. Right now, I receive inputs into the database and I show them in the development server but I am not able to dinamically use it with Pusher.
Could you please, provide me with some futher explanations? Find below the config/pusher files and others:
config/chatmessenger.php
<?php
return [
'user_model' => App\User::class,
'message_model' => App\Models\Message::class,
'participant_model' => App\Models\Participant::class,
'thread_model' => App\Models\Thread::class,
/**
* Define custom database table names - without prefixes.
*/
'messages_table' => 'messages',
'participants_table' => 'participants',
'threads_table' => 'threads',
/**
* Define custom database table names - without prefixes.
*/
'use_pusher' => true,
];
config/app.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services your application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
/*
* Package Service Providers...
*/
Pusher\Laravel\PusherServiceProvider::class,
Lexx\ChatMessenger\ChatMessengerServiceProvider::class,
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Notification' => Illuminate\Support\Facades\Notification::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
'Pusher' => Pusher\Laravel\Facades\Pusher::class,
],
];
The connections are included in config/pusher but nothing is sent to the pusher area or at least I don't see in the Pusher dashboard any connection.
thank you in advance!
Hello, thanks for reaching out.
Now, after persisting the data in the database, are you dispatching/broadcasting an event to Pusher itself? What do you see in Pusher's dashboard? Any activity?
Hello again,
I see how differents users connects to pusher but nothing happens when I send a message between users. Perphaps, there is a problem with the listener? I don't know how to the bugg it.
Thank you for help
Hi. Could you provide some piece of code for your controller?
yes,sure
`<?php
namespace App\Http\Controllers;
use App\User;
use Carbon\Carbon;
use App\Models\Message;
use App\Models\Participant;
use App\Models\Models;
use App\Models\Thread;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
use Pusher; // Pusher\Laravel\Facades\Pusher
use Illuminate\Http\Request;
class MessagesController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Show all of the message threads to the user.
*
* @return mixed
*/
public function index()
{
// All threads, ignore deleted/archived participants
$threads = Thread::getAllLatest()->get();
// All threads that user is participating in
// $threads = Thread::forUser(Auth::id())->latest('updated_at')->get();
// All threads that user is participating in, with new messages
// $threads = Thread::forUserWithNewMessages(Auth::id())->latest('updated_at')->get();
return view('messenger.index', compact('threads'));
}
/**
* Shows a message thread.
*
* @param $id
* @return mixed
*/
public function show($id)
{
try {
$thread = Thread::findOrFail($id);
} catch (ModelNotFoundException $e) {
Session::flash('error_message', 'The thread with ID: ' . $id . ' was not found.');
return redirect()->route('messages');
}
// show current user in list if not a current participant
// $users = User::whereNotIn('id', $thread->participantsUserIds())->get();
// don't show the current user in list
$userId = Auth::id();
$users = User::whereNotIn('id', $thread->participantsUserIds($userId))->get();
$thread->markAsRead($userId);
return view('messenger.show', compact('thread', 'users'));
}
/**
* Creates a new message thread.
*
* @return mixed
*/
public function create()
{
$users = User::where('id', '!=', Auth::id())->get();
return view('messenger.create', compact('users'));
}
/**
* Stores a new message thread.
*
* @return mixed
*/
public function store()
{
$input = Input::all();
$thread = Thread::create([
'subject' => $input['subject'],
]);
// Message
$message = Message::create([
'thread_id' => $thread->id,
'user_id' => Auth::id(),
'body' => $input['message'],
]);
// Sender
Participant::create([
'thread_id' => $thread->id,
'user_id' => Auth::id(),
'last_read' => new Carbon,
]);
// Recipients
if (Input::has('recipients')) {
// add code logic here to check if a thread has max participants set
// utilize either $thread->getMaxParticipants() or $thread->hasMaxParticipants()
$thread->addParticipant($input['recipients']);
}
// check if pusher is allowed
if(config('chatmessenger.use_pusher')) {
$this->oooPushIt($message);
}
if(request()->ajax()) {
return response()->json([
'status' => 'OK',
'message' => $message,
'thread' => $thread,
]);
}
return redirect()->route('messages');
}
/**
* Adds a new message to a current thread.
*
* @param $id
* @return mixed
*/
public function update($id)
{
try {
$thread = Thread::findOrFail($id);
} catch (ModelNotFoundException $e) {
Session::flash('error_message', 'The thread with ID: ' . $id . ' was not found.');
return redirect()->route('messages');
}
$thread->activateAllParticipants();
// Message
$message = Message::create([
'thread_id' => $thread->id,
'user_id' => Auth::id(),
'body' => Input::get('message'),
]);
// Add replier as a participant
$participant = Participant::firstOrCreate([
'thread_id' => $thread->id,
'user_id' => Auth::id(),
]);
$participant->last_read = new Carbon;
$participant->save();
// Recipients
if (Input::has('recipients')) {
// add code logic here to check if a thread has max participants set
// utilize either $thread->getMaxParticipants() or $thread->hasMaxParticipants()
$thread->addParticipant(Input::get('recipients'));
}
$html = view('messenger.partials.html-message', compact('message'))->render();
// check if pusher is allowed
if(config('chatmessenger.use_pusher')) {
$this->oooPushIt($message);
}
if(request()->ajax()) {
return response()->json([
'status' => 'OK',
'message' => $message,
'html' => $html,
'thread_subject' => $message->thread->subject,
]);
}
return redirect()->route('messages.show', $id);
}
/**
* Send the new message to Pusher in order to notify users.
*
* @param Message $message
*/
protected function oooPushIt(Message $message, $html = '')
{
$thread = $message->thread;
$sender = $message->user;
$data = [
'thread_id' => $thread->id,
'div_id' => 'thread_' . $thread->id,
'sender_name' => $sender->name,
'thread_url' => route('messages.show', ['id' => $thread->id]),
'thread_subject' => $thread->subject,
'message' => $message->body,
'html' => $html,
'text' => str_limit($message->body, 50),
];
$recipients = $thread->participantsUserIds();
if (count($recipients) > 0) {
foreach ($recipients as $recipient) {
if ($recipient == $sender->id) {
continue;
}
$pusher_resp = Pusher::trigger(['for_user_' . $recipient], 'new_message', $data);
// We're done here - how easy was that, it just works!
}
}
return $pusher_resp;
}
/**
* Mark a specific thread as read, for ajax use.
*
* @param $id
*/
public function read($id)
{
$thread = Thread::find($id);
if (!$thread) {
abort(404);
}
$thread->markAsRead(Auth::id());
}
/**
* Get the number of unread threads, for ajax use.
*
* @return array
*/
public function unread()
{
$count = Auth::user()->unreadMessagesCount();
return ['msg_count' => $count];
}
}
I was able to connect different users to the channels created in the pusher dasboard but when I submit the message I don't receive any live alert or nothing. (Data is sent and stored in the DB)
I see the following message in the console.log when I connect one user to the channel. Could it be the reason?
Pusher.ScriptReceivers[1](null, { host: 'timeline33-clientstats1.pusher.com' });
Hi there!
Finally, I found the problem. There was a mismatch between the server time and pusher. Which is already solved and now the app works as intented.
Thank you for you help!
... Just a follow-up, package now support laravel 6. The docs/examples hav been updated, and Pusher is now used slightly different than before. It is more alligned to how laravel likes it.
Cheers!