/**
  * Breadcast the $event to all subscribers on $topic
  *
  * @param \Ratchet\ConnectionInterface $conn
  * @param string|\Ratchet\Wamp\Topic $topic
  * @param string $event
  * @param array $exclude
  * @param array $eligible
  */
 public function onPublish(Conn $conn, $topic, $event, array $exclude = array(), array $eligible = array())
 {
     if ($topic instanceof \Ratchet\Wamp\Topic) {
         $topic->broadcast($event, $exclude, $eligible);
     }
     $topicName = self::getTopicName($topic);
     $eventPayload = ['topicName' => $topicName, 'connection' => $conn, 'event' => $event, 'exclude' => $exclude, 'eligible' => $eligible, 'wampServer' => $this, 'connectionData' => $this->_connections[$conn->WAMP->sessionId]];
     $this->dispatchEvent('Rachet.WampServer.onPublish', $this, $eventPayload);
     $this->dispatchEvent('Rachet.WampServer.onPublish.' . $topicName, $this, $eventPayload);
 }
Beispiel #2
1
 /**
  * This will receive any Publish requests for this topic.
  *
  * @param ConnectionInterface $connection
  * @param $Topic topic
  * @param WampRequest $request
  * @param $event
  * @param array $exclude
  * @param array $eligibles
  * @return mixed|void
  */
 public function onPublish(ConnectionInterface $connection, Topic $topic, WampRequest $request, $event, array $exclude, array $eligible)
 {
     /*
         $topic->getId() will contain the FULL requested uri, so you can proceed based on that
     
         if ($topic->getId() == "acme/channel/shout")
            //shout something to all subs.
     */
     $topic->broadcast(['msg' => $event]);
 }
Beispiel #3
1
 /**
  * This will receive any Publish requests for this topic.
  *
  * @param ConnectionInterface $connection
  * @param Topic $topic
  * @param WampRequest $request
  * @param $event
  * @param array $exclude
  * @param array $eligible
  *
  * @return mixed|void
  */
 public function onPublish(ConnectionInterface $connection, Topic $topic, WampRequest $request, $event, array $exclude, array $eligible)
 {
     if ($event['event'] && $event['event'] == 'move') {
         $cardHelper = new CardHelper($this->em);
         try {
             $moveResult = $cardHelper->moveCard($event['userId'], $event['gameId'], $event['cardId']);
             if ($moveResult['result'] == CardHelper::MOVED_SUCCESSFULLY) {
                 /** @var Game[] $games */
                 $games = $this->em->getRepository('AppBundle:Game')->createQueryBuilder('game')->select('game, users')->join('game.users', 'users')->where("game.id = {$moveResult['data']}")->getQuery()->getArrayResult();
                 $topic->broadcast(['msg' => ['game' => $games[0] ? $games[0] : []]]);
             } else {
                 if ($moveResult['result'] == CardHelper::MOVED_FAIL_BY_TURN) {
                     $topic->broadcast(['msg' => 'Not your turn.']);
                 } else {
                     $topic->broadcast(['msg' => 'Error.']);
                 }
             }
         } catch (EntityNotFoundException $ex) {
             $topic->broadcast(['msg' => $ex->getMessage()]);
         }
     }
     if ($event['event'] && $event['event'] == 'pass') {
         $gameHelper = new GameHelper();
         $passResult = $gameHelper->pass($this->em, $event['userId'], $event['gameId']);
         if ($passResult['result'] == GameHelper::PASSED_SUCCESSFULLY) {
             /** @var Game[] $games */
             $games = $this->em->getRepository('AppBundle:Game')->createQueryBuilder('game')->select('game, users')->join('game.users', 'users')->where("game.id = {$passResult['data']}")->getQuery()->getArrayResult();
             $topic->broadcast(['msg' => ['game' => $games[0] ? $games[0] : []]]);
         } else {
             if ($passResult['result'] == GameHelper::PASSED_UNSUCCESSFULLY) {
                 $topic->broadcast(['msg' => 'You can not pass.']);
             }
         }
     }
     /*
         $topic->getId() will contain the FULL requested uri, so you can proceed based on that
     
         if ($topic->getId() === 'game/channel/shout')
            //shout something to all subs.
     */
 }
