Compare commits

...

4 Commits

Author SHA1 Message Date
Ben 10a54cf6ac
Create MatrixChat entity, chat rooms for clients 2022-04-30 14:52:32 +02:00
Ben 940c7bed6e
Start implementing matrix chat integration
Implement auto-login for element-web
2022-04-30 14:52:25 +02:00
Ben 33ca2c93db
Add element-web and nextcloud proxy on one origin
Note: continue to use http://localhost:8080 after run.sh
2022-04-30 14:52:24 +02:00
Ben 8fee4d9785
Update dependencies 2022-04-30 14:51:45 +02:00
17 changed files with 564 additions and 114 deletions

View File

@ -12,5 +12,10 @@ return [
'verb' => 'OPTIONS',
'requirements' => ['path' => '.+'],
],
[
'name' => 'ticket_api#fetch_chat',
'url' => '/api/v1/tickets/{id}/chat',
'verb' => 'GET',
],
],
];

54
composer.lock generated
View File

@ -12,12 +12,12 @@
"source": {
"type": "git",
"url": "https://gitea.rs485.network/UPschooling/matrix-php-sdk.git",
"reference": "f1c4a1d7e2c62b8fe6ad4f9cf2279a828ada1921"
"reference": "041bff317de8d37841b230fff7f19358bd449d37"
},
"require": {
"ext-json": "*",
"guzzlehttp/guzzle": "7.2.0",
"php": "^7.2.5 || ^8.0",
"php": "^7.2.5|^8",
"rappasoft/laravel-helpers": "^1.0"
},
"replace": {
@ -65,7 +65,7 @@
"keywords": [
"PhpMatrixSdk"
],
"time": "2022-02-19T16:24:57+00:00"
"time": "2022-04-25T22:19:35+00:00"
},
{
"name": "guzzlehttp/guzzle",
@ -2918,16 +2918,16 @@
},
{
"name": "symfony/console",
"version": "v5.4.7",
"version": "v5.4.8",
"source": {
"type": "git",
"url": "https://github.com/symfony/console.git",
"reference": "900275254f0a1a2afff1ab0e11abd5587a10e1d6"
"reference": "ffe3aed36c4d60da2cf1b0a1cee6b8f2e5fa881b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/console/zipball/900275254f0a1a2afff1ab0e11abd5587a10e1d6",
"reference": "900275254f0a1a2afff1ab0e11abd5587a10e1d6",
"url": "https://api.github.com/repos/symfony/console/zipball/ffe3aed36c4d60da2cf1b0a1cee6b8f2e5fa881b",
"reference": "ffe3aed36c4d60da2cf1b0a1cee6b8f2e5fa881b",
"shasum": ""
},
"require": {
@ -2997,7 +2997,7 @@
"terminal"
],
"support": {
"source": "https://github.com/symfony/console/tree/v5.4.7"
"source": "https://github.com/symfony/console/tree/v5.4.8"
},
"funding": [
{
@ -3013,7 +3013,7 @@
"type": "tidelift"
}
],
"time": "2022-03-31T17:09:19+00:00"
"time": "2022-04-12T16:02:29+00:00"
},
{
"name": "symfony/deprecation-contracts",
@ -3312,16 +3312,16 @@
},
{
"name": "symfony/finder",
"version": "v5.4.3",
"version": "v5.4.8",
"source": {
"type": "git",
"url": "https://github.com/symfony/finder.git",
"reference": "231313534dded84c7ecaa79d14bc5da4ccb69b7d"
"reference": "9b630f3427f3ebe7cd346c277a1408b00249dad9"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/finder/zipball/231313534dded84c7ecaa79d14bc5da4ccb69b7d",
"reference": "231313534dded84c7ecaa79d14bc5da4ccb69b7d",
"url": "https://api.github.com/repos/symfony/finder/zipball/9b630f3427f3ebe7cd346c277a1408b00249dad9",
"reference": "9b630f3427f3ebe7cd346c277a1408b00249dad9",
"shasum": ""
},
"require": {
@ -3355,7 +3355,7 @@
"description": "Finds files and directories via an intuitive fluent interface",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/finder/tree/v5.4.3"
"source": "https://github.com/symfony/finder/tree/v5.4.8"
},
"funding": [
{
@ -3371,7 +3371,7 @@
"type": "tidelift"
}
],
"time": "2022-01-26T16:34:36+00:00"
"time": "2022-04-15T08:07:45+00:00"
},
{
"name": "symfony/options-resolver",
@ -4080,16 +4080,16 @@
},
{
"name": "symfony/process",
"version": "v5.4.7",
"version": "v5.4.8",
"source": {
"type": "git",
"url": "https://github.com/symfony/process.git",
"reference": "38a44b2517b470a436e1c944bf9b9ba3961137fb"
"reference": "597f3fff8e3e91836bb0bd38f5718b56ddbde2f3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/process/zipball/38a44b2517b470a436e1c944bf9b9ba3961137fb",
"reference": "38a44b2517b470a436e1c944bf9b9ba3961137fb",
"url": "https://api.github.com/repos/symfony/process/zipball/597f3fff8e3e91836bb0bd38f5718b56ddbde2f3",
"reference": "597f3fff8e3e91836bb0bd38f5718b56ddbde2f3",
"shasum": ""
},
"require": {
@ -4122,7 +4122,7 @@
"description": "Executes commands in sub-processes",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/process/tree/v5.4.7"
"source": "https://github.com/symfony/process/tree/v5.4.8"
},
"funding": [
{
@ -4138,7 +4138,7 @@
"type": "tidelift"
}
],
"time": "2022-03-18T16:18:52+00:00"
"time": "2022-04-08T05:07:18+00:00"
},
{
"name": "symfony/service-contracts",
@ -4287,16 +4287,16 @@
},
{
"name": "symfony/string",
"version": "v5.4.3",
"version": "v5.4.8",
"source": {
"type": "git",
"url": "https://github.com/symfony/string.git",
"reference": "92043b7d8383e48104e411bc9434b260dbeb5a10"
"reference": "3c061a76bff6d6ea427d85e12ad1bb8ed8cd43e8"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/string/zipball/92043b7d8383e48104e411bc9434b260dbeb5a10",
"reference": "92043b7d8383e48104e411bc9434b260dbeb5a10",
"url": "https://api.github.com/repos/symfony/string/zipball/3c061a76bff6d6ea427d85e12ad1bb8ed8cd43e8",
"reference": "3c061a76bff6d6ea427d85e12ad1bb8ed8cd43e8",
"shasum": ""
},
"require": {
@ -4353,7 +4353,7 @@
"utf8"
],
"support": {
"source": "https://github.com/symfony/string/tree/v5.4.3"
"source": "https://github.com/symfony/string/tree/v5.4.8"
},
"funding": [
{
@ -4369,7 +4369,7 @@
"type": "tidelift"
}
],
"time": "2022-01-02T09:53:40+00:00"
"time": "2022-04-19T10:40:37+00:00"
},
{
"name": "theseer/tokenizer",

40
extra/element-config.json Normal file
View File

@ -0,0 +1,40 @@
{
"default_server_config": {
"m.homeserver": {
"base_url": "http://localhost:8008",
"server_name": "synapse"
},
"m.identity_server": {
}
},
"disable_custom_urls": false,
"disable_guests": true,
"disable_login_language_selector": false,
"disable_3pid_login": false,
"brand": "Element",
"integrations_ui_url": "",
"integrations_rest_url": "",
"integrations_widgets_urls": [],
"bug_report_endpoint_url": "https://element.io/bugreports/submit",
"uisi_autorageshake_app": "element-auto-uisi",
"defaultCountryCode": "DE",
"showLabsSettings": false,
"features": { },
"default_federate": true,
"default_theme": "light",
"roomDirectory": {
"servers": [
]
},
"piwik": {
},
"enable_presence_by_hs_url": {
},
"settingDefaults": {
"breadcrumbs": true
},
"jitsi": {
"preferredDomain": "meet.element.io"
},
"map_style_url": "https://api.maptiler.com/maps/streets/style.json?key=fU3vlMsMn4Jb6dnEIFsx"
}

View File

@ -0,0 +1,70 @@
server {
listen 8080;
listen [::]:8080;
server_name localhost;
root /var/empty;
index index.html;
log_not_found on;
access_log /dev/stderr combined;
error_log /dev/stderr info;
location /upschooling/element-web {
rewrite ^/upschooling/element-web/(.*)$ /$1 break;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass "http://127.0.0.1:8082";
}
location /.well-known/matrix {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods GET;
default_type application/json;
# TODO: Add missing matrix well-known files
proxy_set_header Host localhost:8008;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_redirect http://localhost:8008/.well-known/matrix http://localhost:8080/.well-known/matrix;
proxy_pass "http://127.0.0.1:8008$uri";
}
location / {
proxy_set_header Host localhost:8080;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_redirect off;
proxy_pass "http://127.0.0.1:80$uri";
}
}
server {
listen 8082;
listen [::]:8082;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
set_real_ip_from 127.0.0.1;
set_real_ip_from ::1;
# Set no-cache for the version, config and index.html
# so that browsers always check for a new copy of Element Web.
# NB http://your-domain/ and http://your-domain/? are also covered by this
location = /index.html {
add_header Cache-Control "no-cache";
}
location = /version {
add_header Cache-Control "no-cache";
}
# covers config.json and config.hostname.json requests as it is prefix.
location /config {
add_header Cache-Control "no-cache";
}
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
}

View File

@ -3,6 +3,7 @@
namespace OCA\UPschooling\Controller;
use Closure;
use OCA\UPschooling\Exceptions\RoomNotFoundException;
use OCA\UPschooling\Exceptions\TicketNotFoundException;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataResponse;
@ -11,9 +12,9 @@ trait Errors {
protected function handleNotFound(Closure $callback): DataResponse {
try {
return new DataResponse($callback());
} catch (TicketNotFoundException $e) {
$message = ['message' => $e->getMessage()];
return new DataResponse($message, Http::STATUS_NOT_FOUND);
} catch (TicketNotFoundException|RoomNotFoundException $e) {
$result = $e->getResult();
return new DataResponse($result->getMeta(), $result->getStatusCode());
}
}
}

View File

@ -3,25 +3,54 @@
namespace OCA\UPschooling\Controller;
use OCA\UPschooling\AppInfo\Application;
use OCA\UPschooling\Db\TicketMapper;
use OCA\UPschooling\Exceptions\RoomNotFoundException;
use OCA\UPschooling\Service\ChatService;
use OCA\UPschooling\Service\MatrixService;
use OCA\UPschooling\Service\TicketService;
use OCP\AppFramework\ApiController;
use OCP\AppFramework\Http\DataResponse;
use OCP\IRequest;
use Psr\Log\LoggerInterface;
class TicketApiController extends ApiController
{
/** @var LoggerInterface */
private $logger;
/** @var TicketService */
private $service;
private $ticketService;
/** @var MatrixService */
private $matrixService;
/** @var ChatService */
private $chatService;
/** @var TicketMapper */
private $ticketMapper;
/** @var string */
private $userId;
use Errors;
public function __construct(IRequest $request, TicketService $service, $userId)
{
public function __construct(
IRequest $request,
LoggerInterface $logger,
TicketService $ticketService,
TicketMapper $ticketMapper,
MatrixService $matrixService,
ChatService $chatService,
string $userId
) {
parent::__construct(Application::APP_ID, $request);
$this->service = $service;
$this->logger = $logger;
$this->ticketService = $ticketService;
$this->ticketMapper = $ticketMapper;
$this->matrixService = $matrixService;
$this->chatService = $chatService;
$this->userId = $userId;
}
@ -30,7 +59,7 @@ class TicketApiController extends ApiController
*/
public function index(): DataResponse
{
return new DataResponse($this->service->findAll($this->userId));
return new DataResponse($this->ticketService->findAll($this->userId));
}
/**
@ -39,7 +68,27 @@ class TicketApiController extends ApiController
public function show(int $id): DataResponse
{
return $this->handleNotFound(function () use ($id) {
return $this->service->find($id, $this->userId);
return $this->ticketService->find($id, $this->userId);
});
}
/**
* @NoAdminRequired
*/
public function fetchChat(int $id): DataResponse
{
return $this->handleNotFound(function () use ($id) {
$matrixUser = $this->ticketService->getOrCreateUser($this->userId);
$ticket = $this->ticketMapper->findForUser($id, $matrixUser);
$this->logger->debug("fetchChat found matrix data for ticket " . print_r($ticket->jsonSerialize(), true));
// returns 404 RoomNotFoundException if no room could/should be created
$chatRoom = $this->chatService->getOrCreateChatRoom($ticket);
$this->logger->debug("fetchChat got chat room " . print_r($chatRoom->jsonSerialize(), true));
return array(
'matrixChatRoom' => $chatRoom->getMatrixRoomId(),
'matrixAccessToken' => $matrixUser->getMatrixToken(),
'matrixServerUrl' => $this->matrixService->getServerUrl(),
);
});
}
@ -48,7 +97,7 @@ class TicketApiController extends ApiController
*/
public function create(string $title, string $content): DataResponse
{
return new DataResponse($this->service->create($title, $content, $this->userId));
return new DataResponse($this->ticketService->create($title, $content, $this->userId));
}
/**
@ -56,13 +105,13 @@ class TicketApiController extends ApiController
*/
public function update(int $id): DataResponse
{
return new DataResponse($this->service->assign($id, $this->userId));
return new DataResponse($this->ticketService->assign($id, $this->userId));
}
public function destroy(int $id): DataResponse
{
return $this->handleNotFound(function () use ($id) {
return $this->service->delete($id, $this->userId);
return $this->ticketService->delete($id, $this->userId);
});
}
}

63
lib/Db/ChatMapper.php Normal file
View File

@ -0,0 +1,63 @@
<?php
namespace OCA\UPschooling\Db;
use Doctrine\DBAL\Types\Type;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\Entity;
use OCP\AppFramework\Db\QBMapper;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
class ChatMapper extends QBMapper
{
public function __construct(IDBConnection $db)
{
parent::__construct($db, 'upschooling_chats', MatrixChat::class);
}
/**
* @param int $ticketId
* @return array array of Entity|MatrixChat
*/
public function findForTicket(int $ticketId): array
{
/* @var $qb IQueryBuilder */
$qb = $this->db->getQueryBuilder();
$qb->select('*')
->from('upschooling_chats')
->where($qb->expr()->eq('ticket_id', $qb->createNamedParameter($ticketId, IQueryBuilder::PARAM_INT)));
return $this->findEntities($qb);
}
/**
* @param int $ticketId
* @return Entity|MatrixChat
* @throws \OCP\AppFramework\Db\MultipleObjectsReturnedException
* @throws DoesNotExistException
*/
public function findCurrent(int $ticketId): MatrixChat
{
/* @var $qb IQueryBuilder */
$qb = $this->db->getQueryBuilder();
$qb->select('*')
->from('upschooling_chats')
->where(
$qb->expr()->eq('ticket_id', $qb->createNamedParameter($ticketId, IQueryBuilder::PARAM_INT)),
$qb->expr()->isNull('end_date')
);
return $this->findEntity($qb);
}
/**
* @param \DateTime $dateTime
* @return mixed The database representation of the datetime with timezone.
* @throws \Doctrine\DBAL\Exception
* @throws \Doctrine\DBAL\Types\ConversionException
*/
public function convertDateTimeTz(\DateTime $dateTime)
{
$dateTimeTzType = Type::getType("datetimetz");
return $dateTimeTzType->convertToDatabaseValue($dateTime, $this->db->getDatabasePlatform());
}
}

29
lib/Db/MatrixChat.php Normal file
View File

@ -0,0 +1,29 @@
<?php
namespace OCA\UPschooling\Db;
use JsonSerializable;
use OCP\AppFramework\Db\Entity;
class MatrixChat extends Entity implements JsonSerializable
{
protected $ticketId;
protected $matrixRoomId;
protected $matrixHelperUser;
protected $dateStart;
protected $dateEnd;
protected $version;
public function jsonSerialize(): array
{
return [
'id' => $this->id,
'ticketId' => $this->ticketId,
'matrixRoomId' => $this->matrixRoomId,
'matrixHelperUser' => $this->matrixHelperUser,
'dateStart' => $this->dateStart,
'dateEnd' => $this->dateEnd,
'version' => $this->version,
];
}
}

View File

@ -10,12 +10,13 @@ class MatrixUser extends Entity implements JsonSerializable {
protected $matrixUser;
protected $matrixToken;
public function jsonSerialize(): array {
public function jsonSerialize(): array
{
return [
'id' => $this->id,
'userId' => $this->userId,
'matrixUser' => $this->matrixUser,
'matrixToken' => $this->matrixToken,
'userId' => $this->userId,
'matrixUser' => $this->matrixUser,
'matrixToken' => $this->matrixToken,
];
}
}

View File

@ -55,30 +55,61 @@ class Version000000Date20210918151800 extends SimpleMigrationStep {
$table->addIndex(['matrix_control_room'], 'upschooling_mx_room_id_idx');
}
if (!$schema->hasTable('upschooling_users')) {
$table = $schema->createTable('upschooling_users');
$table->addColumn('id', 'integer', [
'autoincrement' => true,
'notnull' => true,
]);
$table->addColumn('user_id', 'string', [
'notnull' => true,
'length' => 64,
]);
$table->addColumn('matrix_user', 'string', [
'notnull' => true,
'length' => 200,
]);
$table->addColumn('matrix_token', 'string', [
'notnull' => true,
'length' => 200,
]);
if (!$schema->hasTable('upschooling_users')) {
$table = $schema->createTable('upschooling_users');
$table->addColumn('id', 'integer', [
'autoincrement' => true,
'notnull' => true,
]);
$table->addColumn('user_id', 'string', [
'notnull' => true,
'length' => 64,
]);
$table->addColumn('matrix_user', 'string', [
'notnull' => true,
'length' => 200,
]);
$table->addColumn('matrix_token', 'string', [
'notnull' => true,
'length' => 200,
]);
$table->setPrimaryKey(['id']);
$table->addUniqueConstraint(['user_id'], 'upschooling_mx_user_nc_uniq');
$table->addUniqueConstraint(['matrix_user'], 'upschooling_mx_user_mx_uniq');
$table->addForeignKeyConstraint('users', ['user_id'], ['uid'], [], 'upschooling_mx_user_nc_fk');
}
$table->setPrimaryKey(['id']);
$table->addUniqueConstraint(['user_id'], 'upschooling_mx_user_nc_uniq');
$table->addUniqueConstraint(['matrix_user'], 'upschooling_mx_user_mx_uniq');
$table->addForeignKeyConstraint('users', ['user_id'], ['uid'], [], 'upschooling_mx_user_nc_fk');
}
if (!$schema->hasTable('upschooling_chats')) {
$table = $schema->createTable('upschooling_chats');
$table->addColumn('id', 'integer', [
'autoincrement' => true,
'notnull' => true,
]);
$table->addColumn('ticket_id', 'integer', [
'notnull' => true,
]);
$table->addColumn('matrix_room_id', 'string', [
'notnull' => true,
'length' => 200,
]);
$table->addColumn('matrix_helper_user', 'string', [
'notnull' => true,
'length' => 200,
]);
$table->addColumn('date_start', 'datetimetz', [
'notnull' => true,
]);
$table->addColumn('date_end', 'datetimetz', [
'notnull' => false,
]);
$table->addColumn('version', 'integer', [
'notnull' => true,
]);
$table->setPrimaryKey(['id']);
$table->addForeignKeyConstraint('upschooling_tickets', ['ticket_id'], ['id'], [], 'upschooling_tckt_id_fk');
}
return $schema;
}
}

View File

@ -0,0 +1,62 @@
<?php
namespace OCA\UPschooling\Service;
use Aryess\PhpMatrixSdk\Room;
use OCA\UPschooling\Db\ChatMapper;
use OCA\UPschooling\Db\MatrixChat;
use OCA\UPschooling\Db\MatrixTicket;
use OCA\UPschooling\Db\TicketMapper;
use OCA\UPschooling\Exceptions\RoomNotFoundException;
use OCP\AppFramework\Db\DoesNotExistException;
use Psr\Log\LoggerInterface;
class ChatService
{
/** @var ChatMapper */
private $chatMapper;
/** @var MatrixService */
private $matrixService;
/** @var LoggerInterface */
private $logger;
public function __construct(ChatMapper $chatMapper, MatrixService $matrixService, LoggerInterface $logger)
{
$this->chatMapper = $chatMapper;
$this->matrixService = $matrixService;
$this->logger = $logger;
}
/**
* @param $ticket MatrixTicket Support ticket
* @throws RoomNotFoundException
*/
public function getOrCreateChatRoom(MatrixTicket $ticket): MatrixChat
{
try {
return $this->chatMapper->findCurrent($ticket->getId());
} catch (DoesNotExistException $e) {
if ($ticket->getMatrixHelperUser() == null) {
$this->logger->debug("No helper assigned to ticket " . $ticket->getId() . ". Not creating chat room");
throw new RoomNotFoundException();
}
$this->logger->debug("Chat room for ticket " . $ticket->getId() . " does not exist. Creating room..");
$roomId = $this->matrixService->createRoom();
$startDate = new \DateTime('now', new \DateTimeZone("utc"));
$matrixChat = new MatrixChat();
$matrixChat->setTicketId($ticket->getId());
$matrixChat->setMatrixRoomId($roomId);
$matrixChat->setMatrixHelperUser($ticket->getMatrixHelperUser());
$matrixChat->setDateStart($this->chatMapper->convertDateTimeTz($startDate));
$matrixChat->setVersion(1);
$this->matrixService->inviteUser($roomId, $ticket->getMatrixHelperUser());
$this->matrixService->inviteUser($roomId, $ticket->getMatrixAssistedUser());
return $this->chatMapper->insert($matrixChat);
}
}
}

View File

@ -56,7 +56,7 @@ class MatrixService
);
$this->serverUrl = $this->config->getSystemValueString(
"upschooling.matrix_server_url",
"http://synapse:8008"
"http://localhost:8008"
);
$this->server = $this->config->getSystemValueString(
"upschooling.matrix_server",
@ -216,6 +216,14 @@ class MatrixService
return $roomId;
}
/**
* @return string the public matrix server url.
*/
public function getServerUrl(): string
{
return $this->serverUrl;
}
private function checkRateLimit()
{
$fullSuperuserId = "@" . $this->superuser . ":" . $this->server;
@ -247,4 +255,10 @@ class MatrixService
$this->logger->debug("No ratelimiting for " . $this->superuser);
}
}
public function inviteUser(string $roomId, string $matrixUserId)
{
$room = $this->client->joinRoom($roomId);
$room->inviteUser($matrixUserId);
}
}

