/**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $playbookFile = $input->getOption('playbook');
     $playbook = $this->fileLoader->load($playbookFile);
     $this->variablesPlacer->setVars(Registry::get('container')['argv_parser']->all());
     $this->variablesPlacer->setText($playbook);
     $playbook = $this->variablesPlacer->place();
     $url = sprintf('http://%s:%d/playbook/run/', $input->getOption('host'), $input->getOption('port'));
     $response = $this->curlRequest->getCurlResult($url, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => ['playbook' => urlencode($playbook), 'filename' => $playbookFile], CURLOPT_TIMEOUT_MS => 100000]);
     echo $response['body'];
 }
 /**
  * @param ActionDto $dto
  * @return null
  */
 public function processAction(ActionDto $dto)
 {
     $container = Registry::get('container');
     $commandName = $dto->get('command');
     /** @var CommandHandlerInterface $command */
     $command = $container['command_' . $commandName];
     if (null === $command) {
         return;
     }
     $command->processCommand($dto->get('args'), $dto->get('channel'));
 }
Example #3
0
 /**
  * Configures console application
  */
 public function bootstrap()
 {
     $coreBuilder = new CoreBuilder();
     $this->container = $coreBuilder->buildContainer($this->argParser, $this->config);
     $coreBuilder->buildLogger($this->container);
     Registry::set('container', $this->container);
     $this->app = new ConsoleApp('CMS Slack Bot', '@package_version@');
     $this->app->add(new commands\ServerStartCommand($this->container['config'], $this->container['argv_parser']));
     $this->app->add(new commands\ServerStopCommand($this->container['config']));
     $this->app->add(new commands\ServerStatusCommand($this->container['config']));
     $this->app->add(new commands\PlaybookRunCommand($this->container['curl_request'], $this->container['variables_placer'], $this->container['file_loader']));
     $this->app->add(new commands\RtmStartCommand($this->config, $this->container['curl_request']));
     $this->app->add(new commands\RtmStopCommand($this->container['config']));
     $this->app->add(new commands\CronWorkerCommand($this->container['curl_request'], $this->container['cron_expression'], $this->container['file_loader']));
     $this->app->add(new commands\ApiStubStartCommand());
     $this->app->add(new commands\RtmStubStartCommand());
 }
 public function processCommand(array $args, $channel)
 {
     /** @var Container $container */
     $container = Registry::get('container');
     /** @var SlackFacade $slackFacade */
     $slackFacade = $container['slack_facade'];
     $currentUserId = $slackFacade->getMyId();
     $this->postMessage($channel, sprintf('I\'m `@%s` (ID `%s`), started %s', $slackFacade->getMyName(), $currentUserId, (new TimeAgoHelper())->format($container['started'])));
     $channels = Ar::map($slackFacade->getUserChannels($currentUserId), function ($channel) {
         return [Ar::get($channel, 'id') => ['name' => Ar::get($channel, 'name'), 'members' => count(Ar::get($channel, 'members'))]];
     });
     $groups = Ar::map($slackFacade->getUserGroups($currentUserId), function ($group) {
         return [Ar::get($group, 'id') => ['name' => Ar::get($group, 'name'), 'members' => count(Ar::get($group, 'members'))]];
     });
     $channelsOutput = (new Tabler())->setRenderer(new MysqlStyleRenderer())->setHeaders(['name' => 'Channel', 'members' => '# of members'])->setData($channels)->render();
     $groupsOutput = (new Tabler())->setRenderer(new MysqlStyleRenderer())->setHeaders(['name' => 'Group', 'members' => '# of members'])->setData($groups)->render();
     $this->postMessage($channel, sprintf('My channels (%d): ```%s```', count($channels), $channelsOutput));
     $this->postMessage($channel, sprintf('My groups (%d): ```%s```', count($groups), $groupsOutput));
 }
Example #5
0
 /**
  * @return Logger
  */
 public static function get()
 {
     $container = Registry::get('container');
     return $container['logger'];
 }
 protected function checkSlackConnection()
 {
     /** @var Container $container */
     $container = Registry::get('container');
     /** @var SlackApi $slackApi */
     $slackApi = $container['slack_api'];
     $this->testResponse = $slackApi->apiTest();
     return (bool) Ar::get($this->testResponse, 'ok');
 }
Example #7
0
 /** @test */
 public function shouldReturnNullOnNonExistentKey()
 {
     $this->assertEquals(null, Registry::get('test1'));
 }