Beispiel #4
0
 /**
  * @param Topic       $topic
  * @param string|null $tokenSeparator
  *
  * @return WampRequest
  *
  * @throws ResourceNotFoundException
  * @throws \Exception
  */
 public function match(Topic $topic, $tokenSeparator = null)
 {
     try {
         list($routeName, $route, $attributes) = $this->pubSubRouter->match($topic->getId(), $tokenSeparator);
         if ($this->debug) {
             $this->logger->debug(sprintf('Matched route "%s"', $routeName), $attributes);
         }
         return new WampRequest($routeName, $route, new ParameterBag($attributes), $topic->getId());
     } catch (ResourceNotFoundException $e) {
         $this->logger->error(sprintf('Unable to find route for %s', $topic->getId()));
         throw $e;
     }
 }
Beispiel #5
0
 public function getTopicHandler(Topic $topic)
 {
     //get network namespace to see if its valid
     $parts = explode("/", $topic->getId());
     if ($parts <= 0) {
         return false;
     }
     $serviceMatch = $parts[0];
     foreach ($this->getTopicServices() as $topicService) {
         if ($topicService['name'] === $serviceMatch) {
             return $this->getContainer()->get($topicService['service']);
         }
     }
     return false;
 }
 public function testCloseConnection()
 {
     $directivesManager = $this->createDirectivesManagerMock();
     $consumerManager = $this->createConsumerManagerMock();
     $directivesManager->expects($this->once())->method('hasAccess')->will($this->returnValue(true));
     $manager = new TopicsManager($directivesManager, $consumerManager);
     $conn = $this->getMock('Ratchet\\ConnectionInterface');
     $conn->User = $this->getMock('Alchemy\\Phrasea\\Websocket\\Consumer\\ConsumerInterface');
     $topic = new Topic('http://topic');
     $topic->add($conn);
     // should be subscribed to be unsubscribed
     $manager->subscribe($conn, $topic);
     $manager->closeConnection($conn);
     $this->assertFalse($topic->has($conn));
 }
 private function getTopicNamespace(Topic $topic)
 {
     //get network namespace to see if its valid
     $parts = explode("/", $topic->getId());
     if ($parts <= 0) {
         return false;
     }
     $serviceMatch = $parts[0];
     return $serviceMatch;
 }
 /**
  * This will receive any Publish requests for this topic.
  *
  * @param ConnectionInterface $connection
  * @param $Topic topic
  * @param WampRequest $request
  * @param $event
  * @param array $exclude
  * @param array $eligibles
  * @return mixed|void
  */
 public function onPublish(ConnectionInterface $connection, Topic $topic, WampRequest $request, $event, array $exclude, array $eligible)
 {
     switch ($event['type']) {
         // Quand un user se connecte
         case "user_co":
             $this->users[$topic->getId()][$connection->resourceId] = intval($event['id_user']);
             $topic->broadcast(['user_add' => intval($event['id_user'])]);
             break;
         case "msg":
             $topic->broadcast(['msg' => $event]);
             break;
     }
 }
Beispiel #9
0
 /**
  * A request to subscribe to a topic has been made
  * @param \Ratchet\ConnectionInterface $conn
  * @param string|Topic $topic The topic to subscribe to
  */
 function onSubscribe(ConnectionInterface $conn, $topic)
 {
     if (!array_key_exists($topic->getId(), $this->subscribedTopics)) {
         $this->subscribedTopics[$topic->getId()] = $topic;
     }
 }
