Commit bb8f9a98 authored by Stephane Bouvry's avatar Stephane Bouvry
Browse files

Test connexion OK, début affichage AJAX

parent 6ccc5a02
Loading
Loading
Loading
Loading
+46 −10
Changes for module/Oscar/Module.php: 46 added lines, 10 removed lines.
Original line number Diff line number Diff line
@@ -28,6 +28,7 @@ use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\Http\RouteMatch;
use Zend\ServiceManager\ServiceManager;
use ZfcUser\Authentication\Adapter\AdapterChainEvent;

class Module implements ConsoleBannerProviderInterface, ConsoleUsageProviderInterface
{
@@ -87,6 +88,14 @@ class Module implements ConsoleBannerProviderInterface, ConsoleUsageProviderInte
                array($this, 'onUserLogin'),
                100);

        $e->getApplication()->getEventManager()->getSharedManager()->attach(
            //'ZfcUser\Authentication\Adapter\AdapterChain',
            "*",
            'authenticate.success',
            array($this, 'onUserLogin'),
           100
        );

        // todo Remplacer l'étoile si possible
        $e->getApplication()->getEventManager()->getSharedManager()->attach(
            '*',
@@ -115,27 +124,45 @@ class Module implements ConsoleBannerProviderInterface, ConsoleUsageProviderInte
        $this->getServiceManager()->get('Logger')->error($msg);
    }

    public function onUserLogin( UserAuthenticatedEvent $e ){
        $user = $e->getDbUser();
    public function onUserLogin( $e ){

        $dbUser = null;
        if( $e instanceof AdapterChainEvent ){
            $dbUser = $this->getEntityManager()->getRepository(Authentification::class)->find($e->getIdentity());
        }
        elseif ($e instanceof UserAuthenticatedEvent ) {
            $dbUser = $e->getDbUser();
        } else {
            die('OK ?');
            // meh !
        }


        try {
            $user->setDateLogin(new \DateTime());
            $user->setSecret(md5($user->getId().'#'.time()));
            $this->getEntityManager()->flush($user);
        } catch( \Exception $e ){}
            $dbUser->setDateLogin(new \DateTime());
            $dbUser->setSecret(md5($dbUser->getId() . '#' . time()));
            $this->getEntityManager()->flush($dbUser);
        } catch (\Exception $e) {

        }

        /** @var PersonService $personService */
        $personService = $this->_serviceManager->get('PersonService');
        try {
            $person = $personService->getPersonByLdapLogin($user->getUsername());
            $person = $personService->getPersonByLdapLogin($dbUser->getUsername());
            $str = $person->log();
        } catch (NoResultException $e) {
            $str = $user->getUsername(). ' - DBUSER';
            $str = $dbUser->getUsername() . ' - DBUSER';
        }
        $this->getServiceActivity()->addInfo(sprintf('%s vient de se connecter à l\'application.', $str), $user);
        $this->getServiceActivity()->addInfo(sprintf('%s vient de se connecter à l\'application.',
            $str), $dbUser);

    }

    protected function trapEvent($event)
    {


        /** @var Request $request */
        $request = $event->getRequest();
        $sm = $event->getApplication()->getServiceManager();
@@ -160,7 +187,16 @@ class Module implements ConsoleBannerProviderInterface, ConsoleUsageProviderInte
                $action = $match->getParam('action');
                $uri = method_exists($request, 'getRequestUri') ? $request->getRequestUri() : 'console';
                $ip = array_key_exists('REMOTE_ADDR', $_SERVER) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
                $user = $userContext->getLdapUser() ? $userContext->getLdapUser()->getDisplayName() : 'Anonymous';

                if( $userContext->getLdapUser() ){
                    $user = $userContext->getLdapUser()->getDisplayName();
                }
                elseif ( $userContext->getDbUser() ){
                    $user = $userContext->getDbUser()->getDisplayName();
                } else {
                    $user = 'Anonymous';
                }

                $userid = $userContext->getDbUser() ? $userContext->getDbUser()->getid() : -1;
                $contextId = $match->getParam('id', '?');
                $message = sprintf('%s@%s:(%s) %s:%s %s', $ip, $userid, $user, $controller, $action, $uri);
+20 −9
Changes for module/Oscar/src/Oscar/Controller/NotificationController.php: 20 added lines, 9 removed lines.
Original line number Diff line number Diff line
@@ -7,27 +7,38 @@

namespace Oscar\Controller;

use Oscar\Service\NotificationService;
use Zend\View\Model\JsonModel;

/**
 * Class NotificationController
 * @package Oscar\Controller
 */
class NotificationController extends AbstractOscarController
{
    public function indexPersonAction()
    public function testAction()
    {
        $personId = $this->params()->fromRoute('idperson', null);
        if( $personId === null ){
            $personId = $this->getCurrentPerson()->getId();
        }
        var_dump($personId);
        die("Notification d'une personne");
        $personsId = [13059, 13060];

        /** @var NotificationService $notificationService */
        $notificationService = $this->getServiceLocator()->get('NotificationService');


        $notificationService->notification("Test de notification", $personsId);

        die('Fini');
    }
    public function indexAction()
    {
        $personId = $this->getCurrentPerson()->getId();

        /** @var NotificationService $notificationService */
        $notificationService = $this->getServiceLocator()->get('NotificationService');

        $notifications = $notificationService->getNotificationsPerson($personId);
        var_dump($notifications);
        die("Notifications");

        $response = new JsonModel($notifications);
        return $response;

    }
}
 No newline at end of file
+48 −2
Changes for module/Oscar/src/Oscar/Service/NotificationService.php: 48 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -7,6 +7,7 @@

namespace Oscar\Service;

use Oscar\Entity\Notification;
use UnicaenApp\Service\EntityManagerAwareInterface;
use UnicaenApp\Service\EntityManagerAwareTrait;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
@@ -17,7 +18,52 @@ class NotificationService implements ServiceLocatorAwareInterface, EntityManager
    use ServiceLocatorAwareTrait, EntityManagerAwareTrait;

    public function getNotificationsPerson( $personId ){
        $notifications = [];
        return $notifications;
        $result = [
            'personid' => $personId,
            'notifications' => []
        ];

        $notifications = $this->getEntityManager()->getRepository(Notification::class)->findBy([
            'recipientId' => $personId
        ]);

        /** @var Notification $notification */
        foreach ($notifications as $notification ){
            $result['notifications'][] = $notification->toArray();
        }

        return $result;
    }

    public function notification( $message, $personsId, $key=null ){
        if( $key === null ){
            $key = uniqid();
        }
        $push = [];
        foreach ( $personsId as $personid ){
            echo "Envoi à $personid\n";
            $hash = md5($personid.'/'.$key);
            $date = new \DateTime();
            $notification = new Notification();
            $notification->setContext('Application')
                ->setContextId(-1)
                ->setDatas([])
                ->setMessage($message)
                ->setDateEffective($date)
                ->setLevel(Notification::LEVEL_INFO)
                ->setRead(false)
                ->setRecipientId($personid);
            $this->getEntityManager()->persist($notification);

            $this->getEntityManager()->flush($notification);
            $push[] = $notification->getId();
        }

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, "http://localhost:3000/push");
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, "ids=".implode(',', $push));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_exec($curl);
    }
}
 No newline at end of file
