POC chat avec Mercure et Symfony

Overview

Mise en place du POC Mercure Chat

Liste des groupes

img.png

Formulaire de création de groupe

img_1.png

Formulaire d'envoi de messages

img_2.png Le POC Mercure Chat consiste à mettre en place un chat avec différents groupes de conversation entre utilisateurs. L'intéret de Mercure est de gérer les messages reçu en temps réel via SSE : Server-sent event.

Informations => Mercure

Installation : Composer & BDD

  1. Installer les bundles & dépendances :composer install --dev & composer update -W
  2. Créer la BDD (DATABASE_URL doit être renseigné préalablement dans le fichier .env.local) : php bin/console doctrine:database:create
  3. Exécuter les migrations :php bin/console d:mi:mi
  4. Éxécuter les fixtures : php bin/console doctrine:fixtures:load

Installation : Mercure

  1. Télécharger Mercure pour votre environment => ici
  2. Créer un fichier .env.local
  3. Exemple .env.local
symfony/mercure-bundle ### # See https://symfony.com/doc/current/mercure.html#configuration # The URL of the Mercure hub, used by the app to publish updates (can be a local URL) MERCURE_URL=https://localhost:3000/.well-known/mercure MERCURE_DEBUG=true # The public URL of the Mercure hub, used by the browser to connect MERCURE_PUBLIC_URL=http://localhost:3000/.well-known/mercure # The secret used to sign the JWTs MERCURE_JWT_KEY="YourJwtKey" MERCURE_ALLOW_ANONYMOUS=1 # a list of origins allowed to publish (only applicable when using cookie-based auth) MERCURE_PUBLISH_URL=http://localhost:3000/.well-known/mercure MERCURE_PUBLISH_ALLOWED_ORIGINS=* # If you use cookie or Authorization HTTP header # MERCURE_PUBLISH_ALLOWED_ORIGINS="http://localhost:3000 http://localhost:8000" # a space-separated list of allowed CORS origins, can be * for all MERCURE_CORS_ALLOWED_ORIGINS=* # If you use cookie or Authorization HTTP header # MERCURE_CORS_ALLOWED_ORIGINS="http://localhost:3000 http://localhost:8000" ###< symfony/mercure-bundle ### ">
#BDD
DATABASE_URL="mysql://root@localhost:3307/poc_chat?serverVersion=mariadb-10.4.13"

###> symfony/mercure-bundle ###
# See https://symfony.com/doc/current/mercure.html#configuration
# The URL of the Mercure hub, used by the app to publish updates (can be a local URL)
MERCURE_URL=https://localhost:3000/.well-known/mercure
MERCURE_DEBUG=true
# The public URL of the Mercure hub, used by the browser to connect
MERCURE_PUBLIC_URL=http://localhost:3000/.well-known/mercure
# The secret used to sign the JWTs
MERCURE_JWT_KEY="YourJwtKey"
MERCURE_ALLOW_ANONYMOUS=1
# a list of origins allowed to publish (only applicable when using cookie-based auth)
MERCURE_PUBLISH_URL=http://localhost:3000/.well-known/mercure
MERCURE_PUBLISH_ALLOWED_ORIGINS=*
# If you use cookie or Authorization HTTP header
# MERCURE_PUBLISH_ALLOWED_ORIGINS="http://localhost:3000 http://localhost:8000"
# a space-separated list of allowed CORS origins, can be * for all
MERCURE_CORS_ALLOWED_ORIGINS=*
# If you use cookie or Authorization HTTP header
# MERCURE_CORS_ALLOWED_ORIGINS="http://localhost:3000 http://localhost:8000"
###< symfony/mercure-bundle ###

Commande Windows PowerShell

Pour lancer Mercure sur Windows :

$env:ADDR=":3000";$env:SERVER_NAME=":3000";$env:JWT_KEY="YourJwtKey";$env:MERCURE_EXTRA_DIRECTIVES="cors_origins http://localhost:8000"; ./mercure run -config Caddyfile.dev

Fichier de conf CaddyFile