Beispiel #10
0
 /**
  * Handler to be executed after client un-subscription.
  *
  * @param ConnectionInterface $connection
  * @param Topic $topic
  * @return void
  */
 public function unsubscribe(ConnectionInterface $connection, Topic $topic)
 {
     $connection->channels->forget($topic->getId());
 }
 /**
  * @param Topic        $topic
  * @param WampRequest  $request
  * @param array|string $data
  * @param string       $provider The name of pusher who push the data
  */
 public function onPush(Topic $topic, WampRequest $request, $data, $provider)
 {
     $this->logger->info("onPush -> " . $topic->getId());
     /* @var $slack \FourPixelsBundle\Entity\Slack */
     /* @var $slackRequest \FourPixelsBundle\Entity\SlackRequest */
     /* @var $slackTeamTreeHouse \FourPixelsBundle\Entity\SlackTeamTreeHouse */
     $this->em->clear();
     $slackRequest = $this->em->getRepository('FourPixelsBundle:SlackRequest')->find($request->getAttributes()->get('slackRequest'));
     $slack = $this->em->getRepository('FourPixelsBundle:Slack')->find($request->getAttributes()->get('slack'));
     $scoreTable = [];
     if ($slack->getId() === $slackRequest->getSlack()->getId()) {
         $client = new \Guzzle\Http\Client();
         $explode = explode(' ', $slackRequest->getText());
         $globalShowMode = 'in_channel';
         // ephemeral OR in_channel
         switch ($explode[0]) {
             case 'help':
                 $myArray = ['username' => '4pixels', "icon_url" => "https://slack.com/img/icons/app-57.png", "icon_emoji" => ":ghost:", "response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/list", "title" => "LIST", "text" => "/teamtreehouse list \n Displays a list of all the Team Tree House usernames participaiting in the tournament. \n *Example:* _/teamtreehouse list_", "mrkdwn_in" => ['text'], "color" => "#3F2860"], ["fallback" => "please visit https://4pixels.co/api-help/add", "title" => "ADD", "text" => "/teamtreehouse add `TeamTreeHouse username` \n adds a Team Tree House username to the tournament. \n *Example:* _/teamtreehouse add jasoncameron_", "mrkdwn_in" => ['text'], "color" => "#F35A00"], ["fallback" => "please visit https://4pixels.co/api-help/remove", "title" => "REMOVE", "text" => "/teamtreehouse remove `TeamTreeHouse username` \n Delete a Team Tree House username from the tournament. \n *Example:* _/teamtreehouse remove jasoncameron_", "mrkdwn_in" => ['text'], "color" => "#B81D18"], ["fallback" => "please visit https://4pixels.co/api-help/remove", "title" => "SHOW", "text" => "/teamtreehouse show `TeamTreeHouse username` \n Show a single Team Tree House username score. \n *Example:* _/teamtreehouse show jasoncameron_", "mrkdwn_in" => ['text'], "color" => "#1253A4"], ["fallback" => "please visit https://4pixels.co/api-help/code", "title" => "CODE", "text" => "" . "/teamtreehouse code \n Displays a ranking list of Team Tree House usernames tournament. \n *Example:* _/teamtreehouse code_ \n\n" . "/teamtreehouse code `TeamTreeHouse language` \n Displays a ranking list of Team Tree House usernames tournament based on one lenguage. \n *Example:* _/teamtreehouse code javascript_  \n\n" . "/teamtreehouse code `TeamTreeHouse languages` \n Displays a ranking list of Team Tree House usernames tournament based on many lenguage. \n *Example:* _/teamtreehouse code javascript, php, html_", "mrkdwn_in" => ['text'], "color" => "#75A3D1"]]];
                 break;
             case 'show':
                 //         /teamtreehouse show jasoncameron
                 $username = $explode[1];
                 //MOST VALIDATE THERE ARE NO MORE PARAMETERS THAN 2
                 try {
                     $teamTreeHouseResponse = $client->get('https://teamtreehouse.com/' . $username . '.json')->send();
                     $slackTeamTreeHouse = new \FourPixelsBundle\Entity\SlackTeamTreeHouse();
                     $slackTeamTreeHouse->setContent($teamTreeHouseResponse->json());
                     $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/show", "title" => "SHOW " . $slackTeamTreeHouse->getName() . " (" . $slackTeamTreeHouse->getProfileName() . ")", "color" => "#75A3D1", "thumb_url" => $slackTeamTreeHouse->getGravatarUrl(), "fields" => $slackTeamTreeHouse->getPoints(true)]]];
                 } catch (ClientErrorResponseException $exception) {
                     $responseBody = $exception->getResponse()->getBody(true);
                     $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/remove", "title" => "SHOW " . $username . " - Ups !!! :panda_face: Panda Trouble", "text" => "Username " . $responseBody . " on Team Tree House", "mrkdwn_in" => ['text'], "color" => "#D40E52"]]];
                 }
                 break;
             case 'code':
                 $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/code", "title" => "Feature CODE", "text" => "The panda is busy right know thinking in other stuff. He will develop this feature soon.", "mrkdwn_in" => ['text'], "color" => "#D40E52"]]];
                 break;
             case 'list':
                 $slackTeamTreeHouseList = $slack->getSlackTeamTreeHouseList();
                 $text = "";
                 foreach ($slackTeamTreeHouseList as $slackTeamTreeHouse) {
                     $text .= $slackTeamTreeHouse->getName() . ' (' . $slackTeamTreeHouse->getProfileName() . ")\n";
                 }
                 $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/list", "title" => "LIST - List size: " . count($slackTeamTreeHouseList), "text" => $text, "color" => "#75A3D1"]]];
                 break;
             case 'add':
                 $username = $explode[1];
                 //MOST VALIDATE THERE ARE NO MORE PARAMETERS THAN 2
                 try {
                     $teamTreeHouseResponse = $client->get('https://teamtreehouse.com/' . $username . '.json')->send();
                     $slackTeamTreeHouse = new \FourPixelsBundle\Entity\SlackTeamTreeHouse();
                     $slackTeamTreeHouse->setContent($teamTreeHouseResponse->json());
                     $slackTeamTreeHouse->setSlack($slack);
                     $this->em->persist($slackTeamTreeHouse);
                     $this->em->flush();
                     $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/add", "title" => "ADD " . $slackTeamTreeHouse->getName() . " (" . $slackTeamTreeHouse->getProfileName() . ")", "text" => "User has been added successfuly", "color" => "#75A3D1", "thumb_url" => $slackTeamTreeHouse->getGravatarUrl()]]];
                 } catch (ClientErrorResponseException $exception) {
                     $responseBody = $exception->getResponse()->getBody(true);
                     $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/add", "title" => "ADD " . $username . " - Ups !!! :panda_face: Panda Trouble ", "text" => "Username " . $responseBody . " on Team Tree House", "color" => "#D40E52"]]];
                 } catch (\Doctrine\DBAL\Exception\UniqueConstraintViolationException $e) {
                     $this->em->clear();
                     $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/add", "title" => "ADD " . $username . " - Ups !!! :panda_face: Panda Warning ", "text" => "Username " . $username . " is already added", "color" => "#FF9900"]]];
                 }
                 break;
             case 'remove':
                 $username = $explode[1];
                 $slackTeamTreeHouse = $this->em->getRepository('FourPixelsBundle:SlackTeamTreeHouse')->findOneBy(['slack' => $slack->getId(), 'profile_name' => $username]);
                 if (!is_null($slackTeamTreeHouse)) {
                     try {
                         $name = $slackTeamTreeHouse->getName();
                         $gravatarUrl = $slackTeamTreeHouse->getGravatarUrl();
                         $this->em->remove($slackTeamTreeHouse);
                         $this->em->flush();
                         $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/remove", "title" => "REMOVE " . $name . " (" . $username . ")", "text" => "User has been removed from the list successfuly", "color" => "#75A3D1", "thumb_url" => $gravatarUrl]]];
                     } catch (\Exception $e) {
                         $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/remove", "title" => "REMOVE " . $username . " - Ups !!! :panda_face: Panda Warning ", "text" => "The was a problem removing the user from the list. ", "color" => "#FF9900"]]];
                     }
                 } else {
                     $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help/remove", "title" => "REMOVE " . $username . " - Ups !!! :panda_face: Panda Trouble ", "text" => "Username was not found on the list. \n You can view the list with: /teamtreehouse list", "color" => "#D40E52"]]];
                 }
                 break;
             default:
                 $slackTeamTreeHouseList = $slackRequest->getSlack()->getSlackTeamTreeHouseList();
                 foreach ($slackTeamTreeHouseList as $slackTeamTreeHouse) {
                     $teamTreeHouseResponse = $client->get('https://teamtreehouse.com/' . $slackTeamTreeHouse->getProfileName() . '.json')->send();
                     $slackTeamTreeHouse->setContent($teamTreeHouseResponse->json());
                     $this->em->persist($slackTeamTreeHouse);
                     $scoreTable[$slackTeamTreeHouse->getName() . ' (' . $slackTeamTreeHouse->getProfileName() . ')'] = $slackTeamTreeHouse->getTotal();
                 }
                 $this->em->flush();
                 $resultBool = arsort($scoreTable);
                 $text = "";
                 foreach ($scoreTable as $key => $value) {
                     $text .= $value . " \t \t " . $key . " \n ";
                 }
                 $myArray = ["response_type" => $globalShowMode, "attachments" => [["fallback" => "please visit https://4pixels.co/api-help", "title" => "RANKING NEWS ", "text" => $text, "color" => "#75A3D1"]]];
                 break;
         }
         $requestForSlack = $client->post($slackRequest->getResponseUrl(), [], ['payload' => json_encode($myArray)]);
         $response = $requestForSlack->send();
     }
     $topic->broadcast(['msg' => 'DONE']);
 }
