1
0
Fork 0
mirror of https://codeberg.org/demostf/api.git synced 2026-06-03 18:04:08 +02:00

Add php-cs-fixer

This commit is contained in:
Robin Appelman 2017-07-30 14:51:54 +02:00
commit 309ae17036
54 changed files with 4900 additions and 4106 deletions

View file

@ -20,111 +20,111 @@ use Doctrine\DBAL\Connection;
use RandomLib\Generator;
class Container {
private $connection;
private $generator;
private $baseUrl;
private $parserUrl;
private $storeRoot;
private $storeUrl;
private $apiRoot;
private $editKey;
private $connection;
private $generator;
private $baseUrl;
private $parserUrl;
private $storeRoot;
private $storeUrl;
private $apiRoot;
private $editKey;
public function __construct(
Connection $connection,
Generator $generator,
string $baseUrl,
string $parserUrl,
string $storeRoot,
string $storeUrl,
string $apiRoot,
string $editKey
) {
$this->connection = $connection;
$this->generator = $generator;
$this->baseUrl = $baseUrl;
$this->parserUrl = $parserUrl;
$this->storeRoot = $storeRoot;
$this->storeUrl = $storeUrl;
$this->apiRoot = $apiRoot;
$this->editKey = $editKey;
}
public function __construct(
Connection $connection,
Generator $generator,
string $baseUrl,
string $parserUrl,
string $storeRoot,
string $storeUrl,
string $apiRoot,
string $editKey
) {
$this->connection = $connection;
$this->generator = $generator;
$this->baseUrl = $baseUrl;
$this->parserUrl = $parserUrl;
$this->storeRoot = $storeRoot;
$this->storeUrl = $storeUrl;
$this->apiRoot = $apiRoot;
$this->editKey = $editKey;
}
public function getAuthProvider(): AuthProvider {
return new AuthProvider($this->connection, $this->generator);
}
public function getAuthProvider(): AuthProvider {
return new AuthProvider($this->connection, $this->generator);
}
public function getChatProvider(): ChatProvider {
return new ChatProvider($this->connection);
}
public function getChatProvider(): ChatProvider {
return new ChatProvider($this->connection);
}
public function getDemoListProvider(): DemoListProvider {
return new DemoListProvider($this->connection);
}
public function getDemoListProvider(): DemoListProvider {
return new DemoListProvider($this->connection);
}
public function getDemoProvider(): DemoProvider {
return new DemoProvider($this->connection);
}
public function getDemoProvider(): DemoProvider {
return new DemoProvider($this->connection);
}
public function getInfoProvider(): InfoProvider {
return new InfoProvider($this->connection);
}
public function getInfoProvider(): InfoProvider {
return new InfoProvider($this->connection);
}
public function getKillProvider(): KillProvider {
return new KillProvider($this->connection);
}
public function getKillProvider(): KillProvider {
return new KillProvider($this->connection);
}
public function getPlayerProvider(): PlayerProvider {
return new PlayerProvider($this->connection);
}
public function getPlayerProvider(): PlayerProvider {
return new PlayerProvider($this->connection);
}
public function getUploadProvider(): UploadProvider {
return new UploadProvider(
$this->connection,
$this->baseUrl,
new HeaderParser(),
new Parser(new RawParser($this->parserUrl)),
new DemoStore($this->storeRoot, $this->storeUrl),
$this->getUserProvider(),
$this->getDemoProvider(),
new DemoSaver(
$this->getKillProvider(),
$this->getPlayerProvider(),
$this->getChatProvider(),
$this->getUserProvider(),
$this->getDemoProvider()
)
);
}
public function getUploadProvider(): UploadProvider {
return new UploadProvider(
$this->connection,
$this->baseUrl,
new HeaderParser(),
new Parser(new RawParser($this->parserUrl)),
new DemoStore($this->storeRoot, $this->storeUrl),
$this->getUserProvider(),
$this->getDemoProvider(),
new DemoSaver(
$this->getKillProvider(),
$this->getPlayerProvider(),
$this->getChatProvider(),
$this->getUserProvider(),
$this->getDemoProvider()
)
);
}
public function getUserProvider(): UserProvider {
return new UserProvider($this->connection, $this->generator);
}
public function getUserProvider(): UserProvider {
return new UserProvider($this->connection, $this->generator);
}
public function getBaseUrl(): string {
return $this->baseUrl;
}
public function getBaseUrl(): string {
return $this->baseUrl;
}
public function getParserUrl(): string {
return $this->parserUrl;
}
public function getParserUrl(): string {
return $this->parserUrl;
}
public function getStoreRoot(): string {
return $this->storeRoot;
}
public function getStoreRoot(): string {
return $this->storeRoot;
}
public function getStoreUrl(): string {
return $this->storeUrl;
}
public function getStoreUrl(): string {
return $this->storeUrl;
}
public function getApiRoot(): string {
return $this->apiRoot;
}
public function getApiRoot(): string {
return $this->apiRoot;
}
public function getEditKey(): string {
return $this->editKey;
}
public function getEditKey(): string {
return $this->editKey;
}
public function getConnection(): Connection {
return $this->connection;
}
public function getConnection(): Connection {
return $this->connection;
}
}

View file

@ -6,69 +6,69 @@ use Demostf\API\Providers\UserProvider;
use flight\Engine;
class AuthController extends BaseController {
/**
* @var UserProvider
*/
private $userProvider;
/**
* @var UserProvider
*/
private $userProvider;
/**
* @var AuthProvider
*/
private $authProvider;
/**
* @var AuthProvider
*/
private $authProvider;
/** @var string */
private $host;
/** @var string */
private $host;
private $apiRoot;
private $apiRoot;
public function __construct(UserProvider $userProvider, AuthProvider $authProvider, string $host, string $apiRoot) {
$this->userProvider = $userProvider;
$this->authProvider = $authProvider;
$this->host = $host;
$this->apiRoot = $apiRoot;
}
public function __construct(UserProvider $userProvider, AuthProvider $authProvider, string $host, string $apiRoot) {
$this->userProvider = $userProvider;
$this->authProvider = $authProvider;
$this->host = $host;
$this->apiRoot = $apiRoot;
}
public function token() {
echo $this->authProvider->generateToken();
}
public function token() {
echo $this->authProvider->generateToken();
}
public function get($token) {
$userData = $this->authProvider->getUser($token);
\Flight::json([
'token' => $token,
'steamid' => $userData['steamid'],
'name' => $userData['name'],
'key' => $userData['key']
]);
}
public function get($token) {
$userData = $this->authProvider->getUser($token);
\Flight::json([
'token' => $token,
'steamid' => $userData['steamid'],
'name' => $userData['name'],
'key' => $userData['key']
]);
}
public function login($token) {
$_SESSION['return'] = $this->query('return', 'https://' . $this->host);
$steam = new SteamLogin();
$url = $steam->url($this->apiRoot . '/auth/handle/' . urlencode($token), $this->apiRoot);
\Flight::redirect(str_replace('&', '&', $url)); // headers make no sense
}
public function login($token) {
$_SESSION['return'] = $this->query('return', 'https://' . $this->host);
$steam = new SteamLogin();
$url = $steam->url($this->apiRoot . '/auth/handle/' . urlencode($token), $this->apiRoot);
\Flight::redirect(str_replace('&', '&', $url)); // headers make no sense
}
public function logout($token) {
$this->authProvider->logout($token);
\Flight::json([
'token' => $token,
'steamid' => null,
'name' => null,
'key' => null
]);
}
public function logout($token) {
$this->authProvider->logout($token);
\Flight::json([
'token' => $token,
'steamid' => null,
'name' => null,
'key' => null
]);
}
public function handle($token) {
$return = $_SESSION['return'] ?? 'https://' . $this->host;
unset($_SESSION['return']);
$steam = new SteamLogin();
$steamId = $steam->validate();
if ($steamId) {
$steamIdObject = new \SteamId($steamId);
$key = $this->userProvider->store($steamIdObject);
$this->authProvider->setUser($token, $steamIdObject, $key);
}
\Flight::redirect($return);
}
public function handle($token) {
$return = $_SESSION['return'] ?? 'https://' . $this->host;
unset($_SESSION['return']);
$steam = new SteamLogin();
$steamId = $steam->validate();
if ($steamId) {
$steamIdObject = new \SteamId($steamId);
$key = $this->userProvider->store($steamIdObject);
$this->authProvider->setUser($token, $steamIdObject, $key);
}
\Flight::redirect($return);
}
}

View file

@ -1,20 +1,18 @@
<?php namespace Demostf\API\Controllers;
class BaseController {
protected function query($name, $default) {
$request = \Flight::request();
return isset($request->query[$name]) ? $request->query[$name] : $default;
}
protected function query($name, $default) {
$request = \Flight::request();
return isset($request->query[$name]) ? $request->query[$name] : $default;
}
protected function file($name) {
$request = \Flight::request();
return $request->files[$name];
}
protected function file($name) {
$request = \Flight::request();
return $request->files[$name];
}
protected function post($name, $default = null) {
$request = \Flight::request();
return isset($request->data[$name]) ? $request->data[$name] : $default;
}
protected function post($name, $default = null) {
$request = \Flight::request();
return isset($request->data[$name]) ? $request->data[$name] : $default;
}
}

View file

@ -6,97 +6,97 @@ use Demostf\API\Providers\DemoProvider;
use flight\Engine;
class DemoController extends BaseController {
/** @var DemoProvider */
private $demoProvider;
/** @var DemoProvider */
private $demoProvider;
/** @var ChatProvider */
private $chatProvider;
/** @var ChatProvider */
private $chatProvider;
private $demoListProvider;
private $demoListProvider;
private $editKey;
private $editKey;
public function __construct(DemoProvider $demoProvider, ChatProvider $chatProvider, DemoListProvider $demoListProvider, string $editKey) {
$this->demoProvider = $demoProvider;
$this->chatProvider = $chatProvider;
$this->demoListProvider = $demoListProvider;
$this->editKey = $editKey;
}
public function __construct(DemoProvider $demoProvider, ChatProvider $chatProvider, DemoListProvider $demoListProvider, string $editKey) {
$this->demoProvider = $demoProvider;
$this->chatProvider = $chatProvider;
$this->demoListProvider = $demoListProvider;
$this->editKey = $editKey;
}
/**
* @param string $id
*/
public function get($id) {
\Flight::json($this->demoProvider->get($id));
}
/**
* @param string $id
*/
public function get($id) {
\Flight::json($this->demoProvider->get($id));
}
protected function getFilter() {
$map = $this->query('map', '');
$players = $this->query('players', '');
$type = $this->query('type', '');
$filter = [];
if ($map) {
$filter['map'] = $map;
}
if ($players) {
if (!is_array($players)) {
$players = explode(',', $players);
}
$players = array_filter($players);
$filter['players'] = $players;
}
switch ($type) {
case 'hl':
$filter['playerCount'] = [17, 18, 19];
break;
case '6v6':
$filter['playerCount'] = [11, 12, 13];
break;
case '4v4':
$filter['playerCount'] = [7, 8, 9];
break;
}
return $filter;
}
protected function getFilter() {
$map = $this->query('map', '');
$players = $this->query('players', '');
$type = $this->query('type', '');
$filter = [];
if ($map) {
$filter['map'] = $map;
}
if ($players) {
if (!is_array($players)) {
$players = explode(',', $players);
}
$players = array_filter($players);
$filter['players'] = $players;
}
switch ($type) {
case 'hl':
$filter['playerCount'] = [17, 18, 19];
break;
case '6v6':
$filter['playerCount'] = [11, 12, 13];
break;
case '4v4':
$filter['playerCount'] = [7, 8, 9];
break;
}
return $filter;
}
public function listDemos() {
$page = $this->query('page', 1);
$order = $this->query('order', 'DESC') === 'ASC' ? 'ASC' : 'DESC';
\Flight::json($this->demoListProvider->listDemos($page, $this->getFilter(), $order));
}
public function listDemos() {
$page = $this->query('page', 1);
$order = $this->query('order', 'DESC') === 'ASC' ? 'ASC' : 'DESC';
\Flight::json($this->demoListProvider->listDemos($page, $this->getFilter(), $order));
}
public function listProfile($steamid) {
$page = $this->query('page', 1);
$where = $this->getFilter();
$where['players'][] = $steamid;
\Flight::json($this->demoListProvider->listProfile($page, $where));
}
public function listProfile($steamid) {
$page = $this->query('page', 1);
$where = $this->getFilter();
$where['players'][] = $steamid;
\Flight::json($this->demoListProvider->listProfile($page, $where));
}
public function listUploads($steamid) {
$page = $this->query('page', 1);
\Flight::json($this->demoListProvider->listUploads($steamid, $page, $this->getFilter()));
}
public function listUploads($steamid) {
$page = $this->query('page', 1);
\Flight::json($this->demoListProvider->listUploads($steamid, $page, $this->getFilter()));
}
public function chat($demoId) {
\Flight::json($this->chatProvider->getChat($demoId));
}
public function chat($demoId) {
\Flight::json($this->chatProvider->getChat($demoId));
}
public function setDemoUrl($id) {
$hash = $this->post('hash', '');
$backend = $this->post('backend', '');
$path = $this->post('path', '');
$url = $this->post('url', '');
$editKey = $this->post('key', '');
if ($editKey !== $this->editKey || $editKey === '') {
throw new \InvalidArgumentException('Invalid key');
}
public function setDemoUrl($id) {
$hash = $this->post('hash', '');
$backend = $this->post('backend', '');
$path = $this->post('path', '');
$url = $this->post('url', '');
$editKey = $this->post('key', '');
if ($editKey !== $this->editKey || $editKey === '') {
throw new \InvalidArgumentException('Invalid key');
}
$demo = $this->demoProvider->get((int)$id);
$existingHash = $demo->getHash();
if ($existingHash === '' || $existingHash === $hash) {
$this->demoProvider->setDemoUrl((int)$id, $backend, $url, $path);
} else {
throw new \InvalidArgumentException('Invalid demo hash');
}
}
$demo = $this->demoProvider->get((int)$id);
$existingHash = $demo->getHash();
if ($existingHash === '' || $existingHash === $hash) {
$this->demoProvider->setDemoUrl((int)$id, $backend, $url, $path);
} else {
throw new \InvalidArgumentException('Invalid demo hash');
}
}
}

