uhh something

This commit is contained in:
Arsen Mirzaev Tatyano-Muradovich 2024-02-02 18:04:48 +07:00
parent 37070c626e
commit f4a109f446
32 changed files with 4151 additions and 1094 deletions

1
asdasd Submodule

@ -0,0 +1 @@
Subproject commit c18318f5de0e34f6af1491f8e550ffd273c55450

View File

@ -1,121 +0,0 @@
<?php
declare(strict_types=1);
namespace mirzaev\notchat\controllers;
// Files of the project
use mirzaev\notchat\views\manager,
mirzaev\notchat\models\core as models,
mirzaev\notchat\models\account_model as account,
mirzaev\notchat\models\session_model as session;
// Library for ArangoDB
use ArangoDBClient\Document as _document;
// Framework for PHP
use mirzaev\minimal\controller;
/**
* Core of controllers
*
* @package mirzaev\notchat\controllers
* @author mirzaev < mail >
*/
class core extends controller
{
/**
* Postfix for name of controllers files
*/
final public const POSTFIX = '';
/**
* Instance of a session
*/
protected readonly session session;
/**
* Instance of an account
*/
protected readonly ?account account;
/**
* Registry of errors
*/
protected array errors = [
'session' => [],
'account' => []
];
/**
* Constructor of an instance
*
* @param bool initialize Initialize a controller?
*
* @return void
*/
public function __construct(bool initialize = true)
{
// Blocking requests from CloudFlare (better to write this blocking into nginx config file)
if (_SERVER['HTTP_USER_AGENT'] === 'nginx-ssl early hints') return;
// For the extends system
parent::__construct(initialize);
if (initialize) {
// Initializing is requested
// Initializing of models core (connect to ArangoDB...)
new models();
// Initializing of the date until which the session will be active
expires = strtotime('+1 week');
// Initializing of default value of hash of the session
_COOKIE["session"] ??= null;
// Initializing of session
this->session = new session(_COOKIE["session"], expires, this->errors['session']);
// Handle a problems with initializing a session
if (!empty(this->errors['session'])) die;
else if (_COOKIE["session"] !== this->session->hash) {
// Hash of the session is changed (implies that the session has expired and recreated)
// Write a new hash of the session to cookies
setcookie(
'session',
this->session->hash,
[
'expires' => expires,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'strict'
]
);
}
// Initializing of preprocessor of views
this->view = new templater(this->session);
}
}
/**
* Check of initialization
*
* Checks whether a property is initialized in a document instance from ArangoDB
*
* @param string name Name of the property from ArangoDB
*
* @return bool The property is initialized?
*/
public function __isset(string name): bool
{
// Check of initialization of the property and exit (success)
return match (name) {
default => isset(this->{name})
};
}
}

View File

@ -1,32 +0,0 @@
<?php
declare(strict_types=1);
namespace mirzaev\notchat\controllers;
// Files of the project
use mirzaev\notchat\controllers\core;
/**
* Index controller
*
* @package mirzaev\notchat\controllers
* @author mirzaev < mail >
*/
final class index extends core
{
/**
* Render the main page
*
* @param array parameters Parameters of the request (POST + GET)
*/
public function index(array parameters = []): ?string
{
// Exit (success)
if (_SERVER['REQUEST_METHOD'] === 'GET') return this->view->render(DIRECTORY_SEPARATOR . 'index.html');
else if (_SERVER['REQUEST_METHOD'] === 'POST') return main;
// Exit (fail)
return null;
}
}

View File

@ -1,289 +0,0 @@
<?php
declare(strict_types=1);
namespace mirzaev\notchat\models;
// Framework for PHP
use mirzaev\minimal\model;
// Framework for ArangoDB
use mirzaev\arangodb\connection as arangodb,
mirzaev\arangodb\collection,
mirzaev\arangodb\document;
// Libraries for ArangoDB
use ArangoDBClient\Document as _document,
ArangoDBClient\DocumentHandler as _document_handler;
// Built-in libraries
use exception;
/**
* Core of models
*
* @package mirzaev\notchat\controllers
* @author mirzaev < mail >
*/
class core extends model
{
/**
* Postfix for name of models files
*/
final public const POSTFIX = '';
/**
* Path to the file with settings of connecting to the ArangoDB
*/
final public const ARANGODB = '../settings/arangodb.php';
/**
* Instance of the session of ArangoDB
*/
protected static arangodb arangodb;
/**
* Name of the collection in ArangoDB
*/
public const COLLECTION = 'THIS_COLLECTION_SHOULD_NOT_EXIST_REPLACE_IT_IN_THE_MODEL';
/**
* Constructor of an instance
*
* @param bool initialize Initialize a model?
* @param ?arangodb arangodb Instance of a session of ArangoDB
*
* @return void
*/
public function __construct(bool initialize = true, ?arangodb arangodb = null)
{
// For the extends system
parent::__construct(initialize);
if (initialize) {
// Initializing is requested
if (isset(arangodb)) {
// Recieved an instance of a session of ArangoDB
// Write an instance of a session of ArangoDB to the property
this->__set('arangodb', arangodb);
} else {
// Not recieved an instance of a session of ArangoDB
// Initializing of an instance of a session of ArangoDB
this->__get('arangodb');
}
}
}
/**
* Read from ArangoDB
*
* @param string filter Expression for filtering (AQL)
* @param string sort Expression for sorting (AQL)
* @param int amount Amount of documents for collect
* @param int page Page
* @param string return Expression describing the parameters to return (AQL)
* @param array &errors The registry on errors
*
* @return _document|array|null An array of instances of documents from ArangoDB, if they are found
*/
public static function read(
string filter = '',
string sort = 'd.created DESC, d._key DESC',
int amount = 1,
int page = 1,
string return = 'd',
array &errors = []
): _document|array|null {
try {
if (collection::init(static::arangodb->session, static::COLLECTION)) {
// Initialized the collection
// Read from ArangoDB and exit (success)
return collection::search(
static::arangodb->session,
sprintf(
<<<'AQL'
FOR d IN %s
%s
%s
LIMIT %d, %d
RETURN %s
AQL,
static::COLLECTION,
empty(filter) ? '' : "FILTER filter",
empty(sort) ? '' : "SORT sort",
--page <= 0 ? 0 : amount * page,
amount,
return
)
);
} else throw new exception('Failed to initialize the collection');
} catch (exception e) {
// Write to the registry of errors
errors[] = [
'text' => e->getMessage(),
'file' => e->getFile(),
'line' => e->getLine(),
'stack' => e->getTrace()
];
}
// Exit (fail)
return null;
}
/**
* Delete from ArangoDB
*
* @param _document instance Instance of the document from ArangoDB
* @param array &errors The registry on errors
*
* @return bool Deleted from ArangoDB without errors?
*/
public static function delete(_document instance, array &errors = []): bool
{
try {
if (collection::init(static::arangodb->session, static::COLLECTION)) {
// Initialized the collection
// Delete from ArangoDB and exit (success)
return (new _document_handler(static::arangodb->session))->remove(instance);
} else throw new exception('Failed to initialize the collection');
} catch (exception e) {
// Write to the registry of errors
errors[] = [
'text' => e->getMessage(),
'file' => e->getFile(),
'line' => e->getLine(),
'stack' => e->getTrace()
];
}
// Exit (fail)
return false;
}
/**
* Update in ArangoDB
*
* @param _document instance Instance of the document from ArangoDB
*
* @return bool Writed to ArangoDB without errors?
*/
public static function update(_document instance): bool
{
// Update in ArangoDB and exit (success)
return document::update(static::arangodb->session, instance);
}
/**
* Write
*
* @param string name Name of the property
* @param mixed value Value of the property
*
* @return void
*/
public function __set(string name, mixed value = null): void
{
match (name) {
'arangodb' => (function () use (value) {
if (this->__isset('arangodb')) {
// Is alredy initialized
// Exit (fail)
throw new exception('Forbidden to reinitialize the session of ArangoDB (this::arangodb)', 500);
} else {
// Is not already initialized
if (value instanceof arangodb) {
// Recieved an appropriate value
// Write the property and exit (success)
self::arangodb = value;
} else {
// Recieved an inappropriate value
// Exit (fail)
throw new exception('Session of ArangoDB (this::arangodb) is need to be mirzaev\arangodb\connection', 500);
}
}
})(),
default => parent::__set(name, value)
};
}
/**
* Read
*
* @param string name Name of the property
*
* @return mixed Content of the property, if they are found
*/
public function __get(string name): mixed
{
return match (name) {
'arangodb' => (function () {
try {
if (!this->__isset('arangodb')) {
// Is not initialized
// Initializing of a default value from settings
this->__set('arangodb', new arangodb(require static::ARANGODB));
}
// Exit (success)
return self::arangodb;
} catch (exception) {
// Exit (fail)
return null;
}
})(),
default => parent::__get(name)
};
}
/**
* Delete
*
* @param string name Name of the property
*
* @return void
*/
public function __unset(string name): void
{
// Deleting a property and exit (success)
parent::__unset(name);
}
/**
* Check of initialization
*
* @param string name Name of the property
*
* @return bool The property is initialized?
*/
public function __isset(string name): bool
{
// Check of initialization of the property and exit (success)
return parent::__isset(name);
}
/**
* Call a static property or method
*
* @param string name Name of the property or the method
* @param array arguments Arguments for the method
*/
public static function __callStatic(string name, array arguments): mixed
{
match (name) {
'arangodb' => (new static)->__get('arangodb'),
default => throw new exception("Not found: name", 500)
};
}
}