View File

@ -15,6 +15,7 @@ use OCA\UPschooling\Exceptions\TicketNotFoundException;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\IUserManager;
use Psr\Log\LoggerInterface;
class TicketService {
@ -30,16 +31,21 @@ class TicketService {
/** @var UserMapper */
private $userMapper;
/** @var LoggerInterface */
private $logger;
public function __construct(
IUserManager $userManager,
MatrixService $matrix,
TicketMapper $ticketMapper,
UserMapper $userMapper
UserMapper $userMapper,
LoggerInterface $logger
) {
$this->userManager = $userManager;
$this->matrix = $matrix;
$this->ticketMapper = $ticketMapper;
$this->userMapper = $userMapper;
$this->logger = $logger;
}
public function findAll(string $userId): array {
@ -83,6 +89,7 @@ class TicketService {
}
public function assign($id, $userId): array{
$this->logger->debug("Assigning $userId to ticket $id..");
$matrixUser = $this->getOrCreateUser($userId);
$ticket = $this->ticketMapper->findTicket($id);
$roomID = $ticket->getMatrixControlRoom();
@ -104,7 +111,7 @@ class TicketService {
}
/**
* matrixTicketContent has all the syncronized data
* matrixTicketContent has all the synchronized data
* @param MatrixTicket $ticket the database object.
* @return array a JSON serializable representation of the resolved ticket, for the frontend.
*/
@ -144,7 +151,7 @@ class TicketService {
* @throws MultipleObjectsReturnedException
* @throws \OCP\DB\Exception
*/
private function getOrCreateUser(string $userId): MatrixUser
public function getOrCreateUser(string $userId): MatrixUser
{
try {
return $this->userMapper->find($userId);

59
package-lock.json generated
View File

@ -2993,9 +2993,9 @@
}
},
"node_modules/async": {
"version": "2.6.3",
"resolved": "https://registry.npmjs.org/async/-/async-2.6.3.tgz",
"integrity": "sha512-zflvls11DCy+dQWzTW2dzuilv8Z5X/pjfmZOWba6TNIVDm+2UDaJmXSOXlasHKfNBs8oo3M0aT50fDEWfKZjXg==",
"version": "2.6.4",
"resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz",
"integrity": "sha512-mzo5dfJYwAn29PeiJ0zvwTo04zj8HDJj0Mn8TD7sno7q12prdbnasKJHhkm2c1LgrhlJ0teaea8860oxi51mGA==",
"dev": true,
"peer": true,
"dependencies": {
@ -5907,21 +5907,6 @@
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
"integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8="
},
"node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"optional": true,
"os": [
"darwin"
],
"peer": true,
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/function-bind": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
@ -7708,9 +7693,9 @@
}
},
"node_modules/minimist": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
"integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw=="
"version": "1.2.6",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz",
"integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q=="
},
"node_modules/minimist-options": {
"version": "4.1.0",
@ -7803,9 +7788,9 @@
"peer": true
},
"node_modules/node-forge": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.2.1.tgz",
"integrity": "sha512-Fcvtbb+zBcZXbTTVwqGA5W+MKBj56UjVRevvchv5XrcyXbmNdesfZL37nlcWOfpgHhgmxApw3tQbTr4CqNmX4w==",
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.1.tgz",
"integrity": "sha512-dPEtOeMvF9VMcYV/1Wb8CPoVAXtp6MKMlcbAt4ddqmGqUJ6fQZFXkNZNkNlfevtNkGtaSoXf/vNNNSvgrdXwtA==",
"dev": true,
"peer": true,
"engines": {
@ -13890,9 +13875,9 @@
"peer": true
},
"async": {
"version": "2.6.3",
"resolved": "https://registry.npmjs.org/async/-/async-2.6.3.tgz",
"integrity": "sha512-zflvls11DCy+dQWzTW2dzuilv8Z5X/pjfmZOWba6TNIVDm+2UDaJmXSOXlasHKfNBs8oo3M0aT50fDEWfKZjXg==",
"version": "2.6.4",
"resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz",
"integrity": "sha512-mzo5dfJYwAn29PeiJ0zvwTo04zj8HDJj0Mn8TD7sno7q12prdbnasKJHhkm2c1LgrhlJ0teaea8860oxi51mGA==",
"dev": true,
"peer": true,
"requires": {
@ -16200,14 +16185,6 @@
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
"integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8="
},
"fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"optional": true,
"peer": true
},
"function-bind": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
@ -17551,9 +17528,9 @@
}
},
"minimist": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
"integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw=="
"version": "1.2.6",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz",
"integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q=="
},
"minimist-options": {
"version": "4.1.0",
@ -17628,9 +17605,9 @@
"peer": true
},
"node-forge": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.2.1.tgz",
"integrity": "sha512-Fcvtbb+zBcZXbTTVwqGA5W+MKBj56UjVRevvchv5XrcyXbmNdesfZL37nlcWOfpgHhgmxApw3tQbTr4CqNmX4w==",
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.1.tgz",
"integrity": "sha512-dPEtOeMvF9VMcYV/1Wb8CPoVAXtp6MKMlcbAt4ddqmGqUJ6fQZFXkNZNkNlfevtNkGtaSoXf/vNNNSvgrdXwtA==",
"dev": true,
"peer": true
},