View file

@ -4,18 +4,18 @@ use Demostf\API\Providers\InfoProvider;
use flight\Engine;
class InfoController extends BaseController {
/** @var InfoProvider */
private $infoProvider;
/** @var InfoProvider */
private $infoProvider;
public function __construct(InfoProvider $infoProvider) {
$this->infoProvider = $infoProvider;
}
public function __construct(InfoProvider $infoProvider) {
$this->infoProvider = $infoProvider;
}
public function listMaps() {
\Flight::json($this->infoProvider->listMaps());
}
public function listMaps() {
\Flight::json($this->infoProvider->listMaps());
}
public function stats() {
\Flight::json($this->infoProvider->getStats());
}
public function stats() {
\Flight::json($this->infoProvider->getStats());
}
}

View file

@ -4,36 +4,36 @@ use Demostf\API\Providers\UploadProvider;
use flight\Engine;
class UploadController extends BaseController {
private $uploadProvider;
private $uploadProvider;
public function __construct(UploadProvider $uploadProvider) {
$this->uploadProvider = $uploadProvider;
}
public function __construct(UploadProvider $uploadProvider) {
$this->uploadProvider = $uploadProvider;
}
public function upload() {
$key = $this->post('key', '');
$red = $this->post('red', 'RED');
$blu = $this->post('blu', 'BLU');
$name = $this->post('name', 'Unnamed');
$demo = $this->file('demo');
if (is_null($demo)) {
echo 'No demo uploaded';
return;
}
$demoFile = $demo['tmp_name'];
public function upload() {
$key = $this->post('key', '');
$red = $this->post('red', 'RED');
$blu = $this->post('blu', 'BLU');
$name = $this->post('name', 'Unnamed');
$demo = $this->file('demo');
if (is_null($demo)) {
echo 'No demo uploaded';
return;
}
$demoFile = $demo['tmp_name'];
try {
$result = $this->uploadProvider->upload($key, $red, $blu, $name, $demoFile);
if ($result === 'Invalid key') {
\Flight::response()->status(401)->write($result)->send();
} else {
echo $result;
}
} catch (\Exception $e) {
\Flight::response()
->status(500)
->write($e->getMessage())
->send();
}
}
try {
$result = $this->uploadProvider->upload($key, $red, $blu, $name, $demoFile);
if ($result === 'Invalid key') {
\Flight::response()->status(401)->write($result)->send();
} else {
echo $result;
}
} catch (\Exception $e) {
\Flight::response()
->status(500)
->write($e->getMessage())
->send();
}
}
}

View file

@ -6,21 +6,21 @@ use Demostf\API\Providers\UserProvider;
use flight\Engine;
class UserController extends BaseController {
/**
* @var UserProvider
*/
private $userProvider;
/**
* @var UserProvider
*/
private $userProvider;
public function __construct(UserProvider $userProvider) {
$this->userProvider = $userProvider;
}
public function __construct(UserProvider $userProvider) {
$this->userProvider = $userProvider;
}
public function get($steamid) {
\Flight::json($this->userProvider->get($steamid));
}
public function get($steamid) {
\Flight::json($this->userProvider->get($steamid));
}
public function search() {
$query = $this->query('query', '');
\Flight::json($this->userProvider->search($query));
}
public function search() {
$query = $this->query('query', '');
\Flight::json($this->userProvider->search($query));
}
}

View file

@ -3,107 +3,107 @@
namespace Demostf\API\Data;
class DemoPlayer implements \JsonSerializable {
/** @var int */
private $id;
/** @var int */
private $userId;
/** @var string */
private $name;
/** @var string */
private $team;
/** @var string */
private $class;
/** @var string */
private $steamId;
/** @var string */
private $avatar;
/** @var int */
private $kills;
/** @var int */
private $assists;
/** @var int */
private $deaths;
/** @var int */
private $id;
/** @var int */
private $userId;
/** @var string */
private $name;
/** @var string */
private $team;
/** @var string */
private $class;
/** @var string */
private $steamId;
/** @var string */
private $avatar;
/** @var int */
private $kills;
/** @var int */
private $assists;
/** @var int */
private $deaths;
public function __construct(int $id, int $userId, string $name, string $team, string $class, string $steamId, string $avatar, int $kills, int $assists, int $deaths) {
$this->id = $id;
$this->userId = $userId;
$this->name = $name;
$this->team = $team;
$this->class = $class;
$this->steamId = $steamId;
$this->avatar = $avatar;
$this->kills = $kills;
$this->assists = $assists;
$this->deaths = $deaths;
}
public function __construct(int $id, int $userId, string $name, string $team, string $class, string $steamId, string $avatar, int $kills, int $assists, int $deaths) {
$this->id = $id;
$this->userId = $userId;
$this->name = $name;
$this->team = $team;
$this->class = $class;
$this->steamId = $steamId;
$this->avatar = $avatar;
$this->kills = $kills;
$this->assists = $assists;
$this->deaths = $deaths;
}
public function getId(): int {
return $this->id;
}
public function getId(): int {
return $this->id;
}
public function getUserId(): int {
return $this->userId;
}
public function getUserId(): int {
return $this->userId;
}
public function getName(): string {
return $this->name;
}
public function getName(): string {
return $this->name;
}
public function getTeam(): string {
return $this->team;
}
public function getTeam(): string {
return $this->team;
}
public function getClass(): string {
return $this->class;
}
public function getClass(): string {
return $this->class;
}
public function getSteamId(): string {
return $this->steamId;
}
public function getSteamId(): string {
return $this->steamId;
}
public function getAvatar(): string {
return $this->avatar;
}
public function getAvatar(): string {
return $this->avatar;
}
public function getKills(): int {
return $this->kills;
}
public function getKills(): int {
return $this->kills;
}
public function getAssists(): int {
return $this->assists;
}
public function getAssists(): int {
return $this->assists;
}
public function getDeaths(): int {
return $this->deaths;
}
public function getDeaths(): int {
return $this->deaths;
}
public static function fromRow($row): DemoPlayer {
return new DemoPlayer(
$row['id'],
$row['user_id'],
$row['name'],
$row['team'],
$row['class'],
$row['steamid'],
$row['avatar'],
$row['kills'],
$row['assists'],
$row['deaths']
);
}
public static function fromRow($row): DemoPlayer {
return new DemoPlayer(
$row['id'],
$row['user_id'],
$row['name'],
$row['team'],
$row['class'],
$row['steamid'],
$row['avatar'],
$row['kills'],
$row['assists'],
$row['deaths']
);
}
public function jsonSerialize() {
return [
'id' => $this->getId(),
'user_id' => $this->getUserId(),
'name' => $this->getName(),
'team' => $this->getTeam(),
'class' => $this->getClass(),
'steamid' => $this->getSteamId(),
'avatar' => $this->getAvatar(),
'kills' => $this->getKills(),
'assists' => $this->getAssists(),
'deaths' => $this->getDeaths()
];
}
public function jsonSerialize() {
return [
'id' => $this->getId(),
'user_id' => $this->getUserId(),
'name' => $this->getName(),
'team' => $this->getTeam(),
'class' => $this->getClass(),
'steamid' => $this->getSteamId(),
'avatar' => $this->getAvatar(),
'kills' => $this->getKills(),
'assists' => $this->getAssists(),
'deaths' => $this->getDeaths()
];
}
}

View file

@ -3,48 +3,48 @@
namespace Demostf\API\Data;
class Kill {
private $id;
private $id;
private $demoId;
private $demoId;
private $attackerId;
private $attackerId;
private $assisterId;
private $assisterId;
private $victimId;
private $victimId;
private $weapon;
private $weapon;
public function __construct(int $id, int $demoId, int $attackerId, int $assisterId, int $victimId, string $weapon) {
$this->id = $id;
$this->demoId = $demoId;
$this->attackerId = $attackerId;
$this->assisterId = $assisterId;
$this->victimId = $victimId;
$this->weapon = $weapon;
}
public function __construct(int $id, int $demoId, int $attackerId, int $assisterId, int $victimId, string $weapon) {
$this->id = $id;
$this->demoId = $demoId;
$this->attackerId = $attackerId;
$this->assisterId = $assisterId;
$this->victimId = $victimId;
$this->weapon = $weapon;
}
public function getId(): int {
return $this->id;
}
public function getId(): int {
return $this->id;
}
public function getDemoId(): int {
return $this->demoId;
}
public function getDemoId(): int {
return $this->demoId;
}
public function getAttackerId(): int {
return $this->attackerId;
}
public function getAttackerId(): int {
return $this->attackerId;
}
public function getAssisterId(): int {
return $this->assisterId;
}
public function getAssisterId(): int {
return $this->assisterId;
}
public function getVictimId(): int {
return $this->victimId;
}
public function getVictimId(): int {
return $this->victimId;
}
public function getWeapon(): string {
return $this->weapon;
}
public function getWeapon(): string {
return $this->weapon;
}
}

View file

@ -5,60 +5,60 @@ namespace Demostf\API\Data;
use Demostf\API\Demo\ChatMessage;
class ParsedDemo {
/** @var int */
private $redScore;
/** @var int */
private $blueScore;
/** @var ChatMessage[] */
private $chat;
/** @var ParsedPlayer[] */
private $players;
/** @var ParsedKill[] */
private $kills;
/** @var int */
private $redScore;
/** @var int */
private $blueScore;
/** @var ChatMessage[] */
private $chat;
/** @var ParsedPlayer[] */
private $players;
/** @var ParsedKill[] */
private $kills;
/**
* ParsedDemo constructor.
*
* @param int $redScore
* @param int $blueScore
* @param ChatMessage[] $chat
* @param ParsedPlayer[] $players
* @param ParsedKill[] $kills
*/
public function __construct(int $redScore, int $blueScore, array $chat, array $players, array $kills) {
$this->redScore = $redScore;
$this->blueScore = $blueScore;
$this->chat = $chat;
$this->players = $players;
$this->kills = $kills;
}
/**
* ParsedDemo constructor.
*
* @param int $redScore
* @param int $blueScore
* @param ChatMessage[] $chat
* @param ParsedPlayer[] $players
* @param ParsedKill[] $kills
*/
public function __construct(int $redScore, int $blueScore, array $chat, array $players, array $kills) {
$this->redScore = $redScore;
$this->blueScore = $blueScore;
$this->chat = $chat;
$this->players = $players;
$this->kills = $kills;
}
public function getRedScore(): int {
return $this->redScore;
}
public function getRedScore(): int {
return $this->redScore;
}
public function getBlueScore(): int {
return $this->blueScore;
}
public function getBlueScore(): int {
return $this->blueScore;
}
/**
* @return ChatMessage[]
*/
public function getChat(): array {
return $this->chat;
}
/**
* @return ChatMessage[]
*/
public function getChat(): array {
return $this->chat;
}
/**
* @return ParsedPlayer[]
*/
public function getPlayers(): array {
return $this->players;
}
/**
* @return ParsedPlayer[]
*/
public function getPlayers(): array {
return $this->players;
}
/**
* @return ParsedKill[]
*/
public function getKills(): array {
return $this->kills;
}
/**
* @return ParsedKill[]
*/
public function getKills(): array {
return $this->kills;
}
}

View file