Beispiel #12
0
 /**
  * Send Response
  *
  * @param \Illuminate\Http\Response $response
  * @param \Ratchet\ConnectionInterface $conntection
  * @param \Ratchet\Wamp\Topic $topic
  * @return void
  * @throws \CupOfTea\TwoStream\Exception\InvalidRecipientException
  */
 protected function send($response, Connection $connection, $topic)
 {
     if ($response == 404) {
         return;
     }
     $recipient = array_get($response, 'recipient', config('twostream.response.recipient'));
     $data = array_get($response, 'data', $response);
     if ($recipient == 'all') {
         $topic->broadcast($data);
     } elseif ($recipient == 'except') {
         foreach ($topic->getIterator() as $client) {
             if ($client->session != $connection->session) {
                 $client->event($topic->getId(), $data);
             }
         }
     } else {
         if ($recipient == 'requestee') {
             $recipient = $connection->session;
         }
         foreach ((array) $recipient as $recipient) {
             // TODO: if translateUserToSessionId ||
             if (WsSession::isValidId($recipient)) {
                 foreach ($topic->getIterator() as $client) {
                     if ($client->session == $recipient) {
                         $client->event($topic->getId(), $data);
                     }
                 }
             } else {
                 throw new InvalidRecipientException($recipient);
             }
         }
     }
 }
