Exemplo n.º 1
0
 public function setChannels(ChannelsCollection $channels)
 {
     $users = DI::get()->getUsers();
     foreach ($channels->getChannels() as $channel) {
         if (!$channel->isPrivate()) {
             $this->channels[$channel->getId()] = ['name' => $channel->getName(), 'usersCount' => $users->getClientsCount($channel->getId())];
         }
     }
     return $this;
 }
 public static function run(User $user, UserCollection $users, ChannelsCollection $chats)
 {
     if (!$user->isInPrivateChat()) {
         return;
     }
     self::moveUsersToPublic($user, $users);
     self::informYouselfOnExit($user);
     ChannelNotifier::uploadHistory($user, true);
     ChannelNotifier::indentifyChat($user, $users);
     $chats->clean($user);
 }
Exemplo n.º 3
0
 public static function uploadHistory(User $user, $clear = null)
 {
     $channel = ChannelsCollection::get()->getChannelById($user->getChannelId());
     if (!$channel) {
         $channel = new Channel($user->getChannelId(), 'Приват_' . $user->getChannelId());
         $channel->setOwnerId($user->getId());
         ChannelsCollection::get()->addChannel($channel);
     }
     $log = $channel->getHistory($user->getLastMsgId());
     $client = (new UserCollection())->attach($user);
     $historyResponse = (new HistoryResponse())->setChannelId($user->getChannelId());
     if (!$user->getLastMsgId()) {
         $historyResponse->setClear($clear);
     }
     foreach ($log as $response) {
         if ($user->getBlacklist()->isBanned($response[Channel::FROM_USER_ID])) {
             continue;
         }
         if (isset($response[Channel::TO_NAME])) {
             if ($response[Channel::FROM_USER_ID] == $user->getId() || $response[Channel::TO_NAME] == $user->getProperties()->getName()) {
                 $historyResponse->addResponse($response);
             }
             continue;
         }
         $historyResponse->addResponse($response);
     }
     $historyResponse->setLastMsgId($channel->getLastMsgId());
     $client->setResponse($historyResponse)->notify(false);
 }
 public function handleRequest(ChainContainer $chain)
 {
     $user = $chain->getFrom();
     $users = DI::get()->getUsers();
     $channels = ChannelsCollection::get();
     MainChatDualsHandler::run($user, $users);
     MainChatPrivateHandler::run($user, $users, $channels);
 }
Exemplo n.º 5
0
 protected function handleLog(Response $response, $log)
 {
     $isMessage = $response instanceof MessageResponse;
     $saveGuests = $response->getGuests();
     if ($isMessage && $log) {
         /* @var $response MessageResponse */
         $lastMsgId = ChannelsCollection::get()->pushToHistory($response);
         $response->setLastMsgId($lastMsgId);
     }
     $response->setGuestsRaw($saveGuests);
 }
Exemplo n.º 6
0
 /**
  * @param User $user
  */
 private function handleHistory(User $user)
 {
     ChannelNotifier::uploadHistory($user);
     $ds = DIRECTORY_SEPARATOR;
     if (file_exists(ROOT . $ds . 'www' . $ds . 'motd.txt') && !$user->getLastMsgId()) {
         $motd = file_get_contents(ROOT . $ds . 'www' . $ds . 'motd.txt');
         $motd .= "<br>Доступны каналы:<br>";
         foreach (ChannelsCollection::get()->getChannels() as $channel) {
             if ($channel->isPrivate()) {
                 continue;
             }
             $motd .= '(' . DI::get()->getUsers()->getClientsCount($channel->getId()) . ') ' . $channel->getName() . '<br>';
         }
         $client = (new UserCollection())->attach($user);
         $response = (new MessageResponse())->setChannelId($user->getChannelId())->setMsg(MsgRaw::create($motd));
         $client->setResponse($response)->notify(false);
     }
 }
Exemplo n.º 7
0
 private function detacher(User $user, Logger $logger)
 {
     return function () use($user, $logger) {
         $clients = DI::get()->getUsers();
         $clients->detach($user);
         $logger->info("OnClose closure:\n                closed userId = {$user->getId()},\n                connId = {$user->getConnectionId()}\n                Total user count {$clients->getTotalCount()}\n", [__CLASS__]);
         $this->notifyOnClose($user, $clients);
         $this->cleanPendingQueue($user);
         ChannelsCollection::get()->clean($user);
         $props = $user->getProperties();
         $props->setOnlineCount(time() - $user->getLoginTime() + $props->getOnlineCount());
         $online = OnlineDAO::create();
         $online->setOnlineList($user->getChannelId());
         $user->save();
         //update access time
         $sessionHandler = DI::get()->getSession();
         $sessionHandler->store($user->getToken(), $user->getId());
         unset($clients);
         unset($sessionHandler);
         unset($user);
     };
 }