@ -3,34 +3,34 @@
namespace Demostf\API\Data;
class ParsedKill {
private $attackerDemoId;
private $attackerDemoId;
private $assisterDemoId;
private $assisterDemoId;
private $victimDemoId;
private $victimDemoId;
private $weapon;
private $weapon;
public function __construct(int $attackerDemoId, int $assisterDemoId, int $victimDemoId, string $weapon) {
$this->attackerDemoId = $attackerDemoId;
$this->assisterDemoId = $assisterDemoId;
$this->victimDemoId = $victimDemoId;
$this->weapon = $weapon;
}
public function __construct(int $attackerDemoId, int $assisterDemoId, int $victimDemoId, string $weapon) {
$this->attackerDemoId = $attackerDemoId;
$this->assisterDemoId = $assisterDemoId;
$this->victimDemoId = $victimDemoId;
$this->weapon = $weapon;
}
public function getAttackerDemoId(): int {
return $this->attackerDemoId;
}
public function getAttackerDemoId(): int {
return $this->attackerDemoId;
}
public function getAssisterDemoId(): int {
return $this->assisterDemoId;
}
public function getAssisterDemoId(): int {
return $this->assisterDemoId;
}
public function getVictimDemoId(): int {
return $this->victimDemoId;
}
public function getVictimDemoId(): int {
return $this->victimDemoId;
}
public function getWeapon(): string {
return $this->weapon;
}
public function getWeapon(): string {
return $this->weapon;
}
}

View file

@ -3,42 +3,42 @@
namespace Demostf\API\Data;
class ParsedPlayer {
/** @var string */
private $name;
/** @var int */
private $demoUserId;
/** @var string */
private $steamId;
/** @var string */
private $team;
/** @var string` */
private $class;
/** @var string */
private $name;
/** @var int */
private $demoUserId;
/** @var string */
private $steamId;
/** @var string */
private $team;
/** @var string` */
private $class;
public function __construct(string $name, int $demoUserId, string $steamId, string $team, string $class) {
$this->name = $name;
$this->demoUserId = $demoUserId;
$this->steamId = $steamId;
$this->team = $team;
$this->class = $class;
}
public function __construct(string $name, int $demoUserId, string $steamId, string $team, string $class) {
$this->name = $name;
$this->demoUserId = $demoUserId;
$this->steamId = $steamId;
$this->team = $team;
$this->class = $class;
}
public function getName(): string {
return $this->name;
}
public function getName(): string {
return $this->name;
}
public function getDemoUserId(): int {
return $this->demoUserId;
}
public function getDemoUserId(): int {
return $this->demoUserId;
}
public function getSteamId(): string {
return $this->steamId;
}
public function getSteamId(): string {
return $this->steamId;
}
public function getTeam(): string {
return $this->team;
}
public function getTeam(): string {
return $this->team;
}
public function getClass(): string {
return $this->class;
}
public function getClass(): string {
return $this->class;
}
}

View file

@ -3,62 +3,62 @@
namespace Demostf\API\Data;
class Player {
/** @var int */
private $id;
/** @var int */
private $id;
/** @var int */
private $demoId;
/** @var int */
private $demoId;
/** @var int */
private $demoUserId;
/** @var int */
private $demoUserId;
/** @var int */
private $userId;
/** @var int */
private $userId;
/** @var string */
private $name;
/** @var string */
private $name;
/** @var string */
private $team;
/** @var string */
private $team;
/** @var string */
private $class;
/** @var string */
private $class;
public function __construct(int $id, int $demoId, int $demoUserId, int $userId, string $name, string $team, string $class) {
$this->id = $id;
$this->demoId = $demoId;
$this->demoUserId = $demoUserId;
$this->userId = $userId;
$this->name = $name;
$this->team = $team;
$this->class = $class;
}
public function __construct(int $id, int $demoId, int $demoUserId, int $userId, string $name, string $team, string $class) {
$this->id = $id;
$this->demoId = $demoId;
$this->demoUserId = $demoUserId;
$this->userId = $userId;
$this->name = $name;
$this->team = $team;
$this->class = $class;
}
public function getId(): int {
return $this->id;
}
public function getId(): int {
return $this->id;
}
public function getDemoId(): int {
return $this->demoId;
}
public function getDemoId(): int {
return $this->demoId;
}
public function getDemoUserId(): int {
return $this->demoUserId;
}
public function getDemoUserId(): int {
return $this->demoUserId;
}
public function getUserId(): int {
return $this->userId;
}
public function getUserId(): int {
return $this->userId;
}
public function getName(): string {
return $this->name;
}
public function getName(): string {
return $this->name;
}
public function getTeam(): string {
return $this->team;
}
public function getTeam(): string {
return $this->team;
}
public function getClass(): string {
return $this->class;
}
public function getClass(): string {
return $this->class;
}
}

View file

@ -3,28 +3,28 @@
namespace Demostf\API\Data;
class StoredDemo {
/** @var string */
private $url;
/** @var string */
private $backend;
/** @var string */
private $path;
/** @var string */
private $url;
/** @var string */
private $backend;
/** @var string */
private $path;
public function __construct(string $url, string $backend, string $path) {
$this->url = $url;
$this->backend = $backend;
$this->path = $path;
}
public function __construct(string $url, string $backend, string $path) {
$this->url = $url;
$this->backend = $backend;
$this->path = $path;
}
public function getUrl(): string {
return $this->url;
}
public function getUrl(): string {
return $this->url;
}
public function getBackend(): string {
return $this->backend;
}
public function getBackend(): string {
return $this->backend;
}
public function getPath(): string {
return $this->path;
}
public function getPath(): string {
return $this->path;
}
}

View file

@ -3,42 +3,42 @@
namespace Demostf\API\Data;
class Upload {
/** @var string */
private $name;
/** @var string */
private $red;
/** @var string */
private $blue;
/** @var int */
private $uploaderId;
/** @var string */
private $hash;
/** @var string */
private $name;
/** @var string */
private $red;
/** @var string */
private $blue;
/** @var int */
private $uploaderId;
/** @var string */
private $hash;
public function __construct(string $name, string $red, string $blue, int $uploaderId, string $hash) {
$this->name = $name;
$this->red = $red;
$this->blue = $blue;
$this->uploaderId = $uploaderId;
$this->hash = $hash;
}
public function __construct(string $name, string $red, string $blue, int $uploaderId, string $hash) {
$this->name = $name;
$this->red = $red;
$this->blue = $blue;
$this->uploaderId = $uploaderId;
$this->hash = $hash;
}
public function getName(): string {
return $this->name;
}
public function getName(): string {
return $this->name;
}
public function getRed(): string {
return $this->red;
}
public function getRed(): string {
return $this->red;
}
public function getBlue(): string {
return $this->blue;
}
public function getBlue(): string {
return $this->blue;
}
public function getUploaderId(): int {
return $this->uploaderId;
}
public function getUploaderId(): int {
return $this->uploaderId;
}
public function getHash(): string {
return $this->hash;
}
public function getHash(): string {
return $this->hash;
}
}

View file

@ -3,61 +3,61 @@
namespace Demostf\API\Data;
class User implements \JsonSerializable {
/** @var int */
private $id;
/** @var string */
private $steamId;
/** @var string */
private $name;
/** @var string */
private $avatar;
/** @var string */
private $token;
/** @var int */
private $id;
/** @var string */
private $steamId;
/** @var string */
private $name;
/** @var string */
private $avatar;
/** @var string */
private $token;
public function __construct(int $id, string $steamId, string $name, string $avatar, string $token) {
$this->id = $id;
$this->steamId = $steamId;
$this->name = $name;
$this->avatar = $avatar;
$this->token = $token;
}
public function __construct(int $id, string $steamId, string $name, string $avatar, string $token) {
$this->id = $id;
$this->steamId = $steamId;
$this->name = $name;
$this->avatar = $avatar;
$this->token = $token;
}
public function getId(): int {
return $this->id;
}
public function getId(): int {
return $this->id;
}
public function getSteamId(): string {
return $this->steamId;
}
public function getSteamId(): string {
return $this->steamId;
}
public function getName(): string {
return $this->name;
}
public function getName(): string {
return $this->name;
}
public function getAvatar(): string {
return $this->avatar;
}
public function getAvatar(): string {
return $this->avatar;
}
public function getToken(): string {
return $this->token;
}
public function getToken(): string {
return $this->token;
}
public function jsonSerialize() {
return [
'id' => $this->getId(),
'steamid' => $this->getSteamId(),
'name' => $this->getName(),
'avatar' => $this->getAvatar()
];
}
public function jsonSerialize() {
return [
'id' => $this->getId(),
'steamid' => $this->getSteamId(),
'name' => $this->getName(),
'avatar' => $this->getAvatar()
];
}
public static function fromRow(array $row): User {
return new User(
(int)$row['id'],
$row['steamid'],
$row['name'],
$row['avatar'],
$row['token'] ?? ''
);
}
public static function fromRow(array $row): User {
return new User(
(int)$row['id'],
$row['steamid'],
$row['name'],
$row['avatar'],
$row['token'] ?? ''
);
}
}

View file

@ -1,46 +1,46 @@
<?php namespace Demostf\API\Demo;
class ChatMessage {
/** @var string */
private $user;
/** @var string */
private $user;
/** @var integer */
private $time;
/** @var integer */
private $time;
/** @var string */
private $message;
/** @var string */
private $message;
/**
* ChatMessage constructor.
*
* @param string $user
* @param int $time
* @param string $message
*/
public function __construct(string $user, int $time, string $message) {
$this->user = $user;
$this->time = $time;
$this->message = $message;
}
/**
* ChatMessage constructor.
*
* @param string $user
* @param int $time
* @param string $message
*/
public function __construct(string $user, int $time, string $message) {
$this->user = $user;
$this->time = $time;
$this->message = $message;
}
/**
* @return string
*/
public function getUser(): string {
return $this->user;
}
/**
* @return string
*/
public function getUser(): string {
return $this->user;
}
/**
* @return int
*/
public function getTime(): int {
return $this->time;
}
/**
* @return int
*/
public function getTime(): int {
return $this->time;
}
/**
* @return string
*/
public function getMessage(): string {
return $this->message;
}
/**
* @return string
*/
public function getMessage(): string {
return $this->message;
}
}

View file