View File

@ -1,276 +0,0 @@
<?php
declare(strict_types=1);
namespace mirzaev\notchat\models;
// Files of the project
use mirzaev\ebala\models\account,
mirzaev\ebala\models\traits\status;
// Framework for ArangoDB
use mirzaev\arangodb\collection,
mirzaev\arangodb\document;
// Library для ArangoDB
use ArangoDBClient\Document as _document;
// Built-in libraries
use exception;
/**
* Model of session
*
* @package mirzaev\notchat\controllers
* @author mirzaev < mail >
*/
final class session extends core
{
/**
* Name of the collection in ArangoDB
*/
final public const COLLECTION = 'session';
/**
* An instance of the ArangoDB document from ArangoDB
*/
protected readonly _document document;
/**
* Constructor of an instance
*
* Initialize of a session and write them to the this->document property
*
* @param ?string hash Hash of the session in ArangoDB
* @param ?int expires Date of expiring of the session (used for creating a new session)
* @param array &errors Registry of errors
*
* @return static instance of the ArangoDB document of session
*/
public function __construct(?string hash = null, ?int expires = null, array &errors = [])
{
try {
if (collection::init(static::arangodb->session, self::COLLECTION)) {
// Initialized the collection
if (this->search(hash, errors)) {
// Found an instance of the ArangoDB document of session and received a session hash
} else {
// Not found an instance of the ArangoDB document of session
// Initializing a new session and write they into ArangoDB
_id = document::write(this::arangodb->session, self::COLLECTION, [
'active' => true,
'expires' => expires ?? time() + 604800,
'ip' => _SERVER['REMOTE_ADDR'],
'x-forwarded-for' => _SERVER['HTTP_X_FORWARDED_FOR'] ?? null,
'referer' => _SERVER['HTTP_REFERER'] ?? null,
'useragent' => _SERVER['HTTP_USER_AGENT'] ?? null
]);
if (session = collection::search(this::arangodb->session, sprintf(
<<<AQL
FOR d IN %s
FILTER d._id == '%s' && d.expires > %d && d.active == true
RETURN d
AQL,
self::COLLECTION,
_id,
time()
))) {
// Found an instance of just created new session
// Generate a hash and write into an instance of the ArangoDB document of session property
session->hash = sodium_bin2hex(sodium_crypto_generichash(_id));
if (document::update(this::arangodb->session, session)) {
// Is writed update
// Write instance of the ArangoDB document of session into property and exit (success)
this->document = session;
} else throw new exception('Could not write the session data');
} else throw new exception('Could not create or find just created session');
}
} else throw new exception('Could not initialize the collection');
} catch (exception e) {
// Write to the registry of errors
errors[] = [
'text' => e->getMessage(),
'file' => e->getFile(),
'line' => e->getLine(),
'stack' => e->getTrace()
];
}
}
/**
* Search
*
* Search for the session in ArangoDB by hash and write they into this->document property if they are found
*
* @param ?string hash Hash of the session in ArangoDB
* @param array &errors Registry of errors
*
* @return static instance of the ArangoDB document of session
*/
public function search(?string hash, array &errors = []): bool
{
try {
if (isset(hash)) {
// Recieved a hash
// Search the session data in ArangoDB
_document = session = collection::search(this::arangodb->session, sprintf(
<<<AQL
FOR d IN %s
FILTER d.hash == '%s' && d.expires > %d && d.active == true
RETURN d
AQL,
self::COLLECTION,
hash,
time()
));
if (_document instanceof _document) {
// An instance of the ArangoDB document of session is found
// Write the session data to the property
this->document = _document;
// Exit (success)
return true;
}
}
} catch (exception e) {
// Write to the registry of errors
errors[] = [
'text' => e->getMessage(),
'file' => e->getFile(),
'line' => e->getLine(),
'stack' => e->getTrace()
];
}
// Exit (fail)
return false;
}
/**
* Write to buffer of the session
*
* @param array data Data for merging
* @param array &errors Registry of errors
*
* @return bool Is data has written into the session buffer?
*/
public function write(array data, array &errors = []): bool
{
try {
if (collection::init(this::arangodb->session, self::COLLECTION)) {
// Initialized the collection
// An instance of the ArangoDB document of session is initialized?
if (!isset(this->document)) throw new exception('An instance of the ArangoDB document of session is not initialized');
// Write data into buffwer of an instance of the ArangoDB document of session
this->document->buffer = array_replace_recursive(
this->document->buffer ?? [],
[_SERVER['INTERFACE'] => array_replace_recursive(this->document->buffer[_SERVER['INTERFACE']] ?? [], data)]
);
// Write to ArangoDB and exit (success)
return document::update(this::arangodb->session, this->document) ? true : throw new exception('Не удалось записать данные в буфер сессии');
} else throw new exception('Could not initialize the collection');
} catch (exception e) {
// Write to the registry of errors
errors[] = [
'text' => e->getMessage(),
'file' => e->getFile(),
'line' => e->getLine(),
'stack' => e->getTrace()
];
}
return false;
}
/**
* Write
*
* Write a property into an instance of the ArangoDB document
*
* @param string name Name of the property
* @param mixed value Content of the property
*
* @return void
*/
public function __set(string name, mixed value = null): void
{
// Write to the property into an instance of the ArangoDB document and exit (success)
this->document->{name} = value;
}
/**
* Read
*
* Read a property from an instance of the ArangoDB docuemnt
*
* @param string name Name of the property
*
* @return mixed Content of the property
*/
public function __get(string name): mixed
{
// Read a property from an instance of the ArangoDB document and exit (success)
return match (name) {
'arangodb' => this::arangodb,
default => this->document->{name}
};
}
/**
* Delete
*
* Deinitialize the property in an instance of the ArangoDB document
*
* @param string name Name of the property
*
* @return void
*/
public function __unset(string name): void
{
// Delete the property in an instance of the ArangoDB document and exit (success)
unset(this->document->{name});
}
/**
* Check of initialization
*
* Check of initialization of the property into an instance of the ArangoDB document
*
* @param string name Name of the property
*
* @return bool The property is initialized?
*/
public function __isset(string name): bool
{
// Check of initializatio nof the property and exit (success)
return isset(this->document->{name});
}
/**
* Execute a method
*
* Execute a method from an instance of the ArangoDB document
*
* @param string name Name of the method
* @param array arguments Arguments for the method
*
* @return mixed Result of execution of the method
*/
public function __call(string name, array arguments = []): mixed
{
// Execute the method and exit (success)
if (method_exists(this->document, name)) return this->document->{name}(arguments);
}
}