Exemplo n.º 8
0
 public static function run(ChainContainer $chain)
 {
     $duals = PendingDuals::get();
     $users = DI::get()->getUsers();
     $user = $chain->getFrom();
     $lang = $user->getLang();
     if ($user->getProperties()->getTim()->getId() == TimEnum::ANY) {
         $user->send(['msg' => $lang->getPhrase('SelectTIMinProfile')]);
         return;
     }
     if ($user->isInPrivateChat()) {
         $user->send(['msg' => $lang->getPhrase('ThisFunctionWorkInPublicOnly')]);
         return;
     }
     if ($duals->getUserPosition($user)) {
         $user->send(['msg' => $lang->getPhrase('YouAlreadySentRequestOnSearch')]);
         return;
     }
     if ($dualUserId = $duals->matchDual($user)) {
         $dualUser = $users->getClientById($dualUserId);
         $oldChatId = $user->getChannelId();
         $newChatRoomId = uniqid('_', 1);
         $channel = new Channel($newChatRoomId, 'Приват_' . $newChatRoomId);
         $channel->setOwnerId($user->getId());
         ChannelsCollection::get()->addChannel($channel);
         $dualUser->setChannelId($newChatRoomId);
         $dualUser->save();
         $user->setChannelId($newChatRoomId);
         $user->save();
         self::sendMatchResponse($users->getUsersByChatId($newChatRoomId), MsgToken::create('DualIsFound'));
         self::renewGuestsList($oldChatId, MsgToken::create('DualizationStarted'));
         self::sendRenewPositions($duals->getUsersByDual($user));
         return;
     }
     self::sendPendingResponse($user, MsgToken::create('DualPending'), true);
     self::dualGuestsList($user);
 }
Exemplo n.º 9
0
 private function onResponse(Chain $chain)
 {
     return function (Response $response) use($chain) {
         BufferedSink::createPromise($response)->then(function ($body) use($chain) {
             $logger = DI::get()->getLogger();
             $logger->info('Got http response: ' . $body);
             if (!($json = json_decode($body, 1))) {
                 return;
             }
             $logger->info('JSON decoded');
             $channelId = $chain->getUser()->getChannelId();
             /** @var UserCollection $users */
             $users = DI::get()->getUsers();
             $response = (new MusicResponse())->setInfo($json)->setChannelId($channelId);
             $loop = DI::get()->container()->get('eventloop');
             $loop->addTimer(1, function () use($users, $response, $logger) {
                 $users->setResponse($response)->notify(false);
                 $logger->info('Sent MusicResponse!');
             });
             $channel = ChannelsCollection::get()->getChannelById($channelId);
             $history = $channel->getHistory(0);
             foreach ($history as $k => $part) {
                 /** @var Msg $msgObj */
                 $msgObj = $part['msg'];
                 $string = $msgObj->getMsg($chain->getUser()->getLang());
                 if (!preg_match('~id="music-(' . $json['track_id'] . ')"~u', $string)) {
                     continue;
                 }
                 $logger->info('Replacing corresponding history row');
                 $string = str_replace('id="music-' . $json['track_id'] . '" data-src=""><span class="glyphicon glyphicon-play-circle">' . '</span> <span class="audio-title">...</span>', 'id="music-' . $json['track_id'] . '" data-src="' . $json['url'] . '" bind-play-click="1">' . '<span class="glyphicon glyphicon-play-circle"></span> ' . '<span class="audio-title">' . $json['artist'] . ' - ' . $json['track'] . '</span>', $string);
                 $part['msg'] = MsgRaw::create($string);
                 $channel->setRow($k, $part);
             }
         });
     };
 }
Exemplo n.º 10
0
 public static function channelNameDuplication()
 {
     return function ($name) {
         return ChannelsCollection::get()->getChannelByName(trim($name));
     };
 }
Exemplo n.º 11
0
<?php