@ -4,215 +4,215 @@ use Demostf\API\Data\DemoPlayer;
use Demostf\API\Data\User;
class Demo implements \JsonSerializable {
/** @var int */
private $id;
/** @var string */
private $url;
/** @var string */
private $name;
/** @var string */
private $server;
/** @var float */
private $duration;
/** @var string */
private $nick;
/** @var string */
private $map;
/** @var \DateTime */
private $time;
/** @var string */
private $red;
/** @var string */
private $blue;
/** @var int */
private $redScore;
/** @var int */
private $blueScore;
/** @var int */
private $playerCount;
/** @var int */
private $uploader;
/** @var User|null */
private $uploaderUser;
/** @var DemoPlayer[] */
private $players;
/** @var string */
private $hash;
/** @var string */
private $backend;
/** @var string */
private $path;
/** @var int */
private $id;
/** @var string */
private $url;
/** @var string */
private $name;
/** @var string */
private $server;
/** @var float */
private $duration;
/** @var string */
private $nick;
/** @var string */
private $map;
/** @var \DateTime */
private $time;
/** @var string */
private $red;
/** @var string */
private $blue;
/** @var int */
private $redScore;
/** @var int */
private $blueScore;
/** @var int */
private $playerCount;
/** @var int */
private $uploader;
/** @var User|null */
private $uploaderUser;
/** @var DemoPlayer[] */
private $players;
/** @var string */
private $hash;
/** @var string */
private $backend;
/** @var string */
private $path;
public function __construct(
int $id,
string $url,
string $name,
string $server,
float $duration,
string $nick,
string $map,
\DateTime $time,
string $red,
string $blue,
int $redScore,
int $blueScore,
int $playerCount,
int $uploader,
string $hash,
string $backend,
string $path
) {
$this->id = $id;
$this->url = $url;
$this->name = $name;
$this->server = $server;
$this->duration = $duration;
$this->nick = $nick;
$this->map = $map;
$this->time = $time;
$this->red = $red;
$this->blue = $blue;
$this->redScore = $redScore;
$this->blueScore = $blueScore;
$this->playerCount = $playerCount;
$this->uploader = $uploader;
$this->hash = $hash;
$this->backend = $backend;
$this->path = $path;
}
public function __construct(
int $id,
string $url,
string $name,
string $server,
float $duration,
string $nick,
string $map,
\DateTime $time,
string $red,
string $blue,
int $redScore,
int $blueScore,
int $playerCount,
int $uploader,
string $hash,
string $backend,
string $path
) {
$this->id = $id;
$this->url = $url;
$this->name = $name;
$this->server = $server;
$this->duration = $duration;
$this->nick = $nick;
$this->map = $map;
$this->time = $time;
$this->red = $red;
$this->blue = $blue;
$this->redScore = $redScore;
$this->blueScore = $blueScore;
$this->playerCount = $playerCount;
$this->uploader = $uploader;
$this->hash = $hash;
$this->backend = $backend;
$this->path = $path;
}
public function getId(): int {
return $this->id;
}
public function getId(): int {
return $this->id;
}
public function getUrl(): string {
return $this->url;
}
public function getUrl(): string {
return $this->url;
}
public function getName(): string {
return $this->name;
}
public function getName(): string {
return $this->name;
}
public function getServer(): string {
return $this->server;
}
public function getServer(): string {
return $this->server;
}
public function getDuration(): float {
return $this->duration;
}
public function getDuration(): float {
return $this->duration;
}
public function getNick(): string {
return $this->nick;
}
public function getNick(): string {
return $this->nick;
}
public function getMap(): string {
return $this->map;
}
public function getMap(): string {
return $this->map;
}
public function getTime(): \DateTime {
return $this->time;
}
public function getTime(): \DateTime {
return $this->time;
}
public function getRed(): string {
return $this->red;
}
public function getRed(): string {
return $this->red;
}
public function getBlue(): string {
return $this->blue;
}
public function getBlue(): string {
return $this->blue;
}
public function getRedScore(): int {
return $this->redScore;
}
public function getRedScore(): int {
return $this->redScore;
}
public function getBlueScore(): int {
return $this->blueScore;
}
public function getBlueScore(): int {
return $this->blueScore;
}
public function getPlayerCount(): int {
return $this->playerCount;
}
public function getPlayerCount(): int {
return $this->playerCount;
}
public function getUploader(): int {
return $this->uploader;
}
public function getUploader(): int {
return $this->uploader;
}
public function getUploaderUser(): ?User {
return $this->uploaderUser;
}
public function getUploaderUser(): ?User {
return $this->uploaderUser;
}
public function setUploaderUser(User $uploaderUser) {
$this->uploaderUser = $uploaderUser;
}
public function setUploaderUser(User $uploaderUser) {
$this->uploaderUser = $uploaderUser;
}
public static function fromRow($row): Demo {
return new Demo(
(int)$row['id'],
$row['url'],
$row['name'],
$row['server'],
(int)$row['duration'],
$row['nick'],
$row['map'],
\DateTime::createFromFormat('U', '' . strtotime($row['created_at'])),
$row['red'],
$row['blu'],
(int)$row['scoreRed'],
(int)$row['scoreBlue'],
(int)$row['playerCount'],
(int)$row['uploader'],
$row['hash'],
$row['backend'],
$row['path']
);
}
public static function fromRow($row): Demo {
return new Demo(
(int)$row['id'],
$row['url'],
$row['name'],
$row['server'],
(int)$row['duration'],
$row['nick'],
$row['map'],
\DateTime::createFromFormat('U', '' . strtotime($row['created_at'])),
$row['red'],
$row['blu'],
(int)$row['scoreRed'],
(int)$row['scoreBlue'],
(int)$row['playerCount'],
(int)$row['uploader'],
$row['hash'],
$row['backend'],
$row['path']
);
}
/**
* @return DemoPlayer[]
*/
public function getPlayers(): array {
return $this->players;
}
/**
* @return DemoPlayer[]
*/
public function getPlayers(): array {
return $this->players;
}
public function setPlayers(array $players) {
$this->players = $players;
}
public function setPlayers(array $players) {
$this->players = $players;
}
public function getHash(): string {
return $this->hash;
}
public function getHash(): string {
return $this->hash;
}
public function getBackend(): string {
return $this->backend;
}
public function getBackend(): string {
return $this->backend;
}
public function getPath(): string {
return $this->path;
}
public function getPath(): string {
return $this->path;
}
public function jsonSerialize() {
$data = [
'id' => $this->getId(),
'url' => $this->getUrl(),
'name' => $this->getName(),
'server' => $this->getServer(),
'duration' => $this->getDuration(),
'nick' => $this->getNick(),
'map' => $this->getMap(),
'time' => $this->getTime()->getTimestamp(),
'red' => $this->getRed(),
'blue' => $this->getBlue(),
'redScore' => $this->getRedScore(),
'blueScore' => $this->getBlueScore(),
'playerCount' => $this->getPlayerCount(),
'uploader' => $this->uploaderUser ? $this->getUploaderUser()->jsonSerialize() : $this->getUploader(),
'hash' => $this->getHash(),
'backend' => $this->getBackend(),
'path' => $this->getPath()
];
if ($this->players) {
$data['players'] = $this->getPlayers();
}
return $data;
}
public function jsonSerialize() {
$data = [
'id' => $this->getId(),
'url' => $this->getUrl(),
'name' => $this->getName(),
'server' => $this->getServer(),
'duration' => $this->getDuration(),
'nick' => $this->getNick(),
'map' => $this->getMap(),
'time' => $this->getTime()->getTimestamp(),
'red' => $this->getRed(),
'blue' => $this->getBlue(),
'redScore' => $this->getRedScore(),
'blueScore' => $this->getBlueScore(),
'playerCount' => $this->getPlayerCount(),
'uploader' => $this->uploaderUser ? $this->getUploaderUser()->jsonSerialize() : $this->getUploader(),
'hash' => $this->getHash(),
'backend' => $this->getBackend(),
'path' => $this->getPath()
];
if ($this->players) {
$data['players'] = $this->getPlayers();
}
return $data;
}
}

View file

@ -14,79 +14,79 @@ use Demostf\API\Providers\PlayerProvider;
use Demostf\API\Providers\UserProvider;
class DemoSaver {
/** @var KillProvider */
private $killProvider;
/** @var PlayerProvider */
private $playerProvider;
/** @var ChatProvider */
private $chatProvider;
/** @var UserProvider */
private $userProvider;
/** @var DemoProvider */
private $demoProvider;
/** @var KillProvider */
private $killProvider;
/** @var PlayerProvider */
private $playerProvider;
/** @var ChatProvider */
private $chatProvider;
/** @var UserProvider */
private $userProvider;
/** @var DemoProvider */
private $demoProvider;
public function __construct(KillProvider $killProvider, PlayerProvider $playerProvider, ChatProvider $chatProvider, UserProvider $userProvider, DemoProvider $demoProvider) {
$this->killProvider = $killProvider;
$this->playerProvider = $playerProvider;
$this->chatProvider = $chatProvider;
$this->userProvider = $userProvider;
$this->demoProvider = $demoProvider;
}
public function __construct(KillProvider $killProvider, PlayerProvider $playerProvider, ChatProvider $chatProvider, UserProvider $userProvider, DemoProvider $demoProvider) {
$this->killProvider = $killProvider;
$this->playerProvider = $playerProvider;
$this->chatProvider = $chatProvider;
$this->userProvider = $userProvider;
$this->demoProvider = $demoProvider;
}
public function saveDemo(ParsedDemo $demo, Header $header, StoredDemo $storedDemo, Upload $upload): int {
/** @var int[] $userMap [$demoUserId => $dbUserId] */
$userMap = [0 => 0];
public function saveDemo(ParsedDemo $demo, Header $header, StoredDemo $storedDemo, Upload $upload): int {
/** @var int[] $userMap [$demoUserId => $dbUserId] */
$userMap = [0 => 0];
$demoId = $this->demoProvider->storeDemo(new Demo(
0,
$storedDemo->getUrl(),
$upload->getName(),
$header->getServer(),
$header->getDuration(),
$header->getNick(),
$header->getMap(),
new \DateTime(),
$upload->getRed(),
$upload->getBlue(),
$demo->getRedScore(),
$demo->getBlueScore(),
count($demo->getPlayers()),
$upload->getUploaderId(),
$upload->getHash(),
$storedDemo->getBackend(),
$storedDemo->getPath()
), $storedDemo->getBackend(), $storedDemo->getPath());
$demoId = $this->demoProvider->storeDemo(new Demo(
0,
$storedDemo->getUrl(),
$upload->getName(),
$header->getServer(),
$header->getDuration(),
$header->getNick(),
$header->getMap(),
new \DateTime(),
$upload->getRed(),
$upload->getBlue(),
$demo->getRedScore(),
$demo->getBlueScore(),
count($demo->getPlayers()),
$upload->getUploaderId(),
$upload->getHash(),
$storedDemo->getBackend(),
$storedDemo->getPath()
), $storedDemo->getBackend(), $storedDemo->getPath());
foreach ($demo->getPlayers() as $player) {
$userId = $this->userProvider->getUserId($player->getSteamId());
$userMap[$player->getDemoUserId()] = $userId;
foreach ($demo->getPlayers() as $player) {
$userId = $this->userProvider->getUserId($player->getSteamId());
$userMap[$player->getDemoUserId()] = $userId;
$this->playerProvider->store(new Player(
0,
$demoId,
$player->getDemoUserId(),
$userId,
$player->getName(),
$player->getTeam(),
$player->getClass()
));
}
$this->playerProvider->store(new Player(
0,
$demoId,
$player->getDemoUserId(),
$userId,
$player->getName(),
$player->getTeam(),
$player->getClass()
));
}
foreach ($demo->getKills() as $kill) {
$this->killProvider->store(new Kill(
0,
$demoId,
$userMap[$kill->getAttackerDemoId()],
$userMap[$kill->getAssisterDemoId()],
$userMap[$kill->getVictimDemoId()],
$kill->getWeapon()
));
}
foreach ($demo->getKills() as $kill) {
$this->killProvider->store(new Kill(
0,
$demoId,
$userMap[$kill->getAttackerDemoId()],
$userMap[$kill->getAssisterDemoId()],
$userMap[$kill->getVictimDemoId()],
$kill->getWeapon()
));
}
foreach ($demo->getChat() as $chat) {
$this->chatProvider->storeChatMessage($demoId, $chat);
}
foreach ($demo->getChat() as $chat) {
$this->chatProvider->storeChatMessage($demoId, $chat);
}
return $demoId;
}
return $demoId;
}
}

View file

@ -3,35 +3,35 @@
use Demostf\API\Data\StoredDemo;
class DemoStore {
/** @var string */
private $root;
/** @var string */
private $webroot;
/** @var string */
private $root;
/** @var string */
private $webroot;
public function __construct(string $root, string $webroot) {
$this->root = $root;
$this->webroot = $webroot;
}
public function __construct(string $root, string $webroot) {
$this->root = $root;
$this->webroot = $webroot;
}
public function store(string $sourcePath, string $name): StoredDemo {
$target = $this->generatePath($name);
if (!is_dir(dirname($target))) {
mkdir(dirname($target), 0777, true);
}
rename($sourcePath, $target);
chmod($target, 0755);
return new StoredDemo($this->getUrl($name), 'static', $target);
}
public function store(string $sourcePath, string $name): StoredDemo {
$target = $this->generatePath($name);
if (!is_dir(dirname($target))) {
mkdir(dirname($target), 0777, true);
}
rename($sourcePath, $target);
chmod($target, 0755);
return new StoredDemo($this->getUrl($name), 'static', $target);
}
private function generatePath(string $name): string {
return $this->root . $this->getPrefix($name) . $name;
}
private function generatePath(string $name): string {
return $this->root . $this->getPrefix($name) . $name;
}
private function getPrefix(string $name) {
return '/' . substr($name, 0, 2) . '/' . substr($name, 2, 2) . '/';
}
private function getPrefix(string $name) {
return '/' . substr($name, 0, 2) . '/' . substr($name, 2, 2) . '/';
}
private function getUrl(string $name): string {
return 'https://' . $this->webroot . $this->getPrefix($name) . $name;
}
private function getUrl(string $name): string {
return 'https://' . $this->webroot . $this->getPrefix($name) . $name;
}
}

View file