View File

@ -1,45 +0,0 @@
<?php
declare(strict_types=1);
namespace mirzaev\notchat\models\traits;
// Built-in libraries
use exception;
/**
* Trait fo initialization of a status
*
* @package mirzaev\notchat\models\traits
*
* @author mirzaev < mail >
*/
trait status
{
/**
* Initialize of a status
*
* @param array &errors Registry of errors
*
* @return ?bool Status, if they are found
*/
public function status(array &errors = []): ?bool
{
try {
// Read from ArangoDB and exit (success)
return this->document->active ?? false;
} catch (exception e) {
// Write to the registry of errors
errors[] = [
'text' => e->getMessage(),
'file' => e->getFile(),
'line' => e->getLine(),
'stack' => e->getTrace()
];
}
// Exit (fail)
return null;
}
}

View File

@ -1,47 +0,0 @@
@charset "UTF-8";
* {
text-decoration: none;
outline: none;
border: none;
/* font-family: , system-ui, sans-serif; */
font-family: "dejavu";
transition: 0.1s ease-out;
}
body {
margin: 0;
min-height: 100vh;
padding: 0;
display: flex;
flex-direction: column;
background-color: var(--background, #fafafa);
}
aside {
}
header {
}
main {
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
transition: 0s;
}
footer {
}
.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

View File

@ -1,32 +0,0 @@
<?php
declare(strict_types=1);
namespace mirzaev\notchat;
use mirzaev\minimal\core;
use mirzaev\minimal\router;
/* ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1); */
define('VIEWS', realpath('..' . DIRECTORY_SEPARATOR . 'views'));
define('STORAGE', realpath('..' . DIRECTORY_SEPARATOR . 'storage'));
define('INDEX', __DIR__);
// Автозагрузка
require __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
// Инициализация маршрутизатора
router = new router;
// Запись маршрутов
router->write('/', 'index', 'index');
// Инициализация ядра
core = new core(namespace: __NAMESPACE__, router: router);
// Обработка запроса
echo core->start();

View File

@ -1,3 +0,0 @@
*
!.gitignore
!*.sample

View File

@ -1,8 +0,0 @@
<?php
return [
'endpoint' => 'unix:///var/run/arangodb3/arango.sock',
'database' => 'notchat',
'name' => 'notchat',
'password' => ''
];

View File

@ -1,202 +0,0 @@
<?php
declare(strict_types=1);
namespace mirzaev\notchat\views;
// Files of the project
use mirzaev\notchat\models\session,
mirzaev\notchat\models\account;
// Framework for PHP
use mirzaev\minimal\controller;
// Templater of views
use Twig\Loader\FilesystemLoader,
Twig\Environment as twig,
Twig\Extra\Intl\IntlExtension as intl,
Twig\TwigFilter;
// Built-in libraries
use ArrayAccess;
/**
* Templater core
*
* @package mirzaev\notchat\views
* @author mirzaev < mail >
*/
final class templater extends controller implements ArrayAccess
{
/**
* Registry of global variables of view
*/
public array variables = [];
/**
* Instance of twig templater
*/
readonly public twig twig;
/**
* Constructor of an instance
*
* @param ?session session Instance of the session of ArangoDB
*
* @return void
*/
public function __construct(?session &session = null): void
{
// Initializing of an instance of twig
this->twig = new twig(new FilesystemLoader(VIEWS));
// Initializing of global variables
this->twig->addGlobal('theme', 'default');
this->twig->addGlobal('server', _SERVER);
this->twig->addGlobal('cookies', _COOKIE);
if (!empty(session->status())) {
this->twig->addGlobal('session', session);
}
// Initializing of twig extensions
this->twig->addExtension(new intl());
}
/**
* Render a HTML-document
*
* @param string file Related path to a HTML-document
* @param ?array variables Registry of variables to push into registry of global variables
*
* @return ?string HTML-документ
*/
public function render(string file, ?array variables = null): ?string
{
// Generation and exit (success)
return this->twig->render('themes' . DIRECTORY_SEPARATOR . this->twig->getGlobal('theme') . DIRECTORY_SEPARATOR . file, variables + this->variables);
}
/**
* Write
*
* Write a variable into registry of global variables
*
* @param string name Name of the variable
* @param mixed value Value of the variable
*
* @return void
*/
public function __set(string name, mixed value = null): void
{
// Write the variable and exit (success)
this->variables[name] = value;
}
/**
* Read
*
* Read a variable from registry of global variables
*
* @param string name Name of the variable
*
* @return mixed Content of the variable, if they are found
*/
public function __get(string name): mixed
{
// Read the variable and exit (success)
return this->variables[name];
}
/**
* Delete
*
* Delete a variable from the registry of global variables
*
* @param string name Name of the variable
*
* @return void
*/
public function __unset(string name): void
{
// Delete the variable and exit (success)
unset(this->variables[name]);
}
/**
* Check of initialization
*
* Check of initialization in registry of global variables
*
* @param string name Name of the variable
*
* @return bool The variable is initialized?
*/
public function __isset(string name): bool
{
// Check of initialization of the variable and exit (success)
return isset(this->variables[name]);
}
/**
* Write
*
* Write a variable into registry of global variables
*
* @param mixed name Name of an offset of the variable
* @param mixed value Value of the variable
*
* @return void
*/
public function offsetSet(mixed name, mixed value): void
{
// Write the variable and exit (success)
this->variables[name] = value;
}
/**
* Read
*
* Read a variable from registry of global variables
*
* @param mixed name Name of the variable
*
* @return mixed Content of the variable, if they are found
*/
public function offsetGet(mixed name): mixed
{
// Read the variable and exit (success)
return this->variables[name];
}
/**
* Delete
*
* Delete a variable from the registry of global variables
*
* @param mixed name Name of the variable
*
* @return void
*/
public function offsetUnset(mixed name): void
{
// Delete the variable and exit (success)
unset(this->variables[name]);
}
/**
* Check of initialization
*
* Check of initialization in registry of global variables
*
* @param mixed name Name of the variable
*
* @return bool The variable is initialized?
*/
public function offsetExists(mixed name): bool
{
// Check of initialization of the variable and exit (success)
return isset(this->variables[name]);
}
}

View File

@ -1,27 +0,0 @@
{% extends "core.html" %}
{% use "core.html" with css as core_css, body as core, js as core_js %}
{% use "header.html" with css as header_css, body as header, js as header_js %}
{% use "footer.html" with css as footer_css, body as footer, js as footer_js %}
{% block css %}
{{ block('core_css') }}
{{ block('header_css') }}
{{ block('footer_css') }}
{% endblock %}
{% block body %}
{{ block('header') }}
<main>
{% block main %}
{{ main|raw }}
{% endblock %}
</main>
{{ block('footer') }}
{% endblock %}
{% block js %}
{{ block('footer_js') }}
{{ block('header_js') }}
{{ block('core_js') }}
{% endblock %}

View File

@ -2,15 +2,19 @@
"name": "mirzaev/notchat", "name": "mirzaev/notchat",
"description": "Free P2P chat based on asdasd", "description": "Free P2P chat based on asdasd",
"readme": "README.md", "readme": "README.md",
"keywords": [], "keywords": [
"chat",
"p2p",
"blockchain"
],
"type": "site", "type": "site",
"homepage": "https://git.mirzaev.sexy/mirzaev/notchat", "homepage": "https://git.mirzaev.sexy/mirzaev/notchat",
"license": "WTFPL", "license": "WTFPL",
"authors": [ "authors": [
{ {
"name": "mirzaev", "name": "Arsen Mirzaev Tatyano-Muradovich",
"email": "mirzaev@gmail.com", "email": "arsen@mirzaev.sexy",
"homepage": "https://mirzaev.page", "homepage": "https://mirzaev.sexy",
"role": "Programmer" "role": "Programmer"
} }
], ],
@ -20,11 +24,8 @@
}, },
"require": { "require": {
"php": "~8.3", "php": "~8.3",
"ext-sodium": "~8.3", "ext-openswoole": "~20230831",
"mirzaev/minimal": "^2.2.0", "mirzaev/minimal": "^2.2.0",
"mirzaev/accounts": "~1.2.x-dev",
"mirzaev/arangodb": "^1.0.0",
"triagens/arangodb": "~3.9.x-dev",
"twig/twig": "^3.4" "twig/twig": "^3.4"
}, },
"require-dev": { "require-dev": {

View File

@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace mirzaev\notchat\controllers;
// Files of the project
use mirzaev\notchat\views\templater,
mirzaev\notchat\models\core as models;
// Framework for PHP
use mirzaev\minimal\controller;
/**
* Core of controllers
*
* @package mirzaev\notchat\controllers
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/
class core extends controller
{
/**
* Postfix for name of controllers files
*/
final public const POSTFIX = '';
/**
* Registry of errors
*/
protected array $errors = [];
/**
* Constructor of an instance
*
* @param bool $initialize Initialize a controller?
*
* @return void
*/
public function __construct(bool $initialize = true)
{
// For the extends system
parent::__construct($initialize);
if ($initialize) {
// Initializing is requested
// Initializing of models core
new models();
// Initializing of preprocessor of views
$this->view = new templater();
}
}
/**
* Check of initialization
*
* Checks whether a property is initialized in a document instance from ArangoDB
*
* @param string $name Name of the property from ArangoDB
*
* @return bool The property is initialized?
*/
public function __isset(string $name): bool
{
// Check of initialization of the property and exit (success)
return match ($name) {
default => isset($this->{$name})
};
}
}

View File

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace mirzaev\notchat\controllers;
// Files of the project
use mirzaev\notchat\controllers\core;
/**
* Index controller
*
* @package mirzaev\notchat\controllers
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/
final class index extends core
{
/**
* Render the main page
*
* @param array $parameters Parameters of the request (POST + GET)
*/
public function index(array $parameters = []): ?string
{
// Exit (success)
if ($_SERVER['REQUEST_METHOD'] === 'GET') return $this->view->render('chats.html');
else if ($_SERVER['REQUEST_METHOD'] === 'POST') return $this->view->render('chats.html');
// Exit (fail)
return null;
}
}

