Compare commits

...

13 Commits

Author SHA1 Message Date
gapodo 28cdfeb205 redo emoji
ci/woodpecker/push/base Pipeline was successful Details
2023-11-20 23:02:09 +01:00
gapodo cbb340aa8d strip foroaccount 2023-11-20 17:08:45 +01:00
gapodo 4c5e744f62 build...
ci/woodpecker/push/base Pipeline was successful Details
2023-11-20 14:17:03 +01:00
gapodo 86351e336c build
ci/woodpecker/push/base Pipeline was successful Details
2023-11-20 13:56:13 +01:00
gapodo 24c6a1e22e update build 2023-11-20 13:52:23 +01:00
gapodo 2a1fd11e2d stun change
ci/woodpecker/push/base Pipeline was successful Details
2023-11-20 01:13:22 +01:00
gapodo 063fdae679 autotag
ci/woodpecker/push/base Pipeline was successful Details
2023-11-19 23:38:50 +01:00
gapodo e5551cea09 fix?
ci/woodpecker/push/base Pipeline was successful Details
2023-11-19 23:07:07 +01:00
gapodo 3ec3db37e0 ci
ci/woodpecker/push/base Pipeline failed Details
2023-11-19 23:00:03 +01:00
gapodo feb564d4a0 save all with +x as script changes them anyways 2023-11-18 20:58:15 +01:00
gapodo bde4bbf5ad build... 2023-11-18 19:25:19 +01:00
gapodo ef0813dd84 hard lock wabt (has breaking change within minor version) 2023-11-17 22:25:04 +01:00
gapodo 5b8b4d07c3 updates... 2023-11-17 21:47:09 +01:00
58 changed files with 6335 additions and 4850 deletions

1
.gitignore vendored
View File

@ -2,6 +2,7 @@
.idea/
node_modules/
.sass-cache/
.npm/
/auth/certs/
/auth/js/auth.js.map

4
.npmrc Normal file
View File

@ -0,0 +1,4 @@
audit=false
fund=false
update-notifier=false
package-lock=true

89
.woodpecker/base.yaml Normal file
View File

@ -0,0 +1,89 @@
when:
event: [push, deployment, manual, cron]
labels:
platform: linux/amd64
variables:
- &node_image 'node:14-bullseye'
- &buildx_image 'woodpeckerci/plugin-docker-buildx:2.2.1'
- &platforms 'linux/amd64'
- &dockerfile 'docker/Dockerfile.ci'
steps:
prepare-npm:
image: *node_image
secrets:
- npmconf
commands:
- git config --add safe.directory '*'
- if [ "$${NPMCONF:-}" != "" ]; then echo "$${NPMCONF}" >> "$${HOME}/.npmrc"; fi
- npm ci
- npx browserslist@latest --update-db
build-npm:
image: *node_image
commands:
- bash ./scripts/build.sh web rel
build-docker-next:
image: *buildx_image
pull: true
settings:
platforms: *platforms
dockerfile: *dockerfile
context: .
registry:
from_secret: registry_domain
repo:
from_secret: target_image_name
password:
from_secret: registry_token
username:
from_secret: registry_user
auto_tag: true
tag: [next, "next-${CI_COMMIT_SHA:0:8}"]
when:
branch: ${CI_REPO_DEFAULT_BRANCH}
event: push
build-docker-branch:
image: *buildx_image
pull: true
settings:
platforms: *platforms
dockerfile: *dockerfile
context: .
registry:
from_secret: registry_domain
repo:
from_secret: target_image_name
password:
from_secret: registry_token
username:
from_secret: registry_user
auto_tag: true
tag: ["${CI_COMMIT_BRANCH}", "${CI_COMMIT_BRANCH}-${CI_COMMIT_SHA:0:8}"]
when:
event: [push, manual]
build-docker-tag:
image: *buildx_image
pull: true
settings:
platforms: *platforms
dockerfile: *dockerfile
context: .
registry:
from_secret: registry_domain
repo:
from_secret: target_image_name
password:
from_secret: registry_token
username:
from_secret: registry_user
auto_tag: true
tag: [latest, "${CI_COMMIT_TAG}", "tag-${CI_COMMIT_SHA:0:8}"]
when:
event: [tag]

View File

@ -4,14 +4,12 @@ export default api => {
[
"@babel/preset-env",
{
"corejs": {"version": 3},
"corejs": {"version": '3.33', "proposals": false},
"useBuiltIns": "usage",
"targets": {
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1",
"ie": "11"
"edge": "111",
"firefox": "100",
"chrome": "109"
}
}
]

0
client/generate_packed.sh Normal file → Executable file
View File

17
docker/Dockerfile.base Normal file
View File

@ -0,0 +1,17 @@
FROM nginx:mainline-alpine
COPY ./docker/default.conf /etc/nginx/conf.d/default.conf
COPY ./docker/nginx.conf /etc/nginx/nginx.conf
COPY ./docker/entrypoint.sh /
RUN apk update --no-cache && apk upgrade --no-cache \
&& apk add --no-cache openssl tzdata \
&& mkdir -p /var/www/TeaWeb /etc/ssl/certs \
&& chmod +x /entrypoint.sh
ENV TZ="Europe/Berlin"
EXPOSE 80 443
ENTRYPOINT ["/entrypoint.sh"]
CMD ["nginx", "-g", "daemon off;"]

19
docker/Dockerfile.ci Normal file
View File

@ -0,0 +1,19 @@
FROM nginx:mainline-alpine
COPY ./docker/default.conf /etc/nginx/conf.d/default.conf
COPY ./docker/nginx.conf /etc/nginx/nginx.conf
COPY ./docker/entrypoint.sh /
RUN apk update --no-cache && apk upgrade --no-cache \
&& apk add --no-cache openssl tzdata \
&& mkdir -p /var/www/TeaWeb /etc/ssl/certs \
&& chmod +x /entrypoint.sh
ENV TZ="Europe/Berlin"
EXPOSE 80 443
ENTRYPOINT ["/entrypoint.sh"]
CMD ["nginx", "-g", "daemon off;"]
COPY ./dist/ /var/www/TeaWeb/

36
docker/default.conf Normal file
View File

@ -0,0 +1,36 @@
server {
listen 80;
server_name _;
return 301 https://$host$request_uri;
}
server {
listen 443 default_server ssl http2;
server_name _;
ssl_ciphers EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:TLS-CHACHA20-POLY1305-SHA256:TLS-AES-256-GCM-SHA384:TLS-AES-128-GCM-SHA256;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_dhparam /etc/ssl/certs/dhparam.pem;
ssl_ecdh_curve secp384r1;
ssl_certificate /etc/ssl/certs/tea_bundle.crt;
ssl_certificate_key /etc/ssl/certs/tea.key;
ssl_session_cache shared:MozSSL:10m;
ssl_session_timeout 1d;
ssl_prefer_server_ciphers on;
location / {
root /var/www/TeaWeb;
index index.html;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
gzip off;
}

29
docker/entrypoint.sh Executable file
View File

@ -0,0 +1,29 @@
#!/usr/bin/env sh
set -e
gen_self_signed() {
echo "[WRN] No certificates found, generating self signed cert with key"
openssl req -x509 -nodes -days 1780 -newkey rsa:4096 \
-keyout /etc/ssl/certs/tea.key \
-out /etc/ssl/certs/tea_bundle.crt \
-subj "/C=DE/ST=Berlin/L=Germany/O=TeaSpeak/OU=TeaWeb/CN=localhost/emailAddress=noreply@teaspeak.de"
}
gen_diffie_hellman() {
echo "[INF] No Diffie-Hellman pem found, generating new with 2048 byte"
openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048
}
if [ "$1" = "nginx" ]; then
if [ ! -f /etc/ssl/certs/tea.key ] && [ ! -f /etc/ssl/certs/tea_bundle.crt ]; then
gen_self_signed
elif [ ! -f /etc/ssl/certs/tea.key ] || [ ! -f /etc/ssl/certs/tea_bundle.crt ]; then
echo "[ERR] Only found a key or crt-bundle file but both files are REQUIRED!"
exit 1
fi
if [ ! -f /etc/ssl/certs/dhparam.pem ]; then
gen_diffie_hellman
fi
fi
exec "$@"

32
docker/nginx.conf Normal file
View File

@ -0,0 +1,32 @@
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
server_tokens off;
keepalive_timeout 75;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}

View File

@ -2,32 +2,32 @@ import "core-js/stable";
import "./polifill";
import "./css";
import {ApplicationLoader} from "./loader/loader";
import {getUrlParameter} from "./loader/Utils";
import { ApplicationLoader } from "./loader/loader";
import { getUrlParameter } from "./loader/Utils";
/* let the loader register himself at the window first */
const target = getUrlParameter("loader-target") || "app";
console.info("Loading app with loader \"%s\"", target);
let appLoader: ApplicationLoader;
if(target === "empty") {
if (target === "empty") {
appLoader = new (require("./targets/empty").default);
} else if(target === "manifest") {
} else if (target === "manifest") {
appLoader = new (require("./targets/maifest-target").default);
} else {
appLoader = new (require("./targets/app").default);
}
setTimeout(() => appLoader.execute(), 0);
export {};
export { };
if(__build.target === "client") {
if (__build.target === "client") {
/* do this so we don't get a react dev tools warning within the client */
if(!('__REACT_DEVTOOLS_GLOBAL_HOOK__' in window)) {
window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {};
if (!('__REACT_DEVTOOLS_GLOBAL_HOOK__' in window)) {
(window as Window).__REACT_DEVTOOLS_GLOBAL_HOOK__ = {};
}
window.__REACT_DEVTOOLS_GLOBAL_HOOK__.inject = function () {};
window.__REACT_DEVTOOLS_GLOBAL_HOOK__.inject = function () { };
}
/* Hello World message */
@ -89,7 +89,7 @@ if(__build.target === "client") {
].join(";");
const display_detect = /./;
display_detect.toString = function() { print_security(); return ""; };
display_detect.toString = function () { print_security(); return ""; };
clog("%cLovely to see you using and debugging the TeaSpeak-Web client.", css);
clog("%cIf you have some good ideas or already done some incredible changes,", css);

7046
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -17,74 +17,74 @@
"author": "TeaSpeak (WolverinDEV)",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.10.4",
"@babel/plugin-transform-runtime": "^7.10.4",
"@babel/preset-env": "^7.10.4",
"@babel/core": "^7.23.3",
"@babel/plugin-transform-runtime": "^7.23.3",
"@babel/preset-env": "^7.23.3",
"@google-cloud/translate": "^5.3.0",
"@svgr/webpack": "^5.5.0",
"@types/dompurify": "^2.0.1",
"@types/ejs": "^3.0.2",
"@types/emoji-mart": "^3.0.2",
"@types/emscripten": "^1.38.0",
"@types/fs-extra": "^8.0.1",
"@types/dompurify": "^2.4.0",
"@types/ejs": "^3.1.5",
"@types/emscripten": "^1.39.10",
"@types/fs-extra": "^8.1.5",
"@types/html-minifier": "^3.5.3",
"@types/jquery": "^3.3.34",
"@types/jquery": "^3.5.27",
"@types/jsrender": "^1.0.5",
"@types/lodash": "^4.14.149",
"@types/lodash": "^4.14.201",
"@types/moment": "^2.13.0",
"@types/node": "^12.7.2",
"@types/react-color": "^3.0.4",
"@types/react-dom": "^16.9.5",
"@types/react-grid-layout": "^1.1.1",
"@types/remarkable": "^1.7.4",
"@types/sdp-transform": "^2.4.4",
"@types/sha256": "^0.2.0",
"@types/twemoji": "^12.1.1",
"@types/node": "^12.20.55",
"@types/react": "^16.14.51",
"@types/react-color": "^3.0.10",
"@types/react-dom": "^16.9.22",
"@types/react-grid-layout": "^1.3.5",
"@types/remarkable": "^1.7.6",
"@types/sdp-transform": "^2.4.9",
"@types/sha256": "^0.2.2",
"@types/twemoji": "^12.1.2",
"@types/websocket": "0.0.40",
"@types/xml-parser": "^1.2.29",
"@wasm-tool/wasm-pack-plugin": "^1.3.1",
"autoprefixer": "^10.2.5",
"babel-loader": "^8.1.0",
"circular-dependency-plugin": "^5.2.0",
"clean-css": "^4.2.1",
"@types/xml-parser": "^1.2.33",
"@wasm-tool/wasm-pack-plugin": "^1.7.0",
"autoprefixer": "^10.4.16",
"babel-loader": "^8.3.0",
"circular-dependency-plugin": "^5.2.2",
"clean-css": "^4.2.4",
"clean-webpack-plugin": "^3.0.0",
"copy-webpack-plugin": "^8.0.0",
"copy-webpack-plugin": "^8.1.1",
"css-loader": "^3.6.0",
"css-minimizer-webpack-plugin": "^1.3.0",
"exports-loader": "^0.7.0",
"fast-xml-parser": "^3.17.4",
"file-loader": "^6.0.0",
"fast-xml-parser": "^3.21.1",
"file-loader": "^6.2.0",
"fs-extra": "latest",
"gulp": "^4.0.2",
"html-loader": "^1.0.0",
"html-loader": "^1.3.2",
"html-minifier": "^4.0.0",
"html-webpack-inline-source-plugin": "0.0.10",
"html-webpack-plugin": "^5.3.1",
"html-webpack-plugin": "^5.5.3",
"inline-chunks-html-webpack-plugin": "^1.3.1",
"mime-types": "^2.1.24",
"mini-css-extract-plugin": "^1.3.9",
"mkdirp": "^0.5.1",
"mime-types": "^2.1.35",
"mini-css-extract-plugin": "^1.6.2",
"mkdirp": "^0.5.6",
"node-sass": "^4.14.1",
"postcss": "^8.3.0",
"postcss-loader": "^5.2.0",
"potpack": "^1.0.1",
"raw-loader": "^4.0.0",
"postcss": "^8.4.31",
"postcss-loader": "^5.3.0",
"potpack": "^1.0.2",
"raw-loader": "^4.0.2",
"sass": "1.22.10",
"sass-loader": "^8.0.2",
"sha256": "^0.2.0",
"style-loader": "^1.1.3",
"style-loader": "^1.3.0",
"svg-inline-loader": "^0.8.2",
"terser": "^4.2.1",
"terser": "^4.8.1",
"terser-webpack-plugin": "4.2.3",
"ts-loader": "^6.2.2",
"ts-loader": "^8.4.0",
"tsd": "^0.13.1",
"typescript": "^4.2",
"typescript": "^4.9.5",
"url-loader": "^4.1.1",
"wabt": "^1.0.13",
"webpack": "^5.26.1",
"webpack-bundle-analyzer": "^3.6.1",
"webpack-cli": "^4.5.0",
"webpack-dev-server": "^3.11.2",
"wabt": "1.0.13",
"webpack": "^5.89.0",
"webpack-bundle-analyzer": "^3.9.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^3.11.3",
"webpack-svg-sprite-generator": "^5.0.4",
"zip-webpack-plugin": "^4.0.1"
},
@ -97,33 +97,35 @@
},
"homepage": "https://www.teaspeak.de",
"dependencies": {
"@types/crypto-js": "^4.0.1",
"@emoji-mart/data": "^1.1.2",
"@emoji-mart/react": "^1.1.1",
"@types/crypto-js": "^4.2.1",
"broadcastchannel-polyfill": "^1.0.1",
"buffer": "^6.0.3",
"crypto-browserify": "^3.12.0",
"crypto-js": "^4.0.0",
"detect-browser": "^5.2.0",
"dompurify": "^2.2.8",
"emoji-mart": "git+https://github.com/WolverinDEV/emoji-mart.git",
"emoji-regex": "^9.0.0",
"highlight.js": "^10.1.1",
"ip-regex": "^4.2.0",
"jquery": "^3.5.1",
"jsrender": "^1.0.7",
"moment": "^2.24.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-grid-layout": "^1.2.2",
"react-player": "^2.5.0",
"crypto-js": "^4.2.0",
"detect-browser": "^5.3.0",
"dompurify": "^2.4.7",
"emoji-mart": "^5.5.2",
"emoji-regex": "^9.2.2",
"highlight.js": "^10.7.3",
"ip-regex": "^4.3.0",
"jquery": "^3.7.1",
"jsrender": "^1.0.13",
"moment": "^2.29.4",
"react": "^16.14.0",
"react-dom": "^16.14.0",
"react-grid-layout": "^1.4.3",
"react-player": "^2.13.0",
"remarkable": "^2.0.1",
"resize-observer-polyfill": "git+https://github.com/albancreton/resize-observer-polyfill.git#patch-1",
"sdp-transform": "^2.14.0",
"sdp-transform": "^2.14.1",
"simple-jsonp-promise": "^1.1.0",
"stream-browserify": "^3.0.0",
"twemoji": "^13.0.0",
"twemoji": "^13.1.1",
"url-knife": "^3.1.3",
"webcrypto-liner": "^1.2.4",
"webpack-manifest-plugin": "^3.1.0",
"webcrypto-liner": "^1.4.2",
"webpack-manifest-plugin": "^3.2.0",
"webrtc-adapter": "^7.5.1"
}
}

0
scripts/build.sh Normal file → Executable file
View File

0
scripts/build_declarations.sh Normal file → Executable file
View File

45
scripts/build_in_docker.sh Executable file
View File

@ -0,0 +1,45 @@
#!/bin/bash
SCRIPT=$(realpath "$0")
SCRIPTPATH=$(dirname "$SCRIPT")
BASEPATH="$(realpath "${SCRIPTPATH}/../")"
NPM_DIR="${BASEPATH}/.npm"
if [[ ! -d "${NPM_DIR}" ]]; then
mkdir "${NPM_DIR}" || exit 1
fi
if [[ "${BUILDINDOCKER:-}" != "yes" ]]; then
docker run --rm --workdir "/work" -v "${NPM_DIR}:/home/" -v "${BASEPATH}:/work" -e BUILDINDOCKER=yes node:14-bullseye /bin/bash -c 'chmod +x /work/scripts/build_in_docker.sh && /work/scripts/build_in_docker.sh'
exit
fi
## in docker
echo "adding npmrc"
cat >>"${HOME}/.npmrc" <<'EOF'
cache=/work/.npm
fund=false
EOF
echo "adding secure git dir"
git config --global --add safe.directory /work
echo "running chmods"
find "${BASEPATH}" -iname "*.sh" -exec chmod +x {} +
echo "Cleaning up old files"
"${BASEPATH}/scripts/cleanup.sh" full >/dev/null 2>&1 || exit 1
echo "Installing npm packages"
npm i || exit 1
echo "Updating browser list"
npx browserslist@latest --update-db || exit 1
echo "running build"
"${BASEPATH}/scripts/build.sh" web rel
echo "fixing perms"
chown -R 1000:1000 /work

0
scripts/cleanup.sh Normal file → Executable file
View File

0
scripts/deploy_ui_files.sh Normal file → Executable file
View File

0
scripts/helper.sh Normal file → Executable file
View File

0
scripts/install_dependencies.sh Normal file → Executable file
View File

0
scripts/travis/build.sh Normal file → Executable file
View File

0
scripts/travis/deploy_docker.sh Normal file → Executable file
View File

0
scripts/travis/deploy_github.sh Normal file → Executable file
View File

0
scripts/travis/deploy_server.sh Normal file → Executable file
View File

0
scripts/travis/properties.sh Normal file → Executable file
View File

View File

@ -3,14 +3,15 @@
:global {
.modal-body.modal-settings {
padding: 0!important;
padding: 0 !important;
display: flex!important;
flex-direction: column!important;
justify-content: stretch!important;
display: flex !important;
flex-direction: column !important;
justify-content: stretch !important;
@include user-select(none);
width: 10000em; /* allocate some space */
width: 10000em;
/* allocate some space */
.inner-container {
flex-grow: 1;
@ -23,7 +24,8 @@
flex-direction: row !important;
justify-content: stretch;
> .left, > .right {
>.left,
>.right {
display: flex;
flex-direction: column;
justify-content: stretch;
@ -38,10 +40,10 @@
.container-seperator {
height: unset !important;
background-color: #222224!important;
background-color: #222224 !important;
}
> .left {
>.left {
width: 25%;
min-width: 10em;
@ -86,7 +88,7 @@
}
}
> .right {
>.right {
width: 75%;
min-width: 12em;
@ -94,7 +96,7 @@
background-color: #2f2f35;
> .container {
>.container {
position: absolute;
top: 0;
bottom: 0;
@ -113,13 +115,15 @@
@include chat-scrollbar-horizontal();
&.general-chat, &.general-application, &.audio-sounds {
&.general-chat,
&.general-application,
&.audio-sounds {
label {
display: flex;
flex-direction: row;
justify-content: flex-start;
> * {
>* {
align-self: center;
}
@ -130,11 +134,11 @@
}
&.general-application {
> div {
>div {
margin-top: .25em;
}
> label:not(:first-child) {
>label:not(:first-child) {
margin-top: 0.25em;
}
@ -168,7 +172,8 @@
flex-direction: row;
justify-content: flex-start;
a, div {
a,
div {
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
@ -184,7 +189,7 @@
flex-direction: row;
justify-content: flex-start;
> .country {
>.country {
align-self: center;
margin-right: .3em;
}
@ -274,7 +279,7 @@
border-radius: $border_radius_middle;
> div {
>div {
align-self: center;
}
@ -282,7 +287,7 @@
background-color: #3c3d40;
}
> *:not(.spacer) {
>*:not(.spacer) {
flex-grow: 0;
flex-shrink: 1;
}
@ -333,15 +338,21 @@
}
}
&.audio-speaker, &.audio-sounds, &.identity-forum {
&.audio-speaker,
&.audio-sounds,
&.identity-forum {
flex-direction: row;
justify-content: stretch;
.left, .right, .fill {
.left,
.right,
.fill {
flex-grow: 1;
flex-shrink: 1;
width: calc(50% - .5em); /* the .5em for the padding/margin */
width: calc(50% - .5em);
/* the .5em for the padding/margin */
&.fill {
width: calc(100% - 1em);
}
@ -410,7 +421,8 @@
background-color: $color_list_background;
&.container-devices, .container-devices {
&.container-devices,
.container-devices {
flex-grow: 1;
flex-shrink: 1;
@ -451,7 +463,7 @@
border: none;
border-right: 1px solid #242527;
> .icon_em {
>.icon_em {
font-size: 2em;
opacity: 0;
}
@ -530,7 +542,7 @@
&.selected {
.container-selected {
> .icon_em {
>.icon_em {
opacity: 1;
}
@ -540,7 +552,9 @@
border-bottom: 1px solid #242527;
border-top: 1px solid #242527;
}
.container-name, .container-activity {
.container-name,
.container-activity {
margin-top: 0;
margin-bottom: 0;
@ -588,8 +602,10 @@
}
}
.right, .fill {
padding-right: .5em; /* for the sliders etc*/
.right,
.fill {
padding-right: .5em;
/* for the sliders etc*/
justify-content: flex-start;
.body {
@ -628,14 +644,14 @@
flex-direction: column;
justify-content: stretch;
> .container {
>.container {
padding: 0;
display: flex;
flex-direction: row;
justify-content: space-between;
> label {
>label {
flex-shrink: 0;
min-width: 5em;
@ -706,13 +722,14 @@
.container-activity-bar {
.bar-hider {
width: 100%!important;
width: 100% !important;
}
.thumb {
background-color: #4d4d4d!important;
background-color: #4d4d4d !important;
.tooltip {
opacity: 0!important;
opacity: 0 !important;
}
}
}
@ -785,9 +802,9 @@
background-color: transparent;
-webkit-box-shadow: inset 0 0 2px 0 rgba(0,0,0,0.25);
-moz-box-shadow: inset 0 0 2px 0 rgba(0,0,0,0.25);
box-shadow: inset 0 0 2px 0 rgba(0,0,0,0.25);
-webkit-box-shadow: inset 0 0 2px 0 rgba(0, 0, 0, 0.25);
-moz-box-shadow: inset 0 0 2px 0 rgba(0, 0, 0, 0.25);
box-shadow: inset 0 0 2px 0 rgba(0, 0, 0, 0.25);
&::-webkit-inner-spin-button,
&::-webkit-outer-spin-button {
@ -1082,11 +1099,13 @@
position: relative;
.left, .right {
.left,
.right {
flex-grow: 1;
flex-shrink: 1;
width: calc(50% - .5em); /* the .5em for the padding/margin */
width: calc(50% - .5em);
/* the .5em for the padding/margin */
display: flex;
flex-direction: column;
@ -1158,16 +1177,17 @@
background-color: #242527;
-webkit-box-shadow: inset 0 0 2px 0 rgba(0,0,0,0.75);
-moz-box-shadow: inset 0 0 2px 0 rgba(0,0,0,0.75);
box-shadow: inset 0 0 2px 0 rgba(0,0,0,0.75);
-webkit-box-shadow: inset 0 0 2px 0 rgba(0, 0, 0, 0.75);
-moz-box-shadow: inset 0 0 2px 0 rgba(0, 0, 0, 0.75);
box-shadow: inset 0 0 2px 0 rgba(0, 0, 0, 0.75);
border-bottom-right-radius: $border_radius_large;
border-top-right-radius: $border_radius_large;
}
&[value] {
overflow: visible; /* for the thumb */
overflow: visible;
/* for the thumb */
border-bottom-left-radius: $border_radius_large;
border-top-left-radius: $border_radius_large;
@ -1212,16 +1232,21 @@
}
}
-webkit-box-shadow: inset 0 0 2px 0 rgba(0,0,0,0.25);
-moz-box-shadow: inset 0 0 2px 0 rgba(0,0,0,0.25);
box-shadow: inset 0 0 2px 0 rgba(0,0,0,0.25);
-webkit-box-shadow: inset 0 0 2px 0 rgba(0, 0, 0, 0.25);
-moz-box-shadow: inset 0 0 2px 0 rgba(0, 0, 0, 0.25);
box-shadow: inset 0 0 2px 0 rgba(0, 0, 0, 0.25);
/* Permalink - use to edit and share this gradient: https://colorzilla.com/gradient-editor/#70407e+0,45407e+100 */
background: rgb(112,64,126); /* Old browsers */
background: -moz-linear-gradient(left, rgba(112,64,126,1) 0%, rgba(69,64,126,1) 100%); /* FF3.6-15 */
background: -webkit-linear-gradient(left, rgba(112,64,126,1) 0%,rgba(69,64,126,1) 100%); /* Chrome10-25,Safari5.1-6 */
background: linear-gradient(to right, rgba(112,64,126,1) 0%,rgba(69,64,126,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#70407e', endColorstr='#45407e',GradientType=1 ); /* IE6-9 */
background: rgb(112, 64, 126);
/* Old browsers */
background: -moz-linear-gradient(left, rgba(112, 64, 126, 1) 0%, rgba(69, 64, 126, 1) 100%);
/* FF3.6-15 */
background: -webkit-linear-gradient(left, rgba(112, 64, 126, 1) 0%, rgba(69, 64, 126, 1) 100%);
/* Chrome10-25,Safari5.1-6 */
background: linear-gradient(to right, rgba(112, 64, 126, 1) 0%, rgba(69, 64, 126, 1) 100%);
/* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#70407e', endColorstr='#45407e', GradientType=1);
/* IE6-9 */
}
.left {
@ -1245,7 +1270,8 @@
background-color: $color_list_background;
&.container-devices, .container-devices {
&.container-devices,
.container-devices {
flex-grow: 1;
flex-shrink: 1;
@ -1288,7 +1314,7 @@
border: none;
border-right: 1px solid #242527;
> * {
>* {
padding: .5em;
position: absolute;
@ -1300,21 +1326,21 @@
margin: auto;
}
> .icon_em {
>.icon_em {
font-size: 2em;
opacity: 0;
}
> .icon-loading {
>.icon-loading {
opacity: 0;
img {
max-height: 100%;
max-width: 100%;
-webkit-animation:spin 4s linear infinite;
-moz-animation:spin 4s linear infinite;
animation:spin 4s linear infinite;
-webkit-animation: spin 4s linear infinite;
-moz-animation: spin 4s linear infinite;
animation: spin 4s linear infinite;
}
}
}
@ -1392,7 +1418,7 @@
&.selected {
.container-selected {
> .icon_em {
>.icon_em {
opacity: 1;
}
@ -1402,7 +1428,9 @@
border-bottom: 1px solid #242527;
border-top: 1px solid #242527;
}
.container-name, .container-activity {
.container-name,
.container-activity {
margin-top: 0;
margin-bottom: 0;
@ -1480,7 +1508,8 @@
}
.right {
padding-right: .5em; /* for the sliders etc*/
padding-right: .5em;
/* for the sliders etc*/
justify-content: flex-start;
.body {
@ -1519,14 +1548,14 @@
flex-direction: column;
justify-content: stretch;
> .container {
>.container {
padding: 0;
display: flex;
flex-direction: row;
justify-content: space-between;
> label {
>label {
flex-shrink: 0;
min-width: 5em;
@ -1597,13 +1626,14 @@
.container-activity-bar {
.bar-hider {
width: 100%!important;
width: 100% !important;
}
.thumb {
background-color: #4d4d4d!important;
background-color: #4d4d4d !important;
.tooltip {
opacity: 0!important;
opacity: 0 !important;
}
}
}
@ -1676,9 +1706,9 @@
background-color: transparent;
-webkit-box-shadow: inset 0 0 2px 0 rgba(0,0,0,0.25);
-moz-box-shadow: inset 0 0 2px 0 rgba(0,0,0,0.25);
box-shadow: inset 0 0 2px 0 rgba(0,0,0,0.25);
-webkit-box-shadow: inset 0 0 2px 0 rgba(0, 0, 0, 0.25);
-moz-box-shadow: inset 0 0 2px 0 rgba(0, 0, 0, 0.25);
box-shadow: inset 0 0 2px 0 rgba(0, 0, 0, 0.25);
&::-webkit-inner-spin-button,
&::-webkit-outer-spin-button {
@ -1731,7 +1761,8 @@
position: relative;
.left, .right {
.left,
.right {
flex-grow: 1;
flex-shrink: 1;
@ -1902,11 +1933,13 @@
text-overflow: ellipsis;
white-space: nowrap;
> *:not(:first-of-type) {
>*:not(:first-of-type) {
margin-left: .25em;
}
.icon-status {
margin-bottom: .2em; /* push it a bit higher than the center */
margin-bottom: .2em;
/* push it a bit higher than the center */
}
div {
@ -1934,7 +1967,8 @@
}
}
.buttons, .buttons-small {
.buttons,
.buttons-small {
flex-grow: 0;
flex-shrink: 0;
@ -1977,7 +2011,8 @@
}
.right {
padding-right: .5em; /* for the sliders etc*/
padding-right: .5em;
/* for the sliders etc*/
justify-content: flex-start;
.body {
@ -1988,7 +2023,7 @@
flex-direction: column;
justify-content: stretch;
> div {
>div {
flex-shrink: 0;
}
@ -1997,6 +2032,7 @@
padding: 1em;
text-align: center;
}
.container-valid {
.container-level {
display: flex;
@ -2023,7 +2059,7 @@
flex-direction: row;
justify-content: space-between;
> div {
>div {
text-align: right;
width: max-content;
@ -2042,17 +2078,6 @@
}
}
.container-teaforo {
.container-valid, .container-invalid {
padding: 1em;
text-align: center;
button {
margin-top: .5em;
}
}
}
.container-highlight-dummy {
margin-top: 1em;
margin-bottom: .5em;
@ -2065,9 +2090,11 @@
}
/* the highlight stuff for the newcommer modal */
.container-settings-identity-profile, .container-settings-audio-microphone {
.container-settings-identity-profile,
.container-settings-audio-microphone {
$highlight-time: .5s;
$backdrop-color: rgba(0, 0, 0, .9);
.help-background {
position: absolute;
@ -2164,12 +2191,13 @@
}
}
.container-teamspeak, .container-teaforo, .container-nickname {
.container-teamspeak,
.container-nickname {
display: none;
}
.container-highlight-dummy {
display: flex!important;
display: flex !important;
}
&.hide-help {
@ -2195,17 +2223,32 @@
:global {
.container-settings-identity-profile {
.buttons {
display: flex!important;
display: flex !important;
}
.buttons-small {
display: none!important;
display: none !important;
}
}
}
}
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
@-moz-keyframes spin {
100% {
-moz-transform: rotate(360deg);
}
}
@-webkit-keyframes spin {
100% {
-webkit-transform: rotate(360deg);
}
}
@keyframes spin {
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}

0
shared/generate_declarations.sh Normal file → Executable file
View File

View File

@ -1,12 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TeaSpeak-Web client templates</title>
</head>
<body>
<div class="template-group-modals">
<script class="jsrender-template" id="tmpl_modal" type="text/html">
<head>
<meta charset="UTF-8">
<title>TeaSpeak-Web client templates</title>
</head>
<body>
<div class="template-group-modals">
<script class="jsrender-template" id="tmpl_modal" type="text/html">
<div class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content" style="{{if full_size}}flex-grow: 1{{/if}}">
@ -32,7 +34,7 @@
</div>
</script>
<script class="jsrender-template" id="tmpl_modal_input" type="text/html">
<script class="jsrender-template" id="tmpl_modal_input" type="text/html">
<div class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
@ -82,10 +84,10 @@
</div>
</div>
</script>
</div>
</div>
<!-- Template for the settings -->
<script class="jsrender-template" id="tmpl_settings" type="text/html">
<!-- Template for the settings -->
<script class="jsrender-template" id="tmpl_settings" type="text/html">
<div class="inner-container">
<div class="left">
<div class="entry group">{{tr "General Settings" /}}</div>
@ -103,7 +105,6 @@
<div class="entry group">{{tr "Identity" /}}</div>
<div class="entry" container="identity-profiles">{{tr "Profiles" /}}</div>
<div class="entry" container="identity-forum">{{tr "TeaForo connection" /}}</div>
</div>
<div class="container-seperator vertical" seperator-id="seperator-settings"></div>
<div class="right">
@ -360,7 +361,7 @@
</div>
</script>
<script class="jsrender-template" id="tmpl_settings-profiles" type="text/html">
<script class="jsrender-template" id="tmpl_settings-profiles" type="text/html">
<div class="container-settings-identity-profile">
<div class="left highlight-profile-list highlightable">
<div class="header">
@ -417,7 +418,6 @@
<select class="form-control profile-identity-type">
<option value="error" style="display: none">error: error</option>
<option value="unset" style="display: none">{{tr "Unset" /}}</option>
<option value="teaforo">{{tr "Forum Account" /}}</option>
<option value="teamspeak">{{tr "TeamSpeak Identity" /}}</option>
<option value="nickname">{{tr "Nickname (Debug only!)" /}}</option>
</select>
@ -453,16 +453,6 @@
</div>
</div>
</div>
<div class="container-teaforo">
<div class="container-valid">
{{tr "You're using your forum account as identification" /}}
</div>
<div class="container-invalid">
<a>{{tr "You cant use your TeaSpeak forum account. You're not connected with your forum Account!" /}}</a>
<button class="btn btn-success button-setup">{{tr "Setup your connection" /}}
</button>
</div>
</div>
<div class="container-nickname">
<div class="form-group">
<label>{{tr "Nickname" /}}</label>
@ -482,7 +472,7 @@
</div>
</script>
<script class="jsrender-template" id="tmpl_settings-sound_entry" type="text/html">
<script class="jsrender-template" id="tmpl_settings-sound_entry" type="text/html">
<div class="entry">
<div class="column sound-name">
<div class="icon client-play button-playback"></div>
@ -498,7 +488,7 @@
</div>
</script>
<script class="jsrender-template" id="tmpl_settings-teamspeak_import" type="text/html">
<script class="jsrender-template" id="tmpl_settings-teamspeak_import" type="text/html">
<div>
<div class="container-status"><a></a></div>
<fieldset class="">
@ -534,7 +524,7 @@
</div>
</script>
<script class="jsrender-template" id="tmpl_settings-teamspeak_improve" type="text/html">
<script class="jsrender-template" id="tmpl_settings-teamspeak_improve" type="text/html">
<div>
<div class="options">
<div class="title">{{tr "Identity: "/}} {{>identity_name}}</div>
@ -597,7 +587,7 @@
</div>
</script>
<script class="jsrender-template" id="settings-profile-list-entry" type="text/html">
<script class="jsrender-template" id="settings-profile-list-entry" type="text/html">
<div class="entry profile {{if id == 'default'}}default{{/if}}">
<div class="name">{{>profile_name}}</div>
<!-- <div class="button button-delete"><div class="icon client-delete"></div></div> -->
@ -606,7 +596,7 @@
</div>
</script>
<script class="jsrender-template" id="settings-translations-list-entry" type="text/html">
<script class="jsrender-template" id="settings-translations-list-entry" type="text/html">
{{if type == "repository" }}
<div class="entry repository" repository="{{:id}}">
<div class="name">{{> name}}</div>
@ -634,7 +624,7 @@
{{/if}}
</script>
<script class="jsrender-template" id="settings-translations-list-entry-info" type="text/html">
<script class="jsrender-template" id="settings-translations-list-entry-info" type="text/html">
<div class="entry-info-container">
{{if type == "repository" }}
<!--
@ -713,7 +703,7 @@
</div>
</script>
<script class="jsrender-template" id="tmpl_change_latency" type="text/html">
<script class="jsrender-template" id="tmpl_change_latency" type="text/html">
<div> <!-- for the renderer -->
<div class="info">
<div>{{tr "Change latency for client "/}} <node key="client"></node></div>
@ -758,7 +748,7 @@
</div>
</script>
<script class="jsrender-template" id="tmpl_server_edit" type="text/html">
<script class="jsrender-template" id="tmpl_server_edit" type="text/html">
<div> <!-- Only for rendering -->
<div class="container-general">
<div class="container-name-icon">
@ -1354,8 +1344,8 @@
</div>
</script>
<!-- General management templates -->
<script class="jsrender-template" id="tmpl_ban_list" type="text/html">
<!-- General management templates -->
<script class="jsrender-template" id="tmpl_ban_list" type="text/html">
<div> <!-- required for jquery -->
<div class="left">
<div class="head">
@ -1641,7 +1631,7 @@
</div>
</script>
<script class="jsrender-template" id="tmpl_client_ban" type="text/html">
<script class="jsrender-template" id="tmpl_client_ban" type="text/html">
<div> <!-- for the renderer -->
<div class="container-info">
<div class="container container-name">
@ -1724,7 +1714,7 @@
</div>
</script>
<script class="jsrender-template" id="tmpl_query_create" type="text/html">
<script class="jsrender-template" id="tmpl_query_create" type="text/html">
<div class="query-create">
<a>{{tr "Set the login name for your Server Query account." /}}</a>
<a>{{tr "You'll receive your password within the next step." /}}</a>
@ -1738,7 +1728,7 @@
</div>
</div>
</script>
<script class="jsrender-template" id="tmpl_query_created" type="text/html">
<script class="jsrender-template" id="tmpl_query_created" type="text/html">
<div class="query-created">
<a>{{tr "Your server query credentials:" /}}</a>
<div class="form-row">
@ -1763,7 +1753,7 @@
</div>
</script>
<script class="jsrender-template" id="tmpl_query_manager" type="text/html">
<script class="jsrender-template" id="tmpl_query_manager" type="text/html">
<div class="container"> <!-- required for the seperator -->
<div class="left">
<div class="title">
@ -1823,7 +1813,7 @@
</div>
</script>
<script class="jsrender-template" id="tmpl_avatar_list" type="text/html">
<script class="jsrender-template" id="tmpl_avatar_list" type="text/html">
<div class="modal-avatar-list">
<div class="container-list">
<div class="list-header">
@ -1885,7 +1875,7 @@
</div>
</script>
<script class="jsrender-template" id="tmpl_avatar_list-list_entry" type="text/html">
<script class="jsrender-template" id="tmpl_avatar_list-list_entry" type="text/html">
<div class="entry">
<div class="column column-username">{{>username}}</div>
<div class="column column-unique-id">{{>unique_id}}</div>
@ -1894,7 +1884,7 @@
</div>
</script>
<script class="jsrender-template" id="tmpl_key_select" type="text/html">
<script class="jsrender-template" id="tmpl_key_select" type="text/html">
<div> <!-- required for the renderer-->
<div class="body">
<a>{{tr "Press any key which you want to use." /}}</a>
@ -1912,7 +1902,7 @@
</div>
</script>
<script class="jsrender-template" id="tmpl_client_info" type="text/html">
<script class="jsrender-template" id="tmpl_client_info" type="text/html">
<div> <!-- Important for the renderer -->
<div class="head">
<div class="status-row">
@ -1970,14 +1960,6 @@
</div>
</div>
</div>
<div class="property property-teaforo">
<div class="title">
<a>{{tr "TeaForo Connection" /}}</a>
</div>
<div class="value">
<a>This will be a really long string...</a>
</div>
</div>
<div class="property property-version">
<div class="title">
<a>{{tr "Version" /}}</a>
@ -2169,5 +2151,6 @@
</div>
</div>
</script>
</body>
</body>
</html>

View File

@ -40,15 +40,15 @@ export interface KeyBoardBackend {
registerListener(listener: (event: KeyEvent) => void);
unregisterListener(listener: (event: KeyEvent) => void);
registerHook(hook: KeyHook) : () => void;
registerHook(hook: KeyHook): () => void;
unregisterHook(hook: KeyHook);
isKeyPressed(key: string | SpecialKey) : boolean;
isKeyPressed(key: string | SpecialKey): boolean;
}
export class AbstractKeyBoard implements KeyBoardBackend {
protected readonly registeredListener: ((event: KeyEvent) => void)[];
protected readonly activeSpecialKeys: { [key: number] : boolean };
protected readonly activeSpecialKeys: { [key: number]: boolean };
protected readonly activeKeys;
protected registeredKeyHooks: RegisteredKeyHook[] = [];
@ -59,10 +59,10 @@ export class AbstractKeyBoard implements KeyBoardBackend {
this.registeredListener = [];
}
protected destroy() {}
protected destroy() { }
isKeyPressed(key: string | SpecialKey): boolean {
if(typeof(key) === 'string') {
if (typeof (key) === 'string') {
return typeof this.activeKeys[key] !== "undefined";
}
@ -76,7 +76,7 @@ export class AbstractKeyBoard implements KeyBoardBackend {
};
this.registeredKeyHooks.push(registeredHook);
if(this.shouldHookBeActive(registeredHook)) {
if (this.shouldHookBeActive(registeredHook)) {
registeredHook.triggered = true;
registeredHook.callbackPress();
}
@ -85,11 +85,11 @@ export class AbstractKeyBoard implements KeyBoardBackend {
}
unregisterHook(hook: KeyHook) {
if(!("triggered" in hook)) {
if (!("triggered" in hook)) {
return;
}
this.registeredKeyHooks.remove(hook);
this.registeredKeyHooks.remove(hook as RegisteredKeyHook);
}
registerListener(listener: (event: KeyEvent) => void) {
@ -101,19 +101,19 @@ export class AbstractKeyBoard implements KeyBoardBackend {
}
private shouldHookBeActive(hook: KeyHook) {
if(typeof hook.keyAlt !== "undefined" && hook.keyAlt != this.activeSpecialKeys[SpecialKey.ALT]) {
if (typeof hook.keyAlt !== "undefined" && hook.keyAlt != this.activeSpecialKeys[SpecialKey.ALT]) {
return false;
}
if(typeof hook.keyCtrl !== "undefined" && hook.keyCtrl != this.activeSpecialKeys[SpecialKey.CTRL]) {
if (typeof hook.keyCtrl !== "undefined" && hook.keyCtrl != this.activeSpecialKeys[SpecialKey.CTRL]) {
return false;
}
if(typeof hook.keyShift !== "undefined" && hook.keyShift != this.activeSpecialKeys[SpecialKey.SHIFT]) {
if (typeof hook.keyShift !== "undefined" && hook.keyShift != this.activeSpecialKeys[SpecialKey.SHIFT]) {
return false;
}
if(typeof hook.keyWindows !== "undefined" && hook.keyWindows != this.activeSpecialKeys[SpecialKey.WINDOWS]) {
if (typeof hook.keyWindows !== "undefined" && hook.keyWindows != this.activeSpecialKeys[SpecialKey.WINDOWS]) {
return false;
}
@ -122,11 +122,11 @@ export class AbstractKeyBoard implements KeyBoardBackend {
protected fireKeyEvent(event: KeyEvent) {
//console.debug("Trigger key event %o", key_event);
for(const listener of this.registeredListener) {
for (const listener of this.registeredListener) {
listener(event);
}
if(event.type == EventType.KEY_TYPED) {
if (event.type == EventType.KEY_TYPED) {
return;
}
@ -134,26 +134,26 @@ export class AbstractKeyBoard implements KeyBoardBackend {
this.activeSpecialKeys[SpecialKey.CTRL] = event.keyCtrl;
this.activeSpecialKeys[SpecialKey.SHIFT] = event.keyShift;
this.activeSpecialKeys[SpecialKey.WINDOWS] = event.keyWindows;
if(event.type == EventType.KEY_PRESS) {
if (event.type == EventType.KEY_PRESS) {
this.activeKeys[event.keyCode] = event;
} else {
delete this.activeKeys[event.keyCode];
}
for(const hook of this.registeredKeyHooks) {
for (const hook of this.registeredKeyHooks) {
const hookActive = this.shouldHookBeActive(hook);
if(hookActive === hook.triggered) {
if (hookActive === hook.triggered) {
continue;
}
hook.triggered = hookActive;
if(hookActive) {
if(hook.callbackPress) {
if (hookActive) {
if (hook.callbackPress) {
hook.callbackPress();
}
} else {
if(hook.callbackRelease) {
if (hook.callbackRelease) {
hook.callbackRelease();
}
}
@ -166,13 +166,13 @@ export class AbstractKeyBoard implements KeyBoardBackend {
this.activeSpecialKeys[SpecialKey.SHIFT] = false;
this.activeSpecialKeys[SpecialKey.WINDOWS] = false;
for(const code of Object.keys(this.activeKeys)) {
for (const code of Object.keys(this.activeKeys)) {
delete this.activeKeys[code];
}
for(const hook of this.registeredKeyHooks) {
if(hook.triggered) {
if(hook.callbackRelease) {
for (const hook of this.registeredKeyHooks) {
if (hook.triggered) {
if (hook.callbackRelease) {
hook.callbackRelease();
}
@ -183,7 +183,7 @@ export class AbstractKeyBoard implements KeyBoardBackend {
}
let keyBoardBackend: KeyBoardBackend;
export function getKeyBoard() : KeyBoardBackend {
export function getKeyBoard(): KeyBoardBackend {
return keyBoardBackend;
}
@ -193,29 +193,29 @@ export function setKeyBoardBackend(newBackend: KeyBoardBackend) {
export function getKeyDescription(key: KeyDescriptor) {
let result = "";
if(key.keyShift) {
if (key.keyShift) {
result += " + " + tr("Shift");
}
if(key.keyAlt) {
if (key.keyAlt) {
result += " + " + tr("Alt");
}
if(key.keyCtrl) {
if (key.keyCtrl) {
result += " + " + tr("CTRL");
}
if(key.keyWindows) {
if (key.keyWindows) {
result += " + " + tr("Win");
}
if(key.keyCode) {
if (key.keyCode) {
let keyName;
if(key.keyCode.startsWith("Key")) {
if (key.keyCode.startsWith("Key")) {
keyName = key.keyCode.substr(3);
} else if(key.keyCode.startsWith("Digit")) {
} else if (key.keyCode.startsWith("Digit")) {
keyName = key.keyCode.substr(5);
} else if(key.keyCode.startsWith("Numpad")) {
} else if (key.keyCode.startsWith("Numpad")) {
keyName = "Numpad " + key.keyCode.substr(6);
} else {
keyName = key.keyCode;

View File

@ -1,12 +1,12 @@
import {ConnectionHandler, ConnectionState} from "tc-shared/ConnectionHandler";
import { ConnectionHandler, ConnectionState } from "tc-shared/ConnectionHandler";
import {
ClientForumInfo,
ClientInfoType,
ClientStatusInfo,
ClientVersionInfo
} from "tc-shared/ui/frames/side/ClientInfoDefinitions";
import {ClientEntry, ClientType, LocalClientEntry} from "tc-shared/tree/Client";
import {Registry} from "tc-shared/events";
import { ClientEntry, ClientType, LocalClientEntry } from "tc-shared/tree/Client";
import { Registry } from "tc-shared/events";
import * as i18nc from "./i18n/CountryFlag";
export type CachedClientInfoCategory = "name" | "description" | "online-state" | "country" | "volume" | "status" | "forum-account" | "group-channel" | "groups-server" | "version";
@ -55,7 +55,7 @@ export class SelectedClientInfo {
this.listenerClient = [];
this.listenerConnection = [];
this.listenerConnection.push(connection.channelTree.events.on("notify_client_leave_view", event => {
if(event.client !== this.currentClient) {
if (event.client !== this.currentClient) {
return;
}
@ -67,7 +67,7 @@ export class SelectedClientInfo {
}));
this.listenerConnection.push(connection.events().on("notify_connection_state_changed", event => {
if(event.newState !== ConnectionState.CONNECTED && this.currentClientStatus) {
if (event.newState !== ConnectionState.CONNECTED && this.currentClientStatus) {
this.currentClient = undefined;
this.currentClientStatus.leaveTimestamp = Date.now() / 1000;
this.events.fire("notify_cache_changed", { category: "online-state" });
@ -82,23 +82,23 @@ export class SelectedClientInfo {
this.unregisterClientEvents();
}
getInfo() : CachedClientInfo {
getInfo(): CachedClientInfo {
return this.currentClientStatus;
}
setClient(client: ClientEntry | undefined) {
if(this.currentClient === client) {
if (this.currentClient === client) {
return;
}
if(client.channelTree.client !== this.connection) {
if (client.channelTree.client !== this.connection) {
throw tr("client does not belong to current connection handler");
}
this.unregisterClientEvents();
this.currentClient = client;
this.currentClientStatus = undefined;
if(this.currentClient) {
if (this.currentClient) {
this.currentClient.updateClientVariables().then(undefined);
this.registerClientEvents(this.currentClient);
this.initializeClientInfo(this.currentClient);
@ -107,7 +107,7 @@ export class SelectedClientInfo {
this.events.fire("notify_client_changed", { newClient: client });
}
getClient() : ClientEntry | undefined {
getClient(): ClientEntry | undefined {
return this.currentClient;
}
@ -120,57 +120,52 @@ export class SelectedClientInfo {
const events = this.listenerClient;
events.push(client.events.on("notify_properties_updated", event => {
if('client_nickname' in event.updated_properties) {
if ('client_nickname' in event.updated_properties) {
this.currentClientStatus.name = event.client_properties.client_nickname;
this.events.fire("notify_cache_changed", { category: "name" });
}
if('client_description' in event.updated_properties) {
if ('client_description' in event.updated_properties) {
this.currentClientStatus.description = event.client_properties.client_description;
this.events.fire("notify_cache_changed", { category: "description" });
}
if('client_channel_group_id' in event.updated_properties || 'client_channel_group_inherited_channel_id' in event.updated_properties) {
if ('client_channel_group_id' in event.updated_properties || 'client_channel_group_inherited_channel_id' in event.updated_properties) {
this.updateChannelGroup(client);
this.events.fire("notify_cache_changed", { category: "group-channel" });
}
if('client_servergroups' in event.updated_properties) {
if ('client_servergroups' in event.updated_properties) {
this.currentClientStatus.serverGroups = client.assignedServerGroupIds();
this.events.fire("notify_cache_changed", { category: "groups-server" });
}
/* Can happen since that variable isn't in view on client appearance */
if('client_lastconnected' in event.updated_properties) {
if ('client_lastconnected' in event.updated_properties) {
this.currentClientStatus.joinTimestamp = event.client_properties.client_lastconnected;
this.events.fire("notify_cache_changed", { category: "online-state" });
}
if('client_country' in event.updated_properties) {
if ('client_country' in event.updated_properties) {
this.updateCachedCountry(client);
this.events.fire("notify_cache_changed", { category: "country" });
}
for(const key of ["client_away", "client_away_message", "client_input_muted", "client_input_hardware", "client_output_muted", "client_output_hardware"]) {
if(key in event.updated_properties) {
for (const key of ["client_away", "client_away_message", "client_input_muted", "client_input_hardware", "client_output_muted", "client_output_hardware"]) {
if (key in event.updated_properties) {
this.updateCachedClientStatus(client);
this.events.fire("notify_cache_changed", { category: "status" });
break;
}
}
if('client_platform' in event.updated_properties || 'client_version' in event.updated_properties) {
if ('client_platform' in event.updated_properties || 'client_version' in event.updated_properties) {
this.currentClientStatus.version = {
platform: client.properties.client_platform,
version: client.properties.client_version
};
this.events.fire("notify_cache_changed", { category: "version" });
}
if('client_teaforo_flags' in event.updated_properties || 'client_teaforo_name' in event.updated_properties || 'client_teaforo_id' in event.updated_properties) {
this.updateForumAccount(client);
this.events.fire("notify_cache_changed", { category: "forum-account" });
}
}));
events.push(client.events.on("notify_audio_level_changed", () => {
@ -209,22 +204,11 @@ export class SelectedClientInfo {
}
}
private updateForumAccount(client: ClientEntry) {
if(client.properties.client_teaforo_id) {
this.currentClientStatus.forumAccount = {
flags: client.properties.client_teaforo_flags,
nickname: client.properties.client_teaforo_name,
userId: client.properties.client_teaforo_id
};
} else {
this.currentClientStatus.forumAccount = undefined;
}
}
private updateChannelGroup(client: ClientEntry) {
this.currentClientStatus.channelGroup = client.properties.client_channel_group_id;
this.currentClientStatus.channelGroupInheritedChannel = client.properties.client_channel_group_inherited_channel_id;
if(this.currentClientStatus.channelGroupInheritedChannel === client.currentChannel().channelId) {
if (this.currentClientStatus.channelGroupInheritedChannel === client.currentChannel().channelId) {
this.currentClientStatus.channelGroupInheritedChannel = 0;
}
}
@ -259,6 +243,5 @@ export class SelectedClientInfo {
this.updateCachedClientStatus(client);
this.updateCachedCountry(client);
this.updateCachedVolume(client);
this.updateForumAccount(client);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
import {Registry} from "tc-shared/events";
import {LogCategory, logTrace, logWarn} from "tc-shared/log";
import {tr} from "tc-shared/i18n/localize";
import {getAudioBackend} from "tc-shared/audio/Player";
import { Registry } from "tc-shared/events";
import { LogCategory, logTrace, logWarn } from "tc-shared/log";
import { tr } from "tc-shared/i18n/localize";
import { getAudioBackend } from "tc-shared/audio/Player";
export interface TrackClientInfo {
media?: number,
@ -56,34 +56,34 @@ export class RemoteRTPTrack {
this.events.destroy();
}
getEvents() : Registry<RemoteRTPTrackEvents> {
getEvents(): Registry<RemoteRTPTrackEvents> {
return this.events;
}
getState() : RemoteRTPTrackState {
getState(): RemoteRTPTrackState {
return this.currentState;
}
getSsrc() : number {
getSsrc(): number {
return this.ssrc >>> 0;
}
getTrack() : MediaStreamTrack {
getTrack(): MediaStreamTrack {
return this.transceiver.receiver.track;
}
getTransceiver() : RTCRtpTransceiver {
getTransceiver(): RTCRtpTransceiver {
return this.transceiver;
}
getCurrentAssignment() : TrackClientInfo | undefined {
getCurrentAssignment(): TrackClientInfo | undefined {
return this.currentAssignment;
}
protected setState(state: RemoteRTPTrackState) {
if(this.currentState === state) {
if (this.currentState === state) {
return;
} else if(this.currentState === RemoteRTPTrackState.Destroyed) {
} else if (this.currentState === RemoteRTPTrackState.Destroyed) {
logWarn(LogCategory.WEBRTC, tr("Tried to change the track state for track %d from destroyed to %s."), this.getSsrc(), RemoteRTPTrackState[state]);
return;
}
@ -107,10 +107,9 @@ export class RemoteRTPVideoTrack extends RemoteRTPTrack {
track.onended = () => logTrace(LogCategory.VIDEO, "Track %d ended", ssrc);
track.onmute = () => logTrace(LogCategory.VIDEO, "Track %d muted", ssrc);
track.onunmute = () => logTrace(LogCategory.VIDEO, "Track %d unmuted", ssrc);
track.onisolationchange = () => logTrace(LogCategory.VIDEO, "Track %d isolation changed", ssrc);
}
getMediaStream() : MediaStream {
getMediaStream(): MediaStream {
return this.mediaStream;
}
@ -170,7 +169,7 @@ export class RemoteRTPAudioTrack extends RemoteRTPTrack {
*/
getAudioBackend().executeWhenInitialized(() => {
if(!this.mediaStream) {
if (!this.mediaStream) {
/* we've already been destroyed */
return;
}
@ -200,7 +199,7 @@ export class RemoteRTPAudioTrack extends RemoteRTPTrack {
this.setState(RemoteRTPTrackState.Destroyed);
}
getGain() : GainNode | undefined {
getGain(): GainNode | undefined {
return this.gainNode;
}
@ -213,13 +212,13 @@ export class RemoteRTPAudioTrack extends RemoteRTPTrack {
* Mutes this track until the next setGain(..) call or a new sequence begins (state update)
*/
abortCurrentReplay() {
if(this.gainNode) {
if (this.gainNode) {
this.gainNode.gain.value = 0;
}
}
protected updateGainNode() {
if(!this.gainNode) {
if (!this.gainNode) {
return;
}

View File

@ -1,9 +1,9 @@
/* Note: This will be included into the controller and renderer process */
import {LogCategory, logError, logWarn} from "tc-shared/log";
import { LogCategory, logError, logWarn } from "tc-shared/log";
import * as loader from "tc-loader";
import {Stage} from "tc-loader";
import { Stage } from "tc-loader";
import * as crypto from "crypto-js";
import {tra} from "tc-shared/i18n/localize";
import { tra } from "tc-shared/i18n/localize";
export type LocalAvatarInfo = {
fileName: string,
@ -43,12 +43,12 @@ export type OwnAvatarMode = "uploading" | "server";
export class OwnAvatarStorage {
private openedCache: Cache | undefined;
private static generateRequestUrl(serverUniqueId: string, mode: OwnAvatarMode) : string {
private static generateRequestUrl(serverUniqueId: string, mode: OwnAvatarMode): string {
return "https://_local_avatar/" + serverUniqueId + "/" + mode;
}
async initialize() {
if(!("caches" in window)) {
if (!("caches" in window)) {
/* Not available (may unsecure context?) */
this.openedCache = undefined;
return;
@ -62,8 +62,8 @@ export class OwnAvatarStorage {
}
}
private async loadAvatarRequest(serverUniqueId: string, mode: OwnAvatarMode) : Promise<LocalAvatarLoadResult<Response>> {
if(!this.openedCache) {
private async loadAvatarRequest(serverUniqueId: string, mode: OwnAvatarMode): Promise<LocalAvatarLoadResult<Response>> {
if (!this.openedCache) {
return { status: "cache-unavailable" };
}
@ -73,7 +73,7 @@ export class OwnAvatarStorage {
ignoreSearch: true,
});
if(!response) {
if (!response) {
return { status: "empty-result" };
}
@ -84,9 +84,9 @@ export class OwnAvatarStorage {
}
}
async loadAvatarImage(serverUniqueId: string, mode: OwnAvatarMode) : Promise<LocalAvatarLoadResult<ArrayBuffer>> {
async loadAvatarImage(serverUniqueId: string, mode: OwnAvatarMode): Promise<LocalAvatarLoadResult<ArrayBuffer>> {
const loadResult = await this.loadAvatarRequest(serverUniqueId, mode);
if(loadResult.status !== "success") {
if (loadResult.status !== "success") {
return loadResult;
}
@ -98,9 +98,9 @@ export class OwnAvatarStorage {
}
}
async loadAvatar(serverUniqueId: string, mode: OwnAvatarMode, createResourceUrl: boolean) : Promise<LocalAvatarLoadResult<LocalAvatarInfo>> {
async loadAvatar(serverUniqueId: string, mode: OwnAvatarMode, createResourceUrl: boolean): Promise<LocalAvatarLoadResult<LocalAvatarInfo>> {
const loadResult = await this.loadAvatarRequest(serverUniqueId, mode);
if(loadResult.status !== "success") {
if (loadResult.status !== "success") {
return loadResult;
}
@ -112,28 +112,28 @@ export class OwnAvatarStorage {
const avatarDateModified = parseInt(headers.get("X-File-Date-Modified"));
const avatarDateUploaded = parseInt(headers.get("X-File-Uploaded"));
if(!avatarHash) {
if (!avatarHash) {
return { status: "error", reason: tr("missing response header file hash") };
}
if(!avatarName) {
if (!avatarName) {
return { status: "error", reason: tr("missing response header file name") };
}
if(isNaN(avatarSize)) {
if (isNaN(avatarSize)) {
return { status: "error", reason: tr("missing/invalid response header file size") };
}
if(isNaN(avatarDateModified)) {
if (isNaN(avatarDateModified)) {
return { status: "error", reason: tr("missing/invalid response header file modify date") };
}
if(isNaN(avatarDateUploaded)) {
if (isNaN(avatarDateUploaded)) {
return { status: "error", reason: tr("missing/invalid response header file upload date") };
}
let resourceUrl;
if(createResourceUrl) {
if (createResourceUrl) {
try {
resourceUrl = URL.createObjectURL(await loadResult.result.blob());
} catch (error) {
@ -159,12 +159,12 @@ export class OwnAvatarStorage {
};
}
async updateAvatar(serverUniqueId: string, mode: OwnAvatarMode, target: File) : Promise<LocalAvatarUpdateResult> {
if(!this.openedCache) {
async updateAvatar(serverUniqueId: string, mode: OwnAvatarMode, target: File): Promise<LocalAvatarUpdateResult> {
if (!this.openedCache) {
return { status: "cache-unavailable" };
}
if(target.size > kMaxAvatarSize) {
if (target.size > kMaxAvatarSize) {
return { status: "error", reason: tra("Image exceeds maximum software size of {} bytes", kMaxAvatarSize) };
}
@ -173,7 +173,7 @@ export class OwnAvatarStorage {
const hasher = crypto.algo.MD5.create();
await target.stream().pipeTo(new WritableStream({
write(data) {
hasher.update(crypto.lib.WordArray.create(data));
hasher.update(crypto.lib.WordArray.create(Array.from(data)));
}
}));
@ -203,7 +203,7 @@ export class OwnAvatarStorage {
}
async removeAvatar(serverUniqueId: string, mode: OwnAvatarMode) {
if(!this.openedCache) {
if (!this.openedCache) {
return;
}
@ -219,13 +219,13 @@ export class OwnAvatarStorage {
* @param serverUniqueId
*/
async avatarUploadSucceeded(serverUniqueId: string) {
if(!this.openedCache) {
if (!this.openedCache) {
return;
}
const request = await this.loadAvatarRequest(serverUniqueId, "uploading");
if(request.status !== "success") {
if(request.status !== "empty-result") {
if (request.status !== "success") {
if (request.status !== "empty-result") {
logError(LogCategory.GENERAL, tr("Failed to save uploaded avatar. Request failed to load: %o"), request);
}
return;

View File

@ -1,31 +1,30 @@
import * as loader from "tc-loader";
import {initializeI18N, tra} from "./i18n/localize";
import * as fidentity from "./profiles/identities/TeaForumIdentity";
import { initializeI18N, tra } from "./i18n/localize";
import * as global_ev_handler from "./events/ClientGlobalControlHandler";
import {AppParameters, settings, Settings, UrlParameterBuilder, UrlParameterParser} from "tc-shared/settings";
import {LogCategory, logDebug, logError, logInfo, logWarn} from "tc-shared/log";
import {ConnectionHandler} from "tc-shared/ConnectionHandler";
import {createErrorModal, createInfoModal} from "tc-shared/ui/elements/Modal";
import {RecorderProfile, setDefaultRecorder} from "tc-shared/voice/RecorderProfile";
import {formatMessage} from "tc-shared/ui/frames/chat";
import {openModalNewcomer} from "tc-shared/ui/modal/ModalNewcomer";
import {global_client_actions} from "tc-shared/events/GlobalEvents";
import {MenuEntryType, spawn_context_menu} from "tc-shared/ui/elements/ContextMenu";
import {copyToClipboard} from "tc-shared/utils/helpers";
import {checkForUpdatedApp} from "tc-shared/update";
import {setupJSRender} from "tc-shared/ui/jsrender";
import {ConnectRequestData} from "tc-shared/ipc/ConnectHandler";
import {defaultConnectProfile, findConnectProfile} from "tc-shared/profiles/ConnectionProfile";
import {server_connections} from "tc-shared/ConnectionManager";
import {spawnConnectModalNew} from "tc-shared/ui/modal/connect/Controller";
import {initializeKeyControl} from "./KeyControl";
import {assertMainApplication} from "tc-shared/ui/utils";
import {clientServiceInvite} from "tc-shared/clientservice";
import {ActionResult} from "tc-services";
import {CommandResult} from "tc-shared/connection/ServerConnectionDeclaration";
import {ErrorCode} from "tc-shared/connection/ErrorCode";
import {bookmarks} from "tc-shared/Bookmarks";
import {getAudioBackend, OutputDevice} from "tc-shared/audio/Player";
import { AppParameters, settings, Settings, UrlParameterBuilder, UrlParameterParser } from "tc-shared/settings";
import { LogCategory, logDebug, logError, logInfo, logWarn } from "tc-shared/log";
import { ConnectionHandler } from "tc-shared/ConnectionHandler";
import { createErrorModal, createInfoModal } from "tc-shared/ui/elements/Modal";
import { RecorderProfile, setDefaultRecorder } from "tc-shared/voice/RecorderProfile";
import { formatMessage } from "tc-shared/ui/frames/chat";
import { openModalNewcomer } from "tc-shared/ui/modal/ModalNewcomer";
import { global_client_actions } from "tc-shared/events/GlobalEvents";
import { MenuEntryType, spawn_context_menu } from "tc-shared/ui/elements/ContextMenu";
import { copyToClipboard } from "tc-shared/utils/helpers";
import { checkForUpdatedApp } from "tc-shared/update";
import { setupJSRender } from "tc-shared/ui/jsrender";
import { ConnectRequestData } from "tc-shared/ipc/ConnectHandler";
import { defaultConnectProfile, findConnectProfile } from "tc-shared/profiles/ConnectionProfile";
import { server_connections } from "tc-shared/ConnectionManager";
import { spawnConnectModalNew } from "tc-shared/ui/modal/connect/Controller";
import { initializeKeyControl } from "./KeyControl";
import { assertMainApplication } from "tc-shared/ui/utils";
import { clientServiceInvite } from "tc-shared/clientservice";
import { ActionResult } from "tc-services";
import { CommandResult } from "tc-shared/connection/ServerConnectionDeclaration";
import { ErrorCode } from "tc-shared/connection/ErrorCode";
import { bookmarks } from "tc-shared/Bookmarks";
import { getAudioBackend, OutputDevice } from "tc-shared/audio/Player";
/* required import for init */
import "svg-sprites/client-icons";
@ -50,9 +49,9 @@ import "./ui/elements/Tab";
import "./clientservice";
import "./text/bbcode/InviteController";
import "./text/bbcode/YoutubeController";
import {initializeSounds, setSoundMasterVolume} from "./audio/Sounds";
import {getInstanceConnectHandler, setupIpcHandler} from "./ipc/BrowserIPC";
import {promptYesNo} from "tc-shared/ui/modal/yes-no/Controller";
import { initializeSounds, setSoundMasterVolume } from "./audio/Sounds";
import { getInstanceConnectHandler, setupIpcHandler } from "./ipc/BrowserIPC";
import { promptYesNo } from "tc-shared/ui/modal/yes-no/Controller";
assertMainApplication();
@ -60,7 +59,7 @@ let preventWelcomeUI = false;
async function initialize() {
try {
await initializeI18N();
} catch(error) {
} catch (error) {
console.error(tr("Failed to initialized the translation system!\nError: %o"), error);
loader.critical_error("Failed to setup the translation system");
return;
@ -75,13 +74,13 @@ async function initializeApp() {
getAudioBackend().executeWhenInitialized(() => {
const defaultDeviceId = getAudioBackend().getDefaultDeviceId();
let targetDeviceId = settings.getValue(Settings.KEY_SPEAKER_DEVICE_ID, OutputDevice.DefaultDeviceId);
if(targetDeviceId === OutputDevice.DefaultDeviceId) {
if (targetDeviceId === OutputDevice.DefaultDeviceId) {
targetDeviceId = defaultDeviceId;
}
getAudioBackend().setCurrentDevice(targetDeviceId).catch(error => {
logWarn(LogCategory.AUDIO, tr("Failed to set last used output speaker device: %o"), error);
if(targetDeviceId !== defaultDeviceId) {
if (targetDeviceId !== defaultDeviceId) {
getAudioBackend().setCurrentDevice(defaultDeviceId).catch(error => {
logError(LogCategory.AUDIO, tr("Failed to set output device to default device: %o"), error);
createErrorModal(tr("Failed to initialize output device"), tr("Failed to initialize output device.")).open();
@ -108,10 +107,10 @@ async function initializeApp() {
/* The native client has received a connect request. */
export function handleNativeConnectRequest(url: URL) {
let serverAddress = url.host;
if(url.searchParams.has("port")) {
if(serverAddress.indexOf(':') !== -1) {
if (url.searchParams.has("port")) {
if (serverAddress.indexOf(':') !== -1) {
logWarn(LogCategory.GENERAL, tr("Received connect request which specified the port twice (via parameter and host). Using host port."));
} else if(serverAddress.indexOf(":") === -1) {
} else if (serverAddress.indexOf(":") === -1) {
serverAddress += ":" + url.searchParams.get("port");
} else {
serverAddress = `[${serverAddress}]:${url.searchParams.get("port")}`;
@ -125,16 +124,16 @@ export async function handleConnectRequest(serverAddress: string, serverUniqueId
const inviteLinkId = parameters.getValue(AppParameters.KEY_CONNECT_INVITE_REFERENCE, undefined);
logDebug(LogCategory.STATISTICS, tr("Executing connect request with invite key reference: %o"), inviteLinkId);
if(inviteLinkId) {
if (inviteLinkId) {
clientServiceInvite.logAction(inviteLinkId, "ConnectAttempt").then(result => {
if(result.status !== "success") {
if (result.status !== "success") {
logWarn(LogCategory.STATISTICS, tr("Failed to register connect attempt: %o"), result.result);
}
});
}
const result = await doHandleConnectRequest(serverAddress, serverUniqueId, parameters);
if(inviteLinkId) {
if (inviteLinkId) {
let promise: Promise<ActionResult<void>>;
switch (result.status) {
case "success":
@ -152,7 +151,7 @@ export async function handleConnectRequest(serverAddress: string, serverUniqueId
}
promise.then(result => {
if(result.status !== "success") {
if (result.status !== "success") {
logWarn(LogCategory.STATISTICS, tr("Failed to register connect result: %o"), result.result);
}
});
@ -161,14 +160,14 @@ export async function handleConnectRequest(serverAddress: string, serverUniqueId
type ConnectRequestResult = {
status:
"success" |
"profile-invalid" |
"client-aborted" |
"server-join-failed" |
"server-already-joined" |
"channel-already-joined" |
"channel-not-visible" |
"channel-join-failed"
"success" |
"profile-invalid" |
"client-aborted" |
"server-join-failed" |
"server-already-joined" |
"channel-already-joined" |
"channel-not-visible" |
"channel-join-failed"
}
/**
@ -176,12 +175,12 @@ type ConnectRequestResult = {
* @param serverUniqueId If given a server unique id. If any of our current connections matches it, such connection will be used
* @param parameters General connect parameters from the connect URL
*/
async function doHandleConnectRequest(serverAddress: string, serverUniqueId: string | undefined, parameters: UrlParameterParser) : Promise<ConnectRequestResult> {
async function doHandleConnectRequest(serverAddress: string, serverUniqueId: string | undefined, parameters: UrlParameterParser): Promise<ConnectRequestResult> {
let targetServerConnection: ConnectionHandler;
let isCurrentServerConnection: boolean;
if(serverUniqueId) {
if(server_connections.getActiveConnectionHandler()?.getCurrentServerUniqueId() === serverUniqueId) {
if (serverUniqueId) {
if (server_connections.getActiveConnectionHandler()?.getCurrentServerUniqueId() === serverUniqueId) {
targetServerConnection = server_connections.getActiveConnectionHandler();
isCurrentServerConnection = true;
} else {
@ -193,7 +192,7 @@ async function doHandleConnectRequest(serverAddress: string, serverUniqueId: str
const profileId = parameters.getValue(AppParameters.KEY_CONNECT_PROFILE, undefined);
const profile = findConnectProfile(profileId) || targetServerConnection?.serverConnection.handshake_handler()?.parameters.profile || defaultConnectProfile();
if(!profile || !profile.valid()) {
if (!profile || !profile.valid()) {
spawnConnectModalNew({
selectedAddress: serverAddress,
selectedProfile: profile
@ -201,14 +200,14 @@ async function doHandleConnectRequest(serverAddress: string, serverUniqueId: str
return { status: "profile-invalid" };
}
if(!getAudioBackend().isInitialized()) {
if (!getAudioBackend().isInitialized()) {
/* Trick the client into clicking somewhere on the site to initialize audio */
const result = await promptYesNo({
title: tra("Connect to {}", serverAddress),
question: tra("Would you like to connect to {}?", serverAddress)
});
if(!result) {
if (!result) {
/* Well... the client don't want to... */
return { status: "client-aborted" };
}
@ -226,30 +225,30 @@ async function doHandleConnectRequest(serverAddress: string, serverUniqueId: str
const connectToken = parameters.getValue(AppParameters.KEY_CONNECT_TOKEN, undefined);
if(!targetServerConnection) {
if (!targetServerConnection) {
targetServerConnection = server_connections.getActiveConnectionHandler();
if(targetServerConnection.connected) {
if (targetServerConnection.connected) {
targetServerConnection = server_connections.spawnConnectionHandler();
}
}
server_connections.setActiveConnectionHandler(targetServerConnection);
if(targetServerConnection.getCurrentServerUniqueId() === serverUniqueId) {
if (targetServerConnection.getCurrentServerUniqueId() === serverUniqueId) {
/* Just join the new channel and may use the token (before) */
if(connectToken) {
if (connectToken) {
try {
await targetServerConnection.serverConnection.send_command("tokenuse", { token: connectToken }, { process_result: false });
} catch (error) {
if(error instanceof CommandResult) {
if(error.id === ErrorCode.TOKEN_INVALID_ID) {
targetServerConnection.log.log("error.custom", { message: tr("Try to use invite key token but the token is invalid.")});
} else if(error.id == ErrorCode.TOKEN_EXPIRED) {
targetServerConnection.log.log("error.custom", { message: tr("Try to use invite key token but the token is expired.")});
} else if(error.id === ErrorCode.TOKEN_USE_LIMIT_EXCEEDED) {
targetServerConnection.log.log("error.custom", { message: tr("Try to use invite key token but the token has been used too many times.")});
if (error instanceof CommandResult) {
if (error.id === ErrorCode.TOKEN_INVALID_ID) {
targetServerConnection.log.log("error.custom", { message: tr("Try to use invite key token but the token is invalid.") });
} else if (error.id == ErrorCode.TOKEN_EXPIRED) {
targetServerConnection.log.log("error.custom", { message: tr("Try to use invite key token but the token is expired.") });
} else if (error.id === ErrorCode.TOKEN_USE_LIMIT_EXCEEDED) {
targetServerConnection.log.log("error.custom", { message: tr("Try to use invite key token but the token has been used too many times.") });
} else {
targetServerConnection.log.log("error.custom", { message: tra("Try to use invite key token but an error occurred: {}", error.formattedMessage())});
targetServerConnection.log.log("error.custom", { message: tra("Try to use invite key token but an error occurred: {}", error.formattedMessage()) });
}
} else {
logError(LogCategory.GENERAL, tr("Failed to use token: {}"), error);
@ -257,9 +256,9 @@ async function doHandleConnectRequest(serverAddress: string, serverUniqueId: str
}
}
if(!channel) {
if (!channel) {
/* No need to join any channel */
if(!connectToken) {
if (!connectToken) {
createInfoModal(tr("Already connected"), tr("You're already connected to the target server.")).open();
} else {
/* Don't show a message since a token has been used */
@ -269,19 +268,19 @@ async function doHandleConnectRequest(serverAddress: string, serverUniqueId: str
}
const targetChannel = targetServerConnection.channelTree.resolveChannelPath(channel);
if(!targetChannel) {
if (!targetChannel) {
createErrorModal(tr("Missing target channel"), tr("Failed to join channel since it is not visible.")).open();
return { status: "channel-not-visible" };
}
if(targetServerConnection.getClient().currentChannel() === targetChannel) {
if (targetServerConnection.getClient().currentChannel() === targetChannel) {
createErrorModal(tr("Channel already joined"), tr("You already joined the channel.")).open();
return { status: "channel-already-joined" };
}
if(targetChannel.getCachedPasswordHash()) {
if (targetChannel.getCachedPasswordHash()) {
const succeeded = await targetChannel.joinChannel();
if(succeeded) {
if (succeeded) {
/* Successfully joined channel with a password we already knew */
return { status: "success" };
}
@ -289,7 +288,7 @@ async function doHandleConnectRequest(serverAddress: string, serverUniqueId: str
targetChannel.setCachedHashedPassword(channelPassword);
/* Force join the channel. Either we have the password, can ignore the password or we don't want to join. */
if(await targetChannel.joinChannel(true)) {
if (await targetChannel.joinChannel(true)) {
return { status: "success" };
} else {
/* TODO: More detail? */
@ -313,7 +312,7 @@ async function doHandleConnectRequest(serverAddress: string, serverUniqueId: str
defaultChannelPasswordHashed: passwordsHashed
}, false);
if(targetServerConnection.connected) {
if (targetServerConnection.connected) {
return { status: "success" };
} else {
/* TODO: More detail? */
@ -348,13 +347,13 @@ function main() {
/* context menu prevent */
document.addEventListener("contextmenu", event => {
if(event.defaultPrevented) {
if (event.defaultPrevented) {
return;
}
if(event.target instanceof HTMLInputElement) {
if (event.target instanceof HTMLInputElement) {
const target = event.target;
if((!!event.target.value || __build.target === "client") && !event.target.disabled && !event.target.readOnly && event.target.type !== "number") {
if ((!!event.target.value || __build.target === "client") && !event.target.disabled && !event.target.readOnly && event.target.type !== "number") {
spawn_context_menu(event.pageX, event.pageY, {
type: MenuEntryType.ENTRY,
name: tr("Copy"),
@ -377,7 +376,7 @@ function main() {
return;
}
if(settings.getValue(Settings.KEY_DISABLE_GLOBAL_CONTEXT_MENU)) {
if (settings.getValue(Settings.KEY_DISABLE_GLOBAL_CONTEXT_MENU)) {
event.preventDefault();
}
});
@ -385,15 +384,13 @@ function main() {
const initialHandler = server_connections.spawnConnectionHandler();
server_connections.setActiveConnectionHandler(initialHandler);
initialHandler.acquireInputHardware().then(() => {});
initialHandler.acquireInputHardware().then(() => { });
/** Setup the XF forum identity **/
fidentity.update_forum();
initializeKeyControl();
checkForUpdatedApp();
if(settings.getValue(Settings.KEY_USER_IS_NEW) && !preventWelcomeUI) {
if (settings.getValue(Settings.KEY_USER_IS_NEW) && !preventWelcomeUI) {
const modal = openModalNewcomer();
modal.close_listener.push(() => settings.setValue(Settings.KEY_USER_IS_NEW, false));
}
@ -408,7 +405,7 @@ const task_teaweb_starter: loader.Task = {
loader.config.abortAnimationOnFinish = settings.getValue(Settings.KEY_LOADER_ANIMATION_ABORT);
} catch (ex) {
console.error(ex.stack);
if(ex instanceof ReferenceError || ex instanceof TypeError) {
if (ex instanceof ReferenceError || ex instanceof TypeError) {
ex = ex.name + ": " + ex.message;
}
loader.critical_error("Failed to invoke main function:<br>" + ex);
@ -421,7 +418,7 @@ const task_connect_handler: loader.Task = {
name: "Connect handler",
function: async () => {
const address = AppParameters.getValue(AppParameters.KEY_CONNECT_ADDRESS, undefined);
if(typeof address === "undefined") {
if (typeof address === "undefined") {
loader.register_task(loader.Stage.LOADED, task_teaweb_starter);
return;
}
@ -440,7 +437,7 @@ const task_connect_handler: loader.Task = {
};
const chandler = getInstanceConnectHandler();
if(chandler && AppParameters.getValue(AppParameters.KEY_CONNECT_NO_SINGLE_INSTANCE)) {
if (chandler && AppParameters.getValue(AppParameters.KEY_CONNECT_NO_SINGLE_INSTANCE)) {
try {
await chandler.post_connect_request(connectData, async () => {
return await promptYesNo({
@ -459,11 +456,11 @@ const task_connect_handler: loader.Task = {
}
).open();
return;
} catch(error) {
} catch (error) {
logInfo(LogCategory.CLIENT, tr("Failed to execute connect within other TeaWeb instance. Using this one. Error: %o"), error);
}
if(chandler) {
if (chandler) {
/* no instance avail, so lets make us avail */
chandler.callback_available = () => {
return !settings.getValue(Settings.KEY_DISABLE_MULTI_SESSION);
@ -497,7 +494,7 @@ loader.register_task(loader.Stage.JAVASCRIPT_INITIALIZING, {
name: "jrendere initialize",
function: async () => {
try {
if(!setupJSRender())
if (!setupJSRender())
throw "invalid load";
} catch (error) {
loader.critical_error(tr("Failed to setup jsrender"));
@ -514,17 +511,17 @@ loader.register_task(loader.Stage.JAVASCRIPT_INITIALIZING, {
try {
await initialize();
if(__build.target == "web") {
if (__build.target == "web") {
loader.register_task(loader.Stage.LOADED, task_connect_handler);
} else {
loader.register_task(loader.Stage.LOADED, task_teaweb_starter);
}
} catch (ex) {
if(ex instanceof Error || typeof(ex.stack) !== "undefined") {
if (ex instanceof Error || typeof (ex.stack) !== "undefined") {
console.error((tr || (msg => msg))("Critical error stack trace: %o"), ex.stack);
}
if(ex instanceof ReferenceError || ex instanceof TypeError) {
if (ex instanceof ReferenceError || ex instanceof TypeError) {
ex = ex.name + ": " + ex.message;
}
@ -537,7 +534,7 @@ loader.register_task(loader.Stage.JAVASCRIPT_INITIALIZING, {
loader.register_task(loader.Stage.LOADED, {
name: "error task",
function: async () => {
if(AppParameters.getValue(AppParameters.KEY_LOAD_DUMMY_ERROR)) {
if (AppParameters.getValue(AppParameters.KEY_LOAD_DUMMY_ERROR)) {
loader.critical_error("The tea is cold!", "Argh, this is evil! Cold tea does not taste good.");
throw "The tea is cold!";
}
@ -549,7 +546,7 @@ let preventExecuteAutoConnect = false;
loader.register_task(loader.Stage.LOADED, {
priority: 0,
function: async () => {
if(preventExecuteAutoConnect) {
if (preventExecuteAutoConnect) {
return;
}

View File

@ -1,6 +1,6 @@
import {InputStartError} from "tc-shared/voice/RecorderBase";
import {LogCategory, logInfo, logWarn} from "tc-shared/log";
import {tr} from "tc-shared/i18n/localize";
import { InputStartError } from "tc-shared/voice/RecorderBase";
import { LogCategory, logInfo, logWarn } from "tc-shared/log";
import { tr } from "tc-shared/i18n/localize";
export type MediaStreamType = "audio" | "video";
@ -18,15 +18,15 @@ export interface MediaStreamEvents {
export const mediaStreamEvents = new Registry<MediaStreamEvents>();
*/
export async function requestMediaStreamWithConstraints(constraints: MediaTrackConstraints, type: MediaStreamType) : Promise<InputStartError | MediaStream> {
export async function requestMediaStreamWithConstraints(constraints: MediaTrackConstraints, type: MediaStreamType): Promise<InputStartError | MediaStream> {
const beginTimestamp = Date.now();
try {
logInfo(LogCategory.AUDIO, tr("Requesting a %s stream for device %s in group %s"), type, constraints.deviceId, constraints.groupId);
return await navigator.mediaDevices.getUserMedia(type === "audio" ? { audio: constraints } : { video: constraints });
} catch(error) {
if('name' in error) {
if(error.name === "NotAllowedError") {
if(Date.now() - beginTimestamp < 250) {
} catch (error) {
if ('name' in error) {
if (error.name === "NotAllowedError") {
if (Date.now() - beginTimestamp < 250) {
logWarn(LogCategory.AUDIO, tr("Media stream request failed (System denied). Browser message: %o"), error.message);
return InputStartError.ESYSTEMDENIED;
} else {
@ -46,21 +46,21 @@ export async function requestMediaStreamWithConstraints(constraints: MediaTrackC
/* request permission for devices only one per time! */
let currentMediaStreamRequest: Promise<MediaStream | InputStartError>;
export async function requestMediaStream(deviceId: string | undefined, groupId: string | undefined, type: MediaStreamType) : Promise<MediaStream | InputStartError> {
export async function requestMediaStream(deviceId: string | undefined, groupId: string | undefined, type: MediaStreamType): Promise<MediaStream | InputStartError> {
/* wait for the current media stream requests to finish */
while(currentMediaStreamRequest) {
while (currentMediaStreamRequest) {
try {
await currentMediaStreamRequest;
} catch(error) { }
} catch (error) { }
}
const constrains: MediaTrackConstraints = {};
if(window.detectedBrowser?.name === "firefox") {
if (window.detectedBrowser?.name === "firefox") {
/*
* Firefox only allows to open one mic/video as well deciding whats the input device it.
* It does not respect the deviceId nor the groupId
*/
} else if(deviceId !== undefined) {
} else if (deviceId !== undefined) {
constrains.deviceId = deviceId;
constrains.groupId = groupId;
} else {
@ -75,25 +75,28 @@ export async function requestMediaStream(deviceId: string | undefined, groupId:
try {
return await currentMediaStreamRequest;
} finally {
if(currentMediaStreamRequest === promise) {
if (currentMediaStreamRequest === promise) {
currentMediaStreamRequest = undefined;
}
}
}
export async function queryMediaPermissions(type: MediaStreamType, changeListener?: (value: PermissionState) => void) : Promise<PermissionState> {
if('permissions' in navigator && 'query' in navigator.permissions) {
try {
const result = await navigator.permissions.query({ name: type === "audio" ? "microphone" : "camera" });
if(changeListener) {
result.addEventListener("change", () => {
changeListener(result.state);
});
}
return result.state;
} catch (error) {
logWarn(LogCategory.GENERAL, tr("Failed to query for %s permissions: %s"), type, error);
export async function queryMediaPermissions(type: MediaStreamType, changeListener?: (value: PermissionState) => void): Promise<PermissionState> {
try {
// @ts-ignore needed, as firefox doesn't allow microphone or camera, caught using the catch below
const result = await navigator.permissions.query({ name: type === "audio" ? "microphone" : "camera" });
if (changeListener) {
result.addEventListener("change", () => {
changeListener(result.state);
});
}
return result.state;
} catch (error) {
// Firefox doesn't support querying for the camera / microphone permission, so return undetermined status
if (error instanceof TypeError) {
return "prompt";
}
logWarn(LogCategory.GENERAL, tr("Failed to query for %s permissions: %s"), type, error);
}
return "prompt";
}
@ -101,7 +104,7 @@ export async function queryMediaPermissions(type: MediaStreamType, changeListene
export function stopMediaStream(stream: MediaStream) {
stream.getVideoTracks().forEach(track => track.stop());
stream.getAudioTracks().forEach(track => track.stop());
if('stop' in stream) {
if ('stop' in stream) {
(stream as any).stop();
}
}

View File

@ -1,18 +1,17 @@
import {decode_identity, IdentitifyType, Identity} from "../profiles/Identity";
import {guid} from "../crypto/uid";
import {TeaForumIdentity} from "../profiles/identities/TeaForumIdentity";
import {TeaSpeakIdentity} from "../profiles/identities/TeamSpeakIdentity";
import {AbstractServerConnection} from "../connection/ConnectionBase";
import {HandshakeIdentityHandler} from "../connection/HandshakeHandler";
import {createErrorModal} from "../ui/elements/Modal";
import {formatMessage} from "../ui/frames/chat";
import { decode_identity, IdentitifyType, Identity } from "../profiles/Identity";
import { guid } from "../crypto/uid";
import { TeaSpeakIdentity } from "../profiles/identities/TeamSpeakIdentity";
import { AbstractServerConnection } from "../connection/ConnectionBase";
import { HandshakeIdentityHandler } from "../connection/HandshakeHandler";
import { createErrorModal } from "../ui/elements/Modal";
import { formatMessage } from "../ui/frames/chat";
import * as loader from "tc-loader";
import {Stage} from "tc-loader";
import {LogCategory, logDebug, logError} from "tc-shared/log";
import {tr} from "tc-shared/i18n/localize";
import {getStorageAdapter} from "tc-shared/StorageAdapter";
import {ignorePromise} from "tc-shared/proto";
import {assertMainApplication} from "tc-shared/ui/utils";
import { Stage } from "tc-loader";
import { LogCategory, logDebug, logError } from "tc-shared/log";
import { tr } from "tc-shared/i18n/localize";
import { getStorageAdapter } from "tc-shared/StorageAdapter";
import { ignorePromise } from "tc-shared/proto";
import { assertMainApplication } from "tc-shared/ui/utils";
/*
* We're loading & saving profiles with the StorageAdapter.
@ -52,9 +51,7 @@ export class ConnectionProfile {
if (current_type === undefined)
return undefined;
if (current_type == IdentitifyType.TEAFORO) {
return TeaForumIdentity.identity();
} else if (current_type == IdentitifyType.TEAMSPEAK || current_type == IdentitifyType.NICKNAME) {
if (current_type == IdentitifyType.TEAMSPEAK || current_type == IdentitifyType.NICKNAME) {
return this.identities[IdentitifyType[current_type].toLowerCase()];
}
@ -144,7 +141,7 @@ async function loadConnectProfiles() {
const profiles_json = await getStorageAdapter().get("profiles");
let profiles_data: ProfilesData = (() => {
try {
return profiles_json ? JSON.parse(profiles_json) : {version: 0} as any;
return profiles_json ? JSON.parse(profiles_json) : { version: 0 } as any;
} catch (error) {
logError(LogCategory.IDENTITIES, tr("Invalid profile json! Resetting profiles :( (%o)"), profiles_json);
createErrorModal(tr("Profile data invalid"), formatMessage(tr("The profile data is invalid.{:br:}This might cause data loss."))).open();
@ -170,7 +167,7 @@ async function loadConnectProfiles() {
}
const defaultProfile = findConnectProfile("default");
if (!defaultProfile) { //Create a default profile and teaforo profile
if (!defaultProfile) { //Create a default profile
{
const profile = createConnectProfile(tr("Default Profile"), "default");
profile.defaultPassword = "";
@ -194,15 +191,6 @@ async function loadConnectProfiles() {
}
}
{ /* forum identity (works only when connected to the forum) */
const profile = createConnectProfile(tr("TeaSpeak Forum Profile"), "teaforo");
profile.defaultPassword = "";
profile.defaultUsername = "";
profile.setIdentity(IdentitifyType.TEAFORO, TeaForumIdentity.identity());
profile.selectedIdentityType = IdentitifyType[IdentitifyType.TEAFORO];
}
save();
}
}
@ -280,7 +268,7 @@ export function delete_profile(profile: ConnectionProfile) {
}
window.addEventListener("beforeunload", event => {
if(requires_save()) {
if (requires_save()) {
save();
}
});

View File

@ -1,51 +1,46 @@
import {AbstractServerConnection, ServerCommand} from "../connection/ConnectionBase";
import {HandshakeIdentityHandler} from "../connection/HandshakeHandler";
import {AbstractCommandHandler} from "../connection/AbstractCommandHandler";
import {LogCategory, logError, logWarn} from "tc-shared/log";
import {tr} from "tc-shared/i18n/localize";
import { AbstractServerConnection, ServerCommand } from "../connection/ConnectionBase";
import { HandshakeIdentityHandler } from "../connection/HandshakeHandler";
import { AbstractCommandHandler } from "../connection/AbstractCommandHandler";
import { LogCategory, logError, logWarn } from "tc-shared/log";
import { tr } from "tc-shared/i18n/localize";
export enum IdentitifyType {
TEAFORO,
TEAMSPEAK,
NICKNAME
}
export interface Identity {
fallback_name(): string | undefined ;
uid() : string;
type() : IdentitifyType;
fallback_name(): string | undefined;
uid(): string;
type(): IdentitifyType;
valid() : boolean;
valid(): boolean;
encode?() : string;
decode(data: string) : Promise<void>;
encode?(): string;
decode(data: string): Promise<void>;
spawn_identity_handshake_handler(connection: AbstractServerConnection) : HandshakeIdentityHandler;
spawn_identity_handshake_handler(connection: AbstractServerConnection): HandshakeIdentityHandler;
}
/* avoid circular dependencies here */
export async function decode_identity(type: IdentitifyType, data: string) : Promise<Identity> {
export async function decode_identity(type: IdentitifyType, data: string): Promise<Identity> {
let identity: Identity;
switch (type) {
case IdentitifyType.NICKNAME:
const nidentity = require("tc-shared/profiles/identities/NameIdentity");
identity = new nidentity.NameIdentity();
break;
case IdentitifyType.TEAFORO:
const fidentity = require("tc-shared/profiles/identities/TeaForumIdentity");
identity = new fidentity.TeaForumIdentity(undefined);
break;
case IdentitifyType.TEAMSPEAK:
const tidentity = require("tc-shared/profiles/identities/TeamSpeakIdentity");
identity = new tidentity.TeaSpeakIdentity(undefined, undefined);
break;
}
if(!identity)
if (!identity)
return undefined;
try {
await identity.decode(data)
} catch(error) {
} catch (error) {
logError(LogCategory.IDENTITIES, tr("Failed to decode identity: %o"), error);
return undefined;
}
@ -60,10 +55,6 @@ export function create_identity(type: IdentitifyType) {
const nidentity = require("tc-shared/profiles/identities/NameIdentity");
identity = new nidentity.NameIdentity();
break;
case IdentitifyType.TEAFORO:
const fidentity = require("tc-shared/profiles/identities/TeaForumIdentity");
identity = new fidentity.TeaForumIdentity(undefined);
break;
case IdentitifyType.TEAMSPEAK:
const tidentity = require("tc-shared/profiles/identities/TeamSpeakIdentity");
identity = new tidentity.TeaSpeakIdentity(undefined, undefined);
@ -82,9 +73,9 @@ export class HandshakeCommandHandler<T extends AbstractHandshakeIdentityHandler>
handle_command(command: ServerCommand): boolean {
if(typeof this[command.command] === "function") {
if (typeof this[command.command] === "function") {
this[command.command](command.arguments);
} else if(command.command == "error") {
} else if (command.command == "error") {
return false;
} else {
logWarn(LogCategory.IDENTITIES, tr("Received unknown command while handshaking (%o)"), command);
@ -111,12 +102,12 @@ export abstract class AbstractHandshakeIdentityHandler implements HandshakeIdent
abstract executeHandshake();
protected trigger_success() {
for(const callback of this.callbacks)
for (const callback of this.callbacks)
callback(true);
}
protected trigger_fail(message: string) {
for(const callback of this.callbacks)
for (const callback of this.callbacks)
callback(false, message);
}
}

View File

@ -1,135 +0,0 @@
import {
AbstractHandshakeIdentityHandler,
HandshakeCommandHandler,
IdentitifyType,
Identity
} from "../../profiles/Identity";
import {LogCategory, logError} from "../../log";
import {CommandResult} from "../../connection/ServerConnectionDeclaration";
import {AbstractServerConnection} from "../../connection/ConnectionBase";
import {HandshakeIdentityHandler} from "../../connection/HandshakeHandler";
import * as forum from "./teaspeak-forum";
import { tr } from "tc-shared/i18n/localize";
class TeaForumHandshakeHandler extends AbstractHandshakeIdentityHandler {
readonly identity: TeaForumIdentity;
handler: HandshakeCommandHandler<TeaForumHandshakeHandler>;
constructor(connection: AbstractServerConnection, identity: TeaForumIdentity) {
super(connection);
this.identity = identity;
this.handler = new HandshakeCommandHandler(connection, this);
this.handler["handshakeidentityproof"] = this.handle_proof.bind(this);
}
executeHandshake() {
this.connection.getCommandHandler().registerHandler(this.handler);
this.connection.send_command("handshakebegin", {
intention: 0,
authentication_method: this.identity.type(),
data: this.identity.data().data_json()
}).catch(error => {
logError(LogCategory.IDENTITIES, tr("Failed to initialize TeaForum based handshake. Error: %o"), error);
if(error instanceof CommandResult)
error = error.extra_message || error.message;
this.trigger_fail("failed to execute begin (" + error + ")");
});
}
private handle_proof(json) {
this.connection.send_command("handshakeindentityproof", {
proof: this.identity.data().data_sign()
}).catch(error => {
logError(LogCategory.IDENTITIES, tr("Failed to proof the identity. Error: %o"), error);
if(error instanceof CommandResult)
error = error.extra_message || error.message;
this.trigger_fail("failed to execute proof (" + error + ")");
}).then(() => this.trigger_success());
}
protected trigger_fail(message: string) {
this.connection.getCommandHandler().unregisterHandler(this.handler);
super.trigger_fail(message);
}
protected trigger_success() {
this.connection.getCommandHandler().unregisterHandler(this.handler);
super.trigger_success();
}
}
export class TeaForumIdentity implements Identity {
private readonly identity_data: forum.Data;
valid() : boolean {
return !!this.identity_data && !this.identity_data.is_expired();
}
constructor(data: forum.Data) {
this.identity_data = data;
}
data() {
return this.identity_data;
}
decode(data) : Promise<void> {
data = JSON.parse(data);
if(data.version !== 1)
throw "invalid version";
return;
}
encode() : string {
return JSON.stringify({
version: 1
});
}
spawn_identity_handshake_handler(connection: AbstractServerConnection) : HandshakeIdentityHandler {
return new TeaForumHandshakeHandler(connection, this);
}
fallback_name(): string | undefined {
return this.identity_data ? this.identity_data.name() : undefined;
}
type(): IdentitifyType {
return IdentitifyType.TEAFORO;
}
uid(): string {
//FIXME: Real UID!
return "TeaForo#" + ((this.identity_data ? this.identity_data.name() : "Another TeaSpeak user"));
}
public static identity() {
return static_identity;
}
}
let static_identity: TeaForumIdentity;
export function set_static_identity(identity: TeaForumIdentity) {
static_identity = identity;
}
export function update_forum() {
if(forum.logged_in() && (!static_identity || static_identity.data() !== forum.data())) {
static_identity = new TeaForumIdentity(forum.data());
} else {
static_identity = undefined;
}
}
export function valid_static_forum_identity() : boolean {
return static_identity && static_identity.valid();
}
export function static_forum_identity() : TeaForumIdentity | undefined {
return static_identity;
}

View File

@ -1,399 +0,0 @@
import {settings, Settings} from "../../settings";
import * as loader from "tc-loader";
import * as fidentity from "./TeaForumIdentity";
import {LogCategory, logDebug, logError, logInfo, logWarn} from "../../log";
import {tr} from "tc-shared/i18n/localize";
import {getStorageAdapter} from "tc-shared/StorageAdapter";
/* TODO: Properly redesign this whole system! */
declare global {
interface Window {
grecaptcha: GReCaptcha;
}
}
interface GReCaptcha {
render(container: string | HTMLElement, parameters: {
sitekey: string;
theme?: "dark" | "light";
size?: "compact" | "normal";
tabindex?: number;
callback?: (token: string) => any;
"expired-callback"?: () => any;
"error-callback"?: (error: any) => any;
}) : string; /* widget_id */
reset(widget_id?: string);
}
export namespace gcaptcha {
export async function initialize() {
if(typeof(window.grecaptcha) === "undefined") {
let script = document.createElement("script");
script.async = true;
let timeout;
const callback_name = "captcha_callback_" + Math.random().toString().replace(".", "");
try {
await new Promise((resolve, reject) => {
script.onerror = reject;
window[callback_name] = resolve;
script.src = "https://www.google.com/recaptcha/api.js?onload=" + encodeURIComponent(callback_name) + "&render=explicit";
document.body.append(script);
timeout = setTimeout(() => reject("timeout"), 15000);
});
} catch(error) {
script.remove();
script = undefined;
logError(LogCategory.GENERAL, tr("Failed to fetch recaptcha javascript source: %o"), error);
throw tr("failed to download source");
} finally {
if(script)
script.onerror = undefined;
delete window[callback_name];
timeout && clearTimeout(timeout);
}
}
if(typeof(window.grecaptcha) === "undefined") {
throw tr("failed to load recaptcha");
}
}
export async function spawn(container: JQuery, key: string, callback_data: (token: string) => any) {
try {
await initialize();
} catch(error) {
logError(LogCategory.GENERAL, tr("Failed to initialize G-Recaptcha. Error: %o"), error);
throw tr("initialisation failed");
}
if(container.attr("captcha-uuid"))
window.grecaptcha.reset(container.attr("captcha-uuid"));
else {
container.attr("captcha-uuid", window.grecaptcha.render(container[0], {
"sitekey": key,
callback: callback_data
}));
}
}
}
function getForumApiURL() {
return settings.getValue(Settings.KEY_TEAFORO_URL);
}
export class Data {
readonly auth_key: string;
readonly raw: string;
readonly sign: string;
parsed: {
user_id: number;
user_name: string;
data_age: number;
user_group_id: number;
is_staff: boolean;
user_groups: number[];
};
constructor(auth: string, raw: string, sign: string) {
this.auth_key = auth;
this.raw = raw;
this.sign = sign;
this.parsed = JSON.parse(raw);
}
data_json() : string { return this.raw; }
data_sign() : string { return this.sign; }
name() : string { return this.parsed.user_name; }
user_id() { return this.parsed.user_id; }
user_group() { return this.parsed.user_group_id; }
is_stuff() : boolean { return this.parsed.is_staff; }
is_premium() : boolean { return this.parsed.user_groups.indexOf(5) != -1; }
data_age() : Date { return new Date(this.parsed.data_age); }
is_expired() : boolean { return this.parsed.data_age + 48 * 60 * 60 * 1000 < Date.now(); }
should_renew() : boolean { return this.parsed.data_age + 24 * 60 * 60 * 1000 < Date.now(); } /* renew data all 24hrs */
}
let forumData: Data | undefined;
export function logged_in() : boolean {
return !!forumData && !forumData.is_expired();
}
export function data() : Data { return forumData; }
export interface LoginResult {
status: "success" | "captcha" | "error";
error_message?: string;
captcha?: {
type: "gre-captcha" | "unknown";
data: any; /* in case of gre-captcha it would be the side key */
};
}
export async function login(username: string, password: string, captcha?: any) : Promise<LoginResult> {
let response;
try {
response = await new Promise<any>((resolve, reject) => {
$.ajax({
url: getForumApiURL() + "?web-api/v1/login",
type: "POST",
cache: false,
data: {
username: username,
password: password,
remember: true,
"g-recaptcha-response": captcha
},
crossDomain: true,
success: resolve,
error: (xhr, status, error) => {
logDebug(LogCategory.GENERAL, tr("Login request failed %o: %o"), status, error);
reject(tr("request failed"));
}
})
});
} catch(error) {
return {
status: "error",
error_message: tr("failed to send login request")
};
}
if(response["status"] !== "ok") {
logError(LogCategory.GENERAL, tr("Response status not okey. Error happend: %o"), response);
return {
status: "error",
error_message: (response["errors"] || [])[0] || tr("Unknown error")
};
}
if(!response["success"]) {
logError(LogCategory.GENERAL, tr("Login failed. Response %o"), response);
let message = tr("failed to login");
let captcha;
/* user/password wrong | and maybe captcha required */
if(response["code"] == 1 || response["code"] == 3)
message = tr("Invalid username or password");
if(response["code"] == 2 || response["code"] == 3) {
captcha = {
type: response["captcha"]["type"],
data: response["captcha"]["siteKey"] //TODO: Why so static here?
};
if(response["code"] == 2)
message = tr("captcha required");
}
return {
status: typeof(captcha) !== "undefined" ? "captcha" : "error",
error_message: message,
captcha: captcha
};
}
//document.cookie = "user_data=" + response["data"] + ";path=/";
//document.cookie = "user_sign=" + response["sign"] + ";path=/";
try {
forumData = new Data(response["auth-key"], response["data"], response["sign"]);
const adapter = getStorageAdapter();
await adapter.set("teaspeak-forum-data", response["data"]);
await adapter.set("teaspeak-forum-sign", response["sign"]);
await adapter.set("teaspeak-forum-auth", response["auth-key"]);
fidentity.update_forum();
} catch(error) {
logError(LogCategory.GENERAL, tr("Failed to parse forum given data: %o"), error);
return {
status: "error",
error_message: tr("Failed to parse response data")
}
}
return {
status: "success"
};
}
async function resetForumLocalData() {
const adapter = getStorageAdapter();
await adapter.delete("teaspeak-forum-data");
await adapter.delete("teaspeak-forum-sign");
await adapter.delete("teaspeak-forum-auth");
}
export async function renew_data() : Promise<"success" | "login-required"> {
let response;
try {
response = await new Promise<any>((resolve, reject) => {
$.ajax({
url: getForumApiURL() + "?web-api/v1/renew-data",
type: "GET",
cache: false,
crossDomain: true,
data: {
"auth-key": forumData.auth_key
},
success: resolve,
error: (xhr, status, error) => {
logError(LogCategory.GENERAL, tr("Renew request failed %o: %o"), status, error);
reject(tr("request failed"));
}
})
});
} catch(error) {
throw tr("failed to send renew request");
}
if(response["status"] !== "ok") {
logError(LogCategory.GENERAL, tr("Response status not okey. Error happend: %o"), response);
throw (response["errors"] || [])[0] || tr("Unknown error");
}
if(!response["success"]) {
if(response["code"] == 1) {
return "login-required";
}
throw "invalid error code (" + response["code"] + ")";
}
if(!response["data"] || !response["sign"])
throw tr("response missing data");
logDebug(LogCategory.GENERAL, tr("Renew succeeded. Parsing data."));
try {
forumData = new Data(forumData.auth_key, response["data"], response["sign"]);
await getStorageAdapter().set("teaspeak-forum-data", response["data"]);
await getStorageAdapter().set("teaspeak-forum-sign", response["sign"]);
fidentity.update_forum();
} catch(error) {
logError(LogCategory.GENERAL, tr("Failed to parse forum given data: %o"), error);
throw tr("failed to parse data");
}
return "success";
}
export async function logout() : Promise<void> {
if(!logged_in()) {
return;
}
let response;
try {
response = await new Promise<any>((resolve, reject) => {
$.ajax({
url: getForumApiURL() + "?web-api/v1/logout",
type: "GET",
cache: false,
crossDomain: true,
data: {
"auth-key": forumData.auth_key
},
success: resolve,
error: (xhr, status, error) => {
logInfo(LogCategory.GENERAL, tr("Logout request failed %o: %o"), status, error);
reject(tr("request failed"));
}
})
});
} catch(error) {
throw tr("failed to send logout request");
}
if(response["status"] !== "ok") {
logError(LogCategory.GENERAL, tr("Response status not ok. Error happened: %o"), response);
throw (response["errors"] || [])[0] || tr("Unknown error");
}
if(!response["success"]) {
/* code 1 means not logged in, its an success */
if(response["code"] != 1) {
throw "invalid error code (" + response["code"] + ")";
}
}
forumData = undefined;
await resetForumLocalData();
fidentity.update_forum();
}
loader.register_task(loader.Stage.JAVASCRIPT_INITIALIZING, {
name: "TeaForo initialize",
priority: 10,
function: async () => {
const rawData = await getStorageAdapter().get("teaspeak-forum-data");
const rawSign = await getStorageAdapter().get("teaspeak-forum-sign");
const rawForumAuth = await getStorageAdapter().get("teaspeak-forum-auth");
if(!rawData || !rawSign || !rawForumAuth) {
logInfo(LogCategory.GENERAL, tr("No TeaForo authentication found. TeaForo connection status: unconnected"));
return;
}
try {
forumData = new Data(rawForumAuth, rawData, rawSign);
} catch(error) {
logError(LogCategory.GENERAL, tr("Failed to initialize TeaForo connection from local data. Error: %o"), error);
return;
}
if(forumData.should_renew()) {
logInfo(LogCategory.GENERAL, tr("TeaForo data should be renewed. Executing renew."));
renew_data().then(async status => {
if(status === "success") {
logInfo(LogCategory.GENERAL, tr("TeaForo data has been successfully renewed."));
} else {
logWarn(LogCategory.GENERAL, tr("Failed to renew TeaForo data. New login required."));
await resetForumLocalData();
}
}).catch(error => {
logWarn(LogCategory.GENERAL, tr("Failed to renew TeaForo data. An error occurred: %o"), error);
});
return;
}
if(forumData && forumData.is_expired()) {
logError(LogCategory.GENERAL, tr("TeaForo data is expired. TeaForo connection isn't available!"));
}
setInterval(() => {
/* if we don't have any _data object set we could not renew anything */
if(forumData) {
logInfo(LogCategory.IDENTITIES, tr("Renewing TeaForo data."));
renew_data().then(async status => {
if(status === "success") {
logInfo(LogCategory.IDENTITIES,tr("TeaForo data has been successfully renewed."));
} else {
logWarn(LogCategory.IDENTITIES,tr("Failed to renew TeaForo data. New login required."));
await resetForumLocalData();
}
}).catch(error => {
logWarn(LogCategory.GENERAL, tr("Failed to renew TeaForo data. An error occurred: %o"), error);
});
}
}, 24 * 60 * 60 * 1000);
}
});

View File

@ -1,7 +1,7 @@
/* setup jsrenderer */
import "jsrender";
import {tr} from "./i18n/localize";
import {LogCategory, logError, logTrace} from "tc-shared/log";
import { tr } from "./i18n/localize";
import { LogCategory, logError, logTrace } from "tc-shared/log";
(window as any).$ = require("jquery");
(window as any).jQuery = $;
@ -22,7 +22,7 @@ declare global {
* @param entry The entry to toggle
* @returns `true` if the entry has been inserted and false if the entry has been deleted
*/
toggle(entry: T) : boolean;
toggle(entry: T): boolean;
/**
* @param entry The entry to toggle
@ -33,21 +33,21 @@ declare global {
}
interface JSON {
map_to<T>(object: T, json: any, variables?: string | string[], validator?: (map_field: string, map_value: string) => boolean, variable_direction?: number) : number;
map_field_to<T>(object: T, value: any, field: string) : boolean;
map_to<T>(object: T, json: any, variables?: string | string[], validator?: (map_field: string, map_value: string) => boolean, variable_direction?: number): number;
map_field_to<T>(object: T, value: any, field: string): boolean;
}
type JQueryScrollType = "height" | "width";
interface JQuery<TElement = HTMLElement> {
renderTag(values?: any) : JQuery<TElement>;
hasScrollBar(direction?: JQueryScrollType) : boolean;
renderTag(values?: any): JQuery<TElement>;
hasScrollBar(direction?: JQueryScrollType): boolean;
visible_height() : number;
visible_width() : number;
visible_height(): number;
visible_width(): number;
/* first element which matches the selector, could be the element itself or a parent */
firstParent(selector: string) : JQuery;
firstParent(selector: string): JQuery;
}
interface JQueryStatic<TElement extends Node = HTMLElement> {
@ -73,9 +73,6 @@ declare global {
name: string,
version: string
};
mozGetUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void;
webkitGetUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void;
}
interface ObjectConstructor {
@ -83,9 +80,9 @@ declare global {
}
}
export type IfEquals<X, Y, A=X, B=never> =
export type IfEquals<X, Y, A = X, B = never> =
(<T>() => T extends X ? 1 : 2) extends
(<T>() => T extends Y ? 1 : 2) ? A : B;
(<T>() => T extends Y ? 1 : 2) ? A : B;
export type WritableKeys<T> = {
[P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P, never>
@ -95,7 +92,7 @@ export type ReadonlyKeys<T> = {
[P in keyof T]: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, never, P>
}[keyof T];
if(!Object.isSimilar) {
if (!Object.isSimilar) {
Object.isSimilar = function (a, b) {
const aType = typeof a;
const bType = typeof b;
@ -106,8 +103,8 @@ if(!Object.isSimilar) {
if (aType === "object") {
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
if(aKeys.length != bKeys.length) { return false; }
if(aKeys.findIndex(key => bKeys.indexOf(key) !== -1) !== -1) { return false; }
if (aKeys.length != bKeys.length) { return false; }
if (aKeys.findIndex(key => bKeys.indexOf(key) !== -1) !== -1) { return false; }
return aKeys.findIndex(key => !Object.isSimilar(a[key], b[key])) === -1;
} else {
return a === b;
@ -115,7 +112,7 @@ if(!Object.isSimilar) {
};
}
if(!JSON.map_to) {
if (!JSON.map_to) {
JSON.map_to = function <T>(object: T, json: any, variables?: string | string[], validator?: (map_field: string, map_value: string) => boolean, variable_direction?: number): number {
if (!validator)
validator = () => true;
@ -145,29 +142,29 @@ if(!JSON.map_to) {
continue;
}
if(JSON.map_field_to(object, json[field], field))
if (JSON.map_field_to(object, json[field], field))
updates++;
}
return updates;
}
}
if(!JSON.map_field_to) {
JSON.map_field_to = function<T>(object: T, value: any, field: string) : boolean {
if (!JSON.map_field_to) {
JSON.map_field_to = function <T>(object: T, value: any, field: string): boolean {
let fieldType = typeof object[field];
let newValue;
if(fieldType == "string" || fieldType == "object" || fieldType == "undefined") {
if (fieldType == "string" || fieldType == "object" || fieldType == "undefined") {
newValue = value;
} else if(fieldType == "number") {
} else if (fieldType == "number") {
newValue = parseFloat(value);
} else if(fieldType == "boolean") {
} else if (fieldType == "boolean") {
newValue = typeof value === "boolean" && value || value === "1" || value === "true";
} else {
console.warn(tr("Invalid object type %s for entry %s"), fieldType, field);
return false;
}
if(newValue === object[field]) {
if (newValue === object[field]) {
return false;
}
@ -177,7 +174,7 @@ if(!JSON.map_field_to) {
}
if (!Array.prototype.remove) {
Array.prototype.remove = function<T>(elem?: T): boolean {
Array.prototype.remove = function <T>(elem?: T): boolean {
const index = this.indexOf(elem);
if (index > -1) {
this.splice(index, 1);
@ -188,18 +185,18 @@ if (!Array.prototype.remove) {
}
if (!Array.prototype.pop_front) {
Array.prototype.pop_front = function<T>(): T {
if(this.length == 0) return undefined;
Array.prototype.pop_front = function <T>(): T {
if (this.length == 0) return undefined;
return this.splice(0, 1)[0];
}
}
if (!Array.prototype.toggle) {
Array.prototype.toggle = function<T>(element: T, insert?: boolean): boolean {
Array.prototype.toggle = function <T>(element: T, insert?: boolean): boolean {
const index = this.findIndex(e => e === element);
if((index !== -1) === insert) {
if ((index !== -1) === insert) {
return false;
} else if(index === -1) {
} else if (index === -1) {
this.push(element);
return true;
} else {
@ -209,25 +206,25 @@ if (!Array.prototype.toggle) {
}
}
if (!Array.prototype.last){
Array.prototype.last = function(){
if(this.length == 0) return undefined;
if (!Array.prototype.last) {
Array.prototype.last = function () {
if (this.length == 0) return undefined;
return this[this.length - 1];
};
}
if(typeof ($) !== "undefined") {
if(!$.spawn) {
$.spawn = function<K extends keyof HTMLElementTagNameMap>(tagName: K): JQuery<HTMLElementTagNameMap[K]> {
if (typeof ($) !== "undefined") {
if (!$.spawn) {
$.spawn = function <K extends keyof HTMLElementTagNameMap>(tagName: K): JQuery<HTMLElementTagNameMap[K]> {
return $(document.createElement(tagName) as any);
}
}
if(!$.fn.renderTag) {
$.fn.renderTag = function (this: JQuery, values?: any) : JQuery {
if (!$.fn.renderTag) {
$.fn.renderTag = function (this: JQuery, values?: any): JQuery {
let result;
const template = $.views.templates[this.attr("id")];
if(!template) {
if (!template) {
console.error("Tried to render template %o, but template is not available!", this.attr("id"));
throw "missing template " + this.attr("id");
}
@ -243,30 +240,30 @@ if(typeof ($) !== "undefined") {
return result;
}
}
if(!$.fn.hasScrollBar)
$.fn.hasScrollBar = function(direction?: "height" | "width") {
if(this.length <= 0)
if (!$.fn.hasScrollBar)
$.fn.hasScrollBar = function (direction?: "height" | "width") {
if (this.length <= 0)
return false;
const scroll_height = this.get(0).scrollHeight > this.height();
const scroll_width = this.get(0).scrollWidth > this.width();
if(typeof(direction) === "string") {
if(direction === "height")
if (typeof (direction) === "string") {
if (direction === "height")
return scroll_height;
if(direction === "width")
if (direction === "width")
return scroll_width;
}
return scroll_width || scroll_height;
};
if(!$.fn.visible_height)
if (!$.fn.visible_height)
$.fn.visible_height = function (this: JQuery<HTMLElement>) {
const original_style = this.attr("style");
this.css({
position: 'absolute!important',
position: 'absolute!important',
visibility: 'hidden!important',
display: 'block!important'
display: 'block!important'
});
const result = this.height();
@ -274,13 +271,13 @@ if(typeof ($) !== "undefined") {
return result;
};
if(!$.fn.visible_width)
if (!$.fn.visible_width)
$.fn.visible_width = function (this: JQuery<HTMLElement>) {
const original_style = this.attr("style");
this.css({
position: 'absolute!important',
position: 'absolute!important',
visibility: 'hidden!important',
display: 'block!important'
display: 'block!important'
});
const result = this.width();
@ -288,20 +285,20 @@ if(typeof ($) !== "undefined") {
return result;
};
if(!$.fn.firstParent)
if (!$.fn.firstParent)
$.fn.firstParent = function (this: JQuery<HTMLElement>, selector: string) {
if(this.is(selector))
if (this.is(selector))
return this;
return this.parent(selector);
}
}
if(!Object.values) {
if (!Object.values) {
Object.values = object => Object.keys(object).map(e => object[e]);
}
export function crashOnThrow<T>(promise: Promise<T> | (() => Promise<T>)) : Promise<T> {
if(typeof promise === "function") {
export function crashOnThrow<T>(promise: Promise<T> | (() => Promise<T>)): Promise<T> {
if (typeof promise === "function") {
try {
promise = promise();
} catch (error) {
@ -314,11 +311,11 @@ export function crashOnThrow<T>(promise: Promise<T> | (() => Promise<T>)) : Prom
logError(LogCategory.GENERAL, tr("Critical app error: %o"), error);
/* Lets make this promise stuck for ever */
return new Promise(() => {});
return new Promise(() => { });
});
}
export function ignorePromise<T>(_promise: Promise<T>) {}
export function ignorePromise<T>(_promise: Promise<T>) { }
export function NoThrow(target: any, methodName: string, descriptor: PropertyDescriptor) {
const crashApp = error => {
@ -332,13 +329,13 @@ export function NoThrow(target: any, methodName: string, descriptor: PropertyDes
descriptor.value = function () {
try {
const result = originalMethod.apply(this, arguments);
if(result instanceof Promise) {
if (result instanceof Promise) {
promiseAccepted.value = true;
return result.catch(error => {
crashApp(error);
/* Lets make this promise stuck for ever since we're in a not well defined state */
return new Promise(() => {});
return new Promise(() => { });
});
}
@ -346,14 +343,14 @@ export function NoThrow(target: any, methodName: string, descriptor: PropertyDes
} catch (error) {
crashApp(error);
if(!promiseAccepted.value) {
if (!promiseAccepted.value) {
throw error;
} else {
/*
* We don't know if we can return a promise or if just the object is expected.
* Since we don't know that, we're just rethrowing the error for now.
*/
return new Promise(() => {});
return new Promise(() => { });
}
}
};
@ -365,7 +362,7 @@ export function CallOnce(target: any, methodName: string, descriptor: PropertyDe
const originalMethod: Function = descriptor.value;
descriptor.value = function () {
if(callOnceData[methodName]) {
if (callOnceData[methodName]) {
debugger;
throw "method " + methodName + " has already been called";
}
@ -378,7 +375,7 @@ const kNonNullSymbol = Symbol("non-null-data");
export function NonNull(target: any, methodName: string, parameterIndex: number) {
const nonNullInfo = target[kNonNullSymbol] || (target[kNonNullSymbol] = {});
const methodInfo = nonNullInfo[methodName] || (nonNullInfo[methodName] = {});
if(!Array.isArray(methodInfo.indexes)) {
if (!Array.isArray(methodInfo.indexes)) {
/* Initialize method info */
methodInfo.overloaded = false;
methodInfo.indexes = [];
@ -386,7 +383,7 @@ export function NonNull(target: any, methodName: string, parameterIndex: number)
methodInfo.indexes.push(parameterIndex);
setImmediate(() => {
if(methodInfo.overloaded || methodInfo.missingWarned) {
if (methodInfo.overloaded || methodInfo.missingWarned) {
return;
}
@ -401,21 +398,21 @@ export function NonNull(target: any, methodName: string, parameterIndex: number)
*/
export function ParameterConstrained(target: any, methodName: string, descriptor: PropertyDescriptor) {
const nonNullInfo = target[kNonNullSymbol];
if(!nonNullInfo) {
if (!nonNullInfo) {
return;
}
const methodInfo = nonNullInfo[methodName] || (nonNullInfo[methodName] = {});
if(!methodInfo) {
if (!methodInfo) {
return;
}
methodInfo.overloaded = true;
const originalMethod: Function = descriptor.value;
descriptor.value = function () {
for(let index = 0; index < methodInfo.indexes.length; index++) {
for (let index = 0; index < methodInfo.indexes.length; index++) {
const argument = arguments[methodInfo.indexes[index]];
if(typeof argument === undefined || typeof argument === null) {
if (typeof argument === undefined || typeof argument === null) {
throw "parameter " + methodInfo.indexes[index] + " should not be null or undefined";
}
}

View File

@ -1,10 +1,10 @@
import {LogCategory, logError, logInfo, logTrace} from "./log";
import { LogCategory, logError, logInfo, logTrace } from "./log";
import * as loader from "tc-loader";
import {Stage} from "tc-loader";
import {Registry} from "./events";
import {tr} from "./i18n/localize";
import {CallOnce, ignorePromise} from "tc-shared/proto";
import {getStorageAdapter} from "tc-shared/StorageAdapter";
import { Stage } from "tc-loader";
import { Registry } from "./events";
import { tr } from "./i18n/localize";
import { CallOnce, ignorePromise } from "tc-shared/proto";
import { getStorageAdapter } from "tc-shared/StorageAdapter";
/*
* TODO: Sync settings across renderer instances
@ -14,17 +14,17 @@ export type RegistryValueType = boolean | number | string | object;
export type RegistryValueTypeNames = "boolean" | "number" | "string" | "object";
export type RegistryValueTypeMapping<T> = T extends boolean ? "boolean" :
T extends number ? "number" :
T extends string ? "string" :
T extends object ? "object" :
never;
T extends number ? "number" :
T extends string ? "string" :
T extends object ? "object" :
never;
export interface RegistryKey<ValueType extends RegistryValueType> {
key: string;
valueType: RegistryValueTypeMapping<ValueType>;
fallbackKeys?: string | string[];
fallbackImports?: {[key: string]:(value: string) => ValueType};
fallbackImports?: { [key: string]: (value: string) => ValueType };
description?: string;
@ -37,7 +37,7 @@ export interface ValuedRegistryKey<ValueType extends RegistryValueType> extends
const UPDATE_DIRECT: boolean = true;
function decodeValueFromString<T extends RegistryValueType>(input: string, type: RegistryValueTypeMapping<T>) : T {
function decodeValueFromString<T extends RegistryValueType>(input: string, type: RegistryValueTypeMapping<T>): T {
switch (type) {
case "string":
return input as any;
@ -60,7 +60,7 @@ function decodeValueFromString<T extends RegistryValueType>(input: string, type:
}
}
export function encodeSettingValueToString<T extends RegistryValueType>(input: T) : string {
export function encodeSettingValueToString<T extends RegistryValueType>(input: T): string {
switch (typeof input) {
case "string":
return input;
@ -83,24 +83,24 @@ export function resolveSettingKey<ValueType extends RegistryValueType, DefaultTy
key: RegistryKey<ValueType>,
resolver: (key: string) => string | undefined | null,
defaultValue: DefaultType
) : ValueType | DefaultType {
): ValueType | DefaultType {
let value = resolver(key.key);
const keys = [key.key];
if(Array.isArray(key.fallbackKeys)) {
if (Array.isArray(key.fallbackKeys)) {
keys.push(...key.fallbackKeys);
}
for(const resolveKey of keys) {
for (const resolveKey of keys) {
value = resolver(resolveKey);
if(typeof value !== "string") {
if (typeof value !== "string") {
continue;
}
switch (key.valueType) {
case "number":
case "boolean":
if(value.length === 0) {
if (value.length === 0) {
continue;
}
break;
@ -109,9 +109,9 @@ export function resolveSettingKey<ValueType extends RegistryValueType, DefaultTy
break;
}
if(key.fallbackImports) {
if (key.fallbackImports) {
const fallbackValueImporter = key.fallbackImports[resolveKey];
if(fallbackValueImporter) {
if (fallbackValueImporter) {
return fallbackValueImporter(value);
}
}
@ -129,21 +129,21 @@ export class UrlParameterParser {
this.url = url;
}
private getParameter(key: string) : string | undefined {
private getParameter(key: string): string | undefined {
const value = this.url.searchParams.get(key);
if(value === null) {
if (value === null) {
return undefined;
}
return decodeURIComponent(value);
}
getValue<V extends RegistryValueType, DV>(key: RegistryKey<V>, defaultValue: DV) : V | DV;
getValue<V extends RegistryValueType>(key: ValuedRegistryKey<V>, defaultValue?: V) : V;
getValue<V extends RegistryValueType, DV>(key: RegistryKey<V> | ValuedRegistryKey<V>, defaultValue: DV) : V | DV {
if(arguments.length > 1) {
getValue<V extends RegistryValueType, DV>(key: RegistryKey<V>, defaultValue: DV): V | DV;
getValue<V extends RegistryValueType>(key: ValuedRegistryKey<V>, defaultValue?: V): V;
getValue<V extends RegistryValueType, DV>(key: RegistryKey<V> | ValuedRegistryKey<V>, defaultValue: DV): V | DV {
if (arguments.length > 1) {
return resolveSettingKey(key, key => this.getParameter(key), defaultValue);
} else if("defaultValue" in key) {
} else if ("defaultValue" in key) {
return resolveSettingKey(key, key => this.getParameter(key), key.defaultValue);
} else {
throw tr("missing value");
@ -155,14 +155,14 @@ export class UrlParameterBuilder {
private parameters = {};
setValue<V extends RegistryValueType>(key: RegistryKey<V>, value: V) {
if(value === undefined) {
if (value === undefined) {
delete this.parameters[key.key];
} else {
this.parameters[key.key] = encodeURIComponent(encodeSettingValueToString(value));
}
}
build() : string {
build(): string {
return Object.keys(this.parameters).map(key => `${key}=${this.parameters[key]}`).join("&");
}
}
@ -174,12 +174,12 @@ export class UrlParameterBuilder {
export namespace AppParameters {
export const Instance = new UrlParameterParser(new URL(window.location.href));
export function getValue<V extends RegistryValueType, DV>(key: RegistryKey<V>, defaultValue: DV) : V | DV;
export function getValue<V extends RegistryValueType>(key: ValuedRegistryKey<V>, defaultValue?: V) : V;
export function getValue<V extends RegistryValueType, DV>(key: RegistryKey<V> | ValuedRegistryKey<V>, defaultValue: DV) : V | DV {
if(arguments.length > 1) {
export function getValue<V extends RegistryValueType, DV>(key: RegistryKey<V>, defaultValue: DV): V | DV;
export function getValue<V extends RegistryValueType>(key: ValuedRegistryKey<V>, defaultValue?: V): V;
export function getValue<V extends RegistryValueType, DV>(key: RegistryKey<V> | ValuedRegistryKey<V>, defaultValue: DV): V | DV {
if (arguments.length > 1) {
return Instance.getValue(key, defaultValue);
} else if("defaultValue" in key) {
} else if ("defaultValue" in key) {
return Instance.getValue(key);
} else {
throw tr("missing value");
@ -408,12 +408,12 @@ export class Settings {
static readonly KEY_FLAG_CONNECT_DEFAULT: ValuedRegistryKey<boolean> = {
key: "connect_default",
valueType: "boolean",
defaultValue: false
defaultValue: true
};
static readonly KEY_CONNECT_ADDRESS: ValuedRegistryKey<string> = {
key: "connect_address",
valueType: "string",
defaultValue: undefined
defaultValue: "tea.lp.kle.li"
};
static readonly KEY_CONNECT_PROFILE: ValuedRegistryKey<string> = {
key: "connect_profile",
@ -448,7 +448,7 @@ export class Settings {
static readonly KEY_CONNECT_NO_DNSPROXY: ValuedRegistryKey<boolean> = {
key: "connect_no_dnsproxy",
defaultValue: false,
defaultValue: true,
valueType: "boolean",
};
@ -572,12 +572,6 @@ export class Settings {
valueType: "boolean",
};
static readonly KEY_TEAFORO_URL: ValuedRegistryKey<string> = {
key: "teaforo_url",
defaultValue: "https://forum.teaspeak.de/",
valueType: "string",
};
static readonly KEY_FONT_SIZE: ValuedRegistryKey<number> = {
key: "font_size",
valueType: "number",
@ -616,7 +610,7 @@ export class Settings {
/* defaultValue: <users download directory> */
};
static readonly KEY_IPC_REMOTE_ADDRESS: RegistryKey<string> = {
static readonly KEY_IPC_REMOTE_ADDRESS: RegistryKey<string> = {
key: "ipc-address",
valueType: "string"
};
@ -913,8 +907,8 @@ export class Settings {
static readonly KEYS = (() => {
const result = [];
for(const key of Object.keys(Settings)) {
if(!key.toUpperCase().startsWith("KEY_")) {
for (const key of Object.keys(Settings)) {
if (!key.toUpperCase().startsWith("KEY_")) {
continue;
}
@ -943,13 +937,13 @@ export class Settings {
const json = await getStorageAdapter().get("settings.global");
try {
if(json === null) {
if (json === null) {
logInfo(LogCategory.GENERAL, tr("Found no settings. Creating new client settings."));
this.settingsCache = {};
} else {
this.settingsCache = JSON.parse(json);
}
} catch(error) {
} catch (error) {
this.settingsCache = {};
logError(LogCategory.GENERAL, tr("Failed to load global settings!\nJson: %s\nError: %o"), json, error);
@ -957,7 +951,7 @@ export class Settings {
//FIXME: Readd this
//createErrorModal(tr("Failed to load global settings"), tr("Failed to load global client settings!\nLookup console for more information.")).open();
};
if(!loader.finished()) {
if (!loader.finished()) {
loader.register_task(loader.Stage.LOADED, {
priority: 0,
name: "Settings error",
@ -969,18 +963,18 @@ export class Settings {
}
this.saveWorker = setInterval(() => {
if(this.updated) {
if (this.updated) {
this.save();
}
}, 5 * 1000);
}
getValue<V extends RegistryValueType, DV>(key: RegistryKey<V>, defaultValue: DV) : V | DV;
getValue<V extends RegistryValueType>(key: ValuedRegistryKey<V>, defaultValue?: V) : V;
getValue<V extends RegistryValueType, DV>(key: RegistryKey<V> | ValuedRegistryKey<V>, defaultValue: DV) : V | DV {
if(arguments.length > 1) {
getValue<V extends RegistryValueType, DV>(key: RegistryKey<V>, defaultValue: DV): V | DV;
getValue<V extends RegistryValueType>(key: ValuedRegistryKey<V>, defaultValue?: V): V;
getValue<V extends RegistryValueType, DV>(key: RegistryKey<V> | ValuedRegistryKey<V>, defaultValue: DV): V | DV {
if (arguments.length > 1) {
return resolveSettingKey(key, key => this.settingsCache[key], defaultValue);
} else if("defaultValue" in key) {
} else if ("defaultValue" in key) {
return resolveSettingKey(key, key => this.settingsCache[key], key.defaultValue);
} else {
debugger;
@ -988,17 +982,17 @@ export class Settings {
}
}
setValue<T extends RegistryValueType>(key: RegistryKey<T>, value?: T){
if(value === null) {
setValue<T extends RegistryValueType>(key: RegistryKey<T>, value?: T) {
if (value === null) {
value = undefined;
}
if(this.settingsCache[key.key] === value) {
if (this.settingsCache[key.key] === value) {
return;
}
const oldValue = this.settingsCache[key.key];
if(value === undefined) {
if (value === undefined) {
delete this.settingsCache[key.key];
} else {
this.settingsCache[key.key] = encodeSettingValueToString(value);
@ -1014,21 +1008,21 @@ export class Settings {
});
logTrace(LogCategory.GENERAL, tr("Changing global setting %s to %o"), key.key, value);
if(UPDATE_DIRECT) {
if (UPDATE_DIRECT) {
this.save();
}
}
globalChangeListener<T extends RegistryValueType>(key: RegistryKey<T>, listener: (newValue: T) => void) : () => void {
globalChangeListener<T extends RegistryValueType>(key: RegistryKey<T>, listener: (newValue: T) => void): () => void {
return this.events.on("notify_setting_changed", event => {
if(event.setting === key.key && event.mode === "global") {
if (event.setting === key.key && event.mode === "global") {
listener(event.newCastedValue);
}
})
}
private async doSave() {
if(this.saveState === "none") {
if (this.saveState === "none") {
return;
}
@ -1040,7 +1034,7 @@ export class Settings {
} catch (error) {
logError(LogCategory.GENERAL, tr("Failed to save global settings: %o"), error);
}
} while(this.saveState !== "saving");
} while (this.saveState !== "saving");
this.saveState = "none";
}

View File

@ -1,20 +1,20 @@
import * as React from "react";
import {IpcInviteInfo, IpcInviteInfoLoaded} from "tc-shared/text/bbcode/InviteDefinitions";
import {ChannelMessage, getIpcInstance, IPCChannel} from "tc-shared/ipc/BrowserIPC";
import { IpcInviteInfo, IpcInviteInfoLoaded } from "tc-shared/text/bbcode/InviteDefinitions";
import { ChannelMessage, getIpcInstance, IPCChannel } from "tc-shared/ipc/BrowserIPC";
import * as loader from "tc-loader";
import {useEffect, useState} from "react";
import { useEffect, useState } from "react";
import _ = require("lodash");
import {Translatable} from "tc-shared/ui/react-elements/i18n";
import {Button} from "tc-shared/ui/react-elements/Button";
import {SimpleUrlRenderer} from "tc-shared/text/bbcode/url";
import {LoadingDots} from "tc-shared/ui/react-elements/LoadingDots";
import {ClientIconRenderer} from "tc-shared/ui/react-elements/Icons";
import {ClientIcon} from "svg-sprites/client-icons";
import { Translatable } from "tc-shared/ui/react-elements/i18n";
import { Button } from "tc-shared/ui/react-elements/Button";
import { SimpleUrlRenderer } from "tc-shared/text/bbcode/url";
import { LoadingDots } from "tc-shared/ui/react-elements/LoadingDots";
import { ClientIconRenderer } from "tc-shared/ui/react-elements/Icons";
import { ClientIcon } from "svg-sprites/client-icons";
const cssStyle = require("./InviteRenderer.scss");
const kInviteUrlRegex = /^(https:\/\/)?(teaspeak.de\/|join.teaspeak.de\/(invite\/)?)([a-zA-Z0-9]{4})$/gm;
export function isInviteLink(url: string) : boolean {
export function isInviteLink(url: string): boolean {
kInviteUrlRegex.lastIndex = 0;
return !!url.match(kInviteUrlRegex);
}
@ -26,25 +26,25 @@ const localInviteCache: { [key: string]: InviteCacheEntry } = {};
const localInviteCallbacks: { [key: string]: (() => void)[] } = {};
const useInviteLink = (linkId: string): LocalInviteInfo => {
if(!localInviteCache[linkId]) {
if (!localInviteCache[linkId]) {
localInviteCache[linkId] = { status: { status: "loading" }, timeout: setTimeout(() => delete localInviteCache[linkId], 60 * 1000) };
ipcChannel?.sendMessage("query", { linkId });
}
const [ value, setValue ] = useState(localInviteCache[linkId].status);
const [value, setValue] = useState(localInviteCache[linkId].status);
useEffect(() => {
if(typeof localInviteCache[linkId]?.status === "undefined") {
if (typeof localInviteCache[linkId]?.status === "undefined") {
return;
}
if(!_.isEqual(value, localInviteCache[linkId].status)) {
if (!_.isEqual(value, localInviteCache[linkId].status)) {
setValue(localInviteCache[linkId].status);
}
const callback = () => setValue(localInviteCache[linkId].status);
(localInviteCallbacks[linkId] || (localInviteCallbacks[linkId] = [])).push(callback);
return () => localInviteCallbacks[linkId]?.remove(callback);
return () => { localInviteCallbacks[linkId]?.remove(callback); }
}, [linkId]);
return value;
@ -69,14 +69,14 @@ const LoadedInviteRenderer = React.memo((props: { info: IpcInviteInfoLoaded }) =
</div>
);
const [, setRevision ] = useState(0);
const [, setRevision] = useState(0);
useEffect(() => {
if(props.info.expireTimestamp === 0) {
if (props.info.expireTimestamp === 0) {
return;
}
const timeout = props.info.expireTimestamp - (Date.now() / 1000);
if(timeout <= 0) {
if (timeout <= 0) {
return;
}
@ -84,7 +84,7 @@ const LoadedInviteRenderer = React.memo((props: { info: IpcInviteInfoLoaded }) =
return () => clearTimeout(timeoutId);
});
if(props.info.expireTimestamp > 0 && Date.now() / 1000 >= props.info.expireTimestamp) {
if (props.info.expireTimestamp > 0 && Date.now() / 1000 >= props.info.expireTimestamp) {
return (
<InviteErrorRenderer noTitle={true} key={"expired"}>
<Translatable>Link expired</Translatable>
@ -92,7 +92,7 @@ const LoadedInviteRenderer = React.memo((props: { info: IpcInviteInfoLoaded }) =
);
}
if(props.info.channelName) {
if (props.info.channelName) {
return (
<div className={cssStyle.container + " " + cssStyle.info} key={"with-channel"}>
<div className={cssStyle.left}>
@ -215,8 +215,8 @@ loader.register_task(loader.Stage.JAVASCRIPT_INITIALIZING, {
function handleIpcMessage(remoteId: string, broadcast: boolean, message: ChannelMessage) {
if(message.type === "query-result") {
if(!localInviteCache[message.data.linkId]) {
if (message.type === "query-result") {
if (!localInviteCache[message.data.linkId]) {
return;
}

File diff suppressed because it is too large Load Diff

View File

@ -83,9 +83,11 @@ $bot_thumbnail_height: 9em;
&:hover {
opacity: 1;
}
@include transition(opacity $button_hover_animation_time ease-in-out);
&:before, &:after {
&:before,
&:after {
position: absolute;
left: .25em;
content: ' ';
@ -126,6 +128,7 @@ $bot_thumbnail_height: 9em;
&:hover {
background-color: #393939;
}
@include transition($button_hover_animation_time ease-in-out);
}
}
@ -208,8 +211,8 @@ $bot_thumbnail_height: 9em;
}
&.disabled {
opacity: 0!important;
pointer-events: none!important;
opacity: 0 !important;
pointer-events: none !important;
}
}
@ -282,7 +285,7 @@ $bot_thumbnail_height: 9em;
flex-direction: row;
justify-content: stretch;
> .icon {
>.icon {
margin-bottom: .1em;
font-size: 2em;
@ -300,8 +303,9 @@ $bot_thumbnail_height: 9em;
}
&.list {
> .icon_em {
margin-top: 0; /* for lists the .1em patting on the top looks odd */
>.icon_em {
margin-top: 0;
/* for lists the .1em patting on the top looks odd */
}
}
@ -311,13 +315,15 @@ $bot_thumbnail_height: 9em;
flex-shrink: 1;
flex-grow: 1;
min-width: 4em; /* 2em for the icon the last 4 for the text */
min-width: 4em;
/* 2em for the icon the last 4 for the text */
display: flex;
flex-direction: column;
justify-content: flex-start;
.title, .value {
.title,
.value {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
@ -340,10 +346,12 @@ $bot_thumbnail_height: 9em;
align-self: center;
}
&.status, &.groups {
&.status,
&.groups {
flex-direction: column;
.statusEntry, .groupEntry {
.statusEntry,
.groupEntry {
.icon {
vertical-align: text-top;
}
@ -366,12 +374,6 @@ $bot_thumbnail_height: 9em;
justify-content: flex-end;
}
}
&.clientTeaforoAccount {
a, a:visited {
color: #d9d9d9;
}
}
}
}

View File

@ -1,5 +1,5 @@
import * as React from "react";
import {useContext, useEffect, useRef, useState} from "react";
import { useContext, useEffect, useRef, useState } from "react";
import {
ClientCountryInfo,
ClientForumInfo,
@ -11,22 +11,22 @@ import {
ClientVolumeInfo, InheritedChannelInfo,
OptionalClientInfoInfo
} from "tc-shared/ui/frames/side/ClientInfoDefinitions";
import {Registry} from "tc-shared/events";
import {ClientAvatar, getGlobalAvatarManagerFactory} from "tc-shared/file/Avatars";
import {AvatarRenderer} from "tc-shared/ui/react-elements/Avatar";
import {Translatable} from "tc-shared/ui/react-elements/i18n";
import {LoadingDots} from "tc-shared/ui/react-elements/LoadingDots";
import {ClientTag} from "tc-shared/ui/tree/EntryTags";
import {guid} from "tc-shared/crypto/uid";
import {useDependentState} from "tc-shared/ui/react-elements/Helper";
import {format_online_time} from "tc-shared/utils/TimeUtils";
import {ClientIcon} from "svg-sprites/client-icons";
import {ClientIconRenderer} from "tc-shared/ui/react-elements/Icons";
import {getIconManager} from "tc-shared/file/Icons";
import {RemoteIconRenderer} from "tc-shared/ui/react-elements/Icon";
import {CountryCode} from "tc-shared/ui/react-elements/CountryCode";
import {getKeyBoard} from "tc-shared/PPTListener";
import {tra} from "tc-shared/i18n/localize";
import { Registry } from "tc-shared/events";
import { ClientAvatar, getGlobalAvatarManagerFactory } from "tc-shared/file/Avatars";
import { AvatarRenderer } from "tc-shared/ui/react-elements/Avatar";
import { Translatable } from "tc-shared/ui/react-elements/i18n";
import { LoadingDots } from "tc-shared/ui/react-elements/LoadingDots";
import { ClientTag } from "tc-shared/ui/tree/EntryTags";
import { guid } from "tc-shared/crypto/uid";
import { useDependentState } from "tc-shared/ui/react-elements/Helper";
import { format_online_time } from "tc-shared/utils/TimeUtils";
import { ClientIcon } from "svg-sprites/client-icons";
import { ClientIconRenderer } from "tc-shared/ui/react-elements/Icons";
import { getIconManager } from "tc-shared/file/Icons";
import { RemoteIconRenderer } from "tc-shared/ui/react-elements/Icon";
import { CountryCode } from "tc-shared/ui/react-elements/CountryCode";
import { getKeyBoard } from "tc-shared/PPTListener";
import { tra } from "tc-shared/i18n/localize";
const cssStyle = require("./ClientInfoRenderer.scss");
@ -67,7 +67,7 @@ const Avatar = React.memo(() => {
const client = useContext(ClientContext);
let avatar: "loading" | ClientAvatar;
if(client.type === "none") {
if (client.type === "none") {
avatar = "loading";
} else {
avatar = getGlobalAvatarManagerFactory().getManager(client.handlerId)
@ -88,13 +88,13 @@ const ClientName = React.memo(() => {
const events = useContext(EventsContext);
const client = useContext(ClientContext);
const [ name, setName ] = useDependentState<string | null>(() => {
if(client.type !== "none") {
const [name, setName] = useDependentState<string | null>(() => {
if (client.type !== "none") {
events.fire("query_client_name");
}
return null;
}, [ client.contextHash ]);
}, [client.contextHash]);
events.reactUse("notify_client_name", event => setName(event.name), undefined, []);
@ -111,13 +111,13 @@ const ClientName = React.memo(() => {
const ClientDescription = React.memo(() => {
const events = useContext(EventsContext);
const client = useContext(ClientContext);
const [ description, setDescription ] = useDependentState<string | null | undefined>(() => {
if(client.type !== "none") {
const [description, setDescription] = useDependentState<string | null | undefined>(() => {
if (client.type !== "none") {
events.fire("query_client_description");
}
return null;
}, [ client.contextHash ]);
}, [client.contextHash]);
events.reactUse("notify_client_description", event => {
setDescription(event.description ? event.description : null);
@ -150,23 +150,23 @@ const InfoBlock = (props: { imageUrl?: string, clientIcon?: ClientIcon, children
const ClientOnlineSince = React.memo(() => {
const events = useContext(EventsContext);
const client = useContext(ClientContext);
const [ onlineInfo, setOnlineInfo ] = useDependentState<ClientInfoOnline>(() => {
if(client.type !== "none") {
const [onlineInfo, setOnlineInfo] = useDependentState<ClientInfoOnline>(() => {
if (client.type !== "none") {
events.fire("query_online");
}
return undefined;
}, [ client.contextHash ]);
const [ revision, setRevision ] = useState(0);
}, [client.contextHash]);
const [revision, setRevision] = useState(0);
events.reactUse("notify_online", event => setOnlineInfo(event.status), undefined, []);
let onlineBody;
if(client.type === "none" || !onlineInfo) {
if (client.type === "none" || !onlineInfo) {
onlineBody = <React.Fragment key={"loading"}><Translatable>loading</Translatable> <LoadingDots /></React.Fragment>;
} else if(onlineInfo.joinTimestamp === 0) {
} else if (onlineInfo.joinTimestamp === 0) {
onlineBody = <React.Fragment key={"invalid"}><Translatable>Join timestamp not logged</Translatable></React.Fragment>;
} else if(onlineInfo.leaveTimestamp === 0) {
} else if (onlineInfo.leaveTimestamp === 0) {
const onlineTime = Date.now() / 1000 - onlineInfo.joinTimestamp;
onlineBody = <React.Fragment key={"value-live"}>{format_online_time(onlineTime)}</React.Fragment>;
} else {
@ -175,7 +175,7 @@ const ClientOnlineSince = React.memo(() => {
}
useEffect(() => {
if(!onlineInfo || onlineInfo.leaveTimestamp !== 0 || onlineInfo.joinTimestamp === 0) {
if (!onlineInfo || onlineInfo.leaveTimestamp !== 0 || onlineInfo.joinTimestamp === 0) {
return;
}
@ -194,13 +194,13 @@ const ClientOnlineSince = React.memo(() => {
const ClientCountry = React.memo(() => {
const events = useContext(EventsContext);
const client = useContext(ClientContext);
const [ country, setCountry ] = useDependentState<ClientCountryInfo>(() => {
if(client.type !== "none") {
const [country, setCountry] = useDependentState<ClientCountryInfo>(() => {
if (client.type !== "none") {
events.fire("query_country");
}
return undefined;
}, [ client.contextHash ]);
}, [client.contextHash]);
events.reactUse("notify_country", event => setCountry(event.country), undefined, []);
@ -215,24 +215,24 @@ const ClientCountry = React.memo(() => {
const ClientVolume = React.memo(() => {
const events = useContext(EventsContext);
const client = useContext(ClientContext);
const [ volume, setVolume ] = useDependentState<ClientVolumeInfo>(() => {
if(client.type !== "none") {
const [volume, setVolume] = useDependentState<ClientVolumeInfo>(() => {
if (client.type !== "none") {
events.fire("query_volume");
}
return undefined;
}, [ client.contextHash ]);
}, [client.contextHash]);
events.reactUse("notify_volume", event => setVolume(event.volume), undefined, []);
if(client.type === "self" || client.type === "none") {
if (client.type === "self" || client.type === "none") {
return null;
}
let body;
if(volume) {
if (volume) {
let text = (volume.volume * 100).toFixed(0) + "%";
if(volume.muted) {
if (volume.muted) {
text += " (" + tr("Muted") + ")";
}
body = <React.Fragment key={"value"}>{text}</React.Fragment>;
@ -248,62 +248,24 @@ const ClientVolume = React.memo(() => {
);
});
const ClientForumAccount = React.memo(() => {
const events = useContext(EventsContext);
const client = useContext(ClientContext);
const [ forum, setForum ] = useDependentState<ClientForumInfo>(() => {
if(client.type !== "none") {
events.fire("query_forum");
}
return undefined;
}, [ client.contextHash ]);
events.reactUse("notify_forum", event => setForum(event.forum), undefined, []);
if(!forum) {
return null;
}
let text = forum.nickname;
if((forum.flags & 0x01) > 0) {
text += " (" + tr("Banned") + ")";
}
if((forum.flags & 0x02) > 0) {
text += " (" + tr("Stuff") + ")";
}
if((forum.flags & 0x04) > 0) {
text += " (" + tr("Premium") + ")";
}
return (
<InfoBlock clientIcon={ClientIcon.ClientInfoForumAccount} valueClass={cssStyle.clientTeaforoAccount}>
<Translatable>TeaSpeak Forum account</Translatable>
<a href={"https://forum.teaspeak.de/index.php?members/" + forum.userId} target={"_blank"}>{text}</a>
</InfoBlock>
);
});
const ClientVersion = React.memo(() => {
const events = useContext(EventsContext);
const client = useContext(ClientContext);
const [ version, setVersion ] = useDependentState<ClientVersionInfo>(() => {
if(client.type !== "none") {
const [version, setVersion] = useDependentState<ClientVersionInfo>(() => {
if (client.type !== "none") {
events.fire("query_version");
}
return undefined;
}, [ client.contextHash ]);
}, [client.contextHash]);
events.reactUse("notify_version", event => setVersion(event.version), undefined, []);
let body;
if(version) {
if (version) {
let platform = version.platform;
if(platform.indexOf("Win32") != 0 && (version.version.indexOf("Win64") != -1 || version.version.indexOf("WOW64") != -1)) {
if (platform.indexOf("Win32") != 0 && (version.version.indexOf("Win64") != -1 || version.version.indexOf("WOW64") != -1)) {
platform = platform.replace("Win32", "Win64");
}
@ -330,41 +292,41 @@ const ClientStatusEntry = (props: { icon: ClientIcon, children: React.ReactEleme
const ClientStatus = React.memo(() => {
const events = useContext(EventsContext);
const client = useContext(ClientContext);
const [ status, setStatus ] = useDependentState<ClientStatusInfo>(() => {
if(client.type !== "none") {
const [status, setStatus] = useDependentState<ClientStatusInfo>(() => {
if (client.type !== "none") {
events.fire("query_status");
}
return undefined;
}, [ client.contextHash ]);
}, [client.contextHash]);
events.reactUse("notify_status", event => setStatus(event.status), undefined, []);
let elements = [];
if(status) {
if(status.away) {
if (status) {
if (status.away) {
let message = typeof status.away === "string" ? " (" + status.away + ")" : undefined;
elements.push(<ClientStatusEntry key={"away"} icon={ClientIcon.Away}><><Translatable>Away</Translatable> {message}</></ClientStatusEntry>);
}
if(status.speakerDisabled) {
if (status.speakerDisabled) {
elements.push(<ClientStatusEntry key={"hardwareoutputmuted"} icon={ClientIcon.HardwareOutputMuted}><Translatable>Speakers/Headphones disabled</Translatable></ClientStatusEntry>);
}
if(status.microphoneDisabled) {
if (status.microphoneDisabled) {
elements.push(<ClientStatusEntry key={"hardwareinputmuted"} icon={ClientIcon.HardwareInputMuted}><Translatable>Microphone disabled</Translatable></ClientStatusEntry>);
}
if(status.speakerMuted) {
if (status.speakerMuted) {
elements.push(<ClientStatusEntry key={"outputmuted"} icon={ClientIcon.OutputMuted}><Translatable>Speakers/Headphones Muted</Translatable></ClientStatusEntry>);
}
if(status.microphoneMuted) {
if (status.microphoneMuted) {
elements.push(<ClientStatusEntry key={"inputmuted"} icon={ClientIcon.InputMuted}><Translatable>Microphone Muted</Translatable></ClientStatusEntry>);
}
}
if(elements.length === 0) {
if (elements.length === 0) {
return null;
}
@ -379,17 +341,17 @@ const ClientStatus = React.memo(() => {
const FullInfoButton = () => {
const events = useContext(EventsContext);
const client = useContext(ClientContext);
const [ onlineInfo, setOnlineInfo ] = useDependentState<ClientInfoOnline>(() => {
if(client.type !== "none") {
const [onlineInfo, setOnlineInfo] = useDependentState<ClientInfoOnline>(() => {
if (client.type !== "none") {
events.fire("query_online");
}
return undefined;
}, [ client.contextHash ]);
}, [client.contextHash]);
events.reactUse("notify_online", event => setOnlineInfo(event.status), undefined, []);
if(!onlineInfo || onlineInfo.leaveTimestamp !== 0) {
if (!onlineInfo || onlineInfo.leaveTimestamp !== 0) {
return null;
}
@ -413,15 +375,15 @@ const GroupRenderer = (props: { group: ClientGroupInfo }) => {
const ChannelGroupRenderer = () => {
const events = useContext(EventsContext);
const client = useContext(ClientContext);
const [ channelGroup, setChannelGroup ] = useDependentState<ClientGroupInfo>(() => {
if(client.type !== "none") {
const [channelGroup, setChannelGroup] = useDependentState<ClientGroupInfo>(() => {
if (client.type !== "none") {
events.fire("query_channel_group");
}
return undefined;
}, [ client.contextHash ]);
}, [client.contextHash]);
const [ inheritedChannel, setInheritedChannel ] = useDependentState<InheritedChannelInfo>(() => undefined, [ client.contextHash ]);
const [inheritedChannel, setInheritedChannel] = useDependentState<InheritedChannelInfo>(() => undefined, [client.contextHash]);
events.reactUse("notify_channel_group", event => {
setChannelGroup(event.group);
@ -429,9 +391,9 @@ const ChannelGroupRenderer = () => {
}, undefined, []);
let body;
if(channelGroup) {
if (channelGroup) {
let groupRendered = <GroupRenderer group={channelGroup} key={"group-" + channelGroup.groupId} />;
if(inheritedChannel) {
if (inheritedChannel) {
body = (
<React.Fragment key={"inherited"}>
{groupRendered}
@ -459,18 +421,18 @@ const ChannelGroupRenderer = () => {
const ServerGroupRenderer = () => {
const events = useContext(EventsContext);
const client = useContext(ClientContext);
const [ serverGroups, setServerGroups ] = useDependentState<ClientGroupInfo[]>(() => {
if(client.type !== "none") {
const [serverGroups, setServerGroups] = useDependentState<ClientGroupInfo[]>(() => {
if (client.type !== "none") {
events.fire("query_server_groups");
}
return undefined;
}, [ client.contextHash ]);
}, [client.contextHash]);
events.reactUse("notify_server_groups", event => setServerGroups(event.groups), undefined, []);
let body;
if(serverGroups) {
if (serverGroups) {
body = serverGroups.map(group => <GroupRenderer group={group} key={"group-" + group.groupId} />);
} else {
body = <React.Fragment key={"loading"}><Translatable>loading</Translatable> <LoadingDots /></React.Fragment>;
@ -486,7 +448,7 @@ const ServerGroupRenderer = () => {
const ConnectedClientInfoBlock = () => {
const client = useContext(ClientContext);
if(client.type === "query" || client.type === "none") {
if (client.type === "query" || client.type === "none") {
return null;
}
@ -494,7 +456,6 @@ const ConnectedClientInfoBlock = () => {
<React.Fragment key={"info"}>
<ClientOnlineSince />
<ClientCountry />
<ClientForumAccount />
<ClientVolume />
<ClientVersion />
<ClientStatus />
@ -505,12 +466,12 @@ const ConnectedClientInfoBlock = () => {
const ClientInfoProvider = () => {
const events = useContext(EventsContext);
const [ client, setClient ] = useState<OptionalClientInfoInfo>(() => {
const [client, setClient] = useState<OptionalClientInfoInfo>(() => {
events.fire("query_client");
return { type: "none", contextHash: guid() };
});
events.reactUse("notify_client", event => {
if(event.info) {
if (event.info) {
setClient({
contextHash: guid(),
type: event.info.type,
@ -519,7 +480,7 @@ const ClientInfoProvider = () => {
clientId: event.info.clientId,
clientDatabaseId: event.info.clientDatabaseId
});
} else if(client.type !== "none") {
} else if (client.type !== "none") {
setClient({ type: "none", contextHash: guid() });
}
});

View File

@ -1,13 +1,13 @@
import {ClientConnectionInfo, ClientEntry} from "../../tree/Client";
import { ClientConnectionInfo, ClientEntry } from "../../tree/Client";
import PermissionType from "../../permission/PermissionType";
import {createInfoModal, createModal, Modal} from "../../ui/elements/Modal";
import {copyToClipboard} from "../../utils/helpers";
import { createInfoModal, createModal, Modal } from "../../ui/elements/Modal";
import { copyToClipboard } from "../../utils/helpers";
import * as i18nc from "../../i18n/CountryFlag";
import * as tooltip from "../../ui/elements/Tooltip";
import moment from "moment";
import {format_number, network} from "../../ui/frames/chat";
import {generateIconJQueryTag, getIconManager} from "tc-shared/file/Icons";
import {tr} from "tc-shared/i18n/localize";
import { format_number, network } from "../../ui/frames/chat";
import { generateIconJQueryTag, getIconManager } from "tc-shared/file/Icons";
import { tr } from "tc-shared/i18n/localize";
type InfoUpdateCallback = (info: ClientConnectionInfo) => any;
@ -147,31 +147,6 @@ function apply_basic_info(client: ClientEntry, tag: JQuery, modal: Modal, callba
});
}
/* TeaForo */
{
const container = tag.find(".property-teaforo .value").empty();
if (client.properties.client_teaforo_id) {
container.children().remove();
let text = client.properties.client_teaforo_name;
if ((client.properties.client_teaforo_flags & 0x01) > 0)
text += " (" + tr("Banned") + ")";
if ((client.properties.client_teaforo_flags & 0x02) > 0)
text += " (" + tr("Stuff") + ")";
if ((client.properties.client_teaforo_flags & 0x04) > 0)
text += " (" + tr("Premium") + ")";
$.spawn("a")
.attr("href", "https://forum.teaspeak.de/index.php?members/" + client.properties.client_teaforo_id)
.attr("target", "_blank")
.text(text)
.appendTo(container);
} else {
container.append($.spawn("a").text(tr("Not connected")));
}
}
/* Version */
{
const container = tag.find(".property-version");
@ -376,7 +351,7 @@ function apply_packets(client: ClientEntry, tag: JQuery, modal: Modal, callbacks
if (packets == 0 && info.connection_packets_received_keepalive == -1)
node_downstream.innerText = tr("Not calculated");
else
node_downstream.innerText = format_number(packets, {unit: "Packets"});
node_downstream.innerText = format_number(packets, { unit: "Packets" });
});
node_downstream.innerText = tr("loading...");
}
@ -390,7 +365,7 @@ function apply_packets(client: ClientEntry, tag: JQuery, modal: Modal, callbacks
if (packets == 0 && info.connection_packets_sent_keepalive == -1)
node_upstream.innerText = tr("Not calculated");
else
node_upstream.innerText = format_number(packets, {unit: "Packets"});
node_upstream.innerText = format_number(packets, { unit: "Packets" });
});
node_upstream.innerText = tr("loading...");
}
@ -446,7 +421,7 @@ function apply_packets(client: ClientEntry, tag: JQuery, modal: Modal, callbacks
if (bytes == 0 && info.connection_bandwidth_received_last_second_keepalive == -1)
node_downstream.innerText = tr("Not calculated");
else
node_downstream.innerText = network.format_bytes(bytes, {time: "s"});
node_downstream.innerText = network.format_bytes(bytes, { time: "s" });
});
node_downstream.innerText = tr("loading...");
}
@ -460,7 +435,7 @@ function apply_packets(client: ClientEntry, tag: JQuery, modal: Modal, callbacks
if (bytes == 0 && info.connection_bandwidth_sent_last_second_keepalive == -1)
node_upstream.innerText = tr("Not calculated");
else
node_upstream.innerText = network.format_bytes(bytes, {time: "s"});
node_upstream.innerText = network.format_bytes(bytes, { time: "s" });
});
node_upstream.innerText = tr("loading...");
}
@ -481,7 +456,7 @@ function apply_packets(client: ClientEntry, tag: JQuery, modal: Modal, callbacks
if (bytes == 0 && info.connection_bandwidth_received_last_minute_keepalive == -1)
node_downstream.innerText = tr("Not calculated");
else
node_downstream.innerText = network.format_bytes(bytes, {time: "s"});
node_downstream.innerText = network.format_bytes(bytes, { time: "s" });
});
node_downstream.innerText = tr("loading...");
}
@ -495,7 +470,7 @@ function apply_packets(client: ClientEntry, tag: JQuery, modal: Modal, callbacks
if (bytes == 0 && info.connection_bandwidth_sent_last_minute_keepalive == -1)
node_upstream.innerText = tr("Not calculated");
else
node_upstream.innerText = network.format_bytes(bytes, {time: "s"});
node_upstream.innerText = network.format_bytes(bytes, { time: "s" });
});
node_upstream.innerText = tr("loading...");
}
@ -510,7 +485,7 @@ function apply_packets(client: ClientEntry, tag: JQuery, modal: Modal, callbacks
if (node_downstream) {
client.updateClientVariables().then(info => {
//TODO: Test for own client info and if so then show the max quota (needed permission)
node_downstream.innerText = network.format_bytes(client.properties.client_month_bytes_downloaded, {exact: false});
node_downstream.innerText = network.format_bytes(client.properties.client_month_bytes_downloaded, { exact: false });
});
node_downstream.innerText = tr("loading...");
}
@ -518,7 +493,7 @@ function apply_packets(client: ClientEntry, tag: JQuery, modal: Modal, callbacks
if (node_upstream) {
client.updateClientVariables().then(info => {
//TODO: Test for own client info and if so then show the max quota (needed permission)
node_upstream.innerText = network.format_bytes(client.properties.client_month_bytes_uploaded, {exact: false});
node_upstream.innerText = network.format_bytes(client.properties.client_month_bytes_uploaded, { exact: false });
});
node_upstream.innerText = tr("loading...");
}

View File

@ -1,38 +1,36 @@
import {createErrorModal, createInfoModal, createInputModal, createModal, Modal} from "tc-shared/ui/elements/Modal";
import {sliderfy} from "tc-shared/ui/elements/Slider";
import {settings, Settings} from "tc-shared/settings";
import { createErrorModal, createInfoModal, createInputModal, createModal, Modal } from "tc-shared/ui/elements/Modal";
import { sliderfy } from "tc-shared/ui/elements/Slider";
import { settings, Settings } from "tc-shared/settings";
import * as sound from "tc-shared/audio/Sounds";
import {manager, setSoundMasterVolume, Sound} from "tc-shared/audio/Sounds";
import { manager, setSoundMasterVolume, Sound } from "tc-shared/audio/Sounds";
import * as profiles from "tc-shared/profiles/ConnectionProfile";
import {ConnectionProfile} from "tc-shared/profiles/ConnectionProfile";
import {IdentitifyType} from "tc-shared/profiles/Identity";
import {TeaForumIdentity} from "tc-shared/profiles/identities/TeaForumIdentity";
import {TeaSpeakIdentity} from "tc-shared/profiles/identities/TeamSpeakIdentity";
import {NameIdentity} from "tc-shared/profiles/identities/NameIdentity";
import {LogCategory, logDebug, logError, logTrace, logWarn} from "tc-shared/log";
import { ConnectionProfile } from "tc-shared/profiles/ConnectionProfile";
import { IdentitifyType } from "tc-shared/profiles/Identity";
import { TeaSpeakIdentity } from "tc-shared/profiles/identities/TeamSpeakIdentity";
import { NameIdentity } from "tc-shared/profiles/identities/NameIdentity";
import { LogCategory, logDebug, logError, logTrace, logWarn } from "tc-shared/log";
import * as i18n from "tc-shared/i18n/localize";
import {RepositoryTranslation, TranslationRepository} from "tc-shared/i18n/localize";
import {Registry} from "tc-shared/events";
import { RepositoryTranslation, TranslationRepository } from "tc-shared/i18n/localize";
import { Registry } from "tc-shared/events";
import * as i18nc from "../../i18n/CountryFlag";
import * as forum from "tc-shared/profiles/identities/teaspeak-forum";
import {formatMessage, set_icon_size} from "tc-shared/ui/frames/chat";
import {spawnTeamSpeakIdentityImport, spawnTeamSpeakIdentityImprove} from "tc-shared/ui/modal/ModalIdentity";
import {getAudioBackend, OutputDevice} from "tc-shared/audio/Player";
import {KeyMapSettings} from "tc-shared/ui/modal/settings/Keymap";
import { formatMessage, set_icon_size } from "tc-shared/ui/frames/chat";
import { spawnTeamSpeakIdentityImport, spawnTeamSpeakIdentityImprove } from "tc-shared/ui/modal/ModalIdentity";
import { getAudioBackend, OutputDevice } from "tc-shared/audio/Player";
import { KeyMapSettings } from "tc-shared/ui/modal/settings/Keymap";
import * as React from "react";
import * as ReactDOM from "react-dom";
import {NotificationSettings} from "tc-shared/ui/modal/settings/Notifications";
import {initialize_audio_microphone_controller} from "tc-shared/ui/modal/settings/Microphone";
import {MicrophoneSettings} from "tc-shared/ui/modal/settings/MicrophoneRenderer";
import {getBackend} from "tc-shared/backend";
import {MicrophoneSettingsEvents} from "tc-shared/ui/modal/settings/MicrophoneDefinitions";
import {promptYesNo} from "tc-shared/ui/modal/yes-no/Controller";
import { NotificationSettings } from "tc-shared/ui/modal/settings/Notifications";
import { initialize_audio_microphone_controller } from "tc-shared/ui/modal/settings/Microphone";
import { MicrophoneSettings } from "tc-shared/ui/modal/settings/MicrophoneRenderer";
import { getBackend } from "tc-shared/backend";
import { MicrophoneSettingsEvents } from "tc-shared/ui/modal/settings/MicrophoneDefinitions";
import { promptYesNo } from "tc-shared/ui/modal/yes-no/Controller";
type ProfileInfoEvent = {
id: string,
name: string,
nickname: string,
identity_type: "teaforo" | "teamspeak" | "nickname",
identity_type: "teamspeak" | "nickname",
identity_forum?: {
valid: boolean,
@ -52,7 +50,7 @@ export interface SettingProfileEvents {
"reload-profile": { profile_id?: string },
"select-profile": { profile_id: string },
"query-profile-list": { },
"query-profile-list": {},
"query-profile-list-result": {
status: "error" | "success" | "timeout",
@ -71,7 +69,7 @@ export interface SettingProfileEvents {
"select-identity-type": {
profile_id: string,
identity_type: "teamspeak" | "teaforo" | "nickname" | "unset"
identity_type: "teamspeak" | "nickname" | "unset"
},
"query-profile-validity": { profile_id: string },
@ -232,7 +230,6 @@ export function spawnSettingsModal(default_page?: string): Modal {
settings_audio_speaker(modal.htmlTag.find(".right .container.audio-speaker"), modal);
settings_audio_sounds(modal.htmlTag.find(".right .container.audio-sounds"), modal);
const update_profiles = settings_identity_profiles(modal.htmlTag.find(".right .container.identity-profiles"), modal);
settings_identity_forum(modal.htmlTag.find(".right .container.identity-forum"), modal, update_profiles as any);
modal.close_listener.push(() => {
if (profiles.requires_save())
@ -500,13 +497,13 @@ function settings_general_language(container: JQuery, modal: Modal) {
}
function settings_general_keymap(container: JQuery, modal: Modal) {
const entry = <KeyMapSettings/>;
const entry = <KeyMapSettings />;
ReactDOM.render(entry, container[0]);
modal.close_listener.push(() => ReactDOM.unmountComponentAtNode(container[0]));
}
function settings_general_notifications(container: JQuery, modal: Modal) {
const entry = <NotificationSettings/>;
const entry = <NotificationSettings />;
ReactDOM.render(entry, container[0]);
modal.close_listener.push(() => ReactDOM.unmountComponentAtNode(container[0]));
}
@ -599,7 +596,7 @@ function settings_audio_microphone(container: JQuery, modal: Modal) {
const registry = new Registry<MicrophoneSettingsEvents>();
initialize_audio_microphone_controller(registry);
const entry = <MicrophoneSettings events={registry}/>;
const entry = <MicrophoneSettings events={registry} />;
ReactDOM.render(entry, container[0]);
modal.close_listener.push(() => {
ReactDOM.unmountComponentAtNode(container[0]);
@ -876,11 +873,10 @@ export namespace modal_settings {
}
profiles.delete_profile(profile);
event_registry.fire_react("delete-profile-result", {status: "success", profile_id: event.profile_id});
event_registry.fire_react("delete-profile-result", { status: "success", profile_id: event.profile_id });
});
const build_profile_info = (profile: ConnectionProfile) => {
const forum_data = profile.selectedIdentity(IdentitifyType.TEAFORO) as TeaForumIdentity;
const teamspeak_data = profile.selectedIdentity(IdentitifyType.TEAMSPEAK) as TeaSpeakIdentity;
const nickname_data = profile.selectedIdentity(IdentitifyType.NICKNAME) as NameIdentity;
@ -889,10 +885,6 @@ export namespace modal_settings {
name: profile.profileName,
nickname: profile.defaultUsername,
identity_type: profile.selectedIdentityType as any,
identity_forum: !forum_data ? undefined : {
valid: forum_data.valid(),
fallback_name: forum_data.fallback_name()
},
identity_nickname: !nickname_data ? undefined : {
name: nickname_data.name(),
fallback_name: nickname_data.fallback_name()
@ -1041,7 +1033,7 @@ export namespace modal_settings {
});
event_registry.on("select-identity-type", event => {
if(!event.identity_type) {
if (!event.identity_type) {
/* dummy event for UI init */
return;
}
@ -1184,11 +1176,11 @@ export namespace modal_settings {
);
tag_avatar.hide(); /* no avatars yet */
tag.on('click', event => event_registry.fire("select-profile", {profile_id: profile.id}));
tag.on('click', event => event_registry.fire("select-profile", { profile_id: profile.id }));
tag.toggleClass("selected", selected);
tag_default.toggle(profile.id === "default");
event_registry.fire("query-profile-validity", {profile_id: profile.id});
event_registry.fire("query-profile-validity", { profile_id: profile.id });
return tag;
};
@ -1233,7 +1225,7 @@ export namespace modal_settings {
if (event.status !== "success") return;
event_registry.fire("query-profile-list");
event_registry.one("query-profile-list-result", e => event_registry.fire("select-profile", {profile_id: event.profile_id}));
event_registry.one("query-profile-list-result", e => event_registry.fire("select-profile", { profile_id: event.profile_id }));
});
event_registry.on("set-profile-name-result", event => {
@ -1274,7 +1266,7 @@ export namespace modal_settings {
/* we need a short delay so everything could apply*/
setTimeout(() => {
event_registry.fire("query-profile-validity", {profile_id: event.profile_id});
event_registry.fire("query-profile-validity", { profile_id: event.profile_id });
}, 100);
});
event_registry.on(["set-default-name-result", "set-profile-name-result", "set-identity-name-name-result", "generate-identity-teamspeak-result"], event => {
@ -1283,7 +1275,7 @@ export namespace modal_settings {
return;
}
if ((event as any).status !== "success") return;
event_registry.fire("query-profile-validity", {profile_id: (event as any).profile_id});
event_registry.fire("query-profile-validity", { profile_id: (event as any).profile_id });
})
}
@ -1304,7 +1296,7 @@ export namespace modal_settings {
const button = container.find(".button-set-default");
let current_profile;
button.on('click', event => event_registry.fire("set-default-profile", {profile_id: current_profile}));
button.on('click', event => event_registry.fire("set-default-profile", { profile_id: current_profile }));
event_registry.on("select-profile", event => {
current_profile = event.profile_id;
button.prop("disabled", !event.profile_id || event.profile_id === "default");
@ -1331,7 +1323,7 @@ export namespace modal_settings {
question: tr("Do you really want to delete this profile?"),
}).then(result => {
if (result)
event_registry.fire("delete-profile", {profile_id: current_profile});
event_registry.fire("delete-profile", { profile_id: current_profile });
});
});
@ -1354,7 +1346,7 @@ export namespace modal_settings {
button.on('click', event => {
createInputModal(tr("Please enter a name"), tr("Please enter a name for the new profile:"), text => text.length >= 3 && !profiles.find_profile_by_name(text), value => {
if (value)
event_registry.fire("create-profile", {name: value as string});
event_registry.fire("create-profile", { name: value as string });
}).open();
});
@ -1362,7 +1354,7 @@ export namespace modal_settings {
event_registry.on("create-profile-result", event => {
button.prop("disabled", false);
if (event.status === "success") {
event_registry.fire("select-profile", {profile_id: event.profile_id});
event_registry.fire("select-profile", { profile_id: event.profile_id });
return;
}
@ -1435,7 +1427,7 @@ export namespace modal_settings {
const profile = profiles.find_profile_by_name(text);
if (text.length < 3 || (profile && profile.id != current_profile)) return;
event_registry.fire("set-profile-name", {profile_id: current_profile, name: text});
event_registry.fire("set-profile-name", { profile_id: current_profile, name: text });
});
}
@ -1465,7 +1457,6 @@ export namespace modal_settings {
if (event.status === "success") {
current_identity_type = event.info.identity_type;
fallback_names["nickname"] = event.info.identity_nickname ? event.info.identity_nickname.fallback_name : undefined;
fallback_names["teaforo"] = event.info.identity_forum ? event.info.identity_forum.fallback_name : undefined;
fallback_names["teamspeak"] = event.info.identity_teamspeak ? event.info.identity_teamspeak.fallback_name : undefined;
last_name = event.info.nickname;
@ -1504,7 +1495,7 @@ export namespace modal_settings {
const text = input.val() as string;
if (text.length != 0 && text.length < 3) return;
event_registry.fire("set-default-name", {profile_id: current_profile, name: text});
event_registry.fire("set-default-name", { profile_id: current_profile, name: text });
});
}
@ -1608,7 +1599,7 @@ export namespace modal_settings {
input_unique_id.val(unique_id).attr("placeholder", null);
if (typeof level !== "number")
event_registry.fire("query-identity-teamspeak", {profile_id: current_profile});
event_registry.fire("query-identity-teamspeak", { profile_id: current_profile });
else
input_current_level.val(level).attr("placeholder", null);
@ -1656,10 +1647,10 @@ export namespace modal_settings {
title: tr("Are you sure"),
question: tr("Do you really want to generate a new identity and override the old identity?"),
}).then(result => {
if (result) event_registry.fire("generate-identity-teamspeak", {profile_id: current_profile});
if (result) event_registry.fire("generate-identity-teamspeak", { profile_id: current_profile });
});
} else {
event_registry.fire("generate-identity-teamspeak", {profile_id: current_profile});
event_registry.fire("generate-identity-teamspeak", { profile_id: current_profile });
}
});
@ -1684,10 +1675,10 @@ export namespace modal_settings {
title: tr("Are you sure"),
question: tr("Do you really want to import a new identity and override the old identity?"),
}).then(result => {
if (result) event_registry.fire("import-identity-teamspeak", {profile_id: current_profile});
if (result) event_registry.fire("import-identity-teamspeak", { profile_id: current_profile });
});
} else {
event_registry.fire("import-identity-teamspeak", {profile_id: current_profile});
event_registry.fire("import-identity-teamspeak", { profile_id: current_profile });
}
});
@ -1700,7 +1691,7 @@ export namespace modal_settings {
event_registry.on("import-identity-teamspeak-result", event => {
if (event.profile_id !== current_profile) return;
event_registry.fire_react("query-profile", {profile_id: event.profile_id}); /* we do it like this so the default nickname changes as well */
event_registry.fire_react("query-profile", { profile_id: event.profile_id }); /* we do it like this so the default nickname changes as well */
createInfoModal(tr("Identity imported"), tr("Your identity had been successfully imported generated")).open();
});
}
@ -1719,38 +1710,7 @@ export namespace modal_settings {
}
/* the improve button */
button_improve.on('click', event => event_registry.fire("improve-identity-teamspeak-level", {profile_id: current_profile}));
}
/* special info TeaSpeak - Forum */
{
const container_settings = container.find(".container-teaforo");
const container_valid = container_settings.find(".container-valid");
const container_invalid = container_settings.find(".container-invalid");
const button_setup = container_settings.find(".button-setup");
event_registry.on("select-identity-type", event => {
if (event.profile_id !== current_profile) return;
container_settings.toggle(event.identity_type === "teaforo");
});
event_registry.on("query-profile", event => {
container_valid.toggle(false);
container_invalid.toggle(false);
});
event_registry.on("query-profile-result", event => {
if (event.profile_id !== current_profile) return;
const valid = event.status === "success" && event.info.identity_forum && event.info.identity_forum.valid;
container_valid.toggle(!!valid);
container_invalid.toggle(!valid);
});
button_setup.on('click', event => event_registry.fire_react("setup-forum-connection"));
button_setup.toggle(settings.forum_setuppable);
button_improve.on('click', event => event_registry.fire("improve-identity-teamspeak-level", { profile_id: current_profile }));
}
/* special info nickname */
@ -1811,7 +1771,7 @@ export namespace modal_settings {
const profile = profiles.find_profile_by_name(text);
if (text.length < 3 || (profile && profile.id != current_profile)) return;
event_registry.fire("set-identity-name-name", {profile_id: current_profile, name: text});
event_registry.fire("set-identity-name-name", { profile_id: current_profile, name: text });
});
}
event_registry.on("select-profile", e => current_profile = e.profile_id);
@ -1822,7 +1782,7 @@ export namespace modal_settings {
/* profile list */
{
let timeout;
event_registry.on("query-profile-list", event => timeout = setTimeout(() => event_registry.fire("query-profile-list-result", {status: "timeout"}), 5000));
event_registry.on("query-profile-list", event => timeout = setTimeout(() => event_registry.fire("query-profile-list-result", { status: "timeout" }), 5000));
event_registry.on("query-profile-list-result", event => {
clearTimeout(timeout);
timeout = undefined;
@ -1835,7 +1795,7 @@ export namespace modal_settings {
event_registry.on("create-profile", event => {
clearTimeout(timeouts[event.name]);
timeouts[event.name] = setTimeout(() => {
event_registry.fire("create-profile-result", {name: event.name, status: "timeout"});
event_registry.fire("create-profile-result", { name: event.name, status: "timeout" });
}, 5000);
});
@ -1869,7 +1829,7 @@ export namespace modal_settings {
event_registry.on(event, event => {
clearTimeout(timeouts[event[key]]);
timeouts[event[key]] = setTimeout(() => {
const timeout_event = {status: "timeout"};
const timeout_event = { status: "timeout" };
timeout_event[key] = event[key];
event_registry.fire(response_event, timeout_event as any);
}, 5000);
@ -1899,21 +1859,21 @@ export namespace modal_settings {
if (event.profile_id !== selected_profile) return;
/* the selected profile has been deleted, so we need to select another one */
event_registry.fire("select-profile", {profile_id: "default"});
event_registry.fire("select-profile", { profile_id: "default" });
});
/* reselect the default profile or the new default profile */
event_registry.on("set-default-profile-result", event => {
if (event.status !== "success") return;
if (selected_profile === "default")
event_registry.fire("select-profile", {profile_id: event.new_profile_id});
event_registry.fire("select-profile", { profile_id: event.new_profile_id });
else if (selected_profile === event.old_profile_id)
event_registry.fire("select-profile", {profile_id: "default"});
event_registry.fire("select-profile", { profile_id: "default" });
});
event_registry.on("select-profile", event => {
selected_profile = event.profile_id;
event_registry.fire("query-profile", {profile_id: event.profile_id});
event_registry.fire("query-profile", { profile_id: event.profile_id });
});
event_registry.on("reload-profile", event => {
@ -1923,121 +1883,7 @@ export namespace modal_settings {
}
event_registry.fire("query-profile-list");
event_registry.fire("select-profile", {profile_id: "default"});
event_registry.fire("select-identity-type", {profile_id: "default", identity_type: undefined});
event_registry.fire("select-profile", { profile_id: "default" });
event_registry.fire("select-identity-type", { profile_id: "default", identity_type: undefined });
}
}
function settings_identity_forum(container: JQuery, modal: Modal, update_profiles: () => any) {
const containers_connected = container.find(".show-connected");
const containers_disconnected = container.find(".show-disconnected");
const update_state = () => {
const logged_in = forum.logged_in();
containers_connected.toggle(logged_in);
containers_disconnected.toggle(!logged_in);
if (logged_in) {
container.find(".forum-username").text(forum.data().name());
container.find(".forum-premium").text(forum.data().is_premium() ? tr("Yes") : tr("No"));
}
};
/* login */
{
const button_login = container.find(".button-login");
const input_username = container.find(".input-username");
const input_password = container.find(".input-password");
const container_error = container.find(".container-login .container-error");
const container_captcha_g = container.find(".g-recaptcha");
let captcha: boolean | string = false;
const update_button_state = () => {
let enabled = true;
enabled = enabled && !!input_password.val();
enabled = enabled && !!input_username.val();
enabled = enabled && (typeof (captcha) === "boolean" ? !captcha : !!captcha);
button_login.prop("disabled", !enabled);
};
/* username */
input_username.on('change keyup', update_button_state);
/* password */
input_password.on('change keyup', update_button_state);
button_login.on('click', event => {
input_username.prop("disabled", true);
input_password.prop("disabled", true);
button_login.prop("disabled", true);
container_error.removeClass("shown");
forum.login(input_username.val() as string, input_password.val() as string, typeof (captcha) === "string" ? captcha : undefined).then(state => {
captcha = false;
logTrace(LogCategory.GENERAL, tr("Forum login result: %o"), state);
if (state.status === "success") {
update_state();
update_profiles();
return;
}
setTimeout(() => {
if (!!state.error_message) /* clear password if we have an error */
input_password.val("");
input_password.focus();
update_button_state();
}, 0);
if (state.status === "captcha") {
//TODO Works currently only with localhost!
button_login.hide();
container_error.text(state.error_message || tr("Captcha required")).addClass("shown");
captcha = "";
logDebug(LogCategory.GENERAL, tr("Showing captcha for site-key: %o"), state.captcha.data);
forum.gcaptcha.spawn(container_captcha_g, state.captcha.data, token => {
captcha = token;
logTrace(LogCategory.GENERAL, tr("Got captcha token: %o"), token);
container_captcha_g.hide();
button_login.show();
update_button_state();
}).catch(error => {
logError(LogCategory.GENERAL, tr("Failed to initialize forum captcha: %o"), error);
container_error.text("Failed to initialize GReCaptcha! No authentication possible.").addClass("shown");
container_captcha_g.hide();
button_login.hide();
});
container_captcha_g.show();
} else {
container_error.text(state.error_message || tr("Unknown error")).addClass("shown");
}
}).catch(error => {
logError(LogCategory.GENERAL, tr("Failed to login within the forum. Error: %o"), error);
createErrorModal(tr("Forum login failed."), tr("Forum login failed. Lookup the console for more information")).open();
}).then(() => {
input_username.prop("disabled", false);
input_password.prop("disabled", false);
update_button_state();
});
});
update_button_state();
}
/* logout */
{
container.find(".button-logout").on('click', event => {
forum.logout().catch(error => {
logError(LogCategory.IDENTITIES, tr("Failed to logout from forum: %o"), error);
createErrorModal(tr("Forum logout failed"), formatMessage(tr("Failed to logout from forum account.{:br:}Error: {}"), error)).open();
}).then(() => {
if (modal.shown)
update_state();
update_profiles();
});
});
}
update_state();
}

View File

@ -1,14 +1,19 @@
import * as React from "react";
import {useEffect, useRef, useState} from "react";
import {Registry} from "tc-shared/events";
import { useEffect, useRef, useState } from "react";
import { Registry } from "tc-shared/events";
//import '!style-loader!css-loader!emoji-mart/css/emoji-mart.css'
import { settings, Settings } from "tc-shared/settings";
import { Translatable } from "tc-shared/ui/react-elements/i18n";
import { getTwenmojiHashFromNativeEmoji } from "tc-shared/text/bbcode/EmojiUtil";
import { useGlobalSetting } from "tc-shared/ui/react-elements/Helper";
import Picker from '@emoji-mart/react'
import data from '@emoji-mart/data'
import { Emoji, init } from "emoji-mart";
init({ data })
import '!style-loader!css-loader!emoji-mart/css/emoji-mart.css'
import {Picker, emojiIndex} from 'emoji-mart'
import {settings, Settings} from "tc-shared/settings";
import {Translatable} from "tc-shared/ui/react-elements/i18n";
import {getTwenmojiHashFromNativeEmoji} from "tc-shared/text/bbcode/EmojiUtil";
import {BaseEmoji} from "emoji-mart";
import {useGlobalSetting} from "tc-shared/ui/react-elements/Helper";
const cssStyle = require("./ChatBox.scss");
@ -28,34 +33,38 @@ interface ChatBoxEvents {
}
const LastUsedEmoji = () => {
const settingValue = useGlobalSetting(Settings.KEY_CHAT_LAST_USED_EMOJI);
const lastEmoji: BaseEmoji = (emojiIndex.emojis[settingValue] || emojiIndex.emojis["joy"]) as any;
if(!lastEmoji?.native) {
return <img key={"fallback"} alt={""} src={"img/smiley-smile.svg"} />;
}
// const settingValue = useGlobalSetting(Settings.KEY_CHAT_LAST_USED_EMOJI);
return (
<img draggable={false} src={"https://twemoji.maxcdn.com/v/12.1.2/72x72/" + getTwenmojiHashFromNativeEmoji(lastEmoji.native) + ".png"} alt={lastEmoji.native} className={cssStyle.emoji} />
)
// const lastEmoji: BaseEmoji = (emojiIndex.emojis[settingValue] || emojiIndex.emojis["joy"]) as any;
// if (!lastEmoji?.native) {
// return <img key={"fallback"} alt={""} src={"img/smiley-smile.svg"} />;
// }
const le: Emoji = new Emoji({ id: 'smiley', set: 'native' })
return le.component
// return (
// <img draggable={false} src={"https://twemoji.maxcdn.com/v/12.1.2/72x72/" + getTwenmojiHashFromNativeEmoji(lastEmoji.native) + ".png"} alt={lastEmoji.native} className={cssStyle.emoji} />
// )
}
const EmojiButton = (props: { events: Registry<ChatBoxEvents> }) => {
const [ shown, setShown ] = useState(false);
const [ enabled, setEnabled ] = useState(false);
const [shown, setShown] = useState(false);
const [enabled, setEnabled] = useState(false);
const refContainer = useRef();
useEffect(() => {
if(!shown) {
if (!shown) {
return;
}
const clickListener = (event: MouseEvent) => {
let target = event.target as HTMLElement;
while(target && target !== refContainer.current)
while (target && target !== refContainer.current)
target = target.parentElement;
if(target === refContainer.current && target)
if (target === refContainer.current && target)
return;
setShown(false);
@ -68,6 +77,7 @@ const EmojiButton = (props: { events: Registry<ChatBoxEvents> }) => {
props.events.reactUse("action_set_enabled", event => setEnabled(event.enabled));
props.events.reactUse("action_submit_message", () => setShown(false));
return (
<div className={cssStyle.containerEmojis} ref={refContainer}>
<div className={cssStyle.button} onClick={() => enabled && setShown(true)}>
@ -75,19 +85,35 @@ const EmojiButton = (props: { events: Registry<ChatBoxEvents> }) => {
</div>
<div className={cssStyle.picker} style={{ display: shown ? undefined : "none" }}>
{!shown ? undefined :
// <Picker
// key={"picker"}
// set={"twitter"}
// theme={"light"}
// showPreview={true}
// title={""}
// showSkinTones={true}
// useButton={false}
// native={false}
// onSelect={(emoji: any) => {
// if (enabled) {
// settings.setValue(Settings.KEY_CHAT_LAST_USED_EMOJI, emoji.id as string);
// props.events.fire("action_insert_text", { text: emoji.native, focus: true });
// }
// }}
// />
<Picker
data={data}
key={"picker"}
set={"twitter"}
theme={"light"}
set={"native"}
noCountryFlags={true}
showPreview={true}
title={""}
showSkinTones={true}
useButton={false}
native={false}
skinTonePosition={"none"}
onSelect={(emoji: any) => {
if(enabled) {
settings.setValue(Settings.KEY_CHAT_LAST_USED_EMOJI, emoji.id as string);
onEmojiSelect={(emoji: any) => {
if (enabled) {
//settings.setValue(Settings.KEY_CHAT_LAST_USED_EMOJI, emoji.id as string);
props.events.fire("action_insert_text", { text: emoji.native, focus: true });
}
}}
@ -101,27 +127,27 @@ const EmojiButton = (props: { events: Registry<ChatBoxEvents> }) => {
const pasteTextTransformElement = document.createElement("div");
const nodeToText = (element: Node) => {
if(element instanceof Text) {
if (element instanceof Text) {
return element.textContent;
} else if(element instanceof HTMLElement) {
if(element instanceof HTMLImageElement) {
} else if (element instanceof HTMLElement) {
if (element instanceof HTMLImageElement) {
return element.alt || element.title;
} else if(element instanceof HTMLBRElement) {
} else if (element instanceof HTMLBRElement) {
return '\n';
} else if(element instanceof HTMLAnchorElement) {
} else if (element instanceof HTMLAnchorElement) {
const content = [...element.childNodes].map(nodeToText).join("");
if(element.href) {
if(settings.getValue(Settings.KEY_CHAT_ENABLE_MARKDOWN)) {
if(content && element.title) {
if (element.href) {
if (settings.getValue(Settings.KEY_CHAT_ENABLE_MARKDOWN)) {
if (content && element.title) {
return `[${content}](${element.href} "${element.title}")`;
} else if(content) {
} else if (content) {
return `[${content}](${element.href})`;
} else {
return `[${element.href}](${element.href})`;
}
} else if(settings.getValue(Settings.KEY_CHAT_ENABLE_BBCODE)) {
if(content) {
} else if (settings.getValue(Settings.KEY_CHAT_ENABLE_BBCODE)) {
if (content) {
return `[url=${element.href}]${content}"[/url]`;
} else {
return `[url]${element.href}"[/url]`;
@ -134,11 +160,11 @@ const nodeToText = (element: Node) => {
}
}
if(element.children.length > 0) {
if (element.children.length > 0) {
return [...element.childNodes].map(nodeToText).join("");
}
return typeof(element.innerText) === "string" ? element.innerText : "";
return typeof (element.innerText) === "string" ? element.innerText : "";
} else {
return "";
}
@ -146,19 +172,19 @@ const nodeToText = (element: Node) => {
const htmlEscape = (message: string) => {
pasteTextTransformElement.innerText = message;
message = pasteTextTransformElement.innerHTML;
message = pasteTextTransformElement.innerHTML;
return message.replace(/ /g, '&nbsp;');
};
const TextInput = (props: { events: Registry<ChatBoxEvents>, enabled?: boolean, placeholder?: string }) => {
const [ enabled, setEnabled ] = useState(!!props.enabled);
const [ historyIndex, setHistoryIndex ] = useState(-1);
const [enabled, setEnabled] = useState(!!props.enabled);
const [historyIndex, setHistoryIndex] = useState(-1);
const history = useRef([]);
const refInput = useRef<HTMLInputElement>();
const typingTimeout = useRef(undefined);
const triggerTyping = () => {
if(typeof typingTimeout.current === "number")
if (typeof typingTimeout.current === "number")
return;
props.events.fire("notify_typing");
@ -182,7 +208,7 @@ const TextInput = (props: { events: Registry<ChatBoxEvents>, enabled?: boolean,
event.preventDefault();
const clipboard = event.clipboardData || (window as any).clipboardData;
if(!clipboard) return;
if (!clipboard) return;
const rawText = clipboard.getData('text/plain');
const selection = window.getSelection();
@ -191,7 +217,7 @@ const TextInput = (props: { events: Registry<ChatBoxEvents>, enabled?: boolean,
}
let htmlXML = clipboard.getData('text/html');
if(!htmlXML) {
if (!htmlXML) {
pasteTextTransformElement.textContent = rawText;
htmlXML = pasteTextTransformElement.innerHTML;
}
@ -235,33 +261,33 @@ const TextInput = (props: { events: Registry<ChatBoxEvents>, enabled?: boolean,
triggerTyping();
const inputEmpty = refInput.current.innerText.trim().length === 0;
if(event.key === "Enter" && !event.shiftKey) {
if(inputEmpty) {
if (event.key === "Enter" && !event.shiftKey) {
if (inputEmpty) {
return;
}
const text = refInput.current.innerText;
props.events.fire("action_submit_message", { message: text });
history.current.push(text);
while(history.current.length > 10) {
while (history.current.length > 10) {
history.current.pop_front();
}
refInput.current.innerText = "";
setHistoryIndex(-1);
event.preventDefault();
} else if(event.key === "ArrowUp") {
} else if (event.key === "ArrowUp") {
const inputOriginal = history.current[historyIndex] === refInput.current.innerText;
if(inputEmpty && (historyIndex === -1 || !inputOriginal)) {
if (inputEmpty && (historyIndex === -1 || !inputOriginal)) {
setHistory(history.current.length - 1);
event.preventDefault();
} else if(historyIndex > 0 && inputOriginal) {
} else if (historyIndex > 0 && inputOriginal) {
setHistory(historyIndex - 1);
event.preventDefault();
}
} else if(event.key === "ArrowDown") {
if(history.current[historyIndex] === refInput.current.innerText) {
if(historyIndex < history.current.length - 1) {
} else if (event.key === "ArrowDown") {
if (history.current[historyIndex] === refInput.current.innerText) {
if (historyIndex < history.current.length - 1) {
setHistory(historyIndex + 1);
} else {
setHistory(-1);
@ -273,7 +299,7 @@ const TextInput = (props: { events: Registry<ChatBoxEvents>, enabled?: boolean,
props.events.reactUse("action_request_focus", () => refInput.current?.focus());
props.events.reactUse("notify_typing", () => {
if(typeof typingTimeout.current === "number") {
if (typeof typingTimeout.current === "number") {
return;
}
@ -281,15 +307,15 @@ const TextInput = (props: { events: Registry<ChatBoxEvents>, enabled?: boolean,
});
props.events.reactUse("action_insert_text", event => {
refInput.current.innerHTML = refInput.current.innerHTML + event.text;
if(event.focus) {
if (event.focus) {
refInput.current.focus();
}
});
props.events.reactUse("action_set_enabled", event => {
setEnabled(event.enabled);
if(!event.enabled) {
if (!event.enabled) {
const text = refInput.current.innerText;
if(text.trim().length !== 0)
if (text.trim().length !== 0)
history.current.push(text);
refInput.current.innerText = "";
}
@ -324,17 +350,17 @@ export interface ChatBoxState {
}
const MarkdownFormatHelper = () => {
const [ visible, setVisible ] = useState(settings.getValue(Settings.KEY_CHAT_ENABLE_MARKDOWN));
const [visible, setVisible] = useState(settings.getValue(Settings.KEY_CHAT_ENABLE_MARKDOWN));
settings.events.reactUse("notify_setting_changed", event => {
if(event.setting !== Settings.KEY_CHAT_ENABLE_MARKDOWN.key) {
if (event.setting !== Settings.KEY_CHAT_ENABLE_MARKDOWN.key) {
return;
}
setVisible(settings.getValue(Settings.KEY_CHAT_ENABLE_MARKDOWN));
});
if(visible) {
if (visible) {
return (
<div key={"help"} className={cssStyle.containerHelp}>*italic*, **bold**, ~~strikethrough~~, `code`, <Translatable>and more</Translatable>...</div>
);
@ -380,7 +406,7 @@ export class ChatBox extends React.Component<ChatBoxProperties, ChatBoxState> {
}
componentDidUpdate(prevProps: Readonly<ChatBoxProperties>, prevState: Readonly<ChatBoxState>, snapshot?: any): void {
if(prevState.enabled !== this.state.enabled) {
if (prevState.enabled !== this.state.enabled) {
this.events.fire_react("action_set_enabled", { enabled: this.state.enabled });
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -8,14 +8,27 @@
"declaration": true,
"emitDeclarationOnly": true,
"esModuleInterop": true,
"skipLibCheck": true,
"baseUrl": "../../",
"paths": {
"tc-shared/*": ["shared/js/*"],
"tc-loader": ["loader/exports/loader.d.ts"],
"svg-sprites/*": ["shared/svg-sprites/*"],
"vendor/xbbcode/*": ["vendor/xbbcode/src/*"],
"tc-events": ["vendor/TeaEventBus/src/index.ts"],
"tc-services": ["vendor/TeaClientServices/src/index.ts"]
"tc-shared/*": [
"shared/js/*"
],
"tc-loader": [
"loader/exports/loader.d.ts"
],
"svg-sprites/*": [
"shared/svg-sprites/*"
],
"vendor/xbbcode/*": [
"vendor/xbbcode/src/*"
],
"tc-events": [
"vendor/TeaEventBus/src/index.ts"
],
"tc-services": [
"vendor/TeaClientServices/src/index.ts"
]
}
},
"exclude": [

View File

@ -6,6 +6,7 @@
"sourceMap": true,
"experimentalDecorators": true,
"esModuleInterop": true,
"skipLibCheck": true,
"plugins": [ /* ttypescript */
{
"transform": "../../tools/trgen/ttsc_transformer.js",

0
tools/build_trgen.sh Normal file → Executable file
View File

View File

@ -1,13 +1,14 @@
{
"compilerOptions": {
"baseUrl": ".",
"skipLibCheck": true,
"moduleResolution": "node",
"module": "commonjs",
"lib": ["es6"],
"lib": [
"es6"
],
"typeRoots": [],
"types": [],
"esModuleInterop": true
},
"files": [

View File

@ -4,20 +4,22 @@
"target": "es6",
"module": "commonjs",
"sourceMap": true,
"lib": ["es6", "dom"],
"lib": [
"es6",
"dom"
],
"removeComments": false,
"esModuleInterop": true
"esModuleInterop": true,
"skipLibCheck": true
},
"include": [
"webpack.config.ts",
"webpack-client.config.ts",
"webpack-web.config.ts",
"webpack/build-definitions.d.ts",
"webpack/HtmlWebpackInlineSource.ts",
"webpack/WatLoader.ts",
"webpack/ManifestPlugin.ts",
"babel.config.ts",
"postcss.config.ts",
"file.ts"

View File

@ -5,19 +5,35 @@
"target": "es6",
"module": "commonjs",
"sourceMap": true,
"lib": ["ES7", "dom", "dom.iterable"],
"lib": [
"ES7",
"dom",
"dom.iterable"
],
"removeComments": true, /* we dont really need them within the target files */
"jsx": "react",
"esModuleInterop": true,
"baseUrl": ".",
"skipLibCheck": true,
"paths": {
"tc-shared/*": ["shared/js/*"],
"tc-loader": ["loader/exports/loader.d.ts"],
"tc-events": ["vendor/TeaEventBus/src/index.ts"],
"tc-services": ["vendor/TeaClientServices/src/index.ts"],
"svg-sprites/*": ["shared/svg-sprites/*"],
"vendor/xbbcode/*": ["vendor/xbbcode/src/*"]
"tc-shared/*": [
"shared/js/*"
],
"tc-loader": [
"loader/exports/loader.d.ts"
],
"tc-events": [
"vendor/TeaEventBus/src/index.ts"
],
"tc-services": [
"vendor/TeaClientServices/src/index.ts"
],
"svg-sprites/*": [
"shared/svg-sprites/*"
],
"vendor/xbbcode/*": [
"vendor/xbbcode/src/*"
]
}
},
"exclude": [

View File

@ -1,11 +1,11 @@
import {LogCategory, logError, logTrace, logWarn} from "tc-shared/log";
import {tr} from "tc-shared/i18n/localize";
import {default_options, DNSAddress, DNSResolveResult, ResolveOptions} from "tc-shared/dns";
import {executeDnsRequest, RRType} from "./api";
import { LogCategory, logError, logTrace, logWarn } from "tc-shared/log";
import { tr } from "tc-shared/i18n/localize";
import { default_options, DNSAddress, DNSResolveResult, ResolveOptions } from "tc-shared/dns";
import { executeDnsRequest, RRType } from "./api";
interface DNSResolveMethod {
name() : string;
resolve(address: DNSAddress) : Promise<DNSAddress | undefined>;
name(): string;
resolve(address: DNSAddress): Promise<DNSAddress | undefined>;
}
class LocalhostResolver implements DNSResolveMethod {
@ -14,7 +14,7 @@ class LocalhostResolver implements DNSResolveMethod {
}
async resolve(address: DNSAddress): Promise<DNSAddress | undefined> {
if(address.hostname === "localhost") {
if (address.hostname === "localhost") {
return {
hostname: "127.0.0.1",
port: address.port
@ -26,6 +26,20 @@ class LocalhostResolver implements DNSResolveMethod {
}
class FakeResolver implements DNSResolveMethod {
name(): string {
return "fake resolver";
}
async resolve(address: DNSAddress): Promise<DNSAddress | undefined> {
return {
hostname: "tea.lp.kle.li",
port: address.port
}
}
}
class IPResolveMethod implements DNSResolveMethod {
readonly v6: boolean;
@ -40,7 +54,7 @@ class IPResolveMethod implements DNSResolveMethod {
async resolve(address: DNSAddress): Promise<DNSAddress | undefined> {
const answer = await executeDnsRequest(address.hostname, this.v6 ? RRType.AAAA : RRType.A);
if(!answer.length) {
if (!answer.length) {
return undefined;
}
@ -72,10 +86,10 @@ class SRVResolveMethod implements DNSResolveMethod {
async resolve(address: DNSAddress): Promise<DNSAddress | undefined> {
const answer = await executeDnsRequest((this.application ? this.application + "." : "") + address.hostname, RRType.SRV);
const records: {[key: number]: ParsedSVRRecord[]} = {};
for(const record of answer) {
const records: { [key: number]: ParsedSVRRecord[] } = {};
for (const record of answer) {
const parts = record.data.split(" ");
if(parts.length !== 4) {
if (parts.length !== 4) {
logWarn(LogCategory.DNS, tr("Failed to parse SRV record %s. Invalid split length."), record);
continue;
}
@ -84,7 +98,7 @@ class SRVResolveMethod implements DNSResolveMethod {
const weight = parseInt(parts[1]);
const port = parseInt(parts[2]);
if((priority < 0 || priority > 65535) || (weight < 0 || weight > 65535) || (port < 0 || port > 65535)) {
if ((priority < 0 || priority > 65535) || (weight < 0 || weight > 65535) || (port < 0 || port > 65535)) {
logWarn(LogCategory.DNS, tr("Failed to parse SRV record %s. Malformed data."), record);
continue;
}
@ -99,35 +113,35 @@ class SRVResolveMethod implements DNSResolveMethod {
/* get the record with the highest priority */
const priority_strings = Object.keys(records);
if(!priority_strings.length) {
if (!priority_strings.length) {
return undefined;
}
let highestPriority: ParsedSVRRecord[];
for(const priority_str of priority_strings) {
if(!highestPriority || !highestPriority.length) {
for (const priority_str of priority_strings) {
if (!highestPriority || !highestPriority.length) {
highestPriority = records[priority_str];
}
if(highestPriority[0].priority < parseInt(priority_str)) {
if (highestPriority[0].priority < parseInt(priority_str)) {
highestPriority = records[priority_str];
}
}
if(!highestPriority.length) {
if (!highestPriority.length) {
return undefined;
}
/* select randomly one record */
let record: ParsedSVRRecord;
const max_weight = highestPriority.map(e => e.weight).reduce((a, b) => a + b, 0);
if(max_weight == 0) {
if (max_weight == 0) {
record = highestPriority[Math.floor(Math.random() * highestPriority.length)];
} else {
let rnd = Math.random() * max_weight;
for(let i = 0; i < highestPriority.length; i++) {
for (let i = 0; i < highestPriority.length; i++) {
rnd -= highestPriority[i].weight;
if(rnd > 0) {
if (rnd > 0) {
continue;
}
@ -136,7 +150,7 @@ class SRVResolveMethod implements DNSResolveMethod {
}
}
if(!record) {
if (!record) {
/* shall never happen */
record = highestPriority[0];
}
@ -165,7 +179,7 @@ class SRV_IPResolveMethod implements DNSResolveMethod {
async resolve(address: DNSAddress): Promise<DNSAddress | undefined> {
const srvAddress = await this.srvResolver.resolve(address);
if(!srvAddress) {
if (!srvAddress) {
return undefined;
}
@ -190,7 +204,7 @@ class DomainRootResolveMethod implements DNSResolveMethod {
async resolve(address: DNSAddress): Promise<DNSAddress | undefined> {
const parts = address.hostname.split(".");
if(parts.length < 3) {
if (parts.length < 3) {
return undefined;
}
@ -203,7 +217,7 @@ class DomainRootResolveMethod implements DNSResolveMethod {
class TeaSpeakDNSResolve {
readonly address: DNSAddress;
private resolvers: {[key: string]:{ resolver: DNSResolveMethod, after: string[] }} = {};
private resolvers: { [key: string]: { resolver: DNSResolveMethod, after: string[] } } = {};
private resolving = false;
private timeout;
@ -218,15 +232,15 @@ class TeaSpeakDNSResolve {
}
registerResolver(resolver: DNSResolveMethod, ...after: (string | DNSResolveMethod)[]) {
if(this.resolving) {
if (this.resolving) {
throw tr("resolver is already resolving");
}
this.resolvers[resolver.name()] = { resolver: resolver, after: after.map(e => typeof e === "string" ? e : e.name()) };
}
resolve(timeout: number) : Promise<DNSAddress> {
if(this.resolving) {
resolve(timeout: number): Promise<DNSAddress> {
if (this.resolving) {
throw tr("already resolving");
}
this.resolving = true;
@ -263,52 +277,53 @@ class TeaSpeakDNSResolve {
let invoke_count = 0;
_main_loop:
for(const resolver_name of Object.keys(this.resolvers)) {
if(this.resolving_resolvers.findIndex(e => e === resolver_name) !== -1) continue;
if(this.finished_resolvers.findIndex(e => e === resolver_name) !== -1) continue;
for (const resolver_name of Object.keys(this.resolvers)) {
if (this.resolving_resolvers.findIndex(e => e === resolver_name) !== -1) continue;
if (this.finished_resolvers.findIndex(e => e === resolver_name) !== -1) continue;
const resolver = this.resolvers[resolver_name];
for(const after of resolver.after)
if(this.finished_resolvers.findIndex(e => e === after) === -1) continue _main_loop;
const resolver = this.resolvers[resolver_name];
for (const after of resolver.after)
if (this.finished_resolvers.findIndex(e => e === after) === -1) continue _main_loop;
invoke_count++;
logTrace(LogCategory.DNS, tr(" Executing resolver %s"), resolver_name);
invoke_count++;
logTrace(LogCategory.DNS, tr(" Executing resolver %s"), resolver_name);
this.resolving_resolvers.push(resolver_name);
resolver.resolver.resolve(this.address).then(result => {
if(!this.resolving || !this.callback_success) return; /* resolve has been finished already */
this.finished_resolvers.push(resolver_name);
this.resolving_resolvers.push(resolver_name);
resolver.resolver.resolve(this.address).then(result => {
if (!this.resolving || !this.callback_success) return; /* resolve has been finished already */
this.finished_resolvers.push(resolver_name);
if(!result) {
logTrace(LogCategory.DNS, tr(" Resolver %s returned an empty response."), resolver_name);
this.invoke_resolvers();
return;
}
logTrace(LogCategory.DNS, tr(" Successfully resolved address %s:%d to %s:%d via resolver %s"),
this.address.hostname, this.address.port,
result.hostname, result.port,
resolver_name);
this.callback_success(result);
}).catch(error => {
if(!this.resolving || !this.callback_success) return; /* resolve has been finished already */
this.finished_resolvers.push(resolver_name);
logTrace(LogCategory.DNS, tr(" Resolver %s ran into an error: %o"), resolver_name, error);
if (!result) {
logTrace(LogCategory.DNS, tr(" Resolver %s returned an empty response."), resolver_name);
this.invoke_resolvers();
}).then(() => {
this.resolving_resolvers.remove(resolver_name);
if(!this.resolving_resolvers.length && this.resolving)
this.invoke_resolvers();
});
}
return;
}
if(invoke_count === 0 && !this.resolving_resolvers.length && this.resolving) {
logTrace(LogCategory.DNS, tr(" Successfully resolved address %s:%d to %s:%d via resolver %s"),
this.address.hostname, this.address.port,
result.hostname, result.port,
resolver_name);
this.callback_success(result);
}).catch(error => {
if (!this.resolving || !this.callback_success) return; /* resolve has been finished already */
this.finished_resolvers.push(resolver_name);
logTrace(LogCategory.DNS, tr(" Resolver %s ran into an error: %o"), resolver_name, error);
this.invoke_resolvers();
}).then(() => {
this.resolving_resolvers.remove(resolver_name);
if (!this.resolving_resolvers.length && this.resolving)
this.invoke_resolvers();
});
}
if (invoke_count === 0 && !this.resolving_resolvers.length && this.resolving) {
this.callback_fail("no response");
}
}
}
const kResolverFake = new FakeResolver();
const kResolverLocalhost = new LocalhostResolver();
const kResolverIpV4 = new IPResolveMethod(false);
@ -320,14 +335,16 @@ const resolverSrvTS3 = new SRV_IPResolveMethod(new SRVResolveMethod("_ts3._udp")
const resolverDrSrvTS = new DomainRootResolveMethod(resolverSrvTS);
const resolverDrSrvTS3 = new DomainRootResolveMethod(resolverSrvTS3);
export async function resolveTeaSpeakServerAddress(address: DNSAddress, _options?: ResolveOptions) : Promise<DNSResolveResult> {
export async function resolveTeaSpeakServerAddress(address: DNSAddress, _options?: ResolveOptions): Promise<DNSResolveResult> {
try {
const options = Object.assign({}, default_options);
Object.assign(options, _options);
const resolver = new TeaSpeakDNSResolve(address);
resolver.registerResolver(kResolverLocalhost);
resolver.registerResolver(kResolverFake);
resolver.registerResolver(kResolverLocalhost, kResolverFake);
resolver.registerResolver(resolverSrvTS, kResolverLocalhost);
resolver.registerResolver(resolverSrvTS3, kResolverLocalhost);
@ -340,7 +357,7 @@ export async function resolveTeaSpeakServerAddress(address: DNSAddress, _options
resolver.registerResolver(kResolverIpV6, kResolverIpV4);
const response = await resolver.resolve(options.timeout || 5000);
if(!response) {
if (!response) {
return {
status: "empty-result"
};
@ -352,7 +369,7 @@ export async function resolveTeaSpeakServerAddress(address: DNSAddress, _options
resolvedAddress: response
};
} catch (error) {
if(typeof error !== "string") {
if (typeof error !== "string") {
logError(LogCategory.DNS, tr("Failed to resolve %o: %o"), address, error);
error = tr("lookup the console");
}
@ -364,9 +381,9 @@ export async function resolveTeaSpeakServerAddress(address: DNSAddress, _options
}
}
export async function resolveAddressIpV4(address: string) : Promise<string> {
export async function resolveAddressIpV4(address: string): Promise<string> {
const result = await executeDnsRequest(address, RRType.A);
if(!result.length) return undefined;
if (!result.length) return undefined;
return result[0].data;
}

View File

@ -46,9 +46,9 @@ const generateLocalBuildInfo = async (target: string): Promise<LocalBuildInfo> =
{
const gitRevision = fs.readFileSync(path.join(__dirname, ".git", "HEAD")).toString();
if(gitRevision.indexOf("/") === -1) {
info.gitVersion = (gitRevision || "00000000").substr(0, 8);
info.gitVersion = (gitRevision || "00000000").substring(0, 8);
} else {
info.gitVersion = fs.readFileSync(path.join(__dirname, ".git", gitRevision.substr(5).trim())).toString().substr(0, 8);
info.gitVersion = fs.readFileSync(path.join(__dirname, ".git", gitRevision.substring(5).trim())).toString().substring(0, 8);
}
try {