use SocioChat\Clients\Channel;
use SocioChat\Clients\ChannelsCollection;
use SocioChat\DI;
use SocioChat\Message\MsgContainer;
$dumperCallback = function () use($config) {
    $logger = DI::get()->getLogger();
    $logger->info('Dumping chat log to file', ['CHATLOG']);
    $fn = ROOT . DIRECTORY_SEPARATOR . 'www' . DIRECTORY_SEPARATOR . 'chatlog.txt';
    if (!($fh = fopen($fn, 'w'))) {
        $logger->err('Unable to open file ' . $fn . ' to dump!');
        return;
    }
    $responses = ChannelsCollection::get()->getChannelById(1)->getHistory(0);
    foreach ($responses as $response) {
        if (!isset($response[Channel::TO_NAME])) {
            if (isset($response[Channel::USER_INFO])) {
                $info = $response[Channel::USER_INFO];
                $line = '<div>';
                if (isset($info[Channel::AVATAR_IMG])) {
                    $line .= '<div class="user-avatar" data-src="' . $info[Channel::AVATAR_IMG] . '">';
                    $line .= '<img src="' . $info[Channel::AVATAR_THUMB] . '"></div>';
                } else {
                    $line .= '<div class="user-avatar"><span class="glyphicon glyphicon-user"></span></div>';
                }
                $line .= ' <div class="nickname" title="[' . $response[Channel::TIME] . '] ' . $info[Channel::TIM] . '">' . $response[Channel::FROM_NAME] . '</div>';
            } else {
                $line = '<div class="system">';
            }
            /** @var $msg MsgContainer */
Exemplo n.º 12
0
 public static function setChannelName(ChainContainer $chain)
 {
     $user = $chain->getFrom();
     $request = $chain->getRequest();
     $lang = $user->getLang();
     if (!isset($request['name']) || !isset($request['channelId'])) {
         RespondError::make($user);
         return;
     }
     try {
         $form = (new Form())->import($request)->addRule('channelId', Rules::existsChannel(), $lang->getPhrase('ChannelNotExists'))->addRule('name', Rules::namePattern(100, true), $lang->getPhrase('InvalidNameFormat'), '_nameFormat')->addRule('name', Rules::channelNameDuplication(), $lang->getPhrase('InvalidNameFormat'), '_nameUnique');
     } catch (WrongRuleNameException $e) {
         RespondError::make($user, ['property' => $lang->getPhrase('InvalidProperty')]);
         return;
     }
     if (!$form->validate()) {
         RespondError::make($user, $form->getErrors());
         return;
     }
     $channel = ChannelsCollection::get()->getChannelById($request['channelId']);
     if ($channel->getOwnerId() != $user->getId()) {
         RespondError::make($user, [PropertiesDAO::USER_ID => $lang->getPhrase('InsufficientRights')]);
         return;
     }
     $channel->setName($request['name']);
 }
Exemplo n.º 13
0
    $pid = file_get_contents($pidFile);
    if (file_exists("/proc/{$pid}")) {
        $logger->error("Found already running daemon instance [pid = {$pid}], aborting.");
        exit(1);
    } else {
        unlink($pidFile);
    }
}
$fh = fopen($pidFile, 'w');
if ($fh) {
    fwrite($fh, getmypid());
}
fclose($fh);
$app = new Chat();
$loop = $container->get('eventloop');
$webSock = new Server($loop);
$webSock->listen($config->daemon->port, $config->daemon->host);
$server = new IoServer(new HttpServer(new WsServer($app)), $webSock);
$logger->info("Starting chat server daemon on " . $config->daemon->host . ":" . $config->daemon->port, ['CHAT-SERVER']);
$channels = ChannelsCollection::get()->addChannel((new Channel(1, 'Гостевая', false))->setOnJoinRule(function (Form $form, User $user) {
    return true;
}))->addChannel((new Channel(2, 'Храм просветленных', false))->setOnJoinRule(function (Form $form, User $user) {
    if ($user->getProperties()->getKarma() <= 1) {
        $form->markWrong('channelId', 'Вход разрешён только пользователям с положительной кармой!');
        return false;
    }
    return true;
}));
include_once 'dumper.php';
include_once 'msgsaver.php';
$loop->run();
Exemplo n.º 14
0
<?php

use SocioChat\Clients\ChannelsCollection;
use SocioChat\DI;
$logger = DI::get()->getLogger();
$memcache = DI::get()->getMemcache();
$channels = ChannelsCollection::get();
$logger->info('Restoring history from memcache');
$memcache->get('sociochat.channels', $json);
if ($list = json_decode($json, 1)) {
    foreach ($list as $id => $channelInfo) {
        $channel = $channels->getChannelById($id);
        if (null === $channel) {
            $logger->info('Creating channel id = ' . $id);
            $channel = new \SocioChat\Clients\Channel($id, $channelInfo['name'], $channelInfo['isPrivate']);
            $channels->addChannel($channel);
        }
        $logger->info('Loading messages in channelId ' . $id);
        $logger->info(print_r($channelInfo['responses'], 1));
        if (!isset($channelInfo['responses'])) {
            continue;
        }
        foreach ($channelInfo['responses'] as $response) {
            $channel->pushRawResponse($response);
        }
        $channel->setLastMsgId($channelInfo['lastMsgId']);
    }
}
$saverCallback = function () use($config, $logger, $memcache, $channels) {
    $logger->info('Dumping chat log to memcached');
    $memcache->set('sociochat.channels', json_encode($channels->exportChannels()));
Exemplo n.º 15
0
 /**
  * @return null|Channel
  */
 public function getChannel()
 {
     return ChannelsCollection::get()->getChannelById($this->getChannelId());
 }