View File

@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
namespace mirzaev\notchat\models;
// Framework for PHP
use mirzaev\minimal\model;
// Built-in libraries
use exception;
/**
* Core of models
*
* @package mirzaev\notchat\controllers
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/
class core extends model
{
/**
* Postfix for name of models files
*/
final public const POSTFIX = '';
/**
* Constructor of an instance
*
* @param bool $initialize Initialize a model?
*
* @return void
*/
public function __construct(bool $initialize = true)
{
// For the extends system
parent::__construct($initialize);
if ($initialize) {
// Initializing is requested
}
}
/**
* Write
*
* @param string $name Name of the property
* @param mixed $value Value of the property
*
* @return void
*/
public function __set(string $name, mixed $value = null): void
{
match ($name) {
default => parent::__set($name, $value)
};
}
/**
* Read
*
* @param string $name Name of the property
*
* @return mixed Content of the property, if they are found
*/
public function __get(string $name): mixed
{
return match ($name) {
default => parent::__get($name)
};
}
/**
* Delete
*
* @param string $name Name of the property
*
* @return void
*/
public function __unset(string $name): void
{
// Deleting a property and exit (success)
parent::__unset($name);
}
/**
* Check of initialization
*
* @param string $name Name of the property
*
* @return bool The property is initialized?
*/
public function __isset(string $name): bool
{
// Check of initialization of the property and exit (success)
return parent::__isset($name);
}
/**
* Call a static property or method
*
* @param string $name Name of the property or the method
* @param array $arguments Arguments for the method
*/
public static function __callStatic(string $name, array $arguments): mixed
{
match ($name) {
default => throw new exception("Not found: {$name}", 500)
};
}
}

View File