+41 −5
Changes for module/Oscar/view/layout/layout.phtml: 41 added lines, 5 removed lines.
Original line number Diff line number Diff line
@@ -239,6 +239,9 @@ $this->headScript()
                    <?php /* echo $this->navigation()->menuPrincipal
                    ('navigation'); */ ?>
                    <p class="navbar-text navbar-right">
                        <div id="notifications-area">
                            Notifications
                        </div>
                        <?php echo $this->appConnection(); ?>
                    </p>
                </div><!--/.nav-collapse -->
@@ -325,27 +328,60 @@ $this->headScript()
		});
	})();
	</script>
        <?php if( $this->grant()->dbUser() ): ?>
        <div id="notifications">


        </div>
        <script>
            var socket;
            require(['io'], function(io){
            require(['io', 'vue', 'jquery'], function(io, Vue, $){

                var notifications = [];

                socket = io('127.0.0.1:3000', {
                    query: {
                        token: '<?= md5('toto') ?>'
                        token: '<?= $this->grant()->dbUser()->getSecret() ?>'
                    }
                });
                socket.on('connect', function(){
                    console.log('Connect');
                });
                socket.on('event', function(){
                    console.log('event');
                socket.on('notification', function(datas){
                    console.log('datas', datas);
                    notifications.push(datas.notification);
                    console.log(notifications);
                });
                socket.on('disconnect', function(){
                    console.log('disconnect');
                });

                var v = new Vue({
                    el: "#notifications-area",
                    template: `<section class="navbar-link">
                        <span class="label">{{ notifications.length }}</span> notification(s)
                        <section class="list">
                            <article v-for="notification in notifications">{{ notification.message }}</article>
                        </section>
                    </section>`,
                    data: {
                        notifications: notifications
                    },
                    methods: {
                        loadNotifications(){
                            console.log("Chargement des notifications");
                            $.get('/notification', (res) => {
                                res.notifications.forEach((n) => {
                                    this.notifications.push(n);
                                })
                            })
                        }
                    }
                });

                v.loadNotifications();

            });
        </script>
        <?php endif; ?>
    </body>
</html>
+2 −0
Changes for socket/package.json: 2 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -9,7 +9,9 @@
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.1",
    "express": "^4.15.2",
    "pg": "^7.3.0",
    "socket.io": "^2.0.3"
  }
}
Loading