Example #8
0
 public function buildServer()
 {
     $server = new Server("SlackBot", "0.1");
     $server->post('/playbook/run/', function (Request $request, Response $response, $next) {
         $rawData = $request->getData();
         $postParser = Registry::get('container')['post_parser'];
         $parsedData = $postParser->parse($rawData);
         $playbook = urldecode($parsedData['playbook']);
         $yamlParser = Registry::get('container')['yaml_parser'];
         $playbook = $yamlParser->parse($playbook);
         /** @var SlackApi $slackApi */
         $slackApi = Registry::get('container')['slack_api'];
         $playbookToken = Ar::get($playbook, 'auth.token');
         $oldToken = null;
         if (null !== $playbookToken) {
             $oldToken = $slackApi->getToken();
             $slackApi->setToken($playbookToken);
         }
         $executor = new PlaybookExecutor(Registry::get('container')['core_processor']);
         Variables::clear();
         $executor->execute($playbook);
         $response->write('Playbook executed successfully');
         $response->end();
         if (null !== $playbookToken) {
             $slackApi->setToken($oldToken);
         }
         $fileName = basename($parsedData['filename']);
         echo '[INFO] Executing playbook file ' . $fileName . "\n";
         $next();
     });
     $server->post('/command/run/', function (Request $request, Response $response, $next) {
         $rawData = $request->getData();
         $postParser = Registry::get('container')['post_parser'];
         $parsedData = $postParser->parse($rawData);
         $command = urldecode($parsedData['command']);
         $coreProcessor = Registry::get('container')['core_processor'];
         $dto = new RequestDto();
         $dto->setData(['type' => 'message', 'channel' => 'cron', 'user' => 'cron', 'text' => $command, 'ts' => time()]);
         $coreProcessor->processCommand($dto);
         $response->write('Playbook executed successfully');
         $response->end();
         echo '[INFO] Executing command ' . $command . "\n";
         $next();
     });
     $server->post('/process/message/', function (Request $request, Response $response, $next) {
         $response->sendHeaders();
         $response->writeJson(['ok' => true]);
         $response->end();
         $rawData = $request->getData();
         $postParser = Registry::get('container')['post_parser'];
         $parsedData = $postParser->parse($rawData);
         /** @var CoreProcessor $coreProcessor */
         $coreProcessor = Registry::get('container')['core_processor'];
         $dto = new RequestDto();
         $dto->setSource('rtm');
         $dto->setData(json_decode(Ar::get($parsedData, 'message'), true));
         $coreProcessor->process($dto);
         $next();
     });
     $server->get('/info/cron/', function (Request $request, Response $response, $next) {
         $response->writeJson(Registry::get('container')['config']->getSection('cron'));
         $response->end();
         $next();
     });
     return $server;
 }
Example #9
0
 /**
  * Fires request to Slack server and returns response
  * @param string $method Slack API method to call
  * @param array $data request data
  * @return array
  * @throws \Exception
  */
 private function processRequest($method, $data = [])
 {
     $methodsToFilter = ['api.test', 'rtm.start', 'chat.postMessage'];
     $method = $this->getApiMethodName($method);
     $url = self::BASE_URL . $method;
     $data['token'] = $this->token;
     if (true !== Ar::get($data, 'in_logger')) {
         Logger::get()->raw("➡️ %s", $url, json_encode($data));
     }
     /** @var ApiCache $cache */
     $cache = Registry::get('container')['api_cache'];
     $cachedResponse = $cache->get($url, $data);
     if (null !== $cachedResponse && !in_array($method, $methodsToFilter)) {
         if (true !== Ar::get($data, 'in_logger')) {
             Logger::get()->raw("⬅️ %s: cache hit", $url);
         }
         return $cachedResponse;
     }
     $result = $this->curlRequest->getCurlResult($url, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => $data])['body'];
     if (true !== Ar::get($data, 'in_logger')) {
         Logger::get()->raw("⬅️ %s", $url, $result);
     }
     if (!in_array($method, $methodsToFilter)) {
         $cache->set($url, $data, json_decode($result, true));
     }
     return json_decode($result, true);
 }
Example #10
0
 /**
  * @param RequestDto $dto
  * @param $commandHandler
  * @return bool
  */
 protected function checkAccess(RequestDto $dto, CommandHandlerInterface $commandHandler)
 {
     /** @var Config $config */
     $config = Registry::get('container')['config'];
     $acl = $commandHandler->getAcl();
     if (CommandHandlerInterface::ACL_ANY === $acl) {
         return true;
     } elseif (CommandHandlerInterface::ACL_ADMIN === $acl) {
         $currentUser = $dto->getUser();
         $currentUserName = $this->slackFacade->getUserNameById($currentUser);
         $admins = $config->getEntry('acl.admins') ?: [];
         if (0 === count($admins)) {
             return false;
         }
         return in_array($currentUserName, $admins);
     } else {
         if (!is_array($acl)) {
             throw new \RuntimeException('Wrong ACL format: array expected');
         }
         $currentUser = $dto->getUser();
         $aclUsers = [];
         foreach ($acl as $aclItem) {
             $aclUsers = array_merge($aclUsers, $this->slackFacade->getRecipientUsersIds($aclItem));
         }
         $aclUsers = array_unique($aclUsers);
         return in_array($currentUser, $aclUsers);
     }
 }
Example #11
0
 /**
  * Unset all variables
  */
 public static function clear()
 {
     Registry::set('variables', []);
 }
 /**
  * @return \Pimple\Container
  */
 protected function getContainer()
 {
     return Registry::get('container');
 }