@ -6,144 +6,144 @@ namespace Demostf\API\Demo;
* HL2 demo metadata
*/
class Header {
/**
* @var string
*/
protected $type;
/**
* @var string
*/
protected $type;
/**
* @var int
*/
protected $version;
/**
* @var int
*/
protected $version;
/**
* @var int
*/
protected $protocol;
/**
* @var int
*/
protected $protocol;
/**
* @var string
*/
protected $server;
/**
* @var string
*/
protected $server;
/**
* @var string
*/
protected $nick;
/**
* @var string
*/
protected $nick;
/**
* @var string
*/
protected $map;
/**
* @var string
*/
protected $map;
/**
* @var string
*/
protected $game;
/**
* @var string
*/
protected $game;
/**
* @var float
*/
protected $duration;
/**
* @var float
*/
protected $duration;
/**
* @var int
*/
protected $ticks;
/**
* @var int
*/
protected $ticks;
/**
* @var int
*/
protected $frames;
/**
* @var int
*/
protected $frames;
/**
* @var int
*/
protected $sigon;
/**
* @var int
*/
protected $sigon;
public function __construct(
string $type,
int $version,
int $protocol,
string $server,
string $nick,
string $map,
string $game,
float $duration,
int $ticks,
int $frames,
int $sigon
) {
$this->type = $type;
$this->version = $version;
$this->protocol = $protocol;
$this->server = $server;
$this->nick = $nick;
$this->map = $map;
$this->game = $game;
$this->duration = $duration;
$this->ticks = $ticks;
$this->frames = $frames;
$this->sigon = $sigon;
}
public function __construct(
string $type,
int $version,
int $protocol,
string $server,
string $nick,
string $map,
string $game,
float $duration,
int $ticks,
int $frames,
int $sigon
) {
$this->type = $type;
$this->version = $version;
$this->protocol = $protocol;
$this->server = $server;
$this->nick = $nick;
$this->map = $map;
$this->game = $game;
$this->duration = $duration;
$this->ticks = $ticks;
$this->frames = $frames;
$this->sigon = $sigon;
}
public function getDuration(): float {
return $this->duration;
}
public function getDuration(): float {
return $this->duration;
}
public function getFrames(): int {
return $this->frames;
}
public function getFrames(): int {
return $this->frames;
}
public function getGame(): string {
return $this->game;
}
public function getGame(): string {
return $this->game;
}
public function getMap(): string {
return $this->map;
}
public function getMap(): string {
return $this->map;
}
public function getNick(): string {
return $this->nick;
}
public function getNick(): string {
return $this->nick;
}
public function getProtocol(): int {
return $this->protocol;
}
public function getProtocol(): int {
return $this->protocol;
}
public function getServer(): string {
return $this->server;
}
public function getServer(): string {
return $this->server;
}
public function getSigon(): int {
return $this->sigon;
}
public function getSigon(): int {
return $this->sigon;
}
public function getTicks(): int {
return $this->ticks;
}
public function getTicks(): int {
return $this->ticks;
}
public function getType(): string {
return $this->type;
}
public function getType(): string {
return $this->type;
}
public function getVersion(): int {
return $this->version;
}
public function getVersion(): int {
return $this->version;
}
public static function fromArray(array $info) {
return new Header(
$info['type'],
$info['version'],
$info['protocol'],
$info['server'],
$info['nick'],
$info['map'],
$info['game'],
$info['duration'],
$info['ticks'],
$info['frames'],
$info['sigon']
);
}
public static function fromArray(array $info) {
return new Header(
$info['type'],
$info['version'],
$info['protocol'],
$info['server'],
$info['nick'],
$info['map'],
$info['game'],
$info['duration'],
$info['ticks'],
$info['frames'],
$info['sigon']
);
}
}

View file

@ -3,44 +3,46 @@
namespace Demostf\API\Demo;
class HeaderParser {
/**
* @param string $head string containing the demo header binary data
* @return Header
* @throws \InvalidArgumentException
*/
public function parseString(string $head): Header {
$info = @unpack('A8type/Iversion/Iprotocol/A260server/A260nick/A260map/A260game/fduration/Vticks/Vframes/Vsigon',
$head);
if (!isset($info['type']) || $info['type'] !== 'HL2DEMO') {
throw new \InvalidArgumentException('Not an HL2 demo');
}
return Header::fromArray($info);
}
/**
* @param string $head string containing the demo header binary data
* @return Header
* @throws \InvalidArgumentException
*/
public function parseString(string $head): Header {
$info = @unpack(
'A8type/Iversion/Iprotocol/A260server/A260nick/A260map/A260game/fduration/Vticks/Vframes/Vsigon',
$head
);
if (!isset($info['type']) || $info['type'] !== 'HL2DEMO') {
throw new \InvalidArgumentException('Not an HL2 demo');
}
return Header::fromArray($info);
}
/**
* Parse demo info from a stream
*
* @param resource $stream
* @return Header
* @throws \InvalidArgumentException
*/
public function parseStream($stream): Header {
$head = fread($stream, 2048);
return $this->parseString($head);
}
/**
* Parse demo info from a stream
*
* @param resource $stream
* @return Header
* @throws \InvalidArgumentException
*/
public function parseStream($stream): Header {
$head = fread($stream, 2048);
return $this->parseString($head);
}
/**
* Parse demo info from a local file
*
* @param string $path
* @return Header
* @throws \InvalidArgumentException
*/
public function parseHeader(string $path): Header {
if (!is_readable($path)) {
throw new \InvalidArgumentException('Unable to open demo: ' . $path);
}
$fh = fopen($path, 'rb');
return $this->parseStream($fh);
}
/**
* Parse demo info from a local file
*
* @param string $path
* @return Header
* @throws \InvalidArgumentException
*/
public function parseHeader(string $path): Header {
if (!is_readable($path)) {
throw new \InvalidArgumentException('Unable to open demo: ' . $path);
}
$fh = fopen($path, 'rb');
return $this->parseStream($fh);
}
}

View file

@ -13,118 +13,118 @@ use Demostf\API\Data\Player;
* Processes the raw demo.js output to something more suitable for our purpose
*/
class Parser {
const CLASSES = [
1 => 'scout',
2 => 'sniper',
3 => 'soldier',
4 => 'demoman',
5 => 'medic',
6 => 'heavyweapons',
7 => 'pyro',
8 => 'spy',
9 => 'engineer'
];
const CLASSES = [
1 => 'scout',
2 => 'sniper',
3 => 'soldier',
4 => 'demoman',
5 => 'medic',
6 => 'heavyweapons',
7 => 'pyro',
8 => 'spy',
9 => 'engineer'
];
/** @var RawParser */
private $rawParser;
/** @var RawParser */
private $rawParser;
public function __construct(RawParser $rawParser) {
$this->rawParser = $rawParser;
}
public function __construct(RawParser $rawParser) {
$this->rawParser = $rawParser;
}
public function analyse(string $path): ParsedDemo {
$data = $this->rawParser->parse($path);
if (!is_array($data)) {
throw new \InvalidArgumentException('Error parsing demo');
}
return $this->handleData($data);
}
public function analyse(string $path): ParsedDemo {
$data = $this->rawParser->parse($path);
if (!is_array($data)) {
throw new \InvalidArgumentException('Error parsing demo');
}
return $this->handleData($data);
}
private function handleData(array $data): ParsedDemo {
$intervalPerTick = $data['intervalPerTick'];
$red = 0;
$blue = 0;
/** @var ChatMessage[] $chat */
$chat = [];
/** @var ParsedPlayer[] $players */
$players = [];
foreach ($data['rounds'] as $round) {
if ($round['winner'] === 'red') {
$red++;
} else {
$blue++;
}
}
private function handleData(array $data): ParsedDemo {
$intervalPerTick = $data['intervalPerTick'];
$red = 0;
$blue = 0;
/** @var ChatMessage[] $chat */
$chat = [];
/** @var ParsedPlayer[] $players */
$players = [];
foreach ($data['rounds'] as $round) {
if ($round['winner'] === 'red') {
$red++;
} else {
$blue++;
}
}
foreach ($data['chat'] as $message) {
if (isset($message['from'])) {
$chat[] = new ChatMessage($message['from'], (int)floor(($message['tick'] - $data['startTick']) * $intervalPerTick), $message['text']);
}
}
foreach ($data['chat'] as $message) {
if (isset($message['from'])) {
$chat[] = new ChatMessage($message['from'], (int)floor(($message['tick'] - $data['startTick']) * $intervalPerTick), $message['text']);
}
}
foreach ($data['users'] as $player) {
$class = 0;
$classSpawns = 0;
foreach ($player['classes'] as $classId => $spawns) {
if ($spawns > $classSpawns) {
$classSpawns = $spawns;
$class = $classId;
}
}
if ($class && $player['steamId']) {//skip spectators
$players[] = new ParsedPlayer(
$player['name'],
$player['userId'],
$this->convertSteamIdToCommunityId($player['steamId']),
$player['team'],
$this->getClassName((int)$class)
);
}
}
foreach ($data['users'] as $player) {
$class = 0;
$classSpawns = 0;
foreach ($player['classes'] as $classId => $spawns) {
if ($spawns > $classSpawns) {
$classSpawns = $spawns;
$class = $classId;
}
}
if ($class && $player['steamId']) {//skip spectators
$players[] = new ParsedPlayer(
$player['name'],
$player['userId'],
$this->convertSteamIdToCommunityId($player['steamId']),
$player['team'],
$this->getClassName((int)$class)
);
}
}
$kills = array_map(function (array $death) {
return new ParsedKill($death['killer'] ?? 0, $death['assister'] ?? 0, $death['victim'] ?? 0, $death['weapon']);
}, $data['deaths']);
$kills = array_map(function (array $death) {
return new ParsedKill($death['killer'] ?? 0, $death['assister'] ?? 0, $death['victim'] ?? 0, $death['weapon']);
}, $data['deaths']);
return new ParsedDemo(
$red,
$blue,
$chat,
$players,
$kills
);
}
return new ParsedDemo(
$red,
$blue,
$chat,
$players,
$kills
);
}
private function getClassName(int $classId): string {
return self::CLASSES[$classId] ?? 'Unknown';
}
private function getClassName(int $classId): string {
return self::CLASSES[$classId] ?? 'Unknown';
}
/**
* Credit to https://github.com/koraktor/steam-condenser-php
*
* Converts a SteamID as reported by game servers to a 64bit numeric
* SteamID as used by the Steam Community
*
* @param string $steamId The SteamID string as used on servers, like
* <var>STEAM_0:0:12345</var>
* @return string The converted 64bit numeric SteamID
* @throws \InvalidArgumentException if the SteamID doesn't have the correct
* format
*/
public function convertSteamIdToCommunityId($steamId) {
if ($steamId === 'STEAM_ID_LAN' || $steamId === 'BOT') {
throw new \InvalidArgumentException("Cannot convert SteamID \"$steamId\" to a community ID.");
}
if (preg_match('/^STEAM_[0-1]:[0-1]:[0-9]+$/', $steamId)) {
$steamParts = explode(':', substr($steamId, 8));
$steamId = $steamParts[0] + $steamParts[1] * 2 + 1197960265728;
return '7656' . $steamId;
} else if (preg_match('/^\[U:[0-1]:[0-9]+\]$/', $steamId)) {
$steamParts = explode(':', substr($steamId, 3, -1));
$steamId = $steamParts[0] + $steamParts[1] + 1197960265727;
return '7656' . $steamId;
} else {
throw new \InvalidArgumentException("SteamID \"$steamId\" doesn't have the correct format.");
}
}
/**
* Credit to https://github.com/koraktor/steam-condenser-php
*
* Converts a SteamID as reported by game servers to a 64bit numeric
* SteamID as used by the Steam Community
*
* @param string $steamId The SteamID string as used on servers, like
* <var>STEAM_0:0:12345</var>
* @return string The converted 64bit numeric SteamID
* @throws \InvalidArgumentException if the SteamID doesn't have the correct
* format
*/
public function convertSteamIdToCommunityId($steamId) {
if ($steamId === 'STEAM_ID_LAN' || $steamId === 'BOT') {
throw new \InvalidArgumentException("Cannot convert SteamID \"$steamId\" to a community ID.");
}
if (preg_match('/^STEAM_[0-1]:[0-1]:[0-9]+$/', $steamId)) {
$steamParts = explode(':', substr($steamId, 8));
$steamId = $steamParts[0] + $steamParts[1] * 2 + 1197960265728;
return '7656' . $steamId;
} elseif (preg_match('/^\[U:[0-1]:[0-9]+\]$/', $steamId)) {
$steamParts = explode(':', substr($steamId, 3, -1));
$steamId = $steamParts[0] + $steamParts[1] + 1197960265727;
return '7656' . $steamId;
} else {
throw new \InvalidArgumentException("SteamID \"$steamId\" doesn't have the correct format.");
}
}
}

View file

@ -11,30 +11,30 @@ use GuzzleHttp\Exception\GuzzleException;
* Doesn't do any post-processing on the result
*/
class RawParser {
/** @var string */
private $parserUrl;
/** @var string */
private $parserUrl;
public function __construct(string $parserUrl) {
$this->parserUrl = $parserUrl;
}
public function __construct(string $parserUrl) {
$this->parserUrl = $parserUrl;
}
public function parse(string $path): ?array {
try {
$client = new Client();
$response = $client->post($this->parserUrl, [
'body' => fopen($path, 'r')
]);
$result = json_decode($response->getBody()->getContents(), true);
if (is_null($result)) {
throw new \Exception('Failed to parse demo, unexpected result from parser');
} else {
return $result;
}
} catch (GuzzleException $e) {
if (strpos($e->getMessage(), 'cURL error 52') !== false) {
throw new \Exception('Failed to parse demo, can\'t reach demo parser');
}
throw new \Exception('Failed to parse demo, ' . $e->getMessage());
}
}
public function parse(string $path): ?array {
try {
$client = new Client();
$response = $client->post($this->parserUrl, [
'body' => fopen($path, 'r')
]);
$result = json_decode($response->getBody()->getContents(), true);
if (is_null($result)) {
throw new \Exception('Failed to parse demo, unexpected result from parser');
} else {
return $result;
}
} catch (GuzzleException $e) {
if (strpos($e->getMessage(), 'cURL error 52') !== false) {
throw new \Exception('Failed to parse demo, can\'t reach demo parser');
}
throw new \Exception('Failed to parse demo, ' . $e->getMessage());
}
}
}