Beispiel #13
0
 /**
  * @param \Ratchet\ConnectionInterface $conn
  * @param Topic $topic
  * @param $event
  * @param array $exclude
  * @param array $eligible
  * @return mixed|void
  */
 public function onPublish(Conn $conn, $topic, $event, array $exclude, array $eligible)
 {
     $topic->broadcast(array("sender" => $conn->resourceId, "topic" => $topic->getId(), "event" => $event));
 }
Beispiel #14
0
 /**
  * Get the name of a topic/channel
  * just for convenience
  *
  * @param Ratchet\Wamp\Topic $topic
  * @return string
  */
 protected function getTopicName(Topic $topic)
 {
     return $topic->getId();
 }
Beispiel #15
0
 /**
  * @param ConnectionInterface        $conn
  * @param \Ratchet\Wamp\Topic|string $topic
  */
 public function onSubscribe(ConnectionInterface $conn, $topic)
 {
     $this->subscribedTopics[$topic->getId()] = $topic;
 }
Beispiel #16
0
 /**
  * Récupère l'identifiant de team
  *
  * @param Topic $topic
  * @return integer
  *
  * @author Benjamin Levoir <*****@*****.**>
  */
 private function getTeamId(Topic $topic)
 {
     return explode('/', $topic->getId())[count(explode('/', $topic->getId())) - 1];
 }
