livecoding-console/src/Deblan/Command/PlayCommand.php
2015-07-14 00:19:59 +02:00

80 lines
2.5 KiB
PHP

<?php
namespace Deblan\Command;
use RuntimeException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Process\Process;
class PlayCommand extends Command
{
protected function configure()
{
$this
->setName('play')
->setDescription('Play a stream')
->addArgument('stream', InputArgument::REQUIRED, 'Name of the stream')
// ->addOption('bar', null, InputOption::VALUE_NONE, '')
->setHelp("The <info>%command.name%</info> ");
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$config = $this->getApplication()->getConfigLoader()->getConfig();
$stream = strtolower(trim($input->getArgument('stream'), "/ \r\n"));
if (0 === preg_match('/^\w+$/', $stream)) {
$output->writeln('<error>The stream name is not valid.');
return false;
}
$output->writeln(sprintf('Playing <comment>%s</comment>', $stream));
if (!empty($config['player']['before'])) {
$command = $config['player']['before'];
// $process = new Process($command);
// $process->run();
}
$hash = $this->getHash($this->getApplication()->buildUrl($stream.'/'));
$command = $this->getApplication()->getPlayer($stream.'?t='.$hash);
$process = new Process($command);
if ($this->getApplication()->isDebugMode()) {
$callback = function ($type, $buffer) use ($output) {
if ('err' !== $type) {
$output->writeln($buffer);
}
};
} else {
$callback = function ($type, $buffer) use ($output) {
if ('err' === $type) {
$output->writeln(sprintf('<error>%s</error>', $buffer));
} else {
$output->writeln($buffer);
}
};
}
$process->run($callback);
}
protected function getHash($streamUrl)
{
$page = file_get_contents($streamUrl);
preg_match('/var streamURL = ".+\?t=([^"]+)"/s', $page, $match);
if (!isset($match[1])) {
throw new RuntimeException('Hash is not accessible.');
}
return $match[1];
}
}