livecoding-console/src/Deblan/Command/PlayCommand.php

80 lines
2.5 KiB
PHP
Raw Normal View History

2015-07-13 22:32:34 +02:00
<?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();
2015-07-14 00:19:59 +02:00
$stream = strtolower(trim($input->getArgument('stream'), "/ \r\n"));
2015-07-13 22:32:34 +02:00
2015-07-14 00:47:32 +02:00
if (0 === preg_match('/^[\w-]+$/', $stream)) {
2015-07-14 00:25:03 +02:00
$output->writeln('<error>The stream name is not valid.</error>');
2015-07-13 22:32:34 +02:00
return false;
}
$output->writeln(sprintf('Playing <comment>%s</comment>', $stream));
if (!empty($config['player']['before'])) {
$command = $config['player']['before'];
2015-07-14 00:25:03 +02:00
$process = new Process($command);
$process->run();
2015-07-13 22:32:34 +02:00
}
$hash = $this->getHash($this->getApplication()->buildUrl($stream.'/'));
$command = $this->getApplication()->getPlayer($stream.'?t='.$hash);
$process = new Process($command);
2015-07-14 00:25:03 +02:00
if (!$this->getApplication()->isDebugMode()) {
2015-07-13 22:32:34 +02:00
$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];
}
}