Full Code of screego/server for AI

master 5285d3e07993 cached
94 files
210.7 KB
60.2k tokens
244 symbols
1 requests
Download .txt
Showing preview only (230K chars total). Download the full file or copy to clipboard to get everything.
Repository: screego/server
Branch: master
Commit: 5285d3e07993
Files: 94
Total size: 210.7 KB

Directory structure:
gitextract_5ezl1r5_/

├── .github/
│   ├── FUNDING.yml
│   └── workflows/
│       └── build.yml
├── .gitignore
├── .golangci.yml
├── .goreleaser.yml
├── Dockerfile
├── LICENSE
├── README.md
├── auth/
│   └── auth.go
├── cmd/
│   ├── command.go
│   ├── hash.go
│   └── serve.go
├── config/
│   ├── config.go
│   ├── error.go
│   ├── ip.go
│   ├── ipdns/
│   │   ├── dns.go
│   │   ├── provider.go
│   │   └── static.go
│   ├── loglevel.go
│   ├── loglevel_test.go
│   └── mode/
│       ├── mode.go
│       └── mode_test.go
├── docs/
│   ├── .nojekyll
│   ├── CNAME
│   ├── README.md
│   ├── _sidebar.md
│   ├── config.md
│   ├── development.md
│   ├── faq.md
│   ├── index.html
│   ├── install.md
│   ├── nat-traversal.md
│   └── proxy.md
├── go.mod
├── go.sum
├── logger/
│   └── logger.go
├── main.go
├── router/
│   └── router.go
├── screego.config.development
├── screego.config.example
├── server/
│   ├── server.go
│   └── server_test.go
├── turn/
│   ├── none.go
│   ├── portrange.go
│   └── server.go
├── ui/
│   ├── .gitignore
│   ├── .prettierrc
│   ├── index.html
│   ├── package.json
│   ├── serve.go
│   ├── src/
│   │   ├── LoginForm.tsx
│   │   ├── NumberField.tsx
│   │   ├── Room.tsx
│   │   ├── RoomManage.tsx
│   │   ├── Router.tsx
│   │   ├── SettingDialog.tsx
│   │   ├── Video.tsx
│   │   ├── global.css
│   │   ├── index.tsx
│   │   ├── message.ts
│   │   ├── settings.ts
│   │   ├── url.ts
│   │   ├── useConfig.ts
│   │   ├── useRoom.ts
│   │   ├── useRoomID.ts
│   │   └── vite-env.d.ts
│   ├── tsconfig.json
│   ├── tsconfig.node.json
│   └── vite.config.mts
├── users
├── util/
│   ├── password.go
│   └── sillyname.go
└── ws/
    ├── client.go
    ├── event.go
    ├── event_clientanswer.go
    ├── event_clientice.go
    ├── event_connected.go
    ├── event_create.go
    ├── event_disconnected.go
    ├── event_health.go
    ├── event_hostice.go
    ├── event_hostoffer.go
    ├── event_join.go
    ├── event_name.go
    ├── event_share.go
    ├── event_stop_share.go
    ├── once.go
    ├── once_test.go
    ├── outgoing/
    │   └── messages.go
    ├── prometheus.go
    ├── readwrite.go
    ├── room.go
    ├── rooms.go
    └── rooms_test.go

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms

github: jmattheis
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: https://jmattheis.de/donate


================================================
FILE: .github/workflows/build.yml
================================================
name: build
on: [push, pull_request]

jobs:
  screego:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/setup-go@4dc6199c7b1a012772edbd06daecab0f50c9053c # v6.1.0
        with:
          go-version: 1.25.x
      - uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f #v6.1.0
        with:
          node-version: '25'
      - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 #v6.0.1
      - run: go mod download
      - run: (cd ui && yarn)
      - run: (cd ui && yarn build)
      - run: (cd ui && yarn testformat)
      - uses: golangci/golangci-lint-action@1e7e51e771db61008b38414a730f564565cf7c20 # 9.2.0
        with:
          version: v2.7.2
      - run: go build ./...
      - run: go test -race ./...
      - if: startsWith(github.ref, 'refs/tags/v')
        run: |
          echo "$DOCKER_PASS" | docker login --username "$DOCKER_USER" --password-stdin
          echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io --username "${{ github.actor }}" --password-stdin
        env:
          DOCKER_USER: ${{ secrets.DOCKER_USER }}
          DOCKER_PASS: ${{ secrets.DOCKER_PASS }}
      - if: startsWith(github.ref, 'refs/tags/v')
        uses: goreleaser/goreleaser-action@e435ccd777264be153ace6237001ef4d979d3a7a #v6.4.0
        with:
          version: 2.13.0
          args: release --skip=validate
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}


================================================
FILE: .gitignore
================================================
/target
/.idea
*-packr.go
/dist/
*.local


================================================
FILE: .golangci.yml
================================================
version: "2"
linters:
  disable:
    - errcheck



================================================
FILE: .goreleaser.yml
================================================
# This is an example goreleaser.yaml file with some sane defaults.
# Make sure to check the documentation at http://goreleaser.com
project_name: screego
version: 2
before:
  hooks:
    - go mod download
builds:
  - env:
      - CGO_ENABLED=0
    goos:
      - linux
      - windows
      - darwin
      - freebsd
      - openbsd
    goarch:
      - "386"
      - amd64
      - arm
      - arm64
      - ppc64
      - ppc64le
    goarm:
      - "6"
      - "7"
    flags:
      - '-tags="netgo osusergo"'
    ldflags:
      - "-s"
      - "-w"
      - "-X main.version={{.Version}}"
      - "-X main.commitHash={{.Commit}}"
      - "-X main.mode=prod"
archives:
  - files:
      - LICENSE
      - README.md
      - screego.config.example
    name_template: '{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{- if eq .Arch "386" }}i386{{- else }}{{ .Arch }}{{ end }}{{ if .Arm }}v{{ .Arm }}{{ end }}'
    format_overrides:
      - goos: windows
        formats: [zip]
checksum:
  disable: true
changelog:
  disable: true
dockers:
  - use: buildx
    goos: linux
    goarch: amd64
    goarm: ""
    image_templates:
      - "screego/server:amd64-unstable"
      - "screego/server:amd64-{{ .RawVersion }}"
      - "screego/server:amd64-{{ .Major }}"
      - "ghcr.io/screego/server:amd64-unstable"
      - "ghcr.io/screego/server:amd64-{{ .RawVersion }}"
      - "ghcr.io/screego/server:amd64-{{ .Major }}"
    dockerfile: Dockerfile
    build_flag_templates:
      - "--platform=linux/amd64"
      - "--label=org.opencontainers.image.created={{.Date}}"
      - "--label=org.opencontainers.image.title={{.ProjectName}}"
      - "--label=org.opencontainers.image.revision={{.FullCommit}}"
      - "--label=org.opencontainers.image.version={{.Version}}"
  - use: buildx
    goos: linux
    goarch: "386"
    goarm: ""
    image_templates:
      - "screego/server:386-unstable"
      - "screego/server:386-{{ .RawVersion }}"
      - "screego/server:386-{{ .Major }}"
      - "ghcr.io/screego/server:386-unstable"
      - "ghcr.io/screego/server:386-{{ .RawVersion }}"
      - "ghcr.io/screego/server:386-{{ .Major }}"
    dockerfile: Dockerfile
    build_flag_templates:
      - "--platform=linux/386"
      - "--label=org.opencontainers.image.created={{.Date}}"
      - "--label=org.opencontainers.image.title={{.ProjectName}}"
      - "--label=org.opencontainers.image.revision={{.FullCommit}}"
      - "--label=org.opencontainers.image.version={{.Version}}"
  - use: buildx
    goos: linux
    goarch: arm64
    goarm: ""
    image_templates:
      - "screego/server:arm64-unstable"
      - "screego/server:arm64-{{ .RawVersion }}"
      - "screego/server:arm64-{{ .Major }}"
      - "ghcr.io/screego/server:arm64-unstable"
      - "ghcr.io/screego/server:arm64-{{ .RawVersion }}"
      - "ghcr.io/screego/server:arm64-{{ .Major }}"
    dockerfile: Dockerfile
    build_flag_templates:
      - "--platform=linux/arm64"
      - "--label=org.opencontainers.image.created={{.Date}}"
      - "--label=org.opencontainers.image.title={{.ProjectName}}"
      - "--label=org.opencontainers.image.revision={{.FullCommit}}"
      - "--label=org.opencontainers.image.version={{.Version}}"
  - use: buildx
    goos: linux
    goarch: arm
    goarm: 7
    image_templates:
      - "screego/server:armv7-unstable"
      - "screego/server:armv7-{{ .RawVersion }}"
      - "screego/server:armv7-{{ .Major }}"
      - "ghcr.io/screego/server:armv7-unstable"
      - "ghcr.io/screego/server:armv7-{{ .RawVersion }}"
      - "ghcr.io/screego/server:armv7-{{ .Major }}"
    dockerfile: Dockerfile
    build_flag_templates:
      - "--platform=linux/arm/v7"
      - "--label=org.opencontainers.image.created={{.Date}}"
      - "--label=org.opencontainers.image.title={{.ProjectName}}"
      - "--label=org.opencontainers.image.revision={{.FullCommit}}"
      - "--label=org.opencontainers.image.version={{.Version}}"
  - use: buildx
    goos: linux
    goarch: arm
    goarm: 6
    image_templates:
      - "screego/server:armv6-unstable"
      - "screego/server:armv6-{{ .RawVersion }}"
      - "screego/server:armv6-{{ .Major }}"
      - "ghcr.io/screego/server:armv6-unstable"
      - "ghcr.io/screego/server:armv6-{{ .RawVersion }}"
      - "ghcr.io/screego/server:armv6-{{ .Major }}"
    dockerfile: Dockerfile
    build_flag_templates:
      - "--platform=linux/arm/v6"
      - "--label=org.opencontainers.image.created={{.Date}}"
      - "--label=org.opencontainers.image.title={{.ProjectName}}"
      - "--label=org.opencontainers.image.revision={{.FullCommit}}"
      - "--label=org.opencontainers.image.version={{.Version}}"
  - use: buildx
    goos: linux
    goarch: ppc64le
    goarm: ""
    image_templates:
      - "screego/server:ppc64le-unstable"
      - "screego/server:ppc64le-{{ .RawVersion }}"
      - "screego/server:ppc64le-{{ .Major }}"
      - "ghcr.io/screego/server:ppc64le-unstable"
      - "ghcr.io/screego/server:ppc64le-{{ .RawVersion }}"
      - "ghcr.io/screego/server:ppc64le-{{ .Major }}"
    dockerfile: Dockerfile
    build_flag_templates:
      - "--platform=linux/ppc64le"
      - "--label=org.opencontainers.image.created={{.Date}}"
      - "--label=org.opencontainers.image.title={{.ProjectName}}"
      - "--label=org.opencontainers.image.revision={{.FullCommit}}"
      - "--label=org.opencontainers.image.version={{.Version}}"
docker_manifests:
  - name_template: "ghcr.io/screego/server:unstable"
    image_templates:
      - "ghcr.io/screego/server:amd64-unstable"
      - "ghcr.io/screego/server:386-unstable"
      - "ghcr.io/screego/server:arm64-unstable"
      - "ghcr.io/screego/server:armv7-unstable"
      - "ghcr.io/screego/server:armv6-unstable"
      - "ghcr.io/screego/server:ppc64le-unstable"
  - name_template: "screego/server:unstable"
    image_templates:
      - "screego/server:amd64-unstable"
      - "screego/server:386-unstable"
      - "screego/server:arm64-unstable"
      - "screego/server:armv7-unstable"
      - "screego/server:armv6-unstable"
      - "screego/server:ppc64le-unstable"
  - name_template: "screego/server:{{ .RawVersion }}"
    image_templates:
      - "screego/server:amd64-{{ .RawVersion }}"
      - "screego/server:386-{{ .RawVersion }}"
      - "screego/server:arm64-{{ .RawVersion }}"
      - "screego/server:armv7-{{ .RawVersion }}"
      - "screego/server:armv6-{{ .RawVersion }}"
      - "screego/server:ppc64le-{{ .RawVersion }}"
  - name_template: "ghcr.io/screego/server:{{ .RawVersion }}"
    image_templates:
      - "ghcr.io/screego/server:amd64-{{ .RawVersion }}"
      - "ghcr.io/screego/server:386-{{ .RawVersion }}"
      - "ghcr.io/screego/server:arm64-{{ .RawVersion }}"
      - "ghcr.io/screego/server:armv7-{{ .RawVersion }}"
      - "ghcr.io/screego/server:armv6-{{ .RawVersion }}"
      - "ghcr.io/screego/server:ppc64le-{{ .RawVersion }}"
  - name_template: "screego/server:{{ .Major }}"
    image_templates:
      - "screego/server:amd64-{{ .Major }}"
      - "screego/server:386-{{ .Major }}"
      - "screego/server:arm64-{{ .Major }}"
      - "screego/server:armv7-{{ .Major }}"
      - "screego/server:armv6-{{ .Major }}"
      - "screego/server:ppc64le-{{ .Major }}"
  - name_template: "ghcr.io/screego/server:{{ .Major }}"
    image_templates:
      - "ghcr.io/screego/server:amd64-{{ .Major }}"
      - "ghcr.io/screego/server:386-{{ .Major }}"
      - "ghcr.io/screego/server:arm64-{{ .Major }}"
      - "ghcr.io/screego/server:armv7-{{ .Major }}"
      - "ghcr.io/screego/server:armv6-{{ .Major }}"
      - "ghcr.io/screego/server:ppc64le-{{ .Major }}"


================================================
FILE: Dockerfile
================================================
FROM scratch
USER 1001
COPY screego /screego
EXPOSE 3478/tcp
EXPOSE 3478/udp
EXPOSE 5050
WORKDIR "/"
ENTRYPOINT [ "/screego" ]
CMD ["serve"]


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.



================================================
FILE: README.md
================================================
<p align="center">
    <a href="https://screego.net">
        <img src="docs/logo.png" />
    </a>
</p>


<h1 align="center">screego/server</h1>
<p align="center"><i>screen sharing for developers</i></p>

<p align="center">
    <a href="https://github.com/screego/server/actions?query=workflow%3Abuild">
        <img alt="Build Status" src="https://github.com/screego/server/workflows/build/badge.svg">
    </a> 
    <a href="https://github.com/screego/server/pkgs/container/server">
        <img alt="Build Status" src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2Fipitio%2Fghcr-pulls%2Fmaster%2Findex.json&query=%24%5B%3F(%40.owner%3D%3D%22screego%22%20%26%26%20%40.repo%3D%3D%22server%22%20%26%26%20%40.image%3D%3D%22server%22)%5D.pulls&logo=github&label=pulls">
    </a> 
    <a href="https://goreportcard.com/report/github.com/screego/server">
        <img alt="Go Report Card" src="https://goreportcard.com/badge/github.com/screego/server">
    </a>
    <a href="https://hub.docker.com/r/screego/server">
        <img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/screego/server.svg">
    </a>
    <a href="https://github.com/screego/server/releases/latest">
        <img alt="latest release" src="https://img.shields.io/github/release/screego/server.svg">
    </a>
</p>

## Intro

In the past I've had some problems sharing my screen with coworkers using
corporate chatting solutions like Microsoft Teams. I wanted to show them some
of my code, but either the stream lagged several seconds behind or the quality
was so poor that my colleagues couldn't read the code. Or both.

That's why I created screego. It allows you to share your screen with good
quality and low latency. Screego is an addition to existing software and 
only helps to share your screen. Nothing else (:.

## Features

* Multi User Screenshare
* Secure transfer via WebRTC
* Low latency / High resolution
* Simple Install via Docker / single binary
* Integrated TURN Server see [NAT Traversal](https://screego.net/#/nat-traversal)

[Demo / Public Instance](https://app.screego.net/) ᛫ [Installation](https://screego.net/#/install) ᛫ [Configuration](https://screego.net/#/config) 

## Versioning

We use [SemVer](http://semver.org/) for versioning. For the versions available, see the
[tags on this repository](https://github.com/screego/server/tags).


================================================
FILE: auth/auth.go
================================================
package auth

import (
	"encoding/csv"
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"os"

	"github.com/gorilla/sessions"
	"github.com/rs/zerolog/log"
	"golang.org/x/crypto/bcrypt"
)

type Users struct {
	Lookup         map[string]string
	store          sessions.Store
	sessionTimeout int
}

type UserPW struct {
	Name string
	Pass string
}

func read(r io.Reader) ([]UserPW, error) {
	reader := csv.NewReader(r)
	reader.Comma = ':'
	reader.Comment = '#'
	reader.TrimLeadingSpace = true

	records, err := reader.ReadAll()
	if err != nil {
		return nil, err
	}

	result := []UserPW{}
	for _, record := range records {
		if len(record) != 2 {
			return nil, errors.New("malformed users file")
		}
		result = append(result, UserPW{Name: record[0], Pass: record[1]})
	}
	return result, nil
}

func ReadPasswordsFile(path string, secret []byte, sessionTimeout int) (*Users, error) {
	users := &Users{
		Lookup:         map[string]string{},
		sessionTimeout: sessionTimeout,
		store:          sessions.NewCookieStore(secret),
	}
	if path == "" {
		log.Info().Msg("Users file not specified")
		return users, nil
	}

	file, err := os.Open(path)
	if err != nil {
		return users, err
	}
	defer file.Close()
	userPws, err := read(file)
	if err != nil {
		return users, err
	}

	for _, record := range userPws {
		users.Lookup[record.Name] = record.Pass
	}
	log.Info().Int("amount", len(users.Lookup)).Msg("Loaded Users")
	return users, nil
}

type Response struct {
	Message string `json:"message"`
}

func (u *Users) CurrentUser(r *http.Request) (string, bool) {
	s, _ := u.store.Get(r, "user")
	user, ok := s.Values["user"].(string)
	if !ok {
		return "guest", ok
	}
	return user, ok
}

func (u *Users) Logout(w http.ResponseWriter, r *http.Request) {
	session := sessions.NewSession(u.store, "user")
	session.IsNew = true
	if err := u.store.Save(r, w, session); err != nil {
		w.WriteHeader(500)
		_ = json.NewEncoder(w).Encode(&Response{
			Message: err.Error(),
		})
		return
	}
	w.WriteHeader(200)
}

func (u *Users) Authenticate(w http.ResponseWriter, r *http.Request) {
	user := r.FormValue("user")
	pass := r.FormValue("pass")

	if !u.Validate(user, pass) {
		w.WriteHeader(401)
		_ = json.NewEncoder(w).Encode(&Response{
			Message: "could not authenticate",
		})
		return
	}

	session := sessions.NewSession(u.store, "user")
	session.IsNew = true
	session.Options.MaxAge = u.sessionTimeout
	session.Values["user"] = user
	if err := u.store.Save(r, w, session); err != nil {
		w.WriteHeader(500)
		_ = json.NewEncoder(w).Encode(&Response{
			Message: err.Error(),
		})
		return
	}
	w.WriteHeader(200)
	_ = json.NewEncoder(w).Encode(&Response{
		Message: "authenticated",
	})
}

func (u Users) Validate(user, password string) bool {
	realPassword, exists := u.Lookup[user]
	return exists && bcrypt.CompareHashAndPassword([]byte(realPassword), []byte(password)) == nil
}


================================================
FILE: cmd/command.go
================================================
package cmd

import (
	"fmt"
	"os"

	"github.com/rs/zerolog/log"
	"github.com/urfave/cli"
)

func Run(version, commitHash string) {
	app := cli.App{
		Name:    "screego",
		Version: fmt.Sprintf("%s; screego/server@%s", version, commitHash),
		Commands: []cli.Command{
			serveCmd(version),
			hashCmd,
		},
	}
	err := app.Run(os.Args)
	if err != nil {
		log.Fatal().Err(err).Msg("app error")
	}
}


================================================
FILE: cmd/hash.go
================================================
package cmd

import (
	"fmt"
	"os"
	"syscall"

	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	"github.com/screego/server/logger"
	"github.com/urfave/cli"
	"golang.org/x/crypto/bcrypt"
	"golang.org/x/term"
)

var hashCmd = cli.Command{
	Name: "hash",
	Flags: []cli.Flag{
		&cli.StringFlag{Name: "name"},
		&cli.StringFlag{Name: "pass"},
	},
	Action: func(ctx *cli.Context) {
		logger.Init(zerolog.ErrorLevel)
		name := ctx.String("name")
		pass := []byte(ctx.String("pass"))
		if name == "" {
			log.Fatal().Msg("--name must be set")
		}

		if len(pass) == 0 {
			var err error
			_, _ = fmt.Fprint(os.Stderr, "Enter Password: ")
			pass, err = term.ReadPassword(int(syscall.Stdin))
			if err != nil {
				log.Fatal().Err(err).Msg("could not read stdin")
			}
			_, _ = fmt.Fprintln(os.Stderr, "")
		}
		hashedPw, err := bcrypt.GenerateFromPassword(pass, 12)
		if err != nil {
			log.Fatal().Err(err).Msg("could not generate password")
		}

		fmt.Printf("%s:%s", name, string(hashedPw))
		fmt.Println("")
	},
}


================================================
FILE: cmd/serve.go
================================================
package cmd

import (
	"os"

	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	"github.com/screego/server/auth"
	"github.com/screego/server/config"
	"github.com/screego/server/logger"
	"github.com/screego/server/router"
	"github.com/screego/server/server"
	"github.com/screego/server/turn"
	"github.com/screego/server/ws"
	"github.com/urfave/cli"
)

func serveCmd(version string) cli.Command {
	return cli.Command{
		Name: "serve",
		Action: func(ctx *cli.Context) {
			conf, errs := config.Get()
			logger.Init(conf.LogLevel.AsZeroLogLevel())

			exit := false
			for _, err := range errs {
				log.WithLevel(err.Level).Msg(err.Msg)
				exit = exit || err.Level == zerolog.FatalLevel || err.Level == zerolog.PanicLevel
			}
			if exit {
				os.Exit(1)
			}

			if _, _, err := conf.TurnIPProvider.Get(); err != nil {
				// error is already logged by .Get()
				os.Exit(1)
			}

			users, err := auth.ReadPasswordsFile(conf.UsersFile, conf.Secret, conf.SessionTimeoutSeconds)
			if err != nil {
				log.Fatal().Str("file", conf.UsersFile).Err(err).Msg("While loading users file")
			}

			tServer, err := turn.Start(conf)
			if err != nil {
				log.Fatal().Err(err).Msg("could not start turn server")
			}

			rooms := ws.NewRooms(tServer, users, conf)

			go rooms.Start()

			r := router.Router(conf, rooms, users, version)
			if err := server.Start(r, conf.ServerAddress, conf.TLSCertFile, conf.TLSKeyFile); err != nil {
				log.Fatal().Err(err).Msg("http server")
			}
		},
	}
}


================================================
FILE: config/config.go
================================================
package config

import (
	"crypto/rand"
	"errors"
	"fmt"
	"net"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"

	"github.com/joho/godotenv"
	"github.com/kelseyhightower/envconfig"
	"github.com/rs/zerolog"
	"github.com/screego/server/config/ipdns"
	"github.com/screego/server/config/mode"
)

var (
	prefix        = "screego"
	files         = []string{"screego.config.development.local", "screego.config.development", "screego.config.local", "screego.config"}
	absoluteFiles = []string{"/etc/screego/server.config"}
	osExecutable  = os.Executable
	osStat        = os.Stat
)

const (
	AuthModeTurn = "turn"
	AuthModeAll  = "all"
	AuthModeNone = "none"
)

// Config represents the application configuration.
type Config struct {
	LogLevel LogLevel `default:"info" split_words:"true"`

	ExternalIP []string `split_words:"true"`

	TLSCertFile string `split_words:"true"`
	TLSKeyFile  string `split_words:"true"`

	ServerTLS             bool   `split_words:"true"`
	ServerAddress         string `default:":5050" split_words:"true"`
	Secret                []byte `split_words:"true"`
	SessionTimeoutSeconds int    `default:"0" split_words:"true"`

	TurnAddress   string `default:":3478" required:"true" split_words:"true"`
	TurnPortRange string `split_words:"true"`

	TurnExternalIP     []string `split_words:"true"`
	TurnExternalPort   string   `default:"3478" split_words:"true"`
	TurnExternalSecret string   `split_words:"true"`

	TrustProxyHeaders  bool     `split_words:"true"`
	AuthMode           string   `default:"turn" split_words:"true"`
	CorsAllowedOrigins []string `split_words:"true"`
	UsersFile          string   `split_words:"true"`
	Prometheus         bool     `split_words:"true"`

	CheckOrigin    func(string) bool `ignored:"true" json:"-"`
	TurnExternal   bool              `ignored:"true"`
	TurnIPProvider ipdns.Provider    `ignored:"true"`
	TurnPort       string            `ignored:"true"`

	TurnDenyPeers       []string     `default:"0.0.0.0/8,127.0.0.1/8,::/128,::1/128,fe80::/10" split_words:"true"`
	TurnDenyPeersParsed []*net.IPNet `ignored:"true"`

	CloseRoomWhenOwnerLeaves bool `default:"true" split_words:"true"`
}

func (c Config) parsePortRange() (uint16, uint16, error) {
	if c.TurnPortRange == "" {
		return 0, 0, nil
	}

	parts := strings.Split(c.TurnPortRange, ":")
	if len(parts) != 2 {
		return 0, 0, errors.New("must include one colon")
	}
	stringMin := parts[0]
	stringMax := parts[1]
	min64, err := strconv.ParseUint(stringMin, 10, 16)
	if err != nil {
		return 0, 0, fmt.Errorf("invalid min: %s", err)
	}
	max64, err := strconv.ParseUint(stringMax, 10, 16)
	if err != nil {
		return 0, 0, fmt.Errorf("invalid max: %s", err)
	}

	return uint16(min64), uint16(max64), nil
}

func (c Config) PortRange() (uint16, uint16, bool) {
	min, max, _ := c.parsePortRange()
	return min, max, min != 0 && max != 0
}

// Get loads the application config.
func Get() (Config, []FutureLog) {
	var logs []FutureLog
	dir, log := getExecutableOrWorkDir()
	if log != nil {
		logs = append(logs, *log)
	}

	for _, file := range getFiles(dir) {
		_, fileErr := osStat(file)
		if fileErr == nil {
			if err := godotenv.Load(file); err != nil {
				logs = append(logs, futureFatal(fmt.Sprintf("cannot load file %s: %s", file, err)))
			} else {
				logs = append(logs, FutureLog{
					Level: zerolog.DebugLevel,
					Msg:   fmt.Sprintf("Loading file %s", file),
				})
			}
		} else if os.IsNotExist(fileErr) {
			continue
		} else {
			logs = append(logs, FutureLog{
				Level: zerolog.WarnLevel,
				Msg:   fmt.Sprintf("cannot read file %s because %s", file, fileErr),
			})
		}
	}

	config := Config{}
	err := envconfig.Process(prefix, &config)
	if err != nil {
		logs = append(logs,
			futureFatal(fmt.Sprintf("cannot parse env params: %s", err)))
	}

	if config.AuthMode != AuthModeTurn && config.AuthMode != AuthModeAll && config.AuthMode != AuthModeNone {
		logs = append(logs,
			futureFatal(fmt.Sprintf("invalid SCREEGO_AUTH_MODE: %s", config.AuthMode)))
	}

	if config.ServerTLS {
		if config.TLSCertFile == "" {
			logs = append(logs, futureFatal("SCREEGO_TLS_CERT_FILE must be set if TLS is enabled"))
		}

		if config.TLSKeyFile == "" {
			logs = append(logs, futureFatal("SCREEGO_TLS_KEY_FILE must be set if TLS is enabled"))
		}
	}

	var compiledAllowedOrigins []*regexp.Regexp
	for _, origin := range config.CorsAllowedOrigins {
		compiled, err := regexp.Compile(origin)
		if err != nil {
			logs = append(logs, futureFatal(fmt.Sprintf("invalid regex: %s", err)))
		}
		compiledAllowedOrigins = append(compiledAllowedOrigins, compiled)
	}

	config.CheckOrigin = func(origin string) bool {
		if origin == "" {
			return true
		}
		for _, compiledOrigin := range compiledAllowedOrigins {
			if compiledOrigin.Match([]byte(strings.ToLower(origin))) {
				return true
			}
		}
		return false
	}

	if len(config.Secret) == 0 {
		config.Secret = make([]byte, 32)
		if _, err := rand.Read(config.Secret); err == nil {
			logs = append(logs, FutureLog{
				Level: zerolog.InfoLevel,
				Msg:   "SCREEGO_SECRET unset, user logins will be invalidated on restart",
			})
		} else {
			logs = append(logs, futureFatal(fmt.Sprintf("cannot create secret %s", err)))
		}
	}

	var errs []FutureLog

	if len(config.TurnExternalIP) > 0 {
		if len(config.ExternalIP) > 0 {
			logs = append(logs, futureFatal("SCREEGO_EXTERNAL_IP and SCREEGO_TURN_EXTERNAL_IP must not be both set"))
		}

		config.TurnIPProvider, errs = parseIPProvider(config.TurnExternalIP, "SCREEGO_TURN_EXTERNAL_IP")
		config.TurnPort = config.TurnExternalPort
		config.TurnExternal = true
		logs = append(logs, errs...)
		if config.TurnExternalSecret == "" {
			logs = append(logs, futureFatal("SCREEGO_TURN_EXTERNAL_SECRET must be set if external TURN server is used"))
		}
	} else if len(config.ExternalIP) > 0 {
		config.TurnIPProvider, errs = parseIPProvider(config.ExternalIP, "SCREEGO_EXTERNAL_IP")
		logs = append(logs, errs...)
		split := strings.Split(config.TurnAddress, ":")
		config.TurnPort = split[len(split)-1]
	} else {
		logs = append(logs, futureFatal("SCREEGO_EXTERNAL_IP or SCREEGO_TURN_EXTERNAL_IP must be set"))
	}

	min, max, err := config.parsePortRange()
	if err != nil {
		logs = append(logs, futureFatal(fmt.Sprintf("invalid SCREEGO_TURN_PORT_RANGE: %s", err)))
	} else if min == 0 && max == 0 {
		// valid; no port range
	} else if min == 0 || max == 0 {
		logs = append(logs, futureFatal("invalid SCREEGO_TURN_PORT_RANGE: min or max port is 0"))
	} else if min > max {
		logs = append(logs, futureFatal(fmt.Sprintf("invalid SCREEGO_TURN_PORT_RANGE: min port (%d) is higher than max port (%d)", min, max)))
	} else if (max - min) < 40 {
		logs = append(logs, FutureLog{
			Level: zerolog.WarnLevel,
			Msg:   "Less than 40 ports are available for turn. When using multiple TURN connections this may not be enough",
		})
	}
	logs = append(logs, logDeprecated()...)

	for _, cidrString := range config.TurnDenyPeers {
		_, cidr, err := net.ParseCIDR(cidrString)
		if err != nil {
			logs = append(logs, FutureLog{
				Level: zerolog.FatalLevel,
				Msg:   fmt.Sprintf("Invalid SCREEGO_TURN_DENY_PEERS %q: %s", cidrString, err),
			})
		} else {
			config.TurnDenyPeersParsed = append(config.TurnDenyPeersParsed, cidr)
		}
	}
	logs = append(logs, FutureLog{
		Level: zerolog.InfoLevel,
		Msg:   fmt.Sprintf("Deny turn peers within %q", config.TurnDenyPeersParsed),
	})

	return config, logs
}

func logDeprecated() []FutureLog {
	if os.Getenv("SCREEGO_TURN_STRICT_AUTH") != "" {
		return []FutureLog{{Level: zerolog.WarnLevel, Msg: "The setting SCREEGO_TURN_STRICT_AUTH has been removed."}}
	}
	return nil
}

func getExecutableOrWorkDir() (string, *FutureLog) {
	dir, err := getExecutableDir()
	// when using `go run main.go` the executable lives in th temp directory therefore the env.development
	// will not be read, this enforces that the current work directory is used in dev mode.
	if err != nil || mode.Get() == mode.Dev {
		return filepath.Dir("."), err
	}
	return dir, nil
}

func getExecutableDir() (string, *FutureLog) {
	ex, err := osExecutable()
	if err != nil {
		return "", &FutureLog{
			Level: zerolog.ErrorLevel,
			Msg:   "Could not get path of executable using working directory instead. " + err.Error(),
		}
	}
	return filepath.Dir(ex), nil
}

func getFiles(relativeTo string) []string {
	var result []string
	for _, file := range files {
		result = append(result, filepath.Join(relativeTo, file))
	}
	homeDir, err := os.UserHomeDir()
	if err == nil {
		result = append(result, filepath.Join(homeDir, ".config/screego/server.config"))
	}
	result = append(result, absoluteFiles...)
	return result
}


================================================
FILE: config/error.go
================================================
package config

import "github.com/rs/zerolog"

// FutureLog is an intermediate type for log messages. It is used before the config was loaded because without loaded
// config we do not know the log level, so we log these messages once the config was initialized.
type FutureLog struct {
	Level zerolog.Level
	Msg   string
}

func futureFatal(msg string) FutureLog {
	return FutureLog{
		Level: zerolog.FatalLevel,
		Msg:   msg,
	}
}


================================================
FILE: config/ip.go
================================================
package config

import (
	"context"
	"fmt"
	"net"
	"strings"
	"time"

	"github.com/screego/server/config/ipdns"
)

func parseIPProvider(ips []string, config string) (ipdns.Provider, []FutureLog) {
	if len(ips) == 0 {
		panic("must have at least one ip")
	}

	first := ips[0]
	if strings.HasPrefix(first, "dns:") {
		if len(ips) > 1 {
			return nil, []FutureLog{futureFatal(fmt.Sprintf("invalid %s: when dns server is specified, only one value is allowed", config))}
		}

		return parseDNS(strings.TrimPrefix(first, "dns:")), nil
	}

	return parseStatic(ips, config)
}

func parseStatic(ips []string, config string) (*ipdns.Static, []FutureLog) {
	var static ipdns.Static

	firstV4, errs := applyIPTo(config, ips[0], &static)
	if errs != nil {
		return nil, errs
	}

	if len(ips) == 1 {
		return &static, nil
	}

	secondV4, errs := applyIPTo(config, ips[1], &static)
	if errs != nil {
		return nil, errs
	}

	if firstV4 == secondV4 {
		return nil, []FutureLog{futureFatal(fmt.Sprintf("invalid %s: the ips must be of different type ipv4/ipv6", config))}
	}

	if len(ips) > 2 {
		return nil, []FutureLog{futureFatal(fmt.Sprintf("invalid %s: too many ips supplied", config))}
	}

	return &static, nil
}

func applyIPTo(config, ip string, static *ipdns.Static) (bool, []FutureLog) {
	parsed := net.ParseIP(ip)
	if parsed == nil || ip == "0.0.0.0" {
		return false, []FutureLog{futureFatal(fmt.Sprintf("invalid %s: %s", config, ip))}
	}

	v4 := parsed.To4() != nil
	if v4 {
		static.V4 = parsed
	} else {
		static.V6 = parsed
	}
	return v4, nil
}

func parseDNS(dnsString string) *ipdns.DNS {
	var dns ipdns.DNS

	parts := strings.SplitN(dnsString, "@", 2)

	dns.Domain = parts[0]
	dns.DNS = "system"
	if len(parts) == 2 {
		dns.DNS = parts[1]
		dns.Resolver = &net.Resolver{
			PreferGo: true,
			Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
				d := net.Dialer{Timeout: 10 * time.Second}
				return d.DialContext(ctx, network, parts[1])
			},
		}
	}

	return &dns
}


================================================
FILE: config/ipdns/dns.go
================================================
package ipdns

import (
	"context"
	"errors"
	"net"
	"strings"
	"sync"
	"time"

	"github.com/rs/zerolog/log"
)

type DNS struct {
	sync.Mutex

	DNS      string
	Resolver *net.Resolver
	Domain   string

	refetch time.Time
	v4      net.IP
	v6      net.IP
	err     error
}

func (s *DNS) Get() (net.IP, net.IP, error) {
	s.Lock()
	defer s.Unlock()

	if s.refetch.Before(time.Now()) {
		oldV4, oldV6 := s.v4, s.v6
		s.v4, s.v6, s.err = s.lookup()
		if s.err == nil {
			if !oldV4.Equal(s.v4) || !oldV6.Equal(s.v6) {
				log.Info().Str("v4", s.v4.String()).
					Str("v6", s.v6.String()).
					Str("domain", s.Domain).
					Str("dns", s.DNS).
					Msg("DNS External IP")
			}
			s.refetch = time.Now().Add(time.Minute)
		} else {
			// don't spam the dns server
			s.refetch = time.Now().Add(time.Second)
			log.Err(s.err).Str("domain", s.Domain).Str("dns", s.DNS).Msg("DNS External IP")
		}
	}

	return s.v4, s.v6, s.err
}

func (s *DNS) lookup() (net.IP, net.IP, error) {
	ips, err := s.Resolver.LookupIP(context.Background(), "ip", s.Domain)
	if err != nil {
		if dns, ok := err.(*net.DNSError); ok && s.DNS != "system" {
			dns.Server = ""
		}
		return nil, nil, err
	}

	var v4, v6 net.IP
	for _, ip := range ips {
		isV6 := strings.Contains(ip.String(), ":")
		if isV6 && v6 == nil {
			v6 = ip
		} else if !isV6 && v4 == nil {
			v4 = ip
		}
	}

	if v4 == nil && v6 == nil {
		return nil, nil, errors.New("dns record doesn't have an A or AAAA record")
	}

	return v4, v6, nil
}


================================================
FILE: config/ipdns/provider.go
================================================
package ipdns

import "net"

type Provider interface {
	Get() (net.IP, net.IP, error)
}


================================================
FILE: config/ipdns/static.go
================================================
package ipdns

import "net"

type Static struct {
	V4 net.IP
	V6 net.IP
}

func (s *Static) Get() (net.IP, net.IP, error) {
	return s.V4, s.V6, nil
}


================================================
FILE: config/loglevel.go
================================================
package config

import (
	"errors"

	"github.com/rs/zerolog"
)

// LogLevel type that provides helper methods for decoding.
type LogLevel zerolog.Level

// Decode decodes a string to a log level.
func (ll *LogLevel) Decode(value string) error {
	if level, err := zerolog.ParseLevel(value); err == nil {
		*ll = LogLevel(level)
		return nil
	}
	*ll = LogLevel(zerolog.InfoLevel)
	return errors.New("unknown log level")
}

// AsZeroLogLevel converts the LogLevel to a zerolog.Level.
func (ll LogLevel) AsZeroLogLevel() zerolog.Level {
	return zerolog.Level(ll)
}


================================================
FILE: config/loglevel_test.go
================================================
package config

import (
	"testing"

	"github.com/rs/zerolog"
	"github.com/stretchr/testify/assert"
)

func TestLogLevel_Decode_success(t *testing.T) {
	ll := new(LogLevel)
	err := ll.Decode("fatal")
	assert.Nil(t, err)
	assert.Equal(t, ll.AsZeroLogLevel(), zerolog.FatalLevel)
}

func TestLogLevel_Decode_fail(t *testing.T) {
	ll := new(LogLevel)
	err := ll.Decode("asdasdasdasdasdasd")
	assert.EqualError(t, err, "unknown log level")
	assert.Equal(t, ll.AsZeroLogLevel(), zerolog.InfoLevel)
}


================================================
FILE: config/mode/mode.go
================================================
package mode

const (
	// Dev for development mode.
	Dev = "dev"
	// Prod for production mode.
	Prod = "prod"
)

var mode = Dev

// Set sets the new mode.
func Set(newMode string) {
	mode = newMode
}

// Get returns the current mode.
func Get() string {
	return mode
}


================================================
FILE: config/mode/mode_test.go
================================================
package mode

import (
	"testing"

	"github.com/stretchr/testify/require"
)

func TestGet(t *testing.T) {
	mode = Prod
	require.Equal(t, Prod, Get())
}

func TestSet(t *testing.T) {
	Set(Prod)
	require.Equal(t, Prod, mode)
}


================================================
FILE: docs/.nojekyll
================================================


================================================
FILE: docs/CNAME
================================================
screego.net


================================================
FILE: docs/README.md
================================================
# screego/server

In the past I've had some problems sharing my screen with coworkers using
corporate chatting solutions like Microsoft Teams. I wanted to show them some
of my code, but either the stream lagged several seconds behind or the quality
was so poor that my colleagues couldn't read the code. Or both.

That's why I created screego. It allows you to share your screen with good
quality and low latency. Screego is an addition to existing software and 
only helps to share your screen. Nothing else (:.


## Features

* Multi User Screenshare
* Secure transfer via WebRTC
* Low latency / High resolution
* Simple Install via [Docker](https://hub.docker.com/r/screego/server) / single binary
* Integrated [TURN](nat-traversal.md) Server see [NAT Traversal](nat-traversal.md)

---

[Demo / Public Instance](https://app.screego.net/) ᛫ [Installation](https://screego.net/#/install) ᛫ [Configuration](https://screego.net/#/config) 


================================================
FILE: docs/_sidebar.md
================================================
* [Home](/)
* [Installation](install.md)
* [Config](config.md)
* [NAT Traversal](nat-traversal.md)
* [Reverse Proxy](proxy.md)
* [Development](development.md)
* [FAQ](faq.md)
* [GitHub](https://github.com/screego/server)


================================================
FILE: docs/config.md
================================================
# Config

!> TLS is required for Screego to work. Either enable TLS inside Screego or 
   use a reverse proxy to serve Screego via TLS.

Screego tries to obtain config values from different locations in sequence. 
Properties will never be overridden. Thus, the first occurrence of a setting will be used.

#### Order

* Environment Variables
* `screego.config.local` (in same path as the binary)
* `screego.config` (in same path as the binary)
* `$HOME/.config/screego/server.config`
* `/etc/screego/server.config`

#### Config Example

[screego.config.example](https://raw.githubusercontent.com/screego/server/master/screego.config.example ':include :type=code ini')


================================================
FILE: docs/development.md
================================================
# Development

Screego requires:

- Go 1.15+
- Node 13.x
- Yarn 9+

## Setup

### Clone Repository

Clone screego/server source from git:

```bash
$ git clone https://github.com/screego/server.git && cd server
```

### GOPATH

If you are in GOPATH, enable [go modules](https://github.com/golang/go/wiki/Modules) explicitly:

```bash
$ export GO111MODULE=on
```

### Download Dependencies:

```bash
# Server
$ go mod download
# UI
$ (cd ui && yarn install)
```

## Start / Linting

### Backend

Create a file named `screego.config.development.local` inside the screego folder with the content:

```ini
SCREEGO_EXTERNAL_IP=YOURIP
```

and replace `YOURIP` with your external ip.

Start the server in development mode.

```bash
$ go run . serve
```

The backend is available on [http://localhost:5050](http://localhost:5050)

?> When accessing `localhost:5050` it is normal that there are panics with `no such file or directory`.
The UI will be started separately.

### Frontend

Start the UI development server.

_Commands must be executed inside the ui directory._

```bash
$ yarn start
```

Open [http://localhost:3000](http://localhost:3000) inside your favorite browser.

### Lint

Screego uses [golangci-lint](https://github.com/golangci/golangci-lint) for linting.

After installation you can check the source code with:

```bash
$ golangci-lint run
```

## Build

1. [Setup](#setup)

1. Build the UI

   ```bash
   $ (cd ui && yarn build)
   ```

1. Build the binary
   ```bash
   go build -ldflags "-X main.version=$(git describe --tags HEAD) -X main.mode=prod" -o screego ./main.go
   ```


================================================
FILE: docs/faq.md
================================================
# Frequently Asked Questions

## Stream doesn't load

Check that
* you are using https to access Screego.
* `SCREEGO_EXTERNAL_IP` is set to your external IP. See [Configuration](config.md)
* you are using TURN for NAT-Traversal. See [NAT-Traversal](nat-traversal.md). *On app.screego.net it's enabled without login; when self-hosting it requires user login*
* your browser doesn't block WebRTC (extensions or other settings)
* you have opened ports in your firewall. By default 5050, 3478 and any UDP port when using TURN.

## Automatically create room on join

Sometimes you want to reuse the screego room, but always have to recreate it.
By passing `create=true` in the url, you can automatically create the room if it does not exist.

Example: https://app.screego.net/?room=not-existing-room&create=true


================================================
FILE: docs/index.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Screego</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta name="description" content="Screego - open source screen sharing for developers">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/docsify-themeable@0/dist/css/theme-simple-dark.css">
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
    <meta name="theme-color" content="#ffffff">
    <style>
        .markdown-section h1 {
            border-width: 0;
        }
    </style>
</head>
<body>
<div id="app"></div>
<script>
    const ghVersion = fetch('https://api.github.com/repos/screego/server/tags').then(resp => resp.json()).then(data => data[0].name.slice(1))
    window.$docsify = {
        name: 'screego',
        repo: 'screego/server',
        logo: '/logo.png',
        loadSidebar: true,
        autoHeader: true,
        maxLevel: 4,
        subMaxLevel: 2,
        plugins: [
            function (hook) {
                hook.afterEach(function (html, next) {
                    ghVersion.then((version) => next(html.replace(/GITHUB_VERSION/g, version)))
                })
            }
        ]
    }
</script>
<script src="//cdn.jsdelivr.net/npm/docsify/lib/docsify.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/docsify-themeable@0"></script>
<script src="//cdn.jsdelivr.net/npm/docsify/lib/plugins/search.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/docsify-tabs@1"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.21.0/components/prism-yaml.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.21.0/components/prism-ini.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.21.0/components/prism-bash.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.21.0/components/prism-nginx.js"></script>
</body>
</html>


================================================
FILE: docs/install.md
================================================
# Installation

Latest Version: **GITHUB_VERSION**

Before starting Screego you may read [Configuration](config.md).

!> TLS is required for Screego to work. Either enable TLS inside Screego or 
   use a reverse proxy to serve Screego via TLS.

## Docker

Setting up Screego with docker is pretty easy, you basically just have to start the docker container, and you are ready to go:

[ghcr.io/screego/server](https://github.com/orgs/screego/packages/container/package/server) and
[screego/server](https://hub.docker.com/r/screego/server)
docker images are multi-arch docker images.
This means the image will work for `amd64`, `i386`, `ppc64le` (power pc), `arm64`, `armv7` (Raspberry PI) and `armv6`.

By default, Screego runs on port 5050.

?> Replace `EXTERNALIP` with your external IP. One way to find your external ip is with ipify.
   `curl 'https://api.ipify.org'`

```bash
$ docker run --net=host -e SCREEGO_EXTERNAL_IP=EXTERNALIP ghcr.io/screego/server:GITHUB_VERSION
```

**docker-compose.yml**
```yaml
services:
  screego:
    image: ghcr.io/screego/server:GITHUB_VERSION
    network_mode: host
    environment:
      SCREEGO_EXTERNAL_IP: "EXTERNALIP"
```

If you don't want to use the host network, then you can configure docker like this:

<details><summary>(Click to expand)</summary>
<p>

!> Screego may not work correctly when deploying it in docker without `network_mode: host`.
   See [#226](https://github.com/screego/server/issues/226)

```bash
$ docker run -it \
    -e SCREEGO_EXTERNAL_IP=EXTERNALIP \
    -e SCREEGO_TURN_PORT_RANGE=50000:50200 \
    -p 5050:5050 \
    -p 3478:3478 \
    -p 50000-50200:50000-50200/udp \
    screego/server:GITHUB_VERSION
```

#### docker-compose.yml

```yml
version: "3.7"
services:
  screego:
    image: ghcr.io/screego/server:GITHUB_VERSION
    ports:
      - 5050:5050
      - 3478:3478
      - 50000-50200:50000-50200/udp
    environment:
      SCREEGO_EXTERNAL_IP: "192.168.178.2"
      SCREEGO_TURN_PORT_RANGE: "50000:50200"
```

</p>
</details>

## Binary

### Supported Platforms:

- linux_amd64 (64bit)
- linux_i386 (32bit)
- armv7 (32bit used for Raspberry Pi)
- armv6
- arm64 (ARMv8)
- ppc64
- ppc64le
- windows_i386.exe (32bit)
- windows_amd64.exe (64bit)

Download the zip with the binary for your platform from [screego/server Releases](https://github.com/screego/server/releases).

```bash
$ wget https://github.com/screego/server/releases/download/vGITHUB_VERSION/screego_GITHUB_VERSION_{PLATFORM}.tar.gz
```

Unzip the archive.

```bash
$ tar xvf screego_GITHUB_VERSION_{PLATFORM}.tar.gz
```

Make the binary executable (linux only).

```bash
$ chmod +x screego
```

Execute screego:

```bash
$ ./screego
# on windows
$ screego.exe
```

## Arch-Linux(aur)

!> Maintenance of the AUR Packages is not performed by the Screego team.
   You should always check the PKGBUILD before installing an AUR package.

Screego's latest release is available in the AUR as [screego-server](https://aur.archlinux.org/packages/screego-server/) and [screego-server-bin](https://aur.archlinux.org/packages/screego-server-bin/).
The development-version can be installed with [screego-server-git](https://aur.archlinux.org/packages/screego-server-git/).

## FreeBSD

!> Maintenance of the FreeBSD Package is not performed by the Screego team.
   Check yourself, if you can trust it.

```bash
$ pkg install screego
```

## Source

[See Development#build](development.md#build)


================================================
FILE: docs/nat-traversal.md
================================================
# NAT Traversal

In most cases peers cannot directly communicate with each other because of firewalls or other restrictions like NAT.
To work around this issue, WebRTC uses 
[Interactive Connectivity Establishment (ICE)](http://en.wikipedia.org/wiki/Interactive_Connectivity_Establishment).
This is a framework for helping to connect peers.

ICE uses STUN and/or TURN servers to accomplish this.

?> Screego exposes a STUN and TURN server. You don't have to configure this separately.
   By default, user authentication is required for using TURN.

## STUN

[Session Traversal Utilities for NAT (STUN)](http://en.wikipedia.org/wiki/STUN) is used to find
the public / external ip of a peer. This IP is later sent to others to create a direct connection.

When STUN is used, only the connection enstablishment will be done through Screego. The actual video stream will be
directly sent to the other peer and doesn't go through Screego.

While STUN should work for most cases, there are stricter NATs f.ex. 
[Symmetric NATs](https://en.wikipedia.org/wiki/Network_address_translation) 
where it doesn't, then, TURN will be used.

## TURN

[Traversal Using Relays around NAT (TURN)](http://en.wikipedia.org/wiki/TURN) is used to work around Symmetric NATs.
It does it by relaying all data through a TURN server. As relaying will create traffic on the server,
Screego will require user authentication to use the TURN server. This can be configured see [Configuration](config.md).



================================================
FILE: docs/proxy.md
================================================
# Proxy

!> When using a proxy enable `SCREEGO_TRUST_PROXY_HEADERS`. See [Configuration](config.md).

## nginx

### At root path

```nginx
upstream screego {
  # Set this to the address configured in
  # SCREEGO_SERVER_ADDRESS. Default 5050
  server 127.0.0.1:5050;
}

server {
  listen 80;

  # Here goes your domain / subdomain
  server_name screego.example.com;

  location / {
    # Proxy to screego
    proxy_pass         http://screego;
    proxy_http_version 1.1;

    # Set headers for proxying WebSocket
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection "upgrade";
    proxy_redirect     http:// $scheme://;

    # Set proxy headers
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Proto http;

    # The proxy must preserve the host because screego verifies it with the origin
    # for WebSocket connections
    proxy_set_header   Host $http_host;
  }
}
```

### At a sub path

```nginx
upstream screego {
  # Set this to the address configured in
  # SCREEGO_SERVER_ADDRESS. Default 5050
  server 127.0.0.1:5050;
}

server {
  listen 80;

  # Here goes your domain / subdomain
  server_name screego.example.com;

  location /screego/ {
    rewrite ^/screego(/.*) $1 break;
  
    # Proxy to screego
    proxy_pass         http://screego;
    proxy_http_version 1.1;

    # Set headers for proxying WebSocket
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection "upgrade";
    proxy_redirect     http:// $scheme://;

    # Set proxy headers
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Proto http;

    # The proxy must preserve the host because screego verifies it with the origin
    # for WebSocket connections
    proxy_set_header   Host $http_host;
  }
}
```

## Apache (httpd)

The following modules are required:

* mod_proxy
* mod_proxy_wstunnel
* mod_proxy_http

### At root path

```apache
<VirtualHost *:80>
    ServerName screego.example.com
    Keepalive On

    # The proxy must preserve the host because screego verifies it with the origin
    # for WebSocket connections
    ProxyPreserveHost On

    # Replace 5050 with the port defined in SCREEGO_SERVER_ADDRESS.
    # Default 5050

    # Proxy web socket requests to /stream
    ProxyPass "/stream" ws://127.0.0.1:5050/stream retry=0 timeout=5

    # Proxy all other requests to /
    ProxyPass "/" http://127.0.0.1:5050/ retry=0 timeout=5

    ProxyPassReverse / http://127.0.0.1:5050/
</VirtualHost>
```

### At a sub path

```apache
<VirtualHost *:80>
    ServerName screego.example.com
    Keepalive On

    Redirect 301 "/screego" "/screego/"

    # The proxy must preserve the host because screego verifies it with the origin
    # for WebSocket connections
    ProxyPreserveHost On

    # Proxy web socket requests to /stream
    ProxyPass "/screego/stream" ws://127.0.0.1:5050/stream retry=0 timeout=5

    # Proxy all other requests to /
    ProxyPass "/screego/" http://127.0.0.1:5050/ retry=0 timeout=5
    #                 ^- !!trailing slash is required!!

    ProxyPassReverse /screego/ http://127.0.0.1:5050/
</VirtualHost>
```


================================================
FILE: go.mod
================================================
module github.com/screego/server

go 1.24.0

toolchain go1.24.1

require (
	github.com/gorilla/handlers v1.5.2
	github.com/gorilla/mux v1.8.1
	github.com/gorilla/sessions v1.4.0
	github.com/gorilla/websocket v1.5.3
	github.com/joho/godotenv v1.5.1
	github.com/kelseyhightower/envconfig v1.4.0
	github.com/pion/randutil v0.1.0
	github.com/pion/turn/v4 v4.1.3
	github.com/prometheus/client_golang v1.23.2
	github.com/rs/xid v1.6.0
	github.com/rs/zerolog v1.34.0
	github.com/stretchr/testify v1.11.1
	github.com/urfave/cli v1.22.17
	golang.org/x/crypto v0.46.0
	golang.org/x/term v0.38.0
	golang.org/x/text v0.32.0
)

require (
	github.com/beorn7/perks v1.0.1 // indirect
	github.com/cespare/xxhash/v2 v2.3.0 // indirect
	github.com/cpuguy83/go-md2man/v2 v2.0.7 // indirect
	github.com/davecgh/go-spew v1.1.1 // indirect
	github.com/felixge/httpsnoop v1.0.3 // indirect
	github.com/gorilla/securecookie v1.1.2 // indirect
	github.com/klauspost/compress v1.18.0 // indirect
	github.com/kr/text v0.2.0 // indirect
	github.com/mattn/go-colorable v0.1.13 // indirect
	github.com/mattn/go-isatty v0.0.19 // indirect
	github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
	github.com/pion/dtls/v3 v3.0.7 // indirect
	github.com/pion/logging v0.2.4 // indirect
	github.com/pion/stun/v3 v3.0.1 // indirect
	github.com/pion/transport/v3 v3.1.1 // indirect
	github.com/pmezard/go-difflib v1.0.0 // indirect
	github.com/prometheus/client_model v0.6.2 // indirect
	github.com/prometheus/common v0.66.1 // indirect
	github.com/prometheus/procfs v0.16.1 // indirect
	github.com/russross/blackfriday/v2 v2.1.0 // indirect
	github.com/wlynxg/anet v0.0.5 // indirect
	go.yaml.in/yaml/v2 v2.4.2 // indirect
	golang.org/x/sys v0.39.0 // indirect
	google.golang.org/protobuf v1.36.8 // indirect
	gopkg.in/yaml.v3 v3.0.1 // indirect
)


================================================
FILE: go.sum
================================================
github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/cpuguy83/go-md2man/v2 v2.0.5 h1:ZtcqGrnekaHpVLArFSe4HK5DoKx1T0rq2DwVB0alcyc=
github.com/cpuguy83/go-md2man/v2 v2.0.5/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/cpuguy83/go-md2man/v2 v2.0.7 h1:zbFlGlXEAKlwXpmvle3d8Oe3YnkKIK4xSRTd3sHPnBo=
github.com/cpuguy83/go-md2man/v2 v2.0.7/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk=
github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE=
github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=
github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dvMUtDTo2cv8=
github.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg=
github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/pion/dtls/v3 v3.0.2 h1:425DEeJ/jfuTTghhUDW0GtYZYIwwMtnKKJNMcWccTX0=
github.com/pion/dtls/v3 v3.0.2/go.mod h1:dfIXcFkKoujDQ+jtd8M6RgqKK3DuaUilm3YatAbGp5k=
github.com/pion/dtls/v3 v3.0.7 h1:bItXtTYYhZwkPFk4t1n3Kkf5TDrfj6+4wG+CZR8uI9Q=
github.com/pion/dtls/v3 v3.0.7/go.mod h1:uDlH5VPrgOQIw59irKYkMudSFprY9IEFCqz/eTz16f8=
github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY=
github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms=
github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=
github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
github.com/pion/stun/v3 v3.0.0 h1:4h1gwhWLWuZWOJIJR9s2ferRO+W3zA/b6ijOI6mKzUw=
github.com/pion/stun/v3 v3.0.0/go.mod h1:HvCN8txt8mwi4FBvS3EmDghW6aQJ24T+y+1TKjB5jyU=
github.com/pion/stun/v3 v3.0.1 h1:jx1uUq6BdPihF0yF33Jj2mh+C9p0atY94IkdnW174kA=
github.com/pion/stun/v3 v3.0.1/go.mod h1:RHnvlKFg+qHgoKIqtQWMOJF52wsImCAf/Jh5GjX+4Tw=
github.com/pion/transport/v3 v3.0.7 h1:iRbMH05BzSNwhILHoBoAPxoB9xQgOaJk+591KC9P1o0=
github.com/pion/transport/v3 v3.0.7/go.mod h1:YleKiTZ4vqNxVwh77Z0zytYi7rXHl7j6uPLGhhz9rwo=
github.com/pion/transport/v3 v3.1.1 h1:Tr684+fnnKlhPceU+ICdrw6KKkTms+5qHMgw6bIkYOM=
github.com/pion/transport/v3 v3.1.1/go.mod h1:+c2eewC5WJQHiAA46fkMMzoYZSuGzA/7E2FPrOYHctQ=
github.com/pion/turn/v4 v4.0.0 h1:qxplo3Rxa9Yg1xXDxxH8xaqcyGUtbHYw4QSCvmFWvhM=
github.com/pion/turn/v4 v4.0.0/go.mod h1:MuPDkm15nYSklKpN8vWJ9W2M0PlyQZqYt1McGuxG7mA=
github.com/pion/turn/v4 v4.1.3 h1:jVNW0iR05AS94ysEtvzsrk3gKs9Zqxf6HmnsLfRvlzA=
github.com/pion/turn/v4 v4.1.3/go.mod h1:TD/eiBUf5f5LwXbCJa35T7dPtTpCHRJ9oJWmyPLVT3A=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_golang v1.20.4 h1:Tgh3Yr67PaOv/uTqloMsCEdeuFTatm5zIq5+qNN23vI=
github.com/prometheus/client_golang v1.20.4/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE=
github.com/prometheus/client_golang v1.20.5 h1:cxppBPuYhUnsO6yo/aoRol4L7q7UFfdm+bR9r+8l63Y=
github.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE=
github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q=
github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0=
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.55.0 h1:KEi6DK7lXW/m7Ig5i47x0vRzuBsHuvJdi5ee6Y3G1dc=
github.com/prometheus/common v0.55.0/go.mod h1:2SECS4xJG1kd8XF9IcM1gMX6510RAEL65zxzNImwdc8=
github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io=
github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I=
github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=
github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/urfave/cli v1.22.15 h1:nuqt+pdC/KqswQKhETJjo7pvn/k4xMUxgW6liI7XpnM=
github.com/urfave/cli v1.22.15/go.mod h1:wSan1hmo5zeyLGBjRJbzRTNk8gwoYa2B9n4q9dmRIc0=
github.com/urfave/cli v1.22.16 h1:MH0k6uJxdwdeWQTwhSO42Pwr4YLrNLwBtg1MRgTqPdQ=
github.com/urfave/cli v1.22.16/go.mod h1:EeJR6BKodywf4zciqrdw6hpCPk68JO9z5LazXZMn5Po=
github.com/urfave/cli v1.22.17 h1:SYzXoiPfQjHBbkYxbew5prZHS1TOLT3ierW8SYLqtVQ=
github.com/urfave/cli v1.22.17/go.mod h1:b0ht0aqgH/6pBYzzxURyrM4xXNgsoT/n2ZzwQiEhNVo=
github.com/wlynxg/anet v0.0.4 h1:0de1OFQxnNqAu+x2FAKKCVIrnfGKQbs7FQz++tB0+Uw=
github.com/wlynxg/anet v0.0.4/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A=
golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70=
golang.org/x/crypto v0.30.0 h1:RwoQn3GkWiMkzlX562cLB7OxWvjH1L8xutO2WoJcRoY=
golang.org/x/crypto v0.30.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys=
golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE=
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.24.0 h1:Mh5cbb+Zk2hqqXNO7S1iTjEphVL+jb8ZWaqh/g+JWkM=
golang.org/x/term v0.24.0/go.mod h1:lOBK/LVxemqiMij05LGJ0tzNr8xlmwBRJ81PX6wVLH8=
golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q=
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o=
golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw=
golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q=
golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg=
golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224=
golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM=
google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=


================================================
FILE: logger/logger.go
================================================
package logger

import (
	"os"
	"time"

	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
)

// Init initializes the logger.
func Init(lvl zerolog.Level) {
	log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}).Level(lvl)
	log.Debug().Msg("Logger initialized")
}


================================================
FILE: main.go
================================================
package main

import (
	"github.com/screego/server/cmd"
	pmode "github.com/screego/server/config/mode"
)

var (
	version    = "unknown"
	commitHash = "unknown"
	mode       = pmode.Dev
)

func main() {
	pmode.Set(mode)
	cmd.Run(version, commitHash)
}


================================================
FILE: router/router.go
================================================
package router

import (
	"encoding/json"
	"net/http"
	"time"

	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/rs/zerolog/hlog"
	"github.com/rs/zerolog/log"
	"github.com/screego/server/auth"
	"github.com/screego/server/config"
	"github.com/screego/server/ui"
	"github.com/screego/server/ws"
)

type Health struct {
	Status  string `json:"status"`
	Clients int    `json:"clients"`
	Reason  string `json:"reason,omitempty"`
}

type UIConfig struct {
	AuthMode                 string `json:"authMode"`
	User                     string `json:"user"`
	LoggedIn                 bool   `json:"loggedIn"`
	Version                  string `json:"version"`
	RoomName                 string `json:"roomName"`
	CloseRoomWhenOwnerLeaves bool   `json:"closeRoomWhenOwnerLeaves"`
}

func Router(conf config.Config, rooms *ws.Rooms, users *auth.Users, version string) *mux.Router {
	router := mux.NewRouter()
	router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// https://github.com/gorilla/mux/issues/416
		accessLogger(r, 404, 0, 0)
	})
	router.Use(hlog.AccessHandler(accessLogger))
	router.Use(handlers.CORS(handlers.AllowedMethods([]string{"GET", "POST"}), handlers.AllowedOriginValidator(conf.CheckOrigin)))
	router.HandleFunc("/stream", rooms.Upgrade)
	router.Methods("POST").Path("/login").HandlerFunc(users.Authenticate)
	router.Methods("POST").Path("/logout").HandlerFunc(users.Logout)
	router.Methods("GET").Path("/config").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user, loggedIn := users.CurrentUser(r)
		_ = json.NewEncoder(w).Encode(&UIConfig{
			AuthMode:                 conf.AuthMode,
			LoggedIn:                 loggedIn,
			User:                     user,
			Version:                  version,
			RoomName:                 rooms.RandRoomName(),
			CloseRoomWhenOwnerLeaves: conf.CloseRoomWhenOwnerLeaves,
		})
	})
	router.Methods("GET").Path("/health").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		i, err := rooms.Count()
		status := "up"
		if err != "" {
			status = "down"
			w.WriteHeader(500)
		}
		_ = json.NewEncoder(w).Encode(Health{
			Status:  status,
			Clients: i,
			Reason:  err,
		})
	})
	if conf.Prometheus {
		log.Info().Msg("Prometheus enabled")
		router.Methods("GET").Path("/metrics").Handler(basicAuth(promhttp.Handler(), users))
	}

	ui.Register(router)

	return router
}

func accessLogger(r *http.Request, status, size int, dur time.Duration) {
	log.Debug().
		Str("host", r.Host).
		Int("status", status).
		Int("size", size).
		Str("ip", r.RemoteAddr).
		Str("path", r.URL.Path).
		Str("duration", dur.String()).
		Msg("HTTP")
}

func basicAuth(handler http.Handler, users *auth.Users) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		user, pass, ok := r.BasicAuth()

		if !ok || !users.Validate(user, pass) {
			w.Header().Set("WWW-Authenticate", `Basic realm="screego"`)
			w.WriteHeader(401)
			_, _ = w.Write([]byte("Unauthorized.\n"))
			return
		}

		handler.ServeHTTP(w, r)
	}
}


================================================
FILE: screego.config.development
================================================
SCREEGO_SECRET=secure
SCREEGO_LOG_LEVEL=debug
SCREEGO_CORS_ALLOWED_ORIGINS=http://localhost:3000
SCREEGO_USERS_FILE=./users
SCREEGO_TURN_DENY_PEERS=


================================================
FILE: screego.config.example
================================================
# The external ip of the server.
# When using a dual stack setup define both IPv4 & IPv6 separated by a comma.
# Execute the following command on the server you want to host Screego
# to find your external ip.
#   curl 'https://api.ipify.org'
# Example:
#   SCREEGO_EXTERNAL_IP=192.168.178.2,2a01:c22:a87c:e500:2d8:61ff:fec7:f92a
#
# If the server doesn't have a static ip, the ip can be obtained via a domain:
#   SCREEGO_EXTERNAL_IP=dns:app.screego.net
# You can also specify the dns server to use
#   SCREEGO_EXTERNAL_IP=dns:app.screego.net@9.9.9.9:53
SCREEGO_EXTERNAL_IP=

# A secret which should be unique. Is used for cookie authentication.
SCREEGO_SECRET=

# If TLS should be enabled for HTTP requests. Screego requires TLS,
# you either have to enable this setting or serve TLS via a reverse proxy.
SCREEGO_SERVER_TLS=false
# The TLS cert file (only needed if TLS is enabled)
SCREEGO_TLS_CERT_FILE=
# The TLS key file (only needed if TLS is enabled)
SCREEGO_TLS_KEY_FILE=

# The address the http server will listen on.
# Formats:
# - host:port
#   Example: 127.0.0.1:5050
# - unix socket (must be prefixed with unix:)
#   Example: unix:/my/file/path.socket
SCREEGO_SERVER_ADDRESS=0.0.0.0:5050

# The address the TURN server will listen on.
SCREEGO_TURN_ADDRESS=0.0.0.0:3478

# Limit the ports that TURN will use for data relaying.
# Format: min:max
# Example:
#   50000:55000
SCREEGO_TURN_PORT_RANGE=

# If set, screego will not start TURN server and instead use an external TURN server.
# When using a dual stack setup define both IPv4 & IPv6 separated by a comma.
# Execute the following command on the server where you host TURN server
# to find your external ip.
#   curl 'https://api.ipify.org'
# Example:
#   SCREEGO_TURN_EXTERNAL_IP=192.168.178.2,2a01:c22:a87c:e500:2d8:61ff:fec7:f92a
#
# If the turn server doesn't have a static ip, the ip can be obtained via a domain:
#   SCREEGO_TURN_EXTERNAL_IP=dns:turn.screego.net
# You can also specify the dns server to use
#   SCREEGO_TURN_EXTERNAL_IP=dns:turn.screego.net@9.9.9.9:53
SCREEGO_TURN_EXTERNAL_IP=

# The port the external TURN server listens on.
SCREEGO_TURN_EXTERNAL_PORT=3478

# Authentication secret for the external TURN server.
SCREEGO_TURN_EXTERNAL_SECRET=

# Deny/ban peers within specific CIDRs to prevent TURN server users from
# accessing machines reachable by the TURN server but not from the internet,
# useful when the server is behind a NAT.
#
# Disallow internal ip addresses: https://en.wikipedia.org/wiki/Reserved_IP_addresses
# SCREEGO_TURN_DENY_PEERS=0.0.0.0/8,10.0.0.0/8,100.64.0.0/10,127.0.0.1/8,169.254.0.0/16,172.16.0.0/12,192.0.0.0/24,192.0.2.0/24,192.88.99.0/24,192.168.0.0/16,198.18.0.0/15,198.51.100.0/24,203.0.113.0/24,224.0.0.0/4,239.0.0.0/8,255.255.255.255/32,::/128,::1/128,64:ff9b:1::/48,100::/64,2001::/32,2002::/16,fc00::/7,fe80::/10
#
# By default denies local addresses.
SCREEGO_TURN_DENY_PEERS=0.0.0.0/8,127.0.0.1/8,::/128,::1/128,fe80::/10

# If reverse proxy headers should be trusted.
# Screego uses ip whitelisting for authentication
# of TURN connections. When behind a proxy the ip is always the proxy server.
# To still allow whitelisting this setting must be enabled and
# the `X-Real-Ip` header must be set by the reverse proxy.
SCREEGO_TRUST_PROXY_HEADERS=false

# Defines when a user login is required
# Possible values:
#   all: User login is always required
#   turn: User login is required for TURN connections
#   none: User login is never required
SCREEGO_AUTH_MODE=turn

# Defines origins that will be allowed to access Screego (HTTP + WebSocket)
# The default value is sufficient for most use-cases.
# Example Value: https://screego.net,https://sub.gotify.net
SCREEGO_CORS_ALLOWED_ORIGINS=

# Defines the location of the users file.
# File Format:
#   user1:bcrypt_password_hash
#   user2:bcrypt_password_hash
#
# Example:
#   user1:$2a$12$WEfYCnWGk0PDzbATLTNiTuoZ7e/43v6DM/h7arOnPU6qEtFG.kZQy
#
# The user password pair can be created via
#   screego hash --name "user1" --pass "your password"
SCREEGO_USERS_FILE=

# Defines how long a user session is valid in seconds.
# 0 = session invalides after browser session ends
SCREEGO_SESSION_TIMEOUT_SECONDS=0

# Defines the default value for the checkbox in the room creation dialog to select
# if the room should be closed when the room owner leaves
SCREEGO_CLOSE_ROOM_WHEN_OWNER_LEAVES=true

# The loglevel (one of: debug, info, warn, error)
SCREEGO_LOG_LEVEL=info

# If screego should expose a prometheus endpoint at /metrics. The endpoint
# requires basic authentication from a user in the users file.
SCREEGO_PROMETHEUS=false


================================================
FILE: server/server.go
================================================
package server

import (
	"context"
	"net"
	"net/http"
	"os"
	"os/signal"
	"strings"
	"time"

	"github.com/gorilla/mux"
	"github.com/rs/zerolog/log"
)

var (
	notifySignal   = signal.Notify
	serverShutdown = func(server *http.Server, ctx context.Context) error {
		return server.Shutdown(ctx)
	}
)

// Start starts the http server.
func Start(mux *mux.Router, address, cert, key string) error {
	server, shutdown := startServer(mux, address, cert, key)
	shutdownOnInterruptSignal(server, 2*time.Second, shutdown)
	return waitForServerToClose(shutdown)
}

func startServer(mux *mux.Router, address, cert, key string) (*http.Server, chan error) {
	srv := &http.Server{
		Addr:    address,
		Handler: mux,
	}

	shutdown := make(chan error)
	go func() {
		err := listenAndServe(srv, address, cert, key)
		shutdown <- err
	}()
	return srv, shutdown
}

func listenAndServe(srv *http.Server, address, cert, key string) error {
	var err error
	var listener net.Listener

	if strings.HasPrefix(address, "unix:") {
		listener, err = net.Listen("unix", strings.TrimPrefix(address, "unix:"))
	} else {
		listener, err = net.Listen("tcp", address)
	}
	if err != nil {
		return err
	}

	if cert != "" || key != "" {
		log.Info().Str("addr", address).Msg("Start HTTP with tls")
		return srv.ServeTLS(listener, cert, key)
	} else {
		log.Info().Str("addr", address).Msg("Start HTTP")
		return srv.Serve(listener)
	}
}

func shutdownOnInterruptSignal(server *http.Server, timeout time.Duration, shutdown chan<- error) {
	interrupt := make(chan os.Signal, 1)
	notifySignal(interrupt, os.Interrupt)

	go func() {
		<-interrupt
		log.Info().Msg("Received interrupt. Shutting down...")
		ctx, cancel := context.WithTimeout(context.Background(), timeout)
		defer cancel()
		if err := serverShutdown(server, ctx); err != nil {
			shutdown <- err
		}
	}()
}

func waitForServerToClose(shutdown <-chan error) error {
	err := <-shutdown
	if err == http.ErrServerClosed {
		return nil
	}
	return err
}


================================================
FILE: server/server_test.go
================================================
package server

import (
	"context"
	"errors"
	"net"
	"net/http"
	"os"
	"strconv"
	"testing"
	"time"

	"github.com/gorilla/mux"
	"github.com/stretchr/testify/assert"
)

func TestShutdownOnErrorWhileShutdown(t *testing.T) {
	disposeInterrupt := fakeInterrupt(t)
	defer disposeInterrupt()

	shutdownError := errors.New("shutdown error")
	disposeShutdown := fakeShutdownError(shutdownError)
	defer disposeShutdown()

	finished := make(chan error)

	go func() {
		finished <- Start(mux.NewRouter(), ":"+strconv.Itoa(port()), "", "")
	}()

	select {
	case <-time.After(1 * time.Second):
		t.Fatal("Server should be closed")
	case err := <-finished:
		assert.Equal(t, shutdownError, err)
	}
}

func TestShutdownAfterError(t *testing.T) {
	finished := make(chan error)

	go func() {
		finished <- Start(mux.NewRouter(), ":-5", "", "")
	}()

	select {
	case <-time.After(1 * time.Second):
		t.Fatal("Server should be closed")
	case err := <-finished:
		assert.NotNil(t, err)
	}
}

func TestShutdown(t *testing.T) {
	dispose := fakeInterrupt(t)
	defer dispose()

	finished := make(chan error)

	go func() {
		finished <- Start(mux.NewRouter(), ":"+strconv.Itoa(port()), "", "")
	}()

	select {
	case <-time.After(1 * time.Second):
		t.Fatal("Server should be closed")
	case err := <-finished:
		assert.Nil(t, err)
	}
}

func fakeInterrupt(t *testing.T) func() {
	oldNotify := notifySignal
	notifySignal = func(c chan<- os.Signal, sig ...os.Signal) {
		assert.Contains(t, sig, os.Interrupt)
		go func() {
			time.Sleep(100 * time.Millisecond)
			c <- os.Interrupt
		}()
	}
	return func() {
		notifySignal = oldNotify
	}
}

func fakeShutdownError(err error) func() {
	old := serverShutdown
	serverShutdown = func(server *http.Server, ctx context.Context) error {
		return err
	}
	return func() {
		serverShutdown = old
	}
}

func port() int {
	addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
	if err != nil {
		panic(err)
	}

	l, err := net.ListenTCP("tcp", addr)
	if err != nil {
		panic(err)
	}
	defer l.Close()
	return l.Addr().(*net.TCPAddr).Port
}


================================================
FILE: turn/none.go
================================================
package turn

import (
	"errors"
	"net"
	"strconv"
)

type RelayAddressGeneratorNone struct{}

func (r *RelayAddressGeneratorNone) Validate() error {
	return nil
}

func (r *RelayAddressGeneratorNone) AllocatePacketConn(network string, requestedPort int) (net.PacketConn, net.Addr, error) {
	conn, err := net.ListenPacket("udp", ":"+strconv.Itoa(requestedPort))
	if err != nil {
		return nil, nil, err
	}

	return conn, conn.LocalAddr(), nil
}

func (r *RelayAddressGeneratorNone) AllocateConn(network string, requestedPort int) (net.Conn, net.Addr, error) {
	return nil, nil, errors.New("todo")
}


================================================
FILE: turn/portrange.go
================================================
package turn

import (
	"errors"
	"fmt"
	"net"

	"github.com/pion/randutil"
)

type RelayAddressGeneratorPortRange struct {
	MinPort uint16
	MaxPort uint16
	Rand    randutil.MathRandomGenerator
}

func (r *RelayAddressGeneratorPortRange) Validate() error {
	if r.Rand == nil {
		r.Rand = randutil.NewMathRandomGenerator()
	}

	return nil
}

func (r *RelayAddressGeneratorPortRange) AllocatePacketConn(network string, requestedPort int) (net.PacketConn, net.Addr, error) {
	if requestedPort != 0 {
		conn, err := net.ListenPacket("udp", fmt.Sprintf(":%d", requestedPort))
		if err != nil {
			return nil, nil, err
		}
		relayAddr := conn.LocalAddr().(*net.UDPAddr)
		return conn, relayAddr, nil
	}

	for try := 0; try < 10; try++ {
		port := r.MinPort + uint16(r.Rand.Intn(int((r.MaxPort+1)-r.MinPort)))
		conn, err := net.ListenPacket("udp", fmt.Sprintf(":%d", port))
		if err != nil {
			continue
		}

		relayAddr := conn.LocalAddr().(*net.UDPAddr)
		return conn, relayAddr, nil
	}

	return nil, nil, errors.New("could not find free port: max retries exceeded")
}

func (r *RelayAddressGeneratorPortRange) AllocateConn(network string, requestedPort int) (net.Conn, net.Addr, error) {
	return nil, nil, errors.New("todo")
}


================================================
FILE: turn/server.go
================================================
package turn

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"fmt"
	"net"
	"sync"
	"time"

	"github.com/pion/turn/v4"
	"github.com/rs/zerolog/log"
	"github.com/screego/server/config"
	"github.com/screego/server/config/ipdns"
	"github.com/screego/server/util"
)

type Server interface {
	Credentials(id string, addr net.IP) (string, string)
	Disallow(username string)
}

type InternalServer struct {
	lock   sync.RWMutex
	lookup map[string]Entry
}

type ExternalServer struct {
	secret []byte
	ttl    time.Duration
}

type Entry struct {
	addr     net.IP
	password []byte
}

const Realm = "screego"

type Generator struct {
	turn.RelayAddressGenerator
	IPProvider ipdns.Provider
}

func (r *Generator) AllocatePacketConn(network string, requestedPort int) (net.PacketConn, net.Addr, error) {
	conn, addr, err := r.RelayAddressGenerator.AllocatePacketConn(network, requestedPort)
	if err != nil {
		return conn, addr, err
	}
	relayAddr := *addr.(*net.UDPAddr)

	v4, v6, err := r.IPProvider.Get()
	if err != nil {
		return conn, addr, err
	}

	if v6 == nil || (relayAddr.IP.To4() != nil && v4 != nil) {
		relayAddr.IP = v4
	} else {
		relayAddr.IP = v6
	}
	if err == nil {
		log.Debug().Str("addr", addr.String()).Str("relayaddr", relayAddr.String()).Msg("TURN allocated")
	}
	return conn, &relayAddr, err
}

func Start(conf config.Config) (Server, error) {
	if conf.TurnExternal {
		return newExternalServer(conf)
	} else {
		return newInternalServer(conf)
	}
}

func newExternalServer(conf config.Config) (Server, error) {
	return &ExternalServer{
		secret: []byte(conf.TurnExternalSecret),
		ttl:    24 * time.Hour,
	}, nil
}

func newInternalServer(conf config.Config) (Server, error) {
	udpListener, err := net.ListenPacket("udp", conf.TurnAddress)
	if err != nil {
		return nil, fmt.Errorf("udp: could not listen on %s: %s", conf.TurnAddress, err)
	}
	tcpListener, err := net.Listen("tcp", conf.TurnAddress)
	if err != nil {
		return nil, fmt.Errorf("tcp: could not listen on %s: %s", conf.TurnAddress, err)
	}

	svr := &InternalServer{lookup: map[string]Entry{}}

	gen := &Generator{
		RelayAddressGenerator: generator(conf),
		IPProvider:            conf.TurnIPProvider,
	}

	var permissions turn.PermissionHandler = func(clientAddr net.Addr, peerIP net.IP) bool {
		for _, cidr := range conf.TurnDenyPeersParsed {
			if cidr.Contains(peerIP) {
				return false
			}
		}

		return true
	}

	_, err = turn.NewServer(turn.ServerConfig{
		Realm:       Realm,
		AuthHandler: svr.authenticate,
		ListenerConfigs: []turn.ListenerConfig{
			{Listener: tcpListener, RelayAddressGenerator: gen, PermissionHandler: permissions},
		},
		PacketConnConfigs: []turn.PacketConnConfig{
			{PacketConn: udpListener, RelayAddressGenerator: gen, PermissionHandler: permissions},
		},
	})
	if err != nil {
		return nil, err
	}

	log.Info().Str("addr", conf.TurnAddress).Msg("Start TURN/STUN")
	return svr, nil
}

func generator(conf config.Config) turn.RelayAddressGenerator {
	min, max, useRange := conf.PortRange()
	if useRange {
		log.Debug().Uint16("min", min).Uint16("max", max).Msg("Using Port Range")
		return &RelayAddressGeneratorPortRange{MinPort: min, MaxPort: max}
	}
	return &RelayAddressGeneratorNone{}
}

func (a *InternalServer) allow(username, password string, addr net.IP) {
	a.lock.Lock()
	defer a.lock.Unlock()
	a.lookup[username] = Entry{
		addr:     addr,
		password: turn.GenerateAuthKey(username, Realm, password),
	}
}

func (a *InternalServer) Disallow(username string) {
	a.lock.Lock()
	defer a.lock.Unlock()

	delete(a.lookup, username)
}

func (a *ExternalServer) Disallow(username string) {
	// not supported, will expire on TTL
}

func (a *InternalServer) authenticate(username, realm string, addr net.Addr) ([]byte, bool) {
	a.lock.RLock()
	defer a.lock.RUnlock()

	entry, ok := a.lookup[username]

	if !ok {
		log.Debug().Interface("addr", addr).Str("username", username).Msg("TURN username not found")
		return nil, false
	}

	log.Debug().Interface("addr", addr.String()).Str("realm", realm).Msg("TURN authenticated")
	return entry.password, true
}

func (a *InternalServer) Credentials(id string, addr net.IP) (string, string) {
	password := util.RandString(20)
	a.allow(id, password, addr)
	return id, password
}

func (a *ExternalServer) Credentials(id string, addr net.IP) (string, string) {
	username := fmt.Sprintf("%d:%s", time.Now().Add(a.ttl).Unix(), id)
	mac := hmac.New(sha1.New, a.secret)
	_, _ = mac.Write([]byte(username))
	password := base64.StdEncoding.EncodeToString(mac.Sum(nil))
	return username, password
}


================================================
FILE: ui/.gitignore
================================================
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*


================================================
FILE: ui/.prettierrc
================================================
{
  "printWidth": 100,
  "tabWidth": 4,
  "useTabs": false,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "es5",
  "bracketSpacing": false,
  "arrowParens": "always",
  "parser": "typescript"
}


================================================
FILE: ui/index.html
================================================
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="./favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#FFFFFF" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Screego" />
    <meta property="og:description" content="screen sharing for developers" />
    <meta property="og:image" content="./og-banner.png" />
    <meta property="og:image:width" content="400" />
    <meta property="og:image:height" content="300" />
    <meta
      name="description"
      content="Screego - screen sharing for developers"
    />
    <link rel="apple-touch-icon" href="./apple-touch-icon.png" />
    <title>Screego</title>
  </head>
  <body>
    <noscript>Screego requires JavaScript (:</noscript>
    <div id="root"></div>
    <script type="module" src="/src/index.tsx"></script>
  </body>
</html>


================================================
FILE: ui/package.json
================================================
{
  "name": "ui",
  "version": "0.1.0",
  "homepage": ".",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.13.3",
    "@emotion/styled": "11.14.1",
    "@mui/icons-material": "7.3.6",
    "@mui/material": "7.3.6",
    "@mui/styles": "^6.1.1",
    "@types/react": "19.2.7",
    "@types/react-dom": "19.2.3",
    "@vitejs/plugin-react-swc": "4.2.2",
    "notistack": "^3.0.1",
    "prettier": "3.7.4",
    "react": "19.2.3",
    "react-dom": "19.2.3",
    "react-hotkeys-hook": "5.2.1",
    "tss-react": "^4.9.20",
    "typescript": "5.9.3",
    "use-http": "^1.0.28",
    "vite": "7.3.0",
    "vite-plugin-svgr": "4.5.0",
    "vite-tsconfig-paths": "6.0.3"
  },
  "scripts": {
    "start": "vite",
    "format": "prettier \"src/**/*.{ts,tsx}\" --write",
    "testformat": "prettier \"src/**/*.{ts,tsx}\" --list-different",
    "build": "tsc && vite build"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}


================================================
FILE: ui/serve.go
================================================
package ui

import (
	"embed"
	"io"
	"io/fs"
	"net/http"

	"github.com/gorilla/mux"
	"github.com/rs/zerolog/log"
)

//go:embed build
var buildFiles embed.FS
var files, _ = fs.Sub(buildFiles, "build")

// Register registers the ui on the root path.
func Register(r *mux.Router) {
	r.Handle("/", serveFile("index.html", "text/html"))
	r.Handle("/index.html", serveFile("index.html", "text/html"))
	r.Handle("/assets/{resource}", http.FileServer(http.FS(files)))

	r.Handle("/favicon.ico", serveFile("favicon.ico", "image/x-icon"))
	r.Handle("/logo.svg", serveFile("logo.svg", "image/svg+xml"))
	r.Handle("/apple-touch-icon.png", serveFile("apple-touch-icon.png", "image/png"))
	r.Handle("/og-banner.png", serveFile("og-banner.png", "image/png"))
}

func serveFile(name, contentType string) http.HandlerFunc {
	file, err := files.Open(name)
	if err != nil {
		log.Panic().Err(err).Msgf("could not find %s", file)
	}
	defer file.Close()
	content, err := io.ReadAll(file)
	if err != nil {
		log.Panic().Err(err).Msgf("could not read %s", file)
	}

	return func(writer http.ResponseWriter, reg *http.Request) {
		writer.Header().Set("Content-Type", contentType)
		_, _ = writer.Write(content)
	}
}


================================================
FILE: ui/src/LoginForm.tsx
================================================
import {UseConfig} from './useConfig';
import React from 'react';
import {
    Box,
    Button,
    ButtonProps,
    CircularProgress,
    FormControl,
    TextField,
    Typography,
} from '@mui/material';
import {makeStyles} from 'tss-react/mui';
import {green} from '@mui/material/colors';

export const LoginForm = ({config: {login}, hide}: {config: UseConfig; hide?: () => void}) => {
    const [user, setUser] = React.useState('');
    const [pass, setPass] = React.useState('');
    const [loading, setLoading] = React.useState(false);
    const submit = async (event: {preventDefault: () => void}) => {
        event.preventDefault();
        setLoading(true);
        login(user, pass)
            .then(() => {
                setLoading(false);
            })
            .catch(() => setLoading(false));
    };
    return (
        <div>
            <FormControl fullWidth>
                <form onSubmit={submit}>
                    <div style={{display: 'flex', alignItems: 'center'}}>
                        <Typography style={{flex: 1}}>Login to Screego</Typography>
                        {hide ? (
                            <Button variant="outlined" size="small" onClick={hide}>
                                Go Back
                            </Button>
                        ) : undefined}
                    </div>
                    <TextField
                        fullWidth
                        value={user}
                        onChange={(e) => setUser(e.target.value)}
                        label="Username"
                        size="small"
                        margin="dense"
                    />
                    <TextField
                        fullWidth
                        value={pass}
                        type="password"
                        onChange={(e) => setPass(e.target.value)}
                        label="Password"
                        size="small"
                        margin="dense"
                    />
                    <Box marginTop={1}>
                        <LoadingButton
                            type="submit"
                            loading={loading}
                            onClick={submit}
                            fullWidth
                            variant="contained"
                        >
                            Login
                        </LoadingButton>
                    </Box>
                </form>
            </FormControl>
        </div>
    );
};

export const LoadingButton = ({loading, children, ...props}: ButtonProps & {loading: boolean}) => {
    const {classes} = useStyles();
    return (
        <Button {...props} disabled={loading}>
            {children}
            {loading && (
                <CircularProgress className={classes.buttonProgress} size={24} color="secondary" />
            )}
        </Button>
    );
};

const useStyles = makeStyles()(() => ({
    buttonProgress: {
        color: green[500],
        position: 'absolute',
        top: '50%',
        left: '50%',
        marginTop: -12,
        marginLeft: -12,
    },
}));


================================================
FILE: ui/src/NumberField.tsx
================================================
import {TextField, TextFieldProps} from '@mui/material';
import React from 'react';

export interface NumberFieldProps {
    value: number;
    min: number;
    onChange: (value: number) => void;
}

export const NumberField = ({
    value,
    min,
    onChange,
    ...props
}: NumberFieldProps & Omit<TextFieldProps, 'value' | 'onChange'>) => {
    const [stringValue, setStringValue] = React.useState<string>(value.toString());
    const [error, setError] = React.useState('');

    return (
        <TextField
            value={stringValue}
            type="number"
            helperText={error}
            error={error !== ''}
            onChange={(event) => {
                setStringValue(event.target.value);
                const i = parseInt(event.target.value, 10);
                if (Number.isNaN(i)) {
                    setError('Invalid number');
                    return;
                }

                if (i < min) {
                    setError('Number must be at least ' + min);
                    return;
                }
                onChange(i);
                setError('');
            }}
            {...props}
        />
    );
};


================================================
FILE: ui/src/Room.tsx
================================================
import React, {useCallback} from 'react';
import {Badge, Box, IconButton, Paper, Tooltip, Typography, Slider, Stack} from '@mui/material';
import CancelPresentationIcon from '@mui/icons-material/CancelPresentation';
import PresentToAllIcon from '@mui/icons-material/PresentToAll';
import FullScreenIcon from '@mui/icons-material/Fullscreen';
import PeopleIcon from '@mui/icons-material/People';
import VolumeMuteIcon from '@mui/icons-material/VolumeOff';
import VolumeIcon from '@mui/icons-material/VolumeUp';
import SettingsIcon from '@mui/icons-material/Settings';
import {useHotkeys} from 'react-hotkeys-hook';
import {Video} from './Video';
import {makeStyles} from 'tss-react/mui';
import {ConnectedRoom} from './useRoom';
import {useSnackbar} from 'notistack';
import {RoomUser} from './message';
import {useSettings, VideoDisplayMode} from './settings';
import {SettingDialog} from './SettingDialog';

const HostStream: unique symbol = Symbol('mystream');

const flags = (user: RoomUser) => {
    const result: string[] = [];
    if (user.you) {
        result.push('You');
    }
    if (user.owner) {
        result.push('Owner');
    }
    if (user.streaming) {
        result.push('Streaming');
    }
    if (!result.length) {
        return '';
    }
    return ` (${result.join(', ')})`;
};

interface FullScreenHTMLVideoElement extends HTMLVideoElement {
    msRequestFullscreen?: () => void;
    mozRequestFullScreen?: () => void;
    webkitRequestFullscreen?: () => void;
}

const requestFullscreen = (element: FullScreenHTMLVideoElement | null) => {
    if (element?.requestFullscreen) {
        element.requestFullscreen();
    } else if (element?.mozRequestFullScreen) {
        element.mozRequestFullScreen();
    } else if (element?.msRequestFullscreen) {
        element.msRequestFullscreen();
    } else if (element?.webkitRequestFullscreen) {
        element.webkitRequestFullscreen();
    }
};

export const Room = ({
    state,
    share,
    stopShare,
    setName,
}: {
    state: ConnectedRoom;
    share: () => void;
    stopShare: () => void;
    setName: (name: string) => void;
}) => {
    const {classes} = useStyles();
    const [open, setOpen] = React.useState(false);
    const {enqueueSnackbar} = useSnackbar();
    const [settings, setSettings] = useSettings();
    const [showControl, setShowControl] = React.useState(true);
    const [hoverControl, setHoverControl] = React.useState(false);
    const [selectedStream, setSelectedStream] = React.useState<string | typeof HostStream>();
    const [videoElement, setVideoElement] = React.useState<FullScreenHTMLVideoElement | null>(null);

    useShowOnMouseMovement(setShowControl);

    const handleFullscreen = useCallback(() => requestFullscreen(videoElement), [videoElement]);

    React.useEffect(() => {
        if (selectedStream === HostStream && state.hostStream) {
            return;
        }
        if (state.clientStreams.some(({id}) => id === selectedStream)) {
            return;
        }
        if (state.clientStreams.length === 0 && selectedStream) {
            setSelectedStream(undefined);
            return;
        }
        setSelectedStream(state.clientStreams[0]?.id);
    }, [state.clientStreams, selectedStream, state.hostStream]);

    const stream =
        selectedStream === HostStream
            ? state.hostStream
            : state.clientStreams.find(({id}) => selectedStream === id)?.stream;

    React.useEffect(() => {
        if (videoElement && stream) {
            videoElement.srcObject = stream;
            videoElement.play().catch((err) => {
                console.log('Could not play main video', err);
                if (err.name === 'NotAllowedError') {
                    videoElement.muted = true;
                    videoElement
                        .play()
                        .catch((retryErr) =>
                            console.log('Could not play main video with mute', retryErr)
                        );
                }
            });
        }
    }, [videoElement, stream]);

    const copyLink = () => {
        navigator?.clipboard?.writeText(window.location.href)?.then(
            () => enqueueSnackbar('Link Copied', {variant: 'success'}),
            (err) => enqueueSnackbar('Copy Failed ' + err, {variant: 'error'})
        );
    };

    const setHoverState = React.useMemo(
        () => ({
            onMouseLeave: () => setHoverControl(false),
            onMouseEnter: () => setHoverControl(true),
        }),
        [setHoverControl]
    );

    const controlVisible = showControl || open || hoverControl;

    useHotkeys('s', () => (state.hostStream ? stopShare() : share()), [state.hostStream]);
    useHotkeys(
        'f',
        () => {
            if (selectedStream) {
                handleFullscreen();
            }
        },
        [handleFullscreen, selectedStream]
    );
    useHotkeys('c', copyLink);
    useHotkeys(
        'h',
        () => {
            if (state.clientStreams !== undefined && state.clientStreams.length > 0) {
                const currentStreamIndex = state.clientStreams.findIndex(
                    ({id}) => id === selectedStream
                );
                const nextIndex =
                    currentStreamIndex === state.clientStreams.length - 1
                        ? 0
                        : currentStreamIndex + 1;
                setSelectedStream(state.clientStreams[nextIndex].id);
            }
        },
        [state.clientStreams, selectedStream]
    );
    useHotkeys(
        'l',
        () => {
            if (state.clientStreams !== undefined && state.clientStreams.length > 0) {
                const currentStreamIndex = state.clientStreams.findIndex(
                    ({id}) => id === selectedStream
                );
                const previousIndex =
                    currentStreamIndex === 0
                        ? state.clientStreams.length - 1
                        : currentStreamIndex - 1;
                setSelectedStream(state.clientStreams[previousIndex].id);
            }
        },
        [state.clientStreams, selectedStream]
    );
    useHotkeys(
        'm',
        () => {
            if (videoElement) {
                videoElement.muted = !videoElement.muted;
            }
        },
        [videoElement]
    );

    const videoClasses = () => {
        switch (settings.displayMode) {
            case VideoDisplayMode.FitToWindow:
                return `${classes.video} ${classes.videoWindowFit}`;
            case VideoDisplayMode.OriginalSize:
                return `${classes.video}`;
            case VideoDisplayMode.FitWidth:
                return `${classes.video} ${classes.videoWindowWidth}`;
            case VideoDisplayMode.FitHeight:
                return `${classes.video} ${classes.videoWindowHeight}`;
        }
    };

    return (
        <div className={classes.videoContainer}>
            {controlVisible && (
                <Paper className={classes.title} elevation={10} {...setHoverState}>
                    <Tooltip title="Copy Link">
                        <Typography
                            variant="h4"
                            component="h4"
                            style={{cursor: 'pointer'}}
                            onClick={copyLink}
                        >
                            {state.id}
                        </Typography>
                    </Tooltip>
                </Paper>
            )}

            {stream ? (
                <video
                    ref={setVideoElement}
                    className={videoClasses()}
                    onDoubleClick={handleFullscreen}
                />
            ) : (
                <Typography
                    variant="h4"
                    align="center"
                    component="div"
                    style={{
                        top: '50%',
                        left: '50%',
                        position: 'absolute',
                        transform: 'translate(-50%, -50%)',
                    }}
                >
                    no stream available
                </Typography>
            )}

            {controlVisible && (
                <Paper className={classes.control} elevation={10} {...setHoverState}>
                    {(stream?.getAudioTracks().length ?? 0) > 0 && videoElement && (
                        <AudioControl video={videoElement} />
                    )}
                    <Box whiteSpace="nowrap">
                        {state.hostStream ? (
                            <Tooltip title="Cancel Presentation" arrow>
                                <IconButton onClick={stopShare} size="large">
                                    <CancelPresentationIcon fontSize="large" />
                                </IconButton>
                            </Tooltip>
                        ) : (
                            <Tooltip title="Start Presentation" arrow>
                                <IconButton onClick={share} size="large">
                                    <PresentToAllIcon fontSize="large" />
                                </IconButton>
                            </Tooltip>
                        )}

                        <Tooltip
                            classes={{tooltip: classes.noMaxWidth}}
                            title={
                                <div>
                                    <Typography variant="h5">Member List</Typography>
                                    {state.users.map((user) => (
                                        <Typography key={user.id}>
                                            {user.name} {flags(user)}
                                        </Typography>
                                    ))}
                                </div>
                            }
                            arrow
                        >
                            <Badge badgeContent={state.users.length} color="primary">
                                <PeopleIcon fontSize="large" />
                            </Badge>
                        </Tooltip>
                        <Tooltip title="Fullscreen" arrow>
                            <IconButton
                                onClick={() => handleFullscreen()}
                                disabled={!selectedStream}
                                size="large"
                            >
                                <FullScreenIcon fontSize="large" />
                            </IconButton>
                        </Tooltip>

                        <Tooltip title="Settings" arrow>
                            <IconButton onClick={() => setOpen(true)} size="large">
                                <SettingsIcon fontSize="large" />
                            </IconButton>
                        </Tooltip>
                    </Box>
                </Paper>
            )}

            <div className={classes.bottomContainer}>
                {state.clientStreams
                    .filter(({id}) => id !== selectedStream)
                    .map((client) => {
                        return (
                            <Paper
                                key={client.id}
                                elevation={4}
                                className={classes.smallVideoContainer}
                                onClick={() => setSelectedStream(client.id)}
                            >
                                <Video
                                    key={client.id}
                                    src={client.stream}
                                    className={classes.smallVideo}
                                />
                                <Typography
                                    variant="subtitle1"
                                    component="div"
                                    align="center"
                                    className={classes.smallVideoLabel}
                                >
                                    {state.users.find(({id}) => client.peer_id === id)?.name ??
                                        'unknown'}
                                </Typography>
                            </Paper>
                        );
                    })}
                {state.hostStream && selectedStream !== HostStream && (
                    <Paper
                        elevation={4}
                        className={classes.smallVideoContainer}
                        onClick={() => setSelectedStream(HostStream)}
                    >
                        <Video src={state.hostStream} className={classes.smallVideo} />
                        <Typography
                            variant="subtitle1"
                            component="div"
                            align="center"
                            className={classes.smallVideoLabel}
                        >
                            You
                        </Typography>
                    </Paper>
                )}
                <SettingDialog
                    open={open}
                    setOpen={setOpen}
                    updateName={setName}
                    saveSettings={setSettings}
                />
            </div>
        </div>
    );
};

const useShowOnMouseMovement = (doShow: (s: boolean) => void) => {
    const timeoutHandle = React.useRef(0);

    React.useEffect(() => {
        const update = () => {
            if (timeoutHandle.current === 0) {
                doShow(true);
            }

            clearTimeout(timeoutHandle.current);
            timeoutHandle.current = window.setTimeout(() => {
                timeoutHandle.current = 0;
                doShow(false);
            }, 1000);
        };
        window.addEventListener('mousemove', update);
        return () => window.removeEventListener('mousemove', update);
    }, [doShow]);

    React.useEffect(
        () =>
            void (timeoutHandle.current = window.setTimeout(() => {
                timeoutHandle.current = 0;
                doShow(false);
            }, 1000)),
        // eslint-disable-next-line react-hooks/exhaustive-deps
        []
    );
};

const AudioControl = ({video}: {video: FullScreenHTMLVideoElement}) => {
    // this is used to force a rerender
    const [, setMuted] = React.useState<boolean>();

    React.useEffect(() => {
        const handler = () => setMuted(video.muted);
        video.addEventListener('volumechange', handler);
        setMuted(video.muted);
        return () => video.removeEventListener('volumechange', handler);
    });

    return (
        <Stack spacing={0.5} pr={2} direction="row" sx={{alignItems: 'center', my: 1, height: 35}}>
            <IconButton size="large" onClick={() => (video.muted = !video.muted)}>
                {video.muted ? (
                    <VolumeMuteIcon fontSize="large" />
                ) : (
                    <VolumeIcon fontSize="large" />
                )}
            </IconButton>
            <Slider
                min={0}
                max={1}
                step={0.01}
                defaultValue={video.volume}
                onChange={(_, newVolume) => {
                    video.muted = false;
                    video.volume = newVolume;
                }}
            />
        </Stack>
    );
};

const useStyles = makeStyles()(() => ({
    title: {
        padding: 15,
        position: 'fixed',
        top: '30px',
        left: '50%',
        transform: 'translateX(-50%)',
        zIndex: 30,
    },
    bottomContainer: {
        position: 'fixed',
        display: 'flex',
        bottom: 0,
        right: 0,
        zIndex: 20,
    },
    control: {
        padding: 15,
        position: 'fixed',
        bottom: '30px',
        left: '50%',
        transform: 'translateX(-50%)',
        zIndex: 30,
    },
    video: {
        display: 'block',
        margin: '0 auto',

        '&::-webkit-media-controls-start-playback-button': {
            display: 'none!important',
        },
        '&::-webkit-media-controls': {
            display: 'none!important',
        },
    },
    smallVideo: {
        minWidth: '100%',
        minHeight: '100%',
        width: 'auto',
        maxWidth: '300px',

        maxHeight: '200px',
    },
    videoWindowFit: {
        width: '100%',
        height: '100%',

        position: 'absolute',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%,-50%)',
    },
    videoWindowWidth: {
        height: 'auto',
        width: '100%',
    },
    videoWindowHeight: {
        height: '100%',
        width: 'auto',
    },
    smallVideoLabel: {
        position: 'absolute',
        display: 'block',
        bottom: 0,
        background: 'rgba(0,0,0,.5)',
        padding: '5px 15px',
    },
    noMaxWidth: {
        maxWidth: 'none',
    },
    smallVideoContainer: {
        height: '100%',
        padding: 5,
        maxHeight: 200,
        maxWidth: 400,
        width: '100%',
    },
    videoContainer: {
        position: 'absolute',
        top: 0,
        bottom: 0,
        width: '100%',
        height: '100%',

        overflow: 'auto',
    },
}));


================================================
FILE: ui/src/RoomManage.tsx
================================================
import React from 'react';
import {
    Box,
    Button,
    Checkbox,
    FormControl,
    FormControlLabel,
    Grid,
    Paper,
    TextField,
    Typography,
    Link,
} from '@mui/material';
import {FCreateRoom, UseRoom} from './useRoom';
import {UIConfig} from './message';
import {getRoomFromURL} from './useRoomID';
import {authModeToRoomMode, UseConfig} from './useConfig';
import {LoginForm} from './LoginForm';

const CreateRoom = ({room, config}: Pick<UseRoom, 'room'> & {config: UIConfig}) => {
    const [id, setId] = React.useState(() => getRoomFromURL() ?? config.roomName);
    const mode = authModeToRoomMode(config.authMode, config.loggedIn);
    const [ownerLeave, setOwnerLeave] = React.useState(config.closeRoomWhenOwnerLeaves);
    const submit = () =>
        room({
            type: 'create',
            payload: {
                mode,
                closeOnOwnerLeave: ownerLeave,
                joinIfExist: true,
                id: id || undefined,
            },
        });
    return (
        <div>
            <FormControl fullWidth>
                <TextField
                    fullWidth
                    value={id}
                    onChange={(e) => setId(e.target.value)}
                    label="id"
                    margin="dense"
                />
                <FormControlLabel
                    control={
                        <Checkbox
                            checked={ownerLeave}
                            onChange={(_, checked) => setOwnerLeave(checked)}
                        />
                    }
                    label="Close Room after you leave"
                />
                <Box paddingBottom={0.5}>
                    <Typography>
                        Nat Traversal via:{' '}
                        <Link
                            href="https://screego.net/#/nat-traversal"
                            target="_blank"
                            rel="noreferrer"
                        >
                            {mode.toUpperCase()}
                        </Link>
                    </Typography>
                </Box>
                <Button onClick={submit} fullWidth variant="contained">
                    Create or Join a Room
                </Button>
            </FormControl>
        </div>
    );
};

export const RoomManage = ({room, config}: {room: FCreateRoom; config: UseConfig}) => {
    const [showLogin, setShowLogin] = React.useState(false);

    const canCreateRoom = config.authMode !== 'all';
    const loginVisible = !config.loggedIn && (showLogin || !canCreateRoom);

    return (
        <Grid
            container={true}
            justifyContent="center"
            style={{paddingTop: 50, maxWidth: 400, width: '100%', margin: '0 auto'}}
            spacing={4}
        >
            <Grid size={12}>
                <Typography align="center" gutterBottom>
                    <img src="./logo.svg" style={{width: 230}} alt="logo" />
                </Typography>
                <Paper elevation={3} style={{padding: 20}}>
                    {loginVisible ? (
                        <LoginForm
                            config={config}
                            hide={canCreateRoom ? () => setShowLogin(false) : undefined}
                        />
                    ) : (
                        <>
                            <Typography style={{display: 'flex', alignItems: 'center'}}>
                                <span style={{flex: 1}}>Hello {config.user}!</span>{' '}
                                {config.loggedIn ? (
                                    <Button variant="outlined" size="small" onClick={config.logout}>
                                        Logout
                                    </Button>
                                ) : (
                                    <Button
                                        variant="outlined"
                                        size="small"
                                        onClick={() => setShowLogin(true)}
                                    >
                                        Login
                                    </Button>
                                )}
                            </Typography>

                            <CreateRoom room={room} config={config} />
                        </>
                    )}
                </Paper>
            </Grid>
            <div style={{position: 'absolute', margin: '0 auto', bottom: 0}}>
                Screego {config.version} |{' '}
                <Link href="https://github.com/screego/server/">GitHub</Link>
            </div>
        </Grid>
    );
};


================================================
FILE: ui/src/Router.tsx
================================================
import {RoomManage} from './RoomManage';
import {useRoom} from './useRoom';
import {Room} from './Room';
import {UseConfig, useConfig} from './useConfig';

export const Router = () => {
    const config = useConfig();

    if (config.loading) {
        // show spinner
        return null;
    }
    return <RouterLoadedConfig config={config} />;
};

const RouterLoadedConfig = ({config}: {config: UseConfig}) => {
    const {room, state, ...other} = useRoom(config);

    if (state) {
        return <Room state={state} {...other} />;
    }

    return <RoomManage room={room} config={config} />;
};


================================================
FILE: ui/src/SettingDialog.tsx
================================================
import React from 'react';
import {
    Dialog,
    DialogTitle,
    DialogContent,
    TextField,
    DialogActions,
    Button,
    Autocomplete,
    Box,
} from '@mui/material';
import {
    CodecBestQuality,
    CodecDefault,
    codecName,
    loadSettings,
    PreferredCodec,
    Settings,
    VideoDisplayMode,
} from './settings';
import {NumberField} from './NumberField';

export interface SettingDialogProps {
    open: boolean;
    setOpen: (open: boolean) => void;
    updateName: (s: string) => void;
    saveSettings: (s: Settings) => void;
}

const getAvailableCodecs = (): PreferredCodec[] => {
    if ('getCapabilities' in RTCRtpSender) {
        return RTCRtpSender.getCapabilities('video')?.codecs ?? [];
    }
    return [];
};

const NativeCodecs = getAvailableCodecs();

export const SettingDialog = ({open, setOpen, updateName, saveSettings}: SettingDialogProps) => {
    const [settingsInput, setSettingsInput] = React.useState(loadSettings);

    const doSubmit = () => {
        saveSettings(settingsInput);
        updateName(settingsInput.name ?? '');
        setOpen(false);
    };

    const {name, preferCodec, displayMode, framerate} = settingsInput;

    return (
        <Dialog open={open} onClose={() => setOpen(false)} maxWidth={'xs'} fullWidth>
            <DialogTitle>Settings</DialogTitle>
            <DialogContent>
                <form onSubmit={doSubmit}>
                    <Box paddingBottom={1}>
                        <TextField
                            autoFocus
                            margin="dense"
                            label="Username"
                            value={name}
                            onChange={(e) =>
                                setSettingsInput((c) => ({...c, name: e.target.value}))
                            }
                            fullWidth
                        />
                    </Box>
                    {NativeCodecs.length > 0 ? (
                        <Box paddingY={1}>
                            <Autocomplete<PreferredCodec>
                                options={[CodecBestQuality, CodecDefault, ...NativeCodecs]}
                                getOptionLabel={({mimeType, sdpFmtpLine}) =>
                                    codecName(mimeType) + (sdpFmtpLine ? ` (${sdpFmtpLine})` : '')
                                }
                                value={preferCodec}
                                isOptionEqualToValue={(a, b) =>
                                    a.mimeType === b.mimeType && a.sdpFmtpLine === b.sdpFmtpLine
                                }
                                fullWidth
                                onChange={(_, value) =>
                                    setSettingsInput((c) => ({
                                        ...c,
                                        preferCodec: value ?? undefined,
                                    }))
                                }
                                renderInput={(params) => (
                                    <TextField {...params} label="Preferred Codec" />
                                )}
                            />
                        </Box>
                    ) : undefined}
                    <Box paddingTop={1}>
                        <Autocomplete<VideoDisplayMode>
                            options={Object.values(VideoDisplayMode)}
                            onChange={(_, value) =>
                                setSettingsInput((c) => ({
                                    ...c,
                                    displayMode: value ?? VideoDisplayMode.FitToWindow,
                                }))
                            }
                            value={displayMode}
                            fullWidth
                            renderInput={(params) => <TextField {...params} label="Display Mode" />}
                        />
                    </Box>
                    <Box paddingTop={1}>
                        <NumberField
                            label="FrameRate"
                            min={1}
                            onChange={(framerate) => setSettingsInput((c) => ({...c, framerate}))}
                            value={framerate}
                            fullWidth
                        />
                    </Box>
                </form>
            </DialogContent>
            <DialogActions>
                <Button onClick={() => setOpen(false)} color="primary">
                    Cancel
                </Button>
                <Button onClick={doSubmit} color="primary">
                    Save
                </Button>
            </DialogActions>
        </Dialog>
    );
};


================================================
FILE: ui/src/Video.tsx
================================================
import React from 'react';

export const Video = ({src, className}: {src: MediaStream; className?: string}) => {
    const [element, setElement] = React.useState<HTMLVideoElement | null>(null);

    React.useEffect(() => {
        if (element) {
            element.srcObject = src;
            element.play().catch((e) => console.log('Could not play preview video', e));
        }
    }, [element, src]);

    return <video muted ref={setElement} className={className} />;
};


================================================
FILE: ui/src/global.css
================================================
#root,
body,
html {
    height: 100%;
}

================================================
FILE: ui/src/index.tsx
================================================
import React from 'react';
import ReactDOM from 'react-dom/client';
import './global.css';
import {Button, createTheme, CssBaseline, ThemeProvider, StyledEngineProvider} from '@mui/material';
import {Router} from './Router';
import {SnackbarProvider} from 'notistack';

const theme = createTheme({
    components: {
        MuiSelect: {
            styleOverrides: {
                icon: {position: 'relative'},
            },
        },
        MuiLink: {
            styleOverrides: {
                root: {
                    color: '#458588',
                },
            },
        },
        MuiIconButton: {
            styleOverrides: {
                root: {
                    color: 'inherit',
                },
            },
        },
        MuiListItemIcon: {
            styleOverrides: {
                root: {
                    color: 'inherit',
                },
            },
        },
        MuiToolbar: {
            styleOverrides: {
                root: {
                    background: '#a89984',
                },
            },
        },
        MuiTooltip: {
            styleOverrides: {
                tooltip: {
                    fontSize: '1.6em',
                },
            },
        },
    },
    palette: {
        background: {
            default: '#282828',
            paper: '#32302f',
        },
        text: {
            primary: '#fbf1d4',
        },
        primary: {
            main: '#a89984',
        },
        secondary: {
            main: '#f44336',
        },
        mode: 'dark',
    },
});

const Snackbar: React.FC<React.PropsWithChildren> = ({children}) => {
    const notistackRef = React.createRef<any>();
    const onClickDismiss = (key: unknown) => () => {
        notistackRef.current?.closeSnackbar(key);
    };

    return (
        <SnackbarProvider
            maxSnack={3}
            ref={notistackRef}
            action={(key) => (
                <Button onClick={onClickDismiss(key)} size="small">
                    Dismiss
                </Button>
            )}
        >
            {children}
        </SnackbarProvider>
    );
};

ReactDOM.createRoot(document.getElementById('root')!!).render(
    <StyledEngineProvider injectFirst>
        <ThemeProvider theme={theme}>
            <Snackbar>
                <CssBaseline />
                <Router />
            </Snackbar>
        </ThemeProvider>
    </StyledEngineProvider>
);


================================================
FILE: ui/src/message.ts
================================================
export enum ShareMode {
    Everyone = 'Everyone',
    Selected = 'Selected',
}

type Typed<Base, Type extends string> = {type: Type; payload: Base};

export interface UIConfig {
    authMode: 'turn' | 'none' | 'all';
    user: string;
    loggedIn: boolean;
    version: string;
    roomName: string;
    closeRoomWhenOwnerLeaves: boolean;
}

export interface RoomConfiguration {
    id?: string;
    closeOnOwnerLeave?: boolean;
    mode: RoomMode;
    username?: string;
}

export enum RoomMode {
    Turn = 'turn',
    Stun = 'stun',
    Local = 'local',
}

export interface JoinConfiguration {
    id: string;
    password?: string;
    username?: string;
}

export interface StringMessage {
    message: string;
}

export interface P2PSession {
    id: string;
    peer: string;
    iceServers: ICEServer[];
}

export interface ICEServer {
    urls: string[];
    credential: string;
    username: string;
}

export interface RoomInfo {
    id: string;
    share: ShareMode;
    mode: RoomMode;
    users: RoomUser[];
}

export interface RoomUser {
    id: string;
    name: string;
    streaming: boolean;
    you: boolean;
    owner: boolean;
}

export interface P2PMessage<T> {
    sid: string;
    value: T;
}

export type Room = Typed<RoomInfo, 'room'>;
export type Error = Typed<StringMessage, 'Error'>;
export type HostSession = Typed<P2PSession, 'hostsession'>;
export type Name = Typed<{username: string}, 'name'>;
export type ClientSession = Typed<P2PSession, 'clientsession'>;
export type HostICECandidate = Typed<P2PMessage<RTCIceCandidate>, 'hostice'>;
export type ClientICECandidate = Typed<P2PMessage<RTCIceCandidate>, 'clientice'>;
export type HostOffer = Typed<P2PMessage<RTCSessionDescriptionInit>, 'hostoffer'>;
export type ClientAnswer = Typed<P2PMessage<RTCSessionDescriptionInit>, 'clientanswer'>;
export type StartSharing = Typed<{}, 'share'>;
export type StopShare = Typed<{}, 'stopshare'>;
export type RoomCreate = Typed<RoomConfiguration & {joinIfExist?: boolean}, 'create'>;
export type JoinRoom = Typed<JoinConfiguration, 'join'>;
export type EndShare = Typed<string, 'endshare'>;

export type IncomingMessage =
    | Room
    | Error
    | HostSession
    | ClientSession
    | HostICECandidate
    | ClientICECandidate
    | HostOffer
    | EndShare
    | ClientAnswer;

export type OutgoingMessage =
    | RoomCreate
    | Name
    | JoinRoom
    | HostICECandidate
    | ClientICECandidate
    | HostOffer
    | StopShare
    | ClientAnswer
    | StartSharing;


================================================
FILE: ui/src/settings.ts
================================================
import React from 'react';
export const CodecBestQuality: PreferredCodec = {mimeType: 'BEST_QUALITY'};
export const CodecDefault: PreferredCodec = {mimeType: 'DEFAULT'};

export const preferCodecEquals = (a: PreferredCodec, b: PreferredCodec): boolean => {
    return a.mimeType === b.mimeType && a.sdpFmtpLine === b.sdpFmtpLine;
};

export const codecName = (mimeType: string): string => {
    switch (mimeType) {
        case CodecBestQuality.mimeType:
            return 'Preset: Best Quality';
        case CodecDefault.mimeType:
            return 'Preset: Browser Default';
        default:
            return mimeType;
    }
};

export const resolveCodecPlaceholder = (
    codec: PreferredCodec | undefined
): PreferredCodec | undefined => {
    switch (codec?.mimeType) {
        case CodecBestQuality.mimeType:
            return {
                mimeType: 'video/VP9',
                sdpFmtpLine: 'profile-id=2',
            };
        case CodecDefault.mimeType:
            return undefined;
        default:
            return codec;
    }
};

export interface Settings {
    name?: string;
    displayMode: VideoDisplayMode;
    preferCodec?: PreferredCodec;
    framerate: number;
}
export interface PreferredCodec {
    mimeType: string;
    sdpFmtpLine?: string;
}

export enum VideoDisplayMode {
    FitToWindow = 'FitToWindow',
    FitWidth = 'FitWidth',
    FitHeight = 'FitHeight',
    OriginalSize = 'OriginalSize',
}

const SettingsKey = 'screegoSettings';

export const loadSettings = (): Settings => {
    const settings: Partial<Settings> = JSON.parse(localStorage.getItem(SettingsKey) ?? '{}') ?? {};

    const defaults: Settings = {
        displayMode: VideoDisplayMode.FitToWindow,
        framerate: 30,
    };

    if (settings && typeof settings === 'object') {
        return {
            name: settings.name?.toString(),
            framerate: settings.framerate ?? defaults.framerate,
            displayMode:
                Object.values(VideoDisplayMode).find((mode) => mode === settings.displayMode) ??
                defaults.displayMode,
            preferCodec: settings.preferCodec ?? CodecDefault,
        };
    }
    return defaults;
};

export const saveSettings = (settings: Settings): void => {
    localStorage.setItem(SettingsKey, JSON.stringify(settings));
};

export const useSettings = (): [Settings, (s: Settings) => void] => {
    const [settings, setSettings] = React.useState(loadSettings);

    return [
        settings,
        (newSettings) => {
            setSettings(newSettings);
            saveSettings(newSettings);
        },
    ];
};


================================================
FILE: ui/src/url.ts
================================================
const {port, hostname, protocol, pathname} = window.location;
const slashes = protocol.concat('//');
const path = pathname.endsWith('/') ? pathname : pathname.substring(0, pathname.lastIndexOf('/'));
const url = slashes.concat(port ? hostname.concat(':', port) : hostname) + path;
export const urlWithSlash = url.endsWith('/') ? url : url.concat('/');


================================================
FILE: ui/src/useConfig.ts
================================================
import {RoomMode, UIConfig} from './message';
import {useSnackbar} from 'notistack';
import React from 'react';
import {urlWithSlash} from './url';

export interface UseConfig extends UIConfig {
    login: (username: string, password: string) => Promise<void>;
    refetch: () => void;
    logout: () => Promise<void>;
    loading: boolean;
}

export const useConfig = (): UseConfig => {
    const {enqueueSnackbar} = useSnackbar();
    const [{loading, ...config}, setConfig] = React.useState<UIConfig & {loading: boolean}>({
        authMode: 'all',
        user: 'guest',
        loggedIn: false,
        loading: true,
        version: 'unknown',
        roomName: 'unknown',
        closeRoomWhenOwnerLeaves: true,
    });

    const refetch = React.useCallback(async () => {
        return fetch(`${urlWithSlash}config`)
            .then((data) => data.json())
            .then(setConfig);
    }, [setConfig]);

    const login = async (username: string, password: string) => {
        const body = new FormData();
        body.set('user', username);
        body.set('pass', password);
        const result = await fetch(`${urlWithSlash}login`, {method: 'POST', body});
        const json = await result.json();
        if (result.status !== 200) {
            enqueueSnackbar('Login Failed: ' + json.message, {variant: 'error'});
        } else {
            await refetch();
            enqueueSnackbar('Logged in!', {variant: 'success'});
        }
    };

    const logout = async () => {
        const result = await fetch(`${urlWithSlash}logout`, {method: 'POST'});
        if (result.status !== 200) {
            enqueueSnackbar('Logout Failed: ' + (await result.text()), {variant: 'error'});
        } else {
            await refetch();
            enqueueSnackbar('Logged Out.', {variant: 'success'});
        }
    };

    // eslint-disable-next-line react-hooks/exhaustive-deps
    React.useEffect(() => void refetch(), []);

    return {...config, refetch, loading, login, logout};
};

export const authModeToRoomMode = (authMode: UIConfig['authMode'], loggedIn: boolean): RoomMode => {
    if (loggedIn) {
        return RoomMode.Turn;
    }
    switch (authMode) {
        case 'all':
            return RoomMode.Turn;
        case 'turn':
            return RoomMode.Stun;
        case 'none':
        default:
            return RoomMode.Turn;
    }
};


================================================
FILE: ui/src/useRoom.ts
================================================
import {useSnackbar} from 'notistack';
import React from 'react';

import {
    ICEServer,
    IncomingMessage,
    JoinRoom,
    OutgoingMessage,
    RoomCreate,
    RoomInfo,
    UIConfig,
} from './message';
import {loadSettings, resolveCodecPlaceholder} from './settings';
import {urlWithSlash} from './url';
import {authModeToRoomMode} from './useConfig';
import {getFromURL, useRoomID} from './useRoomID';

export type RoomState = false | ConnectedRoom;
export type ConnectedRoom = {
    ws: WebSocket;
    hostStream?: MediaStream;
    clientStreams: ClientStream[];
} & RoomInfo;

interface ClientStream {
    id: string;
    peer_id: string;
    stream: MediaStream;
}

export interface UseRoom {
    state: RoomState;
    room: FCreateRoom;
    share: () => void;
    setName: (name: string) => void;
    stopShare: () => void;
}

const relayConfig: Partial<RTCConfiguration> =
    window.location.search.indexOf('forceTurn=true') !== -1 ? {iceTransportPolicy: 'relay'} : {};

const hostSession = async ({
    sid,
    ice,
    send,
    done,
    stream,
}: {
    sid: string;
    ice: ICEServer[];
    send: (e: OutgoingMessage) => void;
    done: () => void;
    stream: MediaStream;
}): Promise<RTCPeerConnection> => {
    const peer = new RTCPeerConnection({...relayConfig, iceServers: ice});
    peer.onicecandidate = (event) => {
        if (!event.candidate) {
            return;
        }
        send({type: 'hostice', payload: {sid: sid, value: event.candidate}});
    };

    peer.onconnectionstatechange = (event) => {
        console.log('host change', event);
        if (
            peer.connectionState === 'closed' ||
            peer.connectionState === 'disconnected' ||
            peer.connectionState === 'failed'
        ) {
            peer.close();
            done();
        }
    };

    stream.getTracks().forEach((track) => peer.addTrack(track, stream));

    const preferCodec = resolveCodecPlaceholder(loadSettings().preferCodec);
    if (preferCodec) {
        const transceiver = peer
            .getTransceivers()
            .find((t) => t.sender && t.sender.track === stream.getVideoTracks()[0]);

        if (!!transceiver && 'setCodecPreferences' in transceiver) {
            const exactMatch: RTCRtpCodec[] = [];
            const mimeMatch: RTCRtpCodec[] = [];
            const others: RTCRtpCodec[] = [];

            RTCRtpReceiver.getCapabilities('video')?.codecs.forEach((codec) => {
                if (codec.mimeType === preferCodec.mimeType) {
                    if (codec.sdpFmtpLine === preferCodec.sdpFmtpLine) {
                        exactMatch.push(codec);
                    } else {
                        mimeMatch.push(codec);
                    }
                } else {
                    others.push(codec);
                }
            });

            const sortedCodecs = [...exactMatch, ...mimeMatch, ...others];

            console.log('Setting codec preferences', sortedCodecs);
            transceiver.setCodecPreferences(sortedCodecs);
        }
    }

    const hostOffer = await peer.createOffer({offerToReceiveVideo: true});
    await peer.setLocalDescription(hostOffer);
    send({type: 'hostoffer', payload: {value: hostOffer, sid: sid}});

    return peer;
};

const clientSession = async ({
    sid,
    ice,
    send,
    done,
    onTrack,
}: {
    sid: string;
    ice: ICEServer[];
    send: (e: OutgoingMessage) => void;
    onTrack: (s: MediaStream) => void;
    done: () => void;
}): Promise<RTCPeerConnection> => {
    console.log('ice', ice);
    const peer = new RTCPeerConnection({...relayConfig, iceServers: ice});
    peer.onicecandidate = (event) => {
        if (!event.candidate) {
            return;
        }
        send({type: 'clientice', payload: {sid: sid, value: event.candidate}});
    };
    peer.onconnectionstatechange = (event) => {
        console.log('client change', event);
        if (
            peer.connectionState === 'closed' ||
            peer.connectionState === 'disconnected' ||
            peer.connectionState === 'failed'
        ) {
            peer.close();
            done();
        }
    };

    let notified = false;
    const stream = new MediaStream();
    peer.ontrack = (event) => {
        stream.addTrack(event.track);
        if (!notified) {
            notified = true;
            onTrack(stream);
        }
    };

    return peer;
};

export type FCreateRoom = (room: RoomCreate | JoinRoom) => Promise<void>;

export const useRoom = (config: UIConfig): UseRoom => {
    const [roomID, setRoomID] = useRoomID();
    const {enqueueSnackbar} = useSnackbar();
    const conn = React.useRef<WebSocket | undefined>(undefined);
    const host = React.useRef<Record<string, RTCPeerConnection>>({});
    const client = React.useRef<Record<string, RTCPeerConnection>>({});
    const stream = React.useRef<MediaStream>(undefined);

    const [state, setState] = React.useState<RoomState>(false);

    const room: FCreateRoom = React.useCallback(
        (create) => {
            return new Promise<void>((resolve) => {
                const ws = (conn.current = new WebSocket(
                    urlWithSlash.replace('http', 'ws') + 'stream'
                ));
                const send = (message: OutgoingMessage) => {
                    if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(message));
                };
                let first = true;
                ws.onmessage = (data) => {
                    const event: IncomingMessage = JSON.parse(data.data);
                    if (first) {
                        first = false;
                        if (event.type === 'room') {
                            resolve();
                            setState({ws, ...event.payload, clientStreams: []});
                            setRoomID(event.payload.id);
                        } else {
                            resolve();
                            enqueueSnackbar('Unknown Event: ' + event.type, {variant: 'error'});
                            ws.close(1000, 'received unknown event');
                        }
                        return;
                    }

                    switch (event.type) {
                        case 'room':
                            setState((current) =>
                                current ? {...current, ...event.payload} : current
                            );
                            return;
                        case 'hostsession':
                            if (!stream.current) {
                                return;
                            }
                            hostSession({
                                sid: event.payload.id,
                                stream: stream.current!,
                                ice: event.payload.iceServers,
                                send,
                                done: () => delete host.current[event.payload.id],
                            }).then((peer) => {
                                host.current[event.payload.id] = peer;
                            });
                            return;
                        case 'clientsession':
                            const {id: sid, peer} = event.payload;
                            clientSession({
                                sid,
                                send,
                                ice: event.payload.iceServers,
                                done: () => {
                                    delete client.current[sid];
                                    setState((current) =>
                                        current
                                            ? {
                                                  ...current,
                                                  clientStreams: current.clientStreams.filter(
                                                      ({id}) => id !== sid
                                                  ),
                                              }
                                            : current
                                    );
                                },
                                onTrack: (stream) =>
                                    setState((current) =>
                                        current
                                            ? {
                                                  ...current,
                                                  clientStreams: [
                                                      ...current.clientStreams,
                                                      {
                                                          id: sid,
                                                          stream,
                                                          peer_id: peer,
                                                      },
                                                  ],
                                              }
                                            : current
                                    ),
                            }).then((peer) => (client.current[event.payload.id] = peer));
                            return;
                        case 'clientice':
                            host.current[event.payload.sid]?.addIceCandidate(event.payload.value);
                            return;
                        case 'clientanswer':
                            host.current[event.payload.sid]?.setRemoteDescription(
                                event.payload.value
                            );
                            return;
                        case 'hostoffer':
                            (async () => {
                                await client.current[event.payload.sid]?.setRemoteDescription(
                                    event.payload.value
                                );
                                const answer =
                                    await client.current[event.payload.sid]?.createAnswer();
                                await client.current[event.payload.sid]?.setLocalDescription(
                                    answer
                                );
                                send({
                                    type: 'clientanswer',
                                    payload: {sid: event.payload.sid, value: answer},
                                });
                            })();
                            return;
                        case 'hostice':
                            client.current[event.payload.sid]?.addIceCandidate(event.payload.value);
                            return;
                        case 'endshare':
                            client.current[event.payload]?.close();
                            host.current[event.payload]?.close();
                            setState((current) =>
                                current
                                    ? {
                                          ...current,
                                          clientStreams: current.clientStreams.filter(
                                              ({id}) => id !== event.payload
                                          ),
                                      }
                                    : current
                            );
                    }
                };
                ws.onclose = (event) => {
                    if (first) {
                        resolve();
                        first = false;
                    }
                    enqueueSnackbar(event.reason, {variant: 'error', persist: true});
                    setState(false);
                };
                ws.onerror = (err) => {
                    if (first) {
                        resolve();
                        first = false;
                    }
                    enqueueSnackbar(err?.toString(), {variant: 'error', persist: true});
                    setState(false);
                };
                ws.onopen = () => {
                    create.payload.username = loadSettings().name;
                    send(create);
                };
            });
        },
        [setState, enqueueSnackbar, setRoomID]
    );

    const share = async () => {
        if (!navigator.mediaDevices) {
            enqueueSnackbar(
                'Could not start presentation. Are you using https? (mediaDevices undefined)',
                {variant: 'error', persist: true}
            );
            return;
        }
        if (typeof navigator.mediaDevices.getDisplayMedia !== 'function') {
            enqueueSnackbar(
                `Could not start presentation. Your browser likely doesn't support screensharing. (mediaDevices.getDeviceMedia ${typeof navigator.mediaDevices.getDisplayMedia})`,
                {variant: 'error', persist: true}
            );
            return;
        }
        try {
            stream.current = await navigator.mediaDevices.getDisplayMedia({
                video: {frameRate: loadSettings().framerate},
                audio: {
                    echoCancellation: false,
                    autoGainControl: false,
                    noiseSuppression: false,
                    // https://medium.com/@trystonperry/why-is-getdisplaymedias-audio-quality-so-bad-b49ba9cfaa83
                    // @ts-expect-error
                    googAutoGainControl: false,
                },
            });
        } catch (e) {
            console.log('Could not getDisplayMedia', e);
            enqueueSnackbar(`Could not start presentation. (getDisplayMedia error). ${e}`, {
                variant: 'error',
                persist: true,
            });
            return;
        }

        stream.current?.getVideoTracks()[0].addEventListener('ended', () => stopShare());
        setState((current) => (current ? {...current, hostStream: stream.current} : current));

        conn.current?.send(JSON.stringify({type: 'share', payload: {}}));
    };

    const stopShare = async () => {
        Object.values(host.current).forEach((peer) => {
            peer.close();
        });
        host.current = {};
        stream.current?.getTracks().forEach((track) => track.stop());
        stream.current = undefined;
        conn.current?.send(JSON.stringify({type: 'stopshare', payload: {}}));
        setState((current) => (current ? {...current, hostStream: undefined} : current));
    };

    const setName = (name: string): void => {
        conn.current?.send(JSON.stringify({type: 'name', payload: {username: name}}));
    };

    React.useEffect(() => {
        if (roomID) {
            const create = getFromURL('create') === 'true';
            if (create) {
                const closeOnOwnerLeaveString = getFromURL('closeOnOwnerLeave');
                const closeOnOwnerLeave =
                    closeOnOwnerLeaveString === undefined
                        ? config.closeRoomWhenOwnerLeaves
                        : closeOnOwnerLeaveString === 'true';
                room({
                    type: 'create',
                    payload: {
                        joinIfExist: true,
                        closeOnOwnerLeave,
                        id: roomID,
                        mode: authModeToRoomMode(config.authMode, config.loggedIn),
                    },
                });
            } else {
                room({type: 'join', payload: {id: roomID}});
            }
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    return {state, room, share, stopShare, setName};
};


================================================
FILE: ui/src/useRoomID.ts
================================================
import React from 'react';

export const getRoomFromURL = (): string | undefined => getFromURL('room');

export const getFromURL = (
    key: string,
    search: string = window.location.search
): string | undefined =>
    search
        .slice(1)
        .split('&')
        .find((param) => param.startsWith(`${key}=`))
        ?.split('=')[1];

export const useRoomID = (): [string | undefined, (v?: string) => void] => {
    const [state, setState] = React.useState<string | undefined>(() => getRoomFromURL());
    React.useEffect(() => {
        const onChange = (): void => setState(getRoomFromURL());
        window.addEventListener('popstate', onChange);
        return () => window.removeEventListener('popstate', onChange);
    }, [setState]);
    return [
        state,
        React.useCallback(
            (id) =>
                setState((oldId?: string) => {
                    if (oldId !== id) {
                        window.history.pushState({roomId: id}, '', id ? `?room=${id}` : '?');
                    }
                    return id;
                }),
            [setState]
        ),
    ];
};


================================================
FILE: ui/src/vite-env.d.ts
================================================
/// <reference types="vite/client" />


================================================
FILE: ui/tsconfig.json
================================================
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,

    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",

    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}



================================================
FILE: ui/tsconfig.node.json
================================================
{
  "compilerOptions": {
    "composite": true,
    "skipLibCheck": true,
    "module": "ESNext",
    "moduleResolution": "bundler",
    "allowSyntheticDefaultImports": true
  },
  "include": ["vite.config.ts"]
}


================================================
FILE: ui/vite.config.mts
================================================
import {defineConfig} from 'vite';
import react from '@vitejs/plugin-react-swc';

export default defineConfig({
    base: './',
    server: {
        host: '127.0.0.1',
        port: 3000,
        open: false,
        proxy: {
            '^/(config|logout|login|stream)$': {
                target: 'http://localhost:5050',
                ws: true,
            },
        },
    },
    build: {outDir: 'build/'},
    plugins: [react()],
});


================================================
FILE: users
================================================
# Password: admin
admin:$2a$12$kNgc2ZYAXzIL6SHY.8PHAOQ8Casi0s1bKatYoG/jupt2yV1M5K5nO


================================================
FILE: util/password.go
================================================
package util

import (
	"crypto/rand"
	"math/big"
)

func RandString(length int) string {
	res := make([]byte, length)
	for i := range res {
		index := randIntn(len(tokenCharacters))
		res[i] = tokenCharacters[index]
	}
	return string(res)
}

var (
	tokenCharacters = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_!@#$%^&*()){}\\/=+,.><")
	randReader      = rand.Reader
)

func randIntn(n int) int {
	max := big.NewInt(int64(n))
	res, err := rand.Int(randReader, max)
	if err != nil {
		panic("random source is not available")
	}
	return int(res.Int64())
}


================================================
FILE: util/sillyname.go
================================================
package util

import (
	"math/rand"

	"golang.org/x/text/cases"
	"golang.org/x/text/language"
)

var adjectives = []string{
	"able", "adaptive", "adventurous", "affable", "agreeable", "ambitious",
	"amiable", "amusing", "balanced", "brave", "bright", "calm", "capable",
	"charming", "clever", "compassionate", "considerate", "courageous",
	"creative", "decisive", "determined", "discreet", "dynamic",
	"enthusiastic", "exuberant", "faithful", "fearless", "friendly", "funny",
	"generous", "gentle", "good", "honest", "humorous", "independent",
	"intelligent", "intuitive", "kind", "loving", "loyal", "modest", "nice",
	"optimistic", "patient", "pioneering", "polite", "powerful", "reliable",
	"resourceful", "sensible", "sincere", "thoughtful", "tough", "versatile",
}

var animals = []string{
	"dog", "puppy", "turtle", "rabbit", "parrot", "cat", "kitten", "goldfish",
	"mouse", "hamster", "fish", "cow", "rabbit", "duck", "shrimp", "pig",
	"goat", "crab", "deer", "bee", "sheep", "fish", "turkey", "dove",
	"chicken", "horse", "squirrel", "dog", "chimpanzee", "ox", "lion", "panda",
	"walrus", "otter", "mouse", "kangaroo", "goat", "horse", "monkey", "cow",
	"koala", "mole", "elephant", "leopard", "hippopotamus", "giraffe", "fox",
	"coyote", "hedgehong", "sheep", "deer",
}

var colors = []string{
	"amaranth", "amber", "amethyst", "apricot", "aqua", "aquamarine", "azure",
	"beige", "black", "blue", "blush", "bronze", "brown", "chocolate",
	"coffee", "copper", "coral", "crimson", "cyan", "emerald", "fuchsia",
	"gold", "gray", "green", "harlequin", "indigo", "ivory", "jade",
	"lavender", "lime", "magenta", "maroon", "moccasin", "olive", "orange",
	"peach", "pink", "plum", "purple", "red", "rose", "salmon", "sapphire",
	"scarlet", "silver", "tan", "teal", "tomato", "turquoise", "violet",
	"white", "yellow",
}

func r(r *rand.Rand, l []string) string {
	return l[r.Intn(len(l)-1)]
}

func NewUserName(s *rand.Rand) string {
	title := cases.Title(language.English)
	return title.String(r(s, adjectives)) + " " + title.String(r(s, animals))
}

func NewRoomName(s *rand.Rand) string {
	return r(s, adjectives) + "-" + r(s, colors) + "-" + r(s, animals)
}


================================================
FILE: ws/client.go
================================================
package ws

import (
	"fmt"
	"net"
	"net/http"
	"strings"
	"time"

	"github.com/gorilla/websocket"
	"github.com/rs/xid"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	"github.com/screego/server/ws/outgoing"
)

var ping = func(conn *websocket.Conn) error {
	return conn.WriteMessage(websocket.PingMessage, nil)
}

var writeJSON = func(conn *websocket.Conn, v interface{}) error {
	return conn.WriteJSON(v)
}

const (
	writeWait = 2 * time.Second
)

type Client struct {
	conn *websocket.Conn
	info ClientInfo
	once once
	read chan<- ClientMessage
}

type ClientMessage struct {
	Info               ClientInfo
	SkipConnectedCheck bool
	Incoming           Event
}

type ClientInfo struct {
	ID                xid.ID
	Authenticated     bool
	AuthenticatedUser string
	Write             chan outgoing.Message
	Addr              net.IP
}

func newClient(conn *websocket.Conn, req *http.Request, read chan ClientMessage, authenticatedUser string, authenticated, trustProxy bool) *Client {
	ip := conn.RemoteAddr().(*net.TCPAddr).IP
	if realIP := req.Header.Get("X-Real-IP"); trustProxy && realIP != "" {
		ip = net.ParseIP(realIP)
	}

	client := &Client{
		conn: conn,
		info: ClientInfo{
			Authenticated:     authenticated,
			AuthenticatedUser: authenticatedUser,
			ID:                xid.New(),
			Addr:              ip,
			Write:             make(chan outgoing.Message, 1),
		},
		read: read,
	}
	client.debug().Msg("WebSocket New Connection")
	return client
}

// CloseOnError closes the connection.
func (c *Client) CloseOnError(code int, reason string) {
	c.once.Do(func() {
		go func() {
			c.read <- ClientMessage{
				Info: c.info,
				Incoming: &Disconnected{
					Code:   code,
					Reason: reason,
				},
			}
		}()
		c.writeCloseMessage(code, reason)
	})
}

func (c *Client) CloseOnDone(code int, reason string) {
	c.once.Do(func() {
		c.writeCloseMessage(code, reason)
	})
}

func (c *Client) writeCloseMessage(code int, reason string) {
	message := websocket.FormatCloseMessage(code, reason)
	_ = c.conn.WriteControl(websocket.CloseMessage, message, time.Now().Add(writeWait))
	c.conn.Close()
}

// startWriteHandler starts listening on the client connection. As we do not need anything from the client,
// we ignore incoming messages. Leaves the loop on errors.
func (c *Client) startReading(pongWait time.Duration) {
	defer c.CloseOnError(websocket.CloseNormalClosure, "Reader Routine Closed")

	_ = c.conn.SetReadDeadline(time.Now().Add(pongWait))
	c.conn.SetPongHandler(func(appData string) error {
		_ = c.conn.SetReadDeadline(time.Now().Add(pongWait))
		return nil
	})
	for {
		t, m, err := c.conn.NextReader()
		if err != nil {
			c.CloseOnError(websocket.CloseNormalClosure, "read error: "+err.Error())
			return
		}
		if t == websocket.BinaryMessage {
			c.CloseOnError(websocket.CloseUnsupportedData, "unsupported binary message type")
			return
		}

		incoming, err := ReadTypedIncoming(m)
		if err != nil {
			c.CloseOnError(websocket.CloseUnsupportedData, fmt.Sprintf("malformed message: %s", err))
			return
		}
		c.debug().Interface("event", fmt.Sprintf("%T", incoming)).Interface("payload", incoming).Msg("WebSocket Receive")
		c.read <- ClientMessage{Info: c.info, Incoming: incoming}
	}
}

// startWriteHandler starts the write loop. The method has the following tasks:
// * ping the client in the interval provided as parameter
// * write messages send by the channel to the client
// * on errors exit the loop.
func (c *Client) startWriteHandler(pingPeriod time.Duration) {
	pingTicker := time.NewTicker(pingPeriod)
	defer pingTicker.Stop()
	defer func() {
		c.debug().Msg("WebSocket Done")
	}()
	defer c.conn.Close()
	for {
		select {
		case message := <-c.info.Write:
			if msg, ok := message.(outgoing.CloseWriter); ok {
				c.debug().Str("reason", msg.Reason).Int("code", msg.Code).Msg("WebSocket Close")
				c.CloseOnDone(msg.Code, msg.Reason)
				return
			}

			_ = c.conn.SetWriteDeadline(time.Now().Add(writeWait))
			typed, err := ToTypedOutgoing(message)
			c.debug().Interface("event", typed.Type).Interface("payload", typed.Payload).Msg("WebSocket Send")
			if err != nil {
				c.debug().Err(err).Msg("could not get typed message, exiting connection.")
				c.CloseOnError(websocket.CloseNormalClosure, "malformed outgoing "+err.Error())
				continue
			}

			if err := writeJSON(c.conn, typed); err != nil {
				c.printWebSocketError("write", err)
				c.CloseOnError(websocket.CloseNormalClosure, "write error"+err.Error())
			}
		case <-pingTicker.C:
			_ = c.conn.SetWriteDeadline(time.Now().Add(writeWait))
			if err := ping(c.conn);
Download .txt
gitextract_5ezl1r5_/

├── .github/
│   ├── FUNDING.yml
│   └── workflows/
│       └── build.yml
├── .gitignore
├── .golangci.yml
├── .goreleaser.yml
├── Dockerfile
├── LICENSE
├── README.md
├── auth/
│   └── auth.go
├── cmd/
│   ├── command.go
│   ├── hash.go
│   └── serve.go
├── config/
│   ├── config.go
│   ├── error.go
│   ├── ip.go
│   ├── ipdns/
│   │   ├── dns.go
│   │   ├── provider.go
│   │   └── static.go
│   ├── loglevel.go
│   ├── loglevel_test.go
│   └── mode/
│       ├── mode.go
│       └── mode_test.go
├── docs/
│   ├── .nojekyll
│   ├── CNAME
│   ├── README.md
│   ├── _sidebar.md
│   ├── config.md
│   ├── development.md
│   ├── faq.md
│   ├── index.html
│   ├── install.md
│   ├── nat-traversal.md
│   └── proxy.md
├── go.mod
├── go.sum
├── logger/
│   └── logger.go
├── main.go
├── router/
│   └── router.go
├── screego.config.development
├── screego.config.example
├── server/
│   ├── server.go
│   └── server_test.go
├── turn/
│   ├── none.go
│   ├── portrange.go
│   └── server.go
├── ui/
│   ├── .gitignore
│   ├── .prettierrc
│   ├── index.html
│   ├── package.json
│   ├── serve.go
│   ├── src/
│   │   ├── LoginForm.tsx
│   │   ├── NumberField.tsx
│   │   ├── Room.tsx
│   │   ├── RoomManage.tsx
│   │   ├── Router.tsx
│   │   ├── SettingDialog.tsx
│   │   ├── Video.tsx
│   │   ├── global.css
│   │   ├── index.tsx
│   │   ├── message.ts
│   │   ├── settings.ts
│   │   ├── url.ts
│   │   ├── useConfig.ts
│   │   ├── useRoom.ts
│   │   ├── useRoomID.ts
│   │   └── vite-env.d.ts
│   ├── tsconfig.json
│   ├── tsconfig.node.json
│   └── vite.config.mts
├── users
├── util/
│   ├── password.go
│   └── sillyname.go
└── ws/
    ├── client.go
    ├── event.go
    ├── event_clientanswer.go
    ├── event_clientice.go
    ├── event_connected.go
    ├── event_create.go
    ├── event_disconnected.go
    ├── event_health.go
    ├── event_hostice.go
    ├── event_hostoffer.go
    ├── event_join.go
    ├── event_name.go
    ├── event_share.go
    ├── event_stop_share.go
    ├── once.go
    ├── once_test.go
    ├── outgoing/
    │   └── messages.go
    ├── prometheus.go
    ├── readwrite.go
    ├── room.go
    ├── rooms.go
    └── rooms_test.go
Download .txt
SYMBOL INDEX (244 symbols across 52 files)

FILE: auth/auth.go
  type Users (line 16) | type Users struct
    method CurrentUser (line 80) | func (u *Users) CurrentUser(r *http.Request) (string, bool) {
    method Logout (line 89) | func (u *Users) Logout(w http.ResponseWriter, r *http.Request) {
    method Authenticate (line 102) | func (u *Users) Authenticate(w http.ResponseWriter, r *http.Request) {
    method Validate (line 131) | func (u Users) Validate(user, password string) bool {
  type UserPW (line 22) | type UserPW struct
  function read (line 27) | func read(r io.Reader) ([]UserPW, error) {
  function ReadPasswordsFile (line 48) | func ReadPasswordsFile(path string, secret []byte, sessionTimeout int) (...
  type Response (line 76) | type Response struct

FILE: cmd/command.go
  function Run (line 11) | func Run(version, commitHash string) {

FILE: cmd/serve.go
  function serveCmd (line 18) | func serveCmd(version string) cli.Command {

FILE: config/config.go
  constant AuthModeTurn (line 30) | AuthModeTurn = "turn"
  constant AuthModeAll (line 31) | AuthModeAll  = "all"
  constant AuthModeNone (line 32) | AuthModeNone = "none"
  type Config (line 36) | type Config struct
    method parsePortRange (line 73) | func (c Config) parsePortRange() (uint16, uint16, error) {
    method PortRange (line 96) | func (c Config) PortRange() (uint16, uint16, bool) {
  function Get (line 102) | func Get() (Config, []FutureLog) {
  function logDeprecated (line 244) | func logDeprecated() []FutureLog {
  function getExecutableOrWorkDir (line 251) | func getExecutableOrWorkDir() (string, *FutureLog) {
  function getExecutableDir (line 261) | func getExecutableDir() (string, *FutureLog) {
  function getFiles (line 272) | func getFiles(relativeTo string) []string {

FILE: config/error.go
  type FutureLog (line 7) | type FutureLog struct
  function futureFatal (line 12) | func futureFatal(msg string) FutureLog {

FILE: config/ip.go
  function parseIPProvider (line 13) | func parseIPProvider(ips []string, config string) (ipdns.Provider, []Fut...
  function parseStatic (line 30) | func parseStatic(ips []string, config string) (*ipdns.Static, []FutureLo...
  function applyIPTo (line 58) | func applyIPTo(config, ip string, static *ipdns.Static) (bool, []FutureL...
  function parseDNS (line 73) | func parseDNS(dnsString string) *ipdns.DNS {

FILE: config/ipdns/dns.go
  type DNS (line 14) | type DNS struct
    method Get (line 27) | func (s *DNS) Get() (net.IP, net.IP, error) {
    method lookup (line 53) | func (s *DNS) lookup() (net.IP, net.IP, error) {

FILE: config/ipdns/provider.go
  type Provider (line 5) | type Provider interface

FILE: config/ipdns/static.go
  type Static (line 5) | type Static struct
    method Get (line 10) | func (s *Static) Get() (net.IP, net.IP, error) {

FILE: config/loglevel.go
  type LogLevel (line 10) | type LogLevel
    method Decode (line 13) | func (ll *LogLevel) Decode(value string) error {
    method AsZeroLogLevel (line 23) | func (ll LogLevel) AsZeroLogLevel() zerolog.Level {

FILE: config/loglevel_test.go
  function TestLogLevel_Decode_success (line 10) | func TestLogLevel_Decode_success(t *testing.T) {
  function TestLogLevel_Decode_fail (line 17) | func TestLogLevel_Decode_fail(t *testing.T) {

FILE: config/mode/mode.go
  constant Dev (line 5) | Dev = "dev"
  constant Prod (line 7) | Prod = "prod"
  function Set (line 13) | func Set(newMode string) {
  function Get (line 18) | func Get() string {

FILE: config/mode/mode_test.go
  function TestGet (line 9) | func TestGet(t *testing.T) {
  function TestSet (line 14) | func TestSet(t *testing.T) {

FILE: logger/logger.go
  function Init (line 12) | func Init(lvl zerolog.Level) {

FILE: main.go
  function main (line 14) | func main() {

FILE: router/router.go
  type Health (line 19) | type Health struct
  type UIConfig (line 25) | type UIConfig struct
  function Router (line 34) | func Router(conf config.Config, rooms *ws.Rooms, users *auth.Users, vers...
  function accessLogger (line 79) | func accessLogger(r *http.Request, status, size int, dur time.Duration) {
  function basicAuth (line 90) | func basicAuth(handler http.Handler, users *auth.Users) http.HandlerFunc {

FILE: server/server.go
  function Start (line 24) | func Start(mux *mux.Router, address, cert, key string) error {
  function startServer (line 30) | func startServer(mux *mux.Router, address, cert, key string) (*http.Serv...
  function listenAndServe (line 44) | func listenAndServe(srv *http.Server, address, cert, key string) error {
  function shutdownOnInterruptSignal (line 66) | func shutdownOnInterruptSignal(server *http.Server, timeout time.Duratio...
  function waitForServerToClose (line 81) | func waitForServerToClose(shutdown <-chan error) error {

FILE: server/server_test.go
  function TestShutdownOnErrorWhileShutdown (line 17) | func TestShutdownOnErrorWhileShutdown(t *testing.T) {
  function TestShutdownAfterError (line 39) | func TestShutdownAfterError(t *testing.T) {
  function TestShutdown (line 54) | func TestShutdown(t *testing.T) {
  function fakeInterrupt (line 72) | func fakeInterrupt(t *testing.T) func() {
  function fakeShutdownError (line 86) | func fakeShutdownError(err error) func() {
  function port (line 96) | func port() int {

FILE: turn/none.go
  type RelayAddressGeneratorNone (line 9) | type RelayAddressGeneratorNone struct
    method Validate (line 11) | func (r *RelayAddressGeneratorNone) Validate() error {
    method AllocatePacketConn (line 15) | func (r *RelayAddressGeneratorNone) AllocatePacketConn(network string,...
    method AllocateConn (line 24) | func (r *RelayAddressGeneratorNone) AllocateConn(network string, reque...

FILE: turn/portrange.go
  type RelayAddressGeneratorPortRange (line 11) | type RelayAddressGeneratorPortRange struct
    method Validate (line 17) | func (r *RelayAddressGeneratorPortRange) Validate() error {
    method AllocatePacketConn (line 25) | func (r *RelayAddressGeneratorPortRange) AllocatePacketConn(network st...
    method AllocateConn (line 49) | func (r *RelayAddressGeneratorPortRange) AllocateConn(network string, ...

FILE: turn/server.go
  type Server (line 19) | type Server interface
  type InternalServer (line 24) | type InternalServer struct
    method allow (line 138) | func (a *InternalServer) allow(username, password string, addr net.IP) {
    method Disallow (line 147) | func (a *InternalServer) Disallow(username string) {
    method authenticate (line 158) | func (a *InternalServer) authenticate(username, realm string, addr net...
    method Credentials (line 173) | func (a *InternalServer) Credentials(id string, addr net.IP) (string, ...
  type ExternalServer (line 29) | type ExternalServer struct
    method Disallow (line 154) | func (a *ExternalServer) Disallow(username string) {
    method Credentials (line 179) | func (a *ExternalServer) Credentials(id string, addr net.IP) (string, ...
  type Entry (line 34) | type Entry struct
  constant Realm (line 39) | Realm = "screego"
  type Generator (line 41) | type Generator struct
    method AllocatePacketConn (line 46) | func (r *Generator) AllocatePacketConn(network string, requestedPort i...
  function Start (line 69) | func Start(conf config.Config) (Server, error) {
  function newExternalServer (line 77) | func newExternalServer(conf config.Config) (Server, error) {
  function newInternalServer (line 84) | func newInternalServer(conf config.Config) (Server, error) {
  function generator (line 129) | func generator(conf config.Config) turn.RelayAddressGenerator {

FILE: ui/serve.go
  function Register (line 18) | func Register(r *mux.Router) {
  function serveFile (line 29) | func serveFile(name, contentType string) http.HandlerFunc {

FILE: ui/src/NumberField.tsx
  type NumberFieldProps (line 4) | interface NumberFieldProps {

FILE: ui/src/Room.tsx
  type FullScreenHTMLVideoElement (line 38) | interface FullScreenHTMLVideoElement extends HTMLVideoElement {

FILE: ui/src/SettingDialog.tsx
  type SettingDialogProps (line 23) | interface SettingDialogProps {

FILE: ui/src/message.ts
  type ShareMode (line 1) | enum ShareMode {
  type Typed (line 6) | type Typed<Base, Type extends string> = {type: Type; payload: Base};
  type UIConfig (line 8) | interface UIConfig {
  type RoomConfiguration (line 17) | interface RoomConfiguration {
  type RoomMode (line 24) | enum RoomMode {
  type JoinConfiguration (line 30) | interface JoinConfiguration {
  type StringMessage (line 36) | interface StringMessage {
  type P2PSession (line 40) | interface P2PSession {
  type ICEServer (line 46) | interface ICEServer {
  type RoomInfo (line 52) | interface RoomInfo {
  type RoomUser (line 59) | interface RoomUser {
  type P2PMessage (line 67) | interface P2PMessage<T> {
  type Room (line 72) | type Room = Typed<RoomInfo, 'room'>;
  type Error (line 73) | type Error = Typed<StringMessage, 'Error'>;
  type HostSession (line 74) | type HostSession = Typed<P2PSession, 'hostsession'>;
  type Name (line 75) | type Name = Typed<{username: string}, 'name'>;
  type ClientSession (line 76) | type ClientSession = Typed<P2PSession, 'clientsession'>;
  type HostICECandidate (line 77) | type HostICECandidate = Typed<P2PMessage<RTCIceCandidate>, 'hostice'>;
  type ClientICECandidate (line 78) | type ClientICECandidate = Typed<P2PMessage<RTCIceCandidate>, 'clientice'>;
  type HostOffer (line 79) | type HostOffer = Typed<P2PMessage<RTCSessionDescriptionInit>, 'hostoffer'>;
  type ClientAnswer (line 80) | type ClientAnswer = Typed<P2PMessage<RTCSessionDescriptionInit>, 'client...
  type StartSharing (line 81) | type StartSharing = Typed<{}, 'share'>;
  type StopShare (line 82) | type StopShare = Typed<{}, 'stopshare'>;
  type RoomCreate (line 83) | type RoomCreate = Typed<RoomConfiguration & {joinIfExist?: boolean}, 'cr...
  type JoinRoom (line 84) | type JoinRoom = Typed<JoinConfiguration, 'join'>;
  type EndShare (line 85) | type EndShare = Typed<string, 'endshare'>;
  type IncomingMessage (line 87) | type IncomingMessage =
  type OutgoingMessage (line 98) | type OutgoingMessage =

FILE: ui/src/settings.ts
  type Settings (line 36) | interface Settings {
  type PreferredCodec (line 42) | interface PreferredCodec {
  type VideoDisplayMode (line 47) | enum VideoDisplayMode {

FILE: ui/src/useConfig.ts
  type UseConfig (line 6) | interface UseConfig extends UIConfig {

FILE: ui/src/useRoom.ts
  type RoomState (line 18) | type RoomState = false | ConnectedRoom;
  type ConnectedRoom (line 19) | type ConnectedRoom = {
  type ClientStream (line 25) | interface ClientStream {
  type UseRoom (line 31) | interface UseRoom {
  type FCreateRoom (line 160) | type FCreateRoom = (room: RoomCreate | JoinRoom) => Promise<void>;

FILE: util/password.go
  function RandString (line 8) | func RandString(length int) string {
  function randIntn (line 22) | func randIntn(n int) int {

FILE: util/sillyname.go
  function r (line 43) | func r(r *rand.Rand, l []string) string {
  function NewUserName (line 47) | func NewUserName(s *rand.Rand) string {
  function NewRoomName (line 52) | func NewRoomName(s *rand.Rand) string {

FILE: ws/client.go
  constant writeWait (line 26) | writeWait = 2 * time.Second
  type Client (line 29) | type Client struct
    method CloseOnError (line 72) | func (c *Client) CloseOnError(code int, reason string) {
    method CloseOnDone (line 87) | func (c *Client) CloseOnDone(code int, reason string) {
    method writeCloseMessage (line 93) | func (c *Client) writeCloseMessage(code int, reason string) {
    method startReading (line 101) | func (c *Client) startReading(pongWait time.Duration) {
    method startWriteHandler (line 134) | func (c *Client) startWriteHandler(pingPeriod time.Duration) {
    method debug (line 173) | func (c *Client) debug() *zerolog.Event {
    method printWebSocketError (line 177) | func (c *Client) printWebSocketError(typex string, err error) {
  type ClientMessage (line 36) | type ClientMessage struct
  type ClientInfo (line 42) | type ClientInfo struct
  function newClient (line 50) | func newClient(conn *websocket.Conn, req *http.Request, read chan Client...

FILE: ws/event.go
  type Event (line 3) | type Event interface

FILE: ws/event_clientanswer.go
  function init (line 10) | func init() {
  type ClientAnswer (line 16) | type ClientAnswer
    method Execute (line 18) | func (e *ClientAnswer) Execute(rooms *Rooms, current ClientInfo) error {

FILE: ws/event_clientice.go
  function init (line 10) | func init() {
  type ClientICE (line 16) | type ClientICE
    method Execute (line 18) | func (e *ClientICE) Execute(rooms *Rooms, current ClientInfo) error {

FILE: ws/event_connected.go
  type Connected (line 3) | type Connected struct
    method Execute (line 5) | func (e Connected) Execute(rooms *Rooms, current ClientInfo) error {

FILE: ws/event_create.go
  function init (line 11) | func init() {
  type Create (line 17) | type Create struct
    method Execute (line 25) | func (e *Create) Execute(rooms *Rooms, current ClientInfo) error {

FILE: ws/event_disconnected.go
  type Disconnected (line 10) | type Disconnected struct
    method Execute (line 15) | func (e *Disconnected) Execute(rooms *Rooms, current ClientInfo) error {
    method executeNoError (line 20) | func (e *Disconnected) executeNoError(rooms *Rooms, current ClientInfo) {

FILE: ws/event_health.go
  type Health (line 3) | type Health struct
    method Execute (line 7) | func (e *Health) Execute(rooms *Rooms, current ClientInfo) error {

FILE: ws/event_hostice.go
  function init (line 10) | func init() {
  type HostICE (line 16) | type HostICE
    method Execute (line 18) | func (e *HostICE) Execute(rooms *Rooms, current ClientInfo) error {

FILE: ws/event_hostoffer.go
  function init (line 10) | func init() {
  type HostOffer (line 16) | type HostOffer
    method Execute (line 18) | func (e *HostOffer) Execute(rooms *Rooms, current ClientInfo) error {

FILE: ws/event_join.go
  function init (line 7) | func init() {
  type Join (line 13) | type Join struct
    method Execute (line 18) | func (e *Join) Execute(rooms *Rooms, current ClientInfo) error {

FILE: ws/event_name.go
  function init (line 3) | func init() {
  type Name (line 9) | type Name struct
    method Execute (line 13) | func (e *Name) Execute(rooms *Rooms, current ClientInfo) error {

FILE: ws/event_share.go
  function init (line 3) | func init() {
  type StartShare (line 9) | type StartShare struct
    method Execute (line 11) | func (e *StartShare) Execute(rooms *Rooms, current ClientInfo) error {

FILE: ws/event_stop_share.go
  function init (line 9) | func init() {
  type StopShare (line 15) | type StopShare struct
    method Execute (line 17) | func (e *StopShare) Execute(rooms *Rooms, current ClientInfo) error {

FILE: ws/once.go
  type once (line 14) | type once struct
    method Do (line 19) | func (o *once) Do(f func()) {
    method mayExecute (line 28) | func (o *once) mayExecute() bool {

FILE: ws/once_test.go
  function Test_Execute (line 10) | func Test_Execute(t *testing.T) {

FILE: ws/outgoing/messages.go
  type Message (line 9) | type Message interface
  type Room (line 13) | type Room struct
    method Type (line 27) | func (Room) Type() string {
  type User (line 19) | type User struct
  type HostSession (line 31) | type HostSession struct
    method Type (line 37) | func (HostSession) Type() string {
  type ClientSession (line 41) | type ClientSession struct
    method Type (line 47) | func (ClientSession) Type() string {
  type ICEServer (line 51) | type ICEServer struct
  type P2PMessage (line 57) | type P2PMessage struct
  type HostICE (line 62) | type HostICE
    method Type (line 64) | func (HostICE) Type() string {
  type ClientICE (line 68) | type ClientICE
    method Type (line 70) | func (ClientICE) Type() string {
  type ClientAnswer (line 74) | type ClientAnswer
    method Type (line 76) | func (ClientAnswer) Type() string {
  type HostOffer (line 80) | type HostOffer
    method Type (line 82) | func (HostOffer) Type() string {
  type EndShare (line 86) | type EndShare
    method Type (line 88) | func (EndShare) Type() string {
  type ConnectionMode (line 92) | type ConnectionMode
  constant ConnectionLocal (line 95) | ConnectionLocal ConnectionMode = "local"
  constant ConnectionSTUN (line 96) | ConnectionSTUN  ConnectionMode = "stun"
  constant ConnectionTURN (line 97) | ConnectionTURN  ConnectionMode = "turn"
  type CloseWriter (line 100) | type CloseWriter struct
    method Type (line 105) | func (CloseWriter) Type() string {

FILE: ws/readwrite.go
  type Typed (line 12) | type Typed struct
  function ToTypedOutgoing (line 17) | func ToTypedOutgoing(outgoing outgoing.Message) (Typed, error) {
  function ReadTypedIncoming (line 28) | func ReadTypedIncoming(r io.Reader) (Event, error) {
  function register (line 50) | func register(t string, incoming func() Event) {

FILE: ws/room.go
  type ConnectionMode (line 15) | type ConnectionMode
  constant ConnectionLocal (line 18) | ConnectionLocal ConnectionMode = "local"
  constant ConnectionSTUN (line 19) | ConnectionSTUN  ConnectionMode = "stun"
  constant ConnectionTURN (line 20) | ConnectionTURN  ConnectionMode = config.AuthModeTurn
  type Room (line 23) | type Room struct
    method newSession (line 36) | func (r *Room) newSession(host, client xid.ID, rooms *Rooms, v4, v6 ne...
    method closeSession (line 85) | func (r *Room) closeSession(rooms *Rooms, id xid.ID) {
    method notifyInfoChanged (line 99) | func (r *Room) notifyInfoChanged() {
  constant CloseOwnerLeft (line 32) | CloseOwnerLeft = "Owner Left"
  constant CloseDone (line 33) | CloseDone      = "Read End"
  method addresses (line 69) | func (r *Rooms) addresses(prefix string, v4, v6 net.IP, tcp bool) (resul...
  type RoomSession (line 94) | type RoomSession struct
  type User (line 134) | type User struct
    method WriteTimeout (line 143) | func (u *User) WriteTimeout(msg outgoing.Message) {
  function writeTimeout (line 147) | func writeTimeout[T any](ch chan<- T, msg T) {

FILE: ws/rooms.go
  function NewRooms (line 19) | func NewRooms(tServer turn.Server, users *auth.Users, conf config.Config...
  type Rooms (line 46) | type Rooms struct
    method CurrentRoom (line 57) | func (r *Rooms) CurrentRoom(info ClientInfo) (*Room, error) {
    method RandUserName (line 73) | func (r *Rooms) RandUserName() string {
    method RandRoomName (line 77) | func (r *Rooms) RandRoomName() string {
    method Upgrade (line 81) | func (r *Rooms) Upgrade(w http.ResponseWriter, req *http.Request) {
    method Start (line 98) | func (r *Rooms) Start() {
    method Count (line 113) | func (r *Rooms) Count() (int, string) {
    method closeRoom (line 130) | func (r *Rooms) closeRoom(roomID string) {

FILE: ws/rooms_test.go
  constant SERVER (line 15) | SERVER = "ws://localhost:5050/stream"
  function TestMultipleClients (line 17) | func TestMultipleClients(t *testing.T) {
  function testClient (line 43) | func testClient(i int64, room string) {
  function msg (line 71) | func msg(r *rand.Rand, room string) []byte {
Condensed preview — 94 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (232K chars).
[
  {
    "path": ".github/FUNDING.yml",
    "chars": 599,
    "preview": "# These are supported funding model platforms\n\ngithub: jmattheis\npatreon: # Replace with a single Patreon username\nopen_"
  },
  {
    "path": ".github/workflows/build.yml",
    "chars": 1420,
    "preview": "name: build\non: [push, pull_request]\n\njobs:\n  screego:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/setup"
  },
  {
    "path": ".gitignore",
    "chars": 41,
    "preview": "/target\n/.idea\n*-packr.go\n/dist/\n*.local\n"
  },
  {
    "path": ".golangci.yml",
    "chars": 49,
    "preview": "version: \"2\"\nlinters:\n  disable:\n    - errcheck\n\n"
  },
  {
    "path": ".goreleaser.yml",
    "chars": 7546,
    "preview": "# This is an example goreleaser.yaml file with some sane defaults.\n# Make sure to check the documentation at http://gore"
  },
  {
    "path": "Dockerfile",
    "chars": 141,
    "preview": "FROM scratch\nUSER 1001\nCOPY screego /screego\nEXPOSE 3478/tcp\nEXPOSE 3478/udp\nEXPOSE 5050\nWORKDIR \"/\"\nENTRYPOINT [ \"/scre"
  },
  {
    "path": "LICENSE",
    "chars": 35150,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 2386,
    "preview": "<p align=\"center\">\n    <a href=\"https://screego.net\">\n        <img src=\"docs/logo.png\" />\n    </a>\n</p>\n\n\n<h1 align=\"cen"
  },
  {
    "path": "auth/auth.go",
    "chars": 2868,
    "preview": "package auth\n\nimport (\n\t\"encoding/csv\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"github.com/gorilla/sessions"
  },
  {
    "path": "cmd/command.go",
    "chars": 397,
    "preview": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/rs/zerolog/log\"\n\t\"github.com/urfave/cli\"\n)\n\nfunc Run(version, commitHas"
  },
  {
    "path": "cmd/hash.go",
    "chars": 1018,
    "preview": "package cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"syscall\"\n\n\t\"github.com/rs/zerolog\"\n\t\"github.com/rs/zerolog/log\"\n\t\"github.com/screeg"
  },
  {
    "path": "cmd/serve.go",
    "chars": 1489,
    "preview": "package cmd\n\nimport (\n\t\"os\"\n\n\t\"github.com/rs/zerolog\"\n\t\"github.com/rs/zerolog/log\"\n\t\"github.com/screego/server/auth\"\n\t\"g"
  },
  {
    "path": "config/config.go",
    "chars": 8629,
    "preview": "package config\n\nimport (\n\t\"crypto/rand\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n"
  },
  {
    "path": "config/error.go",
    "chars": 434,
    "preview": "package config\n\nimport \"github.com/rs/zerolog\"\n\n// FutureLog is an intermediate type for log messages. It is used before"
  },
  {
    "path": "config/ip.go",
    "chars": 1994,
    "preview": "package config\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/screego/server/config/ipdns\"\n)\n\nfunc "
  },
  {
    "path": "config/ipdns/dns.go",
    "chars": 1480,
    "preview": "package ipdns\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/rs/zerolog/log\"\n)\n\ntype DNS"
  },
  {
    "path": "config/ipdns/provider.go",
    "chars": 88,
    "preview": "package ipdns\n\nimport \"net\"\n\ntype Provider interface {\n\tGet() (net.IP, net.IP, error)\n}\n"
  },
  {
    "path": "config/ipdns/static.go",
    "chars": 150,
    "preview": "package ipdns\n\nimport \"net\"\n\ntype Static struct {\n\tV4 net.IP\n\tV6 net.IP\n}\n\nfunc (s *Static) Get() (net.IP, net.IP, error"
  },
  {
    "path": "config/loglevel.go",
    "chars": 561,
    "preview": "package config\n\nimport (\n\t\"errors\"\n\n\t\"github.com/rs/zerolog\"\n)\n\n// LogLevel type that provides helper methods for decodi"
  },
  {
    "path": "config/loglevel_test.go",
    "chars": 495,
    "preview": "package config\n\nimport (\n\t\"testing\"\n\n\t\"github.com/rs/zerolog\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestLogLevel"
  },
  {
    "path": "config/mode/mode.go",
    "chars": 269,
    "preview": "package mode\n\nconst (\n\t// Dev for development mode.\n\tDev = \"dev\"\n\t// Prod for production mode.\n\tProd = \"prod\"\n)\n\nvar mod"
  },
  {
    "path": "config/mode/mode_test.go",
    "chars": 225,
    "preview": "package mode\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestGet(t *testing.T) {\n\tmode = Prod\n\t"
  },
  {
    "path": "docs/.nojekyll",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "docs/CNAME",
    "chars": 12,
    "preview": "screego.net\n"
  },
  {
    "path": "docs/README.md",
    "chars": 961,
    "preview": "# screego/server\r\n\r\nIn the past I've had some problems sharing my screen with coworkers using\r\ncorporate chatting soluti"
  },
  {
    "path": "docs/_sidebar.md",
    "chars": 221,
    "preview": "* [Home](/)\n* [Installation](install.md)\n* [Config](config.md)\n* [NAT Traversal](nat-traversal.md)\n* [Reverse Proxy](pro"
  },
  {
    "path": "docs/config.md",
    "chars": 668,
    "preview": "# Config\n\n!> TLS is required for Screego to work. Either enable TLS inside Screego or \n   use a reverse proxy to serve S"
  },
  {
    "path": "docs/development.md",
    "chars": 1596,
    "preview": "# Development\n\nScreego requires:\n\n- Go 1.15+\n- Node 13.x\n- Yarn 9+\n\n## Setup\n\n### Clone Repository\n\nClone screego/server"
  },
  {
    "path": "docs/faq.md",
    "chars": 807,
    "preview": "# Frequently Asked Questions\n\n## Stream doesn't load\n\nCheck that\n* you are using https to access Screego.\n* `SCREEGO_EXT"
  },
  {
    "path": "docs/index.html",
    "chars": 2277,
    "preview": "<!DOCTYPE html>\r\n<html lang=\"en\">\r\n<head>\r\n    <meta charset=\"UTF-8\">\r\n    <title>Screego</title>\r\n    <meta http-equiv="
  },
  {
    "path": "docs/install.md",
    "chars": 3427,
    "preview": "# Installation\n\nLatest Version: **GITHUB_VERSION**\n\nBefore starting Screego you may read [Configuration](config.md).\n\n!>"
  },
  {
    "path": "docs/nat-traversal.md",
    "chars": 1475,
    "preview": "# NAT Traversal\n\nIn most cases peers cannot directly communicate with each other because of firewalls or other restricti"
  },
  {
    "path": "docs/proxy.md",
    "chars": 3285,
    "preview": "# Proxy\n\n!> When using a proxy enable `SCREEGO_TRUST_PROXY_HEADERS`. See [Configuration](config.md).\n\n## nginx\n\n### At r"
  },
  {
    "path": "go.mod",
    "chars": 1833,
    "preview": "module github.com/screego/server\n\ngo 1.24.0\n\ntoolchain go1.24.1\n\nrequire (\n\tgithub.com/gorilla/handlers v1.5.2\n\tgithub.c"
  },
  {
    "path": "go.sum",
    "chars": 16652,
    "preview": "github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=\ngithub.com/BurntSushi/toml v1.4"
  },
  {
    "path": "logger/logger.go",
    "chars": 302,
    "preview": "package logger\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/rs/zerolog\"\n\t\"github.com/rs/zerolog/log\"\n)\n\n// Init initializes the"
  },
  {
    "path": "main.go",
    "chars": 250,
    "preview": "package main\n\nimport (\n\t\"github.com/screego/server/cmd\"\n\tpmode \"github.com/screego/server/config/mode\"\n)\n\nvar (\n\tversion"
  },
  {
    "path": "router/router.go",
    "chars": 3098,
    "preview": "package router\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/gorilla/handlers\"\n\t\"github.com/gorilla/mux\"\n"
  },
  {
    "path": "screego.config.development",
    "chars": 149,
    "preview": "SCREEGO_SECRET=secure\nSCREEGO_LOG_LEVEL=debug\nSCREEGO_CORS_ALLOWED_ORIGINS=http://localhost:3000\nSCREEGO_USERS_FILE=./us"
  },
  {
    "path": "screego.config.example",
    "chars": 4604,
    "preview": "# The external ip of the server.\n# When using a dual stack setup define both IPv4 & IPv6 separated by a comma.\n# Execute"
  },
  {
    "path": "server/server.go",
    "chars": 1975,
    "preview": "package server\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/signal\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gorilla/mux\"\n"
  },
  {
    "path": "server/server_test.go",
    "chars": 2048,
    "preview": "package server\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/goril"
  },
  {
    "path": "turn/none.go",
    "chars": 598,
    "preview": "package turn\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"strconv\"\n)\n\ntype RelayAddressGeneratorNone struct{}\n\nfunc (r *RelayAddressGene"
  },
  {
    "path": "turn/portrange.go",
    "chars": 1224,
    "preview": "package turn\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com/pion/randutil\"\n)\n\ntype RelayAddressGeneratorPortRange struc"
  },
  {
    "path": "turn/server.go",
    "chars": 4558,
    "preview": "package turn\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha1\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/pion"
  },
  {
    "path": "ui/.gitignore",
    "chars": 310,
    "preview": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pn"
  },
  {
    "path": "ui/.prettierrc",
    "chars": 206,
    "preview": "{\n  \"printWidth\": 100,\n  \"tabWidth\": 4,\n  \"useTabs\": false,\n  \"semi\": true,\n  \"singleQuote\": true,\n  \"trailingComma\": \"e"
  },
  {
    "path": "ui/index.html",
    "chars": 954,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"icon\" href=\"./favicon.ico\" />\n    "
  },
  {
    "path": "ui/package.json",
    "chars": 1160,
    "preview": "{\n  \"name\": \"ui\",\n  \"version\": \"0.1.0\",\n  \"homepage\": \".\",\n  \"private\": true,\n  \"dependencies\": {\n    \"@emotion/react\": "
  },
  {
    "path": "ui/serve.go",
    "chars": 1192,
    "preview": "package ui\n\nimport (\n\t\"embed\"\n\t\"io\"\n\t\"io/fs\"\n\t\"net/http\"\n\n\t\"github.com/gorilla/mux\"\n\t\"github.com/rs/zerolog/log\"\n)\n\n//go"
  },
  {
    "path": "ui/src/LoginForm.tsx",
    "chars": 3115,
    "preview": "import {UseConfig} from './useConfig';\nimport React from 'react';\nimport {\n    Box,\n    Button,\n    ButtonProps,\n    Cir"
  },
  {
    "path": "ui/src/NumberField.tsx",
    "chars": 1176,
    "preview": "import {TextField, TextFieldProps} from '@mui/material';\nimport React from 'react';\n\nexport interface NumberFieldProps {"
  },
  {
    "path": "ui/src/Room.tsx",
    "chars": 17238,
    "preview": "import React, {useCallback} from 'react';\nimport {Badge, Box, IconButton, Paper, Tooltip, Typography, Slider, Stack} fro"
  },
  {
    "path": "ui/src/RoomManage.tsx",
    "chars": 4672,
    "preview": "import React from 'react';\nimport {\n    Box,\n    Button,\n    Checkbox,\n    FormControl,\n    FormControlLabel,\n    Grid,\n"
  },
  {
    "path": "ui/src/Router.tsx",
    "chars": 601,
    "preview": "import {RoomManage} from './RoomManage';\nimport {useRoom} from './useRoom';\nimport {Room} from './Room';\nimport {UseConf"
  },
  {
    "path": "ui/src/SettingDialog.tsx",
    "chars": 4721,
    "preview": "import React from 'react';\nimport {\n    Dialog,\n    DialogTitle,\n    DialogContent,\n    TextField,\n    DialogActions,\n  "
  },
  {
    "path": "ui/src/Video.tsx",
    "chars": 477,
    "preview": "import React from 'react';\n\nexport const Video = ({src, className}: {src: MediaStream; className?: string}) => {\n    con"
  },
  {
    "path": "ui/src/global.css",
    "chars": 39,
    "preview": "#root,\nbody,\nhtml {\n    height: 100%;\n}"
  },
  {
    "path": "ui/src/index.tsx",
    "chars": 2445,
    "preview": "import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport './global.css';\nimport {Button, createTheme, "
  },
  {
    "path": "ui/src/message.ts",
    "chars": 2499,
    "preview": "export enum ShareMode {\n    Everyone = 'Everyone',\n    Selected = 'Selected',\n}\n\ntype Typed<Base, Type extends string> ="
  },
  {
    "path": "ui/src/settings.ts",
    "chars": 2613,
    "preview": "import React from 'react';\nexport const CodecBestQuality: PreferredCodec = {mimeType: 'BEST_QUALITY'};\nexport const Code"
  },
  {
    "path": "ui/src/url.ts",
    "chars": 352,
    "preview": "const {port, hostname, protocol, pathname} = window.location;\nconst slashes = protocol.concat('//');\nconst path = pathna"
  },
  {
    "path": "ui/src/useConfig.ts",
    "chars": 2380,
    "preview": "import {RoomMode, UIConfig} from './message';\nimport {useSnackbar} from 'notistack';\nimport React from 'react';\nimport {"
  },
  {
    "path": "ui/src/useRoom.ts",
    "chars": 15632,
    "preview": "import {useSnackbar} from 'notistack';\nimport React from 'react';\n\nimport {\n    ICEServer,\n    IncomingMessage,\n    Join"
  },
  {
    "path": "ui/src/useRoomID.ts",
    "chars": 1127,
    "preview": "import React from 'react';\n\nexport const getRoomFromURL = (): string | undefined => getFromURL('room');\n\nexport const ge"
  },
  {
    "path": "ui/src/vite-env.d.ts",
    "chars": 38,
    "preview": "/// <reference types=\"vite/client\" />\n"
  },
  {
    "path": "ui/tsconfig.json",
    "chars": 565,
    "preview": "{\n  \"compilerOptions\": {\n    \"target\": \"ES2020\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"ES2020\", \"DOM\", \"DOM."
  },
  {
    "path": "ui/tsconfig.node.json",
    "chars": 213,
    "preview": "{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"skipLibCheck\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\""
  },
  {
    "path": "ui/vite.config.mts",
    "chars": 443,
    "preview": "import {defineConfig} from 'vite';\nimport react from '@vitejs/plugin-react-swc';\n\nexport default defineConfig({\n    base"
  },
  {
    "path": "users",
    "chars": 85,
    "preview": "# Password: admin\nadmin:$2a$12$kNgc2ZYAXzIL6SHY.8PHAOQ8Casi0s1bKatYoG/jupt2yV1M5K5nO\n"
  },
  {
    "path": "util/password.go",
    "chars": 584,
    "preview": "package util\n\nimport (\n\t\"crypto/rand\"\n\t\"math/big\"\n)\n\nfunc RandString(length int) string {\n\tres := make([]byte, length)\n\t"
  },
  {
    "path": "util/sillyname.go",
    "chars": 2163,
    "preview": "package util\n\nimport (\n\t\"math/rand\"\n\n\t\"golang.org/x/text/cases\"\n\t\"golang.org/x/text/language\"\n)\n\nvar adjectives = []stri"
  },
  {
    "path": "ws/client.go",
    "chars": 5227,
    "preview": "package ws\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gorilla/websocket\"\n\t\"github.com/rs/xid\"\n"
  },
  {
    "path": "ws/event.go",
    "chars": 72,
    "preview": "package ws\n\ntype Event interface {\n\tExecute(*Rooms, ClientInfo) error\n}\n"
  },
  {
    "path": "ws/event_clientanswer.go",
    "chars": 687,
    "preview": "package ws\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/rs/zerolog/log\"\n\t\"github.com/screego/server/ws/outgoing\"\n)\n\nfunc init() {\n\treg"
  },
  {
    "path": "ws/event_clientice.go",
    "chars": 672,
    "preview": "package ws\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/rs/zerolog/log\"\n\t\"github.com/screego/server/ws/outgoing\"\n)\n\nfunc init() {\n\treg"
  },
  {
    "path": "ws/event_connected.go",
    "chars": 154,
    "preview": "package ws\n\ntype Connected struct{}\n\nfunc (e Connected) Execute(rooms *Rooms, current ClientInfo) error {\n\trooms.connect"
  },
  {
    "path": "ws/event_create.go",
    "chars": 1925,
    "preview": "package ws\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/rs/xid\"\n\t\"github.com/screego/server/config\"\n)\n\nfunc init() {\n\tregist"
  },
  {
    "path": "ws/event_disconnected.go",
    "chars": 1618,
    "preview": "package ws\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/gorilla/websocket\"\n\t\"github.com/screego/server/ws/outgoing\"\n)\n\ntype Disconne"
  },
  {
    "path": "ws/event_health.go",
    "chars": 184,
    "preview": "package ws\n\ntype Health struct {\n\tResponse chan int\n}\n\nfunc (e *Health) Execute(rooms *Rooms, current ClientInfo) error "
  },
  {
    "path": "ws/event_hostice.go",
    "chars": 662,
    "preview": "package ws\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/rs/zerolog/log\"\n\t\"github.com/screego/server/ws/outgoing\"\n)\n\nfunc init() {\n\treg"
  },
  {
    "path": "ws/event_hostoffer.go",
    "chars": 672,
    "preview": "package ws\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/rs/zerolog/log\"\n\t\"github.com/screego/server/ws/outgoing\"\n)\n\nfunc init() {\n\treg"
  },
  {
    "path": "ws/event_join.go",
    "chars": 1132,
    "preview": "package ws\n\nimport (\n\t\"fmt\"\n)\n\nfunc init() {\n\tregister(\"join\", func() Event {\n\t\treturn &Join{}\n\t})\n}\n\ntype Join struct {"
  },
  {
    "path": "ws/event_name.go",
    "chars": 363,
    "preview": "package ws\n\nfunc init() {\n\tregister(\"name\", func() Event {\n\t\treturn &Name{}\n\t})\n}\n\ntype Name struct {\n\tUserName string `"
  },
  {
    "path": "ws/event_share.go",
    "chars": 566,
    "preview": "package ws\n\nfunc init() {\n\tregister(\"share\", func() Event {\n\t\treturn &StartShare{}\n\t})\n}\n\ntype StartShare struct{}\n\nfunc"
  },
  {
    "path": "ws/event_stop_share.go",
    "chars": 658,
    "preview": "package ws\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/screego/server/ws/outgoing\"\n)\n\nfunc init() {\n\tregister(\"stopshare\", func() E"
  },
  {
    "path": "ws/once.go",
    "chars": 718,
    "preview": "// Copyright 2009 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license "
  },
  {
    "path": "ws/once_test.go",
    "chars": 753,
    "preview": "package ws\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc Test_Execute(t *testing.T) {\n\texe"
  },
  {
    "path": "ws/outgoing/messages.go",
    "chars": 1825,
    "preview": "package outgoing\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/rs/xid\"\n)\n\ntype Message interface {\n\tType() string\n}\n\ntype Roo"
  },
  {
    "path": "ws/prometheus.go",
    "chars": 1051,
    "preview": "package ws\n\nimport (\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/"
  },
  {
    "path": "ws/readwrite.go",
    "chars": 993,
    "preview": "package ws\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/screego/server/ws/outgoing\"\n)\n\ntype Typed str"
  },
  {
    "path": "ws/room.go",
    "chars": 3811,
    "preview": "package ws\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"sort\"\n\t\"time\"\n\n\t\"github.com/rs/xid\"\n\t\"github.com/rs/zerolog/log\"\n\t\"github.com/scree"
  },
  {
    "path": "ws/rooms.go",
    "chars": 3441,
    "preview": "package ws\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"time\"\n\n\t\"github.com/gorilla/websocket\"\n\t\"github.com/rs"
  },
  {
    "path": "ws/rooms_test.go",
    "chars": 2143,
    "preview": "package ws\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"math/rand\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/gorilla/websocket\"\n\t\""
  }
]

About this extraction

This page contains the full source code of the screego/server GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 94 files (210.7 KB), approximately 60.2k tokens, and a symbol index with 244 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!