@ -0,0 +1,186 @@
@charset "UTF-8";
:root {
/* --background: #153439; ОЧЕНЬ КРУТОЙ */
--background: #153439;
--background-2: #153439;
--important: #0b4e51;
--envelope: #28575b;
--section-blue: #0b474a;
--section: #11484a;
--red: #4d2d2d;
--green: #415e53;
--blue: #243b4f;
}
* {
text-decoration: none;
outline: none;
border: none;
/* font-family: , system-ui, sans-serif; */
font-family: "dejavu";
transition: 0.1s ease-out;
}
body {
--row-aside: 200px;
--row-settings: 100px;
--gap: 16px;
margin: 0;
width: auto;
height: 100vh;
display: grid;
grid-template-columns: [header] 220px [settings] 320px [main] auto [footer] 180px;
grid-template-rows: [aside] var(--row-aside, 200px) [settings] var(--row-settings, 100px) [main] auto;
gap: var(--gap, 16px);
padding: 0;
overflow-x: scroll;
overflow-y: clip;
background-color: var(--background, #fafafa);
--body-rays: inset 0px 8vh 35vw -8vw var(--background-2), inset 0px -8vh 35vw -8vw var(--background-2);
box-shadow: var(--body-rays);
-webkit-box-shadow: var(--body-rays);
-moz-box-shadow: var(--body-rays);
}
header {
z-index: 1000;
grid-column: header;
grid-row: 1 / -1;
display: grid;
grid-template-rows: inherit;
}
header>section[data-section="window"] {
z-index: 1100;
grid-row: aside;
}
header>section[data-section="main"] {
z-index: 1200;
grid-row: settings / -1;
display: grid;
background-color: var(--envelope);
}
section[data-section="servers"] {
z-index: 250;
grid-row: settings;
background-color: var(--important);
border-radius: 5px;
}
section[data-section="chats"] {
z-index: 200;
margin-bottom: var(--gap);
grid-row: main;
background-color: var(--section);
border-radius: 5px;
}
aside {
z-index: 300;
grid-column: 1 / -1;
grid-row: aside;
display: flex;
}
main {
--sections-default: 1;
--sections-width: 520px;
z-index: 100;
margin-bottom: var(--gap);
grid-row: settings / -1;
grid-column: main;
display: grid;
grid-template-rows: [settings] var(--row-settings, 100px) [main] auto;
grid-template-columns: repeat(var(--sections, var(--sections-default, 1)), [chat] var(--sections-width, 520px));
flex-direction: column;
align-items: center;
gap: var(--gap, 16px);
transition: 0s;
}
main>section {
width: 100%;
height: 100%;
max-width: var(--sections-width, 480px);
grid-column: var(--position, 1);
grid-row: main;
overflow-x: crop;
overflow-y: scroll;
background-color: var(--section);
border-radius: 5px;
}
aside {
z-index: 300;
grid-column: 1 / -1;
grid-row: aside;
display: flex;
}
main {
--sections-default: 1;
--sections-width: 480px;
z-index: 100;
grid-row: settings / -1;
grid-column: main;
display: grid;
grid-template-rows: [settings] var(--row-settings, 100px) [main] auto;
grid-template-columns: repeat(var(--sections, var(--sections-default, 1)), [chat] var(--sections-width, 480px));
flex-direction: column;
align-items: center;
gap: var(--gap, 16px);
transition: 0s;
}
main>section {
width: 100%;
max-width: var(--sections-width, 480px);
grid-column: var(--position, 1);
grid-row: main;
overflow: scroll;
background-color: var(--section);
}
main>section[data-panel-type="settings"] {
grid-row: settings;
}
footer {
z-index: 500;
grid-column: footer;
grid-row: 1 / -1;
display: grid;
grid-template-rows: inherit;
}
footer>section[data-section="window"] {
z-index: 600;
grid-row: aside;
}
footer>section[data-section="main"] {
z-index: 700;
grid-row: settings / -1;
display: grid;
background-color: var(--envelope);
}
:is(div, section).window {
overflow: hidden;
border-right: 1px solid;
border-right-color: rgba(174, 122, 122, 0.71);
background-color: rgba(255, 255, 255, 0.27);
backdrop-filter: blur(2px);
}
.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

View File

@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace mirzaev\notchat;
// Files of the project
use mirzaev\notchat\controllers\core as controller,
mirzaev\notchat\models\core as model;
// Framework for PHP
use mirzaev\minimal\core,
mirzaev\minimal\router;
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
define('VIEWS', realpath('..' . DIRECTORY_SEPARATOR . 'views'));
define('STORAGE', realpath('..' . DIRECTORY_SEPARATOR . 'storage'));
define('INDEX', __DIR__);
// Автозагрузка
require __DIR__ . DIRECTORY_SEPARATOR
. '..' . DIRECTORY_SEPARATOR
. '..' . DIRECTORY_SEPARATOR
. '..' . DIRECTORY_SEPARATOR
. '..' . DIRECTORY_SEPARATOR
. 'vendor' . DIRECTORY_SEPARATOR
. 'autoload.php';
// Инициализация маршрутизатора
$router = new router;
// Запись маршрутов
$router->write('/', 'index', 'index');
// Инициализация ядра
$core = new core(namespace: __NAMESPACE__, router: $router, controller: new controller(false), model: new model(false));
// Обработка запроса
echo $core->start();

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1 @@
../../../../../asdasd/system

View File

@ -0,0 +1,677 @@
// WebSocket and WebRTC based multi-user chat sample with two-way video
// calling, including use of TURN if applicable or necessary.
//
// This file contains the JavaScript code that implements the client-side
// features for connecting and managing chat and video calls.
//
// To read about how this sample works: http://bit.ly/webrtc-from-chat
//
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
"use strict";
// Get our hostname
var myHostname = window.location.hostname;
if (!myHostname) {
myHostname = "localhost";
}
log("Hostname: " + myHostname);
// WebSocket chat/signaling channel variables.
var connection = null;
var clientID = 0;
// The media constraints object describes what sort of stream we want
// to request from the local A/V hardware (typically a webcam and
// microphone). Here, we specify only that we want both audio and
// video; however, you can be more specific. It's possible to state
// that you would prefer (or require) specific resolutions of video,
// whether to prefer the user-facing or rear-facing camera (if available),
// and so on.
//
// See also:
// https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints
// https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
//
var mediaConstraints = {
audio: true, // We want an audio track
video: {
aspectRatio: {
ideal: 1.333333 // 3:2 aspect is preferred
}
}
};
var myUsername = null;
var targetUsername = null; // To store username of other peer
var myPeerConnection = null; // RTCPeerConnection
var transceiver = null; // RTCRtpTransceiver
var webcamStream = null; // MediaStream from webcam
// Output logging information to console.
function log(text) {
var time = new Date();
console.log("[" + time.toLocaleTimeString() + "] " + text);
}
// Output an error message to console.
function log_error(text) {
var time = new Date();
console.trace("[" + time.toLocaleTimeString() + "] " + text);
}
// Send a JavaScript object by converting it to JSON and sending
// it as a message on the WebSocket connection.
function sendToServer(msg) {
var msgJSON = JSON.stringify(msg);
log("Sending '" + msg.type + "' message: " + msgJSON);
connection.send(msgJSON);
}
// Called when the "id" message is received; this message is sent by the
// server to assign this login session a unique ID number; in response,
// this function sends a "username" message to set our username for this
// session.
function setUsername() {
myUsername = document.getElementById("name").value;
sendToServer({
name: myUsername,
date: Date.now(),
id: clientID,
type: "username"
});
}
// Open and configure the connection to the WebSocket server.
function connect() {
var serverUrl;
var scheme = "ws";
// If this is an HTTPS connection, we have to use a secure WebSocket
// connection too, so add another "s" to the scheme.
if (document.location.protocol === "https:") {
scheme += "s";
}
serverUrl = scheme + "://" + 'pantry.bebra.team:6503';
// serverUrl = scheme + "://" + '95.188.77.71:6503';
log(`Connecting to server: ${serverUrl}`);
connection = new WebSocket(serverUrl, "json");
connection.onopen = function(evt) {
document.getElementById("text").disabled = false;
document.getElementById("send").disabled = false;
};
connection.onerror = function(evt) {
console.dir(evt);
}
connection.onmessage = function(evt) {
var chatBox = document.querySelector(".chatbox");
var text = "";
var msg = JSON.parse(evt.data);
log("Message received: ");
console.dir(msg);
var time = new Date(msg.date);
var timeStr = time.toLocaleTimeString();
switch(msg.type) {
case "id":
clientID = msg.id;
setUsername();
break;
case "username":
text = "<b>User <em>" + msg.name + "</em> signed in at " + timeStr + "</b><br>";
break;
case "message":
text = "(" + timeStr + ") <b>" + msg.name + "</b>: " + msg.text + "<br>";
break;
case "rejectusername":
myUsername = msg.name;
text = "<b>Your username has been set to <em>" + myUsername +
"</em> because the name you chose is in use.</b><br>";
break;
case "userlist": // Received an updated user list
handleUserlistMsg(msg);
break;
// Signaling messages: these messages are used to trade WebRTC
// signaling information during negotiations leading up to a video
// call.
case "video-offer": // Invitation and offer to chat
handleVideoOfferMsg(msg);
break;
case "video-answer": // Callee has answered our offer
handleVideoAnswerMsg(msg);
break;
case "new-ice-candidate": // A new ICE candidate has been received
handleNewICECandidateMsg(msg);
break;
case "hang-up": // The other peer has hung up the call
handleHangUpMsg(msg);
break;
// Unknown message; output to console for debugging.
default:
log_error("Unknown message received:");
log_error(msg);
}
// If there's text to insert into the chat buffer, do so now, then
// scroll the chat panel so that the new text is visible.
if (text.length) {
chatBox.innerHTML += text;
chatBox.scrollTop = chatBox.scrollHeight - chatBox.clientHeight;
}
};
}
// Handles a click on the Send button (or pressing return/enter) by
// building a "message" object and sending it to the server.
function handleSendButton() {
var msg = {
text: document.getElementById("text").value,
type: "message",
id: clientID,
date: Date.now()
};
sendToServer(msg);
document.getElementById("text").value = "";
}
// Handler for keyboard events. This is used to intercept the return and
// enter keys so that we can call send() to transmit the entered text
// to the server.
function handleKey(evt) {
if (evt.keyCode === 13 || evt.keyCode === 14) {
if (!document.getElementById("send").disabled) {
handleSendButton();
}
}
}
// Create the RTCPeerConnection which knows how to talk to our
// selected STUN/TURN server and then uses getUserMedia() to find
// our camera and microphone and add that stream to the connection for
// use in our video call. Then we configure event handlers to get
// needed notifications on the call.
async function createPeerConnection() {
log("Setting up a connection...");
// Create an RTCPeerConnection which knows to use our chosen
// STUN server.
myPeerConnection = new RTCPeerConnection({
iceServers: [ // Information about ICE servers - Use your own!
{
urls: "turn:" + myHostname, // A TURN server
username: "webrtc",
credential: "turnserver"
}
]
});
// Set up event handlers for the ICE negotiation process.
myPeerConnection.onicecandidate = handleICECandidateEvent;
myPeerConnection.oniceconnectionstatechange = handleICEConnectionStateChangeEvent;
myPeerConnection.onicegatheringstatechange = handleICEGatheringStateChangeEvent;
myPeerConnection.onsignalingstatechange = handleSignalingStateChangeEvent;
myPeerConnection.onnegotiationneeded = handleNegotiationNeededEvent;
myPeerConnection.ontrack = handleTrackEvent;
}
// Called by the WebRTC layer to let us know when it's time to
// begin, resume, or restart ICE negotiation.
async function handleNegotiationNeededEvent() {
log("*** Negotiation needed");
try {
log("---> Creating offer");
const offer = await myPeerConnection.createOffer();
// If the connection hasn't yet achieved the "stable" state,
// return to the caller. Another negotiationneeded event
// will be fired when the state stabilizes.
if (myPeerConnection.signalingState != "stable") {
log(" -- The connection isn't stable yet; postponing...")
return;
}
// Establish the offer as the local peer's current
// description.
log("---> Setting local description to the offer");
await myPeerConnection.setLocalDescription(offer);
// Send the offer to the remote peer.
log("---> Sending the offer to the remote peer");
sendToServer({
name: myUsername,
target: targetUsername,
type: "video-offer",
sdp: myPeerConnection.localDescription
});
} catch(err) {
log("*** The following error occurred while handling the negotiationneeded event:");
reportError(err);
};
}
// Called by the WebRTC layer when events occur on the media tracks
// on our WebRTC call. This includes when streams are added to and
// removed from the call.
//
// track events include the following fields:
//
// RTCRtpReceiver receiver
// MediaStreamTrack track
// MediaStream[] streams
// RTCRtpTransceiver transceiver
//
// In our case, we're just taking the first stream found and attaching
// it to the <video> element for incoming media.
function handleTrackEvent(event) {
log("*** Track event");
document.getElementById("received_video").srcObject = event.streams[0];
document.getElementById("hangup-button").disabled = false;
}
// Handles |icecandidate| events by forwarding the specified
// ICE candidate (created by our local ICE agent) to the other
// peer through the signaling server.
function handleICECandidateEvent(event) {
if (event.candidate) {
log("*** Outgoing ICE candidate: " + event.candidate.candidate);
sendToServer({
type: "new-ice-candidate",
target: targetUsername,
candidate: event.candidate
});
}
}
// Handle |iceconnectionstatechange| events. This will detect
// when the ICE connection is closed, failed, or disconnected.
//
// This is called when the state of the ICE agent changes.
function handleICEConnectionStateChangeEvent(event) {
log("*** ICE connection state changed to " + myPeerConnection.iceConnectionState);
switch(myPeerConnection.iceConnectionState) {
case "closed":
case "failed":
case "disconnected":
closeVideoCall();
break;
}
}
// Set up a |signalingstatechange| event handler. This will detect when
// the signaling connection is closed.
//
// NOTE: This will actually move to the new RTCPeerConnectionState enum
// returned in the property RTCPeerConnection.connectionState when
// browsers catch up with the latest version of the specification!
function handleSignalingStateChangeEvent(event) {
log("*** WebRTC signaling state changed to: " + myPeerConnection.signalingState);
switch(myPeerConnection.signalingState) {
case "closed":
closeVideoCall();
break;
}
}
// Handle the |icegatheringstatechange| event. This lets us know what the
// ICE engine is currently working on: "new" means no networking has happened
// yet, "gathering" means the ICE engine is currently gathering candidates,
// and "complete" means gathering is complete. Note that the engine can
// alternate between "gathering" and "complete" repeatedly as needs and
// circumstances change.
//
// We don't need to do anything when this happens, but we log it to the
// console so you can see what's going on when playing with the sample.
function handleICEGatheringStateChangeEvent(event) {
log("*** ICE gathering state changed to: " + myPeerConnection.iceGatheringState);
}
// Given a message containing a list of usernames, this function
// populates the user list box with those names, making each item
// clickable to allow starting a video call.
function handleUserlistMsg(msg) {
var i;
var listElem = document.querySelector(".userlistbox");
// Remove all current list members. We could do this smarter,
// by adding and updating users instead of rebuilding from
// scratch but this will do for this sample.
while (listElem.firstChild) {
listElem.removeChild(listElem.firstChild);
}
// Add member names from the received list.
msg.users.forEach(function(username) {
var item = document.createElement("li");
item.appendChild(document.createTextNode(username));
item.addEventListener("click", invite, false);
listElem.appendChild(item);
});
}
// Close the RTCPeerConnection and reset variables so that the user can
// make or receive another call if they wish. This is called both
// when the user hangs up, the other user hangs up, or if a connection
// failure is detected.
function closeVideoCall() {
var localVideo = document.getElementById("local_video");
log("Closing the call");
// Close the RTCPeerConnection
if (myPeerConnection) {
log("--> Closing the peer connection");
// Disconnect all our event listeners; we don't want stray events
// to interfere with the hangup while it's ongoing.
myPeerConnection.ontrack = null;
myPeerConnection.onnicecandidate = null;
myPeerConnection.oniceconnectionstatechange = null;
myPeerConnection.onsignalingstatechange = null;
myPeerConnection.onicegatheringstatechange = null;
myPeerConnection.onnotificationneeded = null;
// Stop all transceivers on the connection
myPeerConnection.getTransceivers().forEach(transceiver => {
transceiver.stop();
});
// Stop the webcam preview as well by pausing the <video>
// element, then stopping each of the getUserMedia() tracks
// on it.
if (localVideo.srcObject) {
localVideo.pause();
localVideo.srcObject.getTracks().forEach(track => {
track.stop();
});
}
// Close the peer connection
myPeerConnection.close();
myPeerConnection = null;
webcamStream = null;
}
// Disable the hangup button
document.getElementById("hangup-button").disabled = true;
targetUsername = null;
}
// Handle the "hang-up" message, which is sent if the other peer
// has hung up the call or otherwise disconnected.
function handleHangUpMsg(msg) {
log("*** Received hang up notification from other peer");
closeVideoCall();
}
// Hang up the call by closing our end of the connection, then
// sending a "hang-up" message to the other peer (keep in mind that
// the signaling is done on a different connection). This notifies
// the other peer that the connection should be terminated and the UI
// returned to the "no call in progress" state.
function hangUpCall() {
closeVideoCall();
sendToServer({
name: myUsername,
target: targetUsername,
type: "hang-up"
});
}
// Handle a click on an item in the user list by inviting the clicked
// user to video chat. Note that we don't actually send a message to
// the callee here -- calling RTCPeerConnection.addTrack() issues
// a |notificationneeded| event, so we'll let our handler for that
// make the offer.
async function invite(evt) {
log("Starting to prepare an invitation");
if (myPeerConnection) {
alert("You can't start a call because you already have one open!");
} else {
var clickedUsername = evt.target.textContent;
// Don't allow users to call themselves, because weird.
if (clickedUsername === myUsername) {
alert("I'm afraid I can't let you talk to yourself. That would be weird.");
return;
}
// Record the username being called for future reference
targetUsername = clickedUsername;
log("Inviting user " + targetUsername);
// Call createPeerConnection() to create the RTCPeerConnection.
// When this returns, myPeerConnection is our RTCPeerConnection
// and webcamStream is a stream coming from the camera. They are
// not linked together in any way yet.
log("Setting up connection to invite user: " + targetUsername);
createPeerConnection();
// Get access to the webcam stream and attach it to the
// "preview" box (id "local_video").
try {
webcamStream = await navigator.mediaDevices.getUserMedia(mediaConstraints);
document.getElementById("local_video").srcObject = webcamStream;
} catch(err) {
handleGetUserMediaError(err);
return;
}
// Add the tracks from the stream to the RTCPeerConnection
try {
webcamStream.getTracks().forEach(
transceiver = track => myPeerConnection.addTransceiver(track, {streams: [webcamStream]})
);
} catch(err) {
handleGetUserMediaError(err);
}
}
}
// Accept an offer to video chat. We configure our local settings,
// create our RTCPeerConnection, get and attach our local camera
// stream, then create and send an answer to the caller.
async function handleVideoOfferMsg(msg) {
targetUsername = msg.name;
// If we're not already connected, create an RTCPeerConnection
// to be linked to the caller.
log("Received video chat offer from " + targetUsername);
if (!myPeerConnection) {
createPeerConnection();
}
// We need to set the remote description to the received SDP offer
// so that our local WebRTC layer knows how to talk to the caller.
var desc = new RTCSessionDescription(msg.sdp);
// If the connection isn't stable yet, wait for it...
if (myPeerConnection.signalingState != "stable") {
log(" - But the signaling state isn't stable, so triggering rollback");
// Set the local and remove descriptions for rollback; don't proceed
// until both return.
await Promise.all([
myPeerConnection.setLocalDescription({type: "rollback"}),
myPeerConnection.setRemoteDescription(desc)
]);
return;
} else {
log (" - Setting remote description");
await myPeerConnection.setRemoteDescription(desc);
}
// Get the webcam stream if we don't already have it
if (!webcamStream) {
try {
webcamStream = await navigator.mediaDevices.getUserMedia(mediaConstraints);
} catch(err) {
handleGetUserMediaError(err);
return;
}
document.getElementById("local_video").srcObject = webcamStream;
// Add the camera stream to the RTCPeerConnection
try {
webcamStream.getTracks().forEach(
transceiver = track => myPeerConnection.addTransceiver(track, {streams: [webcamStream]})
);
} catch(err) {
handleGetUserMediaError(err);
}
}
log("---> Creating and sending answer to caller");
await myPeerConnection.setLocalDescription(await myPeerConnection.createAnswer());
sendToServer({
name: myUsername,
target: targetUsername,
type: "video-answer",
sdp: myPeerConnection.localDescription
});
}
// Responds to the "video-answer" message sent to the caller
// once the callee has decided to accept our request to talk.
async function handleVideoAnswerMsg(msg) {
log("*** Call recipient has accepted our call");
// Configure the remote description, which is the SDP payload
// in our "video-answer" message.
var desc = new RTCSessionDescription(msg.sdp);
await myPeerConnection.setRemoteDescription(desc).catch(reportError);
}
// A new ICE candidate has been received from the other peer. Call
// RTCPeerConnection.addIceCandidate() to send it along to the
// local ICE framework.
async function handleNewICECandidateMsg(msg) {
var candidate = new RTCIceCandidate(msg.candidate);
log("*** Adding received ICE candidate: " + JSON.stringify(candidate));
try {
await myPeerConnection.addIceCandidate(candidate)
} catch(err) {
reportError(err);
}
}
// Handle errors which occur when trying to access the local media
// hardware; that is, exceptions thrown by getUserMedia(). The two most
// likely scenarios are that the user has no camera and/or microphone
// or that they declined to share their equipment when prompted. If
// they simply opted not to share their media, that's not really an
// error, so we won't present a message in that situation.
function handleGetUserMediaError(e) {
log_error(e);
switch(e.name) {
case "NotFoundError":
alert("Unable to open your call because no camera and/or microphone" +
"were found.");
break;
case "SecurityError":
case "PermissionDeniedError":
// Do nothing; this is the same as the user canceling the call.
break;
default:
alert("Error opening your camera and/or microphone: " + e.message);
break;
}
// Make sure we shut down our end of the RTCPeerConnection so we're
// ready to try again.
closeVideoCall();
}
// Handles reporting errors. Currently, we just dump stuff to console but
// in a real-world application, an appropriate (and user-friendly)
// error message should be displayed.
function reportError(errMessage) {
log_error(`Error ${errMessage.name}: ${errMessage.message}`);
}
// Dispatch event: "loaded"
document.dispatchEvent(
new CustomEvent("notchat.loaded", {
detail: {},
}),
);

View File

@ -0,0 +1,39 @@
"use strict";
// Initializin of the variable for instance of asdasd
let blockchain;
function init_asdasd(asdasd) {
/* if (indexedDB instanceof IDBFactory) {
// Supports indexedDB
// Initializing of asdasd
blockchain = new asdasd(
"test",
(text, settings, previous, created) => {
let hash = "";
let nonce = 0;
do {
hash = nobleHashes.utils.bytesToHex(nobleHashes.blake3(
previous + text + created + ++nonce,
settings,
));
} while (hash.substring(0, 3) !== "000");
return { nonce, hash };
},
);
} else {
// Not supports indexed
// Show the error
document.getElementsByTagName("main")[0].innerText =
"Your browser does not support indexedDB which is used for asdasd blockchain";
} */
}
if (typeof window.asdasd === "function") (() => init_asdasd(asdasd))();
else {document.addEventListener("asdasd.initialized", (e) =>
init_asdasd(e.asdasd));}

View File

@ -0,0 +1,43 @@
<?php
namespace mirzaev\notchat;
use OpenSwoole\Server,
OpenSwoole\WebSocket\Server as websocket,
OpenSwoole\Http\Request,
OpenSwoole\WebSocket\Frame,
OpenSwoole\Constant;
$server = new websocket("0.0.0.0", 2024, Server::POOL_MODE, Constant::SOCK_TCP | Constant::SSL);
$server->set([
'ssl_cert_file' => '/etc/letsencrypt/live/mirzaev.sexy/fullchain.pem',
'ssl_key_file' => '/etc/letsencrypt/live/mirzaev.sexy/privkey.pem'
]);
$server->on("Start", function (Server $server) {
echo "OpenSwoole WebSocket Server is started at http://127.0.0.1:2024\n";
});
$server->on('Open', function (Server $server, Request $request) {
echo "connection open: {$request->fd}\n";
$server->tick(1000, function () use ($server, $request) {
$server->push($request->fd, json_encode(["hello", time()]));
});
});
$server->on('Message', function (Server $server, Frame $frame) {
echo "received message: {$frame->data}\n";
$server->push($frame->fd, json_encode(["hello", time()]));
});
$server->on('Close', function (Server $server, int $fd) {
echo "connection close: {$fd}\n";
});
$server->on('Disconnect', function (Server $server, int $fd) {
echo "connection disconnect: {$fd}\n";
});
$server->start();

View File

@ -0,0 +1,184 @@
<?php
declare(strict_types=1);
namespace mirzaev\notchat\views;
// Framework for PHP
use mirzaev\minimal\controller;
// Templater of views
use Twig\Loader\FilesystemLoader,
Twig\Environment as twig;
// Built-in libraries
use ArrayAccess;
/**
* Templater core
*
* @package mirzaev\notchat\views
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/
final class templater extends controller implements ArrayAccess
{
/**
* Registry of global variables of view
*/
public array $variables = [];
/**
* Instance of twig templater
*/
readonly public twig $twig;
/**
* Constructor of an instance
*/
public function __construct()
{
// Initializing of an instance of twig
$this->twig = new twig(new FilesystemLoader(VIEWS));
// Initializing of global variables
$this->twig->addGlobal('theme', 'default');
$this->twig->addGlobal('server', $_SERVER);
}
/**
* Render a HTML-document
*
* @param string $file Related path to a HTML-document
* @param ?array $variables Registry of variables to push into registry of global variables
*
* @return ?string HTML-document
*/
public function render(string $file, ?array $variables = null): ?string
{
// Generation and exit (success)
return $this->twig->render('themes' . DIRECTORY_SEPARATOR . $this->twig->getGlobals()['theme'] . DIRECTORY_SEPARATOR . $file, $this->twig->mergeGlobals($variables ?? []));
}
/**
* Write
*
* Write a variable into registry of global variables
*
* @param string $name Name of the variable
* @param mixed $value Value of the variable
*
* @return void
*/
public function __set(string $name, mixed $value = null): void
{
// Write the variable and exit (success)
$this->variables[$name] = $value;
}
/**
* Read
*
* Read a variable from registry of global variables
*
* @param string $name Name of the variable
*
* @return mixed Content of the variable, if they are found
*/
public function __get(string $name): mixed
{
// Read the variable and exit (success)
return $this->variables[$name];
}
/**
* Delete
*
* Delete a variable from the registry of global variables
*
* @param string $name Name of the variable
*
* @return void
*/
public function __unset(string $name): void
{
// Delete the variable and exit (success)
unset($this->variables[$name]);
}
/**
* Check of initialization
*
* Check of initialization in registry of global variables
*
* @param string $name Name of the variable
*
* @return bool The variable is initialized?
*/
public function __isset(string $name): bool
{
// Check of initialization of the variable and exit (success)
return isset($this->variables[$name]);
}
/**
* Write
*
* Write a variable into registry of global variables
*
* @param mixed $name Name of an offset of the variable
* @param mixed $value Value of the variable
*
* @return void
*/
public function offsetSet(mixed $name, mixed $value): void
{
// Write the variable and exit (success)
$this->variables[$name] = $value;
}
/**
* Read
*
* Read a variable from registry of global variables
*
* @param mixed $name Name of the variable
*
* @return mixed Content of the variable, if they are found
*/
public function offsetGet(mixed $name): mixed
{
// Read the variable and exit (success)
return $this->variables[$name];
}
/**
* Delete
*
* Delete a variable from the registry of global variables
*
* @param mixed $name Name of the variable
*
* @return void
*/
public function offsetUnset(mixed $name): void
{
// Delete the variable and exit (success)
unset($this->variables[$name]);
}
/**
* Check of initialization
*
* Check of initialization in registry of global variables
*
* @param mixed $name Name of the variable
*
* @return bool The variable is initialized?
*/
public function offsetExists(mixed $name): bool
{
// Check of initialization of the variable and exit (success)
return isset($this->variables[$name]);
}
}

