cuju-render 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cuju/render/__init__.py +759 -0
- cuju/render/__main__.py +1065 -0
- cuju/render/_export/__init__.py +3 -0
- cuju/render/_export/feed.py +542 -0
- cuju/render/_export/sizes.py +157 -0
- cuju/render/_export/video.py +1618 -0
- cuju/render/_export/video_jobs.py +408 -0
- cuju/render/_format/__init__.py +3 -0
- cuju/render/_format/annotations.py +235 -0
- cuju/render/_format/codec.py +307 -0
- cuju/render/_format/keep.py +121 -0
- cuju/render/_format/recording.py +860 -0
- cuju/render/_format/writer.py +54 -0
- cuju/render/_guide/__init__.py +3 -0
- cuju/render/_guide/doctor.py +523 -0
- cuju/render/_guide/help.py +62 -0
- cuju/render/_guide/tutorial.py +254 -0
- cuju/render/_http/__init__.py +3 -0
- cuju/render/_http/commands.py +57 -0
- cuju/render/_http/headers.py +103 -0
- cuju/render/_http/launch.py +500 -0
- cuju/render/_http/launchers.py +408 -0
- cuju/render/_http/pwa.py +128 -0
- cuju/render/_http/server.py +2105 -0
- cuju/render/_http/window.py +360 -0
- cuju/render/_moments/__init__.py +3 -0
- cuju/render/_moments/captions.py +284 -0
- cuju/render/_moments/events.py +1123 -0
- cuju/render/_moments/search.py +694 -0
- cuju/render/_packages/__init__.py +3 -0
- cuju/render/_packages/glsl.py +746 -0
- cuju/render/_packages/loudness.py +334 -0
- cuju/render/_packages/pack.py +1959 -0
- cuju/render/_packages/presentation.py +1376 -0
- cuju/render/_packages/vocabulary.py +609 -0
- cuju/render/_playing/__init__.py +3 -0
- cuju/render/_playing/achievements.py +463 -0
- cuju/render/_playing/bench.py +609 -0
- cuju/render/_playing/challenges.py +1813 -0
- cuju/render/_playing/demo.py +323 -0
- cuju/render/_playing/draw.py +211 -0
- cuju/render/_playing/errors.py +20 -0
- cuju/render/_playing/game.py +645 -0
- cuju/render/_playing/limits.py +339 -0
- cuju/render/_playing/play.py +926 -0
- cuju/render/_playing/policy_worker.py +250 -0
- cuju/render/_playing/strict.py +810 -0
- cuju/render/_registry/__init__.py +3 -0
- cuju/render/_registry/clips.py +394 -0
- cuju/render/_registry/joints.py +108 -0
- cuju/render/_registry/teams.py +2058 -0
- cuju/render/_store/__init__.py +3 -0
- cuju/render/_store/home.py +70 -0
- cuju/render/_store/library.py +604 -0
- cuju/render/_store/samples.py +163 -0
- cuju/render/_text/__init__.py +3 -0
- cuju/render/_text/languages.py +637 -0
- cuju/render/_text/messages.py +1396 -0
- cuju/render/_tournaments/__init__.py +3 -0
- cuju/render/_tournaments/results.py +547 -0
- cuju/render/_tournaments/tournament.py +2742 -0
- cuju/render/_tournaments/tournament_cli.py +587 -0
- cuju/render/_tournaments/tournament_runner.py +1975 -0
- cuju/render/_version.py +6 -0
- cuju/render/_watch/__init__.py +3 -0
- cuju/render/_watch/grid.py +265 -0
- cuju/render/_watch/live.py +664 -0
- cuju/render/_watch/notebook.py +79 -0
- cuju/render/_watch/show.py +171 -0
- cuju/render/samples/sample-11v11.cjr +0 -0
- cuju/render/samples/sample-5v5.cjr +0 -0
- cuju/render/samples/teams/starter/main.py +33 -0
- cuju/render/scenarios/benchmark_full_game_11_vs_11_easy.py +46 -0
- cuju/render/scenarios/benchmark_full_game_11_vs_11_hard.py +46 -0
- cuju/render/scenarios/benchmark_full_game_11_vs_11_medium.py +46 -0
- cuju/render/scenarios/benchmark_full_game_5_vs_5_easy.py +34 -0
- cuju/render/scenarios/benchmark_full_game_5_vs_5_hard.py +34 -0
- cuju/render/scenarios/benchmark_full_game_5_vs_5_medium.py +34 -0
- cuju/render/web/assets/adboard_polygon.webp +0 -0
- cuju/render/web/assets/adboard_your_ad_here.webp +0 -0
- cuju/render/web/assets/animations/kaykit-rig-medium-combatmelee.glb +0 -0
- cuju/render/web/assets/animations/kaykit-rig-medium-general.glb +0 -0
- cuju/render/web/assets/animations/kaykit-rig-medium-movementadvanced.glb +0 -0
- cuju/render/web/assets/animations/kaykit-rig-medium-movementbasic.glb +0 -0
- cuju/render/web/assets/animations/kaykit-rig-medium-simulation.glb +0 -0
- cuju/render/web/assets/animations/kaykit-rig-medium-special.glb +0 -0
- cuju/render/web/assets/ball.glb +0 -0
- cuju/render/web/assets/challenges/3_vs_1_with_keeper.mp4 +0 -0
- cuju/render/web/assets/challenges/3_vs_1_with_keeper.webp +0 -0
- cuju/render/web/assets/challenges/corner.mp4 +0 -0
- cuju/render/web/assets/challenges/corner.webp +0 -0
- cuju/render/web/assets/challenges/counterattack_easy.mp4 +0 -0
- cuju/render/web/assets/challenges/counterattack_easy.webp +0 -0
- cuju/render/web/assets/challenges/counterattack_hard.mp4 +0 -0
- cuju/render/web/assets/challenges/counterattack_hard.webp +0 -0
- cuju/render/web/assets/challenges/empty_goal.mp4 +0 -0
- cuju/render/web/assets/challenges/empty_goal.webp +0 -0
- cuju/render/web/assets/challenges/empty_goal_close.mp4 +0 -0
- cuju/render/web/assets/challenges/empty_goal_close.webp +0 -0
- cuju/render/web/assets/challenges/manifest.json +375 -0
- cuju/render/web/assets/challenges/one_on_one.mp4 +0 -0
- cuju/render/web/assets/challenges/one_on_one.webp +0 -0
- cuju/render/web/assets/challenges/one_on_one_hard.mp4 +0 -0
- cuju/render/web/assets/challenges/one_on_one_hard.webp +0 -0
- cuju/render/web/assets/challenges/pass_and_shoot_with_keeper.mp4 +0 -0
- cuju/render/web/assets/challenges/pass_and_shoot_with_keeper.webp +0 -0
- cuju/render/web/assets/challenges/run_pass_and_shoot_with_keeper.mp4 +0 -0
- cuju/render/web/assets/challenges/run_pass_and_shoot_with_keeper.webp +0 -0
- cuju/render/web/assets/challenges/run_to_score.mp4 +0 -0
- cuju/render/web/assets/challenges/run_to_score.webp +0 -0
- cuju/render/web/assets/challenges/run_to_score_with_keeper.mp4 +0 -0
- cuju/render/web/assets/challenges/run_to_score_with_keeper.webp +0 -0
- cuju/render/web/assets/challenges/single_goal_versus_lazy.mp4 +0 -0
- cuju/render/web/assets/challenges/single_goal_versus_lazy.webp +0 -0
- cuju/render/web/assets/crowd.webp +0 -0
- cuju/render/web/assets/crowd_normal.webp +0 -0
- cuju/render/web/assets/cuju-logo-384.png +0 -0
- cuju/render/web/assets/cuju-logo.png +0 -0
- cuju/render/web/assets/cuju-logo.svg +46 -0
- cuju/render/web/assets/cuju-mark-light.svg +33 -0
- cuju/render/web/assets/cuju-mark.svg +33 -0
- cuju/render/web/assets/goal.glb +0 -0
- cuju/render/web/assets/grass.webp +0 -0
- cuju/render/web/assets/hair_black.png +0 -0
- cuju/render/web/assets/hair_blonde.png +0 -0
- cuju/render/web/assets/hair_brown.png +0 -0
- cuju/render/web/assets/hair_darkblonde.png +0 -0
- cuju/render/web/assets/hair_long01.glb +0 -0
- cuju/render/web/assets/hair_long02.glb +0 -0
- cuju/render/web/assets/hair_medium01.glb +0 -0
- cuju/render/web/assets/hair_red.png +0 -0
- cuju/render/web/assets/hair_short01.glb +0 -0
- cuju/render/web/assets/hair_short02.glb +0 -0
- cuju/render/web/assets/icons/cuju-192.png +0 -0
- cuju/render/web/assets/icons/cuju-512.png +0 -0
- cuju/render/web/assets/icons/cuju-maskable-512.png +0 -0
- cuju/render/web/assets/kit_goalkeeper.webp +0 -0
- cuju/render/web/assets/kit_mask.png +0 -0
- cuju/render/web/assets/kit_normal.webp +0 -0
- cuju/render/web/assets/manifest.json +601 -0
- cuju/render/web/assets/models/kaykit-barbarian.glb +0 -0
- cuju/render/web/assets/models/kaykit-barbarian.json +23 -0
- cuju/render/web/assets/models/kaykit-knight.glb +0 -0
- cuju/render/web/assets/models/kaykit-knight.json +23 -0
- cuju/render/web/assets/models/kaykit-mage.glb +0 -0
- cuju/render/web/assets/models/kaykit-mage.json +23 -0
- cuju/render/web/assets/models/kaykit-mannequin-medium.glb +0 -0
- cuju/render/web/assets/models/kaykit-mannequin-medium.json +23 -0
- cuju/render/web/assets/models/kaykit-ranger.glb +0 -0
- cuju/render/web/assets/models/kaykit-ranger.json +23 -0
- cuju/render/web/assets/models/kaykit-rogue-hooded.glb +0 -0
- cuju/render/web/assets/models/kaykit-rogue-hooded.json +23 -0
- cuju/render/web/assets/models/kaykit-rogue.glb +0 -0
- cuju/render/web/assets/models/kaykit-rogue.json +23 -0
- cuju/render/web/assets/models/kaykit-skeleton-mage.glb +0 -0
- cuju/render/web/assets/models/kaykit-skeleton-mage.json +23 -0
- cuju/render/web/assets/models/kaykit-skeleton-minion.glb +0 -0
- cuju/render/web/assets/models/kaykit-skeleton-minion.json +23 -0
- cuju/render/web/assets/models/kaykit-skeleton-rogue.glb +0 -0
- cuju/render/web/assets/models/kaykit-skeleton-rogue.json +23 -0
- cuju/render/web/assets/models/kaykit-skeleton-warrior.glb +0 -0
- cuju/render/web/assets/models/kaykit-skeleton-warrior.json +23 -0
- cuju/render/web/assets/pitch.webp +0 -0
- cuju/render/web/assets/pitch_normal.webp +0 -0
- cuju/render/web/assets/player.glb +0 -0
- cuju/render/web/assets/shoe.webp +0 -0
- cuju/render/web/assets/shoe_sole.png +0 -0
- cuju/render/web/assets/skin_01.png +0 -0
- cuju/render/web/assets/skin_02.png +0 -0
- cuju/render/web/assets/skin_03.png +0 -0
- cuju/render/web/assets/skin_04.png +0 -0
- cuju/render/web/assets/sounds/applause.ogg +0 -0
- cuju/render/web/assets/sounds/beach-wave-1.ogg +0 -0
- cuju/render/web/assets/sounds/beach-wave-2.ogg +0 -0
- cuju/render/web/assets/sounds/beach-wave-3.ogg +0 -0
- cuju/render/web/assets/sounds/beach-wave-4.ogg +0 -0
- cuju/render/web/assets/sounds/city-horn.ogg +0 -0
- cuju/render/web/assets/sounds/city-loop.ogg +0 -0
- cuju/render/web/assets/sounds/city-siren.ogg +0 -0
- cuju/render/web/assets/sounds/crowd-cheer.ogg +0 -0
- cuju/render/web/assets/sounds/crowd-loop.ogg +0 -0
- cuju/render/web/assets/sounds/crowd-ooh.ogg +0 -0
- cuju/render/web/assets/sounds/gulls.ogg +0 -0
- cuju/render/web/assets/sounds/neon-sting.ogg +0 -0
- cuju/render/web/assets/sounds/rain-loop.ogg +0 -0
- cuju/render/web/assets/sounds/sounds.json +46 -0
- cuju/render/web/assets/sounds/space-beep.ogg +0 -0
- cuju/render/web/assets/sounds/space-hum.ogg +0 -0
- cuju/render/web/assets/sounds/space-radio.ogg +0 -0
- cuju/render/web/assets/sounds/whistle-long.ogg +0 -0
- cuju/render/web/assets/sounds/whistle-short.ogg +0 -0
- cuju/render/web/assets/sounds/wind-loop.ogg +0 -0
- cuju/render/web/easy.css +357 -0
- cuju/render/web/export.html +23 -0
- cuju/render/web/feed.css +262 -0
- cuju/render/web/feed.html +28 -0
- cuju/render/web/flat.css +120 -0
- cuju/render/web/home.css +837 -0
- cuju/render/web/index.html +373 -0
- cuju/render/web/js/boot.js +50 -0
- cuju/render/web/js/broadcast/audio.js +2141 -0
- cuju/render/web/js/broadcast/celebrate.js +1238 -0
- cuju/render/web/js/broadcast/decisions.js +609 -0
- cuju/render/web/js/broadcast/hud.js +352 -0
- cuju/render/web/js/broadcast/show.js +3614 -0
- cuju/render/web/js/broadcast/transition.js +2231 -0
- cuju/render/web/js/broadcast/voices.js +153 -0
- cuju/render/web/js/capture.js +101 -0
- cuju/render/web/js/core/accessibility.js +90 -0
- cuju/render/web/js/core/api.js +429 -0
- cuju/render/web/js/core/comfort.js +135 -0
- cuju/render/web/js/core/i18n.js +705 -0
- cuju/render/web/js/core/icons.js +167 -0
- cuju/render/web/js/core/input-settings.js +156 -0
- cuju/render/web/js/core/keys.js +277 -0
- cuju/render/web/js/core/language-ui.js +125 -0
- cuju/render/web/js/core/menu.js +853 -0
- cuju/render/web/js/core/names.js +113 -0
- cuju/render/web/js/core/page-structure.js +110 -0
- cuju/render/web/js/core/scenarios.js +109 -0
- cuju/render/web/js/core/spoilers.js +236 -0
- cuju/render/web/js/core/typeahead.js +38 -0
- cuju/render/web/js/export/dom-picture.js +330 -0
- cuju/render/web/js/export/export-host.js +97 -0
- cuju/render/web/js/export/feed-dialog.js +191 -0
- cuju/render/web/js/export/feed-params.js +266 -0
- cuju/render/web/js/export/feed.js +363 -0
- cuju/render/web/js/export/mp4-mux.js +295 -0
- cuju/render/web/js/export/photo-core.js +313 -0
- cuju/render/web/js/export/photo.js +1314 -0
- cuju/render/web/js/export/safe-frame.js +59 -0
- cuju/render/web/js/export/size-fields.js +103 -0
- cuju/render/web/js/export/sizes.js +178 -0
- cuju/render/web/js/export/video-boot.js +55 -0
- cuju/render/web/js/export/video-browser.js +325 -0
- cuju/render/web/js/export/video-export.js +417 -0
- cuju/render/web/js/export/video-plan.js +207 -0
- cuju/render/web/js/export/video-range.js +185 -0
- cuju/render/web/js/export/webm-mux.js +198 -0
- cuju/render/web/js/feed-boot.js +151 -0
- cuju/render/web/js/feed-frame.js +101 -0
- cuju/render/web/js/help/doctor.js +488 -0
- cuju/render/web/js/help/firstrun.js +379 -0
- cuju/render/web/js/help/help-center.js +438 -0
- cuju/render/web/js/help/install-offer.js +164 -0
- cuju/render/web/js/help/install-state.js +104 -0
- cuju/render/web/js/help/lessons-core.js +207 -0
- cuju/render/web/js/help/lessons.js +463 -0
- cuju/render/web/js/help/palette.js +584 -0
- cuju/render/web/js/help/pwa.js +257 -0
- cuju/render/web/js/help/tour-core.js +241 -0
- cuju/render/web/js/help/tour.js +461 -0
- cuju/render/web/js/main.js +2513 -0
- cuju/render/web/js/pages/draw.js +188 -0
- cuju/render/web/js/pages/fieldpage.js +530 -0
- cuju/render/web/js/pages/home.js +521 -0
- cuju/render/web/js/pages/matches.js +779 -0
- cuju/render/web/js/pages/moments-ui.js +359 -0
- cuju/render/web/js/pages/queue-filters.js +63 -0
- cuju/render/web/js/pages/recording-groups.js +80 -0
- cuju/render/web/js/pages/recordings.js +1069 -0
- cuju/render/web/js/play/bench.js +347 -0
- cuju/render/web/js/play/challenges.js +1302 -0
- cuju/render/web/js/play/medals.js +127 -0
- cuju/render/web/js/play/play.js +1953 -0
- cuju/render/web/js/play/teasers.js +196 -0
- cuju/render/web/js/play/touch.js +350 -0
- cuju/render/web/js/play/tournament-layout.js +487 -0
- cuju/render/web/js/play/tournament-results.js +441 -0
- cuju/render/web/js/play/tournament-strict.js +560 -0
- cuju/render/web/js/play/tournament.js +2585 -0
- cuju/render/web/js/players/animate.js +972 -0
- cuju/render/web/js/players/clips.js +224 -0
- cuju/render/web/js/players/kaykit.js +162 -0
- cuju/render/web/js/players/kits.js +676 -0
- cuju/render/web/js/players/number-patch.js +82 -0
- cuju/render/web/js/players/players.js +2694 -0
- cuju/render/web/js/players/recolor.js +893 -0
- cuju/render/web/js/players/retarget.js +325 -0
- cuju/render/web/js/players/rig-numbers.js +174 -0
- cuju/render/web/js/presentation/animator.js +231 -0
- cuju/render/web/js/presentation/assign.js +85 -0
- cuju/render/web/js/presentation/behaviors.js +440 -0
- cuju/render/web/js/presentation/budget.js +209 -0
- cuju/render/web/js/presentation/catalog.js +1674 -0
- cuju/render/web/js/presentation/clocks.js +72 -0
- cuju/render/web/js/presentation/commands.js +301 -0
- cuju/render/web/js/presentation/contract.js +240 -0
- cuju/render/web/js/presentation/effects.js +904 -0
- cuju/render/web/js/presentation/flash.js +605 -0
- cuju/render/web/js/presentation/freeze-worklet.js +22 -0
- cuju/render/web/js/presentation/glsl.js +464 -0
- cuju/render/web/js/presentation/host.js +323 -0
- cuju/render/web/js/presentation/index.js +2066 -0
- cuju/render/web/js/presentation/loudness-worklet.js +235 -0
- cuju/render/web/js/presentation/loudness.js +740 -0
- cuju/render/web/js/presentation/moments.js +536 -0
- cuju/render/web/js/presentation/post.js +327 -0
- cuju/render/web/js/presentation/preview.js +180 -0
- cuju/render/web/js/presentation/protocol.js +174 -0
- cuju/render/web/js/presentation/reach.js +158 -0
- cuju/render/web/js/presentation/rigging.js +130 -0
- cuju/render/web/js/presentation/sandbox.js +157 -0
- cuju/render/web/js/presentation/shaders.js +235 -0
- cuju/render/web/js/presentation/stage.js +402 -0
- cuju/render/web/js/presentation/teamaudio.js +722 -0
- cuju/render/web/js/presentation/tracks.js +197 -0
- cuju/render/web/js/presentation/values.js +81 -0
- cuju/render/web/js/recording/annotation-data.js +203 -0
- cuju/render/web/js/recording/captions.js +491 -0
- cuju/render/web/js/recording/codec.js +185 -0
- cuju/render/web/js/recording/decode-worker.js +70 -0
- cuju/render/web/js/recording/decode.js +94 -0
- cuju/render/web/js/recording/episodes.js +46 -0
- cuju/render/web/js/recording/format.js +461 -0
- cuju/render/web/js/recording/live.js +348 -0
- cuju/render/web/js/recording/moments-query.js +59 -0
- cuju/render/web/js/recording/moments.js +149 -0
- cuju/render/web/js/recording/pose.js +86 -0
- cuju/render/web/js/recording/timeline.js +275 -0
- cuju/render/web/js/teams/art.js +50 -0
- cuju/render/web/js/teams/clip-editor.js +293 -0
- cuju/render/web/js/teams/editor.js +1979 -0
- cuju/render/web/js/teams/library.js +344 -0
- cuju/render/web/js/teams/painter.js +633 -0
- cuju/render/web/js/teams/surprise-ui.js +195 -0
- cuju/render/web/js/teams/surprise.js +497 -0
- cuju/render/web/js/teams/team-check.js +127 -0
- cuju/render/web/js/watch/annotations.js +270 -0
- cuju/render/web/js/watch/flat.js +366 -0
- cuju/render/web/js/watch/grid.js +436 -0
- cuju/render/web/js/watch/pitch2d.js +289 -0
- cuju/render/web/js/watch/player-tools.js +192 -0
- cuju/render/web/js/watch/presets.js +201 -0
- cuju/render/web/js/world/arenas.js +997 -0
- cuju/render/web/js/world/ball.js +204 -0
- cuju/render/web/js/world/cameras.js +982 -0
- cuju/render/web/js/world/crowd.js +376 -0
- cuju/render/web/js/world/field.js +227 -0
- cuju/render/web/js/world/framing.js +145 -0
- cuju/render/web/js/world/occlusion.js +48 -0
- cuju/render/web/js/world/pitch.js +703 -0
- cuju/render/web/js/world/scene.js +395 -0
- cuju/render/web/js/world/sky.js +325 -0
- cuju/render/web/js/world/stadium.js +1262 -0
- cuju/render/web/js/world/vendor-sky.js +367 -0
- cuju/render/web/js/world/weather.js +264 -0
- cuju/render/web/languages/en.json +4750 -0
- cuju/render/web/lessons.json +137 -0
- cuju/render/web/manifest.webmanifest +23 -0
- cuju/render/web/style.css +8399 -0
- cuju/render/web/sw.js +235 -0
- cuju/render/web/vendor/fabric/LICENSE +16 -0
- cuju/render/web/vendor/fabric/fabric.min.mjs +1 -0
- cuju/render/web/vendor/lucide/LICENSE +43 -0
- cuju/render/web/vendor/lucide/icons.js +141 -0
- cuju/render/web/vendor/three/LICENSE +21 -0
- cuju/render/web/vendor/three/build/three.core.js +60586 -0
- cuju/render/web/vendor/three/build/three.module.js +19719 -0
- cuju/render/web/vendor/three/examples/jsm/loaders/GLTFLoader.js +4925 -0
- cuju/render/web/vendor/three/examples/jsm/postprocessing/EffectComposer.js +365 -0
- cuju/render/web/vendor/three/examples/jsm/postprocessing/MaskPass.js +195 -0
- cuju/render/web/vendor/three/examples/jsm/postprocessing/OutputPass.js +148 -0
- cuju/render/web/vendor/three/examples/jsm/postprocessing/Pass.js +191 -0
- cuju/render/web/vendor/three/examples/jsm/postprocessing/RenderPass.js +193 -0
- cuju/render/web/vendor/three/examples/jsm/postprocessing/ShaderPass.js +135 -0
- cuju/render/web/vendor/three/examples/jsm/postprocessing/UnrealBloomPass.js +541 -0
- cuju/render/web/vendor/three/examples/jsm/shaders/CopyShader.js +52 -0
- cuju/render/web/vendor/three/examples/jsm/shaders/LuminosityHighPassShader.js +68 -0
- cuju/render/web/vendor/three/examples/jsm/shaders/OutputShader.js +103 -0
- cuju/render/web/vendor/three/examples/jsm/utils/BufferGeometryUtils.js +1501 -0
- cuju/render/web/vendor/three/examples/jsm/utils/SkeletonUtils.js +496 -0
- cuju_render-0.1.0.dist-info/METADATA +116 -0
- cuju_render-0.1.0.dist-info/RECORD +382 -0
- cuju_render-0.1.0.dist-info/WHEEL +4 -0
- cuju_render-0.1.0.dist-info/licenses/LICENSE +202 -0
- cuju_render-0.1.0.dist-info/licenses/LICENSES/CC-BY-4.0.txt +396 -0
- cuju_render-0.1.0.dist-info/licenses/LICENSES/CC0-1.0.txt +127 -0
- cuju_render-0.1.0.dist-info/licenses/LICENSES/ISC.txt +16 -0
- cuju_render-0.1.0.dist-info/licenses/LICENSES/MIT.txt +24 -0
- cuju_render-0.1.0.dist-info/licenses/LICENSES/Unlicense.txt +13 -0
- cuju_render-0.1.0.dist-info/licenses/NOTICE +35 -0
|
@@ -0,0 +1,2105 @@
|
|
|
1
|
+
# Copyright 2026 The cuju Authors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""The local server of the renderer, which serves the page and its API on the loopback interface.
|
|
5
|
+
|
|
6
|
+
It lists, sends and annotates recordings, moves them to the Trash and back and deletes them from
|
|
7
|
+
there, lists and relays live sources, keeps the team registry and plays requested matches, each in
|
|
8
|
+
a process of its own. It uses only Python's standard library.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import collections
|
|
14
|
+
import contextlib
|
|
15
|
+
import http.client
|
|
16
|
+
import http.server
|
|
17
|
+
import json
|
|
18
|
+
import logging
|
|
19
|
+
import mimetypes
|
|
20
|
+
import os
|
|
21
|
+
import secrets
|
|
22
|
+
import signal
|
|
23
|
+
import subprocess
|
|
24
|
+
import sys
|
|
25
|
+
import threading
|
|
26
|
+
import time
|
|
27
|
+
import urllib.parse
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
from cuju import __version__, bundled_scenarios
|
|
32
|
+
from cuju.errors import ArgumentError, Error
|
|
33
|
+
|
|
34
|
+
from .. import _version
|
|
35
|
+
from .._export import feed as _feed
|
|
36
|
+
from .._export import video_jobs as _video_jobs
|
|
37
|
+
from .._format import recording as _recording
|
|
38
|
+
from .._guide import doctor as _doctor
|
|
39
|
+
from .._guide import help as _help
|
|
40
|
+
from .._moments import search as _search
|
|
41
|
+
from .._packages import presentation as _presentation
|
|
42
|
+
from .._playing import achievements as _achievements
|
|
43
|
+
from .._playing import challenges as _challenges
|
|
44
|
+
from .._playing import draw as _draw
|
|
45
|
+
from .._registry import clips as _clips
|
|
46
|
+
from .._registry import teams as _teams
|
|
47
|
+
from .._store import home as _home
|
|
48
|
+
from .._store import library as _library
|
|
49
|
+
from .._text import languages as _languages
|
|
50
|
+
from .._text import messages as _messages
|
|
51
|
+
from .._text.messages import MessageError
|
|
52
|
+
from .._tournaments import tournament_runner as _tournament_runner
|
|
53
|
+
from .._watch import grid as _grid
|
|
54
|
+
from . import headers as _headers
|
|
55
|
+
from . import launch as _launch
|
|
56
|
+
from . import pwa as _pwa
|
|
57
|
+
|
|
58
|
+
_WEB = Path(__file__).parents[1] / 'web'
|
|
59
|
+
_LOGGER = logging.getLogger('cuju')
|
|
60
|
+
# A requested match ends after this many seconds, a full match plays in a few minutes.
|
|
61
|
+
_MATCH_SECONDS = 30 * 60
|
|
62
|
+
_TYPES = {
|
|
63
|
+
'.js': 'text/javascript',
|
|
64
|
+
'.mjs': 'text/javascript',
|
|
65
|
+
'.css': 'text/css',
|
|
66
|
+
'.html': 'text/html',
|
|
67
|
+
'.json': 'application/json',
|
|
68
|
+
'.glb': 'model/gltf-binary',
|
|
69
|
+
'.webp': 'image/webp',
|
|
70
|
+
'.png': 'image/png',
|
|
71
|
+
'.svg': 'image/svg+xml',
|
|
72
|
+
'.webmanifest': 'application/manifest+json',
|
|
73
|
+
'.mp4': 'video/mp4',
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# The states of a request, and the error of one that a restart of the server interrupted, by
|
|
78
|
+
# the id of its message and its English text.
|
|
79
|
+
_STATES = ('queued', 'running', 'done', 'failed')
|
|
80
|
+
_INTERRUPTED_ID = 'server.requests.interrupted'
|
|
81
|
+
_INTERRUPTED_PLAYING_ID = 'server.requests.interrupted_playing'
|
|
82
|
+
_INTERRUPTED = _messages.text(_INTERRUPTED_ID)
|
|
83
|
+
_INTERRUPTED_PLAYING = _messages.text(_INTERRUPTED_PLAYING_ID)
|
|
84
|
+
# The history keeps this many finished requests, the newest, with every waiting or playing one.
|
|
85
|
+
_KEPT_REQUESTS = 200
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _number(value: Any) -> bool:
|
|
89
|
+
"""Returns whether `value` is a JSON number, which excludes true and false."""
|
|
90
|
+
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# Every field of a stored request with its check, so that a file edited by hand or written by
|
|
94
|
+
# a later version is skipped with a warning and the server starts all the same.
|
|
95
|
+
_REQUEST_FIELDS: dict[str, Any] = {
|
|
96
|
+
'id': lambda value: isinstance(value, str) and _home.valid_identifier(value),
|
|
97
|
+
'left': lambda value: isinstance(value, str),
|
|
98
|
+
'right': lambda value: isinstance(value, str),
|
|
99
|
+
'scenario': lambda value: isinstance(value, str),
|
|
100
|
+
'seed': lambda value: (
|
|
101
|
+
isinstance(value, int) and not isinstance(value, bool) and 0 <= value < 2**64
|
|
102
|
+
),
|
|
103
|
+
'ability': lambda value: (
|
|
104
|
+
isinstance(value, list)
|
|
105
|
+
and len(value) == 2
|
|
106
|
+
and all(item is None or (_number(item) and 0 <= item <= 1) for item in value)
|
|
107
|
+
),
|
|
108
|
+
'state': lambda value: value in _STATES,
|
|
109
|
+
'progress': _number,
|
|
110
|
+
'match': lambda value: value is None or isinstance(value, str),
|
|
111
|
+
'error': lambda value: value is None or isinstance(value, str),
|
|
112
|
+
'created': _number,
|
|
113
|
+
'started': lambda value: value is None or _number(value),
|
|
114
|
+
'finished': lambda value: value is None or _number(value),
|
|
115
|
+
}
|
|
116
|
+
# The fields that a request of an earlier version lacks, the id and values of the message of its
|
|
117
|
+
# error, which the page shows in its own language, `None` for an error without an id, the draw
|
|
118
|
+
# of a request with a side or a scenario drawn at random, `None` for one without, and the names of
|
|
119
|
+
# its two teams when it was made, each a label for a name that cuju made or a text, which the page
|
|
120
|
+
# shows for a team removed since, `None` for a request of before.
|
|
121
|
+
_OPTIONAL_REQUEST_FIELDS: dict[str, Any] = {
|
|
122
|
+
'draw': _draw.valid,
|
|
123
|
+
'team_names': lambda value: (
|
|
124
|
+
value is None
|
|
125
|
+
or (
|
|
126
|
+
isinstance(value, list)
|
|
127
|
+
and len(value) == 2
|
|
128
|
+
and all(isinstance(item, str) or _messages.valid_label(item) for item in value)
|
|
129
|
+
)
|
|
130
|
+
),
|
|
131
|
+
'error_id': lambda value: value is None or value in _messages.MESSAGES,
|
|
132
|
+
'error_values': lambda value: (
|
|
133
|
+
value is None
|
|
134
|
+
or (isinstance(value, dict) and all(isinstance(item, str) for item in value.values()))
|
|
135
|
+
),
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _stored_request(path: Path) -> dict[str, Any] | None:
|
|
140
|
+
"""Returns the request that a file of the history holds, or `None` with a warning."""
|
|
141
|
+
try:
|
|
142
|
+
entry = json.loads(path.read_text(encoding='utf-8'))
|
|
143
|
+
except (OSError, ValueError) as error:
|
|
144
|
+
_LOGGER.warning('cuju render skips the request file %s, %s', path.name, error)
|
|
145
|
+
return None
|
|
146
|
+
if not isinstance(entry, dict):
|
|
147
|
+
_LOGGER.warning('cuju render skips the request file %s, which holds no object', path.name)
|
|
148
|
+
return None
|
|
149
|
+
wrong = [
|
|
150
|
+
key for key, check in _REQUEST_FIELDS.items() if key not in entry or not check(entry[key])
|
|
151
|
+
]
|
|
152
|
+
wrong += [
|
|
153
|
+
key
|
|
154
|
+
for key, check in _OPTIONAL_REQUEST_FIELDS.items()
|
|
155
|
+
if key in entry and not check(entry[key])
|
|
156
|
+
]
|
|
157
|
+
if wrong or entry['id'] != path.stem:
|
|
158
|
+
_LOGGER.warning(
|
|
159
|
+
'cuju render skips the request file %s, whose fields %s are missing or invalid',
|
|
160
|
+
path.name,
|
|
161
|
+
', '.join(wrong or ['id']),
|
|
162
|
+
)
|
|
163
|
+
return None
|
|
164
|
+
stored = {key: entry[key] for key in _REQUEST_FIELDS}
|
|
165
|
+
stored.update({key: entry.get(key) for key in _OPTIONAL_REQUEST_FIELDS})
|
|
166
|
+
if stored['error_id'] is None or stored['error_values'] is None:
|
|
167
|
+
stored['error_id'] = stored['error_values'] = None
|
|
168
|
+
return stored
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class _Requests:
|
|
172
|
+
"""The queue of requested matches, played one at a time in child processes.
|
|
173
|
+
|
|
174
|
+
Each request lives in a JSON file of the folder `requests`, so the history outlasts the server.
|
|
175
|
+
A request that waited or played when the server stopped is marked as interrupted on the next
|
|
176
|
+
start. A match that was playing then may still finish in its own process and save its
|
|
177
|
+
recording, which then appears in the library while its request stays interrupted.
|
|
178
|
+
"""
|
|
179
|
+
|
|
180
|
+
def __init__(self) -> None:
|
|
181
|
+
self._lock = threading.Lock()
|
|
182
|
+
self._entries: list[dict[str, Any]] = []
|
|
183
|
+
self._processes: dict[str, subprocess.Popen] = {}
|
|
184
|
+
self._wake = threading.Event()
|
|
185
|
+
self._folder = _home.folder('requests')
|
|
186
|
+
# A write that stopped halfway leaves a temporary file, which holds nothing to keep.
|
|
187
|
+
for path in self._folder.glob('*.part'):
|
|
188
|
+
with contextlib.suppress(OSError):
|
|
189
|
+
path.unlink()
|
|
190
|
+
for path in sorted(self._folder.glob('*.json')):
|
|
191
|
+
entry = _stored_request(path)
|
|
192
|
+
if entry is None:
|
|
193
|
+
continue
|
|
194
|
+
if entry['state'] in ('queued', 'running'):
|
|
195
|
+
error = _INTERRUPTED_PLAYING_ID if entry['state'] == 'running' else _INTERRUPTED_ID
|
|
196
|
+
entry.update(state='failed', finished=time.time(), **_messages.fields(error))
|
|
197
|
+
self._checkpoint(entry)
|
|
198
|
+
self._entries.append(entry)
|
|
199
|
+
self._entries.sort(key=lambda entry: entry['created'])
|
|
200
|
+
self._trim()
|
|
201
|
+
threading.Thread(target=self._run, daemon=True).start()
|
|
202
|
+
|
|
203
|
+
def _trim(self) -> None:
|
|
204
|
+
"""Forgets the oldest finished requests beyond the newest 200, with the lock held.
|
|
205
|
+
|
|
206
|
+
A request that waits or plays always stays, and the file of a forgotten request is deleted,
|
|
207
|
+
so the history and the list of the page stay small however many matches were requested.
|
|
208
|
+
"""
|
|
209
|
+
finished = [entry for entry in self._entries if entry['state'] not in ('queued', 'running')]
|
|
210
|
+
for entry in finished[: max(0, len(finished) - _KEPT_REQUESTS)]:
|
|
211
|
+
self._entries.remove(entry)
|
|
212
|
+
with contextlib.suppress(OSError):
|
|
213
|
+
(self._folder / f'{entry["id"]}.json').unlink()
|
|
214
|
+
|
|
215
|
+
def _persist(self, entry: dict[str, Any]) -> None:
|
|
216
|
+
"""Writes a request to its file through a temporary file, with the lock held."""
|
|
217
|
+
path = self._folder / f'{entry["id"]}.json'
|
|
218
|
+
temporary = path.with_name(path.name + '.part')
|
|
219
|
+
stored = {key: entry[key] for key in _REQUEST_FIELDS}
|
|
220
|
+
stored.update({key: entry.get(key) for key in _OPTIONAL_REQUEST_FIELDS})
|
|
221
|
+
try:
|
|
222
|
+
temporary.write_text(json.dumps(stored), encoding='utf-8')
|
|
223
|
+
os.replace(temporary, path)
|
|
224
|
+
except OSError:
|
|
225
|
+
with contextlib.suppress(OSError):
|
|
226
|
+
temporary.unlink()
|
|
227
|
+
raise
|
|
228
|
+
|
|
229
|
+
def _checkpoint(self, entry: dict[str, Any]) -> None:
|
|
230
|
+
"""Writes a request, and notes a failed write on the entry instead of stopping the queue."""
|
|
231
|
+
for key in ('persistence_error', 'persistence_error_id', 'persistence_error_values'):
|
|
232
|
+
entry.pop(key, None)
|
|
233
|
+
try:
|
|
234
|
+
self._persist(entry)
|
|
235
|
+
except OSError as error:
|
|
236
|
+
found = _messages.fields('server.requests.history', error=error)
|
|
237
|
+
entry.update({f'persistence_{key}': value for key, value in found.items()})
|
|
238
|
+
|
|
239
|
+
def _new_identifier(self) -> str:
|
|
240
|
+
"""Draws an identifier that no request and no file of the history holds, with the lock held.
|
|
241
|
+
|
|
242
|
+
Identifiers sort by the second they are made in, so requests of the same second differ by
|
|
243
|
+
their random end alone, and a draw that is taken is drawn again.
|
|
244
|
+
"""
|
|
245
|
+
taken = {entry['id'] for entry in self._entries}
|
|
246
|
+
while True:
|
|
247
|
+
identifier = _home.new_identifier('r')
|
|
248
|
+
if identifier not in taken and not (self._folder / f'{identifier}.json').exists():
|
|
249
|
+
return identifier
|
|
250
|
+
|
|
251
|
+
def add(
|
|
252
|
+
self,
|
|
253
|
+
left: str,
|
|
254
|
+
right: str,
|
|
255
|
+
scenario: str,
|
|
256
|
+
seed: int | None,
|
|
257
|
+
ability: Any = (None, None),
|
|
258
|
+
pool: Any = None,
|
|
259
|
+
same_team: Any = False,
|
|
260
|
+
) -> dict[str, Any]:
|
|
261
|
+
"""Queues a match and returns its entry, with its seed drawn when none is given.
|
|
262
|
+
|
|
263
|
+
A side or the scenario may be `random`, and the seed then draws it, from the teams of
|
|
264
|
+
`pool` or of the whole registry, as `_draw.resolve` describes. The entry names the teams
|
|
265
|
+
and the scenario drawn, and its `draw` keeps what was random, so a retry draws again.
|
|
266
|
+
|
|
267
|
+
Raises:
|
|
268
|
+
ArgumentError: If the scenario, a team, the seed, an ability or the draw is invalid.
|
|
269
|
+
OSError: If the request cannot be written to the history, and then it is not queued.
|
|
270
|
+
"""
|
|
271
|
+
if scenario not in _scenarios() and scenario != _draw.RANDOM:
|
|
272
|
+
raise MessageError('server.scenario', scenario=repr(scenario))
|
|
273
|
+
ability = list(_teams.check_ability(ability))
|
|
274
|
+
seed = _seed(seed)
|
|
275
|
+
seed = secrets.randbelow(2**31) if seed is None else seed
|
|
276
|
+
drawn = _draw.draw_request(left, right, scenario, seed, pool, same_team)
|
|
277
|
+
if drawn is not None:
|
|
278
|
+
left, right, scenario = drawn['left'], drawn['right'], drawn['scenario']
|
|
279
|
+
sides = [_teams.entry(left), _teams.entry(right)]
|
|
280
|
+
_teams.check_scenario(sides, scenario)
|
|
281
|
+
entry = {
|
|
282
|
+
'id': '',
|
|
283
|
+
'left': left,
|
|
284
|
+
'right': right,
|
|
285
|
+
'scenario': scenario,
|
|
286
|
+
'seed': seed,
|
|
287
|
+
'ability': ability,
|
|
288
|
+
'state': 'queued',
|
|
289
|
+
'progress': 0.0,
|
|
290
|
+
'match': None,
|
|
291
|
+
'error': None,
|
|
292
|
+
'created': 0.0,
|
|
293
|
+
'started': None,
|
|
294
|
+
'finished': None,
|
|
295
|
+
'error_id': None,
|
|
296
|
+
'error_values': None,
|
|
297
|
+
'draw': None if drawn is None else drawn['draw'],
|
|
298
|
+
'team_names': [_teams.shown_name(team) for team in sides],
|
|
299
|
+
}
|
|
300
|
+
with self._lock:
|
|
301
|
+
entry['id'] = self._new_identifier()
|
|
302
|
+
# Each request is later than the one before, so the order of the requests survives a
|
|
303
|
+
# restart even where the clock ticks coarsely or two requests come at once.
|
|
304
|
+
latest = max((other['created'] for other in self._entries), default=0.0)
|
|
305
|
+
entry['created'] = max(time.time(), latest + 1e-6)
|
|
306
|
+
self._persist(entry)
|
|
307
|
+
self._entries.append(entry)
|
|
308
|
+
self._trim()
|
|
309
|
+
self._wake.set()
|
|
310
|
+
return self._public(entry)
|
|
311
|
+
|
|
312
|
+
@staticmethod
|
|
313
|
+
def _public(entry: dict[str, Any]) -> dict[str, Any]:
|
|
314
|
+
"""Returns a copy of a request for the page, with a seed beyond JavaScript's as text."""
|
|
315
|
+
result = dict(entry)
|
|
316
|
+
result['seed'] = _public_seed(result.get('seed'))
|
|
317
|
+
return result
|
|
318
|
+
|
|
319
|
+
def entries(self) -> list[dict[str, Any]]:
|
|
320
|
+
"""Returns a copy of every request, newest first."""
|
|
321
|
+
with self._lock:
|
|
322
|
+
return [self._public(entry) for entry in reversed(self._entries)]
|
|
323
|
+
|
|
324
|
+
def _run(self) -> None:
|
|
325
|
+
while True:
|
|
326
|
+
self._wake.wait()
|
|
327
|
+
self._wake.clear()
|
|
328
|
+
while True:
|
|
329
|
+
with self._lock:
|
|
330
|
+
queued = [entry for entry in self._entries if entry['state'] == 'queued']
|
|
331
|
+
if not queued:
|
|
332
|
+
break
|
|
333
|
+
self._play(queued[0])
|
|
334
|
+
|
|
335
|
+
def cancel(self, identifier: str) -> bool:
|
|
336
|
+
"""Cancels a queued match or ends a running one, and returns whether it existed."""
|
|
337
|
+
with self._lock:
|
|
338
|
+
entry = next((item for item in self._entries if item['id'] == identifier), None)
|
|
339
|
+
if entry is None or entry['state'] not in ('queued', 'running'):
|
|
340
|
+
return False
|
|
341
|
+
process = self._processes.get(identifier)
|
|
342
|
+
entry['state'] = 'failed'
|
|
343
|
+
entry.update(_messages.fields('server.requests.cancelled'))
|
|
344
|
+
entry['finished'] = time.time()
|
|
345
|
+
self._checkpoint(entry)
|
|
346
|
+
if process is not None:
|
|
347
|
+
process.kill()
|
|
348
|
+
return True
|
|
349
|
+
|
|
350
|
+
def _play(self, entry: dict[str, Any]) -> None:
|
|
351
|
+
"""Plays one requested match in a child process, which nothing it does can stop for good."""
|
|
352
|
+
try:
|
|
353
|
+
self._play_child(entry)
|
|
354
|
+
except Exception as error:
|
|
355
|
+
with self._lock:
|
|
356
|
+
entry['state'] = 'failed'
|
|
357
|
+
entry.update(_messages.entry_fields(error, _messages.described(error)))
|
|
358
|
+
entry['finished'] = time.time()
|
|
359
|
+
self._checkpoint(entry)
|
|
360
|
+
|
|
361
|
+
def _play_child(self, entry: dict[str, Any]) -> None:
|
|
362
|
+
command = [
|
|
363
|
+
*_home.python_command(),
|
|
364
|
+
'-m',
|
|
365
|
+
'cuju.render._playing.play',
|
|
366
|
+
'--left',
|
|
367
|
+
entry['left'],
|
|
368
|
+
'--right',
|
|
369
|
+
entry['right'],
|
|
370
|
+
'--scenario',
|
|
371
|
+
entry['scenario'],
|
|
372
|
+
]
|
|
373
|
+
if entry['seed'] is not None:
|
|
374
|
+
command += ['--seed', str(entry['seed'])]
|
|
375
|
+
for side, value in zip(('left', 'right'), entry['ability'], strict=True):
|
|
376
|
+
if value is not None:
|
|
377
|
+
command += [f'--{side}-ability', repr(value)]
|
|
378
|
+
if entry.get('draw') is not None:
|
|
379
|
+
command += ['--draw', json.dumps(entry['draw'])]
|
|
380
|
+
with self._lock:
|
|
381
|
+
if entry['state'] != 'queued':
|
|
382
|
+
return
|
|
383
|
+
entry['state'] = 'running'
|
|
384
|
+
entry['started'] = time.time()
|
|
385
|
+
self._checkpoint(entry)
|
|
386
|
+
# Starting and registering the child share the cancellation lock. The child runs in the
|
|
387
|
+
# renderer's folder, so no module beside the server's working folder shadows cuju or
|
|
388
|
+
# torch, with that folder off its path of modules, and it reads nothing from the
|
|
389
|
+
# server's terminal.
|
|
390
|
+
process = subprocess.Popen(
|
|
391
|
+
command,
|
|
392
|
+
stdin=subprocess.DEVNULL,
|
|
393
|
+
stdout=subprocess.PIPE,
|
|
394
|
+
stderr=subprocess.PIPE,
|
|
395
|
+
text=True,
|
|
396
|
+
encoding='utf-8',
|
|
397
|
+
errors='replace',
|
|
398
|
+
cwd=_home.process_folder(),
|
|
399
|
+
env=_home.process_environment(),
|
|
400
|
+
)
|
|
401
|
+
self._processes[entry['id']] = process
|
|
402
|
+
stderr: collections.deque[str] = collections.deque(maxlen=20)
|
|
403
|
+
threading.Thread(target=lambda: stderr.extend(process.stderr), daemon=True).start()
|
|
404
|
+
expired = threading.Event()
|
|
405
|
+
|
|
406
|
+
def expire() -> None:
|
|
407
|
+
expired.set()
|
|
408
|
+
process.kill()
|
|
409
|
+
|
|
410
|
+
timer = threading.Timer(_MATCH_SECONDS, expire)
|
|
411
|
+
timer.daemon = True
|
|
412
|
+
timer.start()
|
|
413
|
+
try:
|
|
414
|
+
for line in process.stdout:
|
|
415
|
+
try:
|
|
416
|
+
report = json.loads(line)
|
|
417
|
+
progress = float(report.get('progress', entry['progress']))
|
|
418
|
+
except (ValueError, TypeError, AttributeError):
|
|
419
|
+
continue
|
|
420
|
+
with self._lock:
|
|
421
|
+
entry['progress'] = progress
|
|
422
|
+
if isinstance(report.get('match'), str):
|
|
423
|
+
entry['match'] = report['match']
|
|
424
|
+
if isinstance(report.get('error'), str):
|
|
425
|
+
entry.update(_messages.report_fields(report))
|
|
426
|
+
code = process.wait()
|
|
427
|
+
finally:
|
|
428
|
+
timer.cancel()
|
|
429
|
+
with self._lock:
|
|
430
|
+
self._processes.pop(entry['id'], None)
|
|
431
|
+
with self._lock:
|
|
432
|
+
if entry['state'] != 'running':
|
|
433
|
+
return
|
|
434
|
+
if code == 0 and entry['match']:
|
|
435
|
+
entry['state'] = 'done'
|
|
436
|
+
else:
|
|
437
|
+
entry['state'] = 'failed'
|
|
438
|
+
if expired.is_set():
|
|
439
|
+
entry.update(
|
|
440
|
+
_messages.fields('server.requests.timeout', minutes=_MATCH_SECONDS // 60)
|
|
441
|
+
)
|
|
442
|
+
elif not entry['error']:
|
|
443
|
+
tail = ''.join(stderr).strip()
|
|
444
|
+
entry.update(_messages.exit_fields('server.requests.exit', code, tail))
|
|
445
|
+
entry['finished'] = time.time()
|
|
446
|
+
self._checkpoint(entry)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
class GameBusyError(_messages.Message, Exception):
|
|
450
|
+
"""Raised when a game is asked for while another one plays, with the id of its message."""
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
class NoGameError(_messages.Message, Exception):
|
|
454
|
+
"""Raised for a game that is not the latest one, with the id of its message."""
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
# A game plays this many steps a second, real time, and a test may play faster.
|
|
458
|
+
_GAME_PACE = 10
|
|
459
|
+
# The page's input of one step names at most this many inputs, the four directions and the buttons.
|
|
460
|
+
_GAME_INPUTS = 16
|
|
461
|
+
# A stream waits this long for the game's process to start and announce its port.
|
|
462
|
+
_GAME_START_SECONDS = 120
|
|
463
|
+
# The process of the next game, kept ready by the server, ends after this long without a game.
|
|
464
|
+
_WARM_IDLE_SECONDS = 600
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
class _Games:
|
|
468
|
+
"""The game that a person plays on the page, one at a time, in a child process.
|
|
469
|
+
|
|
470
|
+
The process reads its commands, the input of each person's side, pause and quit, as JSON lines
|
|
471
|
+
on its standard input, and reports its state, its port and the recording it saved as JSON lines
|
|
472
|
+
on its standard output.
|
|
473
|
+
|
|
474
|
+
With `warm`, the server keeps the process of the next game ready once a game's stream opens, a
|
|
475
|
+
process that has loaded torch and cuju and waits for the arguments of its game, so the next
|
|
476
|
+
game starts at once. Each process still plays one game and ends. A process kept ready that
|
|
477
|
+
died, or whose environment changed, gives way to a new process, and one left without a game
|
|
478
|
+
for `_WARM_IDLE_SECONDS` ends.
|
|
479
|
+
"""
|
|
480
|
+
|
|
481
|
+
def __init__(self, warm: bool = False) -> None:
|
|
482
|
+
self._lock = threading.Lock()
|
|
483
|
+
self._entry: dict[str, Any] | None = None
|
|
484
|
+
self._process: subprocess.Popen | None = None
|
|
485
|
+
self._started = threading.Condition(self._lock)
|
|
486
|
+
self._warm = warm
|
|
487
|
+
self._closed = False
|
|
488
|
+
self._spare: subprocess.Popen | None = None
|
|
489
|
+
self._spare_key: Any = None
|
|
490
|
+
self._spare_timer: threading.Timer | None = None
|
|
491
|
+
self._last = time.monotonic()
|
|
492
|
+
|
|
493
|
+
def start(
|
|
494
|
+
self,
|
|
495
|
+
scenario: str,
|
|
496
|
+
humans: Any,
|
|
497
|
+
ability: Any = (None, None),
|
|
498
|
+
seed: int | None = None,
|
|
499
|
+
record: bool = True,
|
|
500
|
+
teams: Any = (_teams.BUILTIN, _teams.BUILTIN),
|
|
501
|
+
length: int | None = None,
|
|
502
|
+
tournament: dict[str, Any] | None = None,
|
|
503
|
+
) -> dict[str, Any]:
|
|
504
|
+
"""Starts a game and returns its entry.
|
|
505
|
+
|
|
506
|
+
Args:
|
|
507
|
+
scenario: A shipped scenario.
|
|
508
|
+
humans: Whether a person plays the left side and the right side.
|
|
509
|
+
ability: The ability of the built-in AI on each side.
|
|
510
|
+
seed: The seed, or `None` to draw one.
|
|
511
|
+
record: Whether the game goes to the library.
|
|
512
|
+
teams: The registry team of each side, which plays a side without a person and joins a
|
|
513
|
+
person as teammates.
|
|
514
|
+
length: The steps the game lasts, or `None` for the scenario's own duration.
|
|
515
|
+
tournament: The tournament match that the game plays, or `None`.
|
|
516
|
+
|
|
517
|
+
Raises:
|
|
518
|
+
ArgumentError: If the scenario is not shipped, the sides name no person, an ability
|
|
519
|
+
lies outside 0 to 1 or a team cannot play its side.
|
|
520
|
+
GameBusyError: If another game still plays.
|
|
521
|
+
"""
|
|
522
|
+
if scenario not in _scenarios():
|
|
523
|
+
raise MessageError('server.scenario', scenario=repr(scenario))
|
|
524
|
+
if (
|
|
525
|
+
not isinstance(humans, (list, tuple))
|
|
526
|
+
or len(humans) != 2
|
|
527
|
+
or not all(isinstance(value, bool) for value in humans)
|
|
528
|
+
or not any(humans)
|
|
529
|
+
):
|
|
530
|
+
raise MessageError('server.game.humans', humans=repr(humans))
|
|
531
|
+
ability = list(_teams.check_ability(ability))
|
|
532
|
+
if not isinstance(record, bool):
|
|
533
|
+
raise MessageError('server.game.record', record=repr(record))
|
|
534
|
+
if (
|
|
535
|
+
not isinstance(teams, (list, tuple))
|
|
536
|
+
or len(teams) != 2
|
|
537
|
+
or not all(isinstance(value, str) for value in teams)
|
|
538
|
+
):
|
|
539
|
+
raise MessageError('server.game.teams', teams=repr(teams))
|
|
540
|
+
teams = [str(value) for value in teams]
|
|
541
|
+
_teams.game_agents([_teams.entry(value) for value in teams], scenario, humans)
|
|
542
|
+
entry = {
|
|
543
|
+
'id': _home.new_identifier('g'),
|
|
544
|
+
'scenario': scenario,
|
|
545
|
+
'humans': list(humans),
|
|
546
|
+
'team_ids': teams,
|
|
547
|
+
'ability': ability,
|
|
548
|
+
'seed': seed,
|
|
549
|
+
'record': record,
|
|
550
|
+
'state': 'starting',
|
|
551
|
+
'reason': None,
|
|
552
|
+
'ending': None,
|
|
553
|
+
'step': 0,
|
|
554
|
+
'score': [0, 0],
|
|
555
|
+
'teams': None,
|
|
556
|
+
'team_labels': None,
|
|
557
|
+
'match': None,
|
|
558
|
+
'error': None,
|
|
559
|
+
'error_id': None,
|
|
560
|
+
'error_values': None,
|
|
561
|
+
'late': 0,
|
|
562
|
+
'streak': 0,
|
|
563
|
+
'tournament': tournament,
|
|
564
|
+
}
|
|
565
|
+
command = [
|
|
566
|
+
'--scenario',
|
|
567
|
+
scenario,
|
|
568
|
+
'--left',
|
|
569
|
+
'person' if humans[0] else 'builtin',
|
|
570
|
+
'--right',
|
|
571
|
+
'person' if humans[1] else 'builtin',
|
|
572
|
+
'--left-team',
|
|
573
|
+
teams[0],
|
|
574
|
+
'--right-team',
|
|
575
|
+
teams[1],
|
|
576
|
+
'--pace',
|
|
577
|
+
repr(float(_GAME_PACE)),
|
|
578
|
+
]
|
|
579
|
+
if seed is not None:
|
|
580
|
+
command += ['--seed', str(seed)]
|
|
581
|
+
if record:
|
|
582
|
+
command.append('--record')
|
|
583
|
+
for side, value in zip(('left', 'right'), ability, strict=True):
|
|
584
|
+
if value is not None:
|
|
585
|
+
command += [f'--{side}-ability', repr(value)]
|
|
586
|
+
if length is not None:
|
|
587
|
+
command += ['--length', str(int(length))]
|
|
588
|
+
if tournament is not None:
|
|
589
|
+
command += ['--tournament', json.dumps(tournament)]
|
|
590
|
+
with self._lock:
|
|
591
|
+
if self._entry is not None and self._entry['state'] not in ('ended', 'failed'):
|
|
592
|
+
raise GameBusyError('server.game.busy')
|
|
593
|
+
process = self._take(command) or self._spawn(command)
|
|
594
|
+
self._entry, self._process = entry, process
|
|
595
|
+
self._last = time.monotonic()
|
|
596
|
+
threading.Thread(target=self._watch, args=(entry, process), daemon=True).start()
|
|
597
|
+
return self._public(entry)
|
|
598
|
+
|
|
599
|
+
@staticmethod
|
|
600
|
+
def _key() -> Any:
|
|
601
|
+
"""Returns what a process takes from the server as it starts, for a kept one to match."""
|
|
602
|
+
return sys.executable, str(_home.home()), dict(os.environ)
|
|
603
|
+
|
|
604
|
+
@staticmethod
|
|
605
|
+
def _spawn(arguments: list[str]) -> subprocess.Popen:
|
|
606
|
+
"""Starts the process of a game with its arguments, or with `--warm` to keep it ready."""
|
|
607
|
+
# The child runs in the renderer's folder, with that folder off its path of modules,
|
|
608
|
+
# and writes its errors to a pipe of its own.
|
|
609
|
+
return subprocess.Popen(
|
|
610
|
+
[*_home.python_command(), '-m', 'cuju.render._playing.game', *arguments],
|
|
611
|
+
stdin=subprocess.PIPE,
|
|
612
|
+
stdout=subprocess.PIPE,
|
|
613
|
+
stderr=subprocess.PIPE,
|
|
614
|
+
text=True,
|
|
615
|
+
encoding='utf-8',
|
|
616
|
+
errors='replace',
|
|
617
|
+
cwd=_home.process_folder(),
|
|
618
|
+
env=_home.process_environment(),
|
|
619
|
+
)
|
|
620
|
+
|
|
621
|
+
def _take(self, arguments: list[str]) -> subprocess.Popen | None:
|
|
622
|
+
"""Hands the arguments of a game to the process kept ready and returns it, under the lock.
|
|
623
|
+
|
|
624
|
+
Returns `None`, after ending the kept process, when there is none, it died, its
|
|
625
|
+
environment differs from the server's now or it cannot read the arguments, and the game
|
|
626
|
+
then starts in a new process.
|
|
627
|
+
"""
|
|
628
|
+
spare, self._spare = self._spare, None
|
|
629
|
+
if self._spare_timer is not None:
|
|
630
|
+
self._spare_timer.cancel()
|
|
631
|
+
self._spare_timer = None
|
|
632
|
+
if spare is None:
|
|
633
|
+
return None
|
|
634
|
+
if spare.poll() is None and self._spare_key == self._key():
|
|
635
|
+
try:
|
|
636
|
+
spare.stdin.write(json.dumps(arguments) + '\n')
|
|
637
|
+
spare.stdin.flush()
|
|
638
|
+
return spare
|
|
639
|
+
except (OSError, ValueError):
|
|
640
|
+
pass
|
|
641
|
+
self._end(spare)
|
|
642
|
+
return None
|
|
643
|
+
|
|
644
|
+
def _prepare(self) -> None:
|
|
645
|
+
"""Readies the process of the next game, when the server keeps one and none waits."""
|
|
646
|
+
with self._lock:
|
|
647
|
+
if not self._warm or self._closed:
|
|
648
|
+
return
|
|
649
|
+
if self._spare is not None:
|
|
650
|
+
if self._spare.poll() is None:
|
|
651
|
+
return
|
|
652
|
+
self._end(self._spare)
|
|
653
|
+
self._spare = None
|
|
654
|
+
try:
|
|
655
|
+
spare = self._spawn(['--warm'])
|
|
656
|
+
except OSError:
|
|
657
|
+
return
|
|
658
|
+
self._spare, self._spare_key = spare, self._key()
|
|
659
|
+
self._arm(spare, _WARM_IDLE_SECONDS)
|
|
660
|
+
|
|
661
|
+
def _arm(self, spare: subprocess.Popen, seconds: float) -> None:
|
|
662
|
+
"""Ends the kept process after `seconds` without a game, under the lock."""
|
|
663
|
+
if self._spare_timer is not None:
|
|
664
|
+
self._spare_timer.cancel()
|
|
665
|
+
timer = threading.Timer(max(1.0, seconds), self._expire, args=(spare,))
|
|
666
|
+
timer.daemon = True
|
|
667
|
+
self._spare_timer = timer
|
|
668
|
+
timer.start()
|
|
669
|
+
|
|
670
|
+
def _expire(self, spare: subprocess.Popen) -> None:
|
|
671
|
+
"""Ends the kept process once no game has started or ended for `_WARM_IDLE_SECONDS`."""
|
|
672
|
+
with self._lock:
|
|
673
|
+
if self._spare is not spare:
|
|
674
|
+
return
|
|
675
|
+
playing = self._entry is not None and self._entry['state'] not in ('ended', 'failed')
|
|
676
|
+
idle = time.monotonic() - self._last
|
|
677
|
+
if playing or idle < _WARM_IDLE_SECONDS:
|
|
678
|
+
self._arm(spare, _WARM_IDLE_SECONDS - (0 if playing else idle))
|
|
679
|
+
return
|
|
680
|
+
self._spare, self._spare_timer = None, None
|
|
681
|
+
self._end(spare)
|
|
682
|
+
|
|
683
|
+
@staticmethod
|
|
684
|
+
def _end(process: subprocess.Popen) -> None:
|
|
685
|
+
"""Ends a kept process that no game took, and closes its pipes."""
|
|
686
|
+
with contextlib.suppress(OSError):
|
|
687
|
+
process.kill()
|
|
688
|
+
with contextlib.suppress(subprocess.TimeoutExpired):
|
|
689
|
+
process.wait(timeout=10)
|
|
690
|
+
for stream in (process.stdin, process.stdout, process.stderr):
|
|
691
|
+
with contextlib.suppress(OSError, ValueError):
|
|
692
|
+
stream.close()
|
|
693
|
+
|
|
694
|
+
def close(self) -> None:
|
|
695
|
+
"""Ends the process kept for the next game, as the server ends."""
|
|
696
|
+
with self._lock:
|
|
697
|
+
self._closed = True
|
|
698
|
+
spare, self._spare = self._spare, None
|
|
699
|
+
if self._spare_timer is not None:
|
|
700
|
+
self._spare_timer.cancel()
|
|
701
|
+
self._spare_timer = None
|
|
702
|
+
if spare is not None:
|
|
703
|
+
self._end(spare)
|
|
704
|
+
|
|
705
|
+
def current(self) -> dict[str, Any] | None:
|
|
706
|
+
"""Returns a copy of the latest game's entry, or `None` before the first."""
|
|
707
|
+
with self._lock:
|
|
708
|
+
return None if self._entry is None else self._public(self._entry)
|
|
709
|
+
|
|
710
|
+
@staticmethod
|
|
711
|
+
def _public(entry: dict[str, Any]) -> dict[str, Any]:
|
|
712
|
+
result = {key: value for key, value in entry.items() if key != 'port'}
|
|
713
|
+
result['seed'] = _public_seed(result.get('seed'))
|
|
714
|
+
return result
|
|
715
|
+
|
|
716
|
+
def _watch(self, entry: dict[str, Any], process: subprocess.Popen) -> None:
|
|
717
|
+
"""Follows the reports of a game's process until it ends."""
|
|
718
|
+
stderr: collections.deque[str] = collections.deque(maxlen=20)
|
|
719
|
+
threading.Thread(target=lambda: stderr.extend(process.stderr), daemon=True).start()
|
|
720
|
+
for line in process.stdout:
|
|
721
|
+
try:
|
|
722
|
+
report = json.loads(line)
|
|
723
|
+
except ValueError:
|
|
724
|
+
continue
|
|
725
|
+
if not isinstance(report, dict):
|
|
726
|
+
continue
|
|
727
|
+
with self._lock:
|
|
728
|
+
for key in (
|
|
729
|
+
'state',
|
|
730
|
+
'reason',
|
|
731
|
+
'ending',
|
|
732
|
+
'step',
|
|
733
|
+
'score',
|
|
734
|
+
'match',
|
|
735
|
+
'error',
|
|
736
|
+
'seed',
|
|
737
|
+
'teams',
|
|
738
|
+
'team_labels',
|
|
739
|
+
'late',
|
|
740
|
+
'streak',
|
|
741
|
+
'controlled',
|
|
742
|
+
'actions',
|
|
743
|
+
'achievements',
|
|
744
|
+
):
|
|
745
|
+
if key in report:
|
|
746
|
+
entry[key] = report[key]
|
|
747
|
+
if 'error' in report:
|
|
748
|
+
entry.update(_messages.report_fields(report))
|
|
749
|
+
opened = isinstance(report.get('port'), int)
|
|
750
|
+
if opened:
|
|
751
|
+
entry['port'] = report['port']
|
|
752
|
+
self._started.notify_all()
|
|
753
|
+
if opened:
|
|
754
|
+
# The next game's process loads while this game plays, so it starts at once.
|
|
755
|
+
self._prepare()
|
|
756
|
+
code = process.wait()
|
|
757
|
+
with self._lock:
|
|
758
|
+
if code == 0 and entry['state'] == 'ended':
|
|
759
|
+
pass
|
|
760
|
+
elif entry['state'] != 'ended':
|
|
761
|
+
entry['state'] = 'failed'
|
|
762
|
+
if not entry['error']:
|
|
763
|
+
tail = ''.join(stderr).strip()
|
|
764
|
+
entry.update(_messages.exit_fields('server.game.exit', code, tail))
|
|
765
|
+
self._last = time.monotonic()
|
|
766
|
+
self._started.notify_all()
|
|
767
|
+
self._prepare()
|
|
768
|
+
|
|
769
|
+
def port(self, identifier: str) -> int | None:
|
|
770
|
+
"""Waits for the game's stream to open and returns its port, or `None` if it never does."""
|
|
771
|
+
with self._lock:
|
|
772
|
+
entry = self._entry
|
|
773
|
+
if entry is None or entry['id'] != identifier:
|
|
774
|
+
return None
|
|
775
|
+
self._started.wait_for(
|
|
776
|
+
lambda: 'port' in entry or entry['state'] in ('ended', 'failed'),
|
|
777
|
+
_GAME_START_SECONDS,
|
|
778
|
+
)
|
|
779
|
+
return entry.get('port') if entry['state'] not in ('ended', 'failed') else None
|
|
780
|
+
|
|
781
|
+
def send(self, identifier: str, command: dict[str, Any]) -> dict[str, Any]:
|
|
782
|
+
"""Passes a command to the game's process and returns the game's entry.
|
|
783
|
+
|
|
784
|
+
Raises:
|
|
785
|
+
NoGameError: If the latest game has another identifier.
|
|
786
|
+
"""
|
|
787
|
+
with self._lock:
|
|
788
|
+
entry, process = self._entry, self._process
|
|
789
|
+
if entry is None or entry['id'] != identifier or process is None:
|
|
790
|
+
raise NoGameError('server.game.unknown')
|
|
791
|
+
if entry['state'] in ('ended', 'failed'):
|
|
792
|
+
return self._public(entry)
|
|
793
|
+
try:
|
|
794
|
+
process.stdin.write(json.dumps(command) + '\n')
|
|
795
|
+
process.stdin.flush()
|
|
796
|
+
except (OSError, ValueError):
|
|
797
|
+
pass
|
|
798
|
+
return self._public(entry)
|
|
799
|
+
|
|
800
|
+
def input(self, identifier: str, document: dict[str, Any]) -> dict[str, Any]:
|
|
801
|
+
"""Checks the input of a person's side and passes it to the game.
|
|
802
|
+
|
|
803
|
+
The input names the side, 0 for the left and 1 for the right, the inputs held now and the
|
|
804
|
+
buttons pressed since the last input, each from `cuju.render._playing.game.INPUTS`.
|
|
805
|
+
|
|
806
|
+
Raises:
|
|
807
|
+
ArgumentError: If the input holds anything else.
|
|
808
|
+
"""
|
|
809
|
+
from .._playing.game import BUTTONS, INPUTS
|
|
810
|
+
|
|
811
|
+
unknown = set(document) - {'side', 'held', 'pressed'}
|
|
812
|
+
if unknown:
|
|
813
|
+
raise MessageError('server.game.input_fields', unknown=repr(sorted(unknown)))
|
|
814
|
+
side = document.get('side')
|
|
815
|
+
with self._lock:
|
|
816
|
+
humans = self._entry['humans'] if self._entry is not None else [False, False]
|
|
817
|
+
if not any(humans):
|
|
818
|
+
raise NoGameError('server.game.unknown')
|
|
819
|
+
if isinstance(side, bool) or side not in (0, 1) or not humans[side]:
|
|
820
|
+
raise MessageError('server.game.side', sides=_sides(humans), side=repr(side))
|
|
821
|
+
command: dict[str, Any] = {'side': side}
|
|
822
|
+
for key, allowed in (('held', INPUTS), ('pressed', BUTTONS)):
|
|
823
|
+
value = document.get(key, [])
|
|
824
|
+
if (
|
|
825
|
+
not isinstance(value, list)
|
|
826
|
+
or len(value) > _GAME_INPUTS
|
|
827
|
+
or not all(isinstance(name, str) and name in allowed for name in value)
|
|
828
|
+
):
|
|
829
|
+
raise MessageError('server.game.input_list', key=key, allowed=', '.join(allowed))
|
|
830
|
+
command[key] = sorted(set(value))
|
|
831
|
+
return self.send(identifier, command)
|
|
832
|
+
|
|
833
|
+
def quit(self, identifier: str) -> dict[str, Any]:
|
|
834
|
+
"""Asks the game to end, saving it when it records, and ends its process if it hangs."""
|
|
835
|
+
entry = self.send(identifier, {'quit': True})
|
|
836
|
+
with self._lock:
|
|
837
|
+
process = self._process
|
|
838
|
+
if process is not None:
|
|
839
|
+
|
|
840
|
+
def stop() -> None:
|
|
841
|
+
# A game still starting reads the quit once it is ready, so the wait for a hang
|
|
842
|
+
# starts when its stream opens.
|
|
843
|
+
self.port(identifier)
|
|
844
|
+
try:
|
|
845
|
+
process.wait(timeout=30)
|
|
846
|
+
except subprocess.TimeoutExpired:
|
|
847
|
+
process.kill()
|
|
848
|
+
|
|
849
|
+
threading.Thread(target=stop, daemon=True).start()
|
|
850
|
+
return entry
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
def _seed(value: Any) -> int | None:
|
|
854
|
+
"""Returns the seed of a request, an integer from 0 to 2**64 - 1, or `None` to draw one."""
|
|
855
|
+
if value in (None, ''):
|
|
856
|
+
return None
|
|
857
|
+
if isinstance(value, str) and value.strip().isdigit():
|
|
858
|
+
value = int(value)
|
|
859
|
+
if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value < 2**64:
|
|
860
|
+
raise MessageError('server.seed', value=repr(value))
|
|
861
|
+
return value
|
|
862
|
+
|
|
863
|
+
|
|
864
|
+
def _public_seed(seed: Any) -> Any:
|
|
865
|
+
"""Returns a seed for the page, as text when JavaScript's numbers cannot hold it exactly."""
|
|
866
|
+
if isinstance(seed, int) and not isinstance(seed, bool) and seed > 2**53 - 1:
|
|
867
|
+
return str(seed)
|
|
868
|
+
return seed
|
|
869
|
+
|
|
870
|
+
|
|
871
|
+
def _loads(data: bytes | str, name: str | None = None) -> Any:
|
|
872
|
+
"""Returns the value of the JSON of a request, its body or the parameter `name`.
|
|
873
|
+
|
|
874
|
+
Raises:
|
|
875
|
+
MessageError: If the text is no JSON, with the line and column of its first mistake.
|
|
876
|
+
"""
|
|
877
|
+
try:
|
|
878
|
+
return json.loads(data)
|
|
879
|
+
except json.JSONDecodeError as error:
|
|
880
|
+
place = {'line': error.lineno, 'column': error.colno}
|
|
881
|
+
if name is None:
|
|
882
|
+
raise MessageError('server.json', **place) from None
|
|
883
|
+
raise MessageError('server.json_query', name=name, **place) from None
|
|
884
|
+
except UnicodeDecodeError:
|
|
885
|
+
raise MessageError('server.json_text') from None
|
|
886
|
+
|
|
887
|
+
|
|
888
|
+
def _control(query: dict[str, str]) -> dict[str, Any] | None:
|
|
889
|
+
"""Returns uploaded team control, accepting earlier count and goalkeeper queries."""
|
|
890
|
+
if 'control' in query:
|
|
891
|
+
return _loads(query['control'], 'control')
|
|
892
|
+
if 'players' not in query and 'goalkeeper' not in query:
|
|
893
|
+
return None
|
|
894
|
+
players = query.get('players', '1')
|
|
895
|
+
if not players.isdigit():
|
|
896
|
+
raise MessageError('server.teams.controlled_players', players=repr(players))
|
|
897
|
+
return {'players': int(players), 'goalkeeper': query.get('goalkeeper', 'agent')}
|
|
898
|
+
|
|
899
|
+
|
|
900
|
+
def _scenarios() -> list[str]:
|
|
901
|
+
"""Returns the shipped scenarios, without agent counts."""
|
|
902
|
+
return sorted([*bundled_scenarios(), *_teams.renderer_scenarios()])
|
|
903
|
+
|
|
904
|
+
|
|
905
|
+
def _scenario_sides() -> dict[str, list[list[dict[str, Any]]]]:
|
|
906
|
+
"""Returns the players of both sides of every shipped scenario, by scenario.
|
|
907
|
+
|
|
908
|
+
Each player names its GRF role as a number and whether a team can control it, which the page
|
|
909
|
+
reads to tell which teams can play a side, as `_teams.check_scenario` tells it. A scenario
|
|
910
|
+
that fails to load is left out, and the page then checks only its format.
|
|
911
|
+
"""
|
|
912
|
+
sides = {}
|
|
913
|
+
for name in _scenarios():
|
|
914
|
+
try:
|
|
915
|
+
found = _teams.scenario_sides(name)
|
|
916
|
+
except Exception as error:
|
|
917
|
+
_LOGGER.warning('cuju render leaves out the players of %s, %s', name, error)
|
|
918
|
+
continue
|
|
919
|
+
sides[name] = [
|
|
920
|
+
[{'role': role, 'controllable': controllable} for role, controllable in team]
|
|
921
|
+
for team in found
|
|
922
|
+
]
|
|
923
|
+
return sides
|
|
924
|
+
|
|
925
|
+
|
|
926
|
+
def _whole(value: Any) -> bool:
|
|
927
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
|
928
|
+
|
|
929
|
+
|
|
930
|
+
def _announced(source: Any) -> bool:
|
|
931
|
+
"""Returns whether a live announcement holds each field that the server reads, of its kind.
|
|
932
|
+
|
|
933
|
+
The server reaches a source at its port of the loopback interface alone, and only at a port
|
|
934
|
+
that no system service takes, from 1024 on.
|
|
935
|
+
"""
|
|
936
|
+
return (
|
|
937
|
+
isinstance(source, dict)
|
|
938
|
+
and isinstance(source.get('id'), str)
|
|
939
|
+
and _home.valid_identifier(source['id'])
|
|
940
|
+
and isinstance(source.get('title'), str)
|
|
941
|
+
and isinstance(source.get('scenario'), str)
|
|
942
|
+
and _whole(source.get('environment'))
|
|
943
|
+
and _whole(source.get('environment_count', 1))
|
|
944
|
+
and _whole(source.get('generation', 0))
|
|
945
|
+
and _whole(source.get('port'))
|
|
946
|
+
and 1024 <= source['port'] <= 65535
|
|
947
|
+
)
|
|
948
|
+
|
|
949
|
+
|
|
950
|
+
def _sources() -> list[dict[str, Any]]:
|
|
951
|
+
"""Returns the live sources whose process runs, and withdraws the announcements of others."""
|
|
952
|
+
sources = []
|
|
953
|
+
for path in _home.folder('live').glob('*.json'):
|
|
954
|
+
try:
|
|
955
|
+
source = json.loads(path.read_text(encoding='utf-8'))
|
|
956
|
+
except (OSError, ValueError):
|
|
957
|
+
continue
|
|
958
|
+
# An announcement without a whole number for its process, or with a field that the server
|
|
959
|
+
# cannot read, is skipped alone, and the list goes on.
|
|
960
|
+
pid = source.get('pid') if isinstance(source, dict) else None
|
|
961
|
+
if not _whole(pid) or not _announced(source):
|
|
962
|
+
continue
|
|
963
|
+
if not _alive(pid):
|
|
964
|
+
path.unlink(missing_ok=True)
|
|
965
|
+
continue
|
|
966
|
+
sources.append(source)
|
|
967
|
+
return sources
|
|
968
|
+
|
|
969
|
+
|
|
970
|
+
def _sides(humans: list[bool]) -> dict[str, Any]:
|
|
971
|
+
"""Returns the sides that a person plays, as a label for the answer to a wrong side."""
|
|
972
|
+
if all(humans):
|
|
973
|
+
return _messages.label('server.game.sides_both')
|
|
974
|
+
return _messages.label('server.game.sides_right' if humans[1] else 'server.game.sides_left')
|
|
975
|
+
|
|
976
|
+
|
|
977
|
+
def _interrupt(signum: int, frame: Any) -> None:
|
|
978
|
+
"""Ends `serve` as Ctrl+C does, so that it withdraws its file and closes its tournaments."""
|
|
979
|
+
raise KeyboardInterrupt
|
|
980
|
+
|
|
981
|
+
|
|
982
|
+
def _alive(pid: int) -> bool:
|
|
983
|
+
"""Returns whether a process runs, without signalling it."""
|
|
984
|
+
if pid <= 0:
|
|
985
|
+
return False
|
|
986
|
+
if sys.platform == 'win32':
|
|
987
|
+
import ctypes
|
|
988
|
+
|
|
989
|
+
handle = ctypes.windll.kernel32.OpenProcess(0x1000, False, pid)
|
|
990
|
+
if not handle:
|
|
991
|
+
return False
|
|
992
|
+
code = ctypes.c_ulong()
|
|
993
|
+
ctypes.windll.kernel32.GetExitCodeProcess(handle, ctypes.byref(code))
|
|
994
|
+
ctypes.windll.kernel32.CloseHandle(handle)
|
|
995
|
+
# Windows: 259 is `STILL_ACTIVE`.
|
|
996
|
+
return code.value == 259
|
|
997
|
+
try:
|
|
998
|
+
os.kill(pid, 0)
|
|
999
|
+
except ProcessLookupError:
|
|
1000
|
+
return False
|
|
1001
|
+
except PermissionError:
|
|
1002
|
+
return True
|
|
1003
|
+
return True
|
|
1004
|
+
|
|
1005
|
+
|
|
1006
|
+
# The names of the loopback interface, which a request's host must carry.
|
|
1007
|
+
_LOOPBACK = ('127.0.0.1', 'localhost', '::1')
|
|
1008
|
+
# The largest body a request may send, a submission of 100 MB with room for its index.
|
|
1009
|
+
_MAXIMUM_BODY = 110 * 1024 * 1024
|
|
1010
|
+
# The largest body of a refused request that the server reads before it answers.
|
|
1011
|
+
_DRAINED_BODY = 64 * 1024
|
|
1012
|
+
|
|
1013
|
+
|
|
1014
|
+
def make_handler(
|
|
1015
|
+
requests: _Requests,
|
|
1016
|
+
games: _Games | None = None,
|
|
1017
|
+
tournaments: _tournament_runner.Tournaments | None = None,
|
|
1018
|
+
videos: _video_jobs.VideoJobs | None = None,
|
|
1019
|
+
) -> type[http.server.BaseHTTPRequestHandler]:
|
|
1020
|
+
"""Returns the request handler of the server, which serves the loopback interface alone.
|
|
1021
|
+
|
|
1022
|
+
The tournaments start with the first request that names them, unless the server passes them.
|
|
1023
|
+
"""
|
|
1024
|
+
allowed_hosts = set(_LOOPBACK)
|
|
1025
|
+
games = games if games is not None else _Games()
|
|
1026
|
+
held = {'tournaments': tournaments}
|
|
1027
|
+
held_lock = threading.Lock()
|
|
1028
|
+
|
|
1029
|
+
def cups() -> _tournament_runner.Tournaments:
|
|
1030
|
+
with held_lock:
|
|
1031
|
+
if held['tournaments'] is None:
|
|
1032
|
+
held['tournaments'] = _tournament_runner.Tournaments(games)
|
|
1033
|
+
return held['tournaments']
|
|
1034
|
+
|
|
1035
|
+
videos = videos if videos is not None else _video_jobs.VideoJobs()
|
|
1036
|
+
|
|
1037
|
+
class Handler(http.server.BaseHTTPRequestHandler):
|
|
1038
|
+
server_version = 'cuju-render'
|
|
1039
|
+
timeout = 60
|
|
1040
|
+
# Each answer leaves at once, its headers and body together, rather than after the delay
|
|
1041
|
+
# that holds small writes back, which on Windows costs a fifth of a second a request.
|
|
1042
|
+
disable_nagle_algorithm = True
|
|
1043
|
+
|
|
1044
|
+
# How the response being written may be framed, by the rules of `headers`.
|
|
1045
|
+
_framing = _headers.DENY
|
|
1046
|
+
|
|
1047
|
+
def end_headers(self) -> None:
|
|
1048
|
+
"""Adds to every response the headers that keep other sites from framing the page.
|
|
1049
|
+
|
|
1050
|
+
A page asked for with the key of the server, which `show` hands to a notebook, may sit
|
|
1051
|
+
in the frame of a notebook on this machine, in VS Code or in Google Colab. The page of
|
|
1052
|
+
a clean feed sits in the frame of /feed, and the page that draws a video export in the
|
|
1053
|
+
page that encodes it, both pages of this server. The sandbox of team presentation
|
|
1054
|
+
workers sends its own policy, which says who may frame it. The mock servers of `ci`
|
|
1055
|
+
send the same headers, from the same module.
|
|
1056
|
+
"""
|
|
1057
|
+
for name, value in _headers.security(self._framing):
|
|
1058
|
+
self.send_header(name, value)
|
|
1059
|
+
super().end_headers()
|
|
1060
|
+
|
|
1061
|
+
def _allowed(self) -> bool:
|
|
1062
|
+
"""Refuses a request of another site, which could upload and run code.
|
|
1063
|
+
|
|
1064
|
+
A page of another site that names this server, or a host name of another site that
|
|
1065
|
+
resolves here, sends another host or origin, so the server answers only requests that
|
|
1066
|
+
name it by its own host and come from its own page or from no page at all.
|
|
1067
|
+
"""
|
|
1068
|
+
named = self.headers.get('Host') or ''
|
|
1069
|
+
# A server that `show` starts inside Google Colab also answers the names of Colab's
|
|
1070
|
+
# proxy, which resolve to Google alone, so no other site makes a browser send them.
|
|
1071
|
+
domains = getattr(self.server, 'proxy_domains', ())
|
|
1072
|
+
hostname = urllib.parse.urlsplit('//' + named).hostname
|
|
1073
|
+
if hostname not in allowed_hosts and not _launch.in_domains(hostname, domains):
|
|
1074
|
+
self._drain()
|
|
1075
|
+
self._refuse(403, 'server.loopback')
|
|
1076
|
+
return False
|
|
1077
|
+
# A page served by another port of this machine is another site, so the whole
|
|
1078
|
+
# origin, scheme, host and port, must be this server's own.
|
|
1079
|
+
# The proxy of Google Colab shows the page under https at the same loopback host and
|
|
1080
|
+
# port, an origin that no other page can hold while this server holds the port. Behind
|
|
1081
|
+
# the proxy the page's origin names the very host the request names, and a page of
|
|
1082
|
+
# any other notebook, under another name of Colab's domains, is another site.
|
|
1083
|
+
origin = self.headers.get('Origin')
|
|
1084
|
+
own = (f'http://{named}', f'https://{named}')
|
|
1085
|
+
proxied = origin is not None and origin.startswith('https://')
|
|
1086
|
+
if proxied:
|
|
1087
|
+
origin_host = urllib.parse.urlsplit(origin).hostname
|
|
1088
|
+
proxied = origin_host == hostname and _launch.in_domains(origin_host, domains)
|
|
1089
|
+
if origin is not None and self.command != 'GET' and origin not in own and not proxied:
|
|
1090
|
+
self._drain()
|
|
1091
|
+
self._refuse(403, 'server.origin')
|
|
1092
|
+
return False
|
|
1093
|
+
try:
|
|
1094
|
+
length = int(self.headers.get('Content-Length') or 0)
|
|
1095
|
+
except ValueError:
|
|
1096
|
+
self._refuse(400, 'server.content_length')
|
|
1097
|
+
return False
|
|
1098
|
+
if length > _MAXIMUM_BODY:
|
|
1099
|
+
self._refuse(413, 'server.body_size')
|
|
1100
|
+
return False
|
|
1101
|
+
return True
|
|
1102
|
+
|
|
1103
|
+
def _drain(self) -> None:
|
|
1104
|
+
"""Reads a small body that a refused request sent, then closes the connection.
|
|
1105
|
+
|
|
1106
|
+
A server that answers before reading the body and closes the connection makes some
|
|
1107
|
+
systems, Windows among them, reset it, so the client may lose the answer. A body too
|
|
1108
|
+
large or of a malformed length is left unread, since the connection closes anyway.
|
|
1109
|
+
"""
|
|
1110
|
+
self.close_connection = True
|
|
1111
|
+
try:
|
|
1112
|
+
length = int(self.headers.get('Content-Length') or 0)
|
|
1113
|
+
except ValueError:
|
|
1114
|
+
return
|
|
1115
|
+
if 0 < length <= _DRAINED_BODY:
|
|
1116
|
+
self.rfile.read(length)
|
|
1117
|
+
|
|
1118
|
+
def log_message(self, *arguments: Any) -> None:
|
|
1119
|
+
pass
|
|
1120
|
+
|
|
1121
|
+
def _handle(self, method: Any) -> None:
|
|
1122
|
+
if not self._allowed():
|
|
1123
|
+
return
|
|
1124
|
+
try:
|
|
1125
|
+
method()
|
|
1126
|
+
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
|
|
1127
|
+
pass
|
|
1128
|
+
except (ArgumentError, ValueError, TypeError, KeyError, AttributeError) as error:
|
|
1129
|
+
# cuju's own errors say what to do in words, the others name their kind as well.
|
|
1130
|
+
if isinstance(error, Error):
|
|
1131
|
+
self._error(400, str(error), error)
|
|
1132
|
+
else:
|
|
1133
|
+
self._error(400, _messages.described(error), error)
|
|
1134
|
+
except Exception as error:
|
|
1135
|
+
where = self.path.split('?')[0]
|
|
1136
|
+
_doctor.note_error(f'{self.command} {where}, {_messages.described(error)}')
|
|
1137
|
+
self._error(500, _messages.described(error), error)
|
|
1138
|
+
|
|
1139
|
+
def _json(self, value: Any, status: int = 200) -> None:
|
|
1140
|
+
"""Answers with JSON that every page reads, a number that is NaN or infinite as null."""
|
|
1141
|
+
|
|
1142
|
+
def finite(item: Any) -> Any:
|
|
1143
|
+
# A number less itself is zero unless it is NaN or infinite.
|
|
1144
|
+
if isinstance(item, float) and item - item != 0:
|
|
1145
|
+
return None
|
|
1146
|
+
if isinstance(item, dict):
|
|
1147
|
+
return {key: finite(inner) for key, inner in item.items()}
|
|
1148
|
+
if isinstance(item, (list, tuple)):
|
|
1149
|
+
return [finite(inner) for inner in item]
|
|
1150
|
+
return item
|
|
1151
|
+
|
|
1152
|
+
try:
|
|
1153
|
+
body = json.dumps(value, allow_nan=False).encode()
|
|
1154
|
+
except ValueError:
|
|
1155
|
+
# A stored file of an older install may still hold such a number.
|
|
1156
|
+
body = json.dumps(finite(value), allow_nan=False).encode()
|
|
1157
|
+
self.send_response(status)
|
|
1158
|
+
self.send_header('Content-Type', 'application/json')
|
|
1159
|
+
self.send_header('Content-Length', str(len(body)))
|
|
1160
|
+
self.send_header('Cache-Control', 'no-store')
|
|
1161
|
+
self.end_headers()
|
|
1162
|
+
self.wfile.write(body)
|
|
1163
|
+
|
|
1164
|
+
def _error(
|
|
1165
|
+
self,
|
|
1166
|
+
status: int,
|
|
1167
|
+
message: str | BaseException,
|
|
1168
|
+
message_id: str | BaseException | None = None,
|
|
1169
|
+
values: dict[str, Any] | None = None,
|
|
1170
|
+
) -> None:
|
|
1171
|
+
"""Answers with an error, its English text in `error` as always.
|
|
1172
|
+
|
|
1173
|
+
Args:
|
|
1174
|
+
status: The status of the answer.
|
|
1175
|
+
message: The text, or an exception whose text the answer gives.
|
|
1176
|
+
message_id: The id of the message in `_messages.MESSAGES`, or an exception that
|
|
1177
|
+
carries one, or `None` for the id that `message` carries, if any. The answer
|
|
1178
|
+
then names it in `error_id`, with `values` in `error_values`, so the page
|
|
1179
|
+
shows the message in its own language.
|
|
1180
|
+
values: The values of the placeholders of `message_id`.
|
|
1181
|
+
"""
|
|
1182
|
+
text = message if isinstance(message, str) else str(message)
|
|
1183
|
+
origin = message_id
|
|
1184
|
+
if origin is None and isinstance(message, BaseException):
|
|
1185
|
+
origin = message
|
|
1186
|
+
if isinstance(origin, str):
|
|
1187
|
+
document = {
|
|
1188
|
+
'error': text,
|
|
1189
|
+
'error_id': origin,
|
|
1190
|
+
'error_values': {key: str(value) for key, value in (values or {}).items()},
|
|
1191
|
+
}
|
|
1192
|
+
elif isinstance(origin, BaseException) and not isinstance(origin, Error):
|
|
1193
|
+
# An error of another kind, such as a ValueError of Python, says what went wrong in
|
|
1194
|
+
# its own words, which the page shows inside a message of its language.
|
|
1195
|
+
document = _messages.error_fields(origin, text)
|
|
1196
|
+
if 'error_id' not in document:
|
|
1197
|
+
frame = 'server.invalid' if status < 500 else 'server.unexpected'
|
|
1198
|
+
document.update(error_id=frame, error_values={'error': text})
|
|
1199
|
+
elif isinstance(origin, BaseException):
|
|
1200
|
+
document = _messages.error_fields(origin, text)
|
|
1201
|
+
else:
|
|
1202
|
+
document = {'error': text}
|
|
1203
|
+
self._json(document, status)
|
|
1204
|
+
|
|
1205
|
+
def _refuse(self, status: int, message_id: str, **values: Any) -> None:
|
|
1206
|
+
"""Answers with the error of a message of `_messages.MESSAGES`, in English and by id."""
|
|
1207
|
+
self._json(_messages.fields(message_id, **values), status)
|
|
1208
|
+
|
|
1209
|
+
def _body(self) -> bytes:
|
|
1210
|
+
length = int(self.headers.get('Content-Length') or 0)
|
|
1211
|
+
return self.rfile.read(length) if length > 0 else b''
|
|
1212
|
+
|
|
1213
|
+
def _document(self) -> dict[str, Any]:
|
|
1214
|
+
document = _loads(self._body() or b'{}')
|
|
1215
|
+
if not isinstance(document, dict):
|
|
1216
|
+
raise MessageError('server.json_object')
|
|
1217
|
+
return document
|
|
1218
|
+
|
|
1219
|
+
def _route(self) -> tuple[list[str], dict[str, str]]:
|
|
1220
|
+
parsed = urllib.parse.urlsplit(self.path)
|
|
1221
|
+
parts = [urllib.parse.unquote(part) for part in parsed.path.split('/') if part]
|
|
1222
|
+
query = dict(urllib.parse.parse_qsl(parsed.query))
|
|
1223
|
+
return parts, query
|
|
1224
|
+
|
|
1225
|
+
def do_GET(self) -> None:
|
|
1226
|
+
self._handle(self._get)
|
|
1227
|
+
|
|
1228
|
+
def _get(self) -> None:
|
|
1229
|
+
parts, _ = self._route()
|
|
1230
|
+
try:
|
|
1231
|
+
if parts == ['sandbox', 'presentation']:
|
|
1232
|
+
self._sandbox()
|
|
1233
|
+
elif parts == ['feed']:
|
|
1234
|
+
self._static(['feed.html'])
|
|
1235
|
+
elif parts[:1] != ['api']:
|
|
1236
|
+
self._static(parts)
|
|
1237
|
+
elif parts in (['api', 'matches'], ['api', 'trash']):
|
|
1238
|
+
# A group names the recordings of one run of a challenge.
|
|
1239
|
+
group = self._route()[1].get('group') or None
|
|
1240
|
+
self._json(_library.matches(parts[1] == 'trash', group))
|
|
1241
|
+
elif parts == ['api', 'search']:
|
|
1242
|
+
query = self._route()[1]
|
|
1243
|
+
limit = query.get('limit')
|
|
1244
|
+
if limit and not (limit.isdigit() and len(limit) <= 9):
|
|
1245
|
+
raise MessageError('server.search.limit', limit=repr(limit))
|
|
1246
|
+
self._json(_search.search(query.get('q', ''), int(limit) if limit else None))
|
|
1247
|
+
elif len(parts) == 4 and parts[1] == 'matches' and parts[3] == 'moments':
|
|
1248
|
+
self._moments(parts[2], False)
|
|
1249
|
+
elif len(parts) == 4 and parts[1] == 'matches' and parts[3] == 'captions.vtt':
|
|
1250
|
+
self._moments(parts[2], True)
|
|
1251
|
+
elif len(parts) == 4 and parts[1] == 'matches' and parts[3] == 'details':
|
|
1252
|
+
try:
|
|
1253
|
+
self._json(_library.details(parts[2]))
|
|
1254
|
+
except ArgumentError as error:
|
|
1255
|
+
self._error(404, error)
|
|
1256
|
+
elif len(parts) == 3 and parts[1] == 'matches':
|
|
1257
|
+
self._recording(parts[2])
|
|
1258
|
+
elif parts == ['api', 'live']:
|
|
1259
|
+
# A source of 0.2.0 announces neither the number of environments nor the
|
|
1260
|
+
# stream, so those fields read one and zero.
|
|
1261
|
+
self._json(
|
|
1262
|
+
[
|
|
1263
|
+
{
|
|
1264
|
+
**{
|
|
1265
|
+
key: source[key]
|
|
1266
|
+
for key in ('id', 'title', 'scenario', 'environment')
|
|
1267
|
+
},
|
|
1268
|
+
# A title that cuju made comes with its message, as a label.
|
|
1269
|
+
**_messages.named('title', _recording.label_of(source, 'title')),
|
|
1270
|
+
'environment_count': source.get('environment_count', 1),
|
|
1271
|
+
'generation': source.get('generation', 0),
|
|
1272
|
+
}
|
|
1273
|
+
for source in _sources()
|
|
1274
|
+
]
|
|
1275
|
+
)
|
|
1276
|
+
elif len(parts) == 4 and parts[1] == 'live' and parts[3] == 'stream':
|
|
1277
|
+
self._relay(parts[2])
|
|
1278
|
+
elif len(parts) == 4 and parts[1] == 'live' and parts[3] == 'grid':
|
|
1279
|
+
self._live_grid(parts[2])
|
|
1280
|
+
elif parts == ['api', 'feed']:
|
|
1281
|
+
base = f'http://{self.headers.get("Host") or "127.0.0.1"}/'
|
|
1282
|
+
self._json(_feed.targets(base, _sources(), cups().entries()))
|
|
1283
|
+
elif parts == ['api', 'feed', 'resolve']:
|
|
1284
|
+
self._json(self._resolve_feed(self._route()[1].get('source', 'auto')))
|
|
1285
|
+
elif parts == ['api', 'info']:
|
|
1286
|
+
self._json({'version': _version.__version__, 'cuju': __version__})
|
|
1287
|
+
elif parts == ['api', 'video']:
|
|
1288
|
+
self._json(_video_jobs.availability())
|
|
1289
|
+
elif parts == ['api', 'videos']:
|
|
1290
|
+
self._json(videos.entries())
|
|
1291
|
+
elif len(parts) == 3 and parts[1] == 'videos':
|
|
1292
|
+
entry = videos.entry(parts[2])
|
|
1293
|
+
if entry is None:
|
|
1294
|
+
self._refuse(404, 'server.video.unknown')
|
|
1295
|
+
else:
|
|
1296
|
+
self._json(entry)
|
|
1297
|
+
elif len(parts) == 4 and parts[1] == 'videos' and parts[3] == 'file':
|
|
1298
|
+
self._video(videos.file(parts[2]))
|
|
1299
|
+
elif parts == ['api', 'scenarios']:
|
|
1300
|
+
self._json(_scenarios())
|
|
1301
|
+
elif parts == ['api', 'scenarios', 'sides']:
|
|
1302
|
+
self._json(_scenario_sides())
|
|
1303
|
+
elif parts == ['api', 'teams']:
|
|
1304
|
+
self._json(_teams.teams())
|
|
1305
|
+
elif len(parts) == 4 and parts[1] == 'teams' and parts[3] == 'model':
|
|
1306
|
+
self._model(parts[2])
|
|
1307
|
+
elif len(parts) == 5 and parts[1] == 'teams' and parts[3] == 'images':
|
|
1308
|
+
self._image(parts[2], parts[4])
|
|
1309
|
+
elif len(parts) == 5 and parts[1] == 'teams' and parts[3] == 'sounds':
|
|
1310
|
+
self._sound(parts[2], parts[4])
|
|
1311
|
+
elif len(parts) == 5 and parts[1] == 'teams' and parts[3] == 'clips':
|
|
1312
|
+
self._clip(parts[2], parts[4])
|
|
1313
|
+
elif len(parts) == 4 and parts[1] == 'teams' and parts[3] == 'presentation':
|
|
1314
|
+
self._json(_presentation.served(parts[2]))
|
|
1315
|
+
elif len(parts) >= 5 and parts[1] == 'teams' and parts[3] == 'presentation':
|
|
1316
|
+
self._package_file(parts[2], '/'.join(parts[4:]))
|
|
1317
|
+
elif len(parts) == 4 and parts[1] == 'teams' and parts[3] == 'export':
|
|
1318
|
+
self._export(parts[2])
|
|
1319
|
+
elif parts == ['api', 'models']:
|
|
1320
|
+
self._json(_teams.shipped_models())
|
|
1321
|
+
elif parts == ['api', 'presentation', 'sides']:
|
|
1322
|
+
self._json(_presentation.sides())
|
|
1323
|
+
elif parts == ['api', 'requests']:
|
|
1324
|
+
self._json(requests.entries())
|
|
1325
|
+
elif parts == ['api', 'game']:
|
|
1326
|
+
self._json(games.current())
|
|
1327
|
+
elif parts[:2] == ['api', 'tournaments']:
|
|
1328
|
+
self._tournament_get(parts[2:])
|
|
1329
|
+
elif parts[:3] == ['api', 'challenges', 'benches'] and parts[4:] == ['table.csv']:
|
|
1330
|
+
self._bench_csv(parts[3])
|
|
1331
|
+
elif parts[:2] == ['api', 'challenges']:
|
|
1332
|
+
self._json(*_challenges.get(parts[2:], self._route()[1]))
|
|
1333
|
+
elif parts == ['api', 'achievements']:
|
|
1334
|
+
self._json(_achievements.public())
|
|
1335
|
+
elif parts[:2] == ['api', 'help']:
|
|
1336
|
+
self._json(*_help.get(parts[2:], self._route()[1]))
|
|
1337
|
+
elif parts[:2] == ['api', 'languages']:
|
|
1338
|
+
self._json(*_languages.get(parts[2:]))
|
|
1339
|
+
elif len(parts) == 4 and parts[1] == 'game' and parts[3] == 'stream':
|
|
1340
|
+
port = games.port(parts[2])
|
|
1341
|
+
if port is None:
|
|
1342
|
+
self._refuse(404, 'server.game.unknown')
|
|
1343
|
+
else:
|
|
1344
|
+
self._pipe(port, 'game')
|
|
1345
|
+
else:
|
|
1346
|
+
self._refuse(404, 'server.no_resource')
|
|
1347
|
+
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
|
|
1348
|
+
pass
|
|
1349
|
+
|
|
1350
|
+
def do_POST(self) -> None:
|
|
1351
|
+
self._handle(self._post)
|
|
1352
|
+
|
|
1353
|
+
def _post(self) -> None:
|
|
1354
|
+
parts, query = self._route()
|
|
1355
|
+
try:
|
|
1356
|
+
if len(parts) == 4 and parts[1] == 'teams' and parts[3] == 'duplicate':
|
|
1357
|
+
self._json(_teams.duplicate(parts[2]), 201)
|
|
1358
|
+
elif len(parts) == 4 and parts[1] == 'teams' and parts[3] == 'preflight':
|
|
1359
|
+
# The check of a team under strict rules, a pass or the rule it broke.
|
|
1360
|
+
self._json(_tournament_runner.check_team(parts[2], self._document()))
|
|
1361
|
+
elif len(parts) == 4 and parts[1] == 'matches' and parts[3] == 'video':
|
|
1362
|
+
self._json(videos.start(parts[2], self._document()), 201)
|
|
1363
|
+
elif len(parts) == 4 and parts[1] == 'live' and parts[3] == 'environment':
|
|
1364
|
+
self._select_environment(parts[2])
|
|
1365
|
+
elif parts == ['api', 'teams']:
|
|
1366
|
+
entry = _teams.add(
|
|
1367
|
+
query.get('name', ''),
|
|
1368
|
+
query.get('filename', 'main.py'),
|
|
1369
|
+
self._body(),
|
|
1370
|
+
query.get('format', '11v11'),
|
|
1371
|
+
_control(query),
|
|
1372
|
+
)
|
|
1373
|
+
self._json(entry, 201)
|
|
1374
|
+
elif len(parts) == 4 and parts[1] == 'trash' and parts[3] == 'restore':
|
|
1375
|
+
if _library.trash(parts[2], restore=True):
|
|
1376
|
+
self._json(_library.details(parts[2]))
|
|
1377
|
+
else:
|
|
1378
|
+
self._refuse(404, 'server.trash.unknown')
|
|
1379
|
+
elif len(parts) == 4 and parts[1] == 'groups' and parts[3] == 'restore':
|
|
1380
|
+
restored = _library.trash_group(parts[2], restore=True)
|
|
1381
|
+
if restored:
|
|
1382
|
+
self._json({'group': parts[2], 'restored': restored})
|
|
1383
|
+
else:
|
|
1384
|
+
self._refuse(404, 'server.library.group_trash')
|
|
1385
|
+
elif parts == ['api', 'presentation', 'sides']:
|
|
1386
|
+
self._json(_presentation.assign(self._document()))
|
|
1387
|
+
elif parts == ['api', 'requests']:
|
|
1388
|
+
document = self._document()
|
|
1389
|
+
entry = requests.add(
|
|
1390
|
+
str(document.get('left', _teams.BUILTIN)),
|
|
1391
|
+
str(document.get('right', _teams.BUILTIN)),
|
|
1392
|
+
str(document.get('scenario', '11_vs_11_kaggle')),
|
|
1393
|
+
_seed(document.get('seed')),
|
|
1394
|
+
document.get('ability', [None, None]),
|
|
1395
|
+
document.get('pool'),
|
|
1396
|
+
document.get('same_team', False),
|
|
1397
|
+
)
|
|
1398
|
+
self._json(entry, 201)
|
|
1399
|
+
elif parts == ['api', 'game']:
|
|
1400
|
+
document = self._document()
|
|
1401
|
+
entry = games.start(
|
|
1402
|
+
str(document.get('scenario', '11_vs_11_kaggle')),
|
|
1403
|
+
document.get('humans', [True, False]),
|
|
1404
|
+
document.get('ability', [None, None]),
|
|
1405
|
+
_seed(document.get('seed')),
|
|
1406
|
+
document.get('record', True),
|
|
1407
|
+
document.get('teams', [_teams.BUILTIN, _teams.BUILTIN]),
|
|
1408
|
+
)
|
|
1409
|
+
self._json(entry, 201)
|
|
1410
|
+
elif parts[:2] == ['api', 'tournaments']:
|
|
1411
|
+
self._tournament_post(parts[2:])
|
|
1412
|
+
elif parts[:2] == ['api', 'challenges']:
|
|
1413
|
+
self._json(*_challenges.post(parts[2:], self._document()))
|
|
1414
|
+
elif parts[:2] == ['api', 'help']:
|
|
1415
|
+
self._json(*_help.post(parts[2:], self._document()))
|
|
1416
|
+
elif parts[:2] == ['api', 'languages']:
|
|
1417
|
+
self._json(*_languages.post(parts[2:], self._body()))
|
|
1418
|
+
elif len(parts) == 4 and parts[1] == 'game' and parts[3] == 'input':
|
|
1419
|
+
self._json(games.input(parts[2], self._document()))
|
|
1420
|
+
elif len(parts) == 4 and parts[1] == 'game' and parts[3] == 'pause':
|
|
1421
|
+
paused = self._document().get('paused')
|
|
1422
|
+
if not isinstance(paused, bool):
|
|
1423
|
+
raise MessageError('server.game.paused', paused=repr(paused))
|
|
1424
|
+
self._json(games.send(parts[2], {'paused': paused}))
|
|
1425
|
+
else:
|
|
1426
|
+
self._refuse(404, 'server.no_resource')
|
|
1427
|
+
except (GameBusyError, _video_jobs.BusyError) as error:
|
|
1428
|
+
self._error(409, error)
|
|
1429
|
+
except NoGameError as error:
|
|
1430
|
+
self._error(404, error)
|
|
1431
|
+
except (ArgumentError, ValueError) as error:
|
|
1432
|
+
self._error(400, error)
|
|
1433
|
+
|
|
1434
|
+
def do_PUT(self) -> None:
|
|
1435
|
+
self._handle(self._put)
|
|
1436
|
+
|
|
1437
|
+
def _put(self) -> None:
|
|
1438
|
+
parts, query = self._route()
|
|
1439
|
+
try:
|
|
1440
|
+
if len(parts) == 4 and parts[1] == 'teams' and parts[3] == 'model':
|
|
1441
|
+
joints = _loads(query.get('joints') or '{}', 'joints')
|
|
1442
|
+
self._json(_teams.set_model(parts[2], self._body(), joints))
|
|
1443
|
+
elif len(parts) == 5 and parts[1] == 'teams' and parts[3] == 'images':
|
|
1444
|
+
self._json(_teams.set_image(parts[2], parts[4], self._body()))
|
|
1445
|
+
elif len(parts) == 5 and parts[1] == 'teams' and parts[3] == 'sounds':
|
|
1446
|
+
self._json(_teams.set_sound(parts[2], parts[4], self._body()))
|
|
1447
|
+
elif len(parts) == 5 and parts[1] == 'teams' and parts[3] == 'clips':
|
|
1448
|
+
joints = _loads(query['joints'], 'joints') if 'joints' in query else None
|
|
1449
|
+
self._json(_clips.set_clip(parts[2], parts[4], self._body(), joints))
|
|
1450
|
+
else:
|
|
1451
|
+
self._refuse(404, 'server.no_resource')
|
|
1452
|
+
except (ArgumentError, ValueError) as error:
|
|
1453
|
+
self._error(400, error)
|
|
1454
|
+
|
|
1455
|
+
def do_PATCH(self) -> None:
|
|
1456
|
+
self._handle(self._patch)
|
|
1457
|
+
|
|
1458
|
+
def _patch(self) -> None:
|
|
1459
|
+
parts, _ = self._route()
|
|
1460
|
+
try:
|
|
1461
|
+
if len(parts) == 3 and parts[1] == 'matches':
|
|
1462
|
+
document = self._document()
|
|
1463
|
+
self._json(
|
|
1464
|
+
_library.update(
|
|
1465
|
+
parts[2],
|
|
1466
|
+
document.get('title'),
|
|
1467
|
+
document.get('folder'),
|
|
1468
|
+
document.get('favorite'),
|
|
1469
|
+
document.get('tags'),
|
|
1470
|
+
document.get('notes'),
|
|
1471
|
+
)
|
|
1472
|
+
)
|
|
1473
|
+
elif len(parts) == 5 and parts[1] == 'teams' and parts[3] == 'clips':
|
|
1474
|
+
joints = self._document().get('joints')
|
|
1475
|
+
self._json(_clips.set_joints(parts[2], parts[4], joints))
|
|
1476
|
+
elif len(parts) == 3 and parts[1] == 'teams':
|
|
1477
|
+
document = self._document()
|
|
1478
|
+
self._json(
|
|
1479
|
+
_teams.update(
|
|
1480
|
+
parts[2],
|
|
1481
|
+
document.get('name'),
|
|
1482
|
+
document.get('style'),
|
|
1483
|
+
document.get('format'),
|
|
1484
|
+
document.get('control'),
|
|
1485
|
+
)
|
|
1486
|
+
)
|
|
1487
|
+
else:
|
|
1488
|
+
self._refuse(404, 'server.no_resource')
|
|
1489
|
+
except (ArgumentError, ValueError) as error:
|
|
1490
|
+
self._error(400, error)
|
|
1491
|
+
|
|
1492
|
+
def do_DELETE(self) -> None:
|
|
1493
|
+
self._handle(self._delete)
|
|
1494
|
+
|
|
1495
|
+
def _delete(self) -> None:
|
|
1496
|
+
parts, _ = self._route()
|
|
1497
|
+
if len(parts) == 3 and parts[1] == 'game':
|
|
1498
|
+
try:
|
|
1499
|
+
self._json(games.quit(parts[2]))
|
|
1500
|
+
except NoGameError:
|
|
1501
|
+
self._refuse(404, 'server.game.unknown')
|
|
1502
|
+
return
|
|
1503
|
+
if parts[:2] == ['api', 'challenges']:
|
|
1504
|
+
self._json(*_challenges.delete(parts[2:]))
|
|
1505
|
+
return
|
|
1506
|
+
if len(parts) == 3 and parts[1] == 'groups':
|
|
1507
|
+
# Deleting a group moves all its recordings to the Trash at once.
|
|
1508
|
+
trashed = _library.trash_group(parts[2])
|
|
1509
|
+
if trashed:
|
|
1510
|
+
self._json({'group': parts[2], 'trashed': trashed})
|
|
1511
|
+
else:
|
|
1512
|
+
self._refuse(404, 'server.library.group_unknown')
|
|
1513
|
+
return
|
|
1514
|
+
if parts[:2] == ['api', 'languages']:
|
|
1515
|
+
self._json(*_languages.delete(parts[2:]))
|
|
1516
|
+
return
|
|
1517
|
+
if len(parts) == 3 and parts[1] == 'requests':
|
|
1518
|
+
removed = requests.cancel(parts[2])
|
|
1519
|
+
elif len(parts) == 4 and parts[1:3] == ['tournaments', 'presets']:
|
|
1520
|
+
removed = _tournament_runner.remove_preset(parts[3])
|
|
1521
|
+
elif len(parts) == 3 and parts[1] == 'tournaments':
|
|
1522
|
+
try:
|
|
1523
|
+
removed = cups().remove(parts[2])
|
|
1524
|
+
except ArgumentError as error:
|
|
1525
|
+
self._error(409, error)
|
|
1526
|
+
return
|
|
1527
|
+
elif len(parts) == 3 and parts[1] == 'videos':
|
|
1528
|
+
removed = videos.cancel(parts[2])
|
|
1529
|
+
elif len(parts) == 4 and parts[1] == 'teams' and parts[3] == 'model':
|
|
1530
|
+
try:
|
|
1531
|
+
removed = _teams.remove_model(parts[2])
|
|
1532
|
+
except ArgumentError:
|
|
1533
|
+
removed = False
|
|
1534
|
+
elif len(parts) == 5 and parts[1] == 'teams' and parts[3] == 'images':
|
|
1535
|
+
removed = _teams.remove_image(parts[2], parts[4])
|
|
1536
|
+
elif len(parts) == 5 and parts[1] == 'teams' and parts[3] == 'sounds':
|
|
1537
|
+
removed = _teams.remove_sound(parts[2], parts[4])
|
|
1538
|
+
elif len(parts) == 5 and parts[1] == 'teams' and parts[3] == 'clips':
|
|
1539
|
+
removed = _clips.remove_clip(parts[2], parts[4])
|
|
1540
|
+
elif len(parts) == 3 and parts[1] == 'matches':
|
|
1541
|
+
# A deleted recording goes to the Trash, and only the Trash deletes it for good.
|
|
1542
|
+
removed = _library.trash(parts[2])
|
|
1543
|
+
elif len(parts) == 3 and parts[1] == 'trash':
|
|
1544
|
+
removed = _library.purge(parts[2])
|
|
1545
|
+
elif len(parts) == 3 and parts[1] == 'teams':
|
|
1546
|
+
removed = _teams.remove(parts[2])
|
|
1547
|
+
else:
|
|
1548
|
+
self._refuse(404, 'server.no_resource')
|
|
1549
|
+
return
|
|
1550
|
+
if removed:
|
|
1551
|
+
self.send_response(204)
|
|
1552
|
+
self.end_headers()
|
|
1553
|
+
else:
|
|
1554
|
+
self._refuse(404, 'server.no_item')
|
|
1555
|
+
|
|
1556
|
+
def _tournament_get(self, rest: list[str]) -> None:
|
|
1557
|
+
"""Answers the reads of tournaments, their list, presets, ratings and one in full."""
|
|
1558
|
+
if not rest:
|
|
1559
|
+
self._json(cups().entries())
|
|
1560
|
+
elif rest == ['presets']:
|
|
1561
|
+
self._json(_tournament_runner.presets())
|
|
1562
|
+
elif rest == ['ratings']:
|
|
1563
|
+
self._json(_tournament_runner.ratings())
|
|
1564
|
+
elif len(rest) == 1:
|
|
1565
|
+
entry = cups().get(rest[0])
|
|
1566
|
+
if entry is None:
|
|
1567
|
+
self._refuse(404, 'server.tournament.unknown')
|
|
1568
|
+
else:
|
|
1569
|
+
self._json(entry)
|
|
1570
|
+
elif len(rest) == 2 and rest[1] == 'analysis':
|
|
1571
|
+
# The ratings with their intervals, the matrix of goal differences, the standings
|
|
1572
|
+
# and the matches, which the page shows and exports.
|
|
1573
|
+
found = cups().analysis(rest[0])
|
|
1574
|
+
if found is None:
|
|
1575
|
+
self._refuse(404, 'server.tournament.unknown')
|
|
1576
|
+
else:
|
|
1577
|
+
self._json(found)
|
|
1578
|
+
elif len(rest) == 3 and rest[1] == 'files':
|
|
1579
|
+
self._tournament_file(rest[0], rest[2])
|
|
1580
|
+
else:
|
|
1581
|
+
self._refuse(404, 'server.no_resource')
|
|
1582
|
+
|
|
1583
|
+
def _tournament_file(self, identifier: str, name: str) -> None:
|
|
1584
|
+
"""Sends one file of a tournament's results, such as `standings.csv`, to save."""
|
|
1585
|
+
from .._tournaments import results as _results
|
|
1586
|
+
|
|
1587
|
+
if name not in _results.FILES:
|
|
1588
|
+
self._refuse(404, 'server.no_resource')
|
|
1589
|
+
return
|
|
1590
|
+
files = cups().files(identifier)
|
|
1591
|
+
if files is None:
|
|
1592
|
+
self._refuse(404, 'server.tournament.unknown')
|
|
1593
|
+
return
|
|
1594
|
+
body = files[name].encode()
|
|
1595
|
+
kind = {
|
|
1596
|
+
'.csv': 'text/csv',
|
|
1597
|
+
'.jsonl': 'application/x-ndjson',
|
|
1598
|
+
'.json': 'application/json',
|
|
1599
|
+
}[name[name.rindex('.') :]]
|
|
1600
|
+
self.send_response(200)
|
|
1601
|
+
self.send_header('Content-Type', f'{kind}; charset=utf-8')
|
|
1602
|
+
self.send_header('Content-Disposition', f'attachment; filename="{identifier}-{name}"')
|
|
1603
|
+
self.send_header('Content-Length', str(len(body)))
|
|
1604
|
+
self.send_header('Cache-Control', 'no-store')
|
|
1605
|
+
self.end_headers()
|
|
1606
|
+
self.wfile.write(body)
|
|
1607
|
+
|
|
1608
|
+
def _tournament_post(self, rest: list[str]) -> None:
|
|
1609
|
+
"""Creates, checks and changes tournaments, and saves presets."""
|
|
1610
|
+
document = self._document()
|
|
1611
|
+
if not rest:
|
|
1612
|
+
self._json(cups().create(document.get('config', document)), 201)
|
|
1613
|
+
elif rest == ['check']:
|
|
1614
|
+
self._json(_tournament_runner.preview(document.get('config', document)))
|
|
1615
|
+
elif rest == ['preflight']:
|
|
1616
|
+
# The pre-flight of a tournament still to start, which Review shows.
|
|
1617
|
+
self._json(_tournament_runner.preflight_config(document.get('config', document)))
|
|
1618
|
+
elif len(rest) == 2 and rest[0] == 'presets':
|
|
1619
|
+
self._json(_tournament_runner.save_preset(rest[1], document.get('preset')), 201)
|
|
1620
|
+
elif len(rest) == 2 and rest[1] == 'spoilers':
|
|
1621
|
+
# The tournament as a person sees it who has watched only some of its matches.
|
|
1622
|
+
entry = cups().without_spoilers(rest[0], document.get('watched'))
|
|
1623
|
+
if entry is None:
|
|
1624
|
+
self._refuse(404, 'server.tournament.unknown')
|
|
1625
|
+
else:
|
|
1626
|
+
self._json(entry)
|
|
1627
|
+
elif len(rest) == 2 and rest[1] in ('cancel', 'resume', 'play', 'forfeit', 'legs'):
|
|
1628
|
+
identifier, action = rest
|
|
1629
|
+
try:
|
|
1630
|
+
if action == 'legs':
|
|
1631
|
+
self._json(cups().add_legs(identifier, document.get('legs')))
|
|
1632
|
+
elif action == 'cancel':
|
|
1633
|
+
if not cups().cancel(identifier):
|
|
1634
|
+
raise KeyError(identifier)
|
|
1635
|
+
self._json(cups().get(identifier))
|
|
1636
|
+
elif action == 'resume':
|
|
1637
|
+
self._json(cups().resume(identifier))
|
|
1638
|
+
elif action == 'play':
|
|
1639
|
+
self._json(cups().play(identifier, str(document.get('key'))), 201)
|
|
1640
|
+
else:
|
|
1641
|
+
winner = document.get('winner')
|
|
1642
|
+
self._json(cups().forfeit(identifier, str(document.get('key')), winner))
|
|
1643
|
+
except KeyError:
|
|
1644
|
+
self._refuse(404, 'server.tournament.unknown')
|
|
1645
|
+
else:
|
|
1646
|
+
self._refuse(404, 'server.no_resource')
|
|
1647
|
+
|
|
1648
|
+
def _resolve_feed(self, source: str) -> dict[str, Any]:
|
|
1649
|
+
"""Returns what the source of a feed names now, from this server's own lists."""
|
|
1650
|
+
|
|
1651
|
+
def recording(identifier: str) -> dict[str, Any] | None:
|
|
1652
|
+
try:
|
|
1653
|
+
return _library.details(identifier)
|
|
1654
|
+
except ArgumentError:
|
|
1655
|
+
return None
|
|
1656
|
+
|
|
1657
|
+
return _feed.resolve(
|
|
1658
|
+
source,
|
|
1659
|
+
live=_sources,
|
|
1660
|
+
recordings=_library.matches,
|
|
1661
|
+
recording=recording,
|
|
1662
|
+
requests=requests.entries,
|
|
1663
|
+
tournaments=lambda: cups().entries(),
|
|
1664
|
+
tournament=lambda identifier: cups().get(identifier),
|
|
1665
|
+
)
|
|
1666
|
+
|
|
1667
|
+
def _static(self, parts: list[str]) -> None:
|
|
1668
|
+
relative = Path(*parts) if parts else Path('index.html')
|
|
1669
|
+
path = (_WEB / relative).resolve()
|
|
1670
|
+
if _WEB.resolve() not in path.parents or not path.is_file():
|
|
1671
|
+
self._refuse(404, 'server.no_file')
|
|
1672
|
+
return
|
|
1673
|
+
data = path.read_bytes()
|
|
1674
|
+
kind = _TYPES.get(path.suffix) or mimetypes.guess_type(path.name)[0]
|
|
1675
|
+
if relative == Path('manifest.webmanifest'):
|
|
1676
|
+
data = _pwa.manifest(data, self._route()[1].get('lang'))
|
|
1677
|
+
elif relative == Path('sw.js'):
|
|
1678
|
+
data = _pwa.worker(data)
|
|
1679
|
+
page = relative == Path('index.html')
|
|
1680
|
+
if page or relative == Path('feed.html'):
|
|
1681
|
+
data = _languages.inline(data)
|
|
1682
|
+
key = getattr(self.server, 'frame_key', None)
|
|
1683
|
+
self._framing = _headers.framing(relative.as_posix(), self._route()[1], key)
|
|
1684
|
+
self.send_response(200)
|
|
1685
|
+
self.send_header('Content-Type', kind or 'application/octet-stream')
|
|
1686
|
+
self.send_header('Content-Length', str(len(data)))
|
|
1687
|
+
# The service worker of the installable page is checked anew on every registration.
|
|
1688
|
+
if relative == Path('sw.js'):
|
|
1689
|
+
self.send_header('Cache-Control', 'no-cache')
|
|
1690
|
+
self.end_headers()
|
|
1691
|
+
self._framing = _headers.DENY
|
|
1692
|
+
self.wfile.write(data)
|
|
1693
|
+
reached = getattr(self.server, 'on_page', None)
|
|
1694
|
+
if page and reached is not None:
|
|
1695
|
+
reached()
|
|
1696
|
+
|
|
1697
|
+
def _sandbox(self) -> None:
|
|
1698
|
+
data, policy = _headers.sandbox_page(_WEB)
|
|
1699
|
+
self._framing = _headers.OWN
|
|
1700
|
+
self.send_response(200)
|
|
1701
|
+
self.send_header('Content-Type', 'text/html; charset=utf-8')
|
|
1702
|
+
self.send_header('Content-Length', str(len(data)))
|
|
1703
|
+
self.send_header('Content-Security-Policy', policy)
|
|
1704
|
+
self.send_header('Cache-Control', 'no-store')
|
|
1705
|
+
self.end_headers()
|
|
1706
|
+
self._framing = _headers.DENY
|
|
1707
|
+
self.wfile.write(data)
|
|
1708
|
+
|
|
1709
|
+
def _package_file(self, identifier: str, name: str) -> None:
|
|
1710
|
+
path = _presentation.file_path(identifier, name)
|
|
1711
|
+
if path is None:
|
|
1712
|
+
self._refuse(404, 'server.no_package_file')
|
|
1713
|
+
return
|
|
1714
|
+
data = path.read_bytes()
|
|
1715
|
+
self.send_response(200)
|
|
1716
|
+
self.send_header('Content-Type', _presentation.content_type(identifier, name))
|
|
1717
|
+
self.send_header('Content-Length', str(len(data)))
|
|
1718
|
+
self.send_header('Cache-Control', 'no-store')
|
|
1719
|
+
self.end_headers()
|
|
1720
|
+
self.wfile.write(data)
|
|
1721
|
+
|
|
1722
|
+
def _model(self, identifier: str) -> None:
|
|
1723
|
+
path = _teams.model_path(identifier)
|
|
1724
|
+
if path is None:
|
|
1725
|
+
self._refuse(404, 'server.no_model')
|
|
1726
|
+
return
|
|
1727
|
+
data = path.read_bytes()
|
|
1728
|
+
self.send_response(200)
|
|
1729
|
+
self.send_header('Content-Type', 'model/gltf-binary')
|
|
1730
|
+
self.send_header('Content-Length', str(len(data)))
|
|
1731
|
+
self.send_header('Cache-Control', 'no-store')
|
|
1732
|
+
self.end_headers()
|
|
1733
|
+
self.wfile.write(data)
|
|
1734
|
+
|
|
1735
|
+
def _clip(self, identifier: str, name: str) -> None:
|
|
1736
|
+
path = _clips.clip_path(identifier, name)
|
|
1737
|
+
if path is None:
|
|
1738
|
+
self._refuse(404, 'server.no_clip')
|
|
1739
|
+
return
|
|
1740
|
+
data = path.read_bytes()
|
|
1741
|
+
self.send_response(200)
|
|
1742
|
+
self.send_header('Content-Type', 'model/gltf-binary')
|
|
1743
|
+
self.send_header('Content-Length', str(len(data)))
|
|
1744
|
+
self.send_header('Cache-Control', 'no-store')
|
|
1745
|
+
self.end_headers()
|
|
1746
|
+
self.wfile.write(data)
|
|
1747
|
+
|
|
1748
|
+
def _export(self, identifier: str) -> None:
|
|
1749
|
+
try:
|
|
1750
|
+
filename, data = _teams.export(identifier)
|
|
1751
|
+
except ArgumentError as error:
|
|
1752
|
+
self._error(404, error)
|
|
1753
|
+
return
|
|
1754
|
+
self.send_response(200)
|
|
1755
|
+
self.send_header('Content-Type', 'application/zip')
|
|
1756
|
+
# A header carries Latin-1 alone, so the name travels encoded with an ASCII fallback.
|
|
1757
|
+
fallback = filename.encode('ascii', 'replace').decode().replace('?', '-')
|
|
1758
|
+
quoted = urllib.parse.quote(filename)
|
|
1759
|
+
self.send_header(
|
|
1760
|
+
'Content-Disposition',
|
|
1761
|
+
f'attachment; filename="{fallback}"; filename*=UTF-8\'\'{quoted}',
|
|
1762
|
+
)
|
|
1763
|
+
self.send_header('Content-Length', str(len(data)))
|
|
1764
|
+
self.end_headers()
|
|
1765
|
+
self.wfile.write(data)
|
|
1766
|
+
|
|
1767
|
+
def _image(self, identifier: str, slot: str) -> None:
|
|
1768
|
+
path = _teams.image_path(identifier, slot)
|
|
1769
|
+
if path is None:
|
|
1770
|
+
self._refuse(404, 'server.no_image')
|
|
1771
|
+
return
|
|
1772
|
+
data = path.read_bytes()
|
|
1773
|
+
kind = {'.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp'}
|
|
1774
|
+
self.send_response(200)
|
|
1775
|
+
self.send_header('Content-Type', kind.get(path.suffix, 'application/json'))
|
|
1776
|
+
self.send_header('Content-Length', str(len(data)))
|
|
1777
|
+
self.send_header('Cache-Control', 'no-store')
|
|
1778
|
+
self.end_headers()
|
|
1779
|
+
self.wfile.write(data)
|
|
1780
|
+
|
|
1781
|
+
def _sound(self, identifier: str, slot: str) -> None:
|
|
1782
|
+
path = _teams.sound_path(identifier, slot)
|
|
1783
|
+
if path is None:
|
|
1784
|
+
self._refuse(404, 'server.no_sound')
|
|
1785
|
+
return
|
|
1786
|
+
data = path.read_bytes()
|
|
1787
|
+
kind = {'.ogg': 'audio/ogg', '.mp3': 'audio/mpeg', '.wav': 'audio/wav'}
|
|
1788
|
+
self.send_response(200)
|
|
1789
|
+
self.send_header('Content-Type', kind[path.suffix])
|
|
1790
|
+
self.send_header('Content-Length', str(len(data)))
|
|
1791
|
+
self.send_header('Cache-Control', 'no-store')
|
|
1792
|
+
self.end_headers()
|
|
1793
|
+
self.wfile.write(data)
|
|
1794
|
+
|
|
1795
|
+
def _video(self, found: tuple[Path, str] | None) -> None:
|
|
1796
|
+
"""Sends a finished video export as a download, under the name it suggests."""
|
|
1797
|
+
if found is None:
|
|
1798
|
+
self._refuse(404, 'server.video.unknown')
|
|
1799
|
+
return
|
|
1800
|
+
path, filename = found
|
|
1801
|
+
size = path.stat().st_size
|
|
1802
|
+
self.send_response(200)
|
|
1803
|
+
kind = 'video/webm' if path.suffix == '.webm' else 'video/mp4'
|
|
1804
|
+
self.send_header('Content-Type', kind)
|
|
1805
|
+
self.send_header('Content-Disposition', f'attachment; filename="{filename}"')
|
|
1806
|
+
self.send_header('Content-Length', str(size))
|
|
1807
|
+
self.send_header('Cache-Control', 'no-store')
|
|
1808
|
+
self.end_headers()
|
|
1809
|
+
with path.open('rb') as stream:
|
|
1810
|
+
while chunk := stream.read(1 << 20):
|
|
1811
|
+
self.wfile.write(chunk)
|
|
1812
|
+
|
|
1813
|
+
def _bench_csv(self, identifier: str) -> None:
|
|
1814
|
+
"""Sends the table of a benchmark as CSV."""
|
|
1815
|
+
from .._playing import bench as _bench
|
|
1816
|
+
|
|
1817
|
+
text = _bench.csv_of(identifier)
|
|
1818
|
+
if text is None:
|
|
1819
|
+
self._refuse(404, 'server.bench.no_bench')
|
|
1820
|
+
return
|
|
1821
|
+
body = text.encode()
|
|
1822
|
+
self.send_response(200)
|
|
1823
|
+
self.send_header('Content-Type', 'text/csv; charset=utf-8')
|
|
1824
|
+
self.send_header('Content-Disposition', f'attachment; filename="{identifier}.csv"')
|
|
1825
|
+
self.send_header('Content-Length', str(len(body)))
|
|
1826
|
+
self.send_header('Cache-Control', 'no-store')
|
|
1827
|
+
self.end_headers()
|
|
1828
|
+
self.wfile.write(body)
|
|
1829
|
+
|
|
1830
|
+
def _moments(self, identifier: str, vtt: bool) -> None:
|
|
1831
|
+
"""Sends the moments of a recording of the library, or its captions as WebVTT."""
|
|
1832
|
+
if _library.path_of(identifier) is None:
|
|
1833
|
+
self._refuse(404, 'server.no_match')
|
|
1834
|
+
return
|
|
1835
|
+
if not vtt:
|
|
1836
|
+
self._json(_search.moments_of(identifier))
|
|
1837
|
+
return
|
|
1838
|
+
body = _search.captions_vtt(identifier).encode()
|
|
1839
|
+
self.send_response(200)
|
|
1840
|
+
self.send_header('Content-Type', 'text/vtt; charset=utf-8')
|
|
1841
|
+
self.send_header('Content-Disposition', f'attachment; filename="{identifier}.vtt"')
|
|
1842
|
+
self.send_header('Content-Length', str(len(body)))
|
|
1843
|
+
self.send_header('Cache-Control', 'no-store')
|
|
1844
|
+
self.end_headers()
|
|
1845
|
+
self.wfile.write(body)
|
|
1846
|
+
|
|
1847
|
+
def _recording(self, identifier: str) -> None:
|
|
1848
|
+
path = _library.path_of(identifier)
|
|
1849
|
+
if path is None:
|
|
1850
|
+
self._refuse(404, 'server.no_match')
|
|
1851
|
+
return
|
|
1852
|
+
size = path.stat().st_size
|
|
1853
|
+
self.send_response(200)
|
|
1854
|
+
self.send_header('Content-Type', 'application/octet-stream')
|
|
1855
|
+
self.send_header('Content-Length', str(size))
|
|
1856
|
+
self.end_headers()
|
|
1857
|
+
with path.open('rb') as stream:
|
|
1858
|
+
while chunk := stream.read(1 << 20):
|
|
1859
|
+
self.wfile.write(chunk)
|
|
1860
|
+
|
|
1861
|
+
def _select_environment(self, identifier: str) -> None:
|
|
1862
|
+
"""Passes a viewer's choice of environment on to the live source `identifier`."""
|
|
1863
|
+
source = next((entry for entry in _sources() if entry['id'] == identifier), None)
|
|
1864
|
+
if source is None:
|
|
1865
|
+
self._refuse(404, 'server.live.unknown')
|
|
1866
|
+
return
|
|
1867
|
+
environment = self._document().get('environment')
|
|
1868
|
+
count = source.get('environment_count', 1)
|
|
1869
|
+
if (
|
|
1870
|
+
isinstance(environment, bool)
|
|
1871
|
+
or not isinstance(environment, int)
|
|
1872
|
+
or not 0 <= environment < count
|
|
1873
|
+
):
|
|
1874
|
+
raise MessageError(
|
|
1875
|
+
'server.live.environment', last=count - 1, environment=repr(environment)
|
|
1876
|
+
)
|
|
1877
|
+
connection = http.client.HTTPConnection('127.0.0.1', int(source['port']), timeout=10)
|
|
1878
|
+
try:
|
|
1879
|
+
connection.request(
|
|
1880
|
+
'POST',
|
|
1881
|
+
'/environment',
|
|
1882
|
+
json.dumps({'environment': environment}),
|
|
1883
|
+
{'Content-Type': 'application/json'},
|
|
1884
|
+
)
|
|
1885
|
+
response = connection.getresponse()
|
|
1886
|
+
response.read()
|
|
1887
|
+
except OSError as error:
|
|
1888
|
+
self._refuse(502, 'server.live.silent', error=error)
|
|
1889
|
+
return
|
|
1890
|
+
finally:
|
|
1891
|
+
connection.close()
|
|
1892
|
+
if response.status != 202:
|
|
1893
|
+
self._refuse(502, 'server.live.answered', status=response.status)
|
|
1894
|
+
return
|
|
1895
|
+
self._json({'environment': environment, 'generation': source.get('generation', 0)}, 202)
|
|
1896
|
+
|
|
1897
|
+
def _live_grid(self, identifier: str) -> None:
|
|
1898
|
+
"""Relays a viewer's request for the grid of the live source `identifier`.
|
|
1899
|
+
|
|
1900
|
+
Each request makes the source read states for up to 15 seconds, so a page of another
|
|
1901
|
+
origin is refused here as for requests that change data.
|
|
1902
|
+
"""
|
|
1903
|
+
origin = self.headers.get('Origin')
|
|
1904
|
+
if origin is not None and origin != f'http://{self.headers.get("Host")}':
|
|
1905
|
+
self._refuse(403, 'server.origin')
|
|
1906
|
+
return
|
|
1907
|
+
source = next((entry for entry in _sources() if entry['id'] == identifier), None)
|
|
1908
|
+
if source is None:
|
|
1909
|
+
self._refuse(404, 'server.live.unknown')
|
|
1910
|
+
return
|
|
1911
|
+
query = self._route()[1]
|
|
1912
|
+
count = source.get('environment_count', 1)
|
|
1913
|
+
values = []
|
|
1914
|
+
for name in ('first', 'count'):
|
|
1915
|
+
text = query.get(name, '')
|
|
1916
|
+
if not text.isdigit() or len(text) > 9:
|
|
1917
|
+
raise MessageError('server.live.whole_number', name=name, text=repr(text))
|
|
1918
|
+
values.append(int(text))
|
|
1919
|
+
first, size = values
|
|
1920
|
+
if not 0 <= first < count or not 1 <= size <= _grid.MAXIMUM:
|
|
1921
|
+
raise MessageError(
|
|
1922
|
+
'server.live.grid_range',
|
|
1923
|
+
last=count - 1,
|
|
1924
|
+
most=_grid.MAXIMUM,
|
|
1925
|
+
first=first,
|
|
1926
|
+
count=size,
|
|
1927
|
+
)
|
|
1928
|
+
connection = http.client.HTTPConnection('127.0.0.1', int(source['port']), timeout=10)
|
|
1929
|
+
try:
|
|
1930
|
+
connection.request('GET', f'/grid?first={first}&count={size}')
|
|
1931
|
+
response = connection.getresponse()
|
|
1932
|
+
body = response.read()
|
|
1933
|
+
except OSError as error:
|
|
1934
|
+
self._refuse(502, 'server.live.silent', error=error)
|
|
1935
|
+
return
|
|
1936
|
+
finally:
|
|
1937
|
+
connection.close()
|
|
1938
|
+
if response.status == 404:
|
|
1939
|
+
# A source of 0.2.0 has no grid.
|
|
1940
|
+
self._refuse(404, 'server.live.no_grid')
|
|
1941
|
+
return
|
|
1942
|
+
if response.status != 200:
|
|
1943
|
+
self._refuse(502, 'server.live.answered', status=response.status)
|
|
1944
|
+
return
|
|
1945
|
+
self.send_response(200)
|
|
1946
|
+
self.send_header('Content-Type', 'application/json')
|
|
1947
|
+
self.send_header('Content-Length', str(len(body)))
|
|
1948
|
+
self.send_header('Cache-Control', 'no-store')
|
|
1949
|
+
self.end_headers()
|
|
1950
|
+
self.wfile.write(body)
|
|
1951
|
+
|
|
1952
|
+
def _relay(self, identifier: str) -> None:
|
|
1953
|
+
source = next((entry for entry in _sources() if entry['id'] == identifier), None)
|
|
1954
|
+
if source is None:
|
|
1955
|
+
self._refuse(404, 'server.live.unknown')
|
|
1956
|
+
return
|
|
1957
|
+
self._pipe(int(source['port']), 'live')
|
|
1958
|
+
|
|
1959
|
+
def _pipe(self, port: int, kind: str) -> None:
|
|
1960
|
+
"""Relays the stream of a live source or a game, which listens on `port`.
|
|
1961
|
+
|
|
1962
|
+
The kind, `live` or `game`, names the messages of its errors.
|
|
1963
|
+
"""
|
|
1964
|
+
connection = http.client.HTTPConnection('127.0.0.1', port, timeout=10)
|
|
1965
|
+
try:
|
|
1966
|
+
connection.connect()
|
|
1967
|
+
# A batch pauses between steps for as long as training needs, so once connected
|
|
1968
|
+
# the relay waits on the stream without a timeout.
|
|
1969
|
+
connection.sock.settimeout(None)
|
|
1970
|
+
# A page that reconnects asks for numbered frames, and the relay passes that on,
|
|
1971
|
+
# with the annotations that a page which shows them asks for.
|
|
1972
|
+
query = self._route()[1]
|
|
1973
|
+
sequence = query.get('sequence') == '1'
|
|
1974
|
+
path = '/stream?sequence=1' if sequence else '/stream'
|
|
1975
|
+
if sequence and query.get('annotations') == '1':
|
|
1976
|
+
path += '&annotations=1'
|
|
1977
|
+
connection.request('GET', path)
|
|
1978
|
+
response = connection.getresponse()
|
|
1979
|
+
except OSError as error:
|
|
1980
|
+
connection.close()
|
|
1981
|
+
self._refuse(502, f'server.{kind}.silent', error=error)
|
|
1982
|
+
return
|
|
1983
|
+
if response.status != 200:
|
|
1984
|
+
connection.close()
|
|
1985
|
+
self._refuse(502, f'server.{kind}.answered', status=response.status)
|
|
1986
|
+
return
|
|
1987
|
+
self.send_response(200)
|
|
1988
|
+
self.send_header('Content-Type', 'application/octet-stream')
|
|
1989
|
+
self.send_header('Cache-Control', 'no-store')
|
|
1990
|
+
self.end_headers()
|
|
1991
|
+
try:
|
|
1992
|
+
while chunk := response.read1(1 << 16):
|
|
1993
|
+
self.wfile.write(chunk)
|
|
1994
|
+
self.wfile.flush()
|
|
1995
|
+
except OSError:
|
|
1996
|
+
pass
|
|
1997
|
+
finally:
|
|
1998
|
+
connection.close()
|
|
1999
|
+
|
|
2000
|
+
return Handler
|
|
2001
|
+
|
|
2002
|
+
|
|
2003
|
+
def _warm_index() -> None:
|
|
2004
|
+
"""Brings the index of moments up to date, so the first search finds it ready."""
|
|
2005
|
+
try:
|
|
2006
|
+
_search.sync()
|
|
2007
|
+
except Exception as error:
|
|
2008
|
+
_LOGGER.warning('cuju render could not index the moments of the library: %s', error)
|
|
2009
|
+
|
|
2010
|
+
|
|
2011
|
+
def serve(
|
|
2012
|
+
port: int = 8780,
|
|
2013
|
+
open_browser: bool = False,
|
|
2014
|
+
*,
|
|
2015
|
+
page: str = '',
|
|
2016
|
+
remote: bool = False,
|
|
2017
|
+
parent: int | None = None,
|
|
2018
|
+
colab: bool = False,
|
|
2019
|
+
) -> None:
|
|
2020
|
+
"""Serves the renderer's page and API on the loopback interface until interrupted.
|
|
2021
|
+
|
|
2022
|
+
The API deletes files and plays submitted code, so it listens on the loopback interface alone,
|
|
2023
|
+
and another machine reaches it through a tunnel, such as the port forwarding of SSH. While it
|
|
2024
|
+
runs, the file `server.json` of the home folder names it, so that `show` and
|
|
2025
|
+
`cuju render open` find it.
|
|
2026
|
+
|
|
2027
|
+
Args:
|
|
2028
|
+
port: The port, and 0 picks a free one.
|
|
2029
|
+
open_browser: Whether to open the page in the default browser.
|
|
2030
|
+
page: The end of the address to open, from `#` on, such as `#match=sample-5v5`.
|
|
2031
|
+
remote: Whether to print the SSH command that reaches the page from another machine, and
|
|
2032
|
+
a line when a browser first reaches the page.
|
|
2033
|
+
parent: A process whose end stops the server, as `show` asks for.
|
|
2034
|
+
colab: Whether the server also answers through the port proxy of Google Colab, as `show`
|
|
2035
|
+
asks for inside Colab.
|
|
2036
|
+
|
|
2037
|
+
Raises:
|
|
2038
|
+
Error: If the port is in use, with what to do.
|
|
2039
|
+
"""
|
|
2040
|
+
# The diagnostic report of Help shows the server's recent warnings and errors.
|
|
2041
|
+
_doctor.install_capture()
|
|
2042
|
+
# The players of each scenario load in the background, so the page finds them at once.
|
|
2043
|
+
threading.Thread(target=_scenario_sides, daemon=True).start()
|
|
2044
|
+
games = _Games(warm=True)
|
|
2045
|
+
# The tournaments resume as the server starts, each match where it stopped.
|
|
2046
|
+
tournaments = _tournament_runner.Tournaments(games)
|
|
2047
|
+
try:
|
|
2048
|
+
server = _launch.LoopbackServer(
|
|
2049
|
+
('127.0.0.1', port), make_handler(_Requests(), games, tournaments)
|
|
2050
|
+
)
|
|
2051
|
+
except OSError as error:
|
|
2052
|
+
tournaments.close()
|
|
2053
|
+
raise _launch.port_error(port, error, remote) from None
|
|
2054
|
+
server.frame_key = secrets.token_urlsafe(18)
|
|
2055
|
+
server.proxy_domains = _launch.COLAB_DOMAINS if colab else ()
|
|
2056
|
+
# The library receives each shipped sample match once, and keeps a deleted one deleted.
|
|
2057
|
+
try:
|
|
2058
|
+
_library.add_samples(again=False)
|
|
2059
|
+
except OSError as error:
|
|
2060
|
+
print(f'cuju render could not add the sample matches: {error}', flush=True)
|
|
2061
|
+
# The index of the moments of the library catches up while the page loads.
|
|
2062
|
+
threading.Thread(target=_warm_index, daemon=True).start()
|
|
2063
|
+
# The scenario builder loads meanwhile too, so the first review of a tournament is quick.
|
|
2064
|
+
threading.Thread(target=_tournament_runner.warm, daemon=True).start()
|
|
2065
|
+
port = server.server_address[1]
|
|
2066
|
+
address = f'http://127.0.0.1:{port}/'
|
|
2067
|
+
print(f'cuju render serves {address} from {_home.home()}', flush=True)
|
|
2068
|
+
announcement = _launch.announce(port, server.frame_key)
|
|
2069
|
+
if remote:
|
|
2070
|
+
print(_launch.remote_note(port), flush=True)
|
|
2071
|
+
print('Waiting for a browser to reach the page.', flush=True)
|
|
2072
|
+
|
|
2073
|
+
def reached() -> None:
|
|
2074
|
+
server.on_page = None
|
|
2075
|
+
print(f'A browser reached the page at {time.strftime("%H:%M:%S")}.', flush=True)
|
|
2076
|
+
|
|
2077
|
+
server.on_page = reached
|
|
2078
|
+
if parent is not None:
|
|
2079
|
+
|
|
2080
|
+
def watch_parent() -> None:
|
|
2081
|
+
while _alive(parent):
|
|
2082
|
+
time.sleep(1)
|
|
2083
|
+
server.shutdown()
|
|
2084
|
+
|
|
2085
|
+
threading.Thread(target=watch_parent, daemon=True).start()
|
|
2086
|
+
if threading.current_thread() is threading.main_thread():
|
|
2087
|
+
# A server that `show` started ends with a terminate signal when its parent ends, and it
|
|
2088
|
+
# still removes its file of the home folder on the way out.
|
|
2089
|
+
signal.signal(signal.SIGTERM, _interrupt)
|
|
2090
|
+
if open_browser:
|
|
2091
|
+
|
|
2092
|
+
def opening() -> None:
|
|
2093
|
+
if not _launch.open_browser(address + page):
|
|
2094
|
+
print(f'Open {address + page} in a browser.', flush=True)
|
|
2095
|
+
|
|
2096
|
+
threading.Timer(0.5, opening).start()
|
|
2097
|
+
try:
|
|
2098
|
+
server.serve_forever()
|
|
2099
|
+
except KeyboardInterrupt:
|
|
2100
|
+
pass
|
|
2101
|
+
finally:
|
|
2102
|
+
tournaments.close()
|
|
2103
|
+
games.close()
|
|
2104
|
+
_launch.withdraw(announcement)
|
|
2105
|
+
server.server_close()
|