19
run.sh
View File

@ -20,6 +20,10 @@ if $CONTAINER_RUNTIME inspect --type container synapse 1> /dev/null; then
$CONTAINER_RUNTIME rm -f synapse
sleep 0.5
fi
if $CONTAINER_RUNTIME inspect --type container elementweb 1> /dev/null; then
$CONTAINER_RUNTIME rm -f elementweb
sleep 0.5
fi
if $CONTAINER_RUNTIME inspect --type container nextcloud 1> /dev/null; then
$CONTAINER_RUNTIME rm -f nextcloud
fi
@ -30,7 +34,9 @@ fi
$CONTAINER_RUNTIME run -d \
--name=nextcloud \
-p 8080:80 \
-p 8080:8080 \
-p 8081:80 \
-p 8082:8082 \
-p 8008:8008 \
-v "$DIR:/var/www/html/custom_apps/upschooling" \
--add-host "synapse:127.0.0.1" \
@ -128,5 +134,16 @@ else
echo -e "Matrix user @upschooling:synapse created. \e[1;38;5;2mOK\033[0m"
fi
$CONTAINER_RUNTIME run -d \
--log-driver "k8s-file" \
--name=elementweb \
"--network=container:$($CONTAINER_RUNTIME inspect --format "{{.Id}}" nextcloud)" \
-v "$DIR/extra/element-web-nginx.conf:/etc/nginx/conf.d/default.conf" \
-v "$DIR/extra/element-config.json:/app/config.json" \
--hostname elementweb \
docker.io/vectorim/element-web
echo -e "Element Web has started. \e[1;38;5;2mOK\033[0m"
# for nextcloud logs use $CONTAINER_RUNTIME exec --user 33 -it nextcloud ./occ log:watch
# for webserver logs use $CONTAINER_RUNTIME logs -f elementweb