View File

@ -0,0 +1,33 @@
<section style="--position: 1;" class="container" data-chat="1">
<div class="infobox">
<p>This is a simple chat system implemented using WebSockets. It works by sending packets of JSON back and forth
with the server.
<a href="https://github.com/mdn/samples-server/tree/master/s/webrtc-from-chat">
Check out the source</a> on Github.
</p>
<p class="mdn-disclaimer">This text and audio/video chat example is offered as-is for demonstration purposes only,
and should not be used for any other purpose.
</p>
<p>Click a username in the user list to ask them to enter a one-on-one video chat with you.</p>
<p>Enter a username: <input id="name" type="text" maxlength="12" required autocomplete="username"
inputmode="verbatim" placeholder="Username">
<input type="button" name="login" value="Log in" onclick="connect()">
</p>
</div>
<ul class="userlistbox"></ul>
<div class="chatbox"></div>
<div class="camerabox">
<video id="received_video" autoplay></video>
<video id="local_video" autoplay muted></video>
<button id="hangup-button" onclick="hangUpCall();" role="button" disabled>
Hang Up
</button>
</div>
<div class="empty-container"></div>
<div class="chat-controls">
Chat:<br />
<input id="text" type="text" name="text" size="100" maxlength="256" placeholder="Say something meaningful..."
autocomplete="off" onkeyup="handleKey(event)" disabled>
<input type="button" id="send" name="send" value="Send" onclick="handleSendButton()" disabled>
</div>
</section>