# Learn how to configure the Mercure.rocks Hub on https://mercure.rocks/docs/hub/config
{
    # Debug mode (disable it in production!)
    {$DEBUG:debug}
    # HTTP/3 support
    servers {
        protocol {
            experimental_http3
        }
    }
}

{$SERVER_NAME:localhost}

log

route {
    redir / /.well-known/mercure/ui/
    encode zstd gzip

    mercure {
        # Transport to use (default to Bolt)
        transport_url {$MERCURE_TRANSPORT_URL:bolt://mercure.db}
        # Publisher JWT key
        jwt_key {env.JWT_KEY}
        #public_url {env.MERCURE_PUBLIC_URL}
        # Publisher JWT key
        publisher_jwt {env.MERCURE_PUBLISHER_JWT_KEY} {env.MERCURE_PUBLISHER_JWT_ALG}
        # Subscriber JWT key
        subscriber_jwt {env.MERCURE_SUBSCRIBER_JWT_KEY} {env.MERCURE_SUBSCRIBER_JWT_ALG}
        #cors_origins {env.MERCURE_CORS_ALLOWED_ORIGINS}
        #publish_origins {env.MERCURE_PUBLISH_ALLOWED_ORIGINS}
        #demo
        #anonymous
        #subscriptions
        # Extra directives
        {$MERCURE_EXTRA_DIRECTIVES}
    }

    respond /healthz 200

    respond "Not Found" 404
}

Twig

Création d'une variable globale Twig MERCURE_PUBLISH_URL

Cette variable permet d'être utilisée lors de la communication avec le hub mercure, via javascript. Elle retourne l'url du hub utilisé pour la communication.

Le fichier à modifier est situé dans : /config/packages/twig.yaml

twig:
    globals:
        mercure_publish_url: '%env(MERCURE_PUBLISH_URL)%'

Gestion en Javascript des réponses renvoyées par Mercure

Présent dans le fichier de template : templates/base.html.twig

Ping !
`); window.setTimeout( () => { const alert = document.querySelector('.alert'); alert.parentNode.removeChild(alert); }, 2000) } ">

Tests

Postman

Pour test la communication avec mercure voici une conf en JSON à imposter.

  • Il faudra adapter le bearer token value symbolisé par le pattern [REPLACE_BY_YOUR_JWT] présent dans le fichier test_postman.json.

  • Importez dans Postman le fichier : test_postman.json présent à la racine du site.

Vous pouver générer un token JWT sur jwt.io.

  1. Exemple de PAYLOAD :
{
  "mercure": {
    "subscribe": ["*"],
    "publish": ["*"]
  }
}
  1. VERIFY SIGNATURE : renseignez votre MERCURE_JWT_KEY (dispo dans .env & launcher_mercure.bat sous windows)
You might also like...
Chat Application In PHP using AJAX with file transferring system.

Chat Application In PHP using AJAX with file transferring system. Download free source code of real time chat application in PHP using AJAX with file transfer systemChat Application In PHP using AJAX with file transferring system. Download free source code of real time chat application in PHP using AJAX with file transfer system

Chat Application developed for Server Side Development

ChatApp 💬 Chat Application developed for Server Side Development (@IESClaraDelRey) 🧐 About this file The purpose of this file is to provide overview

Created simple login system and chat type website using mysql database along with php and html , css and javascript.

Created simple login system and chat type website using mysql database along with php and html , css and javascript.

Online chatting application through a logical decentralized blockchain network that stores chat information and hashing keys implemented using AJAX, JQuery, PHP, SQL, CSS, and HTML
Online chatting application through a logical decentralized blockchain network that stores chat information and hashing keys implemented using AJAX, JQuery, PHP, SQL, CSS, and HTML

Online chatting application through a logical decentralized blockchain network that stores chat information and hashing keys implemented using AJAX, JQuery, PHP, SQL, CSS, and HTML. The blockchain stores a previous hash value, current hash value, time, chat data, and a special key(nonce) used for encryption in each block (node).

An awesome cryptic chat created in php
An awesome cryptic chat created in php

Cryptocat An awesome cryptic chat created in php ! Table of Contents About The Project Built With Getting Started Prerequisites Installation Screensho

A Responsive Web Chat App Using Php , MySql and JavaScript
A Responsive Web Chat App Using Php , MySql and JavaScript

Web-Chat-App A Responsive Web Chat App Using Php , MySql and JavaScript Prerequisites XAMPP [Php Runtime Environment] click HERE To Download XAMPP Set

A Real time chat app made in Next.js, Laravel and Ably.

Chat App with Next.js, Laravel and Ably This repository serves as a code container for the tutorial I wrote on Ably's Blog. Blog link will be updated

Laravel live chat pusher js, bootstrap, javascript, jquery
Laravel live chat pusher js, bootstrap, javascript, jquery

Documentation First of all install a laravel project. Then install a authentication system like, auth, breze, Jetstream etc. Then you need a model, Ca

Provide modular structure into your symfony application.

Symfony Modular Bundle Provide modular structure into your symfony application. Features Configure doctrine Entity/Document mapping. Load services in

Owner
Florian
Florian
Chat application build with Symfony

Chat App Chat application build with Symfony! Explore the docs » View Demo · Report Bug · Request Feature Table of Contents About The Project Built Wi

Luis Monzon 2 Jan 31, 2022
Um chat web feito com HTML, CSS, SASS, JS, PHP e MYSQL

ChatWeb Tecnologias Front-end usadas: Pré processador CSS: Linguagem de programação usada: Projeto hospedado no: Editor de texto usado: Objetivos: Par

Adriel Cavalcante 4 Oct 27, 2022
Repositório do sistema de Chat em RealTime utilizando WebSocket com Laravel, Vue.js, Inertia e Tailwind

Antes de mais nada... Deixa a estrelinha no repositório Me segue aqui no github Aula desse Projeto no YouTube Esse projeto foi desenvolvido por Gustav

BlackDev Soluções 15 Nov 30, 2022
PHP, MySQL and JS based web chat application

About The Project Chat Application coded in PHP, CSS3 and JS. This is just a project to learn and improve understanding on certain topics. This is not

Neil 8 Apr 18, 2022
Chat Application

The system implements oop in most of its core. The users should login, create accounts, start chats with other users and be able to chat freely with the users .Creation of tables is automated here where two users that want to chat have a table.

Sebastian 4 Oct 8, 2022
Single Page Chat Application

About A single page chat application developed in PHP OOP, Mysql and AJAX. Users email (password) [email protected] (abrazzaq) [email protected] (john)

Abdul Razzaq 1 Oct 15, 2021
🗨️ Nextcloud Talk – chat, video & audio calls for Nextcloud

Nextcloud Talk A video & audio conferencing app for Nextcloud Why is this so awesome? ?? Chat Nextcloud Talk comes with a simple text chat, allowing y

Nextcloud 1.3k Dec 23, 2022
Aplikasi chat dengan laravel dan react

Aplikasi Chat Stack Laravel 8 ReactJs InertiaJs Deskripsi Aplikasi Chat yang menggunakan Backend Laravel dan Frontend React. Namun, karena saya malas

Muhamad arwani maulana 2 Jan 11, 2022
A live chat which utilises Socket.io and validates messages sent against a MySQL Table.

Socket.io Shoutbox with MySQL Validation The purpouse of this demonstration is to allow users to enter messages in either a public or private chat. Th

Jefff 9 Oct 14, 2022
Fala Devs! Estou trazendo aqui uma plataforma de Chat com Socket

Fala Devs! Estou trazendo aqui uma plataforma de Chat com Socket. Essa aplicação tem o intuito de ser bidirecional em tempo real entre clientes e servidores! Nele foi utilizado websockets para resolver o problema de alta latência, porque pense comigo... Um servidor de chat muitas vezes terá um número muito grande de clientes ativos a todo momento, a melhor forma de evitar a lentidão do servidor, seria criar um socket. ??

Raissadev 6 May 2, 2022