Beispiel #17
0
 /**
  * @param string|\Ratchet\Wamp\Topic $topic
  *
  * @return string
  */
 public static function getTopicName($topic)
 {
     if ($topic instanceof \Ratchet\Wamp\Topic) {
         return $topic->getId();
     } else {
         return $topic;
     }
 }
 /**
  * @param Topic $topic
  *
  * @return Directive[]
  */
 private function getDirectives(Topic $topic)
 {
     return array_filter($this->directives, function (Directive $directive) use($topic) {
         return $directive->getTopic() === $topic->getId();
     });
 }
Beispiel #19
0
 /**
  * Removes internal references to topics if they do not contains any reference to an active connection.
  *
  * @param Conn       $conn
  * @param null|Topic $topic Restrict to this topic, if provided
  */
 private function cleanupReferences(Conn $conn, Topic $topic = null)
 {
     $storage = $this->topics;
     $updated = [];
     foreach ($storage as $id => $storedTopic) {
         if (null !== $topic && $id !== $topic->getId()) {
             continue;
         }
         if ($storedTopic->has($conn)) {
             $storedTopic->remove($conn);
         }
         if (count($storedTopic) > 0) {
             $updated[] = $storedTopic;
         }
     }
     $this->topics = $updated;
 }
 /**
  * @param ConnectionInterface        $conn
  * @param \Ratchet\Wamp\Topic|string $topic
  */
 public function onUnSubscribe(ConnectionInterface $conn, $topic)
 {
     $user = $this->clientStorage->getClient($conn->WAMP->clientStorageId);
     $username = $user instanceof UserInterface ? $user->getUsername() : $user;
     $this->logger->info(sprintf('User %s unsubscribed to %s', $username, $topic->getId()));
     $wampRequest = $this->wampRouter->match($topic);
     $this->topicDispatcher->onUnSubscribe($conn, $topic, $wampRequest);
 }
 /**
  * This will receive any Publish requests for this topic.
  *
  * @param  ConnectionInterface $connection
  * @param  Topic $topic
  * @param  WampRequest $request
  * @param  $event
  * @param  array $exclude
  * @param  array $eligible
  */
 public function onPublish(ConnectionInterface $connection, Topic $topic, WampRequest $request, $event, array $exclude, array $eligible)
 {
     $user = $this->clientManipulator->getClient($connection);
     $message = $this->messagesManager->getMessage('conversation', $user, $event);
     $topic->broadcast(['msg' => $message->render()]);
     $this->messagesManager->save($message);
 }
 public function testDoesNotHaveAfterRemove()
 {
     $conn = $this->newConn();
     $topic = new Topic('Ras');
     $topic->add($conn)->remove($conn);
     $this->assertFalse($topic->has($conn));
 }
Beispiel #23
-1
 /**
  * A request to subscribe to a topic has been made.
  *
  * Usually we just want to add the topic to our internal array so we know who to notify about updates, however
  * in a few special cases, upon subscription we want to send a collection of data to "catch-up" the client with
  * our current state. In those cases, we'll emit a (Foo)SubscriptionEvent, and let the system send the bulk
  * data to the client.
  *
  * @param \Ratchet\ConnectionInterface $conn
  * @param string|Topic $topic The topic to subscribe to
  */
 function onSubscribe(ConnectionInterface $conn, $topic)
 {
     $this->subscribedTopics[$topic->getId()] = $topic;
     switch ((string) $topic) {
         case self::QUESTION_DISPLAY_TOPIC:
             $this->emitter->emit(new QuestionSubscriptionEvent($this->getSessionIdFromConnection($conn)));
             break;
         case self::BUZZER_STATUS_TOPIC:
             $this->emitter->emit(new BuzzerStatusSubscriptionEvent($this->getSessionIdFromConnection($conn)));
             break;
         case self::CONTESTANT_SCORE:
             $this->emitter->emit(new ContestantScoreSubscriptionEvent($this->getSessionIdFromConnection($conn)));
             break;
         default:
             break;
     }
 }