View File

@ -0,0 +1,17 @@
{% extends "/themes/default/index.html" %}
{% block css %}
{{ parent() }}
{% endblock %}
{% block main %}
{% endblock %}
{% block js %}
{{ parent() }}
<script src="/js/asdasd/libraries/noble-hashes.js" defer></script>
<script src="/js/asdasd/asdasd.js" defer></script>
<script src="/js/adapter.js" defer></script>
<script src="/js/notchat.js" defer></script>
<script src="/js/pages/chat.js" defer></script>
{% endblock %}

View File

@ -3,7 +3,7 @@
<html lang="ru"> <html lang="ru">
<head> <head>
{% use 'head.html' with title as head_title, meta as head_meta, css as head_css %} {% use '/themes/default/head.html' with title as head_title, meta as head_meta, css as head_css %}
{% block title %} {% block title %}
{{ block('head_title') }} {{ block('head_title') }}
@ -13,8 +13,8 @@
{{ block('head_meta') }} {{ block('head_meta') }}
{% endblock %} {% endblock %}
{{ block('head_css') }}
{% block css %} {% block css %}
{{ block('head_css') }}
{% endblock %} {% endblock %}
</head> </head>
@ -22,8 +22,8 @@
{% block body %} {% block body %}
{% endblock %} {% endblock %}
{% include 'js.html' %}
{% block js %} {% block js %}
{% include '/themes/default/js.html' %}
{% endblock %} {% endblock %}
</body> </body>