View File

@ -64,7 +64,7 @@ export default {
}).catch(console.error)
axios.get(
'api/v1/tickets/1',
{ headers: { 'Content-Type': 'application/json', Accept: 'application/json' } },
{ headers: { Accept: 'application/json' } },
).catch(console.error)
axios.put(
'api/v1/tickets/1',

View File

@ -18,12 +18,19 @@
{{ t('upschooling', 'Speichern') }}
</button>
<hr>
<div class="placeholder" />
<iframe id="element-web-frame"
src="about:blank"
title="Embedded Element Web"
width="100%"
height="400" />
</div>
</template>
<script>
import KeyValueTable from './components/KeyValueTable'
import axios from '@nextcloud/axios'
export default {
name: 'Ticket',
components: { KeyValueTable },
@ -40,6 +47,31 @@ export default {
description: this.ticket.description,
}
},
mounted() {
/** @type {HTMLIFrameElement} */
const elementWebFrame = document.getElementById('element-web-frame')
this.loadChat(elementWebFrame).catch((err) => {
if (err.message === 'Room not found') {
console.debug('No chat room assigned to ticket')
elementWebFrame.src = 'about:blank'
elementWebFrame.onload = function() {
const textElement = elementWebFrame.contentDocument.createElement('strong')
textElement.innerText = 'Textchat nicht verfügbar. Es ist noch kein Helfer zugewiesen.'
elementWebFrame.contentDocument.body.appendChild(textElement)
elementWebFrame.onload = undefined
}
} else {
console.error('Could not load Element Web in iframe', err)
elementWebFrame.src = 'about:blank'
elementWebFrame.onload = function() {
const textElement = elementWebFrame.contentDocument.createElement('strong')
textElement.innerText = 'Element Web konnte nicht geladen werden.'
elementWebFrame.contentDocument.body.appendChild(textElement)
elementWebFrame.onload = undefined
}
}
})
},
methods: {
toLocaleDate(timestamp) {
const date = new Date(timestamp)
@ -53,6 +85,58 @@ export default {
back() {
this.$emit('show-ticket-list')
},
async loadChat(elementWebFrame) {
const matrixInfoResponse = await axios.get(
`api/v1/tickets/${this.ticket.ticketId}/chat`,
{ headers: { Accept: 'application/json' }, validateStatus: status => status === 200 || status === 404 },
)
if (matrixInfoResponse.status === 404 && matrixInfoResponse.data.message === 'Room not found') {
throw Error(matrixInfoResponse.data.message)
}
if (matrixInfoResponse.status !== 200) {
throw Error(`Received unexpected status code ${matrixInfoResponse.status} for fetching matrix chat data`)
}
if (!matrixInfoResponse.data) {
throw Error('Did not receive any matrix chat data')
}
if (typeof matrixInfoResponse.data !== 'object') {
throw Error('Unexpected return value for fetching matrix chat data')
}
const loginPromise = new Promise(function(resolve, reject) {
const tryLogin = (elementWebFrame, matrixInfo, round) => {
if (elementWebFrame.contentWindow.mxLoginWithAccessToken === undefined) {
console.warn('Couldn\'t login in round ' + round)
setTimeout(() => {
tryLogin(elementWebFrame, matrixInfo, round + 1)
}, 1000)
} else {
elementWebFrame.contentWindow.mxLoginWithAccessToken(
matrixInfo.matrixServerUrl,
matrixInfo.matrixAccessToken,
).then(resolve).catch(reject)
}
}
elementWebFrame.onload = function() {
elementWebFrame.onload = undefined
tryLogin(elementWebFrame, matrixInfoResponse.data, 1)
}
})
// load Element Web
elementWebFrame.src = '/upschooling/element-web/'
loginPromise.then(async () => {
const matrixClient = elementWebFrame.contentWindow.mxMatrixClientPeg.get()
await matrixClient.joinRoom(matrixInfoResponse.data.matrixChatRoom)
elementWebFrame.contentWindow.mxDispatcher.dispatch({
action: 'view_room',
room_id: matrixInfoResponse.data.matrixChatRoom,
})
}).catch(console.error)
},
},
}
</script>