View file

@ -4,35 +4,35 @@ use Doctrine\DBAL\Connection;
use RandomLib\Generator;
class AuthProvider extends BaseProvider {
/**
* @var Generator
*/
private $generator;
/**
* @var Generator
*/
private $generator;
public function __construct(Connection $db, Generator $generator) {
parent::__construct($db);
$this->generator = $generator;
}
public function __construct(Connection $db, Generator $generator) {
parent::__construct($db);
$this->generator = $generator;
}
public function generateToken() {
return $this->generator->generateString(32, Generator::CHAR_ALNUM);
}
public function generateToken() {
return $this->generator->generateString(32, Generator::CHAR_ALNUM);
}
public function setUser($token, \SteamId $steamid, $key) {
apcu_store($token, [
'name' => $steamid->getNickname(),
'steamid' => $steamid->getSteamId64(),
'key' => $key
]);
}
public function setUser($token, \SteamId $steamid, $key) {
apcu_store($token, [
'name' => $steamid->getNickname(),
'steamid' => $steamid->getSteamId64(),
'key' => $key
]);
}
public function getUser($token) {
$found = true;
$result = apcu_fetch($token, $found);
return $found ? $result : ['name' => null, 'steamid' => null, 'key' => null];
}
public function getUser($token) {
$found = true;
$result = apcu_fetch($token, $found);
return $found ? $result : ['name' => null, 'steamid' => null, 'key' => null];
}
public function logout($token) {
apcu_delete($token);
}
public function logout($token) {
apcu_delete($token);
}
}

View file

@ -7,64 +7,64 @@ use Doctrine\DBAL\Query\QueryBuilder;
use LessQL\Database;
class BaseProvider {
/**
* @var Connection
*/
protected $connection;
/**
* @var Connection
*/
protected $connection;
/**
* @var \LessQL\Database
*/
protected $db;
/**
* @var \LessQL\Database
*/
protected $db;
public function __construct(Connection $connection) {
$this->connection = $connection;
$this->db = new Database($connection->getWrappedConnection());
$this->dbConfig();
}
public function __construct(Connection $connection) {
$this->connection = $connection;
$this->db = new Database($connection->getWrappedConnection());
$this->dbConfig();
}
private function dbConfig() {
$platform = $this->connection->getDatabasePlatform();
if ($platform instanceof MySqlPlatform) {
$this->db->setIdentifierDelimiter("`");
} else {
$this->db->setIdentifierDelimiter('"');
}
private function dbConfig() {
$platform = $this->connection->getDatabasePlatform();
if ($platform instanceof MySqlPlatform) {
$this->db->setIdentifierDelimiter("`");
} else {
$this->db->setIdentifierDelimiter('"');
}
$this->db->setRewrite(function ($table) {
$rawNames = ['chat'];
$aliases = [
$this->db->setRewrite(function ($table) {
$rawNames = ['chat'];
$aliases = [
];
if (isset($aliases[$table])) {
return $aliases[$table];
} else if (array_search($table, $rawNames) === false) {
return $table . 's';
} else {
return $table;
}
});
}
];
if (isset($aliases[$table])) {
return $aliases[$table];
} elseif (array_search($table, $rawNames) === false) {
return $table . 's';
} else {
return $table;
}
});
}
protected function query($sql, array $params = []) {
$delimiter = $this->db->getIdentifierDelimiter();
$platform = $this->connection->getDatabasePlatform();
$sql = str_replace('`', $delimiter, $sql);
protected function query($sql, array $params = []) {
$delimiter = $this->db->getIdentifierDelimiter();
$platform = $this->connection->getDatabasePlatform();
$sql = str_replace('`', $delimiter, $sql);
if ($platform instanceof PostgreSqlPlatform) {
$sql = str_replace('FROM_UNIXTIME(', 'to_timestamp(', $sql);
}
if ($platform instanceof PostgreSqlPlatform) {
$sql = str_replace('FROM_UNIXTIME(', 'to_timestamp(', $sql);
}
$query = $this->connection->prepare($sql);
$query->execute($params);
$query = $this->connection->prepare($sql);
$query->execute($params);
return $query;
}
return $query;
}
/**
* @return QueryBuilder
*/
protected function getQueryBuilder() {
return new QueryBuilder($this->connection);
}
/**
* @return QueryBuilder
*/
protected function getQueryBuilder() {
return new QueryBuilder($this->connection);
}
}

View file

@ -3,33 +3,33 @@
use Demostf\API\Demo\ChatMessage;
class ChatProvider extends BaseProvider {
public function getChat(int $demoId) {
$query = $this->getQueryBuilder();
$query->select('text', '"from"', 'time')
->from('chat')
->where($query->expr()->eq('demo_id', $query->createNamedParameter($demoId, \PDO::PARAM_INT)));
public function getChat(int $demoId) {
$query = $this->getQueryBuilder();
$query->select('text', '"from"', 'time')
->from('chat')
->where($query->expr()->eq('demo_id', $query->createNamedParameter($demoId, \PDO::PARAM_INT)));
$result = $query->execute();
return array_map(function (array $row) {
return new ChatMessage(
$row['from'],
(int)$row['time'],
$row['text']
);
}, $result->fetchAll());
}
$result = $query->execute();
return array_map(function (array $row) {
return new ChatMessage(
$row['from'],
(int)$row['time'],
$row['text']
);
}, $result->fetchAll());
}
public function storeChatMessage(int $demoId, ChatMessage $message) {
$query = $this->getQueryBuilder();
$query->insert('chat')
->values([
'demo_id' => $query->createNamedParameter($demoId, \PDO::PARAM_INT),
'text' => $query->createNamedParameter($message->getMessage()),
'"from"' => $query->createNamedParameter($message->getUser()),
'time' => $query->createNamedParameter($message->getTime(), \PDO::PARAM_INT),
'created_at' => 'now()',
'updated_at' => 'now()',
]);
$query->execute();
}
public function storeChatMessage(int $demoId, ChatMessage $message) {
$query = $this->getQueryBuilder();
$query->insert('chat')
->values([
'demo_id' => $query->createNamedParameter($demoId, \PDO::PARAM_INT),
'text' => $query->createNamedParameter($message->getMessage()),
'"from"' => $query->createNamedParameter($message->getUser()),
'time' => $query->createNamedParameter($message->getTime(), \PDO::PARAM_INT),
'created_at' => 'now()',
'updated_at' => 'now()',
]);
$query->execute();
}
}

View file

@ -4,74 +4,74 @@ use Demostf\API\Demo\Demo;
use Doctrine\DBAL\Connection;
class DemoListProvider extends BaseProvider {
public function listUploads(string $steamid, int $page, array $where = []) {
$user = $this->db->user()->where('steamid', $steamid);
$where['uploader'] = $user->fetch()->id;
return $this->listDemos($page, $where);
}
public function listUploads(string $steamid, int $page, array $where = []) {
$user = $this->db->user()->where('steamid', $steamid);
$where['uploader'] = $user->fetch()->id;
return $this->listDemos($page, $where);
}
public function listProfile(int $page, array $where = []) {
$users = $this->db->user()->where('steamid', $where['players']);
unset($where['players']);
$userIds = [];
foreach ($users as $user) {
$userIds[] = $user['id'];
}
$in = implode(', ', array_fill(0, count($userIds), '?'));
public function listProfile(int $page, array $where = []) {
$users = $this->db->user()->where('steamid', $where['players']);
unset($where['players']);
$userIds = [];
foreach ($users as $user) {
$userIds[] = $user['id'];
}
$in = implode(', ', array_fill(0, count($userIds), '?'));
$sql = 'SELECT demos.id FROM demos INNER JOIN players ON players.demo_id = demos.id
$sql = 'SELECT demos.id FROM demos INNER JOIN players ON players.demo_id = demos.id
WHERE players.user_id IN (' . $in . ') GROUP BY demos.id HAVING COUNT(user_id) = ? ORDER BY demos.id DESC LIMIT 50 OFFSET ' . ((int)$page - 1) * 50;
$params = $userIds;
$params[] = count($userIds);
$params = $userIds;
$params[] = count($userIds);
$result = $this->query($sql, $params);
$demoIds = $result->fetchAll(\PDO::FETCH_COLUMN);
$result = $this->query($sql, $params);
$demoIds = $result->fetchAll(\PDO::FETCH_COLUMN);
$demos = $this->db->demo()->where('id', $demoIds)
->where($where)
->orderBy('id', 'DESC');
return $this->formatList($demos->fetchAll());
}
$demos = $this->db->demo()->where('id', $demoIds)
->where($where)
->orderBy('id', 'DESC');
return $this->formatList($demos->fetchAll());
}
/**
* @param int $page
* @param array $where
* @param string $order
* @return Demo[]
*/
public function listDemos(int $page, array $where = [], $order = 'DESC') {
if (isset($where['players']) and is_array($where['players']) and count($where['players']) > 0) {
return $this->listProfile($page, $where);
}
/**
* @param int $page
* @param array $where
* @param string $order
* @return Demo[]
*/
public function listDemos(int $page, array $where = [], $order = 'DESC') {
if (isset($where['players']) and is_array($where['players']) and count($where['players']) > 0) {
return $this->listProfile($page, $where);
}
$offset = ($page - 1) * 50;
$offset = ($page - 1) * 50;
$query = $this->getQueryBuilder();
$query->select('d.*')
->from('demos', 'd')
->leftJoin('d', 'upload_blacklist', 'b', $query->expr()->eq('uploader_id', 'uploader'))
->where($query->expr()->isNull('b.id'));
if (isset($where['map'])) {
$query->where($query->expr()->eq('map', $query->createNamedParameter($where['map'])));
}
if (isset($where['playerCount'])) {
$query->where($query->expr()->in('"playerCount"', $query->createNamedParameter($where['playerCount'], Connection::PARAM_INT_ARRAY)));
}
if (isset($where['uploader'])) {
$query->where($query->expr()->in('uploader', $query->createNamedParameter($where['uploader'], \PDO::PARAM_INT)));
}
$query->orderBy('d.id', $order)
->setMaxResults(50)
->setFirstResult($offset);
$query = $this->getQueryBuilder();
$query->select('d.*')
->from('demos', 'd')
->leftJoin('d', 'upload_blacklist', 'b', $query->expr()->eq('uploader_id', 'uploader'))
->where($query->expr()->isNull('b.id'));
if (isset($where['map'])) {
$query->where($query->expr()->eq('map', $query->createNamedParameter($where['map'])));
}
if (isset($where['playerCount'])) {
$query->where($query->expr()->in('"playerCount"', $query->createNamedParameter($where['playerCount'], Connection::PARAM_INT_ARRAY)));
}
if (isset($where['uploader'])) {
$query->where($query->expr()->in('uploader', $query->createNamedParameter($where['uploader'], \PDO::PARAM_INT)));
}
$query->orderBy('d.id', $order)
->setMaxResults(50)
->setFirstResult($offset);
$demos = $query->execute()->fetchAll(\PDO::FETCH_ASSOC);
return $this->formatList($demos);
}
$demos = $query->execute()->fetchAll(\PDO::FETCH_ASSOC);
return $this->formatList($demos);
}
protected function formatList(array $rows) {
return array_map(function ($row) {
return Demo::fromRow($row);
}, $rows);
}
protected function formatList(array $rows) {
return array_map(function ($row) {
return Demo::fromRow($row);
}, $rows);
}
}

View file

@ -7,13 +7,13 @@ use Demostf\API\Data\User;
use Demostf\API\Demo\Demo;
class DemoProvider extends BaseProvider {
const VERSION = 4;
const VERSION = 4;
public function get(int $id, bool $fetchDetails = true): ?Demo {
$demo = $this->db->demo()->where('id', $id);
public function get(int $id, bool $fetchDetails = true): ?Demo {
$demo = $this->db->demo()->where('id', $id);
// sql magic
$sql = 'WITH demokills AS (SELECT attacker_id, assister_id, victim_id FROM kills WHERE demo_id = ?)
// sql magic
$sql = 'WITH demokills AS (SELECT attacker_id, assister_id, victim_id FROM kills WHERE demo_id = ?)
SELECT players.id, user_id, players.name, team, class, users.steamid, users.avatar,
(SELECT COUNT(*) FROM demokills WHERE attacker_id=players.user_id) AS kills,
(SELECT COUNT(*) FROM demokills WHERE assister_id=players.user_id) AS assists,
@ -22,73 +22,73 @@ class DemoProvider extends BaseProvider {
INNER JOIN users ON players.user_id = users.id
WHERE demo_id = ?';
$demoData = $demo->fetch();
if (!$demoData) {
return null;
}
$formattedDemo = Demo::fromRow($demoData);
$demoData = $demo->fetch();
if (!$demoData) {
return null;
}
$formattedDemo = Demo::fromRow($demoData);
if ($fetchDetails) {
$uploader = $demo->user()->via('uploader')->fetch();
$playerQuery = $this->query($sql, [$formattedDemo->getId(), $formattedDemo->getId()]);
$players = $playerQuery->fetchAll(\PDO::FETCH_ASSOC);
if ($fetchDetails) {
$uploader = $demo->user()->via('uploader')->fetch();
$playerQuery = $this->query($sql, [$formattedDemo->getId(), $formattedDemo->getId()]);
$players = $playerQuery->fetchAll(\PDO::FETCH_ASSOC);
$formattedDemo->setUploaderUser(User::fromRow([
'id' => $uploader['id'],
'steamid' => $uploader['steamid'],
'name' => $uploader['name'],
'avatar' => $uploader['avatar']
]));
$formattedDemo->setPlayers(array_map(function ($player) {
return DemoPlayer::fromRow($player);
}, $players));
}
return $formattedDemo;
}
$formattedDemo->setUploaderUser(User::fromRow([
'id' => $uploader['id'],
'steamid' => $uploader['steamid'],
'name' => $uploader['name'],
'avatar' => $uploader['avatar']
]));
$formattedDemo->setPlayers(array_map(function ($player) {
return DemoPlayer::fromRow($player);
}, $players));
}
return $formattedDemo;
}
public function demoIdByHash($hash): int {
$query = $this->getQueryBuilder();
$query->select('id')
->from('demos')
->where($query->expr()->eq('hash', $query->createNamedParameter($hash)));
public function demoIdByHash($hash): int {
$query = $this->getQueryBuilder();
$query->select('id')
->from('demos')
->where($query->expr()->eq('hash', $query->createNamedParameter($hash)));
return (int)$query->execute()->fetchColumn();
}
return (int)$query->execute()->fetchColumn();
}
public function storeDemo(Demo $demo, string $backend, string $path): int {
$query = $this->getQueryBuilder();
$query->insert('demos')
->values([
'name' => $query->createNamedParameter($demo->getName()),
'url' => $query->createNamedParameter($demo->getUrl()),
'map' => $query->createNamedParameter($demo->getMap()),
'red' => $query->createNamedParameter($demo->getRed()),
'blu' => $query->createNamedParameter($demo->getBlue()),
'uploader' => $query->createNamedParameter($demo->getUploader(), \PDO::PARAM_INT),
'duration' => $query->createNamedParameter((int)$demo->getDuration(), \PDO::PARAM_INT),
'created_at' => $query->createNamedParameter($demo->getTime()->format(\DATE_ATOM)),
'updated_at' => 'now()',
'backend' => $query->createNamedParameter($backend),
'path' => $query->createNamedParameter($path),
'"scoreBlue"' => $query->createNamedParameter($demo->getBlueScore(), \PDO::PARAM_INT),
'"scoreRed"' => $query->createNamedParameter($demo->getRedScore(), \PDO::PARAM_INT),
'version' => $query->createNamedParameter(self::VERSION, \PDO::PARAM_INT),
'server' => $query->createNamedParameter($demo->getServer()),
'nick' => $query->createNamedParameter($demo->getNick()),
'"playerCount"' => $query->createNamedParameter($demo->getPlayerCount(), \PDO::PARAM_INT),
'hash' => $query->createNamedParameter($demo->getHash())
])
->execute();
return (int)$this->connection->lastInsertId();
}
public function storeDemo(Demo $demo, string $backend, string $path): int {
$query = $this->getQueryBuilder();
$query->insert('demos')
->values([
'name' => $query->createNamedParameter($demo->getName()),
'url' => $query->createNamedParameter($demo->getUrl()),
'map' => $query->createNamedParameter($demo->getMap()),
'red' => $query->createNamedParameter($demo->getRed()),
'blu' => $query->createNamedParameter($demo->getBlue()),
'uploader' => $query->createNamedParameter($demo->getUploader(), \PDO::PARAM_INT),
'duration' => $query->createNamedParameter((int)$demo->getDuration(), \PDO::PARAM_INT),
'created_at' => $query->createNamedParameter($demo->getTime()->format(\DATE_ATOM)),
'updated_at' => 'now()',
'backend' => $query->createNamedParameter($backend),
'path' => $query->createNamedParameter($path),
'"scoreBlue"' => $query->createNamedParameter($demo->getBlueScore(), \PDO::PARAM_INT),
'"scoreRed"' => $query->createNamedParameter($demo->getRedScore(), \PDO::PARAM_INT),
'version' => $query->createNamedParameter(self::VERSION, \PDO::PARAM_INT),
'server' => $query->createNamedParameter($demo->getServer()),
'nick' => $query->createNamedParameter($demo->getNick()),
'"playerCount"' => $query->createNamedParameter($demo->getPlayerCount(), \PDO::PARAM_INT),
'hash' => $query->createNamedParameter($demo->getHash())
])
->execute();
return (int)$this->connection->lastInsertId();
}
public function setDemoUrl(int $id, string $backend, string $url, string $path) {
$query = $this->getQueryBuilder();
$query->update('demos')
->set('backend', $query->createNamedParameter($backend))
->set('url', $query->createNamedParameter($url))
->set('path', $query->createNamedParameter($path))
->where($query->expr()->eq('id', $query->createNamedParameter($id, \PDO::PARAM_INT)))
->execute();
}
public function setDemoUrl(int $id, string $backend, string $url, string $path) {
$query = $this->getQueryBuilder();
$query->update('demos')
->set('backend', $query->createNamedParameter($backend))
->set('url', $query->createNamedParameter($url))
->set('path', $query->createNamedParameter($path))
->where($query->expr()->eq('id', $query->createNamedParameter($id, \PDO::PARAM_INT)))
->execute();
}
}

View file

@ -1,19 +1,19 @@
<?php namespace Demostf\API\Providers;
class InfoProvider extends BaseProvider {
public function listMaps() {
$sql = 'SELECT DISTINCT(map), COUNT(map) AS count from demos GROUP BY map ORDER BY count DESC';
$result = $this->query($sql);
return $result->fetchAll(\PDO::FETCH_COLUMN);
}
public function listMaps() {
$sql = 'SELECT DISTINCT(map), COUNT(map) AS count from demos GROUP BY map ORDER BY count DESC';
$result = $this->query($sql);
return $result->fetchAll(\PDO::FETCH_COLUMN);
}
public function getStats() {
$demoCount = $this->db->demo()->count();
$playerCount = $this->db->user()->count();
public function getStats() {
$demoCount = $this->db->demo()->count();
$playerCount = $this->db->user()->count();
return [
'demos' => $demoCount,
'players' => $playerCount
];
}
return [
'demos' => $demoCount,
'players' => $playerCount
];
}
}

View file

@ -5,20 +5,20 @@ namespace Demostf\API\Providers;
use Demostf\API\Data\Kill;
class KillProvider extends BaseProvider {
public function store(Kill $kill): int {
$query = $this->getQueryBuilder();
$query->insert('kills')
->values([
'demo_id' => $query->createNamedParameter($kill->getDemoId()),
'attacker_id' => $query->createNamedParameter($kill->getAttackerId()),
'assister_id' => $query->createNamedParameter($kill->getAssisterId()),
'victim_id' => $query->createNamedParameter($kill->getVictimId()),
'weapon' => $query->createNamedParameter($kill->getWeapon()),
'created_at' => 'now()',
'updated_at' => 'now()'
]);
$query->execute();
public function store(Kill $kill): int {
$query = $this->getQueryBuilder();
$query->insert('kills')
->values([
'demo_id' => $query->createNamedParameter($kill->getDemoId()),
'attacker_id' => $query->createNamedParameter($kill->getAttackerId()),
'assister_id' => $query->createNamedParameter($kill->getAssisterId()),
'victim_id' => $query->createNamedParameter($kill->getVictimId()),
'weapon' => $query->createNamedParameter($kill->getWeapon()),
'created_at' => 'now()',
'updated_at' => 'now()'
]);
$query->execute();
return (int)$this->connection->lastInsertId();
}
return (int)$this->connection->lastInsertId();
}
}

View file

@ -5,21 +5,21 @@ namespace Demostf\API\Providers;
use Demostf\API\Data\Player;
class PlayerProvider extends BaseProvider {
public function store(Player $player): int {
$query = $this->getQueryBuilder();
$query->insert('players')
->values([
'demo_id' => $query->createNamedParameter($player->getDemoId()),
'demo_user_id' => $query->createNamedParameter($player->getDemoUserId()),
'user_id' => $query->createNamedParameter($player->getUserId()),
'name' => $query->createNamedParameter($player->getName()),
'team' => $query->createNamedParameter($player->getTeam()),
'class' => $query->createNamedParameter($player->getClass()),
'created_at' => 'now()',
'updated_at' => 'now()'
]);
$query->execute();
public function store(Player $player): int {
$query = $this->getQueryBuilder();
$query->insert('players')
->values([
'demo_id' => $query->createNamedParameter($player->getDemoId()),
'demo_user_id' => $query->createNamedParameter($player->getDemoUserId()),
'user_id' => $query->createNamedParameter($player->getUserId()),
'name' => $query->createNamedParameter($player->getName()),
'team' => $query->createNamedParameter($player->getTeam()),
'class' => $query->createNamedParameter($player->getClass()),
'created_at' => 'now()',
'updated_at' => 'now()'
]);
$query->execute();
return (int)$this->connection->lastInsertId();
}
return (int)$this->connection->lastInsertId();
}
}

View file

@ -13,97 +13,98 @@ use Doctrine\DBAL\Connection;
use RandomLib\Generator;
class UploadProvider extends BaseProvider {
/** @var Generator */
private $generator;
/** @var HeaderParser */
private $headerParser;
/** @var Parser */
private $parser;
/** @var DemoStore */
private $store;
/** @var UserProvider */
private $userProvider;
/** @var DemoProvider */
private $demoProvider;
/** @var DemoSaver */
private $demoSaver;
private $baseUrl;
/** @var Generator */
private $generator;
/** @var HeaderParser */
private $headerParser;
/** @var Parser */
private $parser;
/** @var DemoStore */
private $store;
/** @var UserProvider */
private $userProvider;
/** @var DemoProvider */
private $demoProvider;
/** @var DemoSaver */
private $demoSaver;
private $baseUrl;
public function __construct(Connection $db,
string $baseUrl,
HeaderParser $headerParser,
Parser $parser,
DemoStore $store,
UserProvider $userProvider,
DemoProvider $demoProvider,
DemoSaver $demoSaver
) {
parent::__construct($db);
$this->baseUrl = $baseUrl;
$this->headerParser = $headerParser;
$this->parser = $parser;
$this->store = $store;
$this->userProvider = $userProvider;
$this->demoProvider = $demoProvider;
$this->demoSaver = $demoSaver;
}
public function __construct(
Connection $db,
string $baseUrl,
HeaderParser $headerParser,
Parser $parser,
DemoStore $store,
UserProvider $userProvider,
DemoProvider $demoProvider,
DemoSaver $demoSaver
) {
parent::__construct($db);
$this->baseUrl = $baseUrl;
$this->headerParser = $headerParser;
$this->parser = $parser;
$this->store = $store;
$this->userProvider = $userProvider;
$this->demoProvider = $demoProvider;
$this->demoSaver = $demoSaver;
}
public function upload(string $key, string $red, string $blu, string $name, string $demoFile): string {
$user = $this->userProvider->byKey($key);
if (!$user) {
return 'Invalid key';
}
public function upload(string $key, string $red, string $blu, string $name, string $demoFile): string {
$user = $this->userProvider->byKey($key);
if (!$user) {
return 'Invalid key';
}
$hash = hash_file('md5', $demoFile);
$hash = hash_file('md5', $demoFile);
$existingDemo = $this->demoProvider->demoIdByHash($hash);
if ($existingDemo) {
return 'STV available at: ' . $this->baseUrl . '/' . $existingDemo;
}
$existingDemo = $this->demoProvider->demoIdByHash($hash);
if ($existingDemo) {
return 'STV available at: ' . $this->baseUrl . '/' . $existingDemo;
}
$header = $this->headerParser->parseHeader($demoFile);
$error = $this->validateHeader(filesize($demoFile), $header);
if ($error) {
return $error;
}
$header = $this->headerParser->parseHeader($demoFile);
$error = $this->validateHeader(filesize($demoFile), $header);
if ($error) {
return $error;
}
$parsed = $this->parser->analyse($demoFile);
$parsed = $this->parser->analyse($demoFile);
$error = $this->validateParsed($header, $parsed);
if ($error) {
return $error;
}
$error = $this->validateParsed($header, $parsed);
if ($error) {
return $error;
}
$storedDemo = $this->store->store($demoFile, $hash . '_' . $name);
$upload = new Upload($name, $red, $blu, $user->getId(), $hash);
$storedDemo = $this->store->store($demoFile, $hash . '_' . $name);
$upload = new Upload($name, $red, $blu, $user->getId(), $hash);
$id = $this->demoSaver->saveDemo($parsed, $header, $storedDemo, $upload);
$id = $this->demoSaver->saveDemo($parsed, $header, $storedDemo, $upload);
return 'STV available at: ' . $this->baseUrl . '/' . $id;
}
return 'STV available at: ' . $this->baseUrl . '/' . $id;
}
public function validateHeader(int $size, Header $header) {
if ($size < 1024) {
return 'Demos needs to be at least 1KB is size';
}
public function validateHeader(int $size, Header $header) {
if ($size < 1024) {
return 'Demos needs to be at least 1KB is size';
}
if ($size > 100 * 1024 * 1024) {
return 'Demos cant be more than 100MB in size';
}
if ($size > 100 * 1024 * 1024) {
return 'Demos cant be more than 100MB in size';
}
if ($header->getDuration() > (60 * 60)) {
return 'Demos cant be longer than one hour';
}
if ($header->getDuration() > (60 * 60)) {
return 'Demos cant be longer than one hour';
}
return null;
}
return null;
}
public function validateParsed(Header $header, ParsedDemo $parsedDemo) {
$rounds = $parsedDemo->getRedScore() + $parsedDemo->getBlueScore();
if ($rounds === 0 && $header->getDuration() < (5 * 60)) {
return 'Demos must be at least 5 minutes long';
}
public function validateParsed(Header $header, ParsedDemo $parsedDemo) {
$rounds = $parsedDemo->getRedScore() + $parsedDemo->getBlueScore();
if ($rounds === 0 && $header->getDuration() < (5 * 60)) {
return 'Demos must be at least 5 minutes long';
}
return null;
}
return null;
}
}

View file

@ -7,131 +7,131 @@ use Doctrine\DBAL\Connection;
use RandomLib\Generator;
class UserProvider extends BaseProvider {
/**
* @var Generator
*/
private $generator;
/**
* @var Generator
*/
private $generator;
public function __construct(Connection $db, Generator $generator) {
parent::__construct($db);
$this->generator = $generator;
}
public function __construct(Connection $db, Generator $generator) {
parent::__construct($db);
$this->generator = $generator;
}
public function store(\SteamId $steamId): string {
$token = $this->generator->generateString(64, Generator::EASY_TO_READ);
public function store(\SteamId $steamId): string {
$token = $this->generator->generateString(64, Generator::EASY_TO_READ);
$user = $this->get($steamId->getSteamId64());
if ($user) {
return $user->getToken();
}
$user = $this->get($steamId->getSteamId64());
if ($user) {
return $user->getToken();
}
$query = $this->getQueryBuilder();
$query->insert('users')
->values([
'steamid' => $query->createNamedParameter($steamId->getSteamId64()),
'name' => $query->createNamedParameter($steamId->getNickname()),
'avatar' => $query->createNamedParameter($steamId->getMediumAvatarUrl()),
'token' => $query->createNamedParameter($token)
])->add('orderBy', 'ON CONFLICT DO NOTHING')// hack to append arbitrary string to sql
->execute();
$query = $this->getQueryBuilder();
$query->insert('users')
->values([
'steamid' => $query->createNamedParameter($steamId->getSteamId64()),
'name' => $query->createNamedParameter($steamId->getNickname()),
'avatar' => $query->createNamedParameter($steamId->getMediumAvatarUrl()),
'token' => $query->createNamedParameter($token)
])->add('orderBy', 'ON CONFLICT DO NOTHING')// hack to append arbitrary string to sql
->execute();
$user = $this->get($steamId->getSteamId64());
return $user ? $user->getToken() : $token;
}
$user = $this->get($steamId->getSteamId64());
return $user ? $user->getToken() : $token;
}
public function get(string $steamid): ?User {
$query = $this->getQueryBuilder();
$query->select(['id', 'steamid', 'name', 'avatar', 'token'])
->from('users')
->where($query->expr()->eq('steamid', $query->createNamedParameter($steamid)));
public function get(string $steamid): ?User {
$query = $this->getQueryBuilder();
$query->select(['id', 'steamid', 'name', 'avatar', 'token'])
->from('users')
->where($query->expr()->eq('steamid', $query->createNamedParameter($steamid)));
$row = $query->execute()->fetch();
return $row ? User::fromRow($row) : null;
}
$row = $query->execute()->fetch();
return $row ? User::fromRow($row) : null;
}
private function searchBySteamId(string $steamId): ?array {
$query = $this->getQueryBuilder();
$query->select('u.id', 'p.name', 'count(demo_id) as count', 'steamid')
->from('players', 'p')
->innerJoin('p', 'users', 'u', $query->expr()->eq('p.user_id', 'u.id'))
->where($query->expr()->eq('steamid', $query->createNamedParameter($steamId)))
->groupBy('p.name, u.id')
->orderBy('count(demo_id)', 'DESC')
->setMaxResults(1);
private function searchBySteamId(string $steamId): ?array {
$query = $this->getQueryBuilder();
$query->select('u.id', 'p.name', 'count(demo_id) as count', 'steamid')
->from('players', 'p')
->innerJoin('p', 'users', 'u', $query->expr()->eq('p.user_id', 'u.id'))
->where($query->expr()->eq('steamid', $query->createNamedParameter($steamId)))
->groupBy('p.name, u.id')
->orderBy('count(demo_id)', 'DESC')
->setMaxResults(1);
$result = $query->execute()->fetch();
if (is_array($result)) {
return $result;
} else {
return null;
}
}
$result = $query->execute()->fetch();
if (is_array($result)) {
return $result;
} else {
return null;
}
}
public function search($query): array {
$bySteamId = $this->searchBySteamId($query);
if ($bySteamId) {
return [
$bySteamId
];
}
public function search($query): array {
$bySteamId = $this->searchBySteamId($query);
if ($bySteamId) {
return [
$bySteamId
];
}
$sql = 'SELECT user_id, players.name, count(demo_id) AS count, steamid,
$sql = 'SELECT user_id, players.name, count(demo_id) AS count, steamid,
1-(players.name <-> ?) AS sim FROM players
INNER JOIN users ON users.id = players.user_id
WHERE players.name % ? OR players.name ~* ?
GROUP BY players.name, user_id, steamid
ORDER BY count DESC
LIMIT 100';
$result = $this->query($sql, [$query, $query, $query]);
$players = $result->fetchAll(\PDO::FETCH_ASSOC);
$result = $this->query($sql, [$query, $query, $query]);
$players = $result->fetchAll(\PDO::FETCH_ASSOC);
usort($players, function ($b, $a) use ($query) {
if ($a['steamid'] === $query && $a['steamid'] !== $query) {
return -1;
}
$countWeight = 1;
$simWeight = 5;
$diff = ($a['sim'] * $simWeight + $a['count'] * $countWeight) - ($b['sim'] * $simWeight + $b['count'] * $countWeight);
if ($diff === 0) {
return 0;
} else {
return ($diff < 0) ? -1 : 1;
}
});
usort($players, function ($b, $a) use ($query) {
if ($a['steamid'] === $query && $a['steamid'] !== $query) {
return -1;
}
$countWeight = 1;
$simWeight = 5;
$diff = ($a['sim'] * $simWeight + $a['count'] * $countWeight) - ($b['sim'] * $simWeight + $b['count'] * $countWeight);
if ($diff === 0) {
return 0;
} else {
return ($diff < 0) ? -1 : 1;
}
});
$result = [];
foreach ($players as $player) {
$id = $player['user_id'];
if (!isset($result[$id])) {
$result[$id] = [
'id' => $id,
'name' => $player['name'],
'steamid' => $player['steamid']
];
}
}
$result = [];
foreach ($players as $player) {
$id = $player['user_id'];
if (!isset($result[$id])) {
$result[$id] = [
'id' => $id,
'name' => $player['name'],
'steamid' => $player['steamid']
];
}
}
return array_values($result);
}
return array_values($result);
}
public function byKey($key): ?User {
$query = $this->getQueryBuilder();
$query->select(['id', 'steamid', 'name', 'avatar', 'token'])
->from('users')
->where($query->expr()->eq('token', $query->createNamedParameter($key)));
public function byKey($key): ?User {
$query = $this->getQueryBuilder();
$query->select(['id', 'steamid', 'name', 'avatar', 'token'])
->from('users')
->where($query->expr()->eq('token', $query->createNamedParameter($key)));
$row = $query->execute()->fetch();
return $row ? User::fromRow($row) : null;
}
$row = $query->execute()->fetch();
return $row ? User::fromRow($row) : null;
}
public function getUserId(string $steamId) {
$existing = $this->get($steamId);
if ($existing) {
return $existing->getId();
}
public function getUserId(string $steamId) {
$existing = $this->get($steamId);
if ($existing) {
return $existing->getId();
}
$this->store(new \SteamId($steamId));
$this->store(new \SteamId($steamId));
return $this->get($steamId)->getId();
}
return $this->get($steamId)->getId();
}
}

View file

@ -8,32 +8,32 @@ use Flight;
$container = require __DIR__ . '/init.php';
$demoController = new Controllers\DemoController(
$container->getDemoProvider(),
$container->getChatProvider(),
$container->getDemoListProvider(),
$container->getEditKey()
$container->getDemoProvider(),
$container->getChatProvider(),
$container->getDemoListProvider(),
$container->getEditKey()
);
$authController = new Controllers\AuthController(
$container->getUserProvider(),
$container->getAuthProvider(),
$container->getBaseUrl(),
$container->getApiRoot()
$container->getUserProvider(),
$container->getAuthProvider(),
$container->getBaseUrl(),
$container->getApiRoot()
);
$userController = new Controllers\UserController($container->getUserProvider());
$infoController = new Controllers\InfoController($container->getInfoProvider());
Flight::route('/*', function () {
header('Access-Control-Allow-Origin: *');
return true;
header('Access-Control-Allow-Origin: *');
return true;
});
Flight::route('/auth/*', function () {
session_start();
return true;
session_start();
return true;
});
Flight::route('/', function () {
echo 'hello world!';
echo 'hello world!';
});
Flight::route('/maps', [$infoController, 'listMaps']);

View file

@ -5,19 +5,19 @@ use Demostf\API\Container;
$autoloader = require __DIR__ . '/../vendor/autoload.php';
if (!getenv('DB_TYPE')) {
Dotenv::load(__DIR__ . '/../');
Dotenv::load(__DIR__ . '/../');
}
$connectionParams = array(
'dbname' => getenv('DB_DATABASE'),
'user' => getenv('DB_USERNAME'),
'password' => getenv('DB_PASSWORD'),
'host' => getenv('DB_HOST'),
'port' => getenv('DB_PORT'),
'driver' => getenv('DB_TYPE'),
);
$connectionParams = [
'dbname' => getenv('DB_DATABASE'),
'user' => getenv('DB_USERNAME'),
'password' => getenv('DB_PASSWORD'),
'host' => getenv('DB_HOST'),
'port' => getenv('DB_PORT'),
'driver' => getenv('DB_TYPE'),
];
if ($connectionParams['driver'] === 'pgsql') {
$connectionParams['driver'] = 'pdo_pgsql';
$connectionParams['driver'] = 'pdo_pgsql';
}
$db = \Doctrine\DBAL\DriverManager::getConnection($connectionParams);
$host = getenv('BASE_HOST') ?: '';
@ -31,14 +31,14 @@ $factory = new \RandomLib\Factory;
$generator = $factory->getMediumStrengthGenerator();
$container = new Container(
$db,
$generator,
'https://' . $host,
$parserUrl,
$storeRoot,
$storeHost,
$appRoot,
$editKey
$db,
$generator,
'https://' . $host,
$parserUrl,
$storeRoot,
$storeHost,
$appRoot,
$editKey
);
return $container;

View file

@ -11,8 +11,8 @@ $container = require __DIR__ . '/init.php';
$uploadController = new Controllers\UploadController($container->getUploadProvider());
Flight::route('/*', function () {
header('Access-Control-Allow-Origin: *');
return true;
header('Access-Control-Allow-Origin: *');
return true;
});
Flight::route('/upload', [$uploadController, 'upload']);