View File

@ -3,6 +3,12 @@
{% block body %} {% block body %}
<footer> <footer>
<div class="window" data-section="window">
</div>
<section data-section="main">
</section>
</footer> </footer>
{% endblock %} {% endblock %}

View File

@ -11,5 +11,5 @@
{% endblock %} {% endblock %}
{% block css %} {% block css %}
<link type="text/css" rel="stylesheet" href="/css/themes/default/main.css" /> <link type="text/css" rel="stylesheet" href="/css/themes/{{ theme }}/main.css" />
{% endblock %} {% endblock %}

View File

@ -3,6 +3,12 @@
{% block body %} {% block body %}
<header> <header>
<div class="window" data-section="window">
</div>
<section data-section="main">
</section>
</header> </header>
{% endblock %} {% endblock %}

View File

@ -0,0 +1,35 @@
{% extends "/themes/default/core.html" %}
{% use "/themes/default/header.html" with css as header_css, body as header, js as header_js %}
{% use "/themes/default/footer.html" with css as footer_css, body as footer, js as footer_js %}
{% block css %}
{{ parent() }}
{{ block('header_css') }}
{{ block('footer_css') }}
{% endblock %}
{% block body %}
{{ block('header') }}
<section data-section="servers">
</section>
<section data-section="chats">
</section>
<aside>
{% block aside %}
{{ aside|raw }}
{% endblock %}
</aside>
<main style="--sections: {{ sections ?? 1 }}">
{% block main %}
{{ main|raw }}
{% endblock %}
</main>
{{ block('footer') }}
{% endblock %}
{% block js %}
{{ parent() }}
{{ block('footer_js') }}
{{ block('header_js') }}
{% endblock %}