[
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: jmattheis\npatreon: # Replace with a single Patreon username\nopen_collective: # Replace with a single Open Collective username\nko_fi: # Replace with a single Ko-fi username\ntidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel\ncommunity_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry\nliberapay: # Replace with a single Liberapay username\nissuehunt: # Replace with a single IssueHunt username\notechie: # Replace with a single Otechie username\ncustom: https://jmattheis.de/donate\n"
  },
  {
    "path": ".github/workflows/build.yml",
    "content": "name: build\non: [push, pull_request]\n\njobs:\n  screego:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/setup-go@4dc6199c7b1a012772edbd06daecab0f50c9053c # v6.1.0\n        with:\n          go-version: 1.25.x\n      - uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f #v6.1.0\n        with:\n          node-version: '25'\n      - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 #v6.0.1\n      - run: go mod download\n      - run: (cd ui && yarn)\n      - run: (cd ui && yarn build)\n      - run: (cd ui && yarn testformat)\n      - uses: golangci/golangci-lint-action@1e7e51e771db61008b38414a730f564565cf7c20 # 9.2.0\n        with:\n          version: v2.7.2\n      - run: go build ./...\n      - run: go test -race ./...\n      - if: startsWith(github.ref, 'refs/tags/v')\n        run: |\n          echo \"$DOCKER_PASS\" | docker login --username \"$DOCKER_USER\" --password-stdin\n          echo \"${{ secrets.GITHUB_TOKEN }}\" | docker login ghcr.io --username \"${{ github.actor }}\" --password-stdin\n        env:\n          DOCKER_USER: ${{ secrets.DOCKER_USER }}\n          DOCKER_PASS: ${{ secrets.DOCKER_PASS }}\n      - if: startsWith(github.ref, 'refs/tags/v')\n        uses: goreleaser/goreleaser-action@e435ccd777264be153ace6237001ef4d979d3a7a #v6.4.0\n        with:\n          version: 2.13.0\n          args: release --skip=validate\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n"
  },
  {
    "path": ".gitignore",
    "content": "/target\n/.idea\n*-packr.go\n/dist/\n*.local\n"
  },
  {
    "path": ".golangci.yml",
    "content": "version: \"2\"\nlinters:\n  disable:\n    - errcheck\n\n"
  },
  {
    "path": ".goreleaser.yml",
    "content": "# This is an example goreleaser.yaml file with some sane defaults.\n# Make sure to check the documentation at http://goreleaser.com\nproject_name: screego\nversion: 2\nbefore:\n  hooks:\n    - go mod download\nbuilds:\n  - env:\n      - CGO_ENABLED=0\n    goos:\n      - linux\n      - windows\n      - darwin\n      - freebsd\n      - openbsd\n    goarch:\n      - \"386\"\n      - amd64\n      - arm\n      - arm64\n      - ppc64\n      - ppc64le\n    goarm:\n      - \"6\"\n      - \"7\"\n    flags:\n      - '-tags=\"netgo osusergo\"'\n    ldflags:\n      - \"-s\"\n      - \"-w\"\n      - \"-X main.version={{.Version}}\"\n      - \"-X main.commitHash={{.Commit}}\"\n      - \"-X main.mode=prod\"\narchives:\n  - files:\n      - LICENSE\n      - README.md\n      - screego.config.example\n    name_template: '{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{- if eq .Arch \"386\" }}i386{{- else }}{{ .Arch }}{{ end }}{{ if .Arm }}v{{ .Arm }}{{ end }}'\n    format_overrides:\n      - goos: windows\n        formats: [zip]\nchecksum:\n  disable: true\nchangelog:\n  disable: true\ndockers:\n  - use: buildx\n    goos: linux\n    goarch: amd64\n    goarm: \"\"\n    image_templates:\n      - \"screego/server:amd64-unstable\"\n      - \"screego/server:amd64-{{ .RawVersion }}\"\n      - \"screego/server:amd64-{{ .Major }}\"\n      - \"ghcr.io/screego/server:amd64-unstable\"\n      - \"ghcr.io/screego/server:amd64-{{ .RawVersion }}\"\n      - \"ghcr.io/screego/server:amd64-{{ .Major }}\"\n    dockerfile: Dockerfile\n    build_flag_templates:\n      - \"--platform=linux/amd64\"\n      - \"--label=org.opencontainers.image.created={{.Date}}\"\n      - \"--label=org.opencontainers.image.title={{.ProjectName}}\"\n      - \"--label=org.opencontainers.image.revision={{.FullCommit}}\"\n      - \"--label=org.opencontainers.image.version={{.Version}}\"\n  - use: buildx\n    goos: linux\n    goarch: \"386\"\n    goarm: \"\"\n    image_templates:\n      - \"screego/server:386-unstable\"\n      - \"screego/server:386-{{ .RawVersion }}\"\n      - \"screego/server:386-{{ .Major }}\"\n      - \"ghcr.io/screego/server:386-unstable\"\n      - \"ghcr.io/screego/server:386-{{ .RawVersion }}\"\n      - \"ghcr.io/screego/server:386-{{ .Major }}\"\n    dockerfile: Dockerfile\n    build_flag_templates:\n      - \"--platform=linux/386\"\n      - \"--label=org.opencontainers.image.created={{.Date}}\"\n      - \"--label=org.opencontainers.image.title={{.ProjectName}}\"\n      - \"--label=org.opencontainers.image.revision={{.FullCommit}}\"\n      - \"--label=org.opencontainers.image.version={{.Version}}\"\n  - use: buildx\n    goos: linux\n    goarch: arm64\n    goarm: \"\"\n    image_templates:\n      - \"screego/server:arm64-unstable\"\n      - \"screego/server:arm64-{{ .RawVersion }}\"\n      - \"screego/server:arm64-{{ .Major }}\"\n      - \"ghcr.io/screego/server:arm64-unstable\"\n      - \"ghcr.io/screego/server:arm64-{{ .RawVersion }}\"\n      - \"ghcr.io/screego/server:arm64-{{ .Major }}\"\n    dockerfile: Dockerfile\n    build_flag_templates:\n      - \"--platform=linux/arm64\"\n      - \"--label=org.opencontainers.image.created={{.Date}}\"\n      - \"--label=org.opencontainers.image.title={{.ProjectName}}\"\n      - \"--label=org.opencontainers.image.revision={{.FullCommit}}\"\n      - \"--label=org.opencontainers.image.version={{.Version}}\"\n  - use: buildx\n    goos: linux\n    goarch: arm\n    goarm: 7\n    image_templates:\n      - \"screego/server:armv7-unstable\"\n      - \"screego/server:armv7-{{ .RawVersion }}\"\n      - \"screego/server:armv7-{{ .Major }}\"\n      - \"ghcr.io/screego/server:armv7-unstable\"\n      - \"ghcr.io/screego/server:armv7-{{ .RawVersion }}\"\n      - \"ghcr.io/screego/server:armv7-{{ .Major }}\"\n    dockerfile: Dockerfile\n    build_flag_templates:\n      - \"--platform=linux/arm/v7\"\n      - \"--label=org.opencontainers.image.created={{.Date}}\"\n      - \"--label=org.opencontainers.image.title={{.ProjectName}}\"\n      - \"--label=org.opencontainers.image.revision={{.FullCommit}}\"\n      - \"--label=org.opencontainers.image.version={{.Version}}\"\n  - use: buildx\n    goos: linux\n    goarch: arm\n    goarm: 6\n    image_templates:\n      - \"screego/server:armv6-unstable\"\n      - \"screego/server:armv6-{{ .RawVersion }}\"\n      - \"screego/server:armv6-{{ .Major }}\"\n      - \"ghcr.io/screego/server:armv6-unstable\"\n      - \"ghcr.io/screego/server:armv6-{{ .RawVersion }}\"\n      - \"ghcr.io/screego/server:armv6-{{ .Major }}\"\n    dockerfile: Dockerfile\n    build_flag_templates:\n      - \"--platform=linux/arm/v6\"\n      - \"--label=org.opencontainers.image.created={{.Date}}\"\n      - \"--label=org.opencontainers.image.title={{.ProjectName}}\"\n      - \"--label=org.opencontainers.image.revision={{.FullCommit}}\"\n      - \"--label=org.opencontainers.image.version={{.Version}}\"\n  - use: buildx\n    goos: linux\n    goarch: ppc64le\n    goarm: \"\"\n    image_templates:\n      - \"screego/server:ppc64le-unstable\"\n      - \"screego/server:ppc64le-{{ .RawVersion }}\"\n      - \"screego/server:ppc64le-{{ .Major }}\"\n      - \"ghcr.io/screego/server:ppc64le-unstable\"\n      - \"ghcr.io/screego/server:ppc64le-{{ .RawVersion }}\"\n      - \"ghcr.io/screego/server:ppc64le-{{ .Major }}\"\n    dockerfile: Dockerfile\n    build_flag_templates:\n      - \"--platform=linux/ppc64le\"\n      - \"--label=org.opencontainers.image.created={{.Date}}\"\n      - \"--label=org.opencontainers.image.title={{.ProjectName}}\"\n      - \"--label=org.opencontainers.image.revision={{.FullCommit}}\"\n      - \"--label=org.opencontainers.image.version={{.Version}}\"\ndocker_manifests:\n  - name_template: \"ghcr.io/screego/server:unstable\"\n    image_templates:\n      - \"ghcr.io/screego/server:amd64-unstable\"\n      - \"ghcr.io/screego/server:386-unstable\"\n      - \"ghcr.io/screego/server:arm64-unstable\"\n      - \"ghcr.io/screego/server:armv7-unstable\"\n      - \"ghcr.io/screego/server:armv6-unstable\"\n      - \"ghcr.io/screego/server:ppc64le-unstable\"\n  - name_template: \"screego/server:unstable\"\n    image_templates:\n      - \"screego/server:amd64-unstable\"\n      - \"screego/server:386-unstable\"\n      - \"screego/server:arm64-unstable\"\n      - \"screego/server:armv7-unstable\"\n      - \"screego/server:armv6-unstable\"\n      - \"screego/server:ppc64le-unstable\"\n  - name_template: \"screego/server:{{ .RawVersion }}\"\n    image_templates:\n      - \"screego/server:amd64-{{ .RawVersion }}\"\n      - \"screego/server:386-{{ .RawVersion }}\"\n      - \"screego/server:arm64-{{ .RawVersion }}\"\n      - \"screego/server:armv7-{{ .RawVersion }}\"\n      - \"screego/server:armv6-{{ .RawVersion }}\"\n      - \"screego/server:ppc64le-{{ .RawVersion }}\"\n  - name_template: \"ghcr.io/screego/server:{{ .RawVersion }}\"\n    image_templates:\n      - \"ghcr.io/screego/server:amd64-{{ .RawVersion }}\"\n      - \"ghcr.io/screego/server:386-{{ .RawVersion }}\"\n      - \"ghcr.io/screego/server:arm64-{{ .RawVersion }}\"\n      - \"ghcr.io/screego/server:armv7-{{ .RawVersion }}\"\n      - \"ghcr.io/screego/server:armv6-{{ .RawVersion }}\"\n      - \"ghcr.io/screego/server:ppc64le-{{ .RawVersion }}\"\n  - name_template: \"screego/server:{{ .Major }}\"\n    image_templates:\n      - \"screego/server:amd64-{{ .Major }}\"\n      - \"screego/server:386-{{ .Major }}\"\n      - \"screego/server:arm64-{{ .Major }}\"\n      - \"screego/server:armv7-{{ .Major }}\"\n      - \"screego/server:armv6-{{ .Major }}\"\n      - \"screego/server:ppc64le-{{ .Major }}\"\n  - name_template: \"ghcr.io/screego/server:{{ .Major }}\"\n    image_templates:\n      - \"ghcr.io/screego/server:amd64-{{ .Major }}\"\n      - \"ghcr.io/screego/server:386-{{ .Major }}\"\n      - \"ghcr.io/screego/server:arm64-{{ .Major }}\"\n      - \"ghcr.io/screego/server:armv7-{{ .Major }}\"\n      - \"ghcr.io/screego/server:armv6-{{ .Major }}\"\n      - \"ghcr.io/screego/server:ppc64le-{{ .Major }}\"\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM scratch\nUSER 1001\nCOPY screego /screego\nEXPOSE 3478/tcp\nEXPOSE 3478/udp\nEXPOSE 5050\nWORKDIR \"/\"\nENTRYPOINT [ \"/screego\" ]\nCMD [\"serve\"]\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n\n"
  },
  {
    "path": "README.md",
    "content": "<p align=\"center\">\n    <a href=\"https://screego.net\">\n        <img src=\"docs/logo.png\" />\n    </a>\n</p>\n\n\n<h1 align=\"center\">screego/server</h1>\n<p align=\"center\"><i>screen sharing for developers</i></p>\n\n<p align=\"center\">\n    <a href=\"https://github.com/screego/server/actions?query=workflow%3Abuild\">\n        <img alt=\"Build Status\" src=\"https://github.com/screego/server/workflows/build/badge.svg\">\n    </a> \n    <a href=\"https://github.com/screego/server/pkgs/container/server\">\n        <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\">\n    </a> \n    <a href=\"https://goreportcard.com/report/github.com/screego/server\">\n        <img alt=\"Go Report Card\" src=\"https://goreportcard.com/badge/github.com/screego/server\">\n    </a>\n    <a href=\"https://hub.docker.com/r/screego/server\">\n        <img alt=\"Docker Pulls\" src=\"https://img.shields.io/docker/pulls/screego/server.svg\">\n    </a>\n    <a href=\"https://github.com/screego/server/releases/latest\">\n        <img alt=\"latest release\" src=\"https://img.shields.io/github/release/screego/server.svg\">\n    </a>\n</p>\n\n## Intro\n\nIn the past I've had some problems sharing my screen with coworkers using\ncorporate chatting solutions like Microsoft Teams. I wanted to show them some\nof my code, but either the stream lagged several seconds behind or the quality\nwas so poor that my colleagues couldn't read the code. Or both.\n\nThat's why I created screego. It allows you to share your screen with good\nquality and low latency. Screego is an addition to existing software and \nonly helps to share your screen. Nothing else (:.\n\n## Features\n\n* Multi User Screenshare\n* Secure transfer via WebRTC\n* Low latency / High resolution\n* Simple Install via Docker / single binary\n* Integrated TURN Server see [NAT Traversal](https://screego.net/#/nat-traversal)\n\n[Demo / Public Instance](https://app.screego.net/) ᛫ [Installation](https://screego.net/#/install) ᛫ [Configuration](https://screego.net/#/config) \n\n## Versioning\n\nWe use [SemVer](http://semver.org/) for versioning. For the versions available, see the\n[tags on this repository](https://github.com/screego/server/tags).\n"
  },
  {
    "path": "auth/auth.go",
    "content": "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\"\n\t\"github.com/rs/zerolog/log\"\n\t\"golang.org/x/crypto/bcrypt\"\n)\n\ntype Users struct {\n\tLookup         map[string]string\n\tstore          sessions.Store\n\tsessionTimeout int\n}\n\ntype UserPW struct {\n\tName string\n\tPass string\n}\n\nfunc read(r io.Reader) ([]UserPW, error) {\n\treader := csv.NewReader(r)\n\treader.Comma = ':'\n\treader.Comment = '#'\n\treader.TrimLeadingSpace = true\n\n\trecords, err := reader.ReadAll()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := []UserPW{}\n\tfor _, record := range records {\n\t\tif len(record) != 2 {\n\t\t\treturn nil, errors.New(\"malformed users file\")\n\t\t}\n\t\tresult = append(result, UserPW{Name: record[0], Pass: record[1]})\n\t}\n\treturn result, nil\n}\n\nfunc ReadPasswordsFile(path string, secret []byte, sessionTimeout int) (*Users, error) {\n\tusers := &Users{\n\t\tLookup:         map[string]string{},\n\t\tsessionTimeout: sessionTimeout,\n\t\tstore:          sessions.NewCookieStore(secret),\n\t}\n\tif path == \"\" {\n\t\tlog.Info().Msg(\"Users file not specified\")\n\t\treturn users, nil\n\t}\n\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn users, err\n\t}\n\tdefer file.Close()\n\tuserPws, err := read(file)\n\tif err != nil {\n\t\treturn users, err\n\t}\n\n\tfor _, record := range userPws {\n\t\tusers.Lookup[record.Name] = record.Pass\n\t}\n\tlog.Info().Int(\"amount\", len(users.Lookup)).Msg(\"Loaded Users\")\n\treturn users, nil\n}\n\ntype Response struct {\n\tMessage string `json:\"message\"`\n}\n\nfunc (u *Users) CurrentUser(r *http.Request) (string, bool) {\n\ts, _ := u.store.Get(r, \"user\")\n\tuser, ok := s.Values[\"user\"].(string)\n\tif !ok {\n\t\treturn \"guest\", ok\n\t}\n\treturn user, ok\n}\n\nfunc (u *Users) Logout(w http.ResponseWriter, r *http.Request) {\n\tsession := sessions.NewSession(u.store, \"user\")\n\tsession.IsNew = true\n\tif err := u.store.Save(r, w, session); err != nil {\n\t\tw.WriteHeader(500)\n\t\t_ = json.NewEncoder(w).Encode(&Response{\n\t\t\tMessage: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\tw.WriteHeader(200)\n}\n\nfunc (u *Users) Authenticate(w http.ResponseWriter, r *http.Request) {\n\tuser := r.FormValue(\"user\")\n\tpass := r.FormValue(\"pass\")\n\n\tif !u.Validate(user, pass) {\n\t\tw.WriteHeader(401)\n\t\t_ = json.NewEncoder(w).Encode(&Response{\n\t\t\tMessage: \"could not authenticate\",\n\t\t})\n\t\treturn\n\t}\n\n\tsession := sessions.NewSession(u.store, \"user\")\n\tsession.IsNew = true\n\tsession.Options.MaxAge = u.sessionTimeout\n\tsession.Values[\"user\"] = user\n\tif err := u.store.Save(r, w, session); err != nil {\n\t\tw.WriteHeader(500)\n\t\t_ = json.NewEncoder(w).Encode(&Response{\n\t\t\tMessage: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\tw.WriteHeader(200)\n\t_ = json.NewEncoder(w).Encode(&Response{\n\t\tMessage: \"authenticated\",\n\t})\n}\n\nfunc (u Users) Validate(user, password string) bool {\n\trealPassword, exists := u.Lookup[user]\n\treturn exists && bcrypt.CompareHashAndPassword([]byte(realPassword), []byte(password)) == nil\n}\n"
  },
  {
    "path": "cmd/command.go",
    "content": "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, commitHash string) {\n\tapp := cli.App{\n\t\tName:    \"screego\",\n\t\tVersion: fmt.Sprintf(\"%s; screego/server@%s\", version, commitHash),\n\t\tCommands: []cli.Command{\n\t\t\tserveCmd(version),\n\t\t\thashCmd,\n\t\t},\n\t}\n\terr := app.Run(os.Args)\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"app error\")\n\t}\n}\n"
  },
  {
    "path": "cmd/hash.go",
    "content": "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/screego/server/logger\"\n\t\"github.com/urfave/cli\"\n\t\"golang.org/x/crypto/bcrypt\"\n\t\"golang.org/x/term\"\n)\n\nvar hashCmd = cli.Command{\n\tName: \"hash\",\n\tFlags: []cli.Flag{\n\t\t&cli.StringFlag{Name: \"name\"},\n\t\t&cli.StringFlag{Name: \"pass\"},\n\t},\n\tAction: func(ctx *cli.Context) {\n\t\tlogger.Init(zerolog.ErrorLevel)\n\t\tname := ctx.String(\"name\")\n\t\tpass := []byte(ctx.String(\"pass\"))\n\t\tif name == \"\" {\n\t\t\tlog.Fatal().Msg(\"--name must be set\")\n\t\t}\n\n\t\tif len(pass) == 0 {\n\t\t\tvar err error\n\t\t\t_, _ = fmt.Fprint(os.Stderr, \"Enter Password: \")\n\t\t\tpass, err = term.ReadPassword(int(syscall.Stdin))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal().Err(err).Msg(\"could not read stdin\")\n\t\t\t}\n\t\t\t_, _ = fmt.Fprintln(os.Stderr, \"\")\n\t\t}\n\t\thashedPw, err := bcrypt.GenerateFromPassword(pass, 12)\n\t\tif err != nil {\n\t\t\tlog.Fatal().Err(err).Msg(\"could not generate password\")\n\t\t}\n\n\t\tfmt.Printf(\"%s:%s\", name, string(hashedPw))\n\t\tfmt.Println(\"\")\n\t},\n}\n"
  },
  {
    "path": "cmd/serve.go",
    "content": "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\"github.com/screego/server/config\"\n\t\"github.com/screego/server/logger\"\n\t\"github.com/screego/server/router\"\n\t\"github.com/screego/server/server\"\n\t\"github.com/screego/server/turn\"\n\t\"github.com/screego/server/ws\"\n\t\"github.com/urfave/cli\"\n)\n\nfunc serveCmd(version string) cli.Command {\n\treturn cli.Command{\n\t\tName: \"serve\",\n\t\tAction: func(ctx *cli.Context) {\n\t\t\tconf, errs := config.Get()\n\t\t\tlogger.Init(conf.LogLevel.AsZeroLogLevel())\n\n\t\t\texit := false\n\t\t\tfor _, err := range errs {\n\t\t\t\tlog.WithLevel(err.Level).Msg(err.Msg)\n\t\t\t\texit = exit || err.Level == zerolog.FatalLevel || err.Level == zerolog.PanicLevel\n\t\t\t}\n\t\t\tif exit {\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\tif _, _, err := conf.TurnIPProvider.Get(); err != nil {\n\t\t\t\t// error is already logged by .Get()\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\tusers, err := auth.ReadPasswordsFile(conf.UsersFile, conf.Secret, conf.SessionTimeoutSeconds)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal().Str(\"file\", conf.UsersFile).Err(err).Msg(\"While loading users file\")\n\t\t\t}\n\n\t\t\ttServer, err := turn.Start(conf)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal().Err(err).Msg(\"could not start turn server\")\n\t\t\t}\n\n\t\t\trooms := ws.NewRooms(tServer, users, conf)\n\n\t\t\tgo rooms.Start()\n\n\t\t\tr := router.Router(conf, rooms, users, version)\n\t\t\tif err := server.Start(r, conf.ServerAddress, conf.TLSCertFile, conf.TLSKeyFile); err != nil {\n\t\t\t\tlog.Fatal().Err(err).Msg(\"http server\")\n\t\t\t}\n\t\t},\n\t}\n}\n"
  },
  {
    "path": "config/config.go",
    "content": "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\t\"github.com/joho/godotenv\"\n\t\"github.com/kelseyhightower/envconfig\"\n\t\"github.com/rs/zerolog\"\n\t\"github.com/screego/server/config/ipdns\"\n\t\"github.com/screego/server/config/mode\"\n)\n\nvar (\n\tprefix        = \"screego\"\n\tfiles         = []string{\"screego.config.development.local\", \"screego.config.development\", \"screego.config.local\", \"screego.config\"}\n\tabsoluteFiles = []string{\"/etc/screego/server.config\"}\n\tosExecutable  = os.Executable\n\tosStat        = os.Stat\n)\n\nconst (\n\tAuthModeTurn = \"turn\"\n\tAuthModeAll  = \"all\"\n\tAuthModeNone = \"none\"\n)\n\n// Config represents the application configuration.\ntype Config struct {\n\tLogLevel LogLevel `default:\"info\" split_words:\"true\"`\n\n\tExternalIP []string `split_words:\"true\"`\n\n\tTLSCertFile string `split_words:\"true\"`\n\tTLSKeyFile  string `split_words:\"true\"`\n\n\tServerTLS             bool   `split_words:\"true\"`\n\tServerAddress         string `default:\":5050\" split_words:\"true\"`\n\tSecret                []byte `split_words:\"true\"`\n\tSessionTimeoutSeconds int    `default:\"0\" split_words:\"true\"`\n\n\tTurnAddress   string `default:\":3478\" required:\"true\" split_words:\"true\"`\n\tTurnPortRange string `split_words:\"true\"`\n\n\tTurnExternalIP     []string `split_words:\"true\"`\n\tTurnExternalPort   string   `default:\"3478\" split_words:\"true\"`\n\tTurnExternalSecret string   `split_words:\"true\"`\n\n\tTrustProxyHeaders  bool     `split_words:\"true\"`\n\tAuthMode           string   `default:\"turn\" split_words:\"true\"`\n\tCorsAllowedOrigins []string `split_words:\"true\"`\n\tUsersFile          string   `split_words:\"true\"`\n\tPrometheus         bool     `split_words:\"true\"`\n\n\tCheckOrigin    func(string) bool `ignored:\"true\" json:\"-\"`\n\tTurnExternal   bool              `ignored:\"true\"`\n\tTurnIPProvider ipdns.Provider    `ignored:\"true\"`\n\tTurnPort       string            `ignored:\"true\"`\n\n\tTurnDenyPeers       []string     `default:\"0.0.0.0/8,127.0.0.1/8,::/128,::1/128,fe80::/10\" split_words:\"true\"`\n\tTurnDenyPeersParsed []*net.IPNet `ignored:\"true\"`\n\n\tCloseRoomWhenOwnerLeaves bool `default:\"true\" split_words:\"true\"`\n}\n\nfunc (c Config) parsePortRange() (uint16, uint16, error) {\n\tif c.TurnPortRange == \"\" {\n\t\treturn 0, 0, nil\n\t}\n\n\tparts := strings.Split(c.TurnPortRange, \":\")\n\tif len(parts) != 2 {\n\t\treturn 0, 0, errors.New(\"must include one colon\")\n\t}\n\tstringMin := parts[0]\n\tstringMax := parts[1]\n\tmin64, err := strconv.ParseUint(stringMin, 10, 16)\n\tif err != nil {\n\t\treturn 0, 0, fmt.Errorf(\"invalid min: %s\", err)\n\t}\n\tmax64, err := strconv.ParseUint(stringMax, 10, 16)\n\tif err != nil {\n\t\treturn 0, 0, fmt.Errorf(\"invalid max: %s\", err)\n\t}\n\n\treturn uint16(min64), uint16(max64), nil\n}\n\nfunc (c Config) PortRange() (uint16, uint16, bool) {\n\tmin, max, _ := c.parsePortRange()\n\treturn min, max, min != 0 && max != 0\n}\n\n// Get loads the application config.\nfunc Get() (Config, []FutureLog) {\n\tvar logs []FutureLog\n\tdir, log := getExecutableOrWorkDir()\n\tif log != nil {\n\t\tlogs = append(logs, *log)\n\t}\n\n\tfor _, file := range getFiles(dir) {\n\t\t_, fileErr := osStat(file)\n\t\tif fileErr == nil {\n\t\t\tif err := godotenv.Load(file); err != nil {\n\t\t\t\tlogs = append(logs, futureFatal(fmt.Sprintf(\"cannot load file %s: %s\", file, err)))\n\t\t\t} else {\n\t\t\t\tlogs = append(logs, FutureLog{\n\t\t\t\t\tLevel: zerolog.DebugLevel,\n\t\t\t\t\tMsg:   fmt.Sprintf(\"Loading file %s\", file),\n\t\t\t\t})\n\t\t\t}\n\t\t} else if os.IsNotExist(fileErr) {\n\t\t\tcontinue\n\t\t} else {\n\t\t\tlogs = append(logs, FutureLog{\n\t\t\t\tLevel: zerolog.WarnLevel,\n\t\t\t\tMsg:   fmt.Sprintf(\"cannot read file %s because %s\", file, fileErr),\n\t\t\t})\n\t\t}\n\t}\n\n\tconfig := Config{}\n\terr := envconfig.Process(prefix, &config)\n\tif err != nil {\n\t\tlogs = append(logs,\n\t\t\tfutureFatal(fmt.Sprintf(\"cannot parse env params: %s\", err)))\n\t}\n\n\tif config.AuthMode != AuthModeTurn && config.AuthMode != AuthModeAll && config.AuthMode != AuthModeNone {\n\t\tlogs = append(logs,\n\t\t\tfutureFatal(fmt.Sprintf(\"invalid SCREEGO_AUTH_MODE: %s\", config.AuthMode)))\n\t}\n\n\tif config.ServerTLS {\n\t\tif config.TLSCertFile == \"\" {\n\t\t\tlogs = append(logs, futureFatal(\"SCREEGO_TLS_CERT_FILE must be set if TLS is enabled\"))\n\t\t}\n\n\t\tif config.TLSKeyFile == \"\" {\n\t\t\tlogs = append(logs, futureFatal(\"SCREEGO_TLS_KEY_FILE must be set if TLS is enabled\"))\n\t\t}\n\t}\n\n\tvar compiledAllowedOrigins []*regexp.Regexp\n\tfor _, origin := range config.CorsAllowedOrigins {\n\t\tcompiled, err := regexp.Compile(origin)\n\t\tif err != nil {\n\t\t\tlogs = append(logs, futureFatal(fmt.Sprintf(\"invalid regex: %s\", err)))\n\t\t}\n\t\tcompiledAllowedOrigins = append(compiledAllowedOrigins, compiled)\n\t}\n\n\tconfig.CheckOrigin = func(origin string) bool {\n\t\tif origin == \"\" {\n\t\t\treturn true\n\t\t}\n\t\tfor _, compiledOrigin := range compiledAllowedOrigins {\n\t\t\tif compiledOrigin.Match([]byte(strings.ToLower(origin))) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\tif len(config.Secret) == 0 {\n\t\tconfig.Secret = make([]byte, 32)\n\t\tif _, err := rand.Read(config.Secret); err == nil {\n\t\t\tlogs = append(logs, FutureLog{\n\t\t\t\tLevel: zerolog.InfoLevel,\n\t\t\t\tMsg:   \"SCREEGO_SECRET unset, user logins will be invalidated on restart\",\n\t\t\t})\n\t\t} else {\n\t\t\tlogs = append(logs, futureFatal(fmt.Sprintf(\"cannot create secret %s\", err)))\n\t\t}\n\t}\n\n\tvar errs []FutureLog\n\n\tif len(config.TurnExternalIP) > 0 {\n\t\tif len(config.ExternalIP) > 0 {\n\t\t\tlogs = append(logs, futureFatal(\"SCREEGO_EXTERNAL_IP and SCREEGO_TURN_EXTERNAL_IP must not be both set\"))\n\t\t}\n\n\t\tconfig.TurnIPProvider, errs = parseIPProvider(config.TurnExternalIP, \"SCREEGO_TURN_EXTERNAL_IP\")\n\t\tconfig.TurnPort = config.TurnExternalPort\n\t\tconfig.TurnExternal = true\n\t\tlogs = append(logs, errs...)\n\t\tif config.TurnExternalSecret == \"\" {\n\t\t\tlogs = append(logs, futureFatal(\"SCREEGO_TURN_EXTERNAL_SECRET must be set if external TURN server is used\"))\n\t\t}\n\t} else if len(config.ExternalIP) > 0 {\n\t\tconfig.TurnIPProvider, errs = parseIPProvider(config.ExternalIP, \"SCREEGO_EXTERNAL_IP\")\n\t\tlogs = append(logs, errs...)\n\t\tsplit := strings.Split(config.TurnAddress, \":\")\n\t\tconfig.TurnPort = split[len(split)-1]\n\t} else {\n\t\tlogs = append(logs, futureFatal(\"SCREEGO_EXTERNAL_IP or SCREEGO_TURN_EXTERNAL_IP must be set\"))\n\t}\n\n\tmin, max, err := config.parsePortRange()\n\tif err != nil {\n\t\tlogs = append(logs, futureFatal(fmt.Sprintf(\"invalid SCREEGO_TURN_PORT_RANGE: %s\", err)))\n\t} else if min == 0 && max == 0 {\n\t\t// valid; no port range\n\t} else if min == 0 || max == 0 {\n\t\tlogs = append(logs, futureFatal(\"invalid SCREEGO_TURN_PORT_RANGE: min or max port is 0\"))\n\t} else if min > max {\n\t\tlogs = append(logs, futureFatal(fmt.Sprintf(\"invalid SCREEGO_TURN_PORT_RANGE: min port (%d) is higher than max port (%d)\", min, max)))\n\t} else if (max - min) < 40 {\n\t\tlogs = append(logs, FutureLog{\n\t\t\tLevel: zerolog.WarnLevel,\n\t\t\tMsg:   \"Less than 40 ports are available for turn. When using multiple TURN connections this may not be enough\",\n\t\t})\n\t}\n\tlogs = append(logs, logDeprecated()...)\n\n\tfor _, cidrString := range config.TurnDenyPeers {\n\t\t_, cidr, err := net.ParseCIDR(cidrString)\n\t\tif err != nil {\n\t\t\tlogs = append(logs, FutureLog{\n\t\t\t\tLevel: zerolog.FatalLevel,\n\t\t\t\tMsg:   fmt.Sprintf(\"Invalid SCREEGO_TURN_DENY_PEERS %q: %s\", cidrString, err),\n\t\t\t})\n\t\t} else {\n\t\t\tconfig.TurnDenyPeersParsed = append(config.TurnDenyPeersParsed, cidr)\n\t\t}\n\t}\n\tlogs = append(logs, FutureLog{\n\t\tLevel: zerolog.InfoLevel,\n\t\tMsg:   fmt.Sprintf(\"Deny turn peers within %q\", config.TurnDenyPeersParsed),\n\t})\n\n\treturn config, logs\n}\n\nfunc logDeprecated() []FutureLog {\n\tif os.Getenv(\"SCREEGO_TURN_STRICT_AUTH\") != \"\" {\n\t\treturn []FutureLog{{Level: zerolog.WarnLevel, Msg: \"The setting SCREEGO_TURN_STRICT_AUTH has been removed.\"}}\n\t}\n\treturn nil\n}\n\nfunc getExecutableOrWorkDir() (string, *FutureLog) {\n\tdir, err := getExecutableDir()\n\t// when using `go run main.go` the executable lives in th temp directory therefore the env.development\n\t// will not be read, this enforces that the current work directory is used in dev mode.\n\tif err != nil || mode.Get() == mode.Dev {\n\t\treturn filepath.Dir(\".\"), err\n\t}\n\treturn dir, nil\n}\n\nfunc getExecutableDir() (string, *FutureLog) {\n\tex, err := osExecutable()\n\tif err != nil {\n\t\treturn \"\", &FutureLog{\n\t\t\tLevel: zerolog.ErrorLevel,\n\t\t\tMsg:   \"Could not get path of executable using working directory instead. \" + err.Error(),\n\t\t}\n\t}\n\treturn filepath.Dir(ex), nil\n}\n\nfunc getFiles(relativeTo string) []string {\n\tvar result []string\n\tfor _, file := range files {\n\t\tresult = append(result, filepath.Join(relativeTo, file))\n\t}\n\thomeDir, err := os.UserHomeDir()\n\tif err == nil {\n\t\tresult = append(result, filepath.Join(homeDir, \".config/screego/server.config\"))\n\t}\n\tresult = append(result, absoluteFiles...)\n\treturn result\n}\n"
  },
  {
    "path": "config/error.go",
    "content": "package config\n\nimport \"github.com/rs/zerolog\"\n\n// FutureLog is an intermediate type for log messages. It is used before the config was loaded because without loaded\n// config we do not know the log level, so we log these messages once the config was initialized.\ntype FutureLog struct {\n\tLevel zerolog.Level\n\tMsg   string\n}\n\nfunc futureFatal(msg string) FutureLog {\n\treturn FutureLog{\n\t\tLevel: zerolog.FatalLevel,\n\t\tMsg:   msg,\n\t}\n}\n"
  },
  {
    "path": "config/ip.go",
    "content": "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 parseIPProvider(ips []string, config string) (ipdns.Provider, []FutureLog) {\n\tif len(ips) == 0 {\n\t\tpanic(\"must have at least one ip\")\n\t}\n\n\tfirst := ips[0]\n\tif strings.HasPrefix(first, \"dns:\") {\n\t\tif len(ips) > 1 {\n\t\t\treturn nil, []FutureLog{futureFatal(fmt.Sprintf(\"invalid %s: when dns server is specified, only one value is allowed\", config))}\n\t\t}\n\n\t\treturn parseDNS(strings.TrimPrefix(first, \"dns:\")), nil\n\t}\n\n\treturn parseStatic(ips, config)\n}\n\nfunc parseStatic(ips []string, config string) (*ipdns.Static, []FutureLog) {\n\tvar static ipdns.Static\n\n\tfirstV4, errs := applyIPTo(config, ips[0], &static)\n\tif errs != nil {\n\t\treturn nil, errs\n\t}\n\n\tif len(ips) == 1 {\n\t\treturn &static, nil\n\t}\n\n\tsecondV4, errs := applyIPTo(config, ips[1], &static)\n\tif errs != nil {\n\t\treturn nil, errs\n\t}\n\n\tif firstV4 == secondV4 {\n\t\treturn nil, []FutureLog{futureFatal(fmt.Sprintf(\"invalid %s: the ips must be of different type ipv4/ipv6\", config))}\n\t}\n\n\tif len(ips) > 2 {\n\t\treturn nil, []FutureLog{futureFatal(fmt.Sprintf(\"invalid %s: too many ips supplied\", config))}\n\t}\n\n\treturn &static, nil\n}\n\nfunc applyIPTo(config, ip string, static *ipdns.Static) (bool, []FutureLog) {\n\tparsed := net.ParseIP(ip)\n\tif parsed == nil || ip == \"0.0.0.0\" {\n\t\treturn false, []FutureLog{futureFatal(fmt.Sprintf(\"invalid %s: %s\", config, ip))}\n\t}\n\n\tv4 := parsed.To4() != nil\n\tif v4 {\n\t\tstatic.V4 = parsed\n\t} else {\n\t\tstatic.V6 = parsed\n\t}\n\treturn v4, nil\n}\n\nfunc parseDNS(dnsString string) *ipdns.DNS {\n\tvar dns ipdns.DNS\n\n\tparts := strings.SplitN(dnsString, \"@\", 2)\n\n\tdns.Domain = parts[0]\n\tdns.DNS = \"system\"\n\tif len(parts) == 2 {\n\t\tdns.DNS = parts[1]\n\t\tdns.Resolver = &net.Resolver{\n\t\t\tPreferGo: true,\n\t\t\tDial: func(ctx context.Context, network, address string) (net.Conn, error) {\n\t\t\t\td := net.Dialer{Timeout: 10 * time.Second}\n\t\t\t\treturn d.DialContext(ctx, network, parts[1])\n\t\t\t},\n\t\t}\n\t}\n\n\treturn &dns\n}\n"
  },
  {
    "path": "config/ipdns/dns.go",
    "content": "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 struct {\n\tsync.Mutex\n\n\tDNS      string\n\tResolver *net.Resolver\n\tDomain   string\n\n\trefetch time.Time\n\tv4      net.IP\n\tv6      net.IP\n\terr     error\n}\n\nfunc (s *DNS) Get() (net.IP, net.IP, error) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tif s.refetch.Before(time.Now()) {\n\t\toldV4, oldV6 := s.v4, s.v6\n\t\ts.v4, s.v6, s.err = s.lookup()\n\t\tif s.err == nil {\n\t\t\tif !oldV4.Equal(s.v4) || !oldV6.Equal(s.v6) {\n\t\t\t\tlog.Info().Str(\"v4\", s.v4.String()).\n\t\t\t\t\tStr(\"v6\", s.v6.String()).\n\t\t\t\t\tStr(\"domain\", s.Domain).\n\t\t\t\t\tStr(\"dns\", s.DNS).\n\t\t\t\t\tMsg(\"DNS External IP\")\n\t\t\t}\n\t\t\ts.refetch = time.Now().Add(time.Minute)\n\t\t} else {\n\t\t\t// don't spam the dns server\n\t\t\ts.refetch = time.Now().Add(time.Second)\n\t\t\tlog.Err(s.err).Str(\"domain\", s.Domain).Str(\"dns\", s.DNS).Msg(\"DNS External IP\")\n\t\t}\n\t}\n\n\treturn s.v4, s.v6, s.err\n}\n\nfunc (s *DNS) lookup() (net.IP, net.IP, error) {\n\tips, err := s.Resolver.LookupIP(context.Background(), \"ip\", s.Domain)\n\tif err != nil {\n\t\tif dns, ok := err.(*net.DNSError); ok && s.DNS != \"system\" {\n\t\t\tdns.Server = \"\"\n\t\t}\n\t\treturn nil, nil, err\n\t}\n\n\tvar v4, v6 net.IP\n\tfor _, ip := range ips {\n\t\tisV6 := strings.Contains(ip.String(), \":\")\n\t\tif isV6 && v6 == nil {\n\t\t\tv6 = ip\n\t\t} else if !isV6 && v4 == nil {\n\t\t\tv4 = ip\n\t\t}\n\t}\n\n\tif v4 == nil && v6 == nil {\n\t\treturn nil, nil, errors.New(\"dns record doesn't have an A or AAAA record\")\n\t}\n\n\treturn v4, v6, nil\n}\n"
  },
  {
    "path": "config/ipdns/provider.go",
    "content": "package ipdns\n\nimport \"net\"\n\ntype Provider interface {\n\tGet() (net.IP, net.IP, error)\n}\n"
  },
  {
    "path": "config/ipdns/static.go",
    "content": "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) {\n\treturn s.V4, s.V6, nil\n}\n"
  },
  {
    "path": "config/loglevel.go",
    "content": "package config\n\nimport (\n\t\"errors\"\n\n\t\"github.com/rs/zerolog\"\n)\n\n// LogLevel type that provides helper methods for decoding.\ntype LogLevel zerolog.Level\n\n// Decode decodes a string to a log level.\nfunc (ll *LogLevel) Decode(value string) error {\n\tif level, err := zerolog.ParseLevel(value); err == nil {\n\t\t*ll = LogLevel(level)\n\t\treturn nil\n\t}\n\t*ll = LogLevel(zerolog.InfoLevel)\n\treturn errors.New(\"unknown log level\")\n}\n\n// AsZeroLogLevel converts the LogLevel to a zerolog.Level.\nfunc (ll LogLevel) AsZeroLogLevel() zerolog.Level {\n\treturn zerolog.Level(ll)\n}\n"
  },
  {
    "path": "config/loglevel_test.go",
    "content": "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_Decode_success(t *testing.T) {\n\tll := new(LogLevel)\n\terr := ll.Decode(\"fatal\")\n\tassert.Nil(t, err)\n\tassert.Equal(t, ll.AsZeroLogLevel(), zerolog.FatalLevel)\n}\n\nfunc TestLogLevel_Decode_fail(t *testing.T) {\n\tll := new(LogLevel)\n\terr := ll.Decode(\"asdasdasdasdasdasd\")\n\tassert.EqualError(t, err, \"unknown log level\")\n\tassert.Equal(t, ll.AsZeroLogLevel(), zerolog.InfoLevel)\n}\n"
  },
  {
    "path": "config/mode/mode.go",
    "content": "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 mode = Dev\n\n// Set sets the new mode.\nfunc Set(newMode string) {\n\tmode = newMode\n}\n\n// Get returns the current mode.\nfunc Get() string {\n\treturn mode\n}\n"
  },
  {
    "path": "config/mode/mode_test.go",
    "content": "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\trequire.Equal(t, Prod, Get())\n}\n\nfunc TestSet(t *testing.T) {\n\tSet(Prod)\n\trequire.Equal(t, Prod, mode)\n}\n"
  },
  {
    "path": "docs/.nojekyll",
    "content": ""
  },
  {
    "path": "docs/CNAME",
    "content": "screego.net\n"
  },
  {
    "path": "docs/README.md",
    "content": "# screego/server\r\n\r\nIn the past I've had some problems sharing my screen with coworkers using\r\ncorporate chatting solutions like Microsoft Teams. I wanted to show them some\r\nof my code, but either the stream lagged several seconds behind or the quality\r\nwas so poor that my colleagues couldn't read the code. Or both.\r\n\r\nThat's why I created screego. It allows you to share your screen with good\r\nquality and low latency. Screego is an addition to existing software and \r\nonly helps to share your screen. Nothing else (:.\r\n\r\n\r\n## Features\r\n\r\n* Multi User Screenshare\r\n* Secure transfer via WebRTC\r\n* Low latency / High resolution\r\n* Simple Install via [Docker](https://hub.docker.com/r/screego/server) / single binary\r\n* Integrated [TURN](nat-traversal.md) Server see [NAT Traversal](nat-traversal.md)\r\n\r\n---\r\n\r\n[Demo / Public Instance](https://app.screego.net/) ᛫ [Installation](https://screego.net/#/install) ᛫ [Configuration](https://screego.net/#/config) \r\n"
  },
  {
    "path": "docs/_sidebar.md",
    "content": "* [Home](/)\n* [Installation](install.md)\n* [Config](config.md)\n* [NAT Traversal](nat-traversal.md)\n* [Reverse Proxy](proxy.md)\n* [Development](development.md)\n* [FAQ](faq.md)\n* [GitHub](https://github.com/screego/server)\n"
  },
  {
    "path": "docs/config.md",
    "content": "# Config\n\n!> TLS is required for Screego to work. Either enable TLS inside Screego or \n   use a reverse proxy to serve Screego via TLS.\n\nScreego tries to obtain config values from different locations in sequence. \nProperties will never be overridden. Thus, the first occurrence of a setting will be used.\n\n#### Order\n\n* Environment Variables\n* `screego.config.local` (in same path as the binary)\n* `screego.config` (in same path as the binary)\n* `$HOME/.config/screego/server.config`\n* `/etc/screego/server.config`\n\n#### Config Example\n\n[screego.config.example](https://raw.githubusercontent.com/screego/server/master/screego.config.example ':include :type=code ini')\n"
  },
  {
    "path": "docs/development.md",
    "content": "# 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 source from git:\n\n```bash\n$ git clone https://github.com/screego/server.git && cd server\n```\n\n### GOPATH\n\nIf you are in GOPATH, enable [go modules](https://github.com/golang/go/wiki/Modules) explicitly:\n\n```bash\n$ export GO111MODULE=on\n```\n\n### Download Dependencies:\n\n```bash\n# Server\n$ go mod download\n# UI\n$ (cd ui && yarn install)\n```\n\n## Start / Linting\n\n### Backend\n\nCreate a file named `screego.config.development.local` inside the screego folder with the content:\n\n```ini\nSCREEGO_EXTERNAL_IP=YOURIP\n```\n\nand replace `YOURIP` with your external ip.\n\nStart the server in development mode.\n\n```bash\n$ go run . serve\n```\n\nThe backend is available on [http://localhost:5050](http://localhost:5050)\n\n?> When accessing `localhost:5050` it is normal that there are panics with `no such file or directory`.\nThe UI will be started separately.\n\n### Frontend\n\nStart the UI development server.\n\n_Commands must be executed inside the ui directory._\n\n```bash\n$ yarn start\n```\n\nOpen [http://localhost:3000](http://localhost:3000) inside your favorite browser.\n\n### Lint\n\nScreego uses [golangci-lint](https://github.com/golangci/golangci-lint) for linting.\n\nAfter installation you can check the source code with:\n\n```bash\n$ golangci-lint run\n```\n\n## Build\n\n1. [Setup](#setup)\n\n1. Build the UI\n\n   ```bash\n   $ (cd ui && yarn build)\n   ```\n\n1. Build the binary\n   ```bash\n   go build -ldflags \"-X main.version=$(git describe --tags HEAD) -X main.mode=prod\" -o screego ./main.go\n   ```\n"
  },
  {
    "path": "docs/faq.md",
    "content": "# Frequently Asked Questions\n\n## Stream doesn't load\n\nCheck that\n* you are using https to access Screego.\n* `SCREEGO_EXTERNAL_IP` is set to your external IP. See [Configuration](config.md)\n* 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*\n* your browser doesn't block WebRTC (extensions or other settings)\n* you have opened ports in your firewall. By default 5050, 3478 and any UDP port when using TURN.\n\n## Automatically create room on join\n\nSometimes you want to reuse the screego room, but always have to recreate it.\nBy passing `create=true` in the url, you can automatically create the room if it does not exist.\n\nExample: https://app.screego.net/?room=not-existing-room&create=true\n"
  },
  {
    "path": "docs/index.html",
    "content": "<!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=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\"/>\r\n    <meta name=\"description\" content=\"Screego - open source screen sharing for developers\">\r\n    <meta name=\"viewport\"\r\n          content=\"width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0\">\r\n    <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/docsify-themeable@0/dist/css/theme-simple-dark.css\">\r\n    <link rel=\"apple-touch-icon\" sizes=\"180x180\" href=\"/apple-touch-icon.png\">\r\n    <link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"/favicon-32x32.png\">\r\n    <link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"/favicon-16x16.png\">\r\n    <meta name=\"theme-color\" content=\"#ffffff\">\r\n    <style>\r\n        .markdown-section h1 {\r\n            border-width: 0;\r\n        }\r\n    </style>\r\n</head>\r\n<body>\r\n<div id=\"app\"></div>\r\n<script>\r\n    const ghVersion = fetch('https://api.github.com/repos/screego/server/tags').then(resp => resp.json()).then(data => data[0].name.slice(1))\r\n    window.$docsify = {\r\n        name: 'screego',\r\n        repo: 'screego/server',\r\n        logo: '/logo.png',\r\n        loadSidebar: true,\r\n        autoHeader: true,\r\n        maxLevel: 4,\r\n        subMaxLevel: 2,\r\n        plugins: [\r\n            function (hook) {\r\n                hook.afterEach(function (html, next) {\r\n                    ghVersion.then((version) => next(html.replace(/GITHUB_VERSION/g, version)))\r\n                })\r\n            }\r\n        ]\r\n    }\r\n</script>\r\n<script src=\"//cdn.jsdelivr.net/npm/docsify/lib/docsify.min.js\"></script>\r\n<script src=\"https://cdn.jsdelivr.net/npm/docsify-themeable@0\"></script>\r\n<script src=\"//cdn.jsdelivr.net/npm/docsify/lib/plugins/search.min.js\"></script>\r\n<script src=\"https://cdn.jsdelivr.net/npm/docsify-tabs@1\"></script>\r\n<script src=\"https://cdn.jsdelivr.net/npm/prismjs@1.21.0/components/prism-yaml.js\"></script>\r\n<script src=\"https://cdn.jsdelivr.net/npm/prismjs@1.21.0/components/prism-ini.js\"></script>\r\n<script src=\"https://cdn.jsdelivr.net/npm/prismjs@1.21.0/components/prism-bash.js\"></script>\r\n<script src=\"https://cdn.jsdelivr.net/npm/prismjs@1.21.0/components/prism-nginx.js\"></script>\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "docs/install.md",
    "content": "# Installation\n\nLatest Version: **GITHUB_VERSION**\n\nBefore starting Screego you may read [Configuration](config.md).\n\n!> TLS is required for Screego to work. Either enable TLS inside Screego or \n   use a reverse proxy to serve Screego via TLS.\n\n## Docker\n\nSetting up Screego with docker is pretty easy, you basically just have to start the docker container, and you are ready to go:\n\n[ghcr.io/screego/server](https://github.com/orgs/screego/packages/container/package/server) and\n[screego/server](https://hub.docker.com/r/screego/server)\ndocker images are multi-arch docker images.\nThis means the image will work for `amd64`, `i386`, `ppc64le` (power pc), `arm64`, `armv7` (Raspberry PI) and `armv6`.\n\nBy default, Screego runs on port 5050.\n\n?> Replace `EXTERNALIP` with your external IP. One way to find your external ip is with ipify.\n   `curl 'https://api.ipify.org'`\n\n```bash\n$ docker run --net=host -e SCREEGO_EXTERNAL_IP=EXTERNALIP ghcr.io/screego/server:GITHUB_VERSION\n```\n\n**docker-compose.yml**\n```yaml\nservices:\n  screego:\n    image: ghcr.io/screego/server:GITHUB_VERSION\n    network_mode: host\n    environment:\n      SCREEGO_EXTERNAL_IP: \"EXTERNALIP\"\n```\n\nIf you don't want to use the host network, then you can configure docker like this:\n\n<details><summary>(Click to expand)</summary>\n<p>\n\n!> Screego may not work correctly when deploying it in docker without `network_mode: host`.\n   See [#226](https://github.com/screego/server/issues/226)\n\n```bash\n$ docker run -it \\\n    -e SCREEGO_EXTERNAL_IP=EXTERNALIP \\\n    -e SCREEGO_TURN_PORT_RANGE=50000:50200 \\\n    -p 5050:5050 \\\n    -p 3478:3478 \\\n    -p 50000-50200:50000-50200/udp \\\n    screego/server:GITHUB_VERSION\n```\n\n#### docker-compose.yml\n\n```yml\nversion: \"3.7\"\nservices:\n  screego:\n    image: ghcr.io/screego/server:GITHUB_VERSION\n    ports:\n      - 5050:5050\n      - 3478:3478\n      - 50000-50200:50000-50200/udp\n    environment:\n      SCREEGO_EXTERNAL_IP: \"192.168.178.2\"\n      SCREEGO_TURN_PORT_RANGE: \"50000:50200\"\n```\n\n</p>\n</details>\n\n## Binary\n\n### Supported Platforms:\n\n- linux_amd64 (64bit)\n- linux_i386 (32bit)\n- armv7 (32bit used for Raspberry Pi)\n- armv6\n- arm64 (ARMv8)\n- ppc64\n- ppc64le\n- windows_i386.exe (32bit)\n- windows_amd64.exe (64bit)\n\nDownload the zip with the binary for your platform from [screego/server Releases](https://github.com/screego/server/releases).\n\n```bash\n$ wget https://github.com/screego/server/releases/download/vGITHUB_VERSION/screego_GITHUB_VERSION_{PLATFORM}.tar.gz\n```\n\nUnzip the archive.\n\n```bash\n$ tar xvf screego_GITHUB_VERSION_{PLATFORM}.tar.gz\n```\n\nMake the binary executable (linux only).\n\n```bash\n$ chmod +x screego\n```\n\nExecute screego:\n\n```bash\n$ ./screego\n# on windows\n$ screego.exe\n```\n\n## Arch-Linux(aur)\n\n!> Maintenance of the AUR Packages is not performed by the Screego team.\n   You should always check the PKGBUILD before installing an AUR package.\n\nScreego'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/).\nThe development-version can be installed with [screego-server-git](https://aur.archlinux.org/packages/screego-server-git/).\n\n## FreeBSD\n\n!> Maintenance of the FreeBSD Package is not performed by the Screego team.\n   Check yourself, if you can trust it.\n\n```bash\n$ pkg install screego\n```\n\n## Source\n\n[See Development#build](development.md#build)\n"
  },
  {
    "path": "docs/nat-traversal.md",
    "content": "# NAT Traversal\n\nIn most cases peers cannot directly communicate with each other because of firewalls or other restrictions like NAT.\nTo work around this issue, WebRTC uses \n[Interactive Connectivity Establishment (ICE)](http://en.wikipedia.org/wiki/Interactive_Connectivity_Establishment).\nThis is a framework for helping to connect peers.\n\nICE uses STUN and/or TURN servers to accomplish this.\n\n?> Screego exposes a STUN and TURN server. You don't have to configure this separately.\n   By default, user authentication is required for using TURN.\n\n## STUN\n\n[Session Traversal Utilities for NAT (STUN)](http://en.wikipedia.org/wiki/STUN) is used to find\nthe public / external ip of a peer. This IP is later sent to others to create a direct connection.\n\nWhen STUN is used, only the connection enstablishment will be done through Screego. The actual video stream will be\ndirectly sent to the other peer and doesn't go through Screego.\n\nWhile STUN should work for most cases, there are stricter NATs f.ex. \n[Symmetric NATs](https://en.wikipedia.org/wiki/Network_address_translation) \nwhere it doesn't, then, TURN will be used.\n\n## TURN\n\n[Traversal Using Relays around NAT (TURN)](http://en.wikipedia.org/wiki/TURN) is used to work around Symmetric NATs.\nIt does it by relaying all data through a TURN server. As relaying will create traffic on the server,\nScreego will require user authentication to use the TURN server. This can be configured see [Configuration](config.md).\n\n"
  },
  {
    "path": "docs/proxy.md",
    "content": "# Proxy\n\n!> When using a proxy enable `SCREEGO_TRUST_PROXY_HEADERS`. See [Configuration](config.md).\n\n## nginx\n\n### At root path\n\n```nginx\nupstream screego {\n  # Set this to the address configured in\n  # SCREEGO_SERVER_ADDRESS. Default 5050\n  server 127.0.0.1:5050;\n}\n\nserver {\n  listen 80;\n\n  # Here goes your domain / subdomain\n  server_name screego.example.com;\n\n  location / {\n    # Proxy to screego\n    proxy_pass         http://screego;\n    proxy_http_version 1.1;\n\n    # Set headers for proxying WebSocket\n    proxy_set_header   Upgrade $http_upgrade;\n    proxy_set_header   Connection \"upgrade\";\n    proxy_redirect     http:// $scheme://;\n\n    # Set proxy headers\n    proxy_set_header   X-Real-IP $remote_addr;\n    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;\n    proxy_set_header   X-Forwarded-Proto http;\n\n    # The proxy must preserve the host because screego verifies it with the origin\n    # for WebSocket connections\n    proxy_set_header   Host $http_host;\n  }\n}\n```\n\n### At a sub path\n\n```nginx\nupstream screego {\n  # Set this to the address configured in\n  # SCREEGO_SERVER_ADDRESS. Default 5050\n  server 127.0.0.1:5050;\n}\n\nserver {\n  listen 80;\n\n  # Here goes your domain / subdomain\n  server_name screego.example.com;\n\n  location /screego/ {\n    rewrite ^/screego(/.*) $1 break;\n  \n    # Proxy to screego\n    proxy_pass         http://screego;\n    proxy_http_version 1.1;\n\n    # Set headers for proxying WebSocket\n    proxy_set_header   Upgrade $http_upgrade;\n    proxy_set_header   Connection \"upgrade\";\n    proxy_redirect     http:// $scheme://;\n\n    # Set proxy headers\n    proxy_set_header   X-Real-IP $remote_addr;\n    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;\n    proxy_set_header   X-Forwarded-Proto http;\n\n    # The proxy must preserve the host because screego verifies it with the origin\n    # for WebSocket connections\n    proxy_set_header   Host $http_host;\n  }\n}\n```\n\n## Apache (httpd)\n\nThe following modules are required:\n\n* mod_proxy\n* mod_proxy_wstunnel\n* mod_proxy_http\n\n### At root path\n\n```apache\n<VirtualHost *:80>\n    ServerName screego.example.com\n    Keepalive On\n\n    # The proxy must preserve the host because screego verifies it with the origin\n    # for WebSocket connections\n    ProxyPreserveHost On\n\n    # Replace 5050 with the port defined in SCREEGO_SERVER_ADDRESS.\n    # Default 5050\n\n    # Proxy web socket requests to /stream\n    ProxyPass \"/stream\" ws://127.0.0.1:5050/stream retry=0 timeout=5\n\n    # Proxy all other requests to /\n    ProxyPass \"/\" http://127.0.0.1:5050/ retry=0 timeout=5\n\n    ProxyPassReverse / http://127.0.0.1:5050/\n</VirtualHost>\n```\n\n### At a sub path\n\n```apache\n<VirtualHost *:80>\n    ServerName screego.example.com\n    Keepalive On\n\n    Redirect 301 \"/screego\" \"/screego/\"\n\n    # The proxy must preserve the host because screego verifies it with the origin\n    # for WebSocket connections\n    ProxyPreserveHost On\n\n    # Proxy web socket requests to /stream\n    ProxyPass \"/screego/stream\" ws://127.0.0.1:5050/stream retry=0 timeout=5\n\n    # Proxy all other requests to /\n    ProxyPass \"/screego/\" http://127.0.0.1:5050/ retry=0 timeout=5\n    #                 ^- !!trailing slash is required!!\n\n    ProxyPassReverse /screego/ http://127.0.0.1:5050/\n</VirtualHost>\n```\n"
  },
  {
    "path": "go.mod",
    "content": "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.com/gorilla/mux v1.8.1\n\tgithub.com/gorilla/sessions v1.4.0\n\tgithub.com/gorilla/websocket v1.5.3\n\tgithub.com/joho/godotenv v1.5.1\n\tgithub.com/kelseyhightower/envconfig v1.4.0\n\tgithub.com/pion/randutil v0.1.0\n\tgithub.com/pion/turn/v4 v4.1.3\n\tgithub.com/prometheus/client_golang v1.23.2\n\tgithub.com/rs/xid v1.6.0\n\tgithub.com/rs/zerolog v1.34.0\n\tgithub.com/stretchr/testify v1.11.1\n\tgithub.com/urfave/cli v1.22.17\n\tgolang.org/x/crypto v0.46.0\n\tgolang.org/x/term v0.38.0\n\tgolang.org/x/text v0.32.0\n)\n\nrequire (\n\tgithub.com/beorn7/perks v1.0.1 // indirect\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/cpuguy83/go-md2man/v2 v2.0.7 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/felixge/httpsnoop v1.0.3 // indirect\n\tgithub.com/gorilla/securecookie v1.1.2 // indirect\n\tgithub.com/klauspost/compress v1.18.0 // indirect\n\tgithub.com/kr/text v0.2.0 // indirect\n\tgithub.com/mattn/go-colorable v0.1.13 // indirect\n\tgithub.com/mattn/go-isatty v0.0.19 // indirect\n\tgithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect\n\tgithub.com/pion/dtls/v3 v3.0.7 // indirect\n\tgithub.com/pion/logging v0.2.4 // indirect\n\tgithub.com/pion/stun/v3 v3.0.1 // indirect\n\tgithub.com/pion/transport/v3 v3.1.1 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/prometheus/client_model v0.6.2 // indirect\n\tgithub.com/prometheus/common v0.66.1 // indirect\n\tgithub.com/prometheus/procfs v0.16.1 // indirect\n\tgithub.com/russross/blackfriday/v2 v2.1.0 // indirect\n\tgithub.com/wlynxg/anet v0.0.5 // indirect\n\tgo.yaml.in/yaml/v2 v2.4.2 // indirect\n\tgolang.org/x/sys v0.39.0 // indirect\n\tgoogle.golang.org/protobuf v1.36.8 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n"
  },
  {
    "path": "go.sum",
    "content": "github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=\ngithub.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=\ngithub.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=\ngithub.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=\ngithub.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=\ngithub.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4=\ngithub.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=\ngithub.com/cpuguy83/go-md2man/v2 v2.0.5 h1:ZtcqGrnekaHpVLArFSe4HK5DoKx1T0rq2DwVB0alcyc=\ngithub.com/cpuguy83/go-md2man/v2 v2.0.5/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=\ngithub.com/cpuguy83/go-md2man/v2 v2.0.7 h1:zbFlGlXEAKlwXpmvle3d8Oe3YnkKIK4xSRTd3sHPnBo=\ngithub.com/cpuguy83/go-md2man/v2 v2.0.7/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=\ngithub.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk=\ngithub.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=\ngithub.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=\ngithub.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=\ngithub.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=\ngithub.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE=\ngithub.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w=\ngithub.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=\ngithub.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=\ngithub.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=\ngithub.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=\ngithub.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=\ngithub.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=\ngithub.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=\ngithub.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=\ngithub.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=\ngithub.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=\ngithub.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dvMUtDTo2cv8=\ngithub.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg=\ngithub.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=\ngithub.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=\ngithub.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=\ngithub.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=\ngithub.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=\ngithub.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=\ngithub.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=\ngithub.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=\ngithub.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=\ngithub.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=\ngithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=\ngithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=\ngithub.com/pion/dtls/v3 v3.0.2 h1:425DEeJ/jfuTTghhUDW0GtYZYIwwMtnKKJNMcWccTX0=\ngithub.com/pion/dtls/v3 v3.0.2/go.mod h1:dfIXcFkKoujDQ+jtd8M6RgqKK3DuaUilm3YatAbGp5k=\ngithub.com/pion/dtls/v3 v3.0.7 h1:bItXtTYYhZwkPFk4t1n3Kkf5TDrfj6+4wG+CZR8uI9Q=\ngithub.com/pion/dtls/v3 v3.0.7/go.mod h1:uDlH5VPrgOQIw59irKYkMudSFprY9IEFCqz/eTz16f8=\ngithub.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY=\ngithub.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms=\ngithub.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=\ngithub.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=\ngithub.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=\ngithub.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=\ngithub.com/pion/stun/v3 v3.0.0 h1:4h1gwhWLWuZWOJIJR9s2ferRO+W3zA/b6ijOI6mKzUw=\ngithub.com/pion/stun/v3 v3.0.0/go.mod h1:HvCN8txt8mwi4FBvS3EmDghW6aQJ24T+y+1TKjB5jyU=\ngithub.com/pion/stun/v3 v3.0.1 h1:jx1uUq6BdPihF0yF33Jj2mh+C9p0atY94IkdnW174kA=\ngithub.com/pion/stun/v3 v3.0.1/go.mod h1:RHnvlKFg+qHgoKIqtQWMOJF52wsImCAf/Jh5GjX+4Tw=\ngithub.com/pion/transport/v3 v3.0.7 h1:iRbMH05BzSNwhILHoBoAPxoB9xQgOaJk+591KC9P1o0=\ngithub.com/pion/transport/v3 v3.0.7/go.mod h1:YleKiTZ4vqNxVwh77Z0zytYi7rXHl7j6uPLGhhz9rwo=\ngithub.com/pion/transport/v3 v3.1.1 h1:Tr684+fnnKlhPceU+ICdrw6KKkTms+5qHMgw6bIkYOM=\ngithub.com/pion/transport/v3 v3.1.1/go.mod h1:+c2eewC5WJQHiAA46fkMMzoYZSuGzA/7E2FPrOYHctQ=\ngithub.com/pion/turn/v4 v4.0.0 h1:qxplo3Rxa9Yg1xXDxxH8xaqcyGUtbHYw4QSCvmFWvhM=\ngithub.com/pion/turn/v4 v4.0.0/go.mod h1:MuPDkm15nYSklKpN8vWJ9W2M0PlyQZqYt1McGuxG7mA=\ngithub.com/pion/turn/v4 v4.1.3 h1:jVNW0iR05AS94ysEtvzsrk3gKs9Zqxf6HmnsLfRvlzA=\ngithub.com/pion/turn/v4 v4.1.3/go.mod h1:TD/eiBUf5f5LwXbCJa35T7dPtTpCHRJ9oJWmyPLVT3A=\ngithub.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/prometheus/client_golang v1.20.4 h1:Tgh3Yr67PaOv/uTqloMsCEdeuFTatm5zIq5+qNN23vI=\ngithub.com/prometheus/client_golang v1.20.4/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE=\ngithub.com/prometheus/client_golang v1.20.5 h1:cxppBPuYhUnsO6yo/aoRol4L7q7UFfdm+bR9r+8l63Y=\ngithub.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE=\ngithub.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q=\ngithub.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0=\ngithub.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=\ngithub.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=\ngithub.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=\ngithub.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=\ngithub.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=\ngithub.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=\ngithub.com/prometheus/common v0.55.0 h1:KEi6DK7lXW/m7Ig5i47x0vRzuBsHuvJdi5ee6Y3G1dc=\ngithub.com/prometheus/common v0.55.0/go.mod h1:2SECS4xJG1kd8XF9IcM1gMX6510RAEL65zxzNImwdc8=\ngithub.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io=\ngithub.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I=\ngithub.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=\ngithub.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=\ngithub.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=\ngithub.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=\ngithub.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=\ngithub.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=\ngithub.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=\ngithub.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=\ngithub.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=\ngithub.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=\ngithub.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=\ngithub.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=\ngithub.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=\ngithub.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=\ngithub.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=\ngithub.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=\ngithub.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=\ngithub.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=\ngithub.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=\ngithub.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=\ngithub.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=\ngithub.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=\ngithub.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngithub.com/urfave/cli v1.22.15 h1:nuqt+pdC/KqswQKhETJjo7pvn/k4xMUxgW6liI7XpnM=\ngithub.com/urfave/cli v1.22.15/go.mod h1:wSan1hmo5zeyLGBjRJbzRTNk8gwoYa2B9n4q9dmRIc0=\ngithub.com/urfave/cli v1.22.16 h1:MH0k6uJxdwdeWQTwhSO42Pwr4YLrNLwBtg1MRgTqPdQ=\ngithub.com/urfave/cli v1.22.16/go.mod h1:EeJR6BKodywf4zciqrdw6hpCPk68JO9z5LazXZMn5Po=\ngithub.com/urfave/cli v1.22.17 h1:SYzXoiPfQjHBbkYxbew5prZHS1TOLT3ierW8SYLqtVQ=\ngithub.com/urfave/cli v1.22.17/go.mod h1:b0ht0aqgH/6pBYzzxURyrM4xXNgsoT/n2ZzwQiEhNVo=\ngithub.com/wlynxg/anet v0.0.4 h1:0de1OFQxnNqAu+x2FAKKCVIrnfGKQbs7FQz++tB0+Uw=\ngithub.com/wlynxg/anet v0.0.4/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=\ngithub.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=\ngithub.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=\ngo.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=\ngo.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=\ngolang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A=\ngolang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70=\ngolang.org/x/crypto v0.30.0 h1:RwoQn3GkWiMkzlX562cLB7OxWvjH1L8xutO2WoJcRoY=\ngolang.org/x/crypto v0.30.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=\ngolang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=\ngolang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=\ngolang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=\ngolang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=\ngolang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys=\ngolang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE=\ngolang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=\ngolang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=\ngolang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=\ngolang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=\ngolang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=\ngolang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=\ngolang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=\ngolang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=\ngolang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=\ngolang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=\ngolang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=\ngolang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/term v0.24.0 h1:Mh5cbb+Zk2hqqXNO7S1iTjEphVL+jb8ZWaqh/g+JWkM=\ngolang.org/x/term v0.24.0/go.mod h1:lOBK/LVxemqiMij05LGJ0tzNr8xlmwBRJ81PX6wVLH8=\ngolang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q=\ngolang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=\ngolang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o=\ngolang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw=\ngolang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q=\ngolang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg=\ngolang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224=\ngolang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=\ngolang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=\ngolang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=\ngolang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=\ngolang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=\ngolang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=\ngolang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=\ngolang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=\ngoogle.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=\ngoogle.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=\ngoogle.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM=\ngoogle.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=\ngoogle.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=\ngoogle.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=\ngopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "logger/logger.go",
    "content": "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 logger.\nfunc Init(lvl zerolog.Level) {\n\tlog.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}).Level(lvl)\n\tlog.Debug().Msg(\"Logger initialized\")\n}\n"
  },
  {
    "path": "main.go",
    "content": "package main\n\nimport (\n\t\"github.com/screego/server/cmd\"\n\tpmode \"github.com/screego/server/config/mode\"\n)\n\nvar (\n\tversion    = \"unknown\"\n\tcommitHash = \"unknown\"\n\tmode       = pmode.Dev\n)\n\nfunc main() {\n\tpmode.Set(mode)\n\tcmd.Run(version, commitHash)\n}\n"
  },
  {
    "path": "router/router.go",
    "content": "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\t\"github.com/prometheus/client_golang/prometheus/promhttp\"\n\t\"github.com/rs/zerolog/hlog\"\n\t\"github.com/rs/zerolog/log\"\n\t\"github.com/screego/server/auth\"\n\t\"github.com/screego/server/config\"\n\t\"github.com/screego/server/ui\"\n\t\"github.com/screego/server/ws\"\n)\n\ntype Health struct {\n\tStatus  string `json:\"status\"`\n\tClients int    `json:\"clients\"`\n\tReason  string `json:\"reason,omitempty\"`\n}\n\ntype UIConfig struct {\n\tAuthMode                 string `json:\"authMode\"`\n\tUser                     string `json:\"user\"`\n\tLoggedIn                 bool   `json:\"loggedIn\"`\n\tVersion                  string `json:\"version\"`\n\tRoomName                 string `json:\"roomName\"`\n\tCloseRoomWhenOwnerLeaves bool   `json:\"closeRoomWhenOwnerLeaves\"`\n}\n\nfunc Router(conf config.Config, rooms *ws.Rooms, users *auth.Users, version string) *mux.Router {\n\trouter := mux.NewRouter()\n\trouter.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t// https://github.com/gorilla/mux/issues/416\n\t\taccessLogger(r, 404, 0, 0)\n\t})\n\trouter.Use(hlog.AccessHandler(accessLogger))\n\trouter.Use(handlers.CORS(handlers.AllowedMethods([]string{\"GET\", \"POST\"}), handlers.AllowedOriginValidator(conf.CheckOrigin)))\n\trouter.HandleFunc(\"/stream\", rooms.Upgrade)\n\trouter.Methods(\"POST\").Path(\"/login\").HandlerFunc(users.Authenticate)\n\trouter.Methods(\"POST\").Path(\"/logout\").HandlerFunc(users.Logout)\n\trouter.Methods(\"GET\").Path(\"/config\").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tuser, loggedIn := users.CurrentUser(r)\n\t\t_ = json.NewEncoder(w).Encode(&UIConfig{\n\t\t\tAuthMode:                 conf.AuthMode,\n\t\t\tLoggedIn:                 loggedIn,\n\t\t\tUser:                     user,\n\t\t\tVersion:                  version,\n\t\t\tRoomName:                 rooms.RandRoomName(),\n\t\t\tCloseRoomWhenOwnerLeaves: conf.CloseRoomWhenOwnerLeaves,\n\t\t})\n\t})\n\trouter.Methods(\"GET\").Path(\"/health\").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\ti, err := rooms.Count()\n\t\tstatus := \"up\"\n\t\tif err != \"\" {\n\t\t\tstatus = \"down\"\n\t\t\tw.WriteHeader(500)\n\t\t}\n\t\t_ = json.NewEncoder(w).Encode(Health{\n\t\t\tStatus:  status,\n\t\t\tClients: i,\n\t\t\tReason:  err,\n\t\t})\n\t})\n\tif conf.Prometheus {\n\t\tlog.Info().Msg(\"Prometheus enabled\")\n\t\trouter.Methods(\"GET\").Path(\"/metrics\").Handler(basicAuth(promhttp.Handler(), users))\n\t}\n\n\tui.Register(router)\n\n\treturn router\n}\n\nfunc accessLogger(r *http.Request, status, size int, dur time.Duration) {\n\tlog.Debug().\n\t\tStr(\"host\", r.Host).\n\t\tInt(\"status\", status).\n\t\tInt(\"size\", size).\n\t\tStr(\"ip\", r.RemoteAddr).\n\t\tStr(\"path\", r.URL.Path).\n\t\tStr(\"duration\", dur.String()).\n\t\tMsg(\"HTTP\")\n}\n\nfunc basicAuth(handler http.Handler, users *auth.Users) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tuser, pass, ok := r.BasicAuth()\n\n\t\tif !ok || !users.Validate(user, pass) {\n\t\t\tw.Header().Set(\"WWW-Authenticate\", `Basic realm=\"screego\"`)\n\t\t\tw.WriteHeader(401)\n\t\t\t_, _ = w.Write([]byte(\"Unauthorized.\\n\"))\n\t\t\treturn\n\t\t}\n\n\t\thandler.ServeHTTP(w, r)\n\t}\n}\n"
  },
  {
    "path": "screego.config.development",
    "content": "SCREEGO_SECRET=secure\nSCREEGO_LOG_LEVEL=debug\nSCREEGO_CORS_ALLOWED_ORIGINS=http://localhost:3000\nSCREEGO_USERS_FILE=./users\nSCREEGO_TURN_DENY_PEERS=\n"
  },
  {
    "path": "screego.config.example",
    "content": "# The external ip of the server.\n# When using a dual stack setup define both IPv4 & IPv6 separated by a comma.\n# Execute the following command on the server you want to host Screego\n# to find your external ip.\n#   curl 'https://api.ipify.org'\n# Example:\n#   SCREEGO_EXTERNAL_IP=192.168.178.2,2a01:c22:a87c:e500:2d8:61ff:fec7:f92a\n#\n# If the server doesn't have a static ip, the ip can be obtained via a domain:\n#   SCREEGO_EXTERNAL_IP=dns:app.screego.net\n# You can also specify the dns server to use\n#   SCREEGO_EXTERNAL_IP=dns:app.screego.net@9.9.9.9:53\nSCREEGO_EXTERNAL_IP=\n\n# A secret which should be unique. Is used for cookie authentication.\nSCREEGO_SECRET=\n\n# If TLS should be enabled for HTTP requests. Screego requires TLS,\n# you either have to enable this setting or serve TLS via a reverse proxy.\nSCREEGO_SERVER_TLS=false\n# The TLS cert file (only needed if TLS is enabled)\nSCREEGO_TLS_CERT_FILE=\n# The TLS key file (only needed if TLS is enabled)\nSCREEGO_TLS_KEY_FILE=\n\n# The address the http server will listen on.\n# Formats:\n# - host:port\n#   Example: 127.0.0.1:5050\n# - unix socket (must be prefixed with unix:)\n#   Example: unix:/my/file/path.socket\nSCREEGO_SERVER_ADDRESS=0.0.0.0:5050\n\n# The address the TURN server will listen on.\nSCREEGO_TURN_ADDRESS=0.0.0.0:3478\n\n# Limit the ports that TURN will use for data relaying.\n# Format: min:max\n# Example:\n#   50000:55000\nSCREEGO_TURN_PORT_RANGE=\n\n# If set, screego will not start TURN server and instead use an external TURN server.\n# When using a dual stack setup define both IPv4 & IPv6 separated by a comma.\n# Execute the following command on the server where you host TURN server\n# to find your external ip.\n#   curl 'https://api.ipify.org'\n# Example:\n#   SCREEGO_TURN_EXTERNAL_IP=192.168.178.2,2a01:c22:a87c:e500:2d8:61ff:fec7:f92a\n#\n# If the turn server doesn't have a static ip, the ip can be obtained via a domain:\n#   SCREEGO_TURN_EXTERNAL_IP=dns:turn.screego.net\n# You can also specify the dns server to use\n#   SCREEGO_TURN_EXTERNAL_IP=dns:turn.screego.net@9.9.9.9:53\nSCREEGO_TURN_EXTERNAL_IP=\n\n# The port the external TURN server listens on.\nSCREEGO_TURN_EXTERNAL_PORT=3478\n\n# Authentication secret for the external TURN server.\nSCREEGO_TURN_EXTERNAL_SECRET=\n\n# Deny/ban peers within specific CIDRs to prevent TURN server users from\n# accessing machines reachable by the TURN server but not from the internet,\n# useful when the server is behind a NAT.\n#\n# Disallow internal ip addresses: https://en.wikipedia.org/wiki/Reserved_IP_addresses\n# 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\n#\n# By default denies local addresses.\nSCREEGO_TURN_DENY_PEERS=0.0.0.0/8,127.0.0.1/8,::/128,::1/128,fe80::/10\n\n# If reverse proxy headers should be trusted.\n# Screego uses ip whitelisting for authentication\n# of TURN connections. When behind a proxy the ip is always the proxy server.\n# To still allow whitelisting this setting must be enabled and\n# the `X-Real-Ip` header must be set by the reverse proxy.\nSCREEGO_TRUST_PROXY_HEADERS=false\n\n# Defines when a user login is required\n# Possible values:\n#   all: User login is always required\n#   turn: User login is required for TURN connections\n#   none: User login is never required\nSCREEGO_AUTH_MODE=turn\n\n# Defines origins that will be allowed to access Screego (HTTP + WebSocket)\n# The default value is sufficient for most use-cases.\n# Example Value: https://screego.net,https://sub.gotify.net\nSCREEGO_CORS_ALLOWED_ORIGINS=\n\n# Defines the location of the users file.\n# File Format:\n#   user1:bcrypt_password_hash\n#   user2:bcrypt_password_hash\n#\n# Example:\n#   user1:$2a$12$WEfYCnWGk0PDzbATLTNiTuoZ7e/43v6DM/h7arOnPU6qEtFG.kZQy\n#\n# The user password pair can be created via\n#   screego hash --name \"user1\" --pass \"your password\"\nSCREEGO_USERS_FILE=\n\n# Defines how long a user session is valid in seconds.\n# 0 = session invalides after browser session ends\nSCREEGO_SESSION_TIMEOUT_SECONDS=0\n\n# Defines the default value for the checkbox in the room creation dialog to select\n# if the room should be closed when the room owner leaves\nSCREEGO_CLOSE_ROOM_WHEN_OWNER_LEAVES=true\n\n# The loglevel (one of: debug, info, warn, error)\nSCREEGO_LOG_LEVEL=info\n\n# If screego should expose a prometheus endpoint at /metrics. The endpoint\n# requires basic authentication from a user in the users file.\nSCREEGO_PROMETHEUS=false\n"
  },
  {
    "path": "server/server.go",
    "content": "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\t\"github.com/rs/zerolog/log\"\n)\n\nvar (\n\tnotifySignal   = signal.Notify\n\tserverShutdown = func(server *http.Server, ctx context.Context) error {\n\t\treturn server.Shutdown(ctx)\n\t}\n)\n\n// Start starts the http server.\nfunc Start(mux *mux.Router, address, cert, key string) error {\n\tserver, shutdown := startServer(mux, address, cert, key)\n\tshutdownOnInterruptSignal(server, 2*time.Second, shutdown)\n\treturn waitForServerToClose(shutdown)\n}\n\nfunc startServer(mux *mux.Router, address, cert, key string) (*http.Server, chan error) {\n\tsrv := &http.Server{\n\t\tAddr:    address,\n\t\tHandler: mux,\n\t}\n\n\tshutdown := make(chan error)\n\tgo func() {\n\t\terr := listenAndServe(srv, address, cert, key)\n\t\tshutdown <- err\n\t}()\n\treturn srv, shutdown\n}\n\nfunc listenAndServe(srv *http.Server, address, cert, key string) error {\n\tvar err error\n\tvar listener net.Listener\n\n\tif strings.HasPrefix(address, \"unix:\") {\n\t\tlistener, err = net.Listen(\"unix\", strings.TrimPrefix(address, \"unix:\"))\n\t} else {\n\t\tlistener, err = net.Listen(\"tcp\", address)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif cert != \"\" || key != \"\" {\n\t\tlog.Info().Str(\"addr\", address).Msg(\"Start HTTP with tls\")\n\t\treturn srv.ServeTLS(listener, cert, key)\n\t} else {\n\t\tlog.Info().Str(\"addr\", address).Msg(\"Start HTTP\")\n\t\treturn srv.Serve(listener)\n\t}\n}\n\nfunc shutdownOnInterruptSignal(server *http.Server, timeout time.Duration, shutdown chan<- error) {\n\tinterrupt := make(chan os.Signal, 1)\n\tnotifySignal(interrupt, os.Interrupt)\n\n\tgo func() {\n\t\t<-interrupt\n\t\tlog.Info().Msg(\"Received interrupt. Shutting down...\")\n\t\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\t\tdefer cancel()\n\t\tif err := serverShutdown(server, ctx); err != nil {\n\t\t\tshutdown <- err\n\t\t}\n\t}()\n}\n\nfunc waitForServerToClose(shutdown <-chan error) error {\n\terr := <-shutdown\n\tif err == http.ErrServerClosed {\n\t\treturn nil\n\t}\n\treturn err\n}\n"
  },
  {
    "path": "server/server_test.go",
    "content": "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/gorilla/mux\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestShutdownOnErrorWhileShutdown(t *testing.T) {\n\tdisposeInterrupt := fakeInterrupt(t)\n\tdefer disposeInterrupt()\n\n\tshutdownError := errors.New(\"shutdown error\")\n\tdisposeShutdown := fakeShutdownError(shutdownError)\n\tdefer disposeShutdown()\n\n\tfinished := make(chan error)\n\n\tgo func() {\n\t\tfinished <- Start(mux.NewRouter(), \":\"+strconv.Itoa(port()), \"\", \"\")\n\t}()\n\n\tselect {\n\tcase <-time.After(1 * time.Second):\n\t\tt.Fatal(\"Server should be closed\")\n\tcase err := <-finished:\n\t\tassert.Equal(t, shutdownError, err)\n\t}\n}\n\nfunc TestShutdownAfterError(t *testing.T) {\n\tfinished := make(chan error)\n\n\tgo func() {\n\t\tfinished <- Start(mux.NewRouter(), \":-5\", \"\", \"\")\n\t}()\n\n\tselect {\n\tcase <-time.After(1 * time.Second):\n\t\tt.Fatal(\"Server should be closed\")\n\tcase err := <-finished:\n\t\tassert.NotNil(t, err)\n\t}\n}\n\nfunc TestShutdown(t *testing.T) {\n\tdispose := fakeInterrupt(t)\n\tdefer dispose()\n\n\tfinished := make(chan error)\n\n\tgo func() {\n\t\tfinished <- Start(mux.NewRouter(), \":\"+strconv.Itoa(port()), \"\", \"\")\n\t}()\n\n\tselect {\n\tcase <-time.After(1 * time.Second):\n\t\tt.Fatal(\"Server should be closed\")\n\tcase err := <-finished:\n\t\tassert.Nil(t, err)\n\t}\n}\n\nfunc fakeInterrupt(t *testing.T) func() {\n\toldNotify := notifySignal\n\tnotifySignal = func(c chan<- os.Signal, sig ...os.Signal) {\n\t\tassert.Contains(t, sig, os.Interrupt)\n\t\tgo func() {\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\tc <- os.Interrupt\n\t\t}()\n\t}\n\treturn func() {\n\t\tnotifySignal = oldNotify\n\t}\n}\n\nfunc fakeShutdownError(err error) func() {\n\told := serverShutdown\n\tserverShutdown = func(server *http.Server, ctx context.Context) error {\n\t\treturn err\n\t}\n\treturn func() {\n\t\tserverShutdown = old\n\t}\n}\n\nfunc port() int {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer l.Close()\n\treturn l.Addr().(*net.TCPAddr).Port\n}\n"
  },
  {
    "path": "turn/none.go",
    "content": "package turn\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"strconv\"\n)\n\ntype RelayAddressGeneratorNone struct{}\n\nfunc (r *RelayAddressGeneratorNone) Validate() error {\n\treturn nil\n}\n\nfunc (r *RelayAddressGeneratorNone) AllocatePacketConn(network string, requestedPort int) (net.PacketConn, net.Addr, error) {\n\tconn, err := net.ListenPacket(\"udp\", \":\"+strconv.Itoa(requestedPort))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn conn, conn.LocalAddr(), nil\n}\n\nfunc (r *RelayAddressGeneratorNone) AllocateConn(network string, requestedPort int) (net.Conn, net.Addr, error) {\n\treturn nil, nil, errors.New(\"todo\")\n}\n"
  },
  {
    "path": "turn/portrange.go",
    "content": "package turn\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com/pion/randutil\"\n)\n\ntype RelayAddressGeneratorPortRange struct {\n\tMinPort uint16\n\tMaxPort uint16\n\tRand    randutil.MathRandomGenerator\n}\n\nfunc (r *RelayAddressGeneratorPortRange) Validate() error {\n\tif r.Rand == nil {\n\t\tr.Rand = randutil.NewMathRandomGenerator()\n\t}\n\n\treturn nil\n}\n\nfunc (r *RelayAddressGeneratorPortRange) AllocatePacketConn(network string, requestedPort int) (net.PacketConn, net.Addr, error) {\n\tif requestedPort != 0 {\n\t\tconn, err := net.ListenPacket(\"udp\", fmt.Sprintf(\":%d\", requestedPort))\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\trelayAddr := conn.LocalAddr().(*net.UDPAddr)\n\t\treturn conn, relayAddr, nil\n\t}\n\n\tfor try := 0; try < 10; try++ {\n\t\tport := r.MinPort + uint16(r.Rand.Intn(int((r.MaxPort+1)-r.MinPort)))\n\t\tconn, err := net.ListenPacket(\"udp\", fmt.Sprintf(\":%d\", port))\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\trelayAddr := conn.LocalAddr().(*net.UDPAddr)\n\t\treturn conn, relayAddr, nil\n\t}\n\n\treturn nil, nil, errors.New(\"could not find free port: max retries exceeded\")\n}\n\nfunc (r *RelayAddressGeneratorPortRange) AllocateConn(network string, requestedPort int) (net.Conn, net.Addr, error) {\n\treturn nil, nil, errors.New(\"todo\")\n}\n"
  },
  {
    "path": "turn/server.go",
    "content": "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/turn/v4\"\n\t\"github.com/rs/zerolog/log\"\n\t\"github.com/screego/server/config\"\n\t\"github.com/screego/server/config/ipdns\"\n\t\"github.com/screego/server/util\"\n)\n\ntype Server interface {\n\tCredentials(id string, addr net.IP) (string, string)\n\tDisallow(username string)\n}\n\ntype InternalServer struct {\n\tlock   sync.RWMutex\n\tlookup map[string]Entry\n}\n\ntype ExternalServer struct {\n\tsecret []byte\n\tttl    time.Duration\n}\n\ntype Entry struct {\n\taddr     net.IP\n\tpassword []byte\n}\n\nconst Realm = \"screego\"\n\ntype Generator struct {\n\tturn.RelayAddressGenerator\n\tIPProvider ipdns.Provider\n}\n\nfunc (r *Generator) AllocatePacketConn(network string, requestedPort int) (net.PacketConn, net.Addr, error) {\n\tconn, addr, err := r.RelayAddressGenerator.AllocatePacketConn(network, requestedPort)\n\tif err != nil {\n\t\treturn conn, addr, err\n\t}\n\trelayAddr := *addr.(*net.UDPAddr)\n\n\tv4, v6, err := r.IPProvider.Get()\n\tif err != nil {\n\t\treturn conn, addr, err\n\t}\n\n\tif v6 == nil || (relayAddr.IP.To4() != nil && v4 != nil) {\n\t\trelayAddr.IP = v4\n\t} else {\n\t\trelayAddr.IP = v6\n\t}\n\tif err == nil {\n\t\tlog.Debug().Str(\"addr\", addr.String()).Str(\"relayaddr\", relayAddr.String()).Msg(\"TURN allocated\")\n\t}\n\treturn conn, &relayAddr, err\n}\n\nfunc Start(conf config.Config) (Server, error) {\n\tif conf.TurnExternal {\n\t\treturn newExternalServer(conf)\n\t} else {\n\t\treturn newInternalServer(conf)\n\t}\n}\n\nfunc newExternalServer(conf config.Config) (Server, error) {\n\treturn &ExternalServer{\n\t\tsecret: []byte(conf.TurnExternalSecret),\n\t\tttl:    24 * time.Hour,\n\t}, nil\n}\n\nfunc newInternalServer(conf config.Config) (Server, error) {\n\tudpListener, err := net.ListenPacket(\"udp\", conf.TurnAddress)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"udp: could not listen on %s: %s\", conf.TurnAddress, err)\n\t}\n\ttcpListener, err := net.Listen(\"tcp\", conf.TurnAddress)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"tcp: could not listen on %s: %s\", conf.TurnAddress, err)\n\t}\n\n\tsvr := &InternalServer{lookup: map[string]Entry{}}\n\n\tgen := &Generator{\n\t\tRelayAddressGenerator: generator(conf),\n\t\tIPProvider:            conf.TurnIPProvider,\n\t}\n\n\tvar permissions turn.PermissionHandler = func(clientAddr net.Addr, peerIP net.IP) bool {\n\t\tfor _, cidr := range conf.TurnDenyPeersParsed {\n\t\t\tif cidr.Contains(peerIP) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t}\n\n\t_, err = turn.NewServer(turn.ServerConfig{\n\t\tRealm:       Realm,\n\t\tAuthHandler: svr.authenticate,\n\t\tListenerConfigs: []turn.ListenerConfig{\n\t\t\t{Listener: tcpListener, RelayAddressGenerator: gen, PermissionHandler: permissions},\n\t\t},\n\t\tPacketConnConfigs: []turn.PacketConnConfig{\n\t\t\t{PacketConn: udpListener, RelayAddressGenerator: gen, PermissionHandler: permissions},\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Info().Str(\"addr\", conf.TurnAddress).Msg(\"Start TURN/STUN\")\n\treturn svr, nil\n}\n\nfunc generator(conf config.Config) turn.RelayAddressGenerator {\n\tmin, max, useRange := conf.PortRange()\n\tif useRange {\n\t\tlog.Debug().Uint16(\"min\", min).Uint16(\"max\", max).Msg(\"Using Port Range\")\n\t\treturn &RelayAddressGeneratorPortRange{MinPort: min, MaxPort: max}\n\t}\n\treturn &RelayAddressGeneratorNone{}\n}\n\nfunc (a *InternalServer) allow(username, password string, addr net.IP) {\n\ta.lock.Lock()\n\tdefer a.lock.Unlock()\n\ta.lookup[username] = Entry{\n\t\taddr:     addr,\n\t\tpassword: turn.GenerateAuthKey(username, Realm, password),\n\t}\n}\n\nfunc (a *InternalServer) Disallow(username string) {\n\ta.lock.Lock()\n\tdefer a.lock.Unlock()\n\n\tdelete(a.lookup, username)\n}\n\nfunc (a *ExternalServer) Disallow(username string) {\n\t// not supported, will expire on TTL\n}\n\nfunc (a *InternalServer) authenticate(username, realm string, addr net.Addr) ([]byte, bool) {\n\ta.lock.RLock()\n\tdefer a.lock.RUnlock()\n\n\tentry, ok := a.lookup[username]\n\n\tif !ok {\n\t\tlog.Debug().Interface(\"addr\", addr).Str(\"username\", username).Msg(\"TURN username not found\")\n\t\treturn nil, false\n\t}\n\n\tlog.Debug().Interface(\"addr\", addr.String()).Str(\"realm\", realm).Msg(\"TURN authenticated\")\n\treturn entry.password, true\n}\n\nfunc (a *InternalServer) Credentials(id string, addr net.IP) (string, string) {\n\tpassword := util.RandString(20)\n\ta.allow(id, password, addr)\n\treturn id, password\n}\n\nfunc (a *ExternalServer) Credentials(id string, addr net.IP) (string, string) {\n\tusername := fmt.Sprintf(\"%d:%s\", time.Now().Add(a.ttl).Unix(), id)\n\tmac := hmac.New(sha1.New, a.secret)\n\t_, _ = mac.Write([]byte(username))\n\tpassword := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\treturn username, password\n}\n"
  },
  {
    "path": "ui/.gitignore",
    "content": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pnp\n.pnp.js\n\n# testing\n/coverage\n\n# production\n/build\n\n# misc\n.DS_Store\n.env.local\n.env.development.local\n.env.test.local\n.env.production.local\n\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n"
  },
  {
    "path": "ui/.prettierrc",
    "content": "{\n  \"printWidth\": 100,\n  \"tabWidth\": 4,\n  \"useTabs\": false,\n  \"semi\": true,\n  \"singleQuote\": true,\n  \"trailingComma\": \"es5\",\n  \"bracketSpacing\": false,\n  \"arrowParens\": \"always\",\n  \"parser\": \"typescript\"\n}\n"
  },
  {
    "path": "ui/index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"icon\" href=\"./favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#FFFFFF\" />\n    <meta property=\"og:type\" content=\"website\" />\n    <meta property=\"og:title\" content=\"Screego\" />\n    <meta property=\"og:description\" content=\"screen sharing for developers\" />\n    <meta property=\"og:image\" content=\"./og-banner.png\" />\n    <meta property=\"og:image:width\" content=\"400\" />\n    <meta property=\"og:image:height\" content=\"300\" />\n    <meta\n      name=\"description\"\n      content=\"Screego - screen sharing for developers\"\n    />\n    <link rel=\"apple-touch-icon\" href=\"./apple-touch-icon.png\" />\n    <title>Screego</title>\n  </head>\n  <body>\n    <noscript>Screego requires JavaScript (:</noscript>\n    <div id=\"root\"></div>\n    <script type=\"module\" src=\"/src/index.tsx\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "ui/package.json",
    "content": "{\n  \"name\": \"ui\",\n  \"version\": \"0.1.0\",\n  \"homepage\": \".\",\n  \"private\": true,\n  \"dependencies\": {\n    \"@emotion/react\": \"^11.13.3\",\n    \"@emotion/styled\": \"11.14.1\",\n    \"@mui/icons-material\": \"7.3.6\",\n    \"@mui/material\": \"7.3.6\",\n    \"@mui/styles\": \"^6.1.1\",\n    \"@types/react\": \"19.2.7\",\n    \"@types/react-dom\": \"19.2.3\",\n    \"@vitejs/plugin-react-swc\": \"4.2.2\",\n    \"notistack\": \"^3.0.1\",\n    \"prettier\": \"3.7.4\",\n    \"react\": \"19.2.3\",\n    \"react-dom\": \"19.2.3\",\n    \"react-hotkeys-hook\": \"5.2.1\",\n    \"tss-react\": \"^4.9.20\",\n    \"typescript\": \"5.9.3\",\n    \"use-http\": \"^1.0.28\",\n    \"vite\": \"7.3.0\",\n    \"vite-plugin-svgr\": \"4.5.0\",\n    \"vite-tsconfig-paths\": \"6.0.3\"\n  },\n  \"scripts\": {\n    \"start\": \"vite\",\n    \"format\": \"prettier \\\"src/**/*.{ts,tsx}\\\" --write\",\n    \"testformat\": \"prettier \\\"src/**/*.{ts,tsx}\\\" --list-different\",\n    \"build\": \"tsc && vite build\"\n  },\n  \"eslintConfig\": {\n    \"extends\": \"react-app\"\n  },\n  \"browserslist\": {\n    \"production\": [\n      \">0.2%\",\n      \"not dead\",\n      \"not op_mini all\"\n    ],\n    \"development\": [\n      \"last 1 chrome version\",\n      \"last 1 firefox version\",\n      \"last 1 safari version\"\n    ]\n  }\n}\n"
  },
  {
    "path": "ui/serve.go",
    "content": "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:embed build\nvar buildFiles embed.FS\nvar files, _ = fs.Sub(buildFiles, \"build\")\n\n// Register registers the ui on the root path.\nfunc Register(r *mux.Router) {\n\tr.Handle(\"/\", serveFile(\"index.html\", \"text/html\"))\n\tr.Handle(\"/index.html\", serveFile(\"index.html\", \"text/html\"))\n\tr.Handle(\"/assets/{resource}\", http.FileServer(http.FS(files)))\n\n\tr.Handle(\"/favicon.ico\", serveFile(\"favicon.ico\", \"image/x-icon\"))\n\tr.Handle(\"/logo.svg\", serveFile(\"logo.svg\", \"image/svg+xml\"))\n\tr.Handle(\"/apple-touch-icon.png\", serveFile(\"apple-touch-icon.png\", \"image/png\"))\n\tr.Handle(\"/og-banner.png\", serveFile(\"og-banner.png\", \"image/png\"))\n}\n\nfunc serveFile(name, contentType string) http.HandlerFunc {\n\tfile, err := files.Open(name)\n\tif err != nil {\n\t\tlog.Panic().Err(err).Msgf(\"could not find %s\", file)\n\t}\n\tdefer file.Close()\n\tcontent, err := io.ReadAll(file)\n\tif err != nil {\n\t\tlog.Panic().Err(err).Msgf(\"could not read %s\", file)\n\t}\n\n\treturn func(writer http.ResponseWriter, reg *http.Request) {\n\t\twriter.Header().Set(\"Content-Type\", contentType)\n\t\t_, _ = writer.Write(content)\n\t}\n}\n"
  },
  {
    "path": "ui/src/LoginForm.tsx",
    "content": "import {UseConfig} from './useConfig';\nimport React from 'react';\nimport {\n    Box,\n    Button,\n    ButtonProps,\n    CircularProgress,\n    FormControl,\n    TextField,\n    Typography,\n} from '@mui/material';\nimport {makeStyles} from 'tss-react/mui';\nimport {green} from '@mui/material/colors';\n\nexport const LoginForm = ({config: {login}, hide}: {config: UseConfig; hide?: () => void}) => {\n    const [user, setUser] = React.useState('');\n    const [pass, setPass] = React.useState('');\n    const [loading, setLoading] = React.useState(false);\n    const submit = async (event: {preventDefault: () => void}) => {\n        event.preventDefault();\n        setLoading(true);\n        login(user, pass)\n            .then(() => {\n                setLoading(false);\n            })\n            .catch(() => setLoading(false));\n    };\n    return (\n        <div>\n            <FormControl fullWidth>\n                <form onSubmit={submit}>\n                    <div style={{display: 'flex', alignItems: 'center'}}>\n                        <Typography style={{flex: 1}}>Login to Screego</Typography>\n                        {hide ? (\n                            <Button variant=\"outlined\" size=\"small\" onClick={hide}>\n                                Go Back\n                            </Button>\n                        ) : undefined}\n                    </div>\n                    <TextField\n                        fullWidth\n                        value={user}\n                        onChange={(e) => setUser(e.target.value)}\n                        label=\"Username\"\n                        size=\"small\"\n                        margin=\"dense\"\n                    />\n                    <TextField\n                        fullWidth\n                        value={pass}\n                        type=\"password\"\n                        onChange={(e) => setPass(e.target.value)}\n                        label=\"Password\"\n                        size=\"small\"\n                        margin=\"dense\"\n                    />\n                    <Box marginTop={1}>\n                        <LoadingButton\n                            type=\"submit\"\n                            loading={loading}\n                            onClick={submit}\n                            fullWidth\n                            variant=\"contained\"\n                        >\n                            Login\n                        </LoadingButton>\n                    </Box>\n                </form>\n            </FormControl>\n        </div>\n    );\n};\n\nexport const LoadingButton = ({loading, children, ...props}: ButtonProps & {loading: boolean}) => {\n    const {classes} = useStyles();\n    return (\n        <Button {...props} disabled={loading}>\n            {children}\n            {loading && (\n                <CircularProgress className={classes.buttonProgress} size={24} color=\"secondary\" />\n            )}\n        </Button>\n    );\n};\n\nconst useStyles = makeStyles()(() => ({\n    buttonProgress: {\n        color: green[500],\n        position: 'absolute',\n        top: '50%',\n        left: '50%',\n        marginTop: -12,\n        marginLeft: -12,\n    },\n}));\n"
  },
  {
    "path": "ui/src/NumberField.tsx",
    "content": "import {TextField, TextFieldProps} from '@mui/material';\nimport React from 'react';\n\nexport interface NumberFieldProps {\n    value: number;\n    min: number;\n    onChange: (value: number) => void;\n}\n\nexport const NumberField = ({\n    value,\n    min,\n    onChange,\n    ...props\n}: NumberFieldProps & Omit<TextFieldProps, 'value' | 'onChange'>) => {\n    const [stringValue, setStringValue] = React.useState<string>(value.toString());\n    const [error, setError] = React.useState('');\n\n    return (\n        <TextField\n            value={stringValue}\n            type=\"number\"\n            helperText={error}\n            error={error !== ''}\n            onChange={(event) => {\n                setStringValue(event.target.value);\n                const i = parseInt(event.target.value, 10);\n                if (Number.isNaN(i)) {\n                    setError('Invalid number');\n                    return;\n                }\n\n                if (i < min) {\n                    setError('Number must be at least ' + min);\n                    return;\n                }\n                onChange(i);\n                setError('');\n            }}\n            {...props}\n        />\n    );\n};\n"
  },
  {
    "path": "ui/src/Room.tsx",
    "content": "import React, {useCallback} from 'react';\nimport {Badge, Box, IconButton, Paper, Tooltip, Typography, Slider, Stack} from '@mui/material';\nimport CancelPresentationIcon from '@mui/icons-material/CancelPresentation';\nimport PresentToAllIcon from '@mui/icons-material/PresentToAll';\nimport FullScreenIcon from '@mui/icons-material/Fullscreen';\nimport PeopleIcon from '@mui/icons-material/People';\nimport VolumeMuteIcon from '@mui/icons-material/VolumeOff';\nimport VolumeIcon from '@mui/icons-material/VolumeUp';\nimport SettingsIcon from '@mui/icons-material/Settings';\nimport {useHotkeys} from 'react-hotkeys-hook';\nimport {Video} from './Video';\nimport {makeStyles} from 'tss-react/mui';\nimport {ConnectedRoom} from './useRoom';\nimport {useSnackbar} from 'notistack';\nimport {RoomUser} from './message';\nimport {useSettings, VideoDisplayMode} from './settings';\nimport {SettingDialog} from './SettingDialog';\n\nconst HostStream: unique symbol = Symbol('mystream');\n\nconst flags = (user: RoomUser) => {\n    const result: string[] = [];\n    if (user.you) {\n        result.push('You');\n    }\n    if (user.owner) {\n        result.push('Owner');\n    }\n    if (user.streaming) {\n        result.push('Streaming');\n    }\n    if (!result.length) {\n        return '';\n    }\n    return ` (${result.join(', ')})`;\n};\n\ninterface FullScreenHTMLVideoElement extends HTMLVideoElement {\n    msRequestFullscreen?: () => void;\n    mozRequestFullScreen?: () => void;\n    webkitRequestFullscreen?: () => void;\n}\n\nconst requestFullscreen = (element: FullScreenHTMLVideoElement | null) => {\n    if (element?.requestFullscreen) {\n        element.requestFullscreen();\n    } else if (element?.mozRequestFullScreen) {\n        element.mozRequestFullScreen();\n    } else if (element?.msRequestFullscreen) {\n        element.msRequestFullscreen();\n    } else if (element?.webkitRequestFullscreen) {\n        element.webkitRequestFullscreen();\n    }\n};\n\nexport const Room = ({\n    state,\n    share,\n    stopShare,\n    setName,\n}: {\n    state: ConnectedRoom;\n    share: () => void;\n    stopShare: () => void;\n    setName: (name: string) => void;\n}) => {\n    const {classes} = useStyles();\n    const [open, setOpen] = React.useState(false);\n    const {enqueueSnackbar} = useSnackbar();\n    const [settings, setSettings] = useSettings();\n    const [showControl, setShowControl] = React.useState(true);\n    const [hoverControl, setHoverControl] = React.useState(false);\n    const [selectedStream, setSelectedStream] = React.useState<string | typeof HostStream>();\n    const [videoElement, setVideoElement] = React.useState<FullScreenHTMLVideoElement | null>(null);\n\n    useShowOnMouseMovement(setShowControl);\n\n    const handleFullscreen = useCallback(() => requestFullscreen(videoElement), [videoElement]);\n\n    React.useEffect(() => {\n        if (selectedStream === HostStream && state.hostStream) {\n            return;\n        }\n        if (state.clientStreams.some(({id}) => id === selectedStream)) {\n            return;\n        }\n        if (state.clientStreams.length === 0 && selectedStream) {\n            setSelectedStream(undefined);\n            return;\n        }\n        setSelectedStream(state.clientStreams[0]?.id);\n    }, [state.clientStreams, selectedStream, state.hostStream]);\n\n    const stream =\n        selectedStream === HostStream\n            ? state.hostStream\n            : state.clientStreams.find(({id}) => selectedStream === id)?.stream;\n\n    React.useEffect(() => {\n        if (videoElement && stream) {\n            videoElement.srcObject = stream;\n            videoElement.play().catch((err) => {\n                console.log('Could not play main video', err);\n                if (err.name === 'NotAllowedError') {\n                    videoElement.muted = true;\n                    videoElement\n                        .play()\n                        .catch((retryErr) =>\n                            console.log('Could not play main video with mute', retryErr)\n                        );\n                }\n            });\n        }\n    }, [videoElement, stream]);\n\n    const copyLink = () => {\n        navigator?.clipboard?.writeText(window.location.href)?.then(\n            () => enqueueSnackbar('Link Copied', {variant: 'success'}),\n            (err) => enqueueSnackbar('Copy Failed ' + err, {variant: 'error'})\n        );\n    };\n\n    const setHoverState = React.useMemo(\n        () => ({\n            onMouseLeave: () => setHoverControl(false),\n            onMouseEnter: () => setHoverControl(true),\n        }),\n        [setHoverControl]\n    );\n\n    const controlVisible = showControl || open || hoverControl;\n\n    useHotkeys('s', () => (state.hostStream ? stopShare() : share()), [state.hostStream]);\n    useHotkeys(\n        'f',\n        () => {\n            if (selectedStream) {\n                handleFullscreen();\n            }\n        },\n        [handleFullscreen, selectedStream]\n    );\n    useHotkeys('c', copyLink);\n    useHotkeys(\n        'h',\n        () => {\n            if (state.clientStreams !== undefined && state.clientStreams.length > 0) {\n                const currentStreamIndex = state.clientStreams.findIndex(\n                    ({id}) => id === selectedStream\n                );\n                const nextIndex =\n                    currentStreamIndex === state.clientStreams.length - 1\n                        ? 0\n                        : currentStreamIndex + 1;\n                setSelectedStream(state.clientStreams[nextIndex].id);\n            }\n        },\n        [state.clientStreams, selectedStream]\n    );\n    useHotkeys(\n        'l',\n        () => {\n            if (state.clientStreams !== undefined && state.clientStreams.length > 0) {\n                const currentStreamIndex = state.clientStreams.findIndex(\n                    ({id}) => id === selectedStream\n                );\n                const previousIndex =\n                    currentStreamIndex === 0\n                        ? state.clientStreams.length - 1\n                        : currentStreamIndex - 1;\n                setSelectedStream(state.clientStreams[previousIndex].id);\n            }\n        },\n        [state.clientStreams, selectedStream]\n    );\n    useHotkeys(\n        'm',\n        () => {\n            if (videoElement) {\n                videoElement.muted = !videoElement.muted;\n            }\n        },\n        [videoElement]\n    );\n\n    const videoClasses = () => {\n        switch (settings.displayMode) {\n            case VideoDisplayMode.FitToWindow:\n                return `${classes.video} ${classes.videoWindowFit}`;\n            case VideoDisplayMode.OriginalSize:\n                return `${classes.video}`;\n            case VideoDisplayMode.FitWidth:\n                return `${classes.video} ${classes.videoWindowWidth}`;\n            case VideoDisplayMode.FitHeight:\n                return `${classes.video} ${classes.videoWindowHeight}`;\n        }\n    };\n\n    return (\n        <div className={classes.videoContainer}>\n            {controlVisible && (\n                <Paper className={classes.title} elevation={10} {...setHoverState}>\n                    <Tooltip title=\"Copy Link\">\n                        <Typography\n                            variant=\"h4\"\n                            component=\"h4\"\n                            style={{cursor: 'pointer'}}\n                            onClick={copyLink}\n                        >\n                            {state.id}\n                        </Typography>\n                    </Tooltip>\n                </Paper>\n            )}\n\n            {stream ? (\n                <video\n                    ref={setVideoElement}\n                    className={videoClasses()}\n                    onDoubleClick={handleFullscreen}\n                />\n            ) : (\n                <Typography\n                    variant=\"h4\"\n                    align=\"center\"\n                    component=\"div\"\n                    style={{\n                        top: '50%',\n                        left: '50%',\n                        position: 'absolute',\n                        transform: 'translate(-50%, -50%)',\n                    }}\n                >\n                    no stream available\n                </Typography>\n            )}\n\n            {controlVisible && (\n                <Paper className={classes.control} elevation={10} {...setHoverState}>\n                    {(stream?.getAudioTracks().length ?? 0) > 0 && videoElement && (\n                        <AudioControl video={videoElement} />\n                    )}\n                    <Box whiteSpace=\"nowrap\">\n                        {state.hostStream ? (\n                            <Tooltip title=\"Cancel Presentation\" arrow>\n                                <IconButton onClick={stopShare} size=\"large\">\n                                    <CancelPresentationIcon fontSize=\"large\" />\n                                </IconButton>\n                            </Tooltip>\n                        ) : (\n                            <Tooltip title=\"Start Presentation\" arrow>\n                                <IconButton onClick={share} size=\"large\">\n                                    <PresentToAllIcon fontSize=\"large\" />\n                                </IconButton>\n                            </Tooltip>\n                        )}\n\n                        <Tooltip\n                            classes={{tooltip: classes.noMaxWidth}}\n                            title={\n                                <div>\n                                    <Typography variant=\"h5\">Member List</Typography>\n                                    {state.users.map((user) => (\n                                        <Typography key={user.id}>\n                                            {user.name} {flags(user)}\n                                        </Typography>\n                                    ))}\n                                </div>\n                            }\n                            arrow\n                        >\n                            <Badge badgeContent={state.users.length} color=\"primary\">\n                                <PeopleIcon fontSize=\"large\" />\n                            </Badge>\n                        </Tooltip>\n                        <Tooltip title=\"Fullscreen\" arrow>\n                            <IconButton\n                                onClick={() => handleFullscreen()}\n                                disabled={!selectedStream}\n                                size=\"large\"\n                            >\n                                <FullScreenIcon fontSize=\"large\" />\n                            </IconButton>\n                        </Tooltip>\n\n                        <Tooltip title=\"Settings\" arrow>\n                            <IconButton onClick={() => setOpen(true)} size=\"large\">\n                                <SettingsIcon fontSize=\"large\" />\n                            </IconButton>\n                        </Tooltip>\n                    </Box>\n                </Paper>\n            )}\n\n            <div className={classes.bottomContainer}>\n                {state.clientStreams\n                    .filter(({id}) => id !== selectedStream)\n                    .map((client) => {\n                        return (\n                            <Paper\n                                key={client.id}\n                                elevation={4}\n                                className={classes.smallVideoContainer}\n                                onClick={() => setSelectedStream(client.id)}\n                            >\n                                <Video\n                                    key={client.id}\n                                    src={client.stream}\n                                    className={classes.smallVideo}\n                                />\n                                <Typography\n                                    variant=\"subtitle1\"\n                                    component=\"div\"\n                                    align=\"center\"\n                                    className={classes.smallVideoLabel}\n                                >\n                                    {state.users.find(({id}) => client.peer_id === id)?.name ??\n                                        'unknown'}\n                                </Typography>\n                            </Paper>\n                        );\n                    })}\n                {state.hostStream && selectedStream !== HostStream && (\n                    <Paper\n                        elevation={4}\n                        className={classes.smallVideoContainer}\n                        onClick={() => setSelectedStream(HostStream)}\n                    >\n                        <Video src={state.hostStream} className={classes.smallVideo} />\n                        <Typography\n                            variant=\"subtitle1\"\n                            component=\"div\"\n                            align=\"center\"\n                            className={classes.smallVideoLabel}\n                        >\n                            You\n                        </Typography>\n                    </Paper>\n                )}\n                <SettingDialog\n                    open={open}\n                    setOpen={setOpen}\n                    updateName={setName}\n                    saveSettings={setSettings}\n                />\n            </div>\n        </div>\n    );\n};\n\nconst useShowOnMouseMovement = (doShow: (s: boolean) => void) => {\n    const timeoutHandle = React.useRef(0);\n\n    React.useEffect(() => {\n        const update = () => {\n            if (timeoutHandle.current === 0) {\n                doShow(true);\n            }\n\n            clearTimeout(timeoutHandle.current);\n            timeoutHandle.current = window.setTimeout(() => {\n                timeoutHandle.current = 0;\n                doShow(false);\n            }, 1000);\n        };\n        window.addEventListener('mousemove', update);\n        return () => window.removeEventListener('mousemove', update);\n    }, [doShow]);\n\n    React.useEffect(\n        () =>\n            void (timeoutHandle.current = window.setTimeout(() => {\n                timeoutHandle.current = 0;\n                doShow(false);\n            }, 1000)),\n        // eslint-disable-next-line react-hooks/exhaustive-deps\n        []\n    );\n};\n\nconst AudioControl = ({video}: {video: FullScreenHTMLVideoElement}) => {\n    // this is used to force a rerender\n    const [, setMuted] = React.useState<boolean>();\n\n    React.useEffect(() => {\n        const handler = () => setMuted(video.muted);\n        video.addEventListener('volumechange', handler);\n        setMuted(video.muted);\n        return () => video.removeEventListener('volumechange', handler);\n    });\n\n    return (\n        <Stack spacing={0.5} pr={2} direction=\"row\" sx={{alignItems: 'center', my: 1, height: 35}}>\n            <IconButton size=\"large\" onClick={() => (video.muted = !video.muted)}>\n                {video.muted ? (\n                    <VolumeMuteIcon fontSize=\"large\" />\n                ) : (\n                    <VolumeIcon fontSize=\"large\" />\n                )}\n            </IconButton>\n            <Slider\n                min={0}\n                max={1}\n                step={0.01}\n                defaultValue={video.volume}\n                onChange={(_, newVolume) => {\n                    video.muted = false;\n                    video.volume = newVolume;\n                }}\n            />\n        </Stack>\n    );\n};\n\nconst useStyles = makeStyles()(() => ({\n    title: {\n        padding: 15,\n        position: 'fixed',\n        top: '30px',\n        left: '50%',\n        transform: 'translateX(-50%)',\n        zIndex: 30,\n    },\n    bottomContainer: {\n        position: 'fixed',\n        display: 'flex',\n        bottom: 0,\n        right: 0,\n        zIndex: 20,\n    },\n    control: {\n        padding: 15,\n        position: 'fixed',\n        bottom: '30px',\n        left: '50%',\n        transform: 'translateX(-50%)',\n        zIndex: 30,\n    },\n    video: {\n        display: 'block',\n        margin: '0 auto',\n\n        '&::-webkit-media-controls-start-playback-button': {\n            display: 'none!important',\n        },\n        '&::-webkit-media-controls': {\n            display: 'none!important',\n        },\n    },\n    smallVideo: {\n        minWidth: '100%',\n        minHeight: '100%',\n        width: 'auto',\n        maxWidth: '300px',\n\n        maxHeight: '200px',\n    },\n    videoWindowFit: {\n        width: '100%',\n        height: '100%',\n\n        position: 'absolute',\n        top: '50%',\n        left: '50%',\n        transform: 'translate(-50%,-50%)',\n    },\n    videoWindowWidth: {\n        height: 'auto',\n        width: '100%',\n    },\n    videoWindowHeight: {\n        height: '100%',\n        width: 'auto',\n    },\n    smallVideoLabel: {\n        position: 'absolute',\n        display: 'block',\n        bottom: 0,\n        background: 'rgba(0,0,0,.5)',\n        padding: '5px 15px',\n    },\n    noMaxWidth: {\n        maxWidth: 'none',\n    },\n    smallVideoContainer: {\n        height: '100%',\n        padding: 5,\n        maxHeight: 200,\n        maxWidth: 400,\n        width: '100%',\n    },\n    videoContainer: {\n        position: 'absolute',\n        top: 0,\n        bottom: 0,\n        width: '100%',\n        height: '100%',\n\n        overflow: 'auto',\n    },\n}));\n"
  },
  {
    "path": "ui/src/RoomManage.tsx",
    "content": "import React from 'react';\nimport {\n    Box,\n    Button,\n    Checkbox,\n    FormControl,\n    FormControlLabel,\n    Grid,\n    Paper,\n    TextField,\n    Typography,\n    Link,\n} from '@mui/material';\nimport {FCreateRoom, UseRoom} from './useRoom';\nimport {UIConfig} from './message';\nimport {getRoomFromURL} from './useRoomID';\nimport {authModeToRoomMode, UseConfig} from './useConfig';\nimport {LoginForm} from './LoginForm';\n\nconst CreateRoom = ({room, config}: Pick<UseRoom, 'room'> & {config: UIConfig}) => {\n    const [id, setId] = React.useState(() => getRoomFromURL() ?? config.roomName);\n    const mode = authModeToRoomMode(config.authMode, config.loggedIn);\n    const [ownerLeave, setOwnerLeave] = React.useState(config.closeRoomWhenOwnerLeaves);\n    const submit = () =>\n        room({\n            type: 'create',\n            payload: {\n                mode,\n                closeOnOwnerLeave: ownerLeave,\n                joinIfExist: true,\n                id: id || undefined,\n            },\n        });\n    return (\n        <div>\n            <FormControl fullWidth>\n                <TextField\n                    fullWidth\n                    value={id}\n                    onChange={(e) => setId(e.target.value)}\n                    label=\"id\"\n                    margin=\"dense\"\n                />\n                <FormControlLabel\n                    control={\n                        <Checkbox\n                            checked={ownerLeave}\n                            onChange={(_, checked) => setOwnerLeave(checked)}\n                        />\n                    }\n                    label=\"Close Room after you leave\"\n                />\n                <Box paddingBottom={0.5}>\n                    <Typography>\n                        Nat Traversal via:{' '}\n                        <Link\n                            href=\"https://screego.net/#/nat-traversal\"\n                            target=\"_blank\"\n                            rel=\"noreferrer\"\n                        >\n                            {mode.toUpperCase()}\n                        </Link>\n                    </Typography>\n                </Box>\n                <Button onClick={submit} fullWidth variant=\"contained\">\n                    Create or Join a Room\n                </Button>\n            </FormControl>\n        </div>\n    );\n};\n\nexport const RoomManage = ({room, config}: {room: FCreateRoom; config: UseConfig}) => {\n    const [showLogin, setShowLogin] = React.useState(false);\n\n    const canCreateRoom = config.authMode !== 'all';\n    const loginVisible = !config.loggedIn && (showLogin || !canCreateRoom);\n\n    return (\n        <Grid\n            container={true}\n            justifyContent=\"center\"\n            style={{paddingTop: 50, maxWidth: 400, width: '100%', margin: '0 auto'}}\n            spacing={4}\n        >\n            <Grid size={12}>\n                <Typography align=\"center\" gutterBottom>\n                    <img src=\"./logo.svg\" style={{width: 230}} alt=\"logo\" />\n                </Typography>\n                <Paper elevation={3} style={{padding: 20}}>\n                    {loginVisible ? (\n                        <LoginForm\n                            config={config}\n                            hide={canCreateRoom ? () => setShowLogin(false) : undefined}\n                        />\n                    ) : (\n                        <>\n                            <Typography style={{display: 'flex', alignItems: 'center'}}>\n                                <span style={{flex: 1}}>Hello {config.user}!</span>{' '}\n                                {config.loggedIn ? (\n                                    <Button variant=\"outlined\" size=\"small\" onClick={config.logout}>\n                                        Logout\n                                    </Button>\n                                ) : (\n                                    <Button\n                                        variant=\"outlined\"\n                                        size=\"small\"\n                                        onClick={() => setShowLogin(true)}\n                                    >\n                                        Login\n                                    </Button>\n                                )}\n                            </Typography>\n\n                            <CreateRoom room={room} config={config} />\n                        </>\n                    )}\n                </Paper>\n            </Grid>\n            <div style={{position: 'absolute', margin: '0 auto', bottom: 0}}>\n                Screego {config.version} |{' '}\n                <Link href=\"https://github.com/screego/server/\">GitHub</Link>\n            </div>\n        </Grid>\n    );\n};\n"
  },
  {
    "path": "ui/src/Router.tsx",
    "content": "import {RoomManage} from './RoomManage';\nimport {useRoom} from './useRoom';\nimport {Room} from './Room';\nimport {UseConfig, useConfig} from './useConfig';\n\nexport const Router = () => {\n    const config = useConfig();\n\n    if (config.loading) {\n        // show spinner\n        return null;\n    }\n    return <RouterLoadedConfig config={config} />;\n};\n\nconst RouterLoadedConfig = ({config}: {config: UseConfig}) => {\n    const {room, state, ...other} = useRoom(config);\n\n    if (state) {\n        return <Room state={state} {...other} />;\n    }\n\n    return <RoomManage room={room} config={config} />;\n};\n"
  },
  {
    "path": "ui/src/SettingDialog.tsx",
    "content": "import React from 'react';\nimport {\n    Dialog,\n    DialogTitle,\n    DialogContent,\n    TextField,\n    DialogActions,\n    Button,\n    Autocomplete,\n    Box,\n} from '@mui/material';\nimport {\n    CodecBestQuality,\n    CodecDefault,\n    codecName,\n    loadSettings,\n    PreferredCodec,\n    Settings,\n    VideoDisplayMode,\n} from './settings';\nimport {NumberField} from './NumberField';\n\nexport interface SettingDialogProps {\n    open: boolean;\n    setOpen: (open: boolean) => void;\n    updateName: (s: string) => void;\n    saveSettings: (s: Settings) => void;\n}\n\nconst getAvailableCodecs = (): PreferredCodec[] => {\n    if ('getCapabilities' in RTCRtpSender) {\n        return RTCRtpSender.getCapabilities('video')?.codecs ?? [];\n    }\n    return [];\n};\n\nconst NativeCodecs = getAvailableCodecs();\n\nexport const SettingDialog = ({open, setOpen, updateName, saveSettings}: SettingDialogProps) => {\n    const [settingsInput, setSettingsInput] = React.useState(loadSettings);\n\n    const doSubmit = () => {\n        saveSettings(settingsInput);\n        updateName(settingsInput.name ?? '');\n        setOpen(false);\n    };\n\n    const {name, preferCodec, displayMode, framerate} = settingsInput;\n\n    return (\n        <Dialog open={open} onClose={() => setOpen(false)} maxWidth={'xs'} fullWidth>\n            <DialogTitle>Settings</DialogTitle>\n            <DialogContent>\n                <form onSubmit={doSubmit}>\n                    <Box paddingBottom={1}>\n                        <TextField\n                            autoFocus\n                            margin=\"dense\"\n                            label=\"Username\"\n                            value={name}\n                            onChange={(e) =>\n                                setSettingsInput((c) => ({...c, name: e.target.value}))\n                            }\n                            fullWidth\n                        />\n                    </Box>\n                    {NativeCodecs.length > 0 ? (\n                        <Box paddingY={1}>\n                            <Autocomplete<PreferredCodec>\n                                options={[CodecBestQuality, CodecDefault, ...NativeCodecs]}\n                                getOptionLabel={({mimeType, sdpFmtpLine}) =>\n                                    codecName(mimeType) + (sdpFmtpLine ? ` (${sdpFmtpLine})` : '')\n                                }\n                                value={preferCodec}\n                                isOptionEqualToValue={(a, b) =>\n                                    a.mimeType === b.mimeType && a.sdpFmtpLine === b.sdpFmtpLine\n                                }\n                                fullWidth\n                                onChange={(_, value) =>\n                                    setSettingsInput((c) => ({\n                                        ...c,\n                                        preferCodec: value ?? undefined,\n                                    }))\n                                }\n                                renderInput={(params) => (\n                                    <TextField {...params} label=\"Preferred Codec\" />\n                                )}\n                            />\n                        </Box>\n                    ) : undefined}\n                    <Box paddingTop={1}>\n                        <Autocomplete<VideoDisplayMode>\n                            options={Object.values(VideoDisplayMode)}\n                            onChange={(_, value) =>\n                                setSettingsInput((c) => ({\n                                    ...c,\n                                    displayMode: value ?? VideoDisplayMode.FitToWindow,\n                                }))\n                            }\n                            value={displayMode}\n                            fullWidth\n                            renderInput={(params) => <TextField {...params} label=\"Display Mode\" />}\n                        />\n                    </Box>\n                    <Box paddingTop={1}>\n                        <NumberField\n                            label=\"FrameRate\"\n                            min={1}\n                            onChange={(framerate) => setSettingsInput((c) => ({...c, framerate}))}\n                            value={framerate}\n                            fullWidth\n                        />\n                    </Box>\n                </form>\n            </DialogContent>\n            <DialogActions>\n                <Button onClick={() => setOpen(false)} color=\"primary\">\n                    Cancel\n                </Button>\n                <Button onClick={doSubmit} color=\"primary\">\n                    Save\n                </Button>\n            </DialogActions>\n        </Dialog>\n    );\n};\n"
  },
  {
    "path": "ui/src/Video.tsx",
    "content": "import React from 'react';\n\nexport const Video = ({src, className}: {src: MediaStream; className?: string}) => {\n    const [element, setElement] = React.useState<HTMLVideoElement | null>(null);\n\n    React.useEffect(() => {\n        if (element) {\n            element.srcObject = src;\n            element.play().catch((e) => console.log('Could not play preview video', e));\n        }\n    }, [element, src]);\n\n    return <video muted ref={setElement} className={className} />;\n};\n"
  },
  {
    "path": "ui/src/global.css",
    "content": "#root,\nbody,\nhtml {\n    height: 100%;\n}"
  },
  {
    "path": "ui/src/index.tsx",
    "content": "import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport './global.css';\nimport {Button, createTheme, CssBaseline, ThemeProvider, StyledEngineProvider} from '@mui/material';\nimport {Router} from './Router';\nimport {SnackbarProvider} from 'notistack';\n\nconst theme = createTheme({\n    components: {\n        MuiSelect: {\n            styleOverrides: {\n                icon: {position: 'relative'},\n            },\n        },\n        MuiLink: {\n            styleOverrides: {\n                root: {\n                    color: '#458588',\n                },\n            },\n        },\n        MuiIconButton: {\n            styleOverrides: {\n                root: {\n                    color: 'inherit',\n                },\n            },\n        },\n        MuiListItemIcon: {\n            styleOverrides: {\n                root: {\n                    color: 'inherit',\n                },\n            },\n        },\n        MuiToolbar: {\n            styleOverrides: {\n                root: {\n                    background: '#a89984',\n                },\n            },\n        },\n        MuiTooltip: {\n            styleOverrides: {\n                tooltip: {\n                    fontSize: '1.6em',\n                },\n            },\n        },\n    },\n    palette: {\n        background: {\n            default: '#282828',\n            paper: '#32302f',\n        },\n        text: {\n            primary: '#fbf1d4',\n        },\n        primary: {\n            main: '#a89984',\n        },\n        secondary: {\n            main: '#f44336',\n        },\n        mode: 'dark',\n    },\n});\n\nconst Snackbar: React.FC<React.PropsWithChildren> = ({children}) => {\n    const notistackRef = React.createRef<any>();\n    const onClickDismiss = (key: unknown) => () => {\n        notistackRef.current?.closeSnackbar(key);\n    };\n\n    return (\n        <SnackbarProvider\n            maxSnack={3}\n            ref={notistackRef}\n            action={(key) => (\n                <Button onClick={onClickDismiss(key)} size=\"small\">\n                    Dismiss\n                </Button>\n            )}\n        >\n            {children}\n        </SnackbarProvider>\n    );\n};\n\nReactDOM.createRoot(document.getElementById('root')!!).render(\n    <StyledEngineProvider injectFirst>\n        <ThemeProvider theme={theme}>\n            <Snackbar>\n                <CssBaseline />\n                <Router />\n            </Snackbar>\n        </ThemeProvider>\n    </StyledEngineProvider>\n);\n"
  },
  {
    "path": "ui/src/message.ts",
    "content": "export enum ShareMode {\n    Everyone = 'Everyone',\n    Selected = 'Selected',\n}\n\ntype Typed<Base, Type extends string> = {type: Type; payload: Base};\n\nexport interface UIConfig {\n    authMode: 'turn' | 'none' | 'all';\n    user: string;\n    loggedIn: boolean;\n    version: string;\n    roomName: string;\n    closeRoomWhenOwnerLeaves: boolean;\n}\n\nexport interface RoomConfiguration {\n    id?: string;\n    closeOnOwnerLeave?: boolean;\n    mode: RoomMode;\n    username?: string;\n}\n\nexport enum RoomMode {\n    Turn = 'turn',\n    Stun = 'stun',\n    Local = 'local',\n}\n\nexport interface JoinConfiguration {\n    id: string;\n    password?: string;\n    username?: string;\n}\n\nexport interface StringMessage {\n    message: string;\n}\n\nexport interface P2PSession {\n    id: string;\n    peer: string;\n    iceServers: ICEServer[];\n}\n\nexport interface ICEServer {\n    urls: string[];\n    credential: string;\n    username: string;\n}\n\nexport interface RoomInfo {\n    id: string;\n    share: ShareMode;\n    mode: RoomMode;\n    users: RoomUser[];\n}\n\nexport interface RoomUser {\n    id: string;\n    name: string;\n    streaming: boolean;\n    you: boolean;\n    owner: boolean;\n}\n\nexport interface P2PMessage<T> {\n    sid: string;\n    value: T;\n}\n\nexport type Room = Typed<RoomInfo, 'room'>;\nexport type Error = Typed<StringMessage, 'Error'>;\nexport type HostSession = Typed<P2PSession, 'hostsession'>;\nexport type Name = Typed<{username: string}, 'name'>;\nexport type ClientSession = Typed<P2PSession, 'clientsession'>;\nexport type HostICECandidate = Typed<P2PMessage<RTCIceCandidate>, 'hostice'>;\nexport type ClientICECandidate = Typed<P2PMessage<RTCIceCandidate>, 'clientice'>;\nexport type HostOffer = Typed<P2PMessage<RTCSessionDescriptionInit>, 'hostoffer'>;\nexport type ClientAnswer = Typed<P2PMessage<RTCSessionDescriptionInit>, 'clientanswer'>;\nexport type StartSharing = Typed<{}, 'share'>;\nexport type StopShare = Typed<{}, 'stopshare'>;\nexport type RoomCreate = Typed<RoomConfiguration & {joinIfExist?: boolean}, 'create'>;\nexport type JoinRoom = Typed<JoinConfiguration, 'join'>;\nexport type EndShare = Typed<string, 'endshare'>;\n\nexport type IncomingMessage =\n    | Room\n    | Error\n    | HostSession\n    | ClientSession\n    | HostICECandidate\n    | ClientICECandidate\n    | HostOffer\n    | EndShare\n    | ClientAnswer;\n\nexport type OutgoingMessage =\n    | RoomCreate\n    | Name\n    | JoinRoom\n    | HostICECandidate\n    | ClientICECandidate\n    | HostOffer\n    | StopShare\n    | ClientAnswer\n    | StartSharing;\n"
  },
  {
    "path": "ui/src/settings.ts",
    "content": "import React from 'react';\nexport const CodecBestQuality: PreferredCodec = {mimeType: 'BEST_QUALITY'};\nexport const CodecDefault: PreferredCodec = {mimeType: 'DEFAULT'};\n\nexport const preferCodecEquals = (a: PreferredCodec, b: PreferredCodec): boolean => {\n    return a.mimeType === b.mimeType && a.sdpFmtpLine === b.sdpFmtpLine;\n};\n\nexport const codecName = (mimeType: string): string => {\n    switch (mimeType) {\n        case CodecBestQuality.mimeType:\n            return 'Preset: Best Quality';\n        case CodecDefault.mimeType:\n            return 'Preset: Browser Default';\n        default:\n            return mimeType;\n    }\n};\n\nexport const resolveCodecPlaceholder = (\n    codec: PreferredCodec | undefined\n): PreferredCodec | undefined => {\n    switch (codec?.mimeType) {\n        case CodecBestQuality.mimeType:\n            return {\n                mimeType: 'video/VP9',\n                sdpFmtpLine: 'profile-id=2',\n            };\n        case CodecDefault.mimeType:\n            return undefined;\n        default:\n            return codec;\n    }\n};\n\nexport interface Settings {\n    name?: string;\n    displayMode: VideoDisplayMode;\n    preferCodec?: PreferredCodec;\n    framerate: number;\n}\nexport interface PreferredCodec {\n    mimeType: string;\n    sdpFmtpLine?: string;\n}\n\nexport enum VideoDisplayMode {\n    FitToWindow = 'FitToWindow',\n    FitWidth = 'FitWidth',\n    FitHeight = 'FitHeight',\n    OriginalSize = 'OriginalSize',\n}\n\nconst SettingsKey = 'screegoSettings';\n\nexport const loadSettings = (): Settings => {\n    const settings: Partial<Settings> = JSON.parse(localStorage.getItem(SettingsKey) ?? '{}') ?? {};\n\n    const defaults: Settings = {\n        displayMode: VideoDisplayMode.FitToWindow,\n        framerate: 30,\n    };\n\n    if (settings && typeof settings === 'object') {\n        return {\n            name: settings.name?.toString(),\n            framerate: settings.framerate ?? defaults.framerate,\n            displayMode:\n                Object.values(VideoDisplayMode).find((mode) => mode === settings.displayMode) ??\n                defaults.displayMode,\n            preferCodec: settings.preferCodec ?? CodecDefault,\n        };\n    }\n    return defaults;\n};\n\nexport const saveSettings = (settings: Settings): void => {\n    localStorage.setItem(SettingsKey, JSON.stringify(settings));\n};\n\nexport const useSettings = (): [Settings, (s: Settings) => void] => {\n    const [settings, setSettings] = React.useState(loadSettings);\n\n    return [\n        settings,\n        (newSettings) => {\n            setSettings(newSettings);\n            saveSettings(newSettings);\n        },\n    ];\n};\n"
  },
  {
    "path": "ui/src/url.ts",
    "content": "const {port, hostname, protocol, pathname} = window.location;\nconst slashes = protocol.concat('//');\nconst path = pathname.endsWith('/') ? pathname : pathname.substring(0, pathname.lastIndexOf('/'));\nconst url = slashes.concat(port ? hostname.concat(':', port) : hostname) + path;\nexport const urlWithSlash = url.endsWith('/') ? url : url.concat('/');\n"
  },
  {
    "path": "ui/src/useConfig.ts",
    "content": "import {RoomMode, UIConfig} from './message';\nimport {useSnackbar} from 'notistack';\nimport React from 'react';\nimport {urlWithSlash} from './url';\n\nexport interface UseConfig extends UIConfig {\n    login: (username: string, password: string) => Promise<void>;\n    refetch: () => void;\n    logout: () => Promise<void>;\n    loading: boolean;\n}\n\nexport const useConfig = (): UseConfig => {\n    const {enqueueSnackbar} = useSnackbar();\n    const [{loading, ...config}, setConfig] = React.useState<UIConfig & {loading: boolean}>({\n        authMode: 'all',\n        user: 'guest',\n        loggedIn: false,\n        loading: true,\n        version: 'unknown',\n        roomName: 'unknown',\n        closeRoomWhenOwnerLeaves: true,\n    });\n\n    const refetch = React.useCallback(async () => {\n        return fetch(`${urlWithSlash}config`)\n            .then((data) => data.json())\n            .then(setConfig);\n    }, [setConfig]);\n\n    const login = async (username: string, password: string) => {\n        const body = new FormData();\n        body.set('user', username);\n        body.set('pass', password);\n        const result = await fetch(`${urlWithSlash}login`, {method: 'POST', body});\n        const json = await result.json();\n        if (result.status !== 200) {\n            enqueueSnackbar('Login Failed: ' + json.message, {variant: 'error'});\n        } else {\n            await refetch();\n            enqueueSnackbar('Logged in!', {variant: 'success'});\n        }\n    };\n\n    const logout = async () => {\n        const result = await fetch(`${urlWithSlash}logout`, {method: 'POST'});\n        if (result.status !== 200) {\n            enqueueSnackbar('Logout Failed: ' + (await result.text()), {variant: 'error'});\n        } else {\n            await refetch();\n            enqueueSnackbar('Logged Out.', {variant: 'success'});\n        }\n    };\n\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    React.useEffect(() => void refetch(), []);\n\n    return {...config, refetch, loading, login, logout};\n};\n\nexport const authModeToRoomMode = (authMode: UIConfig['authMode'], loggedIn: boolean): RoomMode => {\n    if (loggedIn) {\n        return RoomMode.Turn;\n    }\n    switch (authMode) {\n        case 'all':\n            return RoomMode.Turn;\n        case 'turn':\n            return RoomMode.Stun;\n        case 'none':\n        default:\n            return RoomMode.Turn;\n    }\n};\n"
  },
  {
    "path": "ui/src/useRoom.ts",
    "content": "import {useSnackbar} from 'notistack';\nimport React from 'react';\n\nimport {\n    ICEServer,\n    IncomingMessage,\n    JoinRoom,\n    OutgoingMessage,\n    RoomCreate,\n    RoomInfo,\n    UIConfig,\n} from './message';\nimport {loadSettings, resolveCodecPlaceholder} from './settings';\nimport {urlWithSlash} from './url';\nimport {authModeToRoomMode} from './useConfig';\nimport {getFromURL, useRoomID} from './useRoomID';\n\nexport type RoomState = false | ConnectedRoom;\nexport type ConnectedRoom = {\n    ws: WebSocket;\n    hostStream?: MediaStream;\n    clientStreams: ClientStream[];\n} & RoomInfo;\n\ninterface ClientStream {\n    id: string;\n    peer_id: string;\n    stream: MediaStream;\n}\n\nexport interface UseRoom {\n    state: RoomState;\n    room: FCreateRoom;\n    share: () => void;\n    setName: (name: string) => void;\n    stopShare: () => void;\n}\n\nconst relayConfig: Partial<RTCConfiguration> =\n    window.location.search.indexOf('forceTurn=true') !== -1 ? {iceTransportPolicy: 'relay'} : {};\n\nconst hostSession = async ({\n    sid,\n    ice,\n    send,\n    done,\n    stream,\n}: {\n    sid: string;\n    ice: ICEServer[];\n    send: (e: OutgoingMessage) => void;\n    done: () => void;\n    stream: MediaStream;\n}): Promise<RTCPeerConnection> => {\n    const peer = new RTCPeerConnection({...relayConfig, iceServers: ice});\n    peer.onicecandidate = (event) => {\n        if (!event.candidate) {\n            return;\n        }\n        send({type: 'hostice', payload: {sid: sid, value: event.candidate}});\n    };\n\n    peer.onconnectionstatechange = (event) => {\n        console.log('host change', event);\n        if (\n            peer.connectionState === 'closed' ||\n            peer.connectionState === 'disconnected' ||\n            peer.connectionState === 'failed'\n        ) {\n            peer.close();\n            done();\n        }\n    };\n\n    stream.getTracks().forEach((track) => peer.addTrack(track, stream));\n\n    const preferCodec = resolveCodecPlaceholder(loadSettings().preferCodec);\n    if (preferCodec) {\n        const transceiver = peer\n            .getTransceivers()\n            .find((t) => t.sender && t.sender.track === stream.getVideoTracks()[0]);\n\n        if (!!transceiver && 'setCodecPreferences' in transceiver) {\n            const exactMatch: RTCRtpCodec[] = [];\n            const mimeMatch: RTCRtpCodec[] = [];\n            const others: RTCRtpCodec[] = [];\n\n            RTCRtpReceiver.getCapabilities('video')?.codecs.forEach((codec) => {\n                if (codec.mimeType === preferCodec.mimeType) {\n                    if (codec.sdpFmtpLine === preferCodec.sdpFmtpLine) {\n                        exactMatch.push(codec);\n                    } else {\n                        mimeMatch.push(codec);\n                    }\n                } else {\n                    others.push(codec);\n                }\n            });\n\n            const sortedCodecs = [...exactMatch, ...mimeMatch, ...others];\n\n            console.log('Setting codec preferences', sortedCodecs);\n            transceiver.setCodecPreferences(sortedCodecs);\n        }\n    }\n\n    const hostOffer = await peer.createOffer({offerToReceiveVideo: true});\n    await peer.setLocalDescription(hostOffer);\n    send({type: 'hostoffer', payload: {value: hostOffer, sid: sid}});\n\n    return peer;\n};\n\nconst clientSession = async ({\n    sid,\n    ice,\n    send,\n    done,\n    onTrack,\n}: {\n    sid: string;\n    ice: ICEServer[];\n    send: (e: OutgoingMessage) => void;\n    onTrack: (s: MediaStream) => void;\n    done: () => void;\n}): Promise<RTCPeerConnection> => {\n    console.log('ice', ice);\n    const peer = new RTCPeerConnection({...relayConfig, iceServers: ice});\n    peer.onicecandidate = (event) => {\n        if (!event.candidate) {\n            return;\n        }\n        send({type: 'clientice', payload: {sid: sid, value: event.candidate}});\n    };\n    peer.onconnectionstatechange = (event) => {\n        console.log('client change', event);\n        if (\n            peer.connectionState === 'closed' ||\n            peer.connectionState === 'disconnected' ||\n            peer.connectionState === 'failed'\n        ) {\n            peer.close();\n            done();\n        }\n    };\n\n    let notified = false;\n    const stream = new MediaStream();\n    peer.ontrack = (event) => {\n        stream.addTrack(event.track);\n        if (!notified) {\n            notified = true;\n            onTrack(stream);\n        }\n    };\n\n    return peer;\n};\n\nexport type FCreateRoom = (room: RoomCreate | JoinRoom) => Promise<void>;\n\nexport const useRoom = (config: UIConfig): UseRoom => {\n    const [roomID, setRoomID] = useRoomID();\n    const {enqueueSnackbar} = useSnackbar();\n    const conn = React.useRef<WebSocket | undefined>(undefined);\n    const host = React.useRef<Record<string, RTCPeerConnection>>({});\n    const client = React.useRef<Record<string, RTCPeerConnection>>({});\n    const stream = React.useRef<MediaStream>(undefined);\n\n    const [state, setState] = React.useState<RoomState>(false);\n\n    const room: FCreateRoom = React.useCallback(\n        (create) => {\n            return new Promise<void>((resolve) => {\n                const ws = (conn.current = new WebSocket(\n                    urlWithSlash.replace('http', 'ws') + 'stream'\n                ));\n                const send = (message: OutgoingMessage) => {\n                    if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(message));\n                };\n                let first = true;\n                ws.onmessage = (data) => {\n                    const event: IncomingMessage = JSON.parse(data.data);\n                    if (first) {\n                        first = false;\n                        if (event.type === 'room') {\n                            resolve();\n                            setState({ws, ...event.payload, clientStreams: []});\n                            setRoomID(event.payload.id);\n                        } else {\n                            resolve();\n                            enqueueSnackbar('Unknown Event: ' + event.type, {variant: 'error'});\n                            ws.close(1000, 'received unknown event');\n                        }\n                        return;\n                    }\n\n                    switch (event.type) {\n                        case 'room':\n                            setState((current) =>\n                                current ? {...current, ...event.payload} : current\n                            );\n                            return;\n                        case 'hostsession':\n                            if (!stream.current) {\n                                return;\n                            }\n                            hostSession({\n                                sid: event.payload.id,\n                                stream: stream.current!,\n                                ice: event.payload.iceServers,\n                                send,\n                                done: () => delete host.current[event.payload.id],\n                            }).then((peer) => {\n                                host.current[event.payload.id] = peer;\n                            });\n                            return;\n                        case 'clientsession':\n                            const {id: sid, peer} = event.payload;\n                            clientSession({\n                                sid,\n                                send,\n                                ice: event.payload.iceServers,\n                                done: () => {\n                                    delete client.current[sid];\n                                    setState((current) =>\n                                        current\n                                            ? {\n                                                  ...current,\n                                                  clientStreams: current.clientStreams.filter(\n                                                      ({id}) => id !== sid\n                                                  ),\n                                              }\n                                            : current\n                                    );\n                                },\n                                onTrack: (stream) =>\n                                    setState((current) =>\n                                        current\n                                            ? {\n                                                  ...current,\n                                                  clientStreams: [\n                                                      ...current.clientStreams,\n                                                      {\n                                                          id: sid,\n                                                          stream,\n                                                          peer_id: peer,\n                                                      },\n                                                  ],\n                                              }\n                                            : current\n                                    ),\n                            }).then((peer) => (client.current[event.payload.id] = peer));\n                            return;\n                        case 'clientice':\n                            host.current[event.payload.sid]?.addIceCandidate(event.payload.value);\n                            return;\n                        case 'clientanswer':\n                            host.current[event.payload.sid]?.setRemoteDescription(\n                                event.payload.value\n                            );\n                            return;\n                        case 'hostoffer':\n                            (async () => {\n                                await client.current[event.payload.sid]?.setRemoteDescription(\n                                    event.payload.value\n                                );\n                                const answer =\n                                    await client.current[event.payload.sid]?.createAnswer();\n                                await client.current[event.payload.sid]?.setLocalDescription(\n                                    answer\n                                );\n                                send({\n                                    type: 'clientanswer',\n                                    payload: {sid: event.payload.sid, value: answer},\n                                });\n                            })();\n                            return;\n                        case 'hostice':\n                            client.current[event.payload.sid]?.addIceCandidate(event.payload.value);\n                            return;\n                        case 'endshare':\n                            client.current[event.payload]?.close();\n                            host.current[event.payload]?.close();\n                            setState((current) =>\n                                current\n                                    ? {\n                                          ...current,\n                                          clientStreams: current.clientStreams.filter(\n                                              ({id}) => id !== event.payload\n                                          ),\n                                      }\n                                    : current\n                            );\n                    }\n                };\n                ws.onclose = (event) => {\n                    if (first) {\n                        resolve();\n                        first = false;\n                    }\n                    enqueueSnackbar(event.reason, {variant: 'error', persist: true});\n                    setState(false);\n                };\n                ws.onerror = (err) => {\n                    if (first) {\n                        resolve();\n                        first = false;\n                    }\n                    enqueueSnackbar(err?.toString(), {variant: 'error', persist: true});\n                    setState(false);\n                };\n                ws.onopen = () => {\n                    create.payload.username = loadSettings().name;\n                    send(create);\n                };\n            });\n        },\n        [setState, enqueueSnackbar, setRoomID]\n    );\n\n    const share = async () => {\n        if (!navigator.mediaDevices) {\n            enqueueSnackbar(\n                'Could not start presentation. Are you using https? (mediaDevices undefined)',\n                {variant: 'error', persist: true}\n            );\n            return;\n        }\n        if (typeof navigator.mediaDevices.getDisplayMedia !== 'function') {\n            enqueueSnackbar(\n                `Could not start presentation. Your browser likely doesn't support screensharing. (mediaDevices.getDeviceMedia ${typeof navigator.mediaDevices.getDisplayMedia})`,\n                {variant: 'error', persist: true}\n            );\n            return;\n        }\n        try {\n            stream.current = await navigator.mediaDevices.getDisplayMedia({\n                video: {frameRate: loadSettings().framerate},\n                audio: {\n                    echoCancellation: false,\n                    autoGainControl: false,\n                    noiseSuppression: false,\n                    // https://medium.com/@trystonperry/why-is-getdisplaymedias-audio-quality-so-bad-b49ba9cfaa83\n                    // @ts-expect-error\n                    googAutoGainControl: false,\n                },\n            });\n        } catch (e) {\n            console.log('Could not getDisplayMedia', e);\n            enqueueSnackbar(`Could not start presentation. (getDisplayMedia error). ${e}`, {\n                variant: 'error',\n                persist: true,\n            });\n            return;\n        }\n\n        stream.current?.getVideoTracks()[0].addEventListener('ended', () => stopShare());\n        setState((current) => (current ? {...current, hostStream: stream.current} : current));\n\n        conn.current?.send(JSON.stringify({type: 'share', payload: {}}));\n    };\n\n    const stopShare = async () => {\n        Object.values(host.current).forEach((peer) => {\n            peer.close();\n        });\n        host.current = {};\n        stream.current?.getTracks().forEach((track) => track.stop());\n        stream.current = undefined;\n        conn.current?.send(JSON.stringify({type: 'stopshare', payload: {}}));\n        setState((current) => (current ? {...current, hostStream: undefined} : current));\n    };\n\n    const setName = (name: string): void => {\n        conn.current?.send(JSON.stringify({type: 'name', payload: {username: name}}));\n    };\n\n    React.useEffect(() => {\n        if (roomID) {\n            const create = getFromURL('create') === 'true';\n            if (create) {\n                const closeOnOwnerLeaveString = getFromURL('closeOnOwnerLeave');\n                const closeOnOwnerLeave =\n                    closeOnOwnerLeaveString === undefined\n                        ? config.closeRoomWhenOwnerLeaves\n                        : closeOnOwnerLeaveString === 'true';\n                room({\n                    type: 'create',\n                    payload: {\n                        joinIfExist: true,\n                        closeOnOwnerLeave,\n                        id: roomID,\n                        mode: authModeToRoomMode(config.authMode, config.loggedIn),\n                    },\n                });\n            } else {\n                room({type: 'join', payload: {id: roomID}});\n            }\n        }\n        // eslint-disable-next-line react-hooks/exhaustive-deps\n    }, []);\n\n    return {state, room, share, stopShare, setName};\n};\n"
  },
  {
    "path": "ui/src/useRoomID.ts",
    "content": "import React from 'react';\n\nexport const getRoomFromURL = (): string | undefined => getFromURL('room');\n\nexport const getFromURL = (\n    key: string,\n    search: string = window.location.search\n): string | undefined =>\n    search\n        .slice(1)\n        .split('&')\n        .find((param) => param.startsWith(`${key}=`))\n        ?.split('=')[1];\n\nexport const useRoomID = (): [string | undefined, (v?: string) => void] => {\n    const [state, setState] = React.useState<string | undefined>(() => getRoomFromURL());\n    React.useEffect(() => {\n        const onChange = (): void => setState(getRoomFromURL());\n        window.addEventListener('popstate', onChange);\n        return () => window.removeEventListener('popstate', onChange);\n    }, [setState]);\n    return [\n        state,\n        React.useCallback(\n            (id) =>\n                setState((oldId?: string) => {\n                    if (oldId !== id) {\n                        window.history.pushState({roomId: id}, '', id ? `?room=${id}` : '?');\n                    }\n                    return id;\n                }),\n            [setState]\n        ),\n    ];\n};\n"
  },
  {
    "path": "ui/src/vite-env.d.ts",
    "content": "/// <reference types=\"vite/client\" />\n"
  },
  {
    "path": "ui/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"ES2020\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"ES2020\", \"DOM\", \"DOM.Iterable\"],\n    \"module\": \"ESNext\",\n    \"skipLibCheck\": true,\n\n    \"moduleResolution\": \"bundler\",\n    \"allowImportingTsExtensions\": true,\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\",\n\n    \"strict\": true,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true,\n    \"noFallthroughCasesInSwitch\": true\n  },\n  \"include\": [\"src\"],\n  \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n\n"
  },
  {
    "path": "ui/tsconfig.node.json",
    "content": "{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"skipLibCheck\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"bundler\",\n    \"allowSyntheticDefaultImports\": true\n  },\n  \"include\": [\"vite.config.ts\"]\n}\n"
  },
  {
    "path": "ui/vite.config.mts",
    "content": "import {defineConfig} from 'vite';\nimport react from '@vitejs/plugin-react-swc';\n\nexport default defineConfig({\n    base: './',\n    server: {\n        host: '127.0.0.1',\n        port: 3000,\n        open: false,\n        proxy: {\n            '^/(config|logout|login|stream)$': {\n                target: 'http://localhost:5050',\n                ws: true,\n            },\n        },\n    },\n    build: {outDir: 'build/'},\n    plugins: [react()],\n});\n"
  },
  {
    "path": "users",
    "content": "# Password: admin\nadmin:$2a$12$kNgc2ZYAXzIL6SHY.8PHAOQ8Casi0s1bKatYoG/jupt2yV1M5K5nO\n"
  },
  {
    "path": "util/password.go",
    "content": "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\tfor i := range res {\n\t\tindex := randIntn(len(tokenCharacters))\n\t\tres[i] = tokenCharacters[index]\n\t}\n\treturn string(res)\n}\n\nvar (\n\ttokenCharacters = []byte(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_!@#$%^&*()){}\\\\/=+,.><\")\n\trandReader      = rand.Reader\n)\n\nfunc randIntn(n int) int {\n\tmax := big.NewInt(int64(n))\n\tres, err := rand.Int(randReader, max)\n\tif err != nil {\n\t\tpanic(\"random source is not available\")\n\t}\n\treturn int(res.Int64())\n}\n"
  },
  {
    "path": "util/sillyname.go",
    "content": "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 = []string{\n\t\"able\", \"adaptive\", \"adventurous\", \"affable\", \"agreeable\", \"ambitious\",\n\t\"amiable\", \"amusing\", \"balanced\", \"brave\", \"bright\", \"calm\", \"capable\",\n\t\"charming\", \"clever\", \"compassionate\", \"considerate\", \"courageous\",\n\t\"creative\", \"decisive\", \"determined\", \"discreet\", \"dynamic\",\n\t\"enthusiastic\", \"exuberant\", \"faithful\", \"fearless\", \"friendly\", \"funny\",\n\t\"generous\", \"gentle\", \"good\", \"honest\", \"humorous\", \"independent\",\n\t\"intelligent\", \"intuitive\", \"kind\", \"loving\", \"loyal\", \"modest\", \"nice\",\n\t\"optimistic\", \"patient\", \"pioneering\", \"polite\", \"powerful\", \"reliable\",\n\t\"resourceful\", \"sensible\", \"sincere\", \"thoughtful\", \"tough\", \"versatile\",\n}\n\nvar animals = []string{\n\t\"dog\", \"puppy\", \"turtle\", \"rabbit\", \"parrot\", \"cat\", \"kitten\", \"goldfish\",\n\t\"mouse\", \"hamster\", \"fish\", \"cow\", \"rabbit\", \"duck\", \"shrimp\", \"pig\",\n\t\"goat\", \"crab\", \"deer\", \"bee\", \"sheep\", \"fish\", \"turkey\", \"dove\",\n\t\"chicken\", \"horse\", \"squirrel\", \"dog\", \"chimpanzee\", \"ox\", \"lion\", \"panda\",\n\t\"walrus\", \"otter\", \"mouse\", \"kangaroo\", \"goat\", \"horse\", \"monkey\", \"cow\",\n\t\"koala\", \"mole\", \"elephant\", \"leopard\", \"hippopotamus\", \"giraffe\", \"fox\",\n\t\"coyote\", \"hedgehong\", \"sheep\", \"deer\",\n}\n\nvar colors = []string{\n\t\"amaranth\", \"amber\", \"amethyst\", \"apricot\", \"aqua\", \"aquamarine\", \"azure\",\n\t\"beige\", \"black\", \"blue\", \"blush\", \"bronze\", \"brown\", \"chocolate\",\n\t\"coffee\", \"copper\", \"coral\", \"crimson\", \"cyan\", \"emerald\", \"fuchsia\",\n\t\"gold\", \"gray\", \"green\", \"harlequin\", \"indigo\", \"ivory\", \"jade\",\n\t\"lavender\", \"lime\", \"magenta\", \"maroon\", \"moccasin\", \"olive\", \"orange\",\n\t\"peach\", \"pink\", \"plum\", \"purple\", \"red\", \"rose\", \"salmon\", \"sapphire\",\n\t\"scarlet\", \"silver\", \"tan\", \"teal\", \"tomato\", \"turquoise\", \"violet\",\n\t\"white\", \"yellow\",\n}\n\nfunc r(r *rand.Rand, l []string) string {\n\treturn l[r.Intn(len(l)-1)]\n}\n\nfunc NewUserName(s *rand.Rand) string {\n\ttitle := cases.Title(language.English)\n\treturn title.String(r(s, adjectives)) + \" \" + title.String(r(s, animals))\n}\n\nfunc NewRoomName(s *rand.Rand) string {\n\treturn r(s, adjectives) + \"-\" + r(s, colors) + \"-\" + r(s, animals)\n}\n"
  },
  {
    "path": "ws/client.go",
    "content": "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\t\"github.com/rs/zerolog\"\n\t\"github.com/rs/zerolog/log\"\n\t\"github.com/screego/server/ws/outgoing\"\n)\n\nvar ping = func(conn *websocket.Conn) error {\n\treturn conn.WriteMessage(websocket.PingMessage, nil)\n}\n\nvar writeJSON = func(conn *websocket.Conn, v interface{}) error {\n\treturn conn.WriteJSON(v)\n}\n\nconst (\n\twriteWait = 2 * time.Second\n)\n\ntype Client struct {\n\tconn *websocket.Conn\n\tinfo ClientInfo\n\tonce once\n\tread chan<- ClientMessage\n}\n\ntype ClientMessage struct {\n\tInfo               ClientInfo\n\tSkipConnectedCheck bool\n\tIncoming           Event\n}\n\ntype ClientInfo struct {\n\tID                xid.ID\n\tAuthenticated     bool\n\tAuthenticatedUser string\n\tWrite             chan outgoing.Message\n\tAddr              net.IP\n}\n\nfunc newClient(conn *websocket.Conn, req *http.Request, read chan ClientMessage, authenticatedUser string, authenticated, trustProxy bool) *Client {\n\tip := conn.RemoteAddr().(*net.TCPAddr).IP\n\tif realIP := req.Header.Get(\"X-Real-IP\"); trustProxy && realIP != \"\" {\n\t\tip = net.ParseIP(realIP)\n\t}\n\n\tclient := &Client{\n\t\tconn: conn,\n\t\tinfo: ClientInfo{\n\t\t\tAuthenticated:     authenticated,\n\t\t\tAuthenticatedUser: authenticatedUser,\n\t\t\tID:                xid.New(),\n\t\t\tAddr:              ip,\n\t\t\tWrite:             make(chan outgoing.Message, 1),\n\t\t},\n\t\tread: read,\n\t}\n\tclient.debug().Msg(\"WebSocket New Connection\")\n\treturn client\n}\n\n// CloseOnError closes the connection.\nfunc (c *Client) CloseOnError(code int, reason string) {\n\tc.once.Do(func() {\n\t\tgo func() {\n\t\t\tc.read <- ClientMessage{\n\t\t\t\tInfo: c.info,\n\t\t\t\tIncoming: &Disconnected{\n\t\t\t\t\tCode:   code,\n\t\t\t\t\tReason: reason,\n\t\t\t\t},\n\t\t\t}\n\t\t}()\n\t\tc.writeCloseMessage(code, reason)\n\t})\n}\n\nfunc (c *Client) CloseOnDone(code int, reason string) {\n\tc.once.Do(func() {\n\t\tc.writeCloseMessage(code, reason)\n\t})\n}\n\nfunc (c *Client) writeCloseMessage(code int, reason string) {\n\tmessage := websocket.FormatCloseMessage(code, reason)\n\t_ = c.conn.WriteControl(websocket.CloseMessage, message, time.Now().Add(writeWait))\n\tc.conn.Close()\n}\n\n// startWriteHandler starts listening on the client connection. As we do not need anything from the client,\n// we ignore incoming messages. Leaves the loop on errors.\nfunc (c *Client) startReading(pongWait time.Duration) {\n\tdefer c.CloseOnError(websocket.CloseNormalClosure, \"Reader Routine Closed\")\n\n\t_ = c.conn.SetReadDeadline(time.Now().Add(pongWait))\n\tc.conn.SetPongHandler(func(appData string) error {\n\t\t_ = c.conn.SetReadDeadline(time.Now().Add(pongWait))\n\t\treturn nil\n\t})\n\tfor {\n\t\tt, m, err := c.conn.NextReader()\n\t\tif err != nil {\n\t\t\tc.CloseOnError(websocket.CloseNormalClosure, \"read error: \"+err.Error())\n\t\t\treturn\n\t\t}\n\t\tif t == websocket.BinaryMessage {\n\t\t\tc.CloseOnError(websocket.CloseUnsupportedData, \"unsupported binary message type\")\n\t\t\treturn\n\t\t}\n\n\t\tincoming, err := ReadTypedIncoming(m)\n\t\tif err != nil {\n\t\t\tc.CloseOnError(websocket.CloseUnsupportedData, fmt.Sprintf(\"malformed message: %s\", err))\n\t\t\treturn\n\t\t}\n\t\tc.debug().Interface(\"event\", fmt.Sprintf(\"%T\", incoming)).Interface(\"payload\", incoming).Msg(\"WebSocket Receive\")\n\t\tc.read <- ClientMessage{Info: c.info, Incoming: incoming}\n\t}\n}\n\n// startWriteHandler starts the write loop. The method has the following tasks:\n// * ping the client in the interval provided as parameter\n// * write messages send by the channel to the client\n// * on errors exit the loop.\nfunc (c *Client) startWriteHandler(pingPeriod time.Duration) {\n\tpingTicker := time.NewTicker(pingPeriod)\n\tdefer pingTicker.Stop()\n\tdefer func() {\n\t\tc.debug().Msg(\"WebSocket Done\")\n\t}()\n\tdefer c.conn.Close()\n\tfor {\n\t\tselect {\n\t\tcase message := <-c.info.Write:\n\t\t\tif msg, ok := message.(outgoing.CloseWriter); ok {\n\t\t\t\tc.debug().Str(\"reason\", msg.Reason).Int(\"code\", msg.Code).Msg(\"WebSocket Close\")\n\t\t\t\tc.CloseOnDone(msg.Code, msg.Reason)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t_ = c.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\ttyped, err := ToTypedOutgoing(message)\n\t\t\tc.debug().Interface(\"event\", typed.Type).Interface(\"payload\", typed.Payload).Msg(\"WebSocket Send\")\n\t\t\tif err != nil {\n\t\t\t\tc.debug().Err(err).Msg(\"could not get typed message, exiting connection.\")\n\t\t\t\tc.CloseOnError(websocket.CloseNormalClosure, \"malformed outgoing \"+err.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err := writeJSON(c.conn, typed); err != nil {\n\t\t\t\tc.printWebSocketError(\"write\", err)\n\t\t\t\tc.CloseOnError(websocket.CloseNormalClosure, \"write error\"+err.Error())\n\t\t\t}\n\t\tcase <-pingTicker.C:\n\t\t\t_ = c.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := ping(c.conn); err != nil {\n\t\t\t\tc.printWebSocketError(\"ping\", err)\n\t\t\t\tc.CloseOnError(websocket.CloseNormalClosure, \"ping timeout\")\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (c *Client) debug() *zerolog.Event {\n\treturn log.Debug().Str(\"id\", c.info.ID.String()).Str(\"ip\", c.info.Addr.String())\n}\n\nfunc (c *Client) printWebSocketError(typex string, err error) {\n\tif strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\treturn\n\t}\n\tcloseError, ok := err.(*websocket.CloseError)\n\n\tif ok && closeError != nil && (closeError.Code == 1000 || closeError.Code == 1001) {\n\t\t// normal closure\n\t\treturn\n\t}\n\n\tc.debug().Str(\"type\", typex).Err(err).Msg(\"WebSocket Error\")\n}\n"
  },
  {
    "path": "ws/event.go",
    "content": "package ws\n\ntype Event interface {\n\tExecute(*Rooms, ClientInfo) error\n}\n"
  },
  {
    "path": "ws/event_clientanswer.go",
    "content": "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\tregister(\"clientanswer\", func() Event {\n\t\treturn &ClientAnswer{}\n\t})\n}\n\ntype ClientAnswer outgoing.P2PMessage\n\nfunc (e *ClientAnswer) Execute(rooms *Rooms, current ClientInfo) error {\n\troom, err := rooms.CurrentRoom(current)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession, ok := room.Sessions[e.SID]\n\n\tif !ok {\n\t\tlog.Debug().Str(\"id\", e.SID.String()).Msg(\"unknown session\")\n\t\treturn nil\n\t}\n\n\tif session.Client != current.ID {\n\t\treturn fmt.Errorf(\"permission denied for session %s\", e.SID)\n\t}\n\n\troom.Users[session.Host].WriteTimeout(outgoing.ClientAnswer(*e))\n\n\treturn nil\n}\n"
  },
  {
    "path": "ws/event_clientice.go",
    "content": "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\tregister(\"clientice\", func() Event {\n\t\treturn &ClientICE{}\n\t})\n}\n\ntype ClientICE outgoing.P2PMessage\n\nfunc (e *ClientICE) Execute(rooms *Rooms, current ClientInfo) error {\n\troom, err := rooms.CurrentRoom(current)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession, ok := room.Sessions[e.SID]\n\n\tif !ok {\n\t\tlog.Debug().Str(\"id\", e.SID.String()).Msg(\"unknown session\")\n\t\treturn nil\n\t}\n\n\tif session.Client != current.ID {\n\t\treturn fmt.Errorf(\"permission denied for session %s\", e.SID)\n\t}\n\n\troom.Users[session.Host].WriteTimeout(outgoing.ClientICE(*e))\n\n\treturn nil\n}\n"
  },
  {
    "path": "ws/event_connected.go",
    "content": "package ws\n\ntype Connected struct{}\n\nfunc (e Connected) Execute(rooms *Rooms, current ClientInfo) error {\n\trooms.connected[current.ID] = \"\"\n\treturn nil\n}\n"
  },
  {
    "path": "ws/event_create.go",
    "content": "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\tregister(\"create\", func() Event {\n\t\treturn &Create{}\n\t})\n}\n\ntype Create struct {\n\tID                string         `json:\"id\"`\n\tMode              ConnectionMode `json:\"mode\"`\n\tCloseOnOwnerLeave bool           `json:\"closeOnOwnerLeave\"`\n\tUserName          string         `json:\"username\"`\n\tJoinIfExist       bool           `json:\"joinIfExist,omitempty\"`\n}\n\nfunc (e *Create) Execute(rooms *Rooms, current ClientInfo) error {\n\tif rooms.connected[current.ID] != \"\" {\n\t\treturn fmt.Errorf(\"cannot join room, you are already in one\")\n\t}\n\n\tif _, ok := rooms.Rooms[e.ID]; ok {\n\t\tif e.JoinIfExist {\n\t\t\tjoin := &Join{UserName: e.UserName, ID: e.ID}\n\t\t\treturn join.Execute(rooms, current)\n\t\t}\n\n\t\treturn fmt.Errorf(\"room with id %s does already exist\", e.ID)\n\t}\n\n\tname := e.UserName\n\tif current.Authenticated {\n\t\tname = current.AuthenticatedUser\n\t}\n\tif name == \"\" {\n\t\tname = rooms.RandUserName()\n\t}\n\n\tswitch rooms.config.AuthMode {\n\tcase config.AuthModeNone:\n\tcase config.AuthModeAll:\n\t\tif !current.Authenticated {\n\t\t\treturn errors.New(\"you need to login\")\n\t\t}\n\tcase config.AuthModeTurn:\n\t\tif e.Mode != ConnectionSTUN && e.Mode != ConnectionLocal && !current.Authenticated {\n\t\t\treturn errors.New(\"you need to login\")\n\t\t}\n\tdefault:\n\t\treturn errors.New(\"invalid authmode:\" + rooms.config.AuthMode)\n\t}\n\n\troom := &Room{\n\t\tID:                e.ID,\n\t\tCloseOnOwnerLeave: e.CloseOnOwnerLeave,\n\t\tMode:              e.Mode,\n\t\tSessions:          map[xid.ID]*RoomSession{},\n\t\tUsers: map[xid.ID]*User{\n\t\t\tcurrent.ID: {\n\t\t\t\tID:        current.ID,\n\t\t\t\tName:      name,\n\t\t\t\tStreaming: false,\n\t\t\t\tOwner:     true,\n\t\t\t\tAddr:      current.Addr,\n\t\t\t\t_write:    current.Write,\n\t\t\t},\n\t\t},\n\t}\n\trooms.connected[current.ID] = room.ID\n\trooms.Rooms[e.ID] = room\n\troom.notifyInfoChanged()\n\tusersJoinedTotal.Inc()\n\troomsCreatedTotal.Inc()\n\treturn nil\n}\n"
  },
  {
    "path": "ws/event_disconnected.go",
    "content": "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 Disconnected struct {\n\tCode   int\n\tReason string\n}\n\nfunc (e *Disconnected) Execute(rooms *Rooms, current ClientInfo) error {\n\te.executeNoError(rooms, current)\n\treturn nil\n}\n\nfunc (e *Disconnected) executeNoError(rooms *Rooms, current ClientInfo) {\n\troomID := rooms.connected[current.ID]\n\tdelete(rooms.connected, current.ID)\n\twriteTimeout[outgoing.Message](current.Write, outgoing.CloseWriter{Code: e.Code, Reason: e.Reason})\n\n\tif roomID == \"\" {\n\t\treturn\n\t}\n\n\troom, ok := rooms.Rooms[roomID]\n\tif !ok {\n\t\t// room may already be removed\n\t\treturn\n\t}\n\n\tuser, ok := room.Users[current.ID]\n\n\tif !ok {\n\t\t// room may already be removed\n\t\treturn\n\t}\n\n\tdelete(room.Users, current.ID)\n\tusersLeftTotal.Inc()\n\n\tfor id, session := range room.Sessions {\n\t\tif bytes.Equal(session.Client.Bytes(), current.ID.Bytes()) {\n\t\t\thost, ok := room.Users[session.Host]\n\t\t\tif ok {\n\t\t\t\thost.WriteTimeout(outgoing.EndShare(id))\n\t\t\t}\n\t\t\troom.closeSession(rooms, id)\n\t\t}\n\t\tif bytes.Equal(session.Host.Bytes(), current.ID.Bytes()) {\n\t\t\tclient, ok := room.Users[session.Client]\n\t\t\tif ok {\n\t\t\t\tclient.WriteTimeout(outgoing.EndShare(id))\n\t\t\t}\n\t\t\troom.closeSession(rooms, id)\n\t\t}\n\t}\n\n\tif user.Owner && room.CloseOnOwnerLeave {\n\t\tfor _, member := range room.Users {\n\t\t\tdelete(rooms.connected, member.ID)\n\t\t\tmember.WriteTimeout(outgoing.CloseWriter{Code: websocket.CloseNormalClosure, Reason: CloseOwnerLeft})\n\t\t}\n\t\trooms.closeRoom(roomID)\n\t\treturn\n\t}\n\n\tif len(room.Users) == 0 {\n\t\trooms.closeRoom(roomID)\n\t\treturn\n\t}\n\n\troom.notifyInfoChanged()\n}\n"
  },
  {
    "path": "ws/event_health.go",
    "content": "package ws\n\ntype Health struct {\n\tResponse chan int\n}\n\nfunc (e *Health) Execute(rooms *Rooms, current ClientInfo) error {\n\twriteTimeout(e.Response, len(rooms.connected))\n\treturn nil\n}\n"
  },
  {
    "path": "ws/event_hostice.go",
    "content": "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\tregister(\"hostice\", func() Event {\n\t\treturn &HostICE{}\n\t})\n}\n\ntype HostICE outgoing.P2PMessage\n\nfunc (e *HostICE) Execute(rooms *Rooms, current ClientInfo) error {\n\troom, err := rooms.CurrentRoom(current)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession, ok := room.Sessions[e.SID]\n\n\tif !ok {\n\t\tlog.Debug().Str(\"id\", e.SID.String()).Msg(\"unknown session\")\n\t\treturn nil\n\t}\n\n\tif session.Host != current.ID {\n\t\treturn fmt.Errorf(\"permission denied for session %s\", e.SID)\n\t}\n\n\troom.Users[session.Client].WriteTimeout(outgoing.HostICE(*e))\n\n\treturn nil\n}\n"
  },
  {
    "path": "ws/event_hostoffer.go",
    "content": "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\tregister(\"hostoffer\", func() Event {\n\t\treturn &HostOffer{}\n\t})\n}\n\ntype HostOffer outgoing.P2PMessage\n\nfunc (e *HostOffer) Execute(rooms *Rooms, current ClientInfo) error {\n\troom, err := rooms.CurrentRoom(current)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession, ok := room.Sessions[e.SID]\n\n\tif !ok {\n\t\tlog.Debug().Str(\"id\", e.SID.String()).Msg(\"unknown session\")\n\t\treturn nil\n\t}\n\n\tif session.Host != current.ID {\n\t\treturn fmt.Errorf(\"permission denied for session %s\", e.SID)\n\t}\n\n\troom.Users[session.Client].WriteTimeout(outgoing.HostOffer(*e))\n\n\treturn nil\n}\n"
  },
  {
    "path": "ws/event_join.go",
    "content": "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 {\n\tID       string `json:\"id\"`\n\tUserName string `json:\"username,omitempty\"`\n}\n\nfunc (e *Join) Execute(rooms *Rooms, current ClientInfo) error {\n\tif rooms.connected[current.ID] != \"\" {\n\t\treturn fmt.Errorf(\"cannot join room, you are already in one\")\n\t}\n\n\troom, ok := rooms.Rooms[e.ID]\n\tif !ok {\n\t\treturn fmt.Errorf(\"room with id %s does not exist\", e.ID)\n\t}\n\tname := e.UserName\n\tif current.Authenticated {\n\t\tname = current.AuthenticatedUser\n\t}\n\tif name == \"\" {\n\t\tname = rooms.RandUserName()\n\t}\n\n\troom.Users[current.ID] = &User{\n\t\tID:        current.ID,\n\t\tName:      name,\n\t\tStreaming: false,\n\t\tOwner:     false,\n\t\tAddr:      current.Addr,\n\t\t_write:    current.Write,\n\t}\n\trooms.connected[current.ID] = room.ID\n\troom.notifyInfoChanged()\n\tusersJoinedTotal.Inc()\n\n\tv4, v6, err := rooms.config.TurnIPProvider.Get()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, user := range room.Users {\n\t\tif current.ID == user.ID || !user.Streaming {\n\t\t\tcontinue\n\t\t}\n\t\troom.newSession(user.ID, current.ID, rooms, v4, v6)\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "ws/event_name.go",
    "content": "package ws\n\nfunc init() {\n\tregister(\"name\", func() Event {\n\t\treturn &Name{}\n\t})\n}\n\ntype Name struct {\n\tUserName string `json:\"username\"`\n}\n\nfunc (e *Name) Execute(rooms *Rooms, current ClientInfo) error {\n\troom, err := rooms.CurrentRoom(current)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\troom.Users[current.ID].Name = e.UserName\n\n\troom.notifyInfoChanged()\n\treturn nil\n}\n"
  },
  {
    "path": "ws/event_share.go",
    "content": "package ws\n\nfunc init() {\n\tregister(\"share\", func() Event {\n\t\treturn &StartShare{}\n\t})\n}\n\ntype StartShare struct{}\n\nfunc (e *StartShare) Execute(rooms *Rooms, current ClientInfo) error {\n\troom, err := rooms.CurrentRoom(current)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\troom.Users[current.ID].Streaming = true\n\n\tv4, v6, err := rooms.config.TurnIPProvider.Get()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, user := range room.Users {\n\t\tif current.ID == user.ID {\n\t\t\tcontinue\n\t\t}\n\t\troom.newSession(current.ID, user.ID, rooms, v4, v6)\n\t}\n\n\troom.notifyInfoChanged()\n\treturn nil\n}\n"
  },
  {
    "path": "ws/event_stop_share.go",
    "content": "package ws\n\nimport (\n\t\"bytes\"\n\n\t\"github.com/screego/server/ws/outgoing\"\n)\n\nfunc init() {\n\tregister(\"stopshare\", func() Event {\n\t\treturn &StopShare{}\n\t})\n}\n\ntype StopShare struct{}\n\nfunc (e *StopShare) Execute(rooms *Rooms, current ClientInfo) error {\n\troom, err := rooms.CurrentRoom(current)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\troom.Users[current.ID].Streaming = false\n\tfor id, session := range room.Sessions {\n\t\tif bytes.Equal(session.Host.Bytes(), current.ID.Bytes()) {\n\t\t\tclient, ok := room.Users[session.Client]\n\t\t\tif ok {\n\t\t\t\tclient.WriteTimeout(outgoing.EndShare(id))\n\t\t\t}\n\t\t\troom.closeSession(rooms, id)\n\t\t}\n\t}\n\n\troom.notifyInfoChanged()\n\treturn nil\n}\n"
  },
  {
    "path": "ws/once.go",
    "content": "// Copyright 2009 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\npackage ws\n\nimport (\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\n// Modified version of sync.Once (https://github.com/golang/go/blob/master/src/sync/once.go)\n// This version unlocks the mutex early and therefore doesn't hold the lock while executing func f().\ntype once struct {\n\tm    sync.Mutex\n\tdone uint32\n}\n\nfunc (o *once) Do(f func()) {\n\tif atomic.LoadUint32(&o.done) == 1 {\n\t\treturn\n\t}\n\tif o.mayExecute() {\n\t\tf()\n\t}\n}\n\nfunc (o *once) mayExecute() bool {\n\to.m.Lock()\n\tdefer o.m.Unlock()\n\tif o.done == 0 {\n\t\tatomic.StoreUint32(&o.done, 1)\n\t\treturn true\n\t}\n\treturn false\n}\n"
  },
  {
    "path": "ws/once_test.go",
    "content": "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\texecuteOnce := once{}\n\texecution := make(chan struct{})\n\tfExecute := func() {\n\t\texecution <- struct{}{}\n\t}\n\tgo executeOnce.Do(fExecute)\n\tgo executeOnce.Do(fExecute)\n\n\tselect {\n\tcase <-execution:\n\t\t// expected\n\tcase <-time.After(100 * time.Millisecond):\n\t\tt.Fatal(\"fExecute should be executed once\")\n\t}\n\n\tselect {\n\tcase <-execution:\n\t\tt.Fatal(\"should only execute once\")\n\tcase <-time.After(100 * time.Millisecond):\n\t\t// expected\n\t}\n\n\tassert.False(t, executeOnce.mayExecute())\n\n\tgo executeOnce.Do(fExecute)\n\n\tselect {\n\tcase <-execution:\n\t\tt.Fatal(\"should only execute once\")\n\tcase <-time.After(100 * time.Millisecond):\n\t\t// expected\n\t}\n}\n"
  },
  {
    "path": "ws/outgoing/messages.go",
    "content": "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 Room struct {\n\tID    string         `json:\"id\"`\n\tMode  ConnectionMode `json:\"mode\"`\n\tUsers []User         `json:\"users\"`\n}\n\ntype User struct {\n\tID        xid.ID `json:\"id\"`\n\tName      string `json:\"name\"`\n\tStreaming bool   `json:\"streaming\"`\n\tYou       bool   `json:\"you\"`\n\tOwner     bool   `json:\"owner\"`\n}\n\nfunc (Room) Type() string {\n\treturn \"room\"\n}\n\ntype HostSession struct {\n\tID         xid.ID      `json:\"id\"`\n\tPeer       xid.ID      `json:\"peer\"`\n\tICEServers []ICEServer `json:\"iceServers\"`\n}\n\nfunc (HostSession) Type() string {\n\treturn \"hostsession\"\n}\n\ntype ClientSession struct {\n\tID         xid.ID      `json:\"id\"`\n\tPeer       xid.ID      `json:\"peer\"`\n\tICEServers []ICEServer `json:\"iceServers\"`\n}\n\nfunc (ClientSession) Type() string {\n\treturn \"clientsession\"\n}\n\ntype ICEServer struct {\n\tURLs       []string `json:\"urls\"`\n\tCredential string   `json:\"credential\"`\n\tUsername   string   `json:\"username\"`\n}\n\ntype P2PMessage struct {\n\tSID   xid.ID          `json:\"sid\"`\n\tValue json.RawMessage `json:\"value\"`\n}\n\ntype HostICE P2PMessage\n\nfunc (HostICE) Type() string {\n\treturn \"hostice\"\n}\n\ntype ClientICE P2PMessage\n\nfunc (ClientICE) Type() string {\n\treturn \"clientice\"\n}\n\ntype ClientAnswer P2PMessage\n\nfunc (ClientAnswer) Type() string {\n\treturn \"clientanswer\"\n}\n\ntype HostOffer P2PMessage\n\nfunc (HostOffer) Type() string {\n\treturn \"hostoffer\"\n}\n\ntype EndShare xid.ID\n\nfunc (EndShare) Type() string {\n\treturn \"endshare\"\n}\n\ntype ConnectionMode string\n\nconst (\n\tConnectionLocal ConnectionMode = \"local\"\n\tConnectionSTUN  ConnectionMode = \"stun\"\n\tConnectionTURN  ConnectionMode = \"turn\"\n)\n\ntype CloseWriter struct {\n\tCode   int\n\tReason string\n}\n\nfunc (CloseWriter) Type() string {\n\treturn \"closewriter\"\n}\n"
  },
  {
    "path": "ws/prometheus.go",
    "content": "package ws\n\nimport (\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"\n)\n\nvar (\n\troomsCreatedTotal = promauto.NewCounter(prometheus.CounterOpts{\n\t\tName: \"screego_room_created_total\",\n\t\tHelp: \"The total number of rooms created\",\n\t})\n\troomsClosedTotal = promauto.NewCounter(prometheus.CounterOpts{\n\t\tName: \"screego_room_closed_total\",\n\t\tHelp: \"The total number of rooms closed\",\n\t})\n\tusersJoinedTotal = promauto.NewCounter(prometheus.CounterOpts{\n\t\tName: \"screego_user_joined_total\",\n\t\tHelp: \"The total number of users joined\",\n\t})\n\tusersLeftTotal = promauto.NewCounter(prometheus.CounterOpts{\n\t\tName: \"screego_user_left_total\",\n\t\tHelp: \"The total number of users left\",\n\t})\n\tsessionCreatedTotal = promauto.NewCounter(prometheus.CounterOpts{\n\t\tName: \"screego_session_created_total\",\n\t\tHelp: \"The total number of sessions created\",\n\t})\n\tsessionClosedTotal = promauto.NewCounter(prometheus.CounterOpts{\n\t\tName: \"screego_session_closed_total\",\n\t\tHelp: \"The total number of sessions closed\",\n\t})\n)\n"
  },
  {
    "path": "ws/readwrite.go",
    "content": "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 struct {\n\tType    string          `json:\"type\"`\n\tPayload json.RawMessage `json:\"payload\"`\n}\n\nfunc ToTypedOutgoing(outgoing outgoing.Message) (Typed, error) {\n\tpayload, err := json.Marshal(outgoing)\n\tif err != nil {\n\t\treturn Typed{}, err\n\t}\n\treturn Typed{\n\t\tType:    outgoing.Type(),\n\t\tPayload: payload,\n\t}, nil\n}\n\nfunc ReadTypedIncoming(r io.Reader) (Event, error) {\n\ttyped := Typed{}\n\tif err := json.NewDecoder(r).Decode(&typed); err != nil {\n\t\treturn nil, fmt.Errorf(\"%s e\", err)\n\t}\n\n\tcreate, ok := provider[typed.Type]\n\n\tif !ok {\n\t\treturn nil, errors.New(\"cannot handle \" + typed.Type)\n\t}\n\n\tpayload := create()\n\n\tif err := json.Unmarshal(typed.Payload, payload); err != nil {\n\t\treturn nil, fmt.Errorf(\"incoming payload %s\", err)\n\t}\n\treturn payload, nil\n}\n\nvar provider = map[string]func() Event{}\n\nfunc register(t string, incoming func() Event) {\n\tprovider[t] = incoming\n}\n"
  },
  {
    "path": "ws/room.go",
    "content": "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/screego/server/config\"\n\t\"github.com/screego/server/ws/outgoing\"\n)\n\ntype ConnectionMode string\n\nconst (\n\tConnectionLocal ConnectionMode = \"local\"\n\tConnectionSTUN  ConnectionMode = \"stun\"\n\tConnectionTURN  ConnectionMode = config.AuthModeTurn\n)\n\ntype Room struct {\n\tID                string\n\tCloseOnOwnerLeave bool\n\tMode              ConnectionMode\n\tUsers             map[xid.ID]*User\n\tSessions          map[xid.ID]*RoomSession\n}\n\nconst (\n\tCloseOwnerLeft = \"Owner Left\"\n\tCloseDone      = \"Read End\"\n)\n\nfunc (r *Room) newSession(host, client xid.ID, rooms *Rooms, v4, v6 net.IP) {\n\tid := xid.New()\n\tr.Sessions[id] = &RoomSession{\n\t\tHost:   host,\n\t\tClient: client,\n\t}\n\tsessionCreatedTotal.Inc()\n\n\ticeHost := []outgoing.ICEServer{}\n\ticeClient := []outgoing.ICEServer{}\n\tswitch r.Mode {\n\tcase ConnectionLocal:\n\tcase ConnectionSTUN:\n\t\ticeHost = []outgoing.ICEServer{{URLs: rooms.addresses(\"stun\", v4, v6, false)}}\n\t\ticeClient = []outgoing.ICEServer{{URLs: rooms.addresses(\"stun\", v4, v6, false)}}\n\tcase ConnectionTURN:\n\t\thostName, hostPW := rooms.turnServer.Credentials(id.String()+\"host\", r.Users[host].Addr)\n\t\tclientName, clientPW := rooms.turnServer.Credentials(id.String()+\"client\", r.Users[client].Addr)\n\t\ticeHost = []outgoing.ICEServer{{\n\t\t\tURLs:       rooms.addresses(\"turn\", v4, v6, true),\n\t\t\tCredential: hostPW,\n\t\t\tUsername:   hostName,\n\t\t}}\n\t\ticeClient = []outgoing.ICEServer{{\n\t\t\tURLs:       rooms.addresses(\"turn\", v4, v6, true),\n\t\t\tCredential: clientPW,\n\t\t\tUsername:   clientName,\n\t\t}}\n\t}\n\tr.Users[host].WriteTimeout(outgoing.HostSession{Peer: client, ID: id, ICEServers: iceHost})\n\tr.Users[client].WriteTimeout(outgoing.ClientSession{Peer: host, ID: id, ICEServers: iceClient})\n}\n\nfunc (r *Rooms) addresses(prefix string, v4, v6 net.IP, tcp bool) (result []string) {\n\tif v4 != nil {\n\t\tresult = append(result, fmt.Sprintf(\"%s:%s:%s\", prefix, v4.String(), r.config.TurnPort))\n\t\tif tcp {\n\t\t\tresult = append(result, fmt.Sprintf(\"%s:%s:%s?transport=tcp\", prefix, v4.String(), r.config.TurnPort))\n\t\t}\n\t}\n\tif v6 != nil {\n\t\tresult = append(result, fmt.Sprintf(\"%s:[%s]:%s\", prefix, v6.String(), r.config.TurnPort))\n\t\tif tcp {\n\t\t\tresult = append(result, fmt.Sprintf(\"%s:[%s]:%s?transport=tcp\", prefix, v6.String(), r.config.TurnPort))\n\t\t}\n\t}\n\treturn\n}\n\nfunc (r *Room) closeSession(rooms *Rooms, id xid.ID) {\n\tif r.Mode == ConnectionTURN {\n\t\trooms.turnServer.Disallow(id.String() + \"host\")\n\t\trooms.turnServer.Disallow(id.String() + \"client\")\n\t}\n\tdelete(r.Sessions, id)\n\tsessionClosedTotal.Inc()\n}\n\ntype RoomSession struct {\n\tHost   xid.ID\n\tClient xid.ID\n}\n\nfunc (r *Room) notifyInfoChanged() {\n\tfor _, current := range r.Users {\n\t\tusers := []outgoing.User{}\n\t\tfor _, user := range r.Users {\n\t\t\tusers = append(users, outgoing.User{\n\t\t\t\tID:        user.ID,\n\t\t\t\tName:      user.Name,\n\t\t\t\tStreaming: user.Streaming,\n\t\t\t\tYou:       current == user,\n\t\t\t\tOwner:     user.Owner,\n\t\t\t})\n\t\t}\n\n\t\tsort.Slice(users, func(i, j int) bool {\n\t\t\tleft := users[i]\n\t\t\tright := users[j]\n\n\t\t\tif left.Owner != right.Owner {\n\t\t\t\treturn left.Owner\n\t\t\t}\n\n\t\t\tif left.Streaming != right.Streaming {\n\t\t\t\treturn left.Streaming\n\t\t\t}\n\n\t\t\treturn left.Name < right.Name\n\t\t})\n\n\t\tcurrent.WriteTimeout(outgoing.Room{\n\t\t\tID:    r.ID,\n\t\t\tUsers: users,\n\t\t})\n\t}\n}\n\ntype User struct {\n\tID        xid.ID\n\tAddr      net.IP\n\tName      string\n\tStreaming bool\n\tOwner     bool\n\t_write    chan<- outgoing.Message\n}\n\nfunc (u *User) WriteTimeout(msg outgoing.Message) {\n\twriteTimeout(u._write, msg)\n}\n\nfunc writeTimeout[T any](ch chan<- T, msg T) {\n\tselect {\n\tcase <-time.After(2 * time.Second):\n\t\tlog.Warn().Interface(\"event\", fmt.Sprintf(\"%T\", msg)).Interface(\"payload\", msg).Msg(\"Client write loop didn't accept the message.\")\n\tcase ch <- msg:\n\t}\n}\n"
  },
  {
    "path": "ws/rooms.go",
    "content": "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/xid\"\n\t\"github.com/rs/zerolog/log\"\n\t\"github.com/screego/server/auth\"\n\t\"github.com/screego/server/config\"\n\t\"github.com/screego/server/turn\"\n\t\"github.com/screego/server/util\"\n)\n\nfunc NewRooms(tServer turn.Server, users *auth.Users, conf config.Config) *Rooms {\n\treturn &Rooms{\n\t\tRooms:      map[string]*Room{},\n\t\tIncoming:   make(chan ClientMessage),\n\t\tconnected:  map[xid.ID]string{},\n\t\tturnServer: tServer,\n\t\tusers:      users,\n\t\tconfig:     conf,\n\t\tr:          rand.New(rand.NewSource(time.Now().Unix())),\n\t\tupgrader: websocket.Upgrader{\n\t\t\tReadBufferSize:  1024,\n\t\t\tWriteBufferSize: 1024,\n\t\t\tCheckOrigin: func(r *http.Request) bool {\n\t\t\t\torigin := r.Header.Get(\"origin\")\n\t\t\t\tu, err := url.Parse(origin)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif u.Host == r.Host {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\treturn conf.CheckOrigin(origin)\n\t\t\t},\n\t\t},\n\t}\n}\n\ntype Rooms struct {\n\tturnServer turn.Server\n\tRooms      map[string]*Room\n\tIncoming   chan ClientMessage\n\tupgrader   websocket.Upgrader\n\tusers      *auth.Users\n\tconfig     config.Config\n\tr          *rand.Rand\n\tconnected  map[xid.ID]string\n}\n\nfunc (r *Rooms) CurrentRoom(info ClientInfo) (*Room, error) {\n\troomID, ok := r.connected[info.ID]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"not connected\")\n\t}\n\tif roomID == \"\" {\n\t\treturn nil, fmt.Errorf(\"not in a room\")\n\t}\n\troom, ok := r.Rooms[roomID]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"room with id %s does not exist\", roomID)\n\t}\n\n\treturn room, nil\n}\n\nfunc (r *Rooms) RandUserName() string {\n\treturn util.NewUserName(r.r)\n}\n\nfunc (r *Rooms) RandRoomName() string {\n\treturn util.NewRoomName(r.r)\n}\n\nfunc (r *Rooms) Upgrade(w http.ResponseWriter, req *http.Request) {\n\tconn, err := r.upgrader.Upgrade(w, req, nil)\n\tif err != nil {\n\t\tlog.Debug().Err(err).Msg(\"Websocket upgrade\")\n\t\tw.WriteHeader(400)\n\t\t_, _ = fmt.Fprintf(w, \"Upgrade failed %s\", err)\n\t\treturn\n\t}\n\n\tuser, loggedIn := r.users.CurrentUser(req)\n\tc := newClient(conn, req, r.Incoming, user, loggedIn, r.config.TrustProxyHeaders)\n\tr.Incoming <- ClientMessage{Info: c.info, Incoming: Connected{}, SkipConnectedCheck: true}\n\n\tgo c.startReading(time.Second * 20)\n\tgo c.startWriteHandler(time.Second * 5)\n}\n\nfunc (r *Rooms) Start() {\n\tfor msg := range r.Incoming {\n\t\t_, connected := r.connected[msg.Info.ID]\n\t\tif !msg.SkipConnectedCheck && !connected {\n\t\t\tlog.Debug().Interface(\"event\", fmt.Sprintf(\"%T\", msg.Incoming)).Interface(\"payload\", msg.Incoming).Msg(\"WebSocket Ignore\")\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := msg.Incoming.Execute(r, msg.Info); err != nil {\n\t\t\tdis := Disconnected{Code: websocket.CloseNormalClosure, Reason: err.Error()}\n\t\t\tdis.executeNoError(r, msg.Info)\n\t\t}\n\t}\n}\n\nfunc (r *Rooms) Count() (int, string) {\n\ttimeout := time.After(5 * time.Second)\n\n\th := Health{Response: make(chan int, 1)}\n\tselect {\n\tcase r.Incoming <- ClientMessage{SkipConnectedCheck: true, Incoming: &h}:\n\tcase <-timeout:\n\t\treturn -1, \"main loop didn't accept a message within 5 second\"\n\t}\n\tselect {\n\tcase count := <-h.Response:\n\t\treturn count, \"\"\n\tcase <-timeout:\n\t\treturn -1, \"main loop didn't respond to a message within 5 second\"\n\t}\n}\n\nfunc (r *Rooms) closeRoom(roomID string) {\n\troom, ok := r.Rooms[roomID]\n\tif !ok {\n\t\treturn\n\t}\n\tusersLeftTotal.Add(float64(len(room.Users)))\n\tfor id := range room.Sessions {\n\t\troom.closeSession(r, id)\n\t}\n\n\tdelete(r.Rooms, roomID)\n\troomsClosedTotal.Inc()\n}\n"
  },
  {
    "path": "ws/rooms_test.go",
    "content": "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\"github.com/rs/xid\"\n)\n\nconst SERVER = \"ws://localhost:5050/stream\"\n\nfunc TestMultipleClients(t *testing.T) {\n\tt.Skip(\"only for manual testing\")\n\tr := rand.New(rand.NewSource(time.Now().UnixMicro()))\n\n\tvar wg sync.WaitGroup\n\n\tfor j := 0; j < 100; j++ {\n\t\tname := fmt.Sprint(1)\n\n\t\tusers := r.Intn(5000)\n\t\tfor i := 0; i < users; i++ {\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\ttestClient(r.Int63(), name)\n\t\t\t}()\n\t\t\tif i%100 == 0 {\n\t\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(50 * time.Millisecond)\n\t}\n\n\twg.Wait()\n}\n\nfunc testClient(i int64, room string) {\n\tr := rand.New(rand.NewSource(i))\n\tconn, _, err := websocket.DefaultDialer.Dial(SERVER, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\t_ = conn.SetReadDeadline(time.Now().Add(10 * time.Second))\n\t\t\t_, _, err := conn.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\tdefer conn.Close()\n\n\tops := r.Intn(100)\n\tfor i := 0; i < ops; i++ {\n\t\tm := msg(r, room)\n\t\terr = conn.WriteMessage(websocket.TextMessage, m)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"err\", err)\n\t\t}\n\t\ttime.Sleep(30 * time.Millisecond)\n\t}\n}\n\nfunc msg(r *rand.Rand, room string) []byte {\n\ttyped := Typed{}\n\tvar e Event\n\tswitch r.Intn(8) {\n\tcase 0:\n\t\ttyped.Type = \"clientanswer\"\n\t\te = &ClientAnswer{SID: xid.New(), Value: nil}\n\tcase 1:\n\t\ttyped.Type = \"clientice\"\n\t\te = &ClientICE{SID: xid.New(), Value: nil}\n\tcase 2:\n\t\ttyped.Type = \"hostice\"\n\t\te = &HostICE{SID: xid.New(), Value: nil}\n\tcase 3:\n\t\ttyped.Type = \"hostoffer\"\n\t\te = &HostOffer{SID: xid.New(), Value: nil}\n\tcase 4:\n\t\ttyped.Type = \"name\"\n\t\te = &Name{UserName: \"a\"}\n\tcase 5:\n\t\ttyped.Type = \"share\"\n\t\te = &StartShare{}\n\tcase 6:\n\t\ttyped.Type = \"stopshare\"\n\t\te = &StopShare{}\n\tcase 7:\n\t\ttyped.Type = \"create\"\n\t\te = &Create{ID: room, CloseOnOwnerLeave: r.Intn(2) == 0, JoinIfExist: r.Intn(2) == 0, Mode: ConnectionSTUN, UserName: \"hello\"}\n\t}\n\n\tb, err := json.Marshal(e)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttyped.Payload = json.RawMessage(b)\n\n\tb, err = json.Marshal(typed)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn b\n}\n"
  }
]