Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
49fee1ca19 | ||
|
|
c91d57633f | ||
|
|
22ce40a488 | ||
|
|
07276ce020 | ||
|
|
4c8e40769a | ||
|
|
211ba65e5e | ||
|
|
fe4749ec7f | ||
|
|
51af830160 | ||
|
|
d9d7881747 | ||
|
|
1c915067aa | ||
|
|
0924309abf | ||
|
|
cf41a13528 | ||
|
|
9bbc594048 | ||
|
|
741b258ac1 | ||
|
|
a87ee98faa | ||
|
|
25b19f2d6a | ||
|
|
8970f2694b | ||
|
|
72a3b9adac | ||
|
|
bf9fc193b3 | ||
|
|
4d00b7455e | ||
|
|
629be0d9ed | ||
|
|
130c934b9b | ||
|
|
9f2586b7ff | ||
|
|
51c1c5ab78 | ||
|
|
f4ca02c3cf | ||
|
|
eac45746ce | ||
|
|
a52133b313 | ||
|
|
a1b270fd4e | ||
|
|
7e98ebd1db | ||
|
|
0b0c67acb7 | ||
|
|
622df58295 | ||
|
|
df6f6ef893 | ||
|
|
ea607c1a52 | ||
|
|
e537f9d5f8 | ||
|
|
cf59251449 | ||
|
|
ef562342e2 | ||
|
|
3d81342725 | ||
|
|
b949951ef9 | ||
|
|
fd8064611a | ||
|
|
959eed38a4 | ||
|
|
bcc6d4bac8 | ||
|
|
4526fe86d9 | ||
|
|
8e82a1f7be | ||
|
|
4d74cee67d | ||
|
|
d4952db497 | ||
|
|
50b2b000a4 | ||
|
|
197fe113a1 | ||
|
|
7487b4deb1 | ||
|
|
4ab37c55cf | ||
|
|
572104f49e | ||
|
|
a407d3cbb0 | ||
|
|
1ec4fc8b13 | ||
|
|
9572e8457d | ||
|
|
d8585fb78e | ||
|
|
e52a7633a0 | ||
|
|
c3fe8b682d | ||
|
|
1508d2f804 | ||
|
|
86eb30f498 | ||
|
|
ddd7a21195 | ||
|
|
4275abe470 | ||
|
|
cf2805d3bd | ||
|
|
52f1c481a6 | ||
|
|
771b961b32 | ||
|
|
6b10cae4e6 | ||
|
|
95cd668cfb | ||
|
|
2a7b553597 | ||
|
|
27b4ec2c96 | ||
|
|
ab133dd82f | ||
|
|
1b0a3db439 |
No files matched your search
+15
-3
@@ -35,14 +35,18 @@ jobs:
|
|||||||
- run: dart test
|
- run: dart test
|
||||||
working-directory: packages/server
|
working-directory: packages/server
|
||||||
# Compiling the dedicated server proves it stays Flutter-free.
|
# Compiling the dedicated server proves it stays Flutter-free.
|
||||||
- run: mkdir -p build && dart compile exe bin/server.dart -o build/watch-together-server
|
- run: mkdir -p build && dart compile exe bin/server.dart -o build/starsync-server
|
||||||
working-directory: packages/server
|
working-directory: packages/server
|
||||||
- run: build/watch-together-server --help
|
- run: build/starsync-server --help
|
||||||
working-directory: packages/server
|
working-directory: packages/server
|
||||||
|
|
||||||
# The updater's Windows apply path (running exe parked as .old) only
|
# The updater's Windows apply path (running exe parked as .old) only
|
||||||
# means something on real NTFS. Runner notes: see release.yml.
|
# means something on real NTFS, and the close smoke run needs the real
|
||||||
|
# build. Runner notes: see release.yml.
|
||||||
updater-windows:
|
updater-windows:
|
||||||
|
# Not for a "Release v…" commit: release.yml builds it on the same
|
||||||
|
# (only) Windows runner, which this job would hold up.
|
||||||
|
if: ${{ !startsWith(github.event.head_commit.message, 'Release v') }}
|
||||||
runs-on: windows-latest
|
runs-on: windows-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
@@ -68,3 +72,11 @@ jobs:
|
|||||||
- name: Windows build
|
- name: Windows build
|
||||||
shell: powershell
|
shell: powershell
|
||||||
run: powershell -NoProfile -ExecutionPolicy Bypass -File tool/package_windows.ps1
|
run: powershell -NoProfile -ExecutionPolicy Bypass -File tool/package_windows.ps1
|
||||||
|
# The close smoke run on that build (P32): start, open a short clip in
|
||||||
|
# a player with a video output, close; it must exit within 45 s and
|
||||||
|
# leave no process. A runner that cannot show a window skips with a
|
||||||
|
# warning. Here rather than in a job of its own: one build, one runner.
|
||||||
|
- name: Smoke (start, open, close)
|
||||||
|
shell: powershell
|
||||||
|
timeout-minutes: 3
|
||||||
|
run: powershell -NoProfile -ExecutionPolicy Bypass -File tool/smoke_windows.ps1 -Limit 45
|
||||||
@@ -38,7 +38,7 @@ jobs:
|
|||||||
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||||
run: |
|
run: |
|
||||||
VER="${GITHUB_REF_NAME#v}"
|
VER="${GITHUB_REF_NAME#v}"
|
||||||
dart tool/release_publish.dart "$GITHUB_REF_NAME" "dist/watch-together-$VER-linux-x64.tar.gz"
|
dart tool/release_publish.dart "$GITHUB_REF_NAME" "dist/starsync-$VER-linux-x64.tar.gz"
|
||||||
|
|
||||||
windows:
|
windows:
|
||||||
# yuuka-windows: host-mode runner (no containers), runs as SYSTEM, has
|
# yuuka-windows: host-mode runner (no containers), runs as SYSTEM, has
|
||||||
@@ -73,5 +73,5 @@ jobs:
|
|||||||
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||||
run: |
|
run: |
|
||||||
$Ver = $env:GITHUB_REF_NAME.TrimStart('v')
|
$Ver = $env:GITHUB_REF_NAME.TrimStart('v')
|
||||||
dart tool/release_publish.dart $env:GITHUB_REF_NAME "dist/watch-together-$Ver-windows-x64.zip"
|
dart tool/release_publish.dart $env:GITHUB_REF_NAME "dist/starsync-$Ver-windows-x64.zip"
|
||||||
if ($LASTEXITCODE) { exit 1 }
|
if ($LASTEXITCODE) { exit 1 }
|
||||||
@@ -17,6 +17,7 @@ coverage/
|
|||||||
# Build artifacts that should never be committed
|
# Build artifacts that should never be committed
|
||||||
*.tar.gz
|
*.tar.gz
|
||||||
*.zip
|
*.zip
|
||||||
|
/dist/
|
||||||
app.*.symbols
|
app.*.symbols
|
||||||
app.*.map.json
|
app.*.map.json
|
||||||
|
|
||||||
|
|||||||
@@ -11,9 +11,9 @@ everyone's play, pause and seek stay together.
|
|||||||
Why not Jellyfin SyncPlay: it runs in the browser and its sync is poor.
|
Why not Jellyfin SyncPlay: it runs in the browser and its sync is poor.
|
||||||
This is a desktop app that drives mpv.
|
This is a desktop app that drives mpv.
|
||||||
|
|
||||||
Name: `watch-together` is a placeholder and the final name is undecided
|
Up to 1.2.x the app was called `watch_together` (its files
|
||||||
(`sync-relay` is the working name). It appears in file names and the
|
`watch-together-*`); the repository and the update manifest keep their old
|
||||||
update manifest until that is settled.
|
addresses for now.
|
||||||
|
|
||||||
- Desktop only (Linux and Windows), always mpv. No web clients.
|
- Desktop only (Linux and Windows), always mpv. No web clients.
|
||||||
- No transcoding. Everyone plays the original file.
|
- No transcoding. Everyone plays the original file.
|
||||||
@@ -25,19 +25,33 @@ How it fits together: [docs/HOW-IT-WORKS.md](docs/HOW-IT-WORKS.md).
|
|||||||
|
|
||||||
From the Releases page of this repo:
|
From the Releases page of this repo:
|
||||||
|
|
||||||
- Linux: `watch-together-<version>-linux-x64.tar.gz`. Extract, run
|
- Linux: `starsync-<version>-linux-x64.tar.gz`. Extract, run
|
||||||
`watch_together`. On start it adds itself to your app launcher (and its
|
`starsync`. On start it adds itself to your app launcher (and its
|
||||||
icon), so the window shows its own icon on Wayland. Needs mpv's library installed (`mpv` or `libmpv2`).
|
icon), so the window shows its own icon on Wayland. Needs mpv's library installed (`mpv` or `libmpv2`).
|
||||||
- Windows: `watch-together-<version>-windows-x64.zip`. Extract, run
|
- Windows: `starsync-<version>-windows-x64.zip`. Extract, run
|
||||||
`watch_together.exe`. mpv is bundled. New and not yet tried on a real
|
`starsync.exe`. mpv is bundled. New and not yet tried on a real
|
||||||
Windows desktop; reports welcome.
|
Windows desktop; reports welcome.
|
||||||
|
|
||||||
Update from the app: when a newer version exists, an update indicator
|
The folder also holds `watch_together(.exe)` and
|
||||||
appears in the strip at the top of the window and opens the update card. "Update and restart" downloads,
|
`watch-together-server(.exe)`, the names up to 1.2.x: they start the new
|
||||||
verifies, applies in place and restarts; the install folder must be writable
|
programs, so an update from 1.2.x restarts fine and old shortcuts and
|
||||||
by you. Settings has Check now and an auto-check toggle. From a terminal:
|
service files keep working.
|
||||||
`./watch-together-server --upgrade` (no display needed, so it works on a
|
|
||||||
server box too), `watch_together --upgrade`, or the shipped `update.sh` /
|
Your data (settings, sign-ins, folders, logs, yt-dlp and its cookies) lives
|
||||||
|
in `~/.local/share/dev.foxyz.starsync` on Linux and
|
||||||
|
`%APPDATA%\foxyz\Starsync` on Windows. The first start after 1.2.x copies
|
||||||
|
it over from the old places (`~/.local/share/moe.senkochan.watch_together`
|
||||||
|
or `%APPDATA%\com.example\watch_together`, and the app's files in your
|
||||||
|
Documents folder) and leaves the originals where they were.
|
||||||
|
|
||||||
|
Update from the app: the app looks for a new version at start and every
|
||||||
|
few hours, and when one exists a band across the top of the window says so
|
||||||
|
(never over a playing video). "Update and restart" downloads,
|
||||||
|
verifies, applies in place and restarts; "Later" hides it until the next
|
||||||
|
check; the install folder must be writable by you. The version you run is
|
||||||
|
at the bottom of every Settings page (and in the Settings tab's tooltip). Settings has Check now and an auto-check toggle. From a terminal:
|
||||||
|
`./starsync-server --upgrade` (no display needed, so it works on a
|
||||||
|
server box too), `./starsync --upgrade`, or the shipped `update.sh` /
|
||||||
`update.bat` (which run the first). Each updates the whole folder, app and
|
`update.bat` (which run the first). Each updates the whole folder, app and
|
||||||
server; restart whichever is running to use the new version. A
|
server; restart whichever is running to use the new version. A
|
||||||
release with a newer protocol is a required update: everyone on a server
|
release with a newer protocol is a required update: everyone on a server
|
||||||
@@ -46,33 +60,37 @@ telling you to update.
|
|||||||
|
|
||||||
## Getting started
|
## Getting started
|
||||||
|
|
||||||
Three ways in, all at the top of the Library when you are not in a server.
|
The app always runs its own server, quietly: your server. When it starts
|
||||||
None of them needs Jellyfin or an account.
|
you are on it, alone, and it is a plain player. Three ways in, at the top
|
||||||
|
of the Library the first time; none needs Jellyfin or an account.
|
||||||
|
|
||||||
- **Join a friend** (most people): your friend sends you an address and,
|
- **Join a friend** (most people): your friend sends you an invite (an
|
||||||
maybe, a password. See [Join](#join).
|
address) and, maybe, a password. See [Join](#join).
|
||||||
- **Host**: you have the video and friends watch it with you. See
|
- **Invite friends**: you have the video and friends watch it with you.
|
||||||
[Host from the app](#host-from-the-app).
|
See [Your server and Invite](#your-server-and-invite).
|
||||||
- **Watch solo**: just play something from the Library. It plays for you
|
- **Watch on your own**: just play something from the Library, with
|
||||||
alone, with everything a server has (Jellyfin progress, next episode,
|
everything a server has (Jellyfin progress, next episode, skip buttons).
|
||||||
skip buttons); nothing is reachable from outside this computer. Invite
|
Nobody else can reach your server until you invite them; inviting never
|
||||||
friends in the strip turns it into a hosted server (the Host card's port
|
interrupts what plays.
|
||||||
and password) and the video carries on from where it was; Stop ends it.
|
|
||||||
|
|
||||||
## The window
|
## The window
|
||||||
|
|
||||||
One window. Along the top, the strip: your avatar (click it for your
|
One window. Along the top, the strip: your avatar (click it for your
|
||||||
profile: name, picture with a crop editor, colour, and links to the
|
profile: name, picture with a crop editor, colour, and links to the
|
||||||
settings), the Library / Schedule / Settings tabs, and the party. Offline
|
settings), the Library / Schedule / Settings tabs, and the party. Alone
|
||||||
the party side has Join a friend and Host; watching solo it says Solo,
|
on your server it has just Join a friend and Invite (and "Sharing" while
|
||||||
with Invite friends and Stop; in a server it shows everyone's avatar
|
your server is open to friends); with others there it shows everyone's avatar
|
||||||
with a ring for their state (green ready, amber buffering, grey not ready,
|
with a ring for their state (green ready, amber buffering, grey not ready,
|
||||||
dimmed reconnecting, dimmed with a moon sitting out; a crown on whoever
|
a little faded joining, dimmed reconnecting, dimmed with a moon sitting
|
||||||
|
out; a crown on whoever
|
||||||
hosts, a tower on whoever passes the video on). Click the avatars for the
|
hosts, a tower on whoever passes the video on). Click the avatars for the
|
||||||
member list (force ready, Nudge, Sit out, "Copy invite address"; when you host it lists this computer's
|
member list (each member's app version, amber when it differs from yours,
|
||||||
network addresses with the port, and friends outside your network need
|
and the server's at the top; force ready, Nudge, Sit out; on your
|
||||||
that port forwarded or a server they can all reach, like a VPS). Beside them the server and "ready n/m", the chat button with unread
|
server the invite with Copy invite and Stop sharing, on a friend's "Copy
|
||||||
count, and Leave. Empty strip space drags the window.
|
invite address"). Beside them the server and "ready n/m" (who is sitting out or
|
||||||
|
reconnecting does not count), the chat button with unread
|
||||||
|
count, and Invite on your server or Leave on a friend's. Empty strip
|
||||||
|
space drags the window.
|
||||||
|
|
||||||
The player fills the window under the strip. Pick a tab and it shrinks to
|
The player fills the window under the strip. Pick a tab and it shrinks to
|
||||||
a mini player in a corner: drag it anywhere and it snaps to the nearest
|
a mini player in a corner: drag it anywhere and it snaps to the nearest
|
||||||
@@ -81,16 +99,35 @@ corner; double-click or ⤢ makes it big again, × sits you out (below) and
|
|||||||
double-click on the picture goes fullscreen (the strip hides, the party
|
double-click on the picture goes fullscreen (the strip hides, the party
|
||||||
shows in a corner while paused, the window buttons sit in the player's top
|
shows in a corner while paused, the window buttons sit in the player's top
|
||||||
bar while its controls are up), Esc leaves it. The controls show the
|
bar while its controls are up), Esc leaves it. The controls show the
|
||||||
show's cover, title and episode top left (guests get the cover too); before
|
show's cover, title and episode top left (a web video: its thumbnail and
|
||||||
|
name; guests get the art too; right-click to copy the title, or the link
|
||||||
|
when you have it, or open it in the browser or Jellyfin); before
|
||||||
a video first plays, its banner fills the picture until playback starts.
|
a video first plays, its banner fills the picture until playback starts.
|
||||||
One pill above the controls says what playback waits for ("Press Space
|
One pill bottom centre, just above the controls, says what playback waits for ("Press Space
|
||||||
when you're ready", "Waiting for Bob and Mika · 2/3 ready", "Bob is
|
when you're ready", "Waiting for Bob and Mika · 2/3 ready", "Bob is
|
||||||
loading…") or what went wrong, with Retry or Cancel when it helps. Chat and activity open in a panel on the right (chat button or
|
loading…") or what went wrong, with Retry or Cancel when it helps. Chat and activity open in a panel on the right (chat button or
|
||||||
Tab), ready to type; it shows messages, and its "Activity" toggle adds
|
Tab), ready to type; it shows messages (select text to copy it, or
|
||||||
joins, ready, seeks and the like between them. Joins, leaves, chat and
|
right-click for Copy message and, with a link in it, Copy link / Open in
|
||||||
other news also pop up bottom left with the person's avatar; click a message to open the chat. Unread chat
|
browser), and its "Activity" toggle adds
|
||||||
shows as a count on the chat buttons and, in fullscreen with the controls
|
joins, ready, seeks and the like between them. Joins, leaves, someone
|
||||||
hidden, as a small chip top right.
|
losing connection and coming back, video changes, additions to Up next
|
||||||
|
(the title, its picture and who added it), chat and problems also pop up
|
||||||
|
bottom left with the person's avatar, above the player's controls (never
|
||||||
|
on them); ready, seeks and pauses stay in the activity. Click a message
|
||||||
|
to open the chat (Settings → Notifications & sounds → Chat messages: All
|
||||||
|
by default, or Only when paused, or Off; messages always reach the chat,
|
||||||
|
with their sound). Watching alone, nothing pops up or sounds about the
|
||||||
|
party (there is nobody); the app's own notices still show.
|
||||||
|
|
||||||
|
**While sitting out or in the background.** Sitting out, only chat,
|
||||||
|
nudges, "starting now" (the video starts for the others) and Up next
|
||||||
|
reach you; joins and leaves too if you turn on Settings → Notifications &
|
||||||
|
sounds → "Joins and leaves too". With the window in the background or
|
||||||
|
minimised, the same ones also come as desktop notifications (Linux's
|
||||||
|
notification center, Windows' toasts); clicking one brings the window
|
||||||
|
up, and a chat one opens the chat. Unread chat shows as a count on the chat
|
||||||
|
buttons and, in fullscreen with the controls hidden and the video paused,
|
||||||
|
as a small chip top right.
|
||||||
|
|
||||||
Your name and picture change for everyone in the server right away; the
|
Your name and picture change for everyone in the server right away; the
|
||||||
colour is yours only.
|
colour is yours only.
|
||||||
@@ -100,32 +137,58 @@ row in the member list, or × on the mini player) unloads the video on your
|
|||||||
end, and nobody waits for you any more; you stay in chat. Anyone can sit
|
end, and nobody waits for you any more; you stay in chat. Anyone can sit
|
||||||
anyone out, the host too ("Alice sat you out" tells you who). The player
|
anyone out, the host too ("Alice sat you out" tells you who). The player
|
||||||
then shows the cover, title and where the others are; Join back (or Space)
|
then shows the cover, title and where the others are; Join back (or Space)
|
||||||
loads the video there and readies you. Settings → Party & network → "When idle,
|
loads the video there and readies you, in the background while the others
|
||||||
sit out instead of just unready" does it after 10 idle minutes.
|
play on (nobody is paused for you).
|
||||||
|
|
||||||
|
**Auto sit-out.** Idle for 5 minutes while nothing plays, or the window
|
||||||
|
minimised for 10 minutes (playing or not), sits you out by itself, so
|
||||||
|
nobody waits for you; you are back as soon as you return (a key, the
|
||||||
|
mouse, the window's focus). It never happens when you are alone, and an
|
||||||
|
away you chose (or someone else's) stays until you join back. Settings →
|
||||||
|
Party & network → "Auto sit-out" turns it off.
|
||||||
|
|
||||||
|
**Reconnects.** A bad connection does not throw you out: the video keeps
|
||||||
|
playing, the pill says "Connection unstable…" and then "Reconnecting…",
|
||||||
|
and the app comes back on its own as the same member (ready, sitting out,
|
||||||
|
your Up next items and the video you pass on all kept) for up to 10
|
||||||
|
minutes; the others see you dimmed, "reconnecting…". Only a drop of a
|
||||||
|
few seconds or more makes the lost / back sounds. Leave and closing the
|
||||||
|
app tell the others at once; Update and restart keeps your place for the
|
||||||
|
restarted app. Opening Starsync a second time (another window with the
|
||||||
|
same profile) takes your place over, and the first one says so and stops.
|
||||||
|
|
||||||
**Nudge.** Nudge in the member list pokes someone, sitting out or not:
|
**Nudge.** Nudge in the member list pokes someone, sitting out or not:
|
||||||
only they hear it (a sound, a pop-up, and the taskbar entry asks for
|
only they hear it (a sound, a pop-up, and the taskbar entry asks for
|
||||||
attention when the window is in the background).
|
attention when the window is in the background).
|
||||||
|
|
||||||
## Host from the app
|
## Your server and Invite
|
||||||
|
|
||||||
Host in the strip: set a port and an optional password (blank = anyone can
|
Your server starts with the app and stops when it closes. Only this app
|
||||||
join), then Host. The app starts a server inside itself and joins it; you
|
can reach it until you press **Invite** (in the strip, or in the member
|
||||||
are the host (the crown). Nothing is up yet: pick what to
|
list): that opens it on your network at the port from Settings → Party &
|
||||||
watch in the Library tab (below) and put it up. Leaving or
|
network (default 8080, with the password set there; blank = anyone can
|
||||||
closing the app stops the server. Friends need to reach your machine: open
|
join) and copies an invite ("Join me on Starsync: 192.168.1.20:8080 ·
|
||||||
the TCP port on your router (or use a LAN or VPN address). Friends open
|
Starsync 1.3.0") to send to friends. Nothing restarts: what plays and Up
|
||||||
nothing. Ports you hosted on before are one click away in the Host card.
|
next carry on, and you are the host (the crown). The invite picks this
|
||||||
|
computer's home-network address (not a VPN or proxy one, nor a Docker or
|
||||||
|
VM bridge). Friends elsewhere need the TCP port forwarded on your router
|
||||||
|
(or a VPN address, or a server they can all reach, like a VPS). Friends
|
||||||
|
open nothing. **Stop sharing** (in the member list) closes it again:
|
||||||
|
everyone else leaves (their app goes back to their own server and says
|
||||||
|
why), you and Up next stay.
|
||||||
|
|
||||||
If you put up a local file, the server streams it to everyone from your
|
If you put up a local file, your server streams it to everyone from your
|
||||||
disk. Nothing is uploaded or stored anywhere.
|
disk. Nothing is uploaded or stored anywhere.
|
||||||
|
|
||||||
|
Joining a friend leaves your server for theirs; it stays up meanwhile,
|
||||||
|
and leaving theirs brings you back to it as you left it.
|
||||||
|
|
||||||
## Library
|
## Library
|
||||||
|
|
||||||
What to watch, from three sources (the switch at the top). Drop a video,
|
What to watch, from three sources (the switch at the top). Drop a video,
|
||||||
a folder or a link anywhere on the window, or press Ctrl+V outside a
|
a folder or a link anywhere on the window, or press Ctrl+V outside a
|
||||||
text field, and a small card asks how to open it (put it up, add the
|
text field, and a small card asks how to open it (put it up, add it to
|
||||||
folder to Files, or fill Link).
|
Up next, add the folder to Files, or fill Link).
|
||||||
|
|
||||||
- **Jellyfin**: your linked servers (see below); with none linked it
|
- **Jellyfin**: your linked servers (see below); with none linked it
|
||||||
points to Files and Link and offers Jellyfin as optional. Library chips beside the
|
points to Files and Link and offers Jellyfin as optional. Library chips beside the
|
||||||
@@ -140,29 +203,104 @@ folder to Files, or fill Link).
|
|||||||
details open on the right with "Put it up · S1E3", mark watched /
|
details open on the right with "Put it up · S1E3", mark watched /
|
||||||
unwatched, remove from Continue and the episode list (click an episode
|
unwatched, remove from Continue and the episode list (click an episode
|
||||||
to choose it). Double-click a card or an episode to put it up at once.
|
to choose it). Double-click a card or an episode to put it up at once.
|
||||||
|
Right-click a card or an episode to copy its title or open it in
|
||||||
|
Jellyfin's web page (the details panel has that button too).
|
||||||
- **Link**: paste an http(s) link: a video file, or a web page with a
|
- **Link**: paste an http(s) link: a video file, or a web page with a
|
||||||
video (YouTube, X, and whatever else yt-dlp knows). The preview shows
|
video (YouTube, X, and whatever else yt-dlp knows). The preview shows
|
||||||
what it is (a page's title, uploader, length and thumbnail, else the
|
what it is (a page's title, uploader, length and thumbnail, else the
|
||||||
file name); in a server, pick how the
|
file name); in a server, pick how the
|
||||||
others get it (everyone fetches it, the server fetches it, or through
|
others get it (everyone fetches it, the server fetches it, or through
|
||||||
you). Your last 12 links are listed under it. A link that does not
|
you). Your last 12 links are listed under it (right-click one to copy
|
||||||
|
or open it). A link seen before shows its preview at once, without
|
||||||
|
asking the site again. A link that does not
|
||||||
open here (needs cookies, 403, 404, not a video) says why and goes up
|
open here (needs cookies, 403, 404, not a video) says why and goes up
|
||||||
only with "Put it up anyway"; in the player, whoever cannot play it is
|
only with "Put it up anyway"; in the player, whoever cannot play it is
|
||||||
named ("Bob can't play this: Not allowed (403)") and nobody waits for them.
|
named ("Bob can't play this: Not allowed (403)") and nobody waits for them.
|
||||||
- **Files**: video folders you add on this computer, grouped by series
|
- **Files**: your own library from the video folders you add on this
|
||||||
(click a series to list its episodes), or any file through Browse. The others stream it from you.
|
computer (the **Library** shows them all together, each folder on its
|
||||||
|
own too), or any file through Browse. Files are sorted into shows and
|
||||||
|
movies by their names and folders: one show split over several folders
|
||||||
|
is one show, OP/ED and specials go under its **Extras**, a folder like
|
||||||
|
"Show (Season 3 - Alicization)" gives the season and its name. Shows
|
||||||
|
are looked up on AniList for their proper name, cover and banner. A
|
||||||
|
show's page has its seasons and episodes and a button for the next one
|
||||||
|
after what you last watched here; when episodes are missing on the way
|
||||||
|
it says so ("66–107 aren't in your folders — skip to 108?"). An
|
||||||
|
episode you put up continues with the next one at its end (see Up
|
||||||
|
next). Matched
|
||||||
|
the wrong show? **Wrong show?** searches AniList and pins the right one
|
||||||
|
for the show everywhere or just one folder; **Episode numbers…** says
|
||||||
|
which episode the first file is when the files count differently. Both
|
||||||
|
stay through rescans. The others stream what you put up from you, and
|
||||||
|
see its proper name too.
|
||||||
|
|
||||||
Put it up and the player opens. Not in a server, the buttons say Play
|
Put it up and the player opens. With nobody else in the server, the
|
||||||
and it plays for you alone ([Watch solo](#getting-started)).
|
buttons say Play and a link plays straight from the site.
|
||||||
|
|
||||||
|
### Up next (the queue)
|
||||||
|
|
||||||
|
Anything can wait its turn instead of going up
|
||||||
|
now: **Add to queue** on the Link page (in the way you picked), or
|
||||||
|
right-click a Jellyfin card or episode, a video in Files, a recent link
|
||||||
|
or an episode on the Schedule for **Add to queue** / **Play next**; the
|
||||||
|
Jellyfin details panel has a queue button (right-click it to play next),
|
||||||
|
and the card for a dropped or pasted video or link has both. A link is
|
||||||
|
checked first, like Put it up. Every app keeps the next item ready,
|
||||||
|
its first seconds already loaded, so skipping to it starts at once.
|
||||||
|
For a link passed on, a member's file or a link the server fetches,
|
||||||
|
the server starts getting the next item while the current one plays
|
||||||
|
(from the app of whoever added it, or by fetching the link itself), so
|
||||||
|
everyone has its start before it goes up; whoever added it keeps the
|
||||||
|
app open for that. Everyone shares one Up next and anyone can change it; what
|
||||||
|
you added stays when you leave.
|
||||||
|
|
||||||
|
In the player, Up next sits in the top bar, right of the title: the
|
||||||
|
next item's picture and title (or what continues the episode). Rest the mouse on
|
||||||
|
it for a larger preview (who added it, its length, whether it is ready
|
||||||
|
to start); ⏭ plays it now, a click opens the queue: drag rows to reorder, hover a
|
||||||
|
row to play it now (▶) or remove it (×), right-click it for more (copy its
|
||||||
|
title or link, open it in the browser or in Jellyfin). To add, press
|
||||||
|
Ctrl+V with the queue open (a copied link or video file goes in at once,
|
||||||
|
its title and picture showing while it is checked), type one after
|
||||||
|
**+ Add link**, or drop a link or a video on it. When a video ends, a card shows
|
||||||
|
what is up next with a 10 s countdown everyone sees, and it plays;
|
||||||
|
Cancel stops it for everyone, and so does seeking back. `>` or Shift+N
|
||||||
|
plays it at once. Under the queue, **Continues with** shows what
|
||||||
|
continues the episode playing: its next episode (a Jellyfin episode's,
|
||||||
|
or a file's next one in your Files library, saying which numbers it
|
||||||
|
skips), added by whoever put the episode up, and greyed because it
|
||||||
|
plays only once Up next is empty; **Clear** drops it for everyone. The
|
||||||
|
further episodes of a Jellyfin series show under it; **+** adds one.
|
||||||
|
|
||||||
|
A link you pass on ("through me") or a file of yours can only be played
|
||||||
|
by your app: if you left when its turn comes, it is skipped ("Skipped …:
|
||||||
|
Foxyz left"). If you are only gone for a moment, the countdown waits for
|
||||||
|
you. A Jellyfin item needs someone with an account on that server. Up
|
||||||
|
next is kept by the server while it runs. If the server restarts, the
|
||||||
|
apps put back what was playing, where it was, and Up next with it (a
|
||||||
|
link the server fetched has to be added again).
|
||||||
|
|
||||||
|
## Schedule
|
||||||
|
|
||||||
|
The week's airing anime, one column per day (AniList), each episode
|
||||||
|
marked with what the Jellyfin server has of it when AnimeFlow is
|
||||||
|
connected (Settings, Jellyfin & integrations): **on Jellyfin** (Put it
|
||||||
|
up, right-click to queue), **downloading**, **waiting for release**
|
||||||
|
(aired in Japan, AnimeFlow downloads it by itself once a release
|
||||||
|
appears; with when AnimeFlow last searched, or **release rejected** when
|
||||||
|
it found releases it won't take, the reason on hover), **failed**, **not monitored** (Request asks AnimeFlow for it),
|
||||||
|
or the time left until it airs. A show AnimeFlow does not follow can be asked for with **Request
|
||||||
|
series**. Episodes you already watched on Jellyfin carry a check on the
|
||||||
|
cover; one you started shows how far you got.
|
||||||
|
|
||||||
## Dedicated server
|
## Dedicated server
|
||||||
|
|
||||||
For an always-on box (no display needed): the release tarball also contains
|
For an always-on box (no display needed): the release tarball also contains
|
||||||
`watch-together-server`, a small standalone server without the app. Run it,
|
`starsync-server`, a small standalone server without the app. Run it,
|
||||||
then everyone (you included) uses Join.
|
then everyone (you included) uses Join.
|
||||||
|
|
||||||
```
|
```
|
||||||
./watch-together-server --port 8080 --secret <password>
|
./starsync-server --port 8080 --secret <password>
|
||||||
```
|
```
|
||||||
|
|
||||||
| Flag | Default | Meaning |
|
| Flag | Default | Meaning |
|
||||||
@@ -175,47 +313,79 @@ then everyone (you included) uses Join.
|
|||||||
| `--[no-]yt-dlp` | on | read web pages (YouTube, X, …) with yt-dlp when the server fetches a link |
|
| `--[no-]yt-dlp` | on | read web pages (YouTube, X, …) with yt-dlp when the server fetches a link |
|
||||||
| `--yt-dlp-dir` | next to the binary | writable folder for the server's yt-dlp (systemd: the unit's `StateDirectory`) |
|
| `--yt-dlp-dir` | next to the binary | writable folder for the server's yt-dlp (systemd: the unit's `StateDirectory`) |
|
||||||
| `--yt-dlp-cookies` | none | cookies.txt or cookie-extension JSON export for that yt-dlp (sites that refuse guests); copied into the yt-dlp folder at start, removed from it when not given. **An account login**: keep it private, use a throwaway account for YouTube |
|
| `--yt-dlp-cookies` | none | cookies.txt or cookie-extension JSON export for that yt-dlp (sites that refuse guests); copied into the yt-dlp folder at start, removed from it when not given. **An account login**: keep it private, use a throwaway account for YouTube |
|
||||||
|
| `--log-dir` | `logs` next to `--config`, else next to the binary (systemd: the unit's `StateDirectory`) | folder for the log files (`server-YYYY-MM-DD.log` and the session log `session-YYYY-MM-DD.log`, kept 7 days; passwords, tokens and cookies left out) |
|
||||||
| `--config` | none | YAML or JSON file with the same settings (`port`, `secret`, `name`, `mediaPath`, `advertiseHost`, `ytDlp`, `ytDlpDir`, `ytDlpCookies`); replaces the flags |
|
| `--config` | none | YAML or JSON file with the same settings (`port`, `secret`, `name`, `mediaPath`, `advertiseHost`, `ytDlp`, `ytDlpDir`, `ytDlpCookies`); replaces the flags |
|
||||||
| `--upgrade` | | update the install folder to the latest release ([Install and update](#install-and-update)), then exit |
|
| `--upgrade` | | update the install folder to the latest release ([Install and update](#install-and-update)), then exit |
|
||||||
| `--check-update` | | print whether a newer release exists, then exit |
|
| `--check-update` | | print whether a newer release exists, then exit |
|
||||||
|
|
||||||
It prints `READY port=... name=...` once listening and stops cleanly on
|
It prints `READY port=... name=...` once listening and stops cleanly on
|
||||||
Ctrl+C or SIGTERM. A dedicated server has no host.
|
Ctrl+C or SIGTERM. A dedicated server has no host.
|
||||||
To run it as a service, unpack the tarball to `/opt/watch-together` and use
|
To run it as a service, unpack the tarball to `/opt/starsync` and use
|
||||||
[deploy/watch-together.service](deploy/watch-together.service) (copy it to
|
[deploy/starsync.service](deploy/starsync.service) (copy it to
|
||||||
`/etc/systemd/system/`, edit the flags, `systemctl enable --now watch-together`).
|
`/etc/systemd/system/`, edit the flags, `systemctl enable --now starsync`).
|
||||||
|
A service set up before the rename (`/opt/watch-together`, running
|
||||||
|
`watch-together-server`) keeps working as it is.
|
||||||
|
|
||||||
|
Something not playing? Settings → About → **Copy diagnostics** puts the
|
||||||
|
app's recent log (passwords, tokens and cookies left out) on the
|
||||||
|
clipboard: paste it to whoever helps you, from both sides if you can.
|
||||||
|
|
||||||
|
While you are in a server, the app also sends its log to that server, which
|
||||||
|
merges everyone's lines and its own into one session log
|
||||||
|
(`session-YYYY-MM-DD.log` next to the server's logs; your own server
|
||||||
|
keeps it in the app's logs folder), so a problem can be read afterwards from every
|
||||||
|
side. Chat is never logged anywhere, nor passwords, tokens and cookies.
|
||||||
|
When something goes wrong, press **Mark a problem** (Ctrl+Shift+B, also in
|
||||||
|
the player's ⚙ and Settings → About) and add a few words if you like: a
|
||||||
|
marker with your name goes in the session log at that moment. In a server,
|
||||||
|
Copy diagnostics can add the session log of the last 6 hours (any member
|
||||||
|
may read it). Don't want to share? Settings → About → **Share diagnostics
|
||||||
|
with the server** off: your log stays on your machine (the server only
|
||||||
|
notes that you don't share; a problem you mark still goes in).
|
||||||
|
|
||||||
## Join
|
## Join
|
||||||
|
|
||||||
Join in the strip. Servers you got into are listed first (up to 6), with
|
Join a friend in the strip. Servers you got into are listed first (up
|
||||||
live status (online and how many are watching, or offline, plus "needs
|
to 6), with live status (online and how many are watching, or offline,
|
||||||
update" when the server runs another protocol): click one to rejoin, x to
|
plus "needs update" when its version and yours do not match): click one
|
||||||
forget it. Or enter the host's address, port, and the password if there
|
to rejoin, x to forget it. Or paste the invite (or the address and port)
|
||||||
is one, then Enter or Join. Your name and picture come from your profile
|
and the password if there is one, then Enter or Join. Before connecting
|
||||||
(your avatar at the top left).
|
the app checks the server's version: when they do not match it says who
|
||||||
|
has to update ("Bob's server runs Starsync 1.2.1 — they need to
|
||||||
|
update"), and offers the update when it is you. Your name and picture
|
||||||
|
come from your profile (your avatar at the top left). Leave goes back to
|
||||||
|
your own server.
|
||||||
|
|
||||||
## Settings
|
## Settings
|
||||||
|
|
||||||
The Settings tab (Ctrl+,) has a page per topic, each setting with a line
|
The Settings tab (Ctrl+,) has a page per topic, each setting with a line
|
||||||
of help: Profile; Party & network (the Host card's default port and
|
of help: Profile; Party & network (your server's port and password for
|
||||||
password, recent servers with remove); Player (below); Jellyfin &
|
Invite, recent servers with remove); Player (below); Jellyfin &
|
||||||
integrations (linked Jellyfin servers, below, the AnimeFlow connection:
|
integrations (linked Jellyfin servers, below, the AnimeFlow connection:
|
||||||
"connected as <name>" with what you may do, or why not, and playing the
|
"connected as <name>" with what you may do, or why not, and playing the
|
||||||
next episode automatically); Notifications & sounds (what pops up; the sound
|
next episode automatically); Notifications & sounds (what pops up, chat
|
||||||
|
pop-ups, what reaches you while sitting out or in the background; the sound
|
||||||
volume and sound set, and every sound with a preview, its own set and a switch); Updates; Keyboard shortcuts (read-only); About
|
volume and sound set, and every sound with a preview, its own set and a switch); Updates; Keyboard shortcuts (read-only); About
|
||||||
(the version).
|
(the version, also at the bottom of every Settings page and in the
|
||||||
|
Settings tab's tooltip; and the credits, e.g. that the Minimal player design is inspired by uosc).
|
||||||
|
|
||||||
Player settings live in the player: ⚙ at the right end of its controls
|
Player settings live in the player too: ⚙ → Player settings, at the
|
||||||
(both designs) opens them, and Settings → Player has the same ones (plus
|
right of its controls, and Settings → Player has the same ones (plus the
|
||||||
the custom shader files). Player design: Standard or uosc (below);
|
controls' layout and the custom shader files). Player design: Standard or
|
||||||
progress line when hidden (on by default: a 2 px line at the bottom of
|
Minimal (below); progress line when hidden (on by default: a thin line at
|
||||||
the video while the controls are hidden); upscaling shader (see below);
|
the bottom of the video while the controls are hidden); upscaling shader
|
||||||
hardware decoding (auto, off or custom; the env var `SYNC_RELAY_HWDEC`
|
(see below); hardware decoding (auto, off or custom; auto is mpv's
|
||||||
overrides it); in the player also the subtitle and audio track. Every
|
`auto-copy` on Windows, `auto` elsewhere; the env var
|
||||||
change applies right away.
|
`SYNC_RELAY_HWDEC` overrides it); in the player also the subtitle and
|
||||||
|
audio track. Settings → Player → Controls: time display (elapsed / total
|
||||||
|
or remaining), controls size (normal or large), hide the controls after
|
||||||
|
2, 3 or 5 s, and which optional buttons sit in the bar (chapter buttons,
|
||||||
|
subtitles, audio, chat; hidden ones are still in ⚙). Every change
|
||||||
|
applies right away.
|
||||||
|
|
||||||
Anywhere in a server (unless you are typing): Space = ready / unready,
|
Anywhere in a server (unless you are typing): Space = ready / unready,
|
||||||
Tab = chat & activity (Tab never moves between buttons). Keys while the
|
Tab = chat & activity (Tab never moves between buttons). Anywhere:
|
||||||
|
Ctrl+Shift+B = mark a problem in the session log. Keys while the
|
||||||
player fills the window: Left/Right = seek 10 s, Up/Down = volume, Shift+Right = skip 1:30,
|
player fills the window: Left/Right = seek 10 s, Up/Down = volume, Shift+Right = skip 1:30,
|
||||||
PgUp/PgDn = previous / next chapter (as in mpv), F = fullscreen, Esc =
|
PgUp/PgDn = previous / next chapter (as in mpv), F = fullscreen, Esc =
|
||||||
close the chat, then fullscreen, then shrink the player to mini; from the
|
close the chat, then fullscreen, then shrink the player to mini; from the
|
||||||
@@ -224,30 +394,45 @@ mini it asks to leave, Ctrl+R = reload video,
|
|||||||
Ctrl+1..6 = Anime4K mode A, B, C, A+A, B+B, C+A, Ctrl+0 = shaders off.
|
Ctrl+1..6 = Anime4K mode A, B, C, A+A, B+B, C+A, Ctrl+0 = shaders off.
|
||||||
Every seek, skip and chapter jump moves everyone.
|
Every seek, skip and chapter jump moves everyone.
|
||||||
|
|
||||||
Controls: the seek bar marks chapter starts with a diamond; hovering it
|
Controls: both designs have the same buttons in the same places, only
|
||||||
shows the time and the chapter title. The chapters button lists them
|
the look differs. Bottom left: play / pause first (it is your ready, like
|
||||||
(current one checked; click to jump). "1:30" skips ahead 1:30. Audio and
|
Space: ✓ while you are ready and the others are not), previous / next
|
||||||
Subtitles buttons (with the track count) list tracks as "Japanese · E-AC3
|
episode (when there is one; next plays Up next first), previous / next
|
||||||
2.0 · title"; subtitles have Off. Volume (hover the speaker, scroll on
|
chapter (when the video has chapters), volume and the time (click it to
|
||||||
it, or Up/Down) goes to 150 % like mpv: past the tick at 100 % the bar
|
switch between elapsed / total and the time left). Bottom right:
|
||||||
turns amber and mpv amplifies.
|
Subtitles and Audio (with the track count; tracks listed as "Japanese ·
|
||||||
|
E-AC3 2.0 · title", subtitles with Off), ⚙, chat and fullscreen last.
|
||||||
|
Everything else is in ⚙: chapters (current one checked; click to jump),
|
||||||
|
Skip 1:30, upscaling shader, change video, copy link, reload video,
|
||||||
|
mark everyone ready, mark a problem, player settings and leave. The top
|
||||||
|
bar has the title, Up next and back to the library (in fullscreen: exit
|
||||||
|
fullscreen and the window buttons). Volume (scroll anywhere on the
|
||||||
|
video, hover the speaker, or Up/Down) goes to 150 % like mpv: past the
|
||||||
|
tick at 100 % the bar turns amber and mpv amplifies; a scroll or key
|
||||||
|
shows the volume for a moment. Lists and menus under the mouse scroll
|
||||||
|
as usual.
|
||||||
|
|
||||||
The uosc player design (⚙ → Player design, Standard by default,
|
Standard (the default): a seek bar that marks chapter starts with a
|
||||||
switches right away): video controls modeled on mpv's uosc theme. A thick
|
diamond (hovering it shows the time and the chapter title) over a row
|
||||||
timeline across the bottom shows the played part, the cached part ahead
|
of round buttons. Minimal (⚙ → Player settings → Player design, switches
|
||||||
(hatched), chapter starts as diamonds and the time; hovering it shows the
|
right away): a translucent timeline across the bottom tints what has
|
||||||
chapter title and the time there. With the controls hidden it stays as a
|
played, stripes the part not downloaded yet, marks chapter starts with
|
||||||
thin line (unless "Progress line when hidden" is off). Above it flat buttons: ≡ menu, Subtitles and Audio (with the
|
dots (click one to jump), shows the elapsed time left and the total or
|
||||||
track count), the shader badge (the active Anime4K mode, e.g. "A HQ"),
|
the time left right (click it to switch) and, while less than a minute
|
||||||
ready, chapters, 1:30, previous / next episode, change video, volume, ⚙
|
is buffered, the buffered seconds next to the position; hovering it shows
|
||||||
and fullscreen; the title top left, chat and back-to-library top right. Keys and skip buttons work
|
the time there and the chapter title. With the controls hidden it stays
|
||||||
the same.
|
as a thin line (unless "Progress line when hidden" is off). Its buttons
|
||||||
|
sit in two glass capsules above it. Minimal's timeline and controls are
|
||||||
|
inspired by [uosc](https://github.com/tomasklaen/uosc) by tomasklaen
|
||||||
|
(LGPL-2.1).
|
||||||
|
|
||||||
Skipping: during the opening a "Skip OP" button floats in the corner (it
|
Skipping: during the opening a "Skip OP" button shows bottom right, just
|
||||||
|
above the controls (it
|
||||||
jumps to the end of the opening), during the ending "Skip ED" (to the end
|
jumps to the end of the opening), during the ending "Skip ED" (to the end
|
||||||
of the ending only; what comes after is yours to skip). Any skip button
|
of the ending only; what comes after is yours to skip). "Skip OP" and
|
||||||
(also "Skip 1:30") shows for 5 seconds when it comes up, then only while
|
"Skip 1:30" show for 5 seconds when they come up, then only while the
|
||||||
the controls are up (move the mouse). The opening and
|
controls are up (move the mouse); "Skip ED" and "Next episode" show only
|
||||||
|
while the controls are up. The opening and
|
||||||
ending come from Jellyfin's intro / outro segments when your Jellyfin has
|
ending come from Jellyfin's intro / outro segments when your Jellyfin has
|
||||||
them (needs a segment plugin, e.g. Intro Skipper), else from chapter names
|
them (needs a segment plugin, e.g. Intro Skipper), else from chapter names
|
||||||
(OP, Opening, Intro / ED, Ending, Credits, Outro). Without an opening or
|
(OP, Opening, Intro / ED, Ending, Credits, Outro). Without an opening or
|
||||||
@@ -261,7 +446,8 @@ during the first 6 minutes.
|
|||||||
| Sync WebSocket and `/health` | TCP 8080 | plain `ws://`, no TLS |
|
| Sync WebSocket and `/health` | TCP 8080 | plain `ws://`, no TLS |
|
||||||
| Local file streaming | same port | path `/m/...`, needs a session token |
|
| Local file streaming | same port | path `/m/...`, needs a session token |
|
||||||
|
|
||||||
Only the host needs the port reachable.
|
Only the one who invites needs the port reachable; until Invite your
|
||||||
|
server listens on 127.0.0.1 and a free port only.
|
||||||
|
|
||||||
## Jellyfin
|
## Jellyfin
|
||||||
|
|
||||||
@@ -294,49 +480,56 @@ Watching:
|
|||||||
directly with their own sign-in. Jellyfin tracks progress per account:
|
directly with their own sign-in. Jellyfin tracks progress per account:
|
||||||
your watched state, Continue watching and resume point follow what you
|
your watched state, Continue watching and resume point follow what you
|
||||||
saw (reported on start, every 10 s, on pause, resume, seek and track
|
saw (reported on start, every 10 s, on pause, resume, seek and track
|
||||||
change, and when it stops).
|
change, and when it stops). Watched means you were there while most
|
||||||
|
of it played (or while half of it played and it reached the ending),
|
||||||
|
not where it stopped: time you sat out does not count, skipping around
|
||||||
|
does not count, opening a watched episode to check a moment keeps it
|
||||||
|
watched, and a quick peek leaves no resume point. Files and links you
|
||||||
|
watch are remembered the same way on your computer (a show's next
|
||||||
|
episode in Files follows them).
|
||||||
- Friends without an account watch through the server: whoever put the
|
- Friends without an account watch through the server: whoever put the
|
||||||
item up passes it on automatically, with their own sign-in, which never
|
item up passes it on automatically, with their own sign-in, which never
|
||||||
leaves their computer (only the current item, only to people in the
|
leaves their computer (only the current item, only to people in the
|
||||||
session). They show "via host" in the member list (click the avatars). When the app hosts,
|
session). They show "via server" in the member list (click the avatars). On your
|
||||||
or a dedicated server has its own login (`--jellyfin <file>`, see
|
own server (with your sign-in on that item's Jellyfin, whichever of
|
||||||
|
your linked servers it is), or a dedicated server with its own login (`--jellyfin <file>`, see
|
||||||
[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md), Jellyfin relay), the server
|
[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md), Jellyfin relay), the server
|
||||||
fetches it itself instead.
|
fetches it itself instead.
|
||||||
- If nobody can pass it on (the person who put it up left), the app says
|
- If nobody can pass it on (the person who put it up left), the app says
|
||||||
"No Jellyfin account here for ..." with a button to link one; it plays as
|
"No Jellyfin account here for ..." with a button to link one; it plays as
|
||||||
soon as you are signed in.
|
soon as you are signed in.
|
||||||
|
|
||||||
Episodes: the ⏮ / ⏭ buttons next to the controls (or `<` / `>`,
|
Episodes: the ⏮ / ⏭ buttons next to play (or `<` / `>`,
|
||||||
Shift+P / Shift+N) put up the previous or next episode for everyone. From
|
Shift+P / Shift+N) put up the previous or next episode for everyone. From
|
||||||
the ending (when it is known, see Skipping above; else in the last two
|
the ending (when it is known, see Skipping above; else in the last two
|
||||||
minutes) a "Next episode" button floats in the corner. When an
|
minutes) a "Next episode" button floats in the corner while the controls
|
||||||
episode ends, a card shows what is next with Play next; with "Play the
|
are up. With "Play the next episode automatically" (Settings, on by
|
||||||
next episode automatically" (Settings, on by default) it counts down 10 s
|
default), the episode you put up continues with the next one: when it
|
||||||
first, and Cancel stops it on your screen (seeking back stops it for
|
ends, everyone sees a 10 s countdown, and anyone can cancel it (see Up
|
||||||
everyone). Anyone with an account can put the next one up; friends
|
next). Anyone with an account can put the next one up; friends watching
|
||||||
watching via the host cannot.
|
via the host cannot.
|
||||||
|
|
||||||
Audio and subtitles: the Audio and Subtitles buttons in the controls pick tracks.
|
Audio and subtitles: the Audio and Subtitles buttons in the controls pick tracks.
|
||||||
Your choice is remembered per series (and as a default) and the closest
|
Your choice is remembered per series (and as a default) and the closest
|
||||||
match (language, then title, then codec and channels) is selected on the
|
match (language, then title, then codec and channels) is selected on the
|
||||||
next episode. This is per person; nobody else is affected.
|
next episode. This is per person; nobody else is affected.
|
||||||
|
|
||||||
"Change video" in the player's controls opens the Library tab (the player
|
⚙ → Change video in the player opens the Library tab (the player
|
||||||
goes mini): the library starts on the series you are watching with the
|
goes mini): the library starts on the series you are watching with the
|
||||||
current season, else where you left it.
|
current season, else where you left it.
|
||||||
|
|
||||||
Anyone can put up a file from their own computer, also on a dedicated
|
Anyone can put up a file from their own computer, also on a dedicated
|
||||||
server: it streams from your computer through the server to everyone (the
|
server: it streams from your computer through the server to everyone (the
|
||||||
server keeps a few minutes in memory, so seeks and skipping the opening
|
server keeps a few minutes in memory, so seeks and skipping the opening
|
||||||
are quick). Keep the app open while it plays. For a link you choose how
|
are quick). Keep the app open while it plays. A link goes up "Through
|
||||||
the others get it:
|
me": your computer opens it and passes it on, so it plays for everyone
|
||||||
- Everyone fetches it (default): each app plays the link itself.
|
whenever it plays for you (you can't tell ahead which sites want cookies,
|
||||||
|
and YouTube may start asking any day). Under "Other ways" there are two more:
|
||||||
|
- Everyone fetches it: each app plays the link itself.
|
||||||
- Server fetches it: the server downloads it once for everyone, for links
|
- Server fetches it: the server downloads it once for everyone, for links
|
||||||
that are slow or blocked for some. The server must be able to reach it,
|
that are slow or blocked for some. The server must be able to reach it,
|
||||||
and it must have a password (an open server refuses: anyone could make
|
and it must have a password (an open server refuses: anyone could make
|
||||||
it fetch addresses only it can reach).
|
it fetch addresses only it can reach).
|
||||||
- Through me: your computer downloads it and passes it on, for links only
|
|
||||||
you can open.
|
|
||||||
|
|
||||||
Web pages work in all three: the app and the dedicated server each
|
Web pages work in all three: the app and the dedicated server each
|
||||||
download [yt-dlp](https://github.com/yt-dlp/yt-dlp) by themselves (checked
|
download [yt-dlp](https://github.com/yt-dlp/yt-dlp) by themselves (checked
|
||||||
@@ -349,14 +542,32 @@ export (picked or dropped; every site in it is kept). They stay on this
|
|||||||
computer and are used by its yt-dlp only (your own playback, "through
|
computer and are used by its yt-dlp only (your own playback, "through
|
||||||
me", and a server you host). Cookies log yt-dlp in as you on those
|
me", and a server you host). Cookies log yt-dlp in as you on those
|
||||||
sites: keep the file private, and for YouTube consider a throwaway
|
sites: keep the file private, and for YouTube consider a throwaway
|
||||||
account (Google may flag accounts used with yt-dlp).
|
account (Google may flag accounts used with yt-dlp). When a page shows
|
||||||
|
no video, the message says which cookies were used: none, your file
|
||||||
|
(and whether it has any for that site), or your browser's (and how many
|
||||||
|
it has for that site), so you know whether to sign in there or add
|
||||||
|
cookies.
|
||||||
YouTube works in all three too, and so do pages and links that only
|
YouTube works in all three too, and so do pages and links that only
|
||||||
offer streaming playlists (HLS `.m3u8`, DASH `.mpd`, the HLS of X videos).
|
offer streaming playlists (HLS `.m3u8`, DASH `.mpd`, the HLS of X videos).
|
||||||
The last two never show the link to anyone; they can't pass on live
|
Through me and Server fetches it never show the link to anyone; they can't pass on live
|
||||||
streams or DRM-protected video (use "Everyone fetches it" for live).
|
streams or DRM-protected video (use "Everyone fetches it" for live).
|
||||||
Your upload has to beat the video's bitrate: a 25-minute 2 GB episode is
|
Your upload has to beat the video's bitrate: a 25-minute 2 GB episode is
|
||||||
about 11 Mbit/s.
|
about 11 Mbit/s.
|
||||||
|
|
||||||
|
The member list (click the avatars) shows where the video comes from on
|
||||||
|
top: who passes it on, or that the server fetches it, everyone plays the
|
||||||
|
link, or everyone streams it from Jellyfin, with how many watch through
|
||||||
|
the server and, for a relay, how fast it arrives against what the video
|
||||||
|
needs (the bar's mark; past it is keeping up). It turns amber when the
|
||||||
|
source is too slow or its connection dropped ("Bob's connection dropped —
|
||||||
|
playing what the server has (2 min)"), red when it left (the others play
|
||||||
|
out what the server already has; the player's pill says the same and a
|
||||||
|
pop-up tells you once), and whoever passes it on is told once when their
|
||||||
|
upload is too slow. Each member's line says how they get it
|
||||||
|
("via server" with their speed, or "direct") after a dot for their
|
||||||
|
buffer: green enough to play on, amber low, red empty. A red dot on one
|
||||||
|
member while the source keeps up is their own connection.
|
||||||
|
|
||||||
## Video quality and shaders
|
## Video quality and shaders
|
||||||
|
|
||||||
Each viewer can run mpv GLSL shaders on their own picture; nobody else is
|
Each viewer can run mpv GLSL shaders on their own picture; nobody else is
|
||||||
@@ -365,9 +576,9 @@ affected. The app ships [Anime4K](https://github.com/bloc97/Anime4K) v4.0.1
|
|||||||
C (480p), A+A, B+B, C+A, each as HQ (strong GPUs, GTX 1080 and up) or Fast
|
C (480p), A+A, B+B, C+A, each as HQ (strong GPUs, GTX 1080 and up) or Fast
|
||||||
(the guide's low-end set). "Custom shaders" runs your own `.glsl` files.
|
(the guide's low-end set). "Custom shaders" runs your own `.glsl` files.
|
||||||
|
|
||||||
Pick one with the ✨ button in the player's control bar (also in
|
Pick one with ⚙ → Upscaling shader in the player (also in
|
||||||
fullscreen) or Ctrl+0..6; the change applies live and is saved, so the next
|
fullscreen) or Ctrl+0..6; the change applies live and is saved, so the next
|
||||||
session starts with it. The player's ⚙ and Settings → Player set it too,
|
session starts with it. ⚙ → Player settings and Settings → Player set it too,
|
||||||
with HQ or Fast (used by Ctrl+1..6); Settings → Player holds the custom
|
with HQ or Fast (used by Ctrl+1..6); Settings → Player holds the custom
|
||||||
files. Shaders cost GPU time
|
files. Shaders cost GPU time
|
||||||
every frame and need hardware video rendering: on media_kit's software
|
every frame and need hardware video rendering: on media_kit's software
|
||||||
@@ -379,7 +590,7 @@ fails to load shows a toast and switches shaders off.
|
|||||||
- "host offline - check address and port": wrong address, or the port is not open.
|
- "host offline - check address and port": wrong address, or the port is not open.
|
||||||
- "wrong server password": password mismatch.
|
- "wrong server password": password mismatch.
|
||||||
- "host runs a different version": update the app on both sides.
|
- "host runs a different version": update the app on both sides.
|
||||||
- Picture frozen but sound fine: Ctrl+R reloads the video; the app also does it automatically.
|
- Picture frozen but sound fine: Ctrl+R reloads the video.
|
||||||
- Everyone waits at "waiting for X": X has not buffered 4 seconds yet or has not pressed Space.
|
- Everyone waits at "waiting for X": X has not buffered 4 seconds yet or has not pressed Space.
|
||||||
- Windows: the build is new; if something is off there, say so.
|
- Windows: the build is new; if something is off there, say so.
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
|
|||||||
import 'src/screens/home/ui.dart';
|
import 'src/screens/home/ui.dart';
|
||||||
import 'src/shell/app_shell.dart';
|
import 'src/shell/app_shell.dart';
|
||||||
import 'src/widgets/app_keys.dart';
|
import 'src/widgets/app_keys.dart';
|
||||||
|
import 'src/widgets/app_menu.dart';
|
||||||
|
|
||||||
class WatchTogetherApp extends StatelessWidget {
|
class WatchTogetherApp extends StatelessWidget {
|
||||||
const WatchTogetherApp({super.key});
|
const WatchTogetherApp({super.key});
|
||||||
@@ -11,7 +12,9 @@ class WatchTogetherApp extends StatelessWidget {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return MaterialApp(
|
return MaterialApp(
|
||||||
title: appName,
|
title: appName,
|
||||||
theme: ThemeData.dark(),
|
// Material's own menus (the player's track menus, sort) wear the
|
||||||
|
// app menu's surface.
|
||||||
|
theme: AppMenuStyle.theme(ThemeData.dark()),
|
||||||
shortcuts: appShortcuts,
|
shortcuts: appShortcuts,
|
||||||
home: const AppKeys(child: AppShell()),
|
home: const AppKeys(child: AppShell()),
|
||||||
);
|
);
|
||||||
|
|||||||
+53
-42
@@ -3,17 +3,20 @@ import 'dart:io';
|
|||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:hive_ce_flutter/hive_flutter.dart';
|
import 'package:hive_ce_flutter/hive_flutter.dart';
|
||||||
import 'package:media_kit/media_kit.dart';
|
|
||||||
import 'package:sync_relay_core/core.dart';
|
import 'package:sync_relay_core/core.dart';
|
||||||
import 'package:window_manager/window_manager.dart';
|
|
||||||
|
|
||||||
import 'app.dart';
|
import 'app.dart';
|
||||||
import 'src/playback/yt_dlp_app.dart';
|
import 'src/app/app_graph.dart';
|
||||||
|
import 'src/files/thumbnails.dart' show thumbnailPlayers;
|
||||||
|
import 'src/platform/app_log.dart';
|
||||||
|
import 'src/platform/app_shutdown.dart' show closeAppWith;
|
||||||
|
import 'src/platform/desktop/desktop_app_dirs.dart';
|
||||||
import 'src/platform/desktop_entry.dart';
|
import 'src/platform/desktop_entry.dart';
|
||||||
|
import 'src/platform/smoke.dart';
|
||||||
import 'src/screens/home/ui.dart';
|
import 'src/screens/home/ui.dart';
|
||||||
import 'src/state/session_state.dart';
|
import 'src/session/app_events.dart' show UpdateAvailable;
|
||||||
import 'src/state/settings.dart';
|
import 'src/state/settings.dart';
|
||||||
import 'src/update/update_controller.dart' show launchArgs;
|
import 'src/update/update_controller.dart' show UpdateController, UpdatePhase, launchArgs;
|
||||||
|
|
||||||
Future<void> main(List<String> args) async {
|
Future<void> main(List<String> args) async {
|
||||||
launchArgs = List.unmodifiable(args);
|
launchArgs = List.unmodifiable(args);
|
||||||
@@ -40,51 +43,59 @@ Future<void> main(List<String> args) async {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
WidgetsFlutterBinding.ensureInitialized();
|
WidgetsFlutterBinding.ensureInitialized();
|
||||||
await windowManager.ensureInitialized();
|
final dirs = await const DesktopAppDirs().resolve();
|
||||||
await windowManager.setPreventClose(true);
|
await startAppLogging(dirs);
|
||||||
windowManager.addListener(_CloseGuard());
|
Hive.init(dirs.hive);
|
||||||
const windowOptions = WindowOptions(
|
|
||||||
size: Size(1280, 720),
|
|
||||||
minimumSize: Size(160, 90),
|
|
||||||
center: true,
|
|
||||||
backgroundColor: Color(0xFF000000),
|
|
||||||
titleBarStyle: TitleBarStyle.hidden,
|
|
||||||
title: appName,
|
|
||||||
);
|
|
||||||
windowManager.waitUntilReadyToShow(windowOptions, () async {
|
|
||||||
await windowManager.show();
|
|
||||||
await windowManager.focus();
|
|
||||||
});
|
|
||||||
await Hive.initFlutter();
|
|
||||||
await AppSettings.instance.ensureLoaded();
|
await AppSettings.instance.ensureLoaded();
|
||||||
|
// The composition root: every system, made once.
|
||||||
|
final graph = AppGraph.build();
|
||||||
|
// Sounds stay off after an audio-device crash (see SoundEngine.crashMark).
|
||||||
|
graph.sfx.engine.crashMark = '${dirs.support}${Platform.pathSeparator}audio-init.pending';
|
||||||
|
final ports = graph.ports;
|
||||||
|
// Close button / Alt+F4: the orderly close ([shutDownApp]), so others
|
||||||
|
// see "left", your server shuts down and no player outlives the engine.
|
||||||
|
final close = closeAppWith(graph);
|
||||||
|
await ports.shell.start(
|
||||||
|
title: dirs.profile == null ? appName : '$appName [${dirs.profile}]', onCloseRequest: () => close());
|
||||||
|
// Focus, minimise and restore feed auto sit-out and the Notifier (in
|
||||||
|
// the background, notices go out as system notifications).
|
||||||
|
ports.shell.watchActivity((a) {
|
||||||
|
graph.coordinator.windowActivity(a);
|
||||||
|
graph.notifier.window = a;
|
||||||
|
});
|
||||||
try {
|
try {
|
||||||
await SessionState.instance.loadForm();
|
await graph.forms.load();
|
||||||
} catch (e, st) {
|
} catch (e, st) {
|
||||||
debugPrint('load connect form failed: $e\n$st');
|
debugPrint('load connect form failed: $e\n$st');
|
||||||
}
|
}
|
||||||
MediaKit.ensureInitialized();
|
// The library's matches, pins and offsets, and the watch history
|
||||||
|
// (device-owned).
|
||||||
|
unawaited(graph.library.ensureLoaded());
|
||||||
|
unawaited(graph.watch.history.ensureLoaded());
|
||||||
|
ports.players.init();
|
||||||
|
thumbnailPlayers = ports.players;
|
||||||
// yt-dlp for web page links: downloaded on first run, kept current.
|
// yt-dlp for web page links: downloaded on first run, kept current.
|
||||||
AppYtDlp.instance.warmUp();
|
ports.links.warmUp();
|
||||||
// Linux: the launcher entry and icon Wayland needs (release installs).
|
// Linux: the launcher entry and icon Wayland needs (release installs).
|
||||||
unawaited(installDesktopEntry());
|
unawaited(installDesktopEntry());
|
||||||
runApp(const WatchTogetherApp());
|
// A found update is an event too (the band shows it).
|
||||||
}
|
final updates = UpdateController.instance;
|
||||||
|
updates.status.addListener(() {
|
||||||
/// Close button / Alt+F4: leave gracefully first (others see "left", a
|
final s = updates.status.value;
|
||||||
/// hosted server shuts down), bounded so a hung socket can't keep the
|
final version = s.manifest?.version;
|
||||||
/// window open.
|
if (s.phase == UpdatePhase.available && version != null) {
|
||||||
class _CloseGuard with WindowListener {
|
graph.notifier.notify(UpdateAvailable(version));
|
||||||
bool _closing = false;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> onWindowClose() async {
|
|
||||||
if (_closing) return;
|
|
||||||
_closing = true;
|
|
||||||
try {
|
|
||||||
await SessionState.instance.leave().timeout(const Duration(seconds: 2));
|
|
||||||
} catch (e) {
|
|
||||||
debugPrint('leave on close failed: $e');
|
|
||||||
}
|
}
|
||||||
await windowManager.destroy();
|
});
|
||||||
|
runApp(AppScope(graph: graph, child: const WatchTogetherApp()));
|
||||||
|
// CI's close smoke run: open a file, play, close (see smoke.dart).
|
||||||
|
final smoke = smokeMedia;
|
||||||
|
if (smoke != null) {
|
||||||
|
unawaited(WidgetsBinding.instance.endOfFrame.then((_) => runSmoke(graph, smoke)));
|
||||||
}
|
}
|
||||||
|
// Home: your own server, quietly (only this app can reach it until
|
||||||
|
// Invite).
|
||||||
|
unawaited(graph.navigation.start());
|
||||||
|
// The sound device opens once the window is up, not on the first sound.
|
||||||
|
Future.delayed(const Duration(seconds: 2), graph.sfx.warmUp);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
import 'package:flutter/widgets.dart';
|
||||||
|
|
||||||
|
import '../jellyfin/accounts.dart';
|
||||||
|
import '../library/library_store.dart';
|
||||||
|
import '../library/local_next.dart';
|
||||||
|
import '../library/show_matcher.dart';
|
||||||
|
import '../platform/app_log.dart' show appLogDir;
|
||||||
|
import '../platform/desktop/desktop_ports.dart';
|
||||||
|
import '../platform/ports/ports.dart';
|
||||||
|
import '../schedule/anilist.dart';
|
||||||
|
import '../schedule/animeflow.dart';
|
||||||
|
import '../screens/home/health_probe.dart';
|
||||||
|
import '../session/connection.dart' show Connection;
|
||||||
|
import '../session/identity.dart' show ClientIdentity, Profile;
|
||||||
|
import '../session/navigation.dart';
|
||||||
|
import '../session/notifier.dart';
|
||||||
|
import '../session/session_coordinator.dart';
|
||||||
|
import '../session/your_server.dart';
|
||||||
|
import '../sfx/sfx.dart';
|
||||||
|
import '../sfx/sound_bank.dart';
|
||||||
|
import '../sfx/synth_sfx.dart';
|
||||||
|
import '../state/connect_prefs.dart';
|
||||||
|
import '../state/settings.dart';
|
||||||
|
import '../watch/watch_history.dart';
|
||||||
|
import '../watch/watch_tracker.dart';
|
||||||
|
|
||||||
|
/// The composition root: builds the app's systems once (in `main`), wires
|
||||||
|
/// them through their constructors and disposes them. No logic and no
|
||||||
|
/// signals of its own. Widgets reach it through [AppScope].
|
||||||
|
class AppGraph {
|
||||||
|
/// The platform (window, links, folders, yt-dlp, notifications).
|
||||||
|
final Ports ports;
|
||||||
|
|
||||||
|
/// Owns the app's audio device ([SynthSfx.dispose] on close).
|
||||||
|
final SynthSfx sfx;
|
||||||
|
|
||||||
|
/// Every toast, sound, system notification and activity-log line.
|
||||||
|
final Notifier notifier;
|
||||||
|
|
||||||
|
/// The link to whichever server this app is in.
|
||||||
|
final Connection connection;
|
||||||
|
|
||||||
|
final SessionCoordinator coordinator;
|
||||||
|
|
||||||
|
/// The connect form and recent servers.
|
||||||
|
final ConnectStore forms;
|
||||||
|
|
||||||
|
/// This app's own server, alive for the whole run.
|
||||||
|
final YourServer yourServer;
|
||||||
|
|
||||||
|
/// Home (your server) or a friend's.
|
||||||
|
final Navigation navigation;
|
||||||
|
|
||||||
|
/// The library's matches (L2): local shows to AniList, pins, offsets.
|
||||||
|
final ShowMatcher library;
|
||||||
|
|
||||||
|
/// Watch tracking and the device's watch history (D3).
|
||||||
|
final WatchTracker watch;
|
||||||
|
|
||||||
|
AppGraph._({
|
||||||
|
required this.ports,
|
||||||
|
required this.sfx,
|
||||||
|
required this.notifier,
|
||||||
|
required this.connection,
|
||||||
|
required this.coordinator,
|
||||||
|
required this.forms,
|
||||||
|
required this.yourServer,
|
||||||
|
required this.navigation,
|
||||||
|
required this.library,
|
||||||
|
required this.watch,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The desktop app's graph. Tests pass their own [ports], [identity]
|
||||||
|
/// (default: the install's stored one), [healthGet] and server starter.
|
||||||
|
factory AppGraph.build({
|
||||||
|
Ports? ports,
|
||||||
|
ClientIdentity? identity,
|
||||||
|
HealthGetter healthGet = defaultHealthGet,
|
||||||
|
ServerStarter? serverStarter,
|
||||||
|
JellyfinAccounts? jellyfin,
|
||||||
|
ShowMatcher? library,
|
||||||
|
WatchHistory? history,
|
||||||
|
}) {
|
||||||
|
final p = ports ?? desktopPorts();
|
||||||
|
final settings = AppSettings.instance;
|
||||||
|
final sfx = SynthSfx(
|
||||||
|
volume: () => settings.soundVolume.peek(),
|
||||||
|
// A nudge is an explicit poke: it ignores its switch (not the volume).
|
||||||
|
enabled: (k) => k == SfxKind.nudge || !settings.soundsOff.peek().contains(k.name),
|
||||||
|
presetFor: soundPresetFor,
|
||||||
|
);
|
||||||
|
final notifier = Notifier(
|
||||||
|
sfx: sfx,
|
||||||
|
attention: p.shell.requestAttention,
|
||||||
|
system: p.notifications,
|
||||||
|
focusWindow: p.shell.focus,
|
||||||
|
prefs: () => settings.notifyPrefs,
|
||||||
|
);
|
||||||
|
final connection = Connection(notify: notifier.notify, identity: identity ?? ClientIdentity.stored());
|
||||||
|
// Device-owned: the watch history box.
|
||||||
|
final watch = WatchTracker(history: history ?? WatchHistory());
|
||||||
|
final coordinator = SessionCoordinator(
|
||||||
|
notifier: notifier,
|
||||||
|
connection: connection,
|
||||||
|
ytDlp: p.links,
|
||||||
|
jellyfin: jellyfin,
|
||||||
|
players: p.players,
|
||||||
|
settings: settings,
|
||||||
|
watch: watch);
|
||||||
|
// Device-owned: the library box; AnimeFlow's runs when signed in.
|
||||||
|
final matcher = library ??
|
||||||
|
ShowMatcher(
|
||||||
|
store: HiveLibraryStore(),
|
||||||
|
aniList: AniListClient(),
|
||||||
|
flow: AnimeFlowLookup(AnimeFlowClient.fromAccounts(coordinator.jellyfin)),
|
||||||
|
);
|
||||||
|
coordinator
|
||||||
|
..fileRef = matcher.refForPath
|
||||||
|
..nextFile = LocalNextFinder(matcher: matcher, scan: p.folders.scan).nextAfter;
|
||||||
|
final forms = ConnectStore();
|
||||||
|
final yourServer = YourServer(
|
||||||
|
forms: forms,
|
||||||
|
jellyfin: jellyfin,
|
||||||
|
// The app's yt-dlp folder; '' (the server's own default) when the
|
||||||
|
// app-support folder is not available.
|
||||||
|
ytDlpDir: () async {
|
||||||
|
try {
|
||||||
|
return (await p.links.ytDlp).dir;
|
||||||
|
} catch (_) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
logDir: () => appLogDir,
|
||||||
|
starter: serverStarter,
|
||||||
|
);
|
||||||
|
final navigation = Navigation(
|
||||||
|
coordinator: coordinator,
|
||||||
|
yourServer: yourServer,
|
||||||
|
forms: forms,
|
||||||
|
healthGet: healthGet,
|
||||||
|
);
|
||||||
|
// The profile keeps its name in the connect form and pushes changes
|
||||||
|
// to whichever server this app is in.
|
||||||
|
Profile.instance
|
||||||
|
..forms = forms
|
||||||
|
..push = ({String? name, String? avatar}) {
|
||||||
|
if (navigation.online.peek()) coordinator.updateProfile(name: name, avatar: avatar);
|
||||||
|
};
|
||||||
|
return AppGraph._(
|
||||||
|
ports: p,
|
||||||
|
sfx: sfx,
|
||||||
|
notifier: notifier,
|
||||||
|
connection: connection,
|
||||||
|
coordinator: coordinator,
|
||||||
|
forms: forms,
|
||||||
|
yourServer: yourServer,
|
||||||
|
navigation: navigation,
|
||||||
|
library: matcher,
|
||||||
|
watch: watch,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> dispose() async {
|
||||||
|
navigation.dispose();
|
||||||
|
await coordinator.dispose();
|
||||||
|
await watch.dispose();
|
||||||
|
await yourServer.stop();
|
||||||
|
await sfx.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The sound set [kind] plays from: its own pick in Settings, else the
|
||||||
|
/// overall one.
|
||||||
|
SoundPreset soundPresetFor(SfxKind kind) {
|
||||||
|
final s = AppSettings.instance;
|
||||||
|
final name = s.soundPresetFor.peek()[kind.name] ?? s.soundPreset.peek();
|
||||||
|
return SoundPreset.values.where((p) => p.name == name).firstOrNull ?? defaultPreset;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hands the [AppGraph] to every widget below: `AppScope.of(context)`.
|
||||||
|
/// The graph never changes, so reading it registers no dependency (safe
|
||||||
|
/// in `initState`).
|
||||||
|
class AppScope extends InheritedWidget {
|
||||||
|
final AppGraph graph;
|
||||||
|
const AppScope({super.key, required this.graph, required super.child});
|
||||||
|
|
||||||
|
static AppGraph of(BuildContext context) {
|
||||||
|
final scope = context.getInheritedWidgetOfExactType<AppScope>();
|
||||||
|
assert(scope != null, 'no AppScope above this widget');
|
||||||
|
return scope!.graph;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool updateShouldNotify(AppScope oldWidget) => !identical(graph, oldWidget.graph);
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:sync_relay_core/core.dart' show JellyfinStreamType;
|
||||||
|
|
||||||
|
import '../jellyfin/track_prefs.dart' show MpvTrack;
|
||||||
|
import '../playback/media_marks.dart';
|
||||||
|
import '../shaders/shader_menu.dart';
|
||||||
|
import '../shell/mark_problem.dart';
|
||||||
|
import '../state/settings.dart';
|
||||||
|
import '../widgets/app_menu.dart';
|
||||||
|
import '../widgets/copy_open.dart';
|
||||||
|
import 'frame.dart';
|
||||||
|
import 'model/controls_layout.dart';
|
||||||
|
import 'model/controls_model.dart';
|
||||||
|
import 'player_settings.dart';
|
||||||
|
|
||||||
|
// The controls' menus, shared by both skins: the track and chapter lists
|
||||||
|
// and the ⚙ menu, all on the app's menu (`showAppMenu`), anchored on the
|
||||||
|
// button that opens them. Each keeps the controls up while open.
|
||||||
|
|
||||||
|
/// How many tracks of [type] there are.
|
||||||
|
int trackCount(List<MpvTrack> tracks, JellyfinStreamType type) => tracks.where((t) => t.type == type).length;
|
||||||
|
|
||||||
|
/// The audio or subtitle tracks ("Japanese · E-AC3 2.0 · title"), mpv's
|
||||||
|
/// selection checked; subtitles start with Off.
|
||||||
|
List<AppMenuItem<TrackPick>> trackMenuItems(JellyfinStreamType type, List<MpvTrack> tracks) {
|
||||||
|
final audio = type == JellyfinStreamType.audio;
|
||||||
|
final list = tracks.where((t) => t.type == type).toList();
|
||||||
|
return [
|
||||||
|
if (!audio)
|
||||||
|
AppMenuItem(
|
||||||
|
key: const ValueKey('track-off'),
|
||||||
|
value: (aid: null, sid: null, subtitlesOff: true),
|
||||||
|
label: 'Off',
|
||||||
|
checked: !list.any((t) => t.selected),
|
||||||
|
),
|
||||||
|
if (audio && list.isEmpty)
|
||||||
|
const AppMenuItem(value: (aid: null, sid: null, subtitlesOff: false), label: 'None', enabled: false),
|
||||||
|
for (final t in list)
|
||||||
|
AppMenuItem(
|
||||||
|
key: ValueKey('track-${t.type.name}-${t.id}'),
|
||||||
|
value: audio ? (aid: t.id, sid: null, subtitlesOff: false) : (aid: null, sid: t.id, subtitlesOff: false),
|
||||||
|
label: t.label,
|
||||||
|
checked: t.selected,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Chapters with their start times, the playing one checked.
|
||||||
|
List<AppMenuItem<MediaChapter>> chapterMenuItems(List<MediaChapter> chapters, int? current) => [
|
||||||
|
for (final c in chapters)
|
||||||
|
AppMenuItem(
|
||||||
|
key: ValueKey('chapter-${c.index}'),
|
||||||
|
value: c,
|
||||||
|
label: c.title.isEmpty ? 'Chapter ${c.index + 1}' : c.title,
|
||||||
|
hint: formatClock(c.start),
|
||||||
|
checked: c.index == current,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
Future<T?> _menu<T>(BuildContext context, PlayerControlsModel model, List<AppMenuItem<T>> items) async {
|
||||||
|
model.menusOpen++;
|
||||||
|
try {
|
||||||
|
return await showAppMenu<T>(context, items: items);
|
||||||
|
} finally {
|
||||||
|
model.menusOpen--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The audio or subtitle list; a pick is applied (and remembered).
|
||||||
|
Future<void> openTrackMenu(BuildContext context, PlayerControlsModel model, JellyfinStreamType type) async {
|
||||||
|
final pick = await _menu(context, model, trackMenuItems(type, model.tracks.peek()));
|
||||||
|
if (pick != null) model.pickTrack(pick);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The chapter list; a pick jumps there for everyone.
|
||||||
|
Future<void> openChapterMenu(BuildContext context, PlayerControlsModel model) async {
|
||||||
|
final pick = await _menu(context, model, chapterMenuItems(model.chapters.peek(), model.currentChapter.peek()));
|
||||||
|
if (pick != null) model.pickChapter(pick);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ⚙ menu: every action that is not a bar button.
|
||||||
|
Future<void> openControlsMenu(BuildContext context, PlayerControlsModel model) async {
|
||||||
|
final s = AppSettings.instance;
|
||||||
|
final shader = shaderShortLabel(s.shaderPreset.peek(), s.shaderQuality.peek()) ?? 'Off';
|
||||||
|
final pick = await _menu(context, model, [
|
||||||
|
for (final a in model.menu())
|
||||||
|
AppMenuItem(
|
||||||
|
key: ValueKey('controls-menu-${a.name}'),
|
||||||
|
value: a,
|
||||||
|
label: a.label,
|
||||||
|
hint: a == ControlAction.shaders ? shader : a.hint,
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
if (pick != null && context.mounted) await runControlAction(context, model, pick);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs a ⚙ menu action; [context] anchors what it opens next.
|
||||||
|
Future<void> runControlAction(BuildContext context, PlayerControlsModel model, ControlAction action) async {
|
||||||
|
switch (action) {
|
||||||
|
case ControlAction.chapters:
|
||||||
|
await openChapterMenu(context, model);
|
||||||
|
case ControlAction.subtitles:
|
||||||
|
await openTrackMenu(context, model, JellyfinStreamType.subtitle);
|
||||||
|
case ControlAction.audio:
|
||||||
|
await openTrackMenu(context, model, JellyfinStreamType.audio);
|
||||||
|
case ControlAction.skipForward:
|
||||||
|
model.skipForward();
|
||||||
|
case ControlAction.shaders:
|
||||||
|
model.menusOpen++;
|
||||||
|
try {
|
||||||
|
await ControlsFrame.holdWhile(
|
||||||
|
context,
|
||||||
|
() => showShaderMenu(context, renderMode: model.renderMode, onPick: model.pickShader),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
model.menusOpen--;
|
||||||
|
}
|
||||||
|
case ControlAction.chat:
|
||||||
|
model.toggleChat();
|
||||||
|
case ControlAction.changeVideo:
|
||||||
|
model.changeVideo();
|
||||||
|
case ControlAction.copyLink:
|
||||||
|
final link = model.link();
|
||||||
|
if (link != null) await copyToClipboard(context, link, done: 'Link copied');
|
||||||
|
case ControlAction.reload:
|
||||||
|
model.reload();
|
||||||
|
case ControlAction.markAllReady:
|
||||||
|
model.markAllReady();
|
||||||
|
case ControlAction.markProblem:
|
||||||
|
await ControlsFrame.holdWhile(context, () => showMarkProblem(context));
|
||||||
|
case ControlAction.playerSettings:
|
||||||
|
await showPlayerSettings(context, renderMode: model.renderMode);
|
||||||
|
case ControlAction.leave:
|
||||||
|
model.leave();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,57 +2,74 @@ import 'dart:async';
|
|||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
/// Follows whether media_kit's desktop controls around [child] are up,
|
/// What keeps the player's controls up besides the mouse on them: the
|
||||||
/// by the same rule they use: up on mount and on any mouse movement,
|
/// mouse on a floating element over the picture (a pill, a card, the
|
||||||
/// down [hideAfter] later or when the mouse leaves. media_kit does not
|
/// status pill: [ControlsHoldRegion]) or an open popover. While anything
|
||||||
/// expose its visibility; this lets the player draw a progress line while
|
/// holds, the controls stay up; on release they hide on their usual
|
||||||
/// they are down. Never takes input.
|
/// countdown. Both skins follow it (through `ControlsFrame`).
|
||||||
class ControlsHoverProbe extends StatefulWidget {
|
class ControlsHold extends ChangeNotifier {
|
||||||
final ValueNotifier<bool> shown;
|
final _by = <Object>{};
|
||||||
final Duration hideAfter;
|
bool _told = false;
|
||||||
final Widget child;
|
bool _queued = false;
|
||||||
const ControlsHoverProbe({super.key, required this.shown, required this.hideAfter, required this.child});
|
bool _disposed = false;
|
||||||
|
|
||||||
@override
|
bool get held => _told;
|
||||||
State<ControlsHoverProbe> createState() => _ControlsHoverProbeState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _ControlsHoverProbeState extends State<ControlsHoverProbe> {
|
/// [who] holds ([on]) or lets go. Listeners hear it in a microtask, never
|
||||||
Timer? _timer;
|
/// during a build or a dispose.
|
||||||
|
void set(Object who, bool on) {
|
||||||
@override
|
if (on ? !_by.add(who) : !_by.remove(who)) return;
|
||||||
void initState() {
|
if (_queued) return;
|
||||||
super.initState();
|
_queued = true;
|
||||||
// Not during this build: the line listening to [shown] may be built.
|
scheduleMicrotask(() {
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
_queued = false;
|
||||||
if (mounted) _wake();
|
if (_disposed) return;
|
||||||
|
final now = _by.isNotEmpty;
|
||||||
|
if (now == _told) return;
|
||||||
|
_told = now;
|
||||||
|
notifyListeners();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
_timer?.cancel();
|
_disposed = true;
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void _wake() {
|
/// The mouse on [child] counts as the mouse on the controls: it holds
|
||||||
widget.shown.value = true;
|
/// [hold] while it is there.
|
||||||
_timer?.cancel();
|
class ControlsHoldRegion extends StatefulWidget {
|
||||||
_timer = Timer(widget.hideAfter, _hide);
|
final ControlsHold? hold;
|
||||||
}
|
final Widget child;
|
||||||
|
const ControlsHoldRegion({super.key, required this.hold, required this.child});
|
||||||
|
|
||||||
void _hide() {
|
@override
|
||||||
_timer?.cancel();
|
State<ControlsHoldRegion> createState() => _ControlsHoldRegionState();
|
||||||
if (mounted) widget.shown.value = false;
|
}
|
||||||
|
|
||||||
|
class _ControlsHoldRegionState extends State<ControlsHoldRegion> {
|
||||||
|
@override
|
||||||
|
void didUpdateWidget(ControlsHoldRegion oldWidget) {
|
||||||
|
super.didUpdateWidget(oldWidget);
|
||||||
|
if (oldWidget.hold != widget.hold) oldWidget.hold?.set(this, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) => MouseRegion(
|
void dispose() {
|
||||||
opaque: false,
|
widget.hold?.set(this, false);
|
||||||
hitTestBehavior: HitTestBehavior.translucent,
|
super.dispose();
|
||||||
onEnter: (_) => _wake(),
|
}
|
||||||
onHover: (_) => _wake(),
|
|
||||||
onExit: (_) => _hide(),
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final hold = widget.hold;
|
||||||
|
if (hold == null) return widget.child;
|
||||||
|
return MouseRegion(
|
||||||
|
onEnter: (_) => hold.set(this, true),
|
||||||
|
onExit: (_) => hold.set(this, false),
|
||||||
child: widget.child,
|
child: widget.child,
|
||||||
);
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/gestures.dart' show kPrimaryMouseButton;
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'controls_probe.dart' show ControlsHold;
|
||||||
|
|
||||||
|
// The frame both control skins live in: when the controls are up, and the
|
||||||
|
// double-click on the picture. Mouse movement shows them; [hideAfter]
|
||||||
|
// without any (or the mouse leaving) hides them and the cursor. Holds keep
|
||||||
|
// them up: a seek drag (no hover events arrive), an open menu (a route
|
||||||
|
// takes the mouse), and the session's [ControlsHold] (the mouse on a
|
||||||
|
// floating pill or card, the Up next popover).
|
||||||
|
|
||||||
|
class ControlsFrame extends StatefulWidget {
|
||||||
|
/// Draws the controls; [visible] false while they are hidden.
|
||||||
|
final Widget Function(BuildContext context, bool visible) builder;
|
||||||
|
final VoidCallback? onDoubleClick;
|
||||||
|
|
||||||
|
/// Bands at the top and bottom where a double-click is the bars', not
|
||||||
|
/// the picture's.
|
||||||
|
final double barTop;
|
||||||
|
final double barBottom;
|
||||||
|
final Duration hideAfter;
|
||||||
|
|
||||||
|
/// Follows whether the controls are up (for overlays outside them).
|
||||||
|
final ValueNotifier<bool>? shown;
|
||||||
|
|
||||||
|
/// Keeps them up while held.
|
||||||
|
final ControlsHold? holdBy;
|
||||||
|
const ControlsFrame({
|
||||||
|
super.key,
|
||||||
|
required this.builder,
|
||||||
|
this.onDoubleClick,
|
||||||
|
this.barTop = 0,
|
||||||
|
this.barBottom = 0,
|
||||||
|
this.hideAfter = const Duration(seconds: 3),
|
||||||
|
this.shown,
|
||||||
|
this.holdBy,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The frame around [context], for widgets that keep it up (a drag, a
|
||||||
|
/// menu).
|
||||||
|
static ControlsFrameState? maybeOf(BuildContext context) => context.findAncestorStateOfType<ControlsFrameState>();
|
||||||
|
|
||||||
|
/// Runs [open] (a menu, a popover) with the controls around [context]
|
||||||
|
/// held up, if there are any.
|
||||||
|
static Future<T> holdWhile<T>(BuildContext context, Future<T> Function() open) {
|
||||||
|
final frame = maybeOf(context);
|
||||||
|
return frame == null ? open() : frame.holdDuring(open);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fade of the controls.
|
||||||
|
static const fade = Duration(milliseconds: 150);
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<ControlsFrame> createState() => ControlsFrameState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class ControlsFrameState extends State<ControlsFrame> {
|
||||||
|
bool _visible = true;
|
||||||
|
int _holds = 0;
|
||||||
|
bool _heldBy = false;
|
||||||
|
Timer? _timer;
|
||||||
|
|
||||||
|
bool get visible => _visible;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
widget.holdBy?.addListener(_holdByChanged);
|
||||||
|
// Not during this build: an overlay listening to [shown] may be built.
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
|
if (mounted) widget.shown?.value = true;
|
||||||
|
});
|
||||||
|
_hideLater();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didUpdateWidget(ControlsFrame oldWidget) {
|
||||||
|
super.didUpdateWidget(oldWidget);
|
||||||
|
if (oldWidget.holdBy != widget.holdBy) {
|
||||||
|
oldWidget.holdBy?.removeListener(_holdByChanged);
|
||||||
|
widget.holdBy?.addListener(_holdByChanged);
|
||||||
|
_holdByChanged();
|
||||||
|
}
|
||||||
|
if (oldWidget.hideAfter != widget.hideAfter && _visible) _hideLater();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
widget.holdBy?.removeListener(_holdByChanged);
|
||||||
|
_timer?.cancel();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _holdByChanged() {
|
||||||
|
final on = widget.holdBy?.held ?? false;
|
||||||
|
if (on == _heldBy || !mounted) return;
|
||||||
|
_heldBy = on;
|
||||||
|
hold(on);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Show the controls and restart the hide countdown.
|
||||||
|
void wake() {
|
||||||
|
if (!_visible && mounted) {
|
||||||
|
setState(() => _visible = true);
|
||||||
|
widget.shown?.value = true;
|
||||||
|
}
|
||||||
|
_hideLater();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keep the controls up while [on] (paired calls).
|
||||||
|
void hold(bool on) {
|
||||||
|
_holds = on ? _holds + 1 : (_holds - 1).clamp(0, 1 << 20);
|
||||||
|
wake();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs [open] (a menu) with the controls held up.
|
||||||
|
Future<T> holdDuring<T>(Future<T> Function() open) async {
|
||||||
|
hold(true);
|
||||||
|
try {
|
||||||
|
return await open();
|
||||||
|
} finally {
|
||||||
|
if (mounted) hold(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _hideLater() {
|
||||||
|
_timer?.cancel();
|
||||||
|
_timer = Timer(widget.hideAfter, _hide);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _hide() {
|
||||||
|
if (!mounted || _holds > 0 || !_visible) return;
|
||||||
|
setState(() => _visible = false);
|
||||||
|
widget.shown?.value = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return MouseRegion(
|
||||||
|
cursor: _visible ? SystemMouseCursors.basic : SystemMouseCursors.none,
|
||||||
|
onEnter: (_) => wake(),
|
||||||
|
onHover: (_) => wake(),
|
||||||
|
onExit: (_) {
|
||||||
|
_timer?.cancel();
|
||||||
|
_hide();
|
||||||
|
},
|
||||||
|
child: Stack(
|
||||||
|
fit: StackFit.expand,
|
||||||
|
children: [
|
||||||
|
if (widget.onDoubleClick != null)
|
||||||
|
Positioned.fill(
|
||||||
|
child: DoubleClickListener(
|
||||||
|
onDoubleClick: widget.onDoubleClick!,
|
||||||
|
skipTop: _visible ? widget.barTop : 0,
|
||||||
|
skipBottom: _visible ? widget.barBottom : 0,
|
||||||
|
child: const ColoredBox(color: Color(0x00000000), child: SizedBox.expand()),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
widget.builder(context, _visible),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Double-click on the picture (not on the bars) without joining the
|
||||||
|
/// gesture arena, so single clicks on buttons stay instant.
|
||||||
|
class DoubleClickListener extends StatefulWidget {
|
||||||
|
final VoidCallback onDoubleClick;
|
||||||
|
final double skipTop, skipBottom;
|
||||||
|
final Widget child;
|
||||||
|
const DoubleClickListener({
|
||||||
|
super.key,
|
||||||
|
required this.onDoubleClick,
|
||||||
|
this.skipTop = 0,
|
||||||
|
this.skipBottom = 0,
|
||||||
|
required this.child,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<DoubleClickListener> createState() => _DoubleClickListenerState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _DoubleClickListenerState extends State<DoubleClickListener> {
|
||||||
|
DateTime? _last;
|
||||||
|
Offset? _lastAt;
|
||||||
|
|
||||||
|
void _down(PointerDownEvent e) {
|
||||||
|
if (e.buttons != kPrimaryMouseButton) return;
|
||||||
|
final h = context.size?.height ?? 0;
|
||||||
|
final y = e.localPosition.dy;
|
||||||
|
if (y < widget.skipTop || y > h - widget.skipBottom) {
|
||||||
|
_last = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final now = DateTime.now();
|
||||||
|
final last = _last, at = _lastAt;
|
||||||
|
if (last != null &&
|
||||||
|
at != null &&
|
||||||
|
now.difference(last) < const Duration(milliseconds: 400) &&
|
||||||
|
(e.localPosition - at).distance < 24) {
|
||||||
|
_last = null;
|
||||||
|
widget.onDoubleClick();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_last = now;
|
||||||
|
_lastAt = e.localPosition;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) =>
|
||||||
|
Listener(behavior: HitTestBehavior.translucent, onPointerDown: _down, child: widget.child);
|
||||||
|
}
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:signals/signals_flutter.dart';
|
||||||
|
import 'package:sync_relay_core/core.dart' show JellyfinStreamType;
|
||||||
|
|
||||||
|
import '../../queue/queue_ui.dart';
|
||||||
|
import '../../shell/now_playing_title.dart';
|
||||||
|
import '../../state/settings.dart';
|
||||||
|
import '../control_menus.dart';
|
||||||
|
import '../controls_probe.dart' show ControlsHold;
|
||||||
|
import '../frame.dart';
|
||||||
|
import '../model/controls_layout.dart';
|
||||||
|
import '../model/controls_model.dart';
|
||||||
|
import '../model/controls_prefs.dart';
|
||||||
|
import '../volume.dart';
|
||||||
|
import 'style.dart';
|
||||||
|
import 'timeline.dart';
|
||||||
|
|
||||||
|
// The Minimal skin (inspired by mpv's uosc): a timeline band across the
|
||||||
|
// bottom that carries the clock, and above it the buttons in two glass
|
||||||
|
// capsules, in the layout's order. Top: what plays, Up next and the window
|
||||||
|
// controls. Hidden, the band shrinks to a thin progress line (unless
|
||||||
|
// switched off).
|
||||||
|
|
||||||
|
class MinimalControls extends StatelessWidget {
|
||||||
|
final PlayerControlsModel model;
|
||||||
|
final bool visible;
|
||||||
|
final double scale;
|
||||||
|
final ControlsHold? hold;
|
||||||
|
final Widget? windowButtons;
|
||||||
|
const MinimalControls({
|
||||||
|
super.key,
|
||||||
|
required this.model,
|
||||||
|
required this.visible,
|
||||||
|
this.scale = 1,
|
||||||
|
this.hold,
|
||||||
|
this.windowButtons,
|
||||||
|
});
|
||||||
|
|
||||||
|
static const _rowGap = 8.0;
|
||||||
|
|
||||||
|
/// The button row's height at [scale] (a capsule).
|
||||||
|
static double rowHeight(double scale) => MinimalStyle.button * scale + 2 * MinimalStyle.capsulePad;
|
||||||
|
|
||||||
|
/// Buttons and timeline at [scale].
|
||||||
|
static double bottomHeight(double scale) => rowHeight(scale) + _rowGap + MinimalTimeline.heightFor(scale);
|
||||||
|
|
||||||
|
/// The top bar's height.
|
||||||
|
static const topHeight = 72.0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
const fade = ControlsFrame.fade;
|
||||||
|
Widget shown(Widget child, {Key? key}) => IgnorePointer(
|
||||||
|
key: key,
|
||||||
|
ignoring: !visible,
|
||||||
|
child: AnimatedOpacity(duration: fade, opacity: visible ? 1 : 0, child: child),
|
||||||
|
);
|
||||||
|
return Stack(
|
||||||
|
children: [
|
||||||
|
Positioned(
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
top: 0,
|
||||||
|
child: shown(
|
||||||
|
key: const ValueKey('minimal-top'),
|
||||||
|
DecoratedBox(
|
||||||
|
decoration: const BoxDecoration(
|
||||||
|
gradient: LinearGradient(
|
||||||
|
begin: Alignment.topCenter,
|
||||||
|
end: Alignment.bottomCenter,
|
||||||
|
colors: [Color(0x99000000), Color(0x00000000)],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: SizedBox(
|
||||||
|
height: topHeight + 24,
|
||||||
|
child: Padding(padding: const EdgeInsets.fromLTRB(16, 0, 10, 24), child: _top()),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Positioned(
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
bottom: 0,
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
shown(
|
||||||
|
key: const ValueKey('minimal-buttons'),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(12, 0, 12, _rowGap),
|
||||||
|
child: SizedBox(
|
||||||
|
height: rowHeight(scale),
|
||||||
|
child: SignalBuilder(
|
||||||
|
builder: (context) {
|
||||||
|
final s = model.snapshot.value;
|
||||||
|
final layout = model.bar.value;
|
||||||
|
// The clock lives on the timeline.
|
||||||
|
List<Widget> cluster(List<BarControl> cs) => [
|
||||||
|
for (final c in cs)
|
||||||
|
if (c != BarControl.time) _control(context, c, s),
|
||||||
|
];
|
||||||
|
return Row(
|
||||||
|
children: [
|
||||||
|
MinimalCapsule(scale: scale, children: cluster(layout.left)),
|
||||||
|
const Spacer(),
|
||||||
|
MinimalCapsule(scale: scale, children: cluster(layout.right)),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SignalBuilder(
|
||||||
|
builder: (context) {
|
||||||
|
final line = AppSettings.instance.progressLine.value;
|
||||||
|
return AnimatedOpacity(
|
||||||
|
key: const ValueKey('minimal-timeline-wrap'),
|
||||||
|
duration: fade,
|
||||||
|
opacity: visible || line ? 1 : 0,
|
||||||
|
child: MinimalTimeline(
|
||||||
|
position: model.position.value,
|
||||||
|
duration: model.duration.value,
|
||||||
|
buffered: model.buffered.value,
|
||||||
|
chapters: model.chapters.value,
|
||||||
|
expanded: visible,
|
||||||
|
remaining: model.settings.timeDisplay.value == TimeDisplay.remaining,
|
||||||
|
scale: scale,
|
||||||
|
onSeek: model.seek,
|
||||||
|
onToggleTime: model.toggleTimeDisplay,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _top() {
|
||||||
|
final m = model;
|
||||||
|
return Row(
|
||||||
|
children: [
|
||||||
|
const Expanded(
|
||||||
|
child: Align(alignment: AlignmentDirectional.centerStart, child: NowPlayingTitle()),
|
||||||
|
),
|
||||||
|
UpNextButton(queue: m.queue, look: UpNextLook.minimal, hold: hold),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
SignalBuilder(
|
||||||
|
builder: (context) {
|
||||||
|
final full = m.fullscreen.value;
|
||||||
|
return MinimalButton(
|
||||||
|
key: const ValueKey('minimal-collapse'),
|
||||||
|
icon: full ? Icons.fullscreen_exit_rounded : Icons.close_fullscreen_rounded,
|
||||||
|
tooltip: full ? 'Exit fullscreen (Esc)' : 'Back to the library (keeps playing)',
|
||||||
|
onPressed: full ? m.toggleFullscreen : m.collapse,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
?windowButtons,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _control(BuildContext context, BarControl c, ControlsSnapshot s) {
|
||||||
|
final m = model;
|
||||||
|
final key = ValueKey('control-${c.name}');
|
||||||
|
final enabled = controlEnabled(c, s);
|
||||||
|
Widget button(VoidCallback? onPressed, {int? badge, bool accent = false}) => MinimalButton(
|
||||||
|
key: key,
|
||||||
|
icon: controlIcon(c, s),
|
||||||
|
tooltip: controlTooltip(c, s),
|
||||||
|
badge: badge,
|
||||||
|
accent: accent,
|
||||||
|
scale: scale,
|
||||||
|
onPressed: enabled ? onPressed : null,
|
||||||
|
);
|
||||||
|
switch (c) {
|
||||||
|
case BarControl.playPause:
|
||||||
|
return Padding(
|
||||||
|
padding: EdgeInsets.only(right: 4 * scale),
|
||||||
|
child: button(m.togglePlay, accent: true),
|
||||||
|
);
|
||||||
|
case BarControl.previous:
|
||||||
|
return button(m.previous);
|
||||||
|
case BarControl.next:
|
||||||
|
return button(m.next);
|
||||||
|
case BarControl.chapterPrevious:
|
||||||
|
return button(() => m.stepChapter(-1));
|
||||||
|
case BarControl.chapterNext:
|
||||||
|
return button(() => m.stepChapter(1));
|
||||||
|
case BarControl.volume:
|
||||||
|
return SignalBuilder(
|
||||||
|
key: key,
|
||||||
|
builder: (context) => VolumeControl(
|
||||||
|
volume: m.volume.value,
|
||||||
|
onChanged: m.setVolume,
|
||||||
|
onToggleMute: m.toggleMute,
|
||||||
|
sliderColor: Theme.of(context).colorScheme.primary,
|
||||||
|
trackColor: MinimalStyle.dim.withValues(alpha: 0.4),
|
||||||
|
button: (context, i, color, tip, onPressed) =>
|
||||||
|
MinimalButton(icon: i, tooltip: tip, color: color, scale: scale, onPressed: onPressed),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
case BarControl.time:
|
||||||
|
return const SizedBox.shrink();
|
||||||
|
case BarControl.subtitles || BarControl.audio:
|
||||||
|
final type = c == BarControl.audio ? JellyfinStreamType.audio : JellyfinStreamType.subtitle;
|
||||||
|
return SignalBuilder(
|
||||||
|
key: key,
|
||||||
|
builder: (context) => Builder(
|
||||||
|
builder: (context) => MinimalButton(
|
||||||
|
icon: controlIcon(c, s),
|
||||||
|
tooltip: controlTooltip(c, s),
|
||||||
|
badge: trackCount(m.tracks.value, type),
|
||||||
|
scale: scale,
|
||||||
|
onPressed: () => openTrackMenu(context, m, type),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
case BarControl.settings:
|
||||||
|
return Builder(
|
||||||
|
key: key,
|
||||||
|
builder: (context) => MinimalButton(
|
||||||
|
icon: controlIcon(c, s),
|
||||||
|
tooltip: controlTooltip(c, s),
|
||||||
|
scale: scale,
|
||||||
|
onPressed: () => openControlsMenu(context, m),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
case BarControl.chat:
|
||||||
|
return SignalBuilder(
|
||||||
|
key: key,
|
||||||
|
builder: (context) => MinimalButton(
|
||||||
|
icon: controlIcon(c, s),
|
||||||
|
tooltip: controlTooltip(c, s),
|
||||||
|
badge: m.unread.value,
|
||||||
|
scale: scale,
|
||||||
|
onPressed: m.toggleChat,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
case BarControl.fullscreen:
|
||||||
|
return button(m.toggleFullscreen);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../../widgets/app_menu.dart' show AppMenuStyle;
|
||||||
|
|
||||||
|
// The Minimal skin's look: the app's glass and accent (the theme's primary)
|
||||||
|
// on a thick timeline band, with soft rounded buttons in two glass capsules.
|
||||||
|
|
||||||
|
abstract final class MinimalStyle {
|
||||||
|
/// The timeline band (no blur: it spans the width over the picture).
|
||||||
|
static const band = Color(0xCC0E0E12);
|
||||||
|
|
||||||
|
/// The capsules holding the buttons: the player pills' glass.
|
||||||
|
static const capsule = AppMenuStyle.pillGlass;
|
||||||
|
static const hover = Color(0x1FFFFFFF);
|
||||||
|
static const text = Colors.white;
|
||||||
|
static const dim = Color(0xB3FFFFFF);
|
||||||
|
static const radius = 10.0;
|
||||||
|
static const fontSize = 13.0;
|
||||||
|
|
||||||
|
/// The tooltips and the timeline's hover tip.
|
||||||
|
static const tip = Color(0xEB18181C);
|
||||||
|
|
||||||
|
/// A button's box at scale 1.
|
||||||
|
static const button = 38.0;
|
||||||
|
|
||||||
|
/// The capsules' padding around the buttons.
|
||||||
|
static const capsulePad = 4.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Minimal skin's tooltip: the app's dark glass colour, above.
|
||||||
|
class MinimalTooltip extends StatelessWidget {
|
||||||
|
final String message;
|
||||||
|
final Widget child;
|
||||||
|
const MinimalTooltip({super.key, required this.message, required this.child});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
if (message.isEmpty) return child;
|
||||||
|
return Tooltip(
|
||||||
|
message: message,
|
||||||
|
preferBelow: false,
|
||||||
|
verticalOffset: 28,
|
||||||
|
waitDuration: const Duration(milliseconds: 300),
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: MinimalStyle.tip,
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
border: Border.all(color: AppMenuStyle.border, width: 0.5),
|
||||||
|
),
|
||||||
|
textStyle: const TextStyle(color: MinimalStyle.text, fontSize: 12),
|
||||||
|
child: child,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Minimal button: a white icon on a rounded square that lights on hover
|
||||||
|
/// ([accent]: filled with the theme's primary, the play button), an
|
||||||
|
/// optional [label] and a count [badge]. Never takes focus.
|
||||||
|
class MinimalButton extends StatefulWidget {
|
||||||
|
final IconData icon;
|
||||||
|
final String tooltip;
|
||||||
|
final VoidCallback? onPressed;
|
||||||
|
final String? label;
|
||||||
|
final int? badge;
|
||||||
|
final bool accent;
|
||||||
|
final Color? color;
|
||||||
|
final double scale;
|
||||||
|
const MinimalButton({
|
||||||
|
super.key,
|
||||||
|
required this.icon,
|
||||||
|
required this.tooltip,
|
||||||
|
required this.onPressed,
|
||||||
|
this.label,
|
||||||
|
this.badge,
|
||||||
|
this.accent = false,
|
||||||
|
this.color,
|
||||||
|
this.scale = 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<MinimalButton> createState() => _MinimalButtonState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _MinimalButtonState extends State<MinimalButton> {
|
||||||
|
bool _hover = false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final w = widget;
|
||||||
|
final primary = Theme.of(context).colorScheme.primary;
|
||||||
|
final onPrimary = Theme.of(context).colorScheme.onPrimary;
|
||||||
|
final enabled = w.onPressed != null;
|
||||||
|
final size = MinimalStyle.button * w.scale;
|
||||||
|
final fg = !enabled
|
||||||
|
? MinimalStyle.dim.withValues(alpha: 0.35)
|
||||||
|
: w.accent
|
||||||
|
? onPrimary
|
||||||
|
: (w.color ?? MinimalStyle.text);
|
||||||
|
final bg = w.accent
|
||||||
|
? (_hover ? Color.lerp(primary, Colors.white, 0.18)! : primary)
|
||||||
|
: (_hover && enabled ? MinimalStyle.hover : Colors.transparent);
|
||||||
|
final badge = w.badge;
|
||||||
|
return MinimalTooltip(
|
||||||
|
message: w.tooltip,
|
||||||
|
child: MouseRegion(
|
||||||
|
cursor: enabled ? SystemMouseCursors.click : SystemMouseCursors.basic,
|
||||||
|
onEnter: (_) => setState(() => _hover = true),
|
||||||
|
onExit: (_) => setState(() => _hover = false),
|
||||||
|
child: GestureDetector(
|
||||||
|
behavior: HitTestBehavior.opaque,
|
||||||
|
onTap: w.onPressed,
|
||||||
|
child: AnimatedContainer(
|
||||||
|
duration: const Duration(milliseconds: 120),
|
||||||
|
height: size,
|
||||||
|
constraints: BoxConstraints(minWidth: size),
|
||||||
|
padding: EdgeInsets.symmetric(horizontal: w.label == null ? 0 : 10 * w.scale),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: bg,
|
||||||
|
borderRadius: BorderRadius.circular(w.accent ? size / 2 : MinimalStyle.radius * w.scale),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
|
children: [
|
||||||
|
Stack(
|
||||||
|
clipBehavior: Clip.none,
|
||||||
|
children: [
|
||||||
|
Icon(w.icon, color: fg, size: (w.accent ? 26 : 22) * w.scale),
|
||||||
|
if (badge != null && badge > 0)
|
||||||
|
Positioned(
|
||||||
|
right: -7,
|
||||||
|
top: -5,
|
||||||
|
child: Container(
|
||||||
|
key: const ValueKey('minimal-badge'),
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 4),
|
||||||
|
decoration: BoxDecoration(color: primary, borderRadius: BorderRadius.circular(999)),
|
||||||
|
child: Text(
|
||||||
|
'$badge',
|
||||||
|
style: TextStyle(color: onPrimary, fontSize: 9, height: 1.35, fontWeight: FontWeight.w700),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
if (w.label != null) ...[
|
||||||
|
SizedBox(width: 6 * w.scale),
|
||||||
|
Text(
|
||||||
|
w.label!,
|
||||||
|
style: TextStyle(
|
||||||
|
color: fg,
|
||||||
|
fontSize: MinimalStyle.fontSize * w.scale,
|
||||||
|
fontFeatures: const [FontFeature.tabularFigures()],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A glass capsule around a row of Minimal buttons.
|
||||||
|
class MinimalCapsule extends StatelessWidget {
|
||||||
|
final List<Widget> children;
|
||||||
|
final double scale;
|
||||||
|
const MinimalCapsule({super.key, required this.children, this.scale = 1});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final r = BorderRadius.circular(MinimalStyle.radius * scale + MinimalStyle.capsulePad);
|
||||||
|
return DecoratedBox(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: MinimalStyle.capsule,
|
||||||
|
borderRadius: r,
|
||||||
|
border: Border.all(color: AppMenuStyle.border, width: 0.5),
|
||||||
|
),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(MinimalStyle.capsulePad),
|
||||||
|
child: Row(mainAxisSize: MainAxisSize.min, spacing: 2, children: children),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,579 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:math' as math;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../../playback/media_marks.dart';
|
||||||
|
import '../frame.dart';
|
||||||
|
import 'style.dart';
|
||||||
|
|
||||||
|
// The Minimal skin's timeline: a band across the bottom with the played
|
||||||
|
// part tinted in the accent and the position as a line, the part not
|
||||||
|
// downloaded yet striped, chapter starts as dots on the top edge (click one
|
||||||
|
// to jump), the elapsed time left and the total or the time left right,
|
||||||
|
// the buffered seconds by the position while under a minute, and a tip
|
||||||
|
// with the time (and the chapter title) under the mouse. Hidden, it shrinks
|
||||||
|
// to a thin progress line.
|
||||||
|
//
|
||||||
|
// Inspired by the timeline of uosc (github.com/tomasklaen/uosc, LGPL-2.1,
|
||||||
|
// by tomasklaen): the striped unbuffered part, the remaining time and the
|
||||||
|
// thin line when hidden come from there. The drawing, geometry and values
|
||||||
|
// here are our own.
|
||||||
|
|
||||||
|
/// Sizes at scale 1.
|
||||||
|
abstract final class MinimalTimelineSpec {
|
||||||
|
/// The band's height while the controls are up.
|
||||||
|
static const size = 36.0;
|
||||||
|
|
||||||
|
/// What is left of it while they are hidden.
|
||||||
|
static const lineSize = 3.0;
|
||||||
|
|
||||||
|
/// The played part's accent tint.
|
||||||
|
static const played = 0.4;
|
||||||
|
|
||||||
|
/// The position line.
|
||||||
|
static const lineWidth = 2.0;
|
||||||
|
static const fontSize = 15.0;
|
||||||
|
|
||||||
|
/// The times' inset from the ends.
|
||||||
|
static const inset = 12.0;
|
||||||
|
|
||||||
|
/// A chapter dot's radius (doubled-ish while hovered).
|
||||||
|
static const dot = 3.5;
|
||||||
|
|
||||||
|
/// The cache label shows while less than this is buffered ahead.
|
||||||
|
static const bufferedThreshold = Duration(seconds: 60);
|
||||||
|
|
||||||
|
/// Collapse / grow.
|
||||||
|
static const animation = Duration(milliseconds: 120);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fraction of [total] at [d], 0..1 (0 without a duration).
|
||||||
|
double timelineFraction(Duration d, Duration total) {
|
||||||
|
final t = total.inMicroseconds;
|
||||||
|
if (t <= 0) return 0;
|
||||||
|
return (d.inMicroseconds / t).clamp(0.0, 1.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the part not downloaded yet starts (it runs to the end), as a
|
||||||
|
/// fraction; null when nothing known is missing. We know only the end of
|
||||||
|
/// mpv's cache ahead ([buffered]); a cache within half a second of the end
|
||||||
|
/// leaves nothing.
|
||||||
|
double? uncachedFrom({required Duration position, required Duration buffered, required Duration duration}) {
|
||||||
|
if (duration <= Duration.zero || buffered <= Duration.zero) return null;
|
||||||
|
final from = buffered > position ? buffered : position;
|
||||||
|
if (duration - from <= const Duration(milliseconds: 500)) return null;
|
||||||
|
return timelineFraction(from, duration);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The cache label by the position ("12s"): the seconds buffered ahead,
|
||||||
|
/// while under [MinimalTimelineSpec.bufferedThreshold] and the cache does
|
||||||
|
/// not reach the end.
|
||||||
|
String? cacheLabel({required Duration position, required Duration buffered, required Duration duration}) {
|
||||||
|
if (duration <= Duration.zero || buffered <= Duration.zero) return null;
|
||||||
|
if (duration - buffered <= const Duration(milliseconds: 500)) return null;
|
||||||
|
final ahead = buffered > position ? buffered - position : Duration.zero;
|
||||||
|
if (ahead >= MinimalTimelineSpec.bufferedThreshold) return null;
|
||||||
|
return '${(ahead.inMilliseconds / 1000).round()}s';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The band's height while it animates between hidden (0) and shown (1).
|
||||||
|
double minimalBandSize(double visibility, double scale) =>
|
||||||
|
MinimalTimelineSpec.lineSize +
|
||||||
|
((MinimalTimelineSpec.size * scale - MinimalTimelineSpec.lineSize) * visibility).roundToDouble();
|
||||||
|
|
||||||
|
/// The Minimal timeline. [expanded] false (the controls hidden) shrinks it,
|
||||||
|
/// animated, to the progress line. Seeks ([onSeek]) on press, on every drag
|
||||||
|
/// move and on release; a press on a hovered chapter dot jumps to that
|
||||||
|
/// chapter, one on the right-hand time switches it ([onToggleTime]).
|
||||||
|
class MinimalTimeline extends StatefulWidget {
|
||||||
|
final Duration position;
|
||||||
|
final Duration duration;
|
||||||
|
|
||||||
|
/// End of the cached range.
|
||||||
|
final Duration buffered;
|
||||||
|
final List<MediaChapter> chapters;
|
||||||
|
final bool expanded;
|
||||||
|
|
||||||
|
/// The right-hand time: the time left instead of the total.
|
||||||
|
final bool remaining;
|
||||||
|
final double scale;
|
||||||
|
final ValueChanged<Duration> onSeek;
|
||||||
|
final VoidCallback? onToggleTime;
|
||||||
|
const MinimalTimeline({
|
||||||
|
super.key,
|
||||||
|
required this.position,
|
||||||
|
required this.duration,
|
||||||
|
this.buffered = Duration.zero,
|
||||||
|
this.chapters = const [],
|
||||||
|
this.expanded = true,
|
||||||
|
this.remaining = true,
|
||||||
|
this.scale = 1,
|
||||||
|
required this.onSeek,
|
||||||
|
this.onToggleTime,
|
||||||
|
});
|
||||||
|
|
||||||
|
static double heightFor(double scale) => MinimalTimelineSpec.size * scale;
|
||||||
|
static const collapsedHeight = MinimalTimelineSpec.lineSize;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<MinimalTimeline> createState() => _MinimalTimelineState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _MinimalTimelineState extends State<MinimalTimeline> {
|
||||||
|
Offset? _hover;
|
||||||
|
bool _dragging = false;
|
||||||
|
double _dragFraction = 0;
|
||||||
|
Duration? _lastSent;
|
||||||
|
// A released seek, shown until the position catches up (else the line
|
||||||
|
// jumps back to the old position for a moment).
|
||||||
|
double? _pending;
|
||||||
|
Timer? _pendingTimer;
|
||||||
|
|
||||||
|
double get _scale => widget.scale;
|
||||||
|
Duration _at(double fraction) => widget.duration * fraction.clamp(0.0, 1.0);
|
||||||
|
|
||||||
|
void _send(Duration d) {
|
||||||
|
if (d == _lastSent) return;
|
||||||
|
_lastSent = d;
|
||||||
|
widget.onSeek(d);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _drag(bool on) {
|
||||||
|
if (_dragging == on) return;
|
||||||
|
setState(() => _dragging = on);
|
||||||
|
ControlsFrame.maybeOf(context)?.hold(on);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _settle(double fraction) {
|
||||||
|
_pending = fraction;
|
||||||
|
_pendingTimer?.cancel();
|
||||||
|
_pendingTimer = Timer(const Duration(seconds: 2), () {
|
||||||
|
if (mounted) setState(() => _pending = null);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didUpdateWidget(MinimalTimeline old) {
|
||||||
|
super.didUpdateWidget(old);
|
||||||
|
if (!widget.expanded && old.expanded) _hover = null;
|
||||||
|
final p = _pending;
|
||||||
|
if (p != null && widget.duration > Duration.zero) {
|
||||||
|
final off = (widget.position - _at(p)).abs();
|
||||||
|
if (off < const Duration(milliseconds: 1500)) {
|
||||||
|
_pending = null;
|
||||||
|
_pendingTimer?.cancel();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_pendingTimer?.cancel();
|
||||||
|
// A drag cut short by a rebuild must not keep the controls up.
|
||||||
|
if (_dragging) ControlsFrame.maybeOf(context)?.hold(false);
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
double _dotRadius(bool hovered) => MinimalTimelineSpec.dot * _scale * (hovered ? 1.7 : 1);
|
||||||
|
|
||||||
|
/// The chapter whose dot is within reach of [at].
|
||||||
|
int? _hoveredChapter(double width, List<MediaChapter> marks, Offset? at) {
|
||||||
|
if (at == null || _dragging) return null;
|
||||||
|
final reach = _dotRadius(false) * 2.5;
|
||||||
|
int? best;
|
||||||
|
var bestD = double.infinity;
|
||||||
|
for (var i = 0; i < marks.length; i++) {
|
||||||
|
final cx = width * timelineFraction(marks[i].start, widget.duration);
|
||||||
|
final d = (Offset(cx, 0) - at).distance;
|
||||||
|
if (d <= reach && d < bestD) {
|
||||||
|
best = i;
|
||||||
|
bestD = d;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _rightText(Duration shown) {
|
||||||
|
final d = widget.duration;
|
||||||
|
if (d <= Duration.zero) return null;
|
||||||
|
if (!widget.remaining) return formatClock(d);
|
||||||
|
final left = d - shown;
|
||||||
|
return '-${formatClock(left.isNegative ? Duration.zero : left)}';
|
||||||
|
}
|
||||||
|
|
||||||
|
// The painter's text takes the app's font (a TextPainter does not
|
||||||
|
// inherit it).
|
||||||
|
String? _font;
|
||||||
|
|
||||||
|
TextStyle get _timeStyle => TextStyle(
|
||||||
|
fontFamily: _font,
|
||||||
|
color: MinimalStyle.text,
|
||||||
|
fontSize: MinimalTimelineSpec.fontSize * _scale,
|
||||||
|
height: 1,
|
||||||
|
fontWeight: FontWeight.w500,
|
||||||
|
fontFeatures: const [FontFeature.tabularFigures()],
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Where the right-hand time sits (a press there switches it).
|
||||||
|
bool _onRightTime(Offset at, double width, String? text) {
|
||||||
|
if (text == null || widget.onToggleTime == null) return false;
|
||||||
|
final tp = TextPainter(
|
||||||
|
text: TextSpan(text: text, style: _timeStyle),
|
||||||
|
textDirection: TextDirection.ltr,
|
||||||
|
)..layout();
|
||||||
|
return at.dx >= width - MinimalTimelineSpec.inset * _scale - tp.width - 6;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
_font = DefaultTextStyle.of(context).style.fontFamily ?? Theme.of(context).textTheme.bodyMedium?.fontFamily;
|
||||||
|
return LayoutBuilder(
|
||||||
|
builder: (context, constraints) => TweenAnimationBuilder<double>(
|
||||||
|
tween: Tween(end: widget.expanded ? 1 : 0),
|
||||||
|
duration: MinimalTimelineSpec.animation,
|
||||||
|
builder: (context, visibility, _) => _band(context, constraints.maxWidth, visibility),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _band(BuildContext context, double width, double visibility) {
|
||||||
|
final expanded = widget.expanded;
|
||||||
|
final duration = widget.duration;
|
||||||
|
final size = minimalBandSize(visibility, _scale);
|
||||||
|
final progress = _dragging ? _dragFraction : (_pending ?? timelineFraction(widget.position, duration));
|
||||||
|
final shown = _at(progress);
|
||||||
|
final marks = duration > Duration.zero ? widget.chapters : const <MediaChapter>[];
|
||||||
|
final hover = expanded ? _hover : null;
|
||||||
|
final hovered = _hoveredChapter(width, marks, hover);
|
||||||
|
final hoverFraction = hovered != null
|
||||||
|
? timelineFraction(marks[hovered].start, duration)
|
||||||
|
: (hover == null || duration <= Duration.zero || width <= 0 ? null : (hover.dx / width).clamp(0.0, 1.0));
|
||||||
|
final hoverAt = hoverFraction == null ? null : _at(hoverFraction);
|
||||||
|
final cursorX = hoverFraction == null ? null : width * hoverFraction;
|
||||||
|
final hoverChapter = hoverAt == null ? null : chapterIndexAt(widget.chapters, hoverAt);
|
||||||
|
final hoverTitle = hoverChapter == null ? '' : widget.chapters[hoverChapter].title;
|
||||||
|
// Text fades out before it would overflow the shrinking band.
|
||||||
|
final minText = MinimalTimelineSpec.fontSize * _scale;
|
||||||
|
final textOpacity = ((size - minText) / (minText / 2)).clamp(0.0, 1.0);
|
||||||
|
final right = _rightText(shown);
|
||||||
|
final primary = Theme.of(context).colorScheme.primary;
|
||||||
|
final painter = MinimalTimelinePainter(
|
||||||
|
progress: progress,
|
||||||
|
visibility: visibility,
|
||||||
|
accent: primary,
|
||||||
|
scale: _scale,
|
||||||
|
uncached: uncachedFrom(position: widget.position, buffered: widget.buffered, duration: duration),
|
||||||
|
chapters: [for (final c in marks) timelineFraction(c.start, duration)],
|
||||||
|
hoveredChapter: hovered,
|
||||||
|
hoverX: hovered == null ? cursorX : null,
|
||||||
|
textOpacity: textOpacity,
|
||||||
|
elapsed: duration > Duration.zero ? formatClock(shown) : null,
|
||||||
|
right: right,
|
||||||
|
cache: cacheLabel(position: widget.position, buffered: widget.buffered, duration: duration),
|
||||||
|
timeStyle: _timeStyle,
|
||||||
|
);
|
||||||
|
final bar = SizedBox(
|
||||||
|
key: const ValueKey('minimal-timeline'),
|
||||||
|
width: width,
|
||||||
|
height: size,
|
||||||
|
child: Stack(
|
||||||
|
clipBehavior: Clip.none,
|
||||||
|
children: [
|
||||||
|
Positioned.fill(
|
||||||
|
child: RepaintBoundary(child: CustomPaint(painter: painter)),
|
||||||
|
),
|
||||||
|
if (hoverAt != null && cursorX != null)
|
||||||
|
Positioned(
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
bottom: size + 8,
|
||||||
|
height: 120,
|
||||||
|
child: IgnorePointer(
|
||||||
|
child: CustomMultiChildLayout(
|
||||||
|
delegate: _TipLayout(x: cursorX),
|
||||||
|
children: [
|
||||||
|
LayoutId(
|
||||||
|
id: #tip,
|
||||||
|
child: _HoverTip(time: formatClock(hoverAt), chapter: hoverTitle, scale: _scale),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (!expanded) return IgnorePointer(child: bar);
|
||||||
|
Offset clampTo(Offset p) => Offset(p.dx.clamp(0.0, width), p.dy);
|
||||||
|
return MouseRegion(
|
||||||
|
cursor: SystemMouseCursors.click,
|
||||||
|
onEnter: (e) => setState(() => _hover = clampTo(e.localPosition)),
|
||||||
|
onHover: (e) => setState(() => _hover = clampTo(e.localPosition)),
|
||||||
|
onExit: (_) {
|
||||||
|
if (!_dragging) setState(() => _hover = null);
|
||||||
|
},
|
||||||
|
child: Listener(
|
||||||
|
behavior: HitTestBehavior.opaque,
|
||||||
|
onPointerDown: (e) {
|
||||||
|
if (width <= 0) return;
|
||||||
|
final at = clampTo(e.localPosition);
|
||||||
|
if (_onRightTime(at, width, right)) {
|
||||||
|
widget.onToggleTime?.call();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (duration <= Duration.zero) return;
|
||||||
|
final chapter = _hoveredChapter(width, marks, at);
|
||||||
|
_lastSent = null;
|
||||||
|
if (chapter != null) {
|
||||||
|
_settle(timelineFraction(marks[chapter].start, duration));
|
||||||
|
_send(marks[chapter].start);
|
||||||
|
setState(() {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_pending = null;
|
||||||
|
_dragFraction = (at.dx / width).clamp(0.0, 1.0);
|
||||||
|
_drag(true);
|
||||||
|
_send(_at(_dragFraction));
|
||||||
|
},
|
||||||
|
onPointerMove: (e) {
|
||||||
|
if (!_dragging) return;
|
||||||
|
final at = clampTo(e.localPosition);
|
||||||
|
setState(() {
|
||||||
|
_hover = at;
|
||||||
|
_dragFraction = (at.dx / width).clamp(0.0, 1.0);
|
||||||
|
});
|
||||||
|
_send(_at(_dragFraction));
|
||||||
|
},
|
||||||
|
onPointerUp: (e) {
|
||||||
|
if (!_dragging) return;
|
||||||
|
_send(_at(_dragFraction));
|
||||||
|
_settle(_dragFraction);
|
||||||
|
final p = e.localPosition;
|
||||||
|
if (p.dx < 0 || p.dx > width || p.dy < 0 || p.dy > size) _hover = null;
|
||||||
|
_drag(false);
|
||||||
|
},
|
||||||
|
onPointerCancel: (_) => _drag(false),
|
||||||
|
child: bar,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _HoverTip extends StatelessWidget {
|
||||||
|
final String time;
|
||||||
|
final String chapter;
|
||||||
|
final double scale;
|
||||||
|
const _HoverTip({required this.time, required this.chapter, required this.scale});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Container(
|
||||||
|
constraints: const BoxConstraints(maxWidth: 360),
|
||||||
|
padding: EdgeInsets.symmetric(horizontal: 10 * scale, vertical: 5 * scale),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: MinimalStyle.tip,
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
border: Border.all(color: const Color(0x1FFFFFFF), width: 0.5),
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
if (chapter.isNotEmpty)
|
||||||
|
Text(
|
||||||
|
chapter,
|
||||||
|
key: const ValueKey('minimal-hover-chapter'),
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(color: MinimalStyle.text, fontSize: 13 * scale, fontWeight: FontWeight.w600),
|
||||||
|
),
|
||||||
|
Text(
|
||||||
|
time,
|
||||||
|
key: const ValueKey('minimal-hover-time'),
|
||||||
|
style: TextStyle(
|
||||||
|
color: chapter.isEmpty ? MinimalStyle.text : MinimalStyle.dim,
|
||||||
|
fontSize: 13 * scale,
|
||||||
|
fontFeatures: const [FontFeature.tabularFigures()],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The hover tip centred on [x], kept inside the band's ends.
|
||||||
|
class _TipLayout extends MultiChildLayoutDelegate {
|
||||||
|
final double x;
|
||||||
|
_TipLayout({required this.x});
|
||||||
|
|
||||||
|
@override
|
||||||
|
void performLayout(Size size) {
|
||||||
|
const gap = 4.0;
|
||||||
|
final tip = layoutChild(#tip, BoxConstraints.loose(size));
|
||||||
|
final left = (x - tip.width / 2).clamp(gap, math.max(gap, size.width - gap - tip.width)).toDouble();
|
||||||
|
positionChild(#tip, Offset(left, size.height - tip.height));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool shouldRelayout(_TipLayout old) => old.x != x;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Paints the band: background, the played tint and the (white) position
|
||||||
|
/// line, the stripes over the part not downloaded, chapter marks, the
|
||||||
|
/// times, the hover line.
|
||||||
|
class MinimalTimelinePainter extends CustomPainter {
|
||||||
|
/// The playing position, 0..1.
|
||||||
|
final double progress;
|
||||||
|
|
||||||
|
/// 0 hidden .. 1 shown.
|
||||||
|
final double visibility;
|
||||||
|
final Color accent;
|
||||||
|
final double scale;
|
||||||
|
|
||||||
|
/// Start of the part not downloaded (to the end), as a fraction.
|
||||||
|
final double? uncached;
|
||||||
|
|
||||||
|
/// Chapter starts, as fractions.
|
||||||
|
final List<double> chapters;
|
||||||
|
final int? hoveredChapter;
|
||||||
|
final double? hoverX;
|
||||||
|
final double textOpacity;
|
||||||
|
final String? elapsed;
|
||||||
|
final String? right;
|
||||||
|
final String? cache;
|
||||||
|
final TextStyle timeStyle;
|
||||||
|
const MinimalTimelinePainter({
|
||||||
|
required this.progress,
|
||||||
|
this.visibility = 1,
|
||||||
|
this.accent = Colors.white,
|
||||||
|
this.scale = 1,
|
||||||
|
this.uncached,
|
||||||
|
this.chapters = const [],
|
||||||
|
this.hoveredChapter,
|
||||||
|
this.hoverX,
|
||||||
|
this.textOpacity = 1,
|
||||||
|
this.elapsed,
|
||||||
|
this.right,
|
||||||
|
this.cache,
|
||||||
|
this.timeStyle = const TextStyle(fontSize: MinimalTimelineSpec.fontSize),
|
||||||
|
});
|
||||||
|
|
||||||
|
/// x of the position line's centre.
|
||||||
|
double lineX(double width) {
|
||||||
|
final lw = MinimalTimelineSpec.lineWidth * scale;
|
||||||
|
return (width * progress).clamp(lw / 2, math.max(lw / 2, width - lw / 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void paint(Canvas canvas, Size size) {
|
||||||
|
final w = size.width, h = size.height;
|
||||||
|
final x = lineX(w);
|
||||||
|
final band = Offset.zero & size;
|
||||||
|
// The same colours shown and hidden: hidden, it is the band shrunk to
|
||||||
|
// a line, so growing and shrinking never switches colour.
|
||||||
|
canvas.drawRect(band, Paint()..color = MinimalStyle.band);
|
||||||
|
canvas.drawRect(Rect.fromLTRB(0, 0, x, h), Paint()..color = accent.withValues(alpha: MinimalTimelineSpec.played));
|
||||||
|
_stripes(canvas, w, h);
|
||||||
|
_chapters(canvas, w, h);
|
||||||
|
if (visibility > 0) {
|
||||||
|
final lw = MinimalTimelineSpec.lineWidth * scale;
|
||||||
|
canvas.drawRect(
|
||||||
|
Rect.fromLTRB(x - lw / 2, 0, x + lw / 2, h),
|
||||||
|
Paint()..color = Colors.white.withValues(alpha: visibility),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (textOpacity > 0) _times(canvas, w, h, x);
|
||||||
|
final hx = hoverX;
|
||||||
|
if (hx != null) {
|
||||||
|
canvas.drawRect(Rect.fromLTRB(hx - 0.5, 0, hx + 0.5, h), Paint()..color = Colors.white.withValues(alpha: 0.45));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Thin 45° stripes over the part not downloaded yet.
|
||||||
|
void _stripes(Canvas canvas, double w, double h) {
|
||||||
|
final from = uncached;
|
||||||
|
if (from == null) return;
|
||||||
|
final ax = (w * from).floorToDouble();
|
||||||
|
if (ax >= w) return;
|
||||||
|
final period = 7.0 * scale;
|
||||||
|
canvas.save();
|
||||||
|
canvas.clipRect(Rect.fromLTRB(ax, 0, w, h));
|
||||||
|
final paint = Paint()
|
||||||
|
// Stronger on the line, where only a few pixels of each show.
|
||||||
|
..color = Colors.white.withValues(alpha: 0.12 + 0.22 * (1 - visibility))
|
||||||
|
..strokeWidth = 1.5 * scale;
|
||||||
|
for (var c = (ax / period).floorToDouble() * period - h; c <= w; c += period) {
|
||||||
|
canvas.drawLine(Offset(c, h), Offset(c + h, 0), paint);
|
||||||
|
}
|
||||||
|
canvas.restore();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _chapters(Canvas canvas, double w, double h) {
|
||||||
|
final cut = Paint()..color = Colors.black.withValues(alpha: 0.3);
|
||||||
|
for (final f in chapters) {
|
||||||
|
if (f <= 0) continue;
|
||||||
|
final cx = w * f;
|
||||||
|
canvas.drawRect(Rect.fromLTRB(cx - 0.5, 0, cx + 0.5, h), cut);
|
||||||
|
}
|
||||||
|
if (visibility <= 0) return;
|
||||||
|
final r = MinimalTimelineSpec.dot * scale * visibility;
|
||||||
|
void dot(double f, double radius, Color fill) {
|
||||||
|
final c = Offset(w * f, 0);
|
||||||
|
canvas.drawCircle(c, radius + 1, Paint()..color = Colors.black.withValues(alpha: 0.7));
|
||||||
|
canvas.drawCircle(c, radius, Paint()..color = fill);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Not at 0: the band's start says that already.
|
||||||
|
for (var i = 0; i < chapters.length; i++) {
|
||||||
|
if (i != hoveredChapter && chapters[i] > 0) dot(chapters[i], r, Colors.white.withValues(alpha: 0.9));
|
||||||
|
}
|
||||||
|
final hv = hoveredChapter;
|
||||||
|
if (hv != null && hv < chapters.length) dot(chapters[hv], r * 1.7, accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
TextPainter _text(String s, TextStyle style) => TextPainter(
|
||||||
|
text: TextSpan(text: s, style: style),
|
||||||
|
textDirection: TextDirection.ltr,
|
||||||
|
)..layout();
|
||||||
|
|
||||||
|
/// White text with a soft shadow, so it reads over the accent tint too.
|
||||||
|
void _label(Canvas canvas, String s, TextStyle style, Offset at) {
|
||||||
|
final o = textOpacity;
|
||||||
|
_text(
|
||||||
|
s,
|
||||||
|
style.copyWith(
|
||||||
|
color: (style.color ?? Colors.white).withValues(alpha: o),
|
||||||
|
shadows: [Shadow(color: Colors.black.withValues(alpha: 0.8 * o), blurRadius: 3)],
|
||||||
|
),
|
||||||
|
).paint(canvas, at);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _times(Canvas canvas, double w, double h, double lineX) {
|
||||||
|
final inset = MinimalTimelineSpec.inset * scale;
|
||||||
|
final fs = timeStyle.fontSize ?? MinimalTimelineSpec.fontSize;
|
||||||
|
final cy = h / 2;
|
||||||
|
final e = elapsed, r = right;
|
||||||
|
final ew = e == null ? 0.0 : _text(e, timeStyle).width;
|
||||||
|
final rw = r == null ? 0.0 : _text(r, timeStyle).width;
|
||||||
|
final c = cache;
|
||||||
|
if (c != null) {
|
||||||
|
final cs = timeStyle.copyWith(fontSize: fs * 0.8, color: MinimalStyle.dim);
|
||||||
|
final cw = _text(c, cs).width;
|
||||||
|
const margin = 6.0;
|
||||||
|
var x = lineX + margin;
|
||||||
|
final minX = inset + margin + ew, maxX = w - inset - margin - rw;
|
||||||
|
if (x < minX) {
|
||||||
|
x = minX;
|
||||||
|
} else if (x + cw > maxX) {
|
||||||
|
x = maxX - cw;
|
||||||
|
}
|
||||||
|
_label(canvas, c, cs, Offset(x, cy - fs * 0.4));
|
||||||
|
}
|
||||||
|
if (e != null) _label(canvas, e, timeStyle, Offset(inset, cy - fs / 2));
|
||||||
|
if (r != null) _label(canvas, r, timeStyle, Offset(w - inset - rw, cy - fs / 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool shouldRepaint(MinimalTimelinePainter old) => true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
import 'package:flutter/material.dart' show IconData, Icons;
|
||||||
|
|
||||||
|
import '../../playback/media_marks.dart' show formatClock;
|
||||||
|
import 'controls_prefs.dart';
|
||||||
|
|
||||||
|
// The controls layout, defined once for both skins: which controls the
|
||||||
|
// bottom bar has, in which order, which actions sit in the ⚙ menu instead,
|
||||||
|
// and their icons, tooltips and labels. Pure: everything here is a
|
||||||
|
// function of a [ControlsSnapshot] and the user's choices, so tests cover
|
||||||
|
// it without a player.
|
||||||
|
|
||||||
|
/// What playback does as this viewer sees it. In a server "play" is being
|
||||||
|
/// ready: the video plays once everyone is.
|
||||||
|
enum PlayState {
|
||||||
|
/// The video plays (the button pauses: you go unready).
|
||||||
|
playing,
|
||||||
|
|
||||||
|
/// You are ready; the others are not yet (the button unreadies you).
|
||||||
|
waiting,
|
||||||
|
|
||||||
|
/// You are not ready (the button readies you).
|
||||||
|
paused,
|
||||||
|
|
||||||
|
/// The media ended.
|
||||||
|
finished,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A control in the bottom bar.
|
||||||
|
enum BarControl {
|
||||||
|
playPause,
|
||||||
|
|
||||||
|
/// Previous episode.
|
||||||
|
previous,
|
||||||
|
|
||||||
|
/// Up next's first item, else the next episode.
|
||||||
|
next,
|
||||||
|
chapterPrevious,
|
||||||
|
chapterNext,
|
||||||
|
volume,
|
||||||
|
time,
|
||||||
|
subtitles,
|
||||||
|
audio,
|
||||||
|
|
||||||
|
/// ⚙: everything that is not a bar button.
|
||||||
|
settings,
|
||||||
|
chat,
|
||||||
|
fullscreen,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An action in the ⚙ menu.
|
||||||
|
enum ControlAction {
|
||||||
|
chapters('Chapters…', null),
|
||||||
|
subtitles('Subtitles…', null),
|
||||||
|
audio('Audio…', null),
|
||||||
|
skipForward('Skip 1:30', 'Shift+Right'),
|
||||||
|
shaders('Upscaling shader…', 'Ctrl+0…6'),
|
||||||
|
chat('Chat & activity', 'Tab'),
|
||||||
|
changeVideo('Change video', null),
|
||||||
|
copyLink('Copy link', null),
|
||||||
|
reload('Reload video', 'Ctrl+R'),
|
||||||
|
markAllReady('Mark everyone ready', null),
|
||||||
|
markProblem('Mark a problem', 'Ctrl+Shift+B'),
|
||||||
|
playerSettings('Player settings…', null),
|
||||||
|
leave('Leave server', null);
|
||||||
|
|
||||||
|
final String label;
|
||||||
|
final String? hint;
|
||||||
|
const ControlAction(this.label, this.hint);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bar's order, left cluster then right cluster. The play button is
|
||||||
|
/// always first and fullscreen always last; controls that do not apply
|
||||||
|
/// (no episode, no chapters) or that the user hid are left out, the rest
|
||||||
|
/// keep their order.
|
||||||
|
abstract final class ControlsLayout {
|
||||||
|
static const left = [
|
||||||
|
BarControl.playPause,
|
||||||
|
BarControl.previous,
|
||||||
|
BarControl.next,
|
||||||
|
BarControl.chapterPrevious,
|
||||||
|
BarControl.chapterNext,
|
||||||
|
BarControl.volume,
|
||||||
|
BarControl.time,
|
||||||
|
];
|
||||||
|
static const right = [
|
||||||
|
BarControl.subtitles,
|
||||||
|
BarControl.audio,
|
||||||
|
BarControl.settings,
|
||||||
|
BarControl.chat,
|
||||||
|
BarControl.fullscreen,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The ⚙ menu's order.
|
||||||
|
static const menu = ControlAction.values;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the layout depends on, at one moment.
|
||||||
|
class ControlsSnapshot {
|
||||||
|
final PlayState play;
|
||||||
|
|
||||||
|
/// The previous episode's label; null: none.
|
||||||
|
final String? previousLabel;
|
||||||
|
|
||||||
|
/// Up next's first item's title, else the next episode's label; null:
|
||||||
|
/// nothing next.
|
||||||
|
final String? nextLabel;
|
||||||
|
|
||||||
|
/// [nextLabel] is Up next (not an episode).
|
||||||
|
final bool nextIsUpNext;
|
||||||
|
final bool hasChapters;
|
||||||
|
|
||||||
|
/// The media's length is known (seeks and skips make sense).
|
||||||
|
final bool hasDuration;
|
||||||
|
|
||||||
|
/// Watching alone (no one to mark ready).
|
||||||
|
final bool alone;
|
||||||
|
|
||||||
|
/// A link to copy (`SessionCoordinator.currentLink`).
|
||||||
|
final bool hasLink;
|
||||||
|
final bool fullscreen;
|
||||||
|
final bool chatOpen;
|
||||||
|
const ControlsSnapshot({
|
||||||
|
this.play = PlayState.paused,
|
||||||
|
this.previousLabel,
|
||||||
|
this.nextLabel,
|
||||||
|
this.nextIsUpNext = false,
|
||||||
|
this.hasChapters = false,
|
||||||
|
this.hasDuration = false,
|
||||||
|
this.alone = false,
|
||||||
|
this.hasLink = false,
|
||||||
|
this.fullscreen = false,
|
||||||
|
this.chatOpen = false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bar's two clusters for [s], in [ControlsLayout] order.
|
||||||
|
({List<BarControl> left, List<BarControl> right}) barControls(ControlsSnapshot s, Set<OptionalControl> hidden) {
|
||||||
|
bool on(BarControl c) => switch (c) {
|
||||||
|
BarControl.previous => s.previousLabel != null,
|
||||||
|
BarControl.next => s.nextLabel != null,
|
||||||
|
BarControl.chapterPrevious || BarControl.chapterNext => s.hasChapters && !hidden.contains(OptionalControl.chapters),
|
||||||
|
BarControl.subtitles => !hidden.contains(OptionalControl.subtitles),
|
||||||
|
BarControl.audio => !hidden.contains(OptionalControl.audio),
|
||||||
|
BarControl.chat => !hidden.contains(OptionalControl.chat),
|
||||||
|
_ => true,
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
left: [
|
||||||
|
for (final c in ControlsLayout.left)
|
||||||
|
if (on(c)) c,
|
||||||
|
],
|
||||||
|
right: [
|
||||||
|
for (final c in ControlsLayout.right)
|
||||||
|
if (on(c)) c,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ⚙ menu for [s]: every action that applies, minus those the bar
|
||||||
|
/// already shows.
|
||||||
|
List<ControlAction> menuActions(ControlsSnapshot s, Set<OptionalControl> hidden) => [
|
||||||
|
for (final a in ControlsLayout.menu)
|
||||||
|
if (switch (a) {
|
||||||
|
ControlAction.chapters => s.hasChapters,
|
||||||
|
ControlAction.subtitles => hidden.contains(OptionalControl.subtitles),
|
||||||
|
ControlAction.audio => hidden.contains(OptionalControl.audio),
|
||||||
|
ControlAction.skipForward => s.hasDuration,
|
||||||
|
ControlAction.chat => hidden.contains(OptionalControl.chat),
|
||||||
|
ControlAction.copyLink => s.hasLink,
|
||||||
|
ControlAction.markAllReady => !s.alone,
|
||||||
|
_ => true,
|
||||||
|
})
|
||||||
|
a,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Whether a bar control does something now (a skin dims it otherwise).
|
||||||
|
bool controlEnabled(BarControl c, ControlsSnapshot s) => switch (c) {
|
||||||
|
BarControl.chapterPrevious || BarControl.chapterNext => s.hasChapters && s.hasDuration,
|
||||||
|
BarControl.previous => s.previousLabel != null,
|
||||||
|
BarControl.next => s.nextLabel != null,
|
||||||
|
_ => true,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The icon of a bar control (volume and the clock draw their own).
|
||||||
|
IconData controlIcon(BarControl c, ControlsSnapshot s) => switch (c) {
|
||||||
|
BarControl.playPause => switch (s.play) {
|
||||||
|
PlayState.playing => Icons.pause_rounded,
|
||||||
|
// Ready: the check says so; a click unreadies.
|
||||||
|
PlayState.waiting => Icons.check_rounded,
|
||||||
|
PlayState.finished => Icons.replay_rounded,
|
||||||
|
PlayState.paused => Icons.play_arrow_rounded,
|
||||||
|
},
|
||||||
|
BarControl.previous => Icons.skip_previous_rounded,
|
||||||
|
BarControl.next => Icons.skip_next_rounded,
|
||||||
|
BarControl.chapterPrevious => Icons.chevron_left_rounded,
|
||||||
|
BarControl.chapterNext => Icons.chevron_right_rounded,
|
||||||
|
BarControl.volume => Icons.volume_up_rounded,
|
||||||
|
BarControl.time => Icons.schedule_rounded,
|
||||||
|
BarControl.subtitles => Icons.subtitles_outlined,
|
||||||
|
BarControl.audio => Icons.graphic_eq_rounded,
|
||||||
|
BarControl.settings => Icons.settings_outlined,
|
||||||
|
BarControl.chat => s.chatOpen ? Icons.chat_bubble_rounded : Icons.chat_bubble_outline_rounded,
|
||||||
|
BarControl.fullscreen => s.fullscreen ? Icons.fullscreen_exit_rounded : Icons.fullscreen_rounded,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The tooltip of a bar control, with its key.
|
||||||
|
String controlTooltip(BarControl c, ControlsSnapshot s) => switch (c) {
|
||||||
|
BarControl.playPause => switch (s.play) {
|
||||||
|
PlayState.playing => 'Pause for everyone (Space)',
|
||||||
|
PlayState.waiting => 'Ready, waiting for the others (Space: not ready)',
|
||||||
|
PlayState.paused => s.alone ? 'Play (Space)' : 'Ready: play when everyone is (Space)',
|
||||||
|
PlayState.finished => 'Ready (Space)',
|
||||||
|
},
|
||||||
|
BarControl.previous => 'Previous: ${s.previousLabel ?? ''} (< or Shift+P)',
|
||||||
|
BarControl.next => '${s.nextIsUpNext ? 'Up next' : 'Next'}: ${s.nextLabel ?? ''} (> or Shift+N)',
|
||||||
|
BarControl.chapterPrevious => 'Previous chapter (PgUp)',
|
||||||
|
BarControl.chapterNext => 'Next chapter (PgDn)',
|
||||||
|
BarControl.volume => 'Volume (scroll, ↑ / ↓)',
|
||||||
|
BarControl.time => 'Elapsed / remaining (click to switch)',
|
||||||
|
BarControl.subtitles => 'Subtitles',
|
||||||
|
BarControl.audio => 'Audio',
|
||||||
|
BarControl.settings => 'Settings and more',
|
||||||
|
BarControl.chat => 'Chat & activity (Tab)',
|
||||||
|
BarControl.fullscreen => s.fullscreen ? 'Exit fullscreen (F, Esc)' : 'Fullscreen (F)',
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The bar's clock: "6:00 / 24:00", or the time left ("-18:00"); "0:00"
|
||||||
|
/// parts while the length is unknown.
|
||||||
|
String clockText(Duration position, Duration duration, TimeDisplay display) {
|
||||||
|
if (display == TimeDisplay.remaining && duration > Duration.zero) {
|
||||||
|
final left = duration - position;
|
||||||
|
return '-${formatClock(left.isNegative ? Duration.zero : left)}';
|
||||||
|
}
|
||||||
|
return '${formatClock(position)} / ${formatClock(duration)}';
|
||||||
|
}
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:signals/signals_flutter.dart';
|
||||||
|
|
||||||
|
import '../../jellyfin/track_prefs.dart' show MpvTrack;
|
||||||
|
import '../../playback/media_marks.dart';
|
||||||
|
import '../../playback/playback_controller.dart';
|
||||||
|
import '../../queue/queue_controller.dart';
|
||||||
|
import '../../session/session_coordinator.dart';
|
||||||
|
import '../../shaders/shader_presets.dart';
|
||||||
|
import '../../state/settings.dart';
|
||||||
|
import '../player_settings.dart' show applyShaderChoice;
|
||||||
|
import '../volume.dart' as vol;
|
||||||
|
import 'controls_layout.dart';
|
||||||
|
|
||||||
|
/// A track pick from a track menu: audio id, subtitle id, or off.
|
||||||
|
typedef TrackPick = ({int? aid, int? sid, bool subtitlesOff});
|
||||||
|
|
||||||
|
/// The player controls, independent of how they look: what the controls
|
||||||
|
/// show (state, as signals) and what they do (actions), wired to the
|
||||||
|
/// session once. Both skins only draw this and call its actions, so a
|
||||||
|
/// control added here shows in both. Built by the session player per
|
||||||
|
/// mount; [fullscreen], [chatOpen] and [unread] are the shell's, passed in.
|
||||||
|
class PlayerControlsModel {
|
||||||
|
final SessionCoordinator coord;
|
||||||
|
final ReadonlySignal<bool> fullscreen;
|
||||||
|
final ReadonlySignal<bool> chatOpen;
|
||||||
|
final ReadonlySignal<int> unread;
|
||||||
|
final VoidCallback _toggleFullscreen;
|
||||||
|
final VoidCallback _toggleChat;
|
||||||
|
final VoidCallback _changeVideo;
|
||||||
|
final VoidCallback _collapse;
|
||||||
|
final VoidCallback _leave;
|
||||||
|
|
||||||
|
PlayerControlsModel({
|
||||||
|
required this.coord,
|
||||||
|
required this.fullscreen,
|
||||||
|
required this.chatOpen,
|
||||||
|
required this.unread,
|
||||||
|
required VoidCallback onToggleFullscreen,
|
||||||
|
required VoidCallback onToggleChat,
|
||||||
|
required VoidCallback onChangeVideo,
|
||||||
|
required VoidCallback onCollapse,
|
||||||
|
required VoidCallback onLeave,
|
||||||
|
}) : _toggleFullscreen = onToggleFullscreen,
|
||||||
|
_toggleChat = onToggleChat,
|
||||||
|
_changeVideo = onChangeVideo,
|
||||||
|
_collapse = onCollapse,
|
||||||
|
_leave = onLeave;
|
||||||
|
|
||||||
|
PlaybackController get playback => coord.playback;
|
||||||
|
QueueController get queue => coord.queue;
|
||||||
|
AppSettings get settings => AppSettings.instance;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- state
|
||||||
|
|
||||||
|
ReadonlySignal<Duration> get position => playback.position;
|
||||||
|
ReadonlySignal<Duration> get duration => playback.duration;
|
||||||
|
|
||||||
|
/// End of the cached range ahead of the position.
|
||||||
|
ReadonlySignal<Duration> get buffered => playback.buffered;
|
||||||
|
ReadonlySignal<List<MediaChapter>> get chapters => playback.chapters;
|
||||||
|
ReadonlySignal<int?> get currentChapter => playback.currentChapter;
|
||||||
|
ReadonlySignal<List<MpvTrack>> get tracks => playback.tracks;
|
||||||
|
|
||||||
|
/// 0..`maxVolume`.
|
||||||
|
ReadonlySignal<double> get volume => playback.volume;
|
||||||
|
ReadonlySignal<SkipOffer?> get skipOffer => coord.skipOffer;
|
||||||
|
ReadonlySignal<RenderMode> get renderMode => playback.renderMode;
|
||||||
|
|
||||||
|
/// Play / pause as the session sees it ([PlayState]).
|
||||||
|
late final Computed<PlayState> play = computed(() {
|
||||||
|
final r = coord.serverState.value;
|
||||||
|
final self = coord.selfMember.value;
|
||||||
|
return switch (r?.transport) {
|
||||||
|
'playing' => PlayState.playing,
|
||||||
|
'finished' => PlayState.finished,
|
||||||
|
_ => (self?.ready ?? false) && (self?.inSet ?? false) ? PlayState.waiting : PlayState.paused,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Everything the layout depends on (not the position: that changes
|
||||||
|
/// four times a second and only the timeline needs it).
|
||||||
|
late final Computed<ControlsSnapshot> snapshot = computed(() {
|
||||||
|
final queued = queue.items.value.firstOrNull;
|
||||||
|
final continues = queue.continues.value;
|
||||||
|
final next = coord.nextEpisode.value;
|
||||||
|
return ControlsSnapshot(
|
||||||
|
play: play.value,
|
||||||
|
previousLabel: coord.previousEpisode.value?.label,
|
||||||
|
// Up next's first item, else the next episode, else what continues
|
||||||
|
// this (a file's next episode).
|
||||||
|
nextLabel: queued?.title ?? next?.label ?? continues?.title,
|
||||||
|
nextIsUpNext: queued != null,
|
||||||
|
hasChapters: chapters.value.isNotEmpty,
|
||||||
|
hasDuration: duration.value > Duration.zero,
|
||||||
|
alone: coord.alone.value,
|
||||||
|
// Not a signal: read again whenever the state changes.
|
||||||
|
hasLink: coord.serverState.value != null && coord.currentLink() != null,
|
||||||
|
fullscreen: fullscreen.value,
|
||||||
|
chatOpen: chatOpen.value,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The bar's clusters, in the layout's order.
|
||||||
|
late final Computed<({List<BarControl> left, List<BarControl> right})> bar = computed(
|
||||||
|
() => barControls(snapshot.value, settings.hiddenControls.value),
|
||||||
|
);
|
||||||
|
|
||||||
|
/// What the ⚙ menu lists now.
|
||||||
|
List<ControlAction> menu() => menuActions(snapshot.peek(), settings.hiddenControls.peek());
|
||||||
|
|
||||||
|
/// Ticks on each wheel / key volume step: the skins flash the volume.
|
||||||
|
final volumeFlash = ValueNotifier(0);
|
||||||
|
|
||||||
|
/// A menu of the controls is open (the player's Esc closes it).
|
||||||
|
int menusOpen = 0;
|
||||||
|
|
||||||
|
void dispose() => volumeFlash.dispose();
|
||||||
|
|
||||||
|
// -------------------------------------------------------------- actions
|
||||||
|
|
||||||
|
/// Space: ready / not ready (being ready is "play" in a server).
|
||||||
|
void togglePlay() => coord.toggleReady();
|
||||||
|
|
||||||
|
/// A seek bar's press or drag; through `player.seek`, the user-seek
|
||||||
|
/// path, so everyone follows.
|
||||||
|
void seek(Duration to) => playback.userSeek(to);
|
||||||
|
|
||||||
|
/// Arrow keys: ±[secs], relative to a seek still in flight.
|
||||||
|
void nudge(double secs) => coord.nudge(secs);
|
||||||
|
|
||||||
|
/// +1:30 for everyone.
|
||||||
|
void skipForward() => coord.skipForward();
|
||||||
|
|
||||||
|
/// A skip pill (Skip OP / ED / 1:30).
|
||||||
|
void skip(SkipOffer offer) => coord.skip(offer);
|
||||||
|
|
||||||
|
/// PgDn (+1) / PgUp (-1). False when there is no chapter to go to.
|
||||||
|
bool stepChapter(int delta) => coord.stepChapter(delta);
|
||||||
|
|
||||||
|
void pickChapter(MediaChapter c) => coord.seekTo(c.start.inMicroseconds / 1e6);
|
||||||
|
|
||||||
|
/// What plays next (Up next's first item, else the continuation), else
|
||||||
|
/// the next episode. False when neither.
|
||||||
|
bool next() {
|
||||||
|
if (queue.head.peek() != null) {
|
||||||
|
queue.skip();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (coord.nextEpisode.peek() == null) return false;
|
||||||
|
coord.playNextEpisode();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The previous episode. False without one.
|
||||||
|
bool previous() {
|
||||||
|
if (coord.previousEpisode.peek() == null) return false;
|
||||||
|
coord.playPreviousEpisode();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void playNextEpisode() => coord.playNextEpisode();
|
||||||
|
|
||||||
|
void setVolume(double v) => playback.setVolume(v.clamp(0.0, vol.maxVolume));
|
||||||
|
|
||||||
|
/// One volume step up (+1) or down (-1) from the wheel or ↑ / ↓;
|
||||||
|
/// flashes the volume readout.
|
||||||
|
void stepVolume(int step) {
|
||||||
|
setVolume(vol.stepVolume(volume.peek(), step * vol.volumeStep));
|
||||||
|
volumeFlash.value++;
|
||||||
|
}
|
||||||
|
|
||||||
|
double _beforeMute = 100;
|
||||||
|
|
||||||
|
/// The speaker: mute, or back to the volume before.
|
||||||
|
void toggleMute() {
|
||||||
|
final v = volume.peek();
|
||||||
|
if (v > 0) {
|
||||||
|
_beforeMute = v;
|
||||||
|
setVolume(0);
|
||||||
|
} else {
|
||||||
|
setVolume(_beforeMute <= 0 ? 100 : _beforeMute);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void pickTrack(TrackPick p) => coord.selectTrack(aid: p.aid, sid: p.sid, subtitlesOff: p.subtitlesOff);
|
||||||
|
|
||||||
|
/// Saved as the choice and applied live; a null quality keeps the
|
||||||
|
/// saved one.
|
||||||
|
void pickShader(ShaderPreset preset, ShaderQuality? quality) => applyShaderChoice(coord, preset, quality);
|
||||||
|
|
||||||
|
void toggleTimeDisplay() => settings.setTimeDisplay(settings.timeDisplay.peek().toggled);
|
||||||
|
|
||||||
|
void toggleFullscreen() => _toggleFullscreen();
|
||||||
|
|
||||||
|
void toggleChat() {
|
||||||
|
coord.markInput();
|
||||||
|
_toggleChat();
|
||||||
|
}
|
||||||
|
|
||||||
|
void changeVideo() => _changeVideo();
|
||||||
|
|
||||||
|
/// Back to the library (keeps playing in the mini player).
|
||||||
|
void collapse() => _collapse();
|
||||||
|
|
||||||
|
/// Asks before leaving the server.
|
||||||
|
void leave() => _leave();
|
||||||
|
|
||||||
|
void reload() {
|
||||||
|
coord.markInput();
|
||||||
|
coord.reloadVideo();
|
||||||
|
}
|
||||||
|
|
||||||
|
void markAllReady() => coord.forcePlayAll();
|
||||||
|
|
||||||
|
String? link() => coord.currentLink();
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
// The player controls' user choices (Settings → Player, stored in
|
||||||
|
// `AppSettings`). Plain values: the layout spec and both skins read them.
|
||||||
|
|
||||||
|
/// The controls' look. Both skins draw the same controls model in the same
|
||||||
|
/// order ([ControlsLayout]); only the look differs.
|
||||||
|
enum ControlsSkin {
|
||||||
|
/// Material-style bar: a seek bar over a row of round icon buttons.
|
||||||
|
standard('Standard'),
|
||||||
|
|
||||||
|
/// The app's own timeline skin (inspired by mpv's uosc): a thick band
|
||||||
|
/// with the buffered part, chapters and times, flat glass buttons.
|
||||||
|
minimal('Minimal');
|
||||||
|
|
||||||
|
final String label;
|
||||||
|
const ControlsSkin(this.label);
|
||||||
|
|
||||||
|
/// A stored name; the old `mpvControls` flag (true: the uosc design)
|
||||||
|
/// when there is none.
|
||||||
|
static ControlsSkin fromStored(Object? name, {Object? legacyMpvControls}) {
|
||||||
|
for (final s in values) {
|
||||||
|
if (s.name == name) return s;
|
||||||
|
}
|
||||||
|
return legacyMpvControls == true ? minimal : standard;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bar's clock: "6:00 / 24:00" or the time left ("-18:00").
|
||||||
|
enum TimeDisplay {
|
||||||
|
elapsed('Elapsed / total'),
|
||||||
|
remaining('Remaining');
|
||||||
|
|
||||||
|
final String label;
|
||||||
|
const TimeDisplay(this.label);
|
||||||
|
|
||||||
|
TimeDisplay get toggled => this == elapsed ? remaining : elapsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bar and button size.
|
||||||
|
enum ControlsSize {
|
||||||
|
normal('Normal', 1.0),
|
||||||
|
large('Large', 1.25);
|
||||||
|
|
||||||
|
final String label;
|
||||||
|
final double scale;
|
||||||
|
const ControlsSize(this.label, this.scale);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bar buttons the user may hide; hidden ones are still in ⚙.
|
||||||
|
enum OptionalControl {
|
||||||
|
chapters('Chapter buttons', 'Previous / next chapter (PgUp / PgDn)'),
|
||||||
|
subtitles('Subtitles', 'The subtitle track list'),
|
||||||
|
audio('Audio', 'The audio track list'),
|
||||||
|
chat('Chat', 'Chat & activity (Tab)');
|
||||||
|
|
||||||
|
final String label;
|
||||||
|
final String help;
|
||||||
|
const OptionalControl(this.label, this.help);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The auto-hide delays offered (seconds).
|
||||||
|
const controlsHideChoices = [2, 3, 5];
|
||||||
|
|
||||||
|
/// The default auto-hide delay (seconds).
|
||||||
|
const defaultControlsHideSecs = 3;
|
||||||
@@ -6,15 +6,18 @@ import 'package:sync_relay_core/core.dart' show JellyfinStreamType;
|
|||||||
|
|
||||||
import '../jellyfin/track_prefs.dart' show MpvTrack;
|
import '../jellyfin/track_prefs.dart' show MpvTrack;
|
||||||
import '../playback/playback_controller.dart' show PlaybackController, RenderMode;
|
import '../playback/playback_controller.dart' show PlaybackController, RenderMode;
|
||||||
|
import '../session/session_coordinator.dart' show SessionCoordinator;
|
||||||
import '../shaders/shader_presets.dart';
|
import '../shaders/shader_presets.dart';
|
||||||
import '../state/session_state.dart';
|
import '../app/app_graph.dart';
|
||||||
|
import '../shell/mark_problem.dart';
|
||||||
import '../shell/motion.dart';
|
import '../shell/motion.dart';
|
||||||
import '../state/settings.dart';
|
import '../state/settings.dart';
|
||||||
import 'uosc/buttons.dart';
|
import '../widgets/app_menu.dart';
|
||||||
import 'uosc/controls.dart';
|
import 'frame.dart';
|
||||||
|
import 'model/controls_prefs.dart';
|
||||||
|
|
||||||
// Everything about the player, defined once: the rows of the ⚙ card in
|
// Everything about the player, defined once: the rows of the player
|
||||||
// both control designs and of Settings → Player. Each row reads and
|
// settings card (⚙ → Player settings, both skins) and of Settings → Player. Each row reads and
|
||||||
// writes [AppSettings] and applies to a running player right away.
|
// writes [AppSettings] and applies to a running player right away.
|
||||||
|
|
||||||
/// One setting: a label, one line of help under it, the control at the
|
/// One setting: a label, one line of help under it, the control at the
|
||||||
@@ -56,29 +59,16 @@ class SettingRow extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
DropdownButton<T> _dropdown<T>({
|
AppSelect<T> _dropdown<T>({
|
||||||
required Key key,
|
required Key key,
|
||||||
required T value,
|
required T value,
|
||||||
required List<(T, String)> items,
|
required List<(T, String)> items,
|
||||||
required ValueChanged<T> onChanged,
|
required ValueChanged<T> onChanged,
|
||||||
bool expanded = false,
|
bool expanded = false,
|
||||||
}) =>
|
}) =>
|
||||||
DropdownButton<T>(
|
AppSelect<T>(key: key, value: value, items: items, onChanged: onChanged, expanded: expanded);
|
||||||
key: key,
|
|
||||||
value: value,
|
|
||||||
isExpanded: expanded,
|
|
||||||
underline: const SizedBox.shrink(),
|
|
||||||
borderRadius: BorderRadius.circular(10),
|
|
||||||
items: [
|
|
||||||
for (final (v, label) in items)
|
|
||||||
DropdownMenuItem(value: v, child: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis)),
|
|
||||||
],
|
|
||||||
onChanged: (v) {
|
|
||||||
if (v != null) onChanged(v);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
/// Standard (our bars over media_kit's controls) or uosc. Live.
|
/// The controls' skin: Standard or Minimal. Live.
|
||||||
class PlayerDesignSetting extends StatelessWidget {
|
class PlayerDesignSetting extends StatelessWidget {
|
||||||
const PlayerDesignSetting({super.key});
|
const PlayerDesignSetting({super.key});
|
||||||
|
|
||||||
@@ -88,12 +78,100 @@ class PlayerDesignSetting extends StatelessWidget {
|
|||||||
return SignalBuilder(
|
return SignalBuilder(
|
||||||
builder: (context) => SettingRow(
|
builder: (context) => SettingRow(
|
||||||
label: 'Player design',
|
label: 'Player design',
|
||||||
help: 'uosc is modeled on mpv: a thick timeline with chapters and what is cached',
|
help: 'Minimal has a thick timeline with chapters and what is downloaded yet',
|
||||||
control: _dropdown<bool>(
|
control: _dropdown<ControlsSkin>(
|
||||||
key: const ValueKey('player-design'),
|
key: const ValueKey('player-design'),
|
||||||
value: s.mpvControls.value,
|
value: s.controlsSkin.value,
|
||||||
items: const [(false, 'Standard'), (true, 'uosc')],
|
items: [for (final k in ControlsSkin.values) (k, k.label)],
|
||||||
onChanged: s.setMpvControls,
|
onChanged: s.setControlsSkin,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bar's clock: elapsed / total or the time left. Live.
|
||||||
|
class TimeDisplaySetting extends StatelessWidget {
|
||||||
|
const TimeDisplaySetting({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final s = AppSettings.instance;
|
||||||
|
return SignalBuilder(
|
||||||
|
builder: (context) => SettingRow(
|
||||||
|
label: 'Time display',
|
||||||
|
help: 'Also switched by a click on the time',
|
||||||
|
control: _dropdown<TimeDisplay>(
|
||||||
|
key: const ValueKey('time-display'),
|
||||||
|
value: s.timeDisplay.value,
|
||||||
|
items: [for (final t in TimeDisplay.values) (t, t.label)],
|
||||||
|
onChanged: s.setTimeDisplay,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Normal or large bar and buttons. Live.
|
||||||
|
class ControlsSizeSetting extends StatelessWidget {
|
||||||
|
const ControlsSizeSetting({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final s = AppSettings.instance;
|
||||||
|
return SignalBuilder(
|
||||||
|
builder: (context) => SettingRow(
|
||||||
|
label: 'Controls size',
|
||||||
|
help: 'Large makes the bar and its buttons a quarter bigger',
|
||||||
|
control: _dropdown<ControlsSize>(
|
||||||
|
key: const ValueKey('controls-size'),
|
||||||
|
value: s.controlsSize.value,
|
||||||
|
items: [for (final z in ControlsSize.values) (z, z.label)],
|
||||||
|
onChanged: s.setControlsSize,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How long the controls stay up without mouse movement. Live.
|
||||||
|
class HideDelaySetting extends StatelessWidget {
|
||||||
|
const HideDelaySetting({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final s = AppSettings.instance;
|
||||||
|
return SignalBuilder(
|
||||||
|
builder: (context) => SettingRow(
|
||||||
|
label: 'Hide the controls after',
|
||||||
|
help: 'Without mouse movement over the video',
|
||||||
|
control: _dropdown<int>(
|
||||||
|
key: const ValueKey('controls-hide'),
|
||||||
|
value: s.controlsHideSecs.value,
|
||||||
|
items: [for (final secs in controlsHideChoices) (secs, '$secs s')],
|
||||||
|
onChanged: s.setControlsHideSecs,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One optional bar button on or off (off: it is still in ⚙). Live.
|
||||||
|
class BarButtonSetting extends StatelessWidget {
|
||||||
|
final OptionalControl control;
|
||||||
|
const BarButtonSetting({super.key, required this.control});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final s = AppSettings.instance;
|
||||||
|
return SignalBuilder(
|
||||||
|
builder: (context) => SettingRow(
|
||||||
|
label: control.label,
|
||||||
|
help: control.help,
|
||||||
|
control: Switch(
|
||||||
|
key: ValueKey('bar-${control.name}'),
|
||||||
|
value: !s.hiddenControls.value.contains(control),
|
||||||
|
onChanged: (on) => s.setControlShown(control, on),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -123,11 +201,10 @@ class ProgressLineSetting extends StatelessWidget {
|
|||||||
|
|
||||||
/// Saves a shader choice (also used on the next join) and puts it on the
|
/// Saves a shader choice (also used on the next join) and puts it on the
|
||||||
/// running player, if any; the player announces the result.
|
/// running player, if any; the player announces the result.
|
||||||
void applyShaderChoice(ShaderPreset preset, ShaderQuality? quality) {
|
void applyShaderChoice(SessionCoordinator coord, ShaderPreset preset, ShaderQuality? quality) {
|
||||||
final s = AppSettings.instance;
|
final s = AppSettings.instance;
|
||||||
if (quality != null) s.setShaderQuality(quality);
|
if (quality != null) s.setShaderQuality(quality);
|
||||||
s.setShaderPreset(preset);
|
s.setShaderPreset(preset);
|
||||||
final coord = SessionState.instance.coordinator;
|
|
||||||
coord.markInput();
|
coord.markInput();
|
||||||
coord.playback.applyShaders(announce: true);
|
coord.playback.applyShaders(announce: true);
|
||||||
}
|
}
|
||||||
@@ -145,7 +222,9 @@ class ShaderPresetSetting extends StatelessWidget {
|
|||||||
final preset = s.shaderPreset.value;
|
final preset = s.shaderPreset.value;
|
||||||
final quality = s.shaderQuality.value;
|
final quality = s.shaderQuality.value;
|
||||||
final hasCustom = s.customShaders.value.isNotEmpty;
|
final hasCustom = s.customShaders.value.isNotEmpty;
|
||||||
final mode = (renderMode ?? PlaybackController.lastRenderMode).value;
|
final mode = (renderMode ??
|
||||||
|
context.getInheritedWidgetOfExactType<AppScope>()?.graph.ports.players.renderMode)
|
||||||
|
?.value;
|
||||||
final warning = switch (mode) {
|
final warning = switch (mode) {
|
||||||
RenderMode.software => 'Software rendering: shaders have no effect',
|
RenderMode.software => 'Software rendering: shaders have no effect',
|
||||||
RenderMode.softwareGl => 'OpenGL on the CPU: shaders will be slow',
|
RenderMode.softwareGl => 'OpenGL on the CPU: shaders will be slow',
|
||||||
@@ -165,7 +244,7 @@ class ShaderPresetSetting extends StatelessWidget {
|
|||||||
for (final p in ShaderPreset.values)
|
for (final p in ShaderPreset.values)
|
||||||
if (p != ShaderPreset.custom || hasCustom || preset == p) (p, p.label),
|
if (p != ShaderPreset.custom || hasCustom || preset == p) (p, p.label),
|
||||||
],
|
],
|
||||||
onChanged: (p) => applyShaderChoice(p, null),
|
onChanged: (p) => applyShaderChoice(AppScope.of(context).coordinator, p, null),
|
||||||
),
|
),
|
||||||
if (preset.isAnime4k) ...[
|
if (preset.isAnime4k) ...[
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
@@ -173,7 +252,7 @@ class ShaderPresetSetting extends StatelessWidget {
|
|||||||
key: const ValueKey('shader-quality'),
|
key: const ValueKey('shader-quality'),
|
||||||
value: quality,
|
value: quality,
|
||||||
items: [for (final q in ShaderQuality.values) (q, q.label)],
|
items: [for (final q in ShaderQuality.values) (q, q.label)],
|
||||||
onChanged: (q) => applyShaderChoice(preset, q),
|
onChanged: (q) => applyShaderChoice(AppScope.of(context).coordinator, preset, q),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
@@ -188,13 +267,12 @@ class ShaderPresetSetting extends StatelessWidget {
|
|||||||
|
|
||||||
/// Puts the hwdec setting on the running player (mpv switches decoders
|
/// Puts the hwdec setting on the running player (mpv switches decoders
|
||||||
/// on the fly). `SYNC_RELAY_HWDEC` wins, as at player start.
|
/// on the fly). `SYNC_RELAY_HWDEC` wins, as at player start.
|
||||||
Future<void> applyHwdecLive() async {
|
Future<void> applyHwdecLive(PlaybackController playback) async {
|
||||||
if ((Platform.environment['SYNC_RELAY_HWDEC'] ?? '').isNotEmpty) return;
|
if ((Platform.environment['SYNC_RELAY_HWDEC'] ?? '').isNotEmpty) return;
|
||||||
final playback = SessionState.instance.coordinator.playback;
|
final p = playback.current;
|
||||||
if (!playback.alive.peek()) return;
|
if (p == null) return;
|
||||||
try {
|
try {
|
||||||
final dynamic platform = playback.player.platform;
|
await p.setProperty('hwdec', AppSettings.instance.hwdec.peek());
|
||||||
await platform?.setProperty('hwdec', AppSettings.instance.hwdec.peek());
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
debugPrint('live hwdec failed: $e');
|
debugPrint('live hwdec failed: $e');
|
||||||
}
|
}
|
||||||
@@ -231,7 +309,7 @@ class _HwdecSettingState extends State<HwdecSetting> {
|
|||||||
items: const [(HwdecMode.auto, 'Auto'), (HwdecMode.off, 'Off'), (HwdecMode.custom, 'Custom')],
|
items: const [(HwdecMode.auto, 'Auto'), (HwdecMode.off, 'Off'), (HwdecMode.custom, 'Custom')],
|
||||||
onChanged: (m) {
|
onChanged: (m) {
|
||||||
_s.setHwdecMode(m);
|
_s.setHwdecMode(m);
|
||||||
applyHwdecLive();
|
applyHwdecLive(AppScope.of(context).coordinator.playback);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
below: mode != HwdecMode.custom
|
below: mode != HwdecMode.custom
|
||||||
@@ -247,7 +325,7 @@ class _HwdecSettingState extends State<HwdecSetting> {
|
|||||||
border: OutlineInputBorder(),
|
border: OutlineInputBorder(),
|
||||||
),
|
),
|
||||||
onChanged: _s.setHwdecCustom,
|
onChanged: _s.setHwdecCustom,
|
||||||
onSubmitted: (_) => applyHwdecLive(),
|
onSubmitted: (_) => applyHwdecLive(AppScope.of(context).coordinator.playback),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -265,7 +343,7 @@ class TrackSetting extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final coord = SessionState.instance.coordinator;
|
final coord = AppScope.of(context).coordinator;
|
||||||
return SignalBuilder(builder: (context) {
|
return SignalBuilder(builder: (context) {
|
||||||
final list = [
|
final list = [
|
||||||
for (final t in coord.playback.tracks.value)
|
for (final t in coord.playback.tracks.value)
|
||||||
@@ -307,7 +385,20 @@ class TrackSetting extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The player rows of Settings → Player and the ⚙ card, in order.
|
/// The controls' own choices (Settings → Player → Controls).
|
||||||
|
List<Widget> controlsSettingRows() => [
|
||||||
|
const TimeDisplaySetting(),
|
||||||
|
const ControlsSizeSetting(),
|
||||||
|
const HideDelaySetting(),
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.only(top: 10, bottom: 2),
|
||||||
|
child: Text('Buttons in the bar (hidden ones stay in ⚙)', style: TextStyle(fontWeight: FontWeight.w600)),
|
||||||
|
),
|
||||||
|
for (final c in OptionalControl.values) BarButtonSetting(control: c),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The player rows of Settings → Player and the player settings card, in
|
||||||
|
/// order.
|
||||||
List<Widget> playerSettingRows({ReadonlySignal<RenderMode>? renderMode}) => [
|
List<Widget> playerSettingRows({ReadonlySignal<RenderMode>? renderMode}) => [
|
||||||
const PlayerDesignSetting(),
|
const PlayerDesignSetting(),
|
||||||
const ProgressLineSetting(),
|
const ProgressLineSetting(),
|
||||||
@@ -315,7 +406,8 @@ List<Widget> playerSettingRows({ReadonlySignal<RenderMode>? renderMode}) => [
|
|||||||
const HwdecSetting(),
|
const HwdecSetting(),
|
||||||
];
|
];
|
||||||
|
|
||||||
/// The ⚙ card: every player setting, plus the running player's tracks.
|
/// The player settings card: every player setting, plus the running
|
||||||
|
/// player's tracks.
|
||||||
class PlayerSettingsCard extends StatelessWidget {
|
class PlayerSettingsCard extends StatelessWidget {
|
||||||
final ReadonlySignal<RenderMode>? renderMode;
|
final ReadonlySignal<RenderMode>? renderMode;
|
||||||
/// Show the audio / subtitle pickers (a player is running).
|
/// Show the audio / subtitle pickers (a player is running).
|
||||||
@@ -324,19 +416,18 @@ class PlayerSettingsCard extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Material(
|
// The app's glass, like the Up next popover and the menus.
|
||||||
|
return AppGlass(
|
||||||
key: const ValueKey('player-settings-card'),
|
key: const ValueKey('player-settings-card'),
|
||||||
elevation: 12,
|
|
||||||
borderRadius: BorderRadius.circular(16),
|
|
||||||
child: SizedBox(
|
child: SizedBox(
|
||||||
width: 420,
|
width: 420,
|
||||||
child: Padding(
|
child: Padding(
|
||||||
padding: const EdgeInsets.fromLTRB(18, 14, 18, 10),
|
padding: const EdgeInsets.fromLTRB(16, 12, 16, 10),
|
||||||
child: Column(
|
child: Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
const Text('Player', style: TextStyle(fontWeight: FontWeight.w700, fontSize: 16)),
|
const Text('Player', style: TextStyle(fontWeight: FontWeight.w600, fontSize: 14)),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
...playerSettingRows(renderMode: renderMode),
|
...playerSettingRows(renderMode: renderMode),
|
||||||
if (tracks) ...[
|
if (tracks) ...[
|
||||||
@@ -345,10 +436,17 @@ class PlayerSettingsCard extends StatelessWidget {
|
|||||||
const TrackSetting(type: JellyfinStreamType.audio),
|
const TrackSetting(type: JellyfinStreamType.audio),
|
||||||
],
|
],
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
Text(
|
Row(
|
||||||
'Custom shader files: Settings → Player',
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
'Controls layout and custom shaders: Settings → Player',
|
||||||
style: TextStyle(color: Theme.of(context).colorScheme.onSurfaceVariant, fontSize: 12),
|
style: TextStyle(color: Theme.of(context).colorScheme.onSurfaceVariant, fontSize: 12),
|
||||||
),
|
),
|
||||||
|
),
|
||||||
|
const MarkProblemButton(),
|
||||||
|
],
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -357,51 +455,14 @@ class PlayerSettingsCard extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Opens the ⚙ card over the player, near the controls' right end. The
|
/// Opens the player settings card over the player, near the controls'
|
||||||
/// uosc controls stay up while it is open.
|
/// right end; the controls stay up while it is open.
|
||||||
Future<void> showPlayerSettings(BuildContext context, {ReadonlySignal<RenderMode>? renderMode}) {
|
Future<void> showPlayerSettings(BuildContext context, {ReadonlySignal<RenderMode>? renderMode}) =>
|
||||||
Future<void> open() => showPopover<void>(
|
ControlsFrame.holdWhile(
|
||||||
|
context,
|
||||||
|
() => showPopover<void>(
|
||||||
context,
|
context,
|
||||||
at: const Alignment(0.96, 0.5),
|
at: const Alignment(0.96, 0.5),
|
||||||
child: PlayerSettingsCard(renderMode: renderMode),
|
child: PlayerSettingsCard(renderMode: renderMode),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
final controls = UoscControls.maybeOf(context);
|
|
||||||
return controls == null ? open() : controls.holdDuring(open);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// ⚙ in the standard controls' bottom bar.
|
|
||||||
class PlayerSettingsButton extends StatelessWidget {
|
|
||||||
final FocusNode? focusNode;
|
|
||||||
final ReadonlySignal<RenderMode>? renderMode;
|
|
||||||
const PlayerSettingsButton({super.key, this.focusNode, this.renderMode});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return IconButton(
|
|
||||||
key: const ValueKey('player-settings'),
|
|
||||||
focusNode: focusNode,
|
|
||||||
tooltip: 'Player settings',
|
|
||||||
color: Colors.white,
|
|
||||||
iconSize: 20,
|
|
||||||
visualDensity: VisualDensity.compact,
|
|
||||||
icon: const Icon(Icons.tune),
|
|
||||||
onPressed: () => showPlayerSettings(context, renderMode: renderMode),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// ⚙ in the uosc controls' button row.
|
|
||||||
class UoscPlayerSettingsButton extends StatelessWidget {
|
|
||||||
final ReadonlySignal<RenderMode>? renderMode;
|
|
||||||
const UoscPlayerSettingsButton({super.key, this.renderMode});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return UoscButton(
|
|
||||||
key: const ValueKey('uosc-player-settings'),
|
|
||||||
icon: Icons.tune_rounded,
|
|
||||||
tooltip: 'Player settings',
|
|
||||||
onPressed: () => showPlayerSettings(context, renderMode: renderMode),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:signals/signals_flutter.dart';
|
||||||
|
|
||||||
|
import '../state/settings.dart';
|
||||||
|
import 'controls_probe.dart' show ControlsHold;
|
||||||
|
import 'frame.dart';
|
||||||
|
import 'minimal/minimal_controls.dart';
|
||||||
|
import 'model/controls_model.dart';
|
||||||
|
import 'model/controls_prefs.dart';
|
||||||
|
import 'standard/standard_controls.dart';
|
||||||
|
|
||||||
|
// The session's controls: one [ControlsFrame] (when they are up) around the
|
||||||
|
// skin the settings pick, both drawing the same [PlayerControlsModel].
|
||||||
|
// Skin, size and the hide delay follow the settings live.
|
||||||
|
|
||||||
|
/// The bottom controls' height in [skin] at [size] (the player's floating
|
||||||
|
/// pills sit just above it).
|
||||||
|
double controlsBottomHeight(ControlsSkin skin, ControlsSize size) => switch (skin) {
|
||||||
|
ControlsSkin.standard => StandardControls.bottomHeight(size.scale),
|
||||||
|
ControlsSkin.minimal => MinimalControls.bottomHeight(size.scale),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The top bar's height in [skin].
|
||||||
|
double controlsTopHeight(ControlsSkin skin) => switch (skin) {
|
||||||
|
ControlsSkin.standard => StandardControls.topHeight,
|
||||||
|
ControlsSkin.minimal => MinimalControls.topHeight,
|
||||||
|
};
|
||||||
|
|
||||||
|
class SessionControls extends StatelessWidget {
|
||||||
|
final PlayerControlsModel model;
|
||||||
|
|
||||||
|
/// Follows whether the controls are up.
|
||||||
|
final ValueNotifier<bool> shown;
|
||||||
|
final ControlsHold hold;
|
||||||
|
final VoidCallback onDoubleClick;
|
||||||
|
final Widget? windowButtons;
|
||||||
|
const SessionControls({
|
||||||
|
super.key,
|
||||||
|
required this.model,
|
||||||
|
required this.shown,
|
||||||
|
required this.hold,
|
||||||
|
required this.onDoubleClick,
|
||||||
|
this.windowButtons,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final s = AppSettings.instance;
|
||||||
|
return SignalBuilder(
|
||||||
|
builder: (context) {
|
||||||
|
final skin = s.controlsSkin.value;
|
||||||
|
final size = s.controlsSize.value;
|
||||||
|
final scale = size.scale;
|
||||||
|
return ControlsFrame(
|
||||||
|
// A new frame per skin: each starts up, like a fresh mount.
|
||||||
|
key: ValueKey(skin),
|
||||||
|
shown: shown,
|
||||||
|
holdBy: hold,
|
||||||
|
hideAfter: Duration(seconds: s.controlsHideSecs.value),
|
||||||
|
onDoubleClick: onDoubleClick,
|
||||||
|
barTop: controlsTopHeight(skin),
|
||||||
|
barBottom: controlsBottomHeight(skin, size),
|
||||||
|
builder: (context, visible) => switch (skin) {
|
||||||
|
ControlsSkin.standard => StandardControls(
|
||||||
|
model: model,
|
||||||
|
visible: visible,
|
||||||
|
scale: scale,
|
||||||
|
hold: hold,
|
||||||
|
windowButtons: windowButtons,
|
||||||
|
),
|
||||||
|
ControlsSkin.minimal => MinimalControls(
|
||||||
|
model: model,
|
||||||
|
visible: visible,
|
||||||
|
scale: scale,
|
||||||
|
hold: hold,
|
||||||
|
windowButtons: windowButtons,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
import 'dart:math' as math;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../../playback/media_marks.dart';
|
||||||
|
import '../frame.dart';
|
||||||
|
|
||||||
|
// The Standard skin's seek bar: a Material-style track with the played and
|
||||||
|
// buffered parts, chapter marks and a hover tip.
|
||||||
|
|
||||||
|
/// The seek bar: played / buffered track, a diamond at each chapter start
|
||||||
|
/// (not the one at 0), and on hover the time with the chapter title above
|
||||||
|
/// it. Like media_kit's bar it reports a seek on every drag move and on
|
||||||
|
/// release ([onSeek]); the session routes those through the user-seek path
|
||||||
|
/// (debounced, everyone follows).
|
||||||
|
class ChapterSeekBar extends StatefulWidget {
|
||||||
|
final Duration position;
|
||||||
|
final Duration duration;
|
||||||
|
final Duration buffer;
|
||||||
|
final List<MediaChapter> chapters;
|
||||||
|
final ValueChanged<Duration> onSeek;
|
||||||
|
|
||||||
|
/// The bar's height (its hit area); the track is centred in it.
|
||||||
|
final double height;
|
||||||
|
const ChapterSeekBar({
|
||||||
|
super.key,
|
||||||
|
required this.position,
|
||||||
|
required this.duration,
|
||||||
|
this.buffer = Duration.zero,
|
||||||
|
this.chapters = const [],
|
||||||
|
required this.onSeek,
|
||||||
|
this.height = ChapterSeekBar.defaultHeight,
|
||||||
|
});
|
||||||
|
|
||||||
|
static const defaultHeight = 28.0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<ChapterSeekBar> createState() => _ChapterSeekBarState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ChapterSeekBarState extends State<ChapterSeekBar> {
|
||||||
|
double? _hoverX;
|
||||||
|
bool _dragging = false;
|
||||||
|
double _dragFraction = 0;
|
||||||
|
|
||||||
|
double _fraction(Duration d) {
|
||||||
|
final total = widget.duration.inMicroseconds;
|
||||||
|
if (total <= 0) return 0;
|
||||||
|
return (d.inMicroseconds / total).clamp(0.0, 1.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
Duration _at(double fraction) => widget.duration * fraction.clamp(0.0, 1.0);
|
||||||
|
|
||||||
|
// A drag sends no hover events: the controls are held up through it.
|
||||||
|
void _drag(bool on) {
|
||||||
|
if (_dragging == on) return;
|
||||||
|
setState(() => _dragging = on);
|
||||||
|
ControlsFrame.maybeOf(context)?.hold(on);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
if (_dragging) ControlsFrame.maybeOf(context)?.hold(false);
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _seekTo(double x, double width) {
|
||||||
|
if (widget.duration <= Duration.zero || width <= 0) return;
|
||||||
|
_dragFraction = (x / width).clamp(0.0, 1.0);
|
||||||
|
widget.onSeek(_at(_dragFraction));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final primary = Theme.of(context).colorScheme.primary;
|
||||||
|
return LayoutBuilder(
|
||||||
|
builder: (context, constraints) {
|
||||||
|
final width = constraints.maxWidth;
|
||||||
|
final active = _hoverX != null || _dragging;
|
||||||
|
final barHeight = active ? 5.0 : 3.0;
|
||||||
|
final played = _dragging ? _dragFraction : _fraction(widget.position);
|
||||||
|
final mid = widget.height / 2;
|
||||||
|
final hoverX = _hoverX;
|
||||||
|
final hoverAt = hoverX == null || width <= 0 ? null : _at(hoverX / width);
|
||||||
|
final hoverChapter = hoverAt == null ? null : chapterIndexAt(widget.chapters, hoverAt);
|
||||||
|
final hoverTitle = hoverChapter == null ? '' : widget.chapters[hoverChapter].title;
|
||||||
|
return MouseRegion(
|
||||||
|
cursor: SystemMouseCursors.click,
|
||||||
|
onEnter: (e) => setState(() => _hoverX = e.localPosition.dx.clamp(0, width)),
|
||||||
|
onHover: (e) => setState(() => _hoverX = e.localPosition.dx.clamp(0, width)),
|
||||||
|
onExit: (_) => setState(() => _hoverX = null),
|
||||||
|
child: Listener(
|
||||||
|
behavior: HitTestBehavior.opaque,
|
||||||
|
onPointerDown: (e) {
|
||||||
|
_dragFraction = width <= 0 ? 0 : (e.localPosition.dx / width).clamp(0.0, 1.0);
|
||||||
|
_drag(true);
|
||||||
|
},
|
||||||
|
onPointerMove: (e) {
|
||||||
|
setState(() => _hoverX = e.localPosition.dx.clamp(0, width));
|
||||||
|
_seekTo(e.localPosition.dx, width);
|
||||||
|
},
|
||||||
|
onPointerUp: (e) {
|
||||||
|
_seekTo(e.localPosition.dx, width);
|
||||||
|
_drag(false);
|
||||||
|
},
|
||||||
|
onPointerCancel: (_) => _drag(false),
|
||||||
|
child: SizedBox(
|
||||||
|
key: const ValueKey('seek-bar'),
|
||||||
|
width: width,
|
||||||
|
height: widget.height,
|
||||||
|
child: Stack(
|
||||||
|
clipBehavior: Clip.none,
|
||||||
|
children: [
|
||||||
|
Positioned(
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
top: mid - barHeight / 2,
|
||||||
|
height: barHeight,
|
||||||
|
child: Container(color: Colors.white24),
|
||||||
|
),
|
||||||
|
Positioned(
|
||||||
|
left: 0,
|
||||||
|
top: mid - barHeight / 2,
|
||||||
|
height: barHeight,
|
||||||
|
width: width * _fraction(widget.buffer),
|
||||||
|
child: Container(color: Colors.white24),
|
||||||
|
),
|
||||||
|
if (hoverX != null && !_dragging)
|
||||||
|
Positioned(
|
||||||
|
left: 0,
|
||||||
|
top: mid - barHeight / 2,
|
||||||
|
height: barHeight,
|
||||||
|
width: hoverX,
|
||||||
|
child: Container(color: Colors.white24),
|
||||||
|
),
|
||||||
|
Positioned(
|
||||||
|
left: 0,
|
||||||
|
top: mid - barHeight / 2,
|
||||||
|
height: barHeight,
|
||||||
|
width: width * played,
|
||||||
|
child: Container(color: primary),
|
||||||
|
),
|
||||||
|
for (final c in widget.chapters)
|
||||||
|
if (c.start > Duration.zero && widget.duration > Duration.zero)
|
||||||
|
Positioned(
|
||||||
|
key: ValueKey('chapter-mark-${c.index}'),
|
||||||
|
left: width * _fraction(c.start) - 4,
|
||||||
|
top: mid - 4,
|
||||||
|
width: 8,
|
||||||
|
height: 8,
|
||||||
|
child: IgnorePointer(
|
||||||
|
child: Transform.rotate(
|
||||||
|
angle: math.pi / 4,
|
||||||
|
child: Container(
|
||||||
|
margin: const EdgeInsets.all(1),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Colors.white,
|
||||||
|
border: Border.all(color: Colors.black54, width: 0.8),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (active)
|
||||||
|
Positioned(
|
||||||
|
left: width * played - 6,
|
||||||
|
top: mid - 6,
|
||||||
|
width: 12,
|
||||||
|
height: 12,
|
||||||
|
child: IgnorePointer(
|
||||||
|
child: DecoratedBox(
|
||||||
|
decoration: BoxDecoration(color: primary, shape: BoxShape.circle),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (hoverAt != null)
|
||||||
|
Positioned(
|
||||||
|
// Kept clear of the window edges (the tip is centred).
|
||||||
|
left: hoverX!.clamp(math.min(60.0, width / 2), math.max(width - 60, width / 2)),
|
||||||
|
bottom: widget.height - 2,
|
||||||
|
child: IgnorePointer(
|
||||||
|
child: FractionalTranslation(
|
||||||
|
translation: const Offset(-0.5, 0),
|
||||||
|
child: _HoverTip(title: hoverTitle, time: formatClock(hoverAt)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _HoverTip extends StatelessWidget {
|
||||||
|
final String title;
|
||||||
|
final String time;
|
||||||
|
const _HoverTip({required this.title, required this.time});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Container(
|
||||||
|
constraints: const BoxConstraints(maxWidth: 320),
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||||
|
decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.8), borderRadius: BorderRadius.circular(6)),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
if (title.isNotEmpty)
|
||||||
|
Text(
|
||||||
|
title,
|
||||||
|
key: const ValueKey('seek-hover-chapter'),
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: const TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
|
||||||
|
),
|
||||||
|
Text(
|
||||||
|
time,
|
||||||
|
key: const ValueKey('seek-hover-time'),
|
||||||
|
style: const TextStyle(color: Colors.white70, fontSize: 11),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,340 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:signals/signals_flutter.dart';
|
||||||
|
import 'package:sync_relay_core/core.dart' show JellyfinStreamType;
|
||||||
|
|
||||||
|
import '../../queue/queue_ui.dart';
|
||||||
|
import '../../shell/now_playing_title.dart';
|
||||||
|
import '../../state/settings.dart';
|
||||||
|
import '../control_menus.dart';
|
||||||
|
import '../controls_probe.dart' show ControlsHold;
|
||||||
|
import '../frame.dart';
|
||||||
|
import '../model/controls_layout.dart';
|
||||||
|
import '../model/controls_model.dart';
|
||||||
|
import '../volume.dart';
|
||||||
|
import 'seek_bar.dart';
|
||||||
|
|
||||||
|
// The Standard skin: Material-style bars over the picture. Top: what plays,
|
||||||
|
// Up next and the window controls; bottom: the seek bar (chapter marks,
|
||||||
|
// hover time) over a row of round icon buttons in the layout's order.
|
||||||
|
// Hidden, a thin progress line stays (unless switched off).
|
||||||
|
|
||||||
|
class StandardControls extends StatelessWidget {
|
||||||
|
final PlayerControlsModel model;
|
||||||
|
final bool visible;
|
||||||
|
final double scale;
|
||||||
|
final ControlsHold? hold;
|
||||||
|
|
||||||
|
/// Right of the top bar's own buttons (the window buttons in fullscreen).
|
||||||
|
final Widget? windowButtons;
|
||||||
|
const StandardControls({
|
||||||
|
super.key,
|
||||||
|
required this.model,
|
||||||
|
required this.visible,
|
||||||
|
this.scale = 1,
|
||||||
|
this.hold,
|
||||||
|
this.windowButtons,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The top bar: room for the cover (2:3, 60 px tall).
|
||||||
|
static const topHeight = 72.0;
|
||||||
|
static const _rowHeight = 56.0;
|
||||||
|
|
||||||
|
/// The bottom bar (seek bar and buttons) at [scale].
|
||||||
|
static double bottomHeight(double scale) => (_rowHeight + ChapterSeekBar.defaultHeight) * scale;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
const fade = ControlsFrame.fade;
|
||||||
|
Widget bar(Widget child) => IgnorePointer(
|
||||||
|
ignoring: !visible,
|
||||||
|
child: AnimatedOpacity(duration: fade, opacity: visible ? 1 : 0, child: child),
|
||||||
|
);
|
||||||
|
// No button here takes focus (Space is the ready key); the top bar's
|
||||||
|
// Up next keeps its own (its popover has a text field).
|
||||||
|
return Stack(
|
||||||
|
children: [
|
||||||
|
Positioned(
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
top: 0,
|
||||||
|
child: bar(
|
||||||
|
DecoratedBox(
|
||||||
|
decoration: const BoxDecoration(
|
||||||
|
gradient: LinearGradient(
|
||||||
|
begin: Alignment.topCenter,
|
||||||
|
end: Alignment.bottomCenter,
|
||||||
|
colors: [Color(0x99000000), Color(0x00000000)],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: SizedBox(
|
||||||
|
key: const ValueKey('standard-top'),
|
||||||
|
height: topHeight,
|
||||||
|
child: Padding(padding: const EdgeInsets.only(left: 16, right: 8), child: _top()),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Positioned(
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
bottom: 0,
|
||||||
|
child: bar(
|
||||||
|
DecoratedBox(
|
||||||
|
decoration: const BoxDecoration(
|
||||||
|
gradient: LinearGradient(
|
||||||
|
begin: Alignment.topCenter,
|
||||||
|
end: Alignment.bottomCenter,
|
||||||
|
colors: [Color(0x00000000), Color(0xB3000000)],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Padding(
|
||||||
|
padding: EdgeInsets.only(top: 24 * scale),
|
||||||
|
child: SizedBox(
|
||||||
|
key: const ValueKey('standard-bottom'),
|
||||||
|
height: bottomHeight(scale),
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||||
|
child: SignalBuilder(
|
||||||
|
builder: (context) => ChapterSeekBar(
|
||||||
|
position: model.position.value,
|
||||||
|
duration: model.duration.value,
|
||||||
|
buffer: model.buffered.value,
|
||||||
|
chapters: model.chapters.value,
|
||||||
|
height: ChapterSeekBar.defaultHeight * scale,
|
||||||
|
onSeek: model.seek,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Expanded(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||||
|
child: ExcludeFocus(
|
||||||
|
child: SignalBuilder(
|
||||||
|
builder: (context) {
|
||||||
|
final s = model.snapshot.value;
|
||||||
|
final layout = model.bar.value;
|
||||||
|
return Row(
|
||||||
|
key: const ValueKey('standard-buttons'),
|
||||||
|
children: [
|
||||||
|
for (final c in layout.left) _control(context, c, s),
|
||||||
|
const Spacer(),
|
||||||
|
for (final c in layout.right) _control(context, c, s),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
// Hidden: the thin progress line.
|
||||||
|
Positioned(
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
bottom: 0,
|
||||||
|
child: IgnorePointer(
|
||||||
|
child: SignalBuilder(
|
||||||
|
builder: (context) {
|
||||||
|
if (visible || !AppSettings.instance.progressLine.value) return const SizedBox.shrink();
|
||||||
|
final d = model.duration.value, p = model.position.value;
|
||||||
|
final v = d.inMilliseconds == 0 ? 0.0 : (p.inMilliseconds / d.inMilliseconds).clamp(0.0, 1.0);
|
||||||
|
return LinearProgressIndicator(
|
||||||
|
key: const ValueKey('progress-line-standard'),
|
||||||
|
value: v,
|
||||||
|
minHeight: 2,
|
||||||
|
backgroundColor: Colors.transparent,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _top() {
|
||||||
|
final m = model;
|
||||||
|
return Row(
|
||||||
|
children: [
|
||||||
|
const Expanded(child: NowPlayingTitle()),
|
||||||
|
UpNextButton(queue: m.queue, look: UpNextLook.standard, hold: hold),
|
||||||
|
SignalBuilder(
|
||||||
|
builder: (context) {
|
||||||
|
final full = m.fullscreen.value;
|
||||||
|
return ExcludeFocus(
|
||||||
|
child: _IconButton(
|
||||||
|
key: const ValueKey('standard-collapse'),
|
||||||
|
icon: full ? Icons.fullscreen_exit_rounded : Icons.close_fullscreen_rounded,
|
||||||
|
tooltip: full ? 'Exit fullscreen (Esc)' : 'Back to the library (keeps playing)',
|
||||||
|
onPressed: full ? m.toggleFullscreen : m.collapse,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
?windowButtons,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _control(BuildContext context, BarControl c, ControlsSnapshot s) {
|
||||||
|
final m = model;
|
||||||
|
final key = ValueKey('control-${c.name}');
|
||||||
|
final enabled = controlEnabled(c, s);
|
||||||
|
Widget icon(VoidCallback? onPressed, {int badge = 0, double size = 24, Color? color}) => _IconButton(
|
||||||
|
key: key,
|
||||||
|
icon: controlIcon(c, s),
|
||||||
|
tooltip: controlTooltip(c, s),
|
||||||
|
badge: badge,
|
||||||
|
size: size * scale,
|
||||||
|
color: color,
|
||||||
|
onPressed: enabled ? onPressed : null,
|
||||||
|
);
|
||||||
|
switch (c) {
|
||||||
|
case BarControl.playPause:
|
||||||
|
final waiting = s.play == PlayState.waiting;
|
||||||
|
return icon(m.togglePlay, size: 30, color: waiting ? Theme.of(context).colorScheme.primary : null);
|
||||||
|
case BarControl.previous:
|
||||||
|
return icon(m.previous);
|
||||||
|
case BarControl.next:
|
||||||
|
return icon(m.next);
|
||||||
|
case BarControl.chapterPrevious:
|
||||||
|
return icon(() => m.stepChapter(-1));
|
||||||
|
case BarControl.chapterNext:
|
||||||
|
return icon(() => m.stepChapter(1));
|
||||||
|
case BarControl.volume:
|
||||||
|
return SignalBuilder(
|
||||||
|
key: key,
|
||||||
|
builder: (context) => VolumeControl(
|
||||||
|
volume: m.volume.value,
|
||||||
|
onChanged: m.setVolume,
|
||||||
|
onToggleMute: m.toggleMute,
|
||||||
|
button: (context, i, color, tip, onPressed) =>
|
||||||
|
_IconButton(icon: i, tooltip: tip, color: color, size: 24 * scale, onPressed: onPressed),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
case BarControl.time:
|
||||||
|
return SignalBuilder(
|
||||||
|
key: key,
|
||||||
|
builder: (context) => _Clock(
|
||||||
|
text: clockText(m.position.value, m.duration.value, m.settings.timeDisplay.value),
|
||||||
|
tooltip: controlTooltip(c, s),
|
||||||
|
scale: scale,
|
||||||
|
onPressed: m.toggleTimeDisplay,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
case BarControl.subtitles || BarControl.audio:
|
||||||
|
final type = c == BarControl.audio ? JellyfinStreamType.audio : JellyfinStreamType.subtitle;
|
||||||
|
return SignalBuilder(
|
||||||
|
key: key,
|
||||||
|
builder: (context) => Builder(
|
||||||
|
builder: (context) => _IconButton(
|
||||||
|
icon: controlIcon(c, s),
|
||||||
|
tooltip: controlTooltip(c, s),
|
||||||
|
badge: trackCount(m.tracks.value, type),
|
||||||
|
size: 22 * scale,
|
||||||
|
onPressed: () => openTrackMenu(context, m, type),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
case BarControl.settings:
|
||||||
|
return Builder(
|
||||||
|
key: key,
|
||||||
|
builder: (context) => _IconButton(
|
||||||
|
icon: controlIcon(c, s),
|
||||||
|
tooltip: controlTooltip(c, s),
|
||||||
|
size: 22 * scale,
|
||||||
|
onPressed: () => openControlsMenu(context, m),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
case BarControl.chat:
|
||||||
|
return SignalBuilder(
|
||||||
|
key: key,
|
||||||
|
builder: (context) => _IconButton(
|
||||||
|
icon: controlIcon(c, s),
|
||||||
|
tooltip: controlTooltip(c, s),
|
||||||
|
badge: m.unread.value,
|
||||||
|
size: 22 * scale,
|
||||||
|
onPressed: m.toggleChat,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
case BarControl.fullscreen:
|
||||||
|
return icon(m.toggleFullscreen, size: 26);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A round white icon button with an optional count badge (the Material
|
||||||
|
/// look of media_kit's bar).
|
||||||
|
class _IconButton extends StatelessWidget {
|
||||||
|
final IconData icon;
|
||||||
|
final String tooltip;
|
||||||
|
final VoidCallback? onPressed;
|
||||||
|
final int badge;
|
||||||
|
final double size;
|
||||||
|
final Color? color;
|
||||||
|
const _IconButton({
|
||||||
|
super.key,
|
||||||
|
required this.icon,
|
||||||
|
required this.tooltip,
|
||||||
|
required this.onPressed,
|
||||||
|
this.badge = 0,
|
||||||
|
this.size = 24,
|
||||||
|
this.color,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final scheme = Theme.of(context).colorScheme;
|
||||||
|
return IconButton(
|
||||||
|
tooltip: tooltip,
|
||||||
|
iconSize: size,
|
||||||
|
color: color ?? Colors.white,
|
||||||
|
disabledColor: Colors.white38,
|
||||||
|
onPressed: onPressed,
|
||||||
|
icon: Badge(
|
||||||
|
isLabelVisible: badge > 0,
|
||||||
|
backgroundColor: scheme.primary,
|
||||||
|
textColor: scheme.onPrimary,
|
||||||
|
label: Text('$badge'),
|
||||||
|
child: Icon(icon),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The clock: "6:00 / 24:00" or "-18:00"; a click switches.
|
||||||
|
class _Clock extends StatelessWidget {
|
||||||
|
final String text;
|
||||||
|
final String tooltip;
|
||||||
|
final double scale;
|
||||||
|
final VoidCallback onPressed;
|
||||||
|
const _Clock({required this.text, required this.tooltip, required this.scale, required this.onPressed});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Tooltip(
|
||||||
|
message: tooltip,
|
||||||
|
waitDuration: const Duration(milliseconds: 500),
|
||||||
|
child: TextButton(
|
||||||
|
style: TextButton.styleFrom(
|
||||||
|
foregroundColor: Colors.white,
|
||||||
|
padding: EdgeInsets.symmetric(horizontal: 10 * scale),
|
||||||
|
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||||
|
),
|
||||||
|
onPressed: onPressed,
|
||||||
|
child: Text(
|
||||||
|
text,
|
||||||
|
style: TextStyle(fontSize: 14 * scale, fontFeatures: const [FontFeature.tabularFigures()]),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,362 +0,0 @@
|
|||||||
import 'package:flutter/gestures.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:signals/signals_flutter.dart';
|
|
||||||
import 'package:sync_relay_core/core.dart' show JellyfinStreamType;
|
|
||||||
|
|
||||||
import '../../jellyfin/track_prefs.dart' show MpvTrack;
|
|
||||||
import '../../playback/media_marks.dart';
|
|
||||||
import '../../playback/playback_controller.dart' show RenderMode;
|
|
||||||
import '../../screens/session/player_controls.dart' show TrackPick;
|
|
||||||
import '../../shaders/shader_menu.dart';
|
|
||||||
import '../../shaders/shader_presets.dart';
|
|
||||||
import '../../state/settings.dart';
|
|
||||||
import '../volume.dart';
|
|
||||||
import 'controls.dart';
|
|
||||||
import 'menu.dart';
|
|
||||||
import 'style.dart';
|
|
||||||
|
|
||||||
/// Flat uosc button: a white icon (optionally a [label] beside it and a
|
|
||||||
/// small count [badge] in the corner), a faint highlight on hover, a dark
|
|
||||||
/// tooltip. Never takes focus (the session's keys are global).
|
|
||||||
class UoscButton extends StatefulWidget {
|
|
||||||
final IconData icon;
|
|
||||||
final String tooltip;
|
|
||||||
final VoidCallback? onPressed;
|
|
||||||
final String? label;
|
|
||||||
final int? badge;
|
|
||||||
/// Tint for an "on" state (ready, shaders on).
|
|
||||||
final Color? color;
|
|
||||||
const UoscButton({
|
|
||||||
super.key,
|
|
||||||
required this.icon,
|
|
||||||
required this.tooltip,
|
|
||||||
required this.onPressed,
|
|
||||||
this.label,
|
|
||||||
this.badge,
|
|
||||||
this.color,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<UoscButton> createState() => _UoscButtonState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _UoscButtonState extends State<UoscButton> {
|
|
||||||
bool _hover = false;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final w = widget;
|
|
||||||
final color = w.onPressed == null ? UoscStyle.dim.withValues(alpha: 0.4) : (w.color ?? UoscStyle.text);
|
|
||||||
final badge = w.badge;
|
|
||||||
return UoscTooltip(
|
|
||||||
message: w.tooltip,
|
|
||||||
child: MouseRegion(
|
|
||||||
cursor: w.onPressed == null ? SystemMouseCursors.basic : SystemMouseCursors.click,
|
|
||||||
onEnter: (_) => setState(() => _hover = true),
|
|
||||||
onExit: (_) => setState(() => _hover = false),
|
|
||||||
child: GestureDetector(
|
|
||||||
behavior: HitTestBehavior.opaque,
|
|
||||||
onTap: w.onPressed,
|
|
||||||
child: Container(
|
|
||||||
height: UoscControls.buttonRowHeight,
|
|
||||||
constraints: const BoxConstraints(minWidth: UoscControls.buttonRowHeight),
|
|
||||||
padding: EdgeInsets.symmetric(horizontal: w.label == null ? 0 : 8),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: _hover && w.onPressed != null ? UoscStyle.hover : Colors.transparent,
|
|
||||||
borderRadius: BorderRadius.circular(UoscStyle.radius),
|
|
||||||
),
|
|
||||||
child: Row(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
|
||||||
children: [
|
|
||||||
Stack(
|
|
||||||
clipBehavior: Clip.none,
|
|
||||||
children: [
|
|
||||||
Icon(w.icon, color: color, size: 22),
|
|
||||||
if (badge != null && badge > 0)
|
|
||||||
Positioned(
|
|
||||||
right: -8,
|
|
||||||
bottom: -5,
|
|
||||||
child: Container(
|
|
||||||
key: const ValueKey('uosc-badge'),
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 3),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: UoscStyle.text,
|
|
||||||
borderRadius: BorderRadius.circular(3),
|
|
||||||
),
|
|
||||||
child: Text('$badge',
|
|
||||||
style: const TextStyle(
|
|
||||||
color: Colors.black, fontSize: 9, height: 1.3, fontWeight: FontWeight.w700)),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
if (w.label != null) ...[
|
|
||||||
const SizedBox(width: 6),
|
|
||||||
Text(w.label!, style: TextStyle(color: color, fontSize: UoscStyle.fontSize)),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Badge-style text button ("HQ" in uosc): a small outlined box with a
|
|
||||||
/// short label, filled when [active].
|
|
||||||
class UoscBadgeButton extends StatefulWidget {
|
|
||||||
final String text;
|
|
||||||
final String tooltip;
|
|
||||||
final bool active;
|
|
||||||
final VoidCallback onPressed;
|
|
||||||
const UoscBadgeButton({
|
|
||||||
super.key,
|
|
||||||
required this.text,
|
|
||||||
required this.tooltip,
|
|
||||||
required this.active,
|
|
||||||
required this.onPressed,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<UoscBadgeButton> createState() => _UoscBadgeButtonState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _UoscBadgeButtonState extends State<UoscBadgeButton> {
|
|
||||||
bool _hover = false;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final w = widget;
|
|
||||||
return UoscTooltip(
|
|
||||||
message: w.tooltip,
|
|
||||||
child: MouseRegion(
|
|
||||||
cursor: SystemMouseCursors.click,
|
|
||||||
onEnter: (_) => setState(() => _hover = true),
|
|
||||||
onExit: (_) => setState(() => _hover = false),
|
|
||||||
child: GestureDetector(
|
|
||||||
behavior: HitTestBehavior.opaque,
|
|
||||||
onTap: w.onPressed,
|
|
||||||
child: Container(
|
|
||||||
height: UoscControls.buttonRowHeight,
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 6),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: _hover ? UoscStyle.hover : Colors.transparent,
|
|
||||||
borderRadius: BorderRadius.circular(UoscStyle.radius),
|
|
||||||
),
|
|
||||||
alignment: Alignment.center,
|
|
||||||
child: Container(
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: w.active ? UoscStyle.text : Colors.transparent,
|
|
||||||
border: Border.all(color: w.active ? UoscStyle.text : UoscStyle.dim, width: 1.4),
|
|
||||||
borderRadius: BorderRadius.circular(3),
|
|
||||||
),
|
|
||||||
child: Text(w.text,
|
|
||||||
style: TextStyle(
|
|
||||||
color: w.active ? Colors.black : UoscStyle.dim,
|
|
||||||
fontSize: 11,
|
|
||||||
fontWeight: FontWeight.w800,
|
|
||||||
letterSpacing: 0.3)),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Volume: click mutes / unmutes, hovering shows a [VolumeBar] up to
|
|
||||||
/// [maxVolume], the wheel steps 5 %.
|
|
||||||
class UoscVolumeButton extends StatefulWidget {
|
|
||||||
/// 0..[maxVolume].
|
|
||||||
final double volume;
|
|
||||||
final ValueChanged<double> onChanged;
|
|
||||||
const UoscVolumeButton({super.key, required this.volume, required this.onChanged});
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<UoscVolumeButton> createState() => _UoscVolumeButtonState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _UoscVolumeButtonState extends State<UoscVolumeButton> {
|
|
||||||
double _beforeMute = 100;
|
|
||||||
bool _hover = false;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final v = widget.volume;
|
|
||||||
final icon = v <= 0 ? Icons.volume_off_rounded : (v < 50 ? Icons.volume_down_rounded : Icons.volume_up_rounded);
|
|
||||||
return MouseRegion(
|
|
||||||
onEnter: (_) => setState(() => _hover = true),
|
|
||||||
onExit: (_) => setState(() => _hover = false),
|
|
||||||
child: Listener(
|
|
||||||
onPointerSignal: (e) {
|
|
||||||
if (e is PointerScrollEvent && e.scrollDelta.dy != 0) {
|
|
||||||
widget.onChanged(stepVolume(v, e.scrollDelta.dy < 0 ? 5 : -5));
|
|
||||||
}
|
|
||||||
},
|
|
||||||
child: Row(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
AnimatedSize(
|
|
||||||
duration: const Duration(milliseconds: 150),
|
|
||||||
child: _hover
|
|
||||||
? Padding(
|
|
||||||
padding: const EdgeInsets.only(left: 6, right: 2),
|
|
||||||
child: VolumeBar(
|
|
||||||
key: const ValueKey('uosc-volume-bar'),
|
|
||||||
volume: v,
|
|
||||||
onChanged: widget.onChanged,
|
|
||||||
color: UoscStyle.text,
|
|
||||||
trackColor: UoscStyle.dim.withValues(alpha: 0.5),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
: const SizedBox.shrink(),
|
|
||||||
),
|
|
||||||
UoscButton(
|
|
||||||
key: const ValueKey('uosc-volume'),
|
|
||||||
icon: icon,
|
|
||||||
color: v > 100 ? boostColor : null,
|
|
||||||
tooltip: 'Volume ${v.round()} % (scroll to change)',
|
|
||||||
onPressed: () {
|
|
||||||
if (v > 0) {
|
|
||||||
_beforeMute = v;
|
|
||||||
widget.onChanged(0);
|
|
||||||
} else {
|
|
||||||
widget.onChanged(_beforeMute <= 0 ? 100 : _beforeMute);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Subtitles or audio: the icon with the track count; the menu lists the
|
|
||||||
/// tracks (mpv's selection active).
|
|
||||||
class UoscTracksButton extends StatelessWidget {
|
|
||||||
final JellyfinStreamType type;
|
|
||||||
final List<MpvTrack> tracks;
|
|
||||||
final void Function(TrackPick pick) onPick;
|
|
||||||
final ValueChanged<bool>? onMenuOpen;
|
|
||||||
const UoscTracksButton({super.key, required this.type, required this.tracks, required this.onPick, this.onMenuOpen});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final audio = type == JellyfinStreamType.audio;
|
|
||||||
final count = tracks.where((t) => t.type == type).length;
|
|
||||||
return UoscButton(
|
|
||||||
key: ValueKey(audio ? 'uosc-audio' : 'uosc-subtitles'),
|
|
||||||
icon: audio ? Icons.graphic_eq_rounded : Icons.subtitles_outlined,
|
|
||||||
tooltip: audio ? 'Audio' : 'Subtitles',
|
|
||||||
badge: count,
|
|
||||||
onPressed: () async {
|
|
||||||
onMenuOpen?.call(true);
|
|
||||||
final pick = await showUoscMenu<TrackPick>(context,
|
|
||||||
title: audio ? 'Audio' : 'Subtitles', items: trackMenuItems(type, tracks));
|
|
||||||
onMenuOpen?.call(false);
|
|
||||||
if (pick != null) onPick(pick);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Chapters: the list with start times, the playing one active; a pick
|
|
||||||
/// jumps there. Nothing without chapters.
|
|
||||||
class UoscChaptersButton extends StatelessWidget {
|
|
||||||
final List<MediaChapter> chapters;
|
|
||||||
final int? current;
|
|
||||||
final Duration duration;
|
|
||||||
final ValueChanged<MediaChapter> onPick;
|
|
||||||
final ValueChanged<bool>? onMenuOpen;
|
|
||||||
const UoscChaptersButton({
|
|
||||||
super.key,
|
|
||||||
required this.chapters,
|
|
||||||
required this.current,
|
|
||||||
required this.duration,
|
|
||||||
required this.onPick,
|
|
||||||
this.onMenuOpen,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
if (chapters.isEmpty) return const SizedBox.shrink();
|
|
||||||
return UoscButton(
|
|
||||||
key: const ValueKey('uosc-chapters'),
|
|
||||||
icon: Icons.bookmarks_outlined,
|
|
||||||
tooltip: 'Chapters (PgUp / PgDn)',
|
|
||||||
onPressed: () async {
|
|
||||||
onMenuOpen?.call(true);
|
|
||||||
final pick = await showUoscMenu<MediaChapter>(context,
|
|
||||||
title: 'Chapters', items: chapterMenuItems(chapters, current, duration));
|
|
||||||
onMenuOpen?.call(false);
|
|
||||||
if (pick != null) onPick(pick);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Shaders as uosc's quality badge: the active Anime4K preset ("A HQ"),
|
|
||||||
/// "4K" dimmed when off. Opens the shader menu.
|
|
||||||
class UoscShaderButton extends StatelessWidget {
|
|
||||||
final ReadonlySignal<RenderMode> renderMode;
|
|
||||||
final void Function(ShaderPreset preset, ShaderQuality? quality) onPick;
|
|
||||||
final ValueChanged<bool>? onMenuOpen;
|
|
||||||
const UoscShaderButton({super.key, required this.renderMode, required this.onPick, this.onMenuOpen});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final s = AppSettings.instance;
|
|
||||||
return SignalBuilder(builder: (context) {
|
|
||||||
final preset = s.shaderPreset.value;
|
|
||||||
final quality = s.shaderQuality.value;
|
|
||||||
final short = shaderShortLabel(preset, quality);
|
|
||||||
return Builder(
|
|
||||||
builder: (context) => UoscBadgeButton(
|
|
||||||
key: const ValueKey('uosc-shaders'),
|
|
||||||
text: short ?? '4K',
|
|
||||||
active: short != null,
|
|
||||||
tooltip: short == null
|
|
||||||
? 'Shaders: off (Ctrl+1..6)'
|
|
||||||
: 'Shaders: ${shaderLabel(preset, quality)} (Ctrl+0 off)',
|
|
||||||
onPressed: () {
|
|
||||||
final controls = UoscControls.maybeOf(context);
|
|
||||||
Future<void> open() =>
|
|
||||||
showShaderMenu(context, renderMode: renderMode, onPick: onPick, onMenuOpen: onMenuOpen);
|
|
||||||
controls == null ? open() : controls.holdDuring(open);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One entry of the ≡ menu.
|
|
||||||
typedef UoscAction = ({String title, String? hint, VoidCallback run});
|
|
||||||
|
|
||||||
/// ≡: the session's actions as a menu.
|
|
||||||
class UoscMainMenuButton extends StatelessWidget {
|
|
||||||
final List<UoscAction> actions;
|
|
||||||
final ValueChanged<bool>? onMenuOpen;
|
|
||||||
const UoscMainMenuButton({super.key, required this.actions, this.onMenuOpen});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return UoscButton(
|
|
||||||
key: const ValueKey('uosc-menu-button'),
|
|
||||||
icon: Icons.menu_rounded,
|
|
||||||
tooltip: 'Menu',
|
|
||||||
onPressed: () async {
|
|
||||||
onMenuOpen?.call(true);
|
|
||||||
final pick = await showUoscMenu<UoscAction>(context, items: [
|
|
||||||
for (final a in actions) UoscMenuItem(value: a, title: a.title, hint: a.hint),
|
|
||||||
]);
|
|
||||||
onMenuOpen?.call(false);
|
|
||||||
pick?.run();
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,265 +0,0 @@
|
|||||||
import 'dart:async';
|
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:signals/signals_flutter.dart';
|
|
||||||
|
|
||||||
import '../../state/settings.dart';
|
|
||||||
|
|
||||||
// The mpv-style (uosc) controls frame: a full-width timeline at the
|
|
||||||
// bottom with a row of flat buttons above it, the title top left and a
|
|
||||||
// corner widget top right.
|
|
||||||
// Mouse movement shows them; after [UoscControls.hideAfter] without any
|
|
||||||
// they fade out, the timeline shrinks to a 2 px line (gone when "Progress
|
|
||||||
// line when hidden" is off) and the cursor hides. Our own frame: no
|
|
||||||
// media_kit controls state to reach into.
|
|
||||||
|
|
||||||
class UoscControls extends StatefulWidget {
|
|
||||||
/// The timeline; [expanded] is false while the controls are hidden.
|
|
||||||
final Widget Function(BuildContext context, bool expanded) timeline;
|
|
||||||
/// Buttons left and right of the row above the timeline.
|
|
||||||
final List<Widget> left;
|
|
||||||
final List<Widget> right;
|
|
||||||
/// Top-right corner (chat, back to the library), shown with the controls.
|
|
||||||
final Widget? top;
|
|
||||||
/// Top left (what is playing), shown with the controls; gets the width
|
|
||||||
/// [top] leaves.
|
|
||||||
final Widget? topLeft;
|
|
||||||
final VoidCallback? onDoubleTap;
|
|
||||||
final Duration hideAfter;
|
|
||||||
/// Follows whether the controls are up (for overlays outside them).
|
|
||||||
final ValueNotifier<bool>? shown;
|
|
||||||
const UoscControls({
|
|
||||||
super.key,
|
|
||||||
required this.timeline,
|
|
||||||
this.left = const [],
|
|
||||||
this.right = const [],
|
|
||||||
this.top,
|
|
||||||
this.topLeft,
|
|
||||||
this.onDoubleTap,
|
|
||||||
this.hideAfter = const Duration(seconds: 3),
|
|
||||||
this.shown,
|
|
||||||
});
|
|
||||||
|
|
||||||
static const buttonRowHeight = 40.0;
|
|
||||||
|
|
||||||
/// The controls around [context], for widgets that need them kept up
|
|
||||||
/// (a timeline drag, an open menu).
|
|
||||||
static UoscControlsState? maybeOf(BuildContext context) =>
|
|
||||||
context.findAncestorStateOfType<UoscControlsState>();
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<UoscControls> createState() => UoscControlsState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class UoscControlsState extends State<UoscControls> {
|
|
||||||
bool _visible = true;
|
|
||||||
int _holds = 0;
|
|
||||||
Timer? _timer;
|
|
||||||
|
|
||||||
bool get visible => _visible;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
// Not during this build: an overlay listening to [shown] may be built.
|
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
||||||
if (mounted) widget.shown?.value = true;
|
|
||||||
});
|
|
||||||
_hideLater();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() {
|
|
||||||
_timer?.cancel();
|
|
||||||
super.dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Show the controls and restart the hide countdown.
|
|
||||||
void wake() {
|
|
||||||
if (!_visible && mounted) {
|
|
||||||
setState(() => _visible = true);
|
|
||||||
widget.shown?.value = true;
|
|
||||||
}
|
|
||||||
_hideLater();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Keep the controls up while [on] (paired calls): a drag sends no
|
|
||||||
/// hover events and a menu route takes the mouse.
|
|
||||||
void hold(bool on) {
|
|
||||||
_holds = on ? _holds + 1 : (_holds - 1).clamp(0, 1 << 20);
|
|
||||||
wake();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Runs [open] (a menu) with the controls held up.
|
|
||||||
Future<T> holdDuring<T>(Future<T> Function() open) async {
|
|
||||||
hold(true);
|
|
||||||
try {
|
|
||||||
return await open();
|
|
||||||
} finally {
|
|
||||||
if (mounted) hold(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _hideLater() {
|
|
||||||
_timer?.cancel();
|
|
||||||
_timer = Timer(widget.hideAfter, _hide);
|
|
||||||
}
|
|
||||||
|
|
||||||
void _hide() {
|
|
||||||
if (!mounted || _holds > 0 || !_visible) return;
|
|
||||||
setState(() => _visible = false);
|
|
||||||
widget.shown?.value = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final visible = _visible;
|
|
||||||
const fade = Duration(milliseconds: 150);
|
|
||||||
return MouseRegion(
|
|
||||||
cursor: visible ? SystemMouseCursors.basic : SystemMouseCursors.none,
|
|
||||||
onEnter: (_) => wake(),
|
|
||||||
onHover: (_) => wake(),
|
|
||||||
onExit: (_) {
|
|
||||||
_timer?.cancel();
|
|
||||||
_hide();
|
|
||||||
},
|
|
||||||
child: Stack(
|
|
||||||
children: [
|
|
||||||
Positioned.fill(
|
|
||||||
child: GestureDetector(
|
|
||||||
behavior: HitTestBehavior.opaque,
|
|
||||||
onDoubleTap: widget.onDoubleTap,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Positioned(
|
|
||||||
left: 0,
|
|
||||||
right: 0,
|
|
||||||
bottom: 0,
|
|
||||||
height: 160,
|
|
||||||
child: IgnorePointer(
|
|
||||||
child: AnimatedOpacity(
|
|
||||||
duration: fade,
|
|
||||||
opacity: visible ? 1 : 0,
|
|
||||||
child: const DecoratedBox(
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
gradient: LinearGradient(
|
|
||||||
begin: Alignment.topCenter,
|
|
||||||
end: Alignment.bottomCenter,
|
|
||||||
colors: [Color(0x00000000), Color(0x8C000000)],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (widget.topLeft != null)
|
|
||||||
Positioned(
|
|
||||||
left: 0,
|
|
||||||
right: 0,
|
|
||||||
top: 0,
|
|
||||||
height: 120,
|
|
||||||
child: IgnorePointer(
|
|
||||||
child: AnimatedOpacity(
|
|
||||||
duration: fade,
|
|
||||||
opacity: visible ? 1 : 0,
|
|
||||||
child: const DecoratedBox(
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
gradient: LinearGradient(
|
|
||||||
begin: Alignment.topCenter,
|
|
||||||
end: Alignment.bottomCenter,
|
|
||||||
colors: [Color(0x8C000000), Color(0x00000000)],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (widget.top != null || widget.topLeft != null)
|
|
||||||
Positioned(
|
|
||||||
top: 0,
|
|
||||||
left: 0,
|
|
||||||
right: 0,
|
|
||||||
child: IgnorePointer(
|
|
||||||
key: const ValueKey('uosc-top'),
|
|
||||||
ignoring: !visible,
|
|
||||||
child: AnimatedOpacity(
|
|
||||||
duration: fade,
|
|
||||||
opacity: visible ? 1 : 0,
|
|
||||||
child: Row(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
|
|
||||||
child: widget.topLeft == null
|
|
||||||
? const SizedBox.shrink()
|
|
||||||
: Align(alignment: AlignmentDirectional.centerStart, child: widget.topLeft),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
?widget.top,
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Positioned(
|
|
||||||
left: 0,
|
|
||||||
right: 0,
|
|
||||||
bottom: 0,
|
|
||||||
child: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
IgnorePointer(
|
|
||||||
key: const ValueKey('uosc-buttons'),
|
|
||||||
ignoring: !visible,
|
|
||||||
child: AnimatedOpacity(
|
|
||||||
duration: fade,
|
|
||||||
opacity: visible ? 1 : 0,
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.fromLTRB(6, 0, 6, 4),
|
|
||||||
child: SizedBox(
|
|
||||||
height: UoscControls.buttonRowHeight,
|
|
||||||
child: Row(children: [...widget.left, const Spacer(), ...widget.right]),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
// Hidden: the collapsed timeline is the progress line,
|
|
||||||
// unless the player settings turn it off.
|
|
||||||
SignalBuilder(
|
|
||||||
builder: (context) {
|
|
||||||
final line = AppSettings.instance.progressLine.value;
|
|
||||||
return AnimatedOpacity(
|
|
||||||
key: const ValueKey('uosc-timeline-wrap'),
|
|
||||||
duration: fade,
|
|
||||||
opacity: visible || line ? 1 : 0,
|
|
||||||
child: widget.timeline(context, visible),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The session's controls: the standard ones ([material]) or, with the
|
|
||||||
/// "Player design" setting on uosc, the uosc ones ([mpv]). Switches live
|
|
||||||
/// when the setting changes.
|
|
||||||
class SessionControlsSwitch extends StatelessWidget {
|
|
||||||
final WidgetBuilder material;
|
|
||||||
final WidgetBuilder mpv;
|
|
||||||
const SessionControlsSwitch({super.key, required this.material, required this.mpv});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return SignalBuilder(
|
|
||||||
builder: (context) =>
|
|
||||||
AppSettings.instance.mpvControls.value ? mpv(context) : material(context),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,249 +0,0 @@
|
|||||||
import 'dart:math' as math;
|
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:sync_relay_core/core.dart' show JellyfinStreamType;
|
|
||||||
|
|
||||||
import '../../jellyfin/track_prefs.dart' show MpvTrack;
|
|
||||||
import '../../playback/media_marks.dart';
|
|
||||||
import '../../screens/session/player_controls.dart' show TrackPick;
|
|
||||||
import 'controls.dart';
|
|
||||||
import 'style.dart';
|
|
||||||
|
|
||||||
/// One row of a uosc menu: [title], a dim [hint] on the right (a time, a
|
|
||||||
/// key), [active] = the current one (highlighted).
|
|
||||||
class UoscMenuItem<T> {
|
|
||||||
final T value;
|
|
||||||
final String title;
|
|
||||||
final String? hint;
|
|
||||||
final bool active;
|
|
||||||
final bool enabled;
|
|
||||||
const UoscMenuItem({
|
|
||||||
required this.value,
|
|
||||||
required this.title,
|
|
||||||
this.hint,
|
|
||||||
this.active = false,
|
|
||||||
this.enabled = true,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A flat dark menu over the controls, above the widget of [context] (the
|
|
||||||
/// button that opens it), with an optional [title] row. Resolves to the
|
|
||||||
/// picked value, or null when dismissed (click outside, Esc). Keeps the
|
|
||||||
/// controls up while open.
|
|
||||||
Future<T?> showUoscMenu<T>(
|
|
||||||
BuildContext context, {
|
|
||||||
String? title,
|
|
||||||
required List<UoscMenuItem<T>> items,
|
|
||||||
}) {
|
|
||||||
final navigator = Navigator.of(context);
|
|
||||||
final overlay = navigator.overlay!.context.findRenderObject() as RenderBox;
|
|
||||||
final box = context.findRenderObject() as RenderBox;
|
|
||||||
final anchor = Rect.fromPoints(
|
|
||||||
box.localToGlobal(Offset.zero, ancestor: overlay),
|
|
||||||
box.localToGlobal(box.size.bottomRight(Offset.zero), ancestor: overlay),
|
|
||||||
);
|
|
||||||
Future<T?> open() => navigator.push<T>(_UoscMenuRoute<T>(anchor: anchor, title: title, items: items));
|
|
||||||
final controls = UoscControls.maybeOf(context);
|
|
||||||
return controls == null ? open() : controls.holdDuring(open);
|
|
||||||
}
|
|
||||||
|
|
||||||
class _UoscMenuRoute<T> extends PopupRoute<T> {
|
|
||||||
final Rect anchor;
|
|
||||||
final String? title;
|
|
||||||
final List<UoscMenuItem<T>> items;
|
|
||||||
_UoscMenuRoute({required this.anchor, required this.title, required this.items});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Color? get barrierColor => null;
|
|
||||||
|
|
||||||
@override
|
|
||||||
bool get barrierDismissible => true;
|
|
||||||
|
|
||||||
@override
|
|
||||||
String? get barrierLabel => 'Close menu';
|
|
||||||
|
|
||||||
@override
|
|
||||||
Duration get transitionDuration => Duration.zero;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
|
|
||||||
return LayoutBuilder(builder: (context, constraints) {
|
|
||||||
const width = 360.0;
|
|
||||||
final screen = constraints.biggest;
|
|
||||||
final left = anchor.left.clamp(8.0, math.max(8.0, screen.width - width - 8));
|
|
||||||
final maxHeight = math.max(120.0, anchor.top - 16);
|
|
||||||
return Stack(
|
|
||||||
children: [
|
|
||||||
Positioned(
|
|
||||||
left: left.toDouble(),
|
|
||||||
bottom: screen.height - anchor.top + 6,
|
|
||||||
width: math.min(width, screen.width - 16),
|
|
||||||
child: ConstrainedBox(
|
|
||||||
constraints: BoxConstraints(maxHeight: maxHeight),
|
|
||||||
child: UoscMenuPanel<T>(
|
|
||||||
title: title,
|
|
||||||
items: items,
|
|
||||||
onPick: (v) => Navigator.of(context).pop(v),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The menu's panel alone (tests pump it without a route).
|
|
||||||
class UoscMenuPanel<T> extends StatefulWidget {
|
|
||||||
final String? title;
|
|
||||||
final List<UoscMenuItem<T>> items;
|
|
||||||
final ValueChanged<T> onPick;
|
|
||||||
const UoscMenuPanel({super.key, this.title, required this.items, required this.onPick});
|
|
||||||
|
|
||||||
static const rowHeight = 36.0;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<UoscMenuPanel<T>> createState() => _UoscMenuPanelState<T>();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _UoscMenuPanelState<T> extends State<UoscMenuPanel<T>> {
|
|
||||||
// Long lists open on the current row.
|
|
||||||
late final _scroll = ScrollController(
|
|
||||||
initialScrollOffset: math.max(0, widget.items.indexWhere((i) => i.active) - 3) * UoscMenuPanel.rowHeight);
|
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() {
|
|
||||||
_scroll.dispose();
|
|
||||||
super.dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final title = widget.title;
|
|
||||||
return Material(
|
|
||||||
key: const ValueKey('uosc-menu'),
|
|
||||||
color: UoscStyle.panel,
|
|
||||||
borderRadius: BorderRadius.circular(UoscStyle.radius * 2),
|
|
||||||
clipBehavior: Clip.antiAlias,
|
|
||||||
child: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
||||||
children: [
|
|
||||||
if (title != null)
|
|
||||||
Container(
|
|
||||||
height: 34,
|
|
||||||
alignment: Alignment.center,
|
|
||||||
decoration: const BoxDecoration(border: Border(bottom: BorderSide(color: Color(0x22FFFFFF)))),
|
|
||||||
child: Text(title,
|
|
||||||
style: const TextStyle(color: UoscStyle.dim, fontSize: UoscStyle.fontSize, fontWeight: FontWeight.w600)),
|
|
||||||
),
|
|
||||||
Flexible(
|
|
||||||
child: ListView.builder(
|
|
||||||
shrinkWrap: true,
|
|
||||||
padding: const EdgeInsets.all(4),
|
|
||||||
controller: _scroll,
|
|
||||||
itemCount: widget.items.length,
|
|
||||||
itemExtent: UoscMenuPanel.rowHeight,
|
|
||||||
itemBuilder: (context, i) => _Row<T>(item: widget.items[i], onPick: widget.onPick),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class _Row<T> extends StatefulWidget {
|
|
||||||
final UoscMenuItem<T> item;
|
|
||||||
final ValueChanged<T> onPick;
|
|
||||||
const _Row({super.key, required this.item, required this.onPick});
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<_Row<T>> createState() => _RowState<T>();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _RowState<T> extends State<_Row<T>> {
|
|
||||||
bool _hover = false;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final item = widget.item;
|
|
||||||
final color = item.active
|
|
||||||
? UoscStyle.fill
|
|
||||||
: _hover && item.enabled
|
|
||||||
? UoscStyle.hover
|
|
||||||
: Colors.transparent;
|
|
||||||
final textColor = item.enabled ? UoscStyle.text : UoscStyle.dim.withValues(alpha: 0.4);
|
|
||||||
return MouseRegion(
|
|
||||||
cursor: item.enabled ? SystemMouseCursors.click : SystemMouseCursors.basic,
|
|
||||||
onEnter: (_) => setState(() => _hover = true),
|
|
||||||
onExit: (_) => setState(() => _hover = false),
|
|
||||||
child: GestureDetector(
|
|
||||||
key: ValueKey('uosc-menu-item-${item.title}'),
|
|
||||||
behavior: HitTestBehavior.opaque,
|
|
||||||
onTap: item.enabled ? () => widget.onPick(item.value) : null,
|
|
||||||
child: Container(
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 10),
|
|
||||||
decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(UoscStyle.radius)),
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: Text(item.title,
|
|
||||||
maxLines: 1,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
style: TextStyle(
|
|
||||||
color: textColor,
|
|
||||||
fontSize: UoscStyle.fontSize,
|
|
||||||
fontWeight: item.active ? FontWeight.w600 : FontWeight.normal)),
|
|
||||||
),
|
|
||||||
if (item.hint != null) ...[
|
|
||||||
const SizedBox(width: 12),
|
|
||||||
Text(item.hint!,
|
|
||||||
style: TextStyle(
|
|
||||||
color: item.active ? UoscStyle.text : UoscStyle.dim,
|
|
||||||
fontSize: 12,
|
|
||||||
fontFeatures: const [FontFeature.tabularFigures()])),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Chapters with their start times, the playing one active.
|
|
||||||
List<UoscMenuItem<MediaChapter>> chapterMenuItems(List<MediaChapter> chapters, int? current, Duration duration) {
|
|
||||||
final withHours = duration >= const Duration(hours: 1);
|
|
||||||
return [
|
|
||||||
for (final c in chapters)
|
|
||||||
UoscMenuItem(
|
|
||||||
value: c,
|
|
||||||
title: c.title.isEmpty ? 'Chapter ${c.index + 1}' : c.title,
|
|
||||||
hint: formatUoscTime(c.start, withHours: withHours),
|
|
||||||
active: c.index == current,
|
|
||||||
),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The audio or subtitle tracks ("Japanese · E-AC3 2.0 · title"), mpv's
|
|
||||||
/// selection active; subtitles start with Off.
|
|
||||||
List<UoscMenuItem<TrackPick>> trackMenuItems(JellyfinStreamType type, List<MpvTrack> tracks) {
|
|
||||||
final audio = type == JellyfinStreamType.audio;
|
|
||||||
final list = tracks.where((t) => t.type == type).toList();
|
|
||||||
return [
|
|
||||||
if (!audio)
|
|
||||||
UoscMenuItem(
|
|
||||||
value: (aid: null, sid: null, subtitlesOff: true),
|
|
||||||
title: 'Off',
|
|
||||||
active: !list.any((t) => t.selected),
|
|
||||||
),
|
|
||||||
for (final t in list)
|
|
||||||
UoscMenuItem(
|
|
||||||
value: audio ? (aid: t.id, sid: null, subtitlesOff: false) : (aid: null, sid: t.id, subtitlesOff: false),
|
|
||||||
title: t.label,
|
|
||||||
hint: '#${t.id}',
|
|
||||||
active: t.selected,
|
|
||||||
),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
import 'package:flutter/material.dart';
|
|
||||||
|
|
||||||
// Look of the experimental mpv-style controls, after the uosc theme as the
|
|
||||||
// owner runs it: flat black panels, white icons, a muted blue fill.
|
|
||||||
|
|
||||||
abstract final class UoscStyle {
|
|
||||||
/// Timeline background and the boxes on it.
|
|
||||||
static const bar = Color(0xCC000000);
|
|
||||||
/// Played part of the timeline; also the active menu row.
|
|
||||||
static const fill = Color(0xFF4C6A8E);
|
|
||||||
/// Menus and tooltips.
|
|
||||||
static const panel = Color(0xF0101010);
|
|
||||||
static const hover = Color(0x24FFFFFF);
|
|
||||||
static const text = Colors.white;
|
|
||||||
static const dim = Color(0xA6FFFFFF);
|
|
||||||
static const radius = 4.0;
|
|
||||||
static const fontSize = 13.0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// uosc's clock: "01:51", "1:02:03" style but zero-padded ("01:02:03")
|
|
||||||
/// once [withHours] (the media is an hour or longer).
|
|
||||||
String formatUoscTime(Duration d, {bool withHours = false}) {
|
|
||||||
final t = d.isNegative ? Duration.zero : d;
|
|
||||||
String two(int n) => n.toString().padLeft(2, '0');
|
|
||||||
final h = t.inHours, m = t.inMinutes % 60, s = t.inSeconds % 60;
|
|
||||||
return withHours || h > 0 ? '${two(h)}:${two(m)}:${two(s)}' : '${two(m)}:${two(s)}';
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Dark rounded hover tip ("Subtitles"), shown above its child.
|
|
||||||
class UoscTooltip extends StatelessWidget {
|
|
||||||
final String message;
|
|
||||||
final Widget child;
|
|
||||||
const UoscTooltip({super.key, required this.message, required this.child});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
if (message.isEmpty) return child;
|
|
||||||
return Tooltip(
|
|
||||||
message: message,
|
|
||||||
preferBelow: false,
|
|
||||||
verticalOffset: 26,
|
|
||||||
waitDuration: const Duration(milliseconds: 250),
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: UoscStyle.panel,
|
|
||||||
borderRadius: BorderRadius.circular(UoscStyle.radius),
|
|
||||||
),
|
|
||||||
textStyle: const TextStyle(color: UoscStyle.text, fontSize: 12),
|
|
||||||
child: child,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A small dark box with one line of text (the timeline's times, the
|
|
||||||
/// hover chapter title).
|
|
||||||
class UoscBox extends StatelessWidget {
|
|
||||||
final String text;
|
|
||||||
final Color color;
|
|
||||||
final TextStyle style;
|
|
||||||
const UoscBox(
|
|
||||||
this.text, {
|
|
||||||
super.key,
|
|
||||||
this.color = UoscStyle.panel,
|
|
||||||
this.style = const TextStyle(color: UoscStyle.text, fontSize: UoscStyle.fontSize),
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return Container(
|
|
||||||
constraints: const BoxConstraints(maxWidth: 360),
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 3),
|
|
||||||
decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(UoscStyle.radius)),
|
|
||||||
child: Text(text,
|
|
||||||
maxLines: 1,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
style: style.copyWith(fontFeatures: const [FontFeature.tabularFigures()])),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,287 +0,0 @@
|
|||||||
import 'dart:math' as math;
|
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
|
|
||||||
import '../../playback/media_marks.dart';
|
|
||||||
import 'controls.dart';
|
|
||||||
import 'style.dart';
|
|
||||||
|
|
||||||
/// Fraction of [total] at [d], 0..1 (0 without a duration).
|
|
||||||
double timelineFraction(Duration d, Duration total) {
|
|
||||||
final t = total.inMicroseconds;
|
|
||||||
if (t <= 0) return 0;
|
|
||||||
return (d.inMicroseconds / t).clamp(0.0, 1.0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The cached-ahead part of a timeline of [size]: from the playing
|
|
||||||
/// position to the end of mpv's cache. Null when nothing is cached ahead.
|
|
||||||
Rect? cacheRect(Size size, {required Duration position, required Duration buffered, required Duration duration}) {
|
|
||||||
final from = timelineFraction(position, duration) * size.width;
|
|
||||||
final to = timelineFraction(buffered, duration) * size.width;
|
|
||||||
if (to - from < 0.5) return null;
|
|
||||||
return Rect.fromLTRB(from, 0, to, size.height);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The hatching of [r]: 45° strokes from bottom-left to top-right,
|
|
||||||
/// [spacing] apart along x, across all of [r] (the painter clips them).
|
|
||||||
/// The first starts half a step in, so none just grazes the corner.
|
|
||||||
List<(Offset, Offset)> hatchLines(Rect r, {double spacing = 6}) {
|
|
||||||
if (r.isEmpty || spacing <= 0) return const [];
|
|
||||||
final h = r.height;
|
|
||||||
return [
|
|
||||||
for (var x = r.left - h + spacing / 2; x < r.right; x += spacing) (Offset(x, r.bottom), Offset(x + h, r.top)),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The uosc timeline: full width, elapsed part filled, the cached range
|
|
||||||
/// ahead hatched, chapter starts as white diamonds on the top edge, the
|
|
||||||
/// current time in a box at the left and the duration at the right.
|
|
||||||
/// Hover shows the chapter title over the hover time. When the controls
|
|
||||||
/// hide ([expanded] false) it shrinks to a thin line with chapter ticks.
|
|
||||||
/// Like the media_kit bar it reports a seek on every drag move and on
|
|
||||||
/// release ([onSeek]); the session sends those through the user-seek path.
|
|
||||||
class UoscTimeline extends StatefulWidget {
|
|
||||||
final Duration position;
|
|
||||||
final Duration duration;
|
|
||||||
/// End of the cached range ([PlaybackController.buffered]).
|
|
||||||
final Duration buffered;
|
|
||||||
final List<MediaChapter> chapters;
|
|
||||||
final bool expanded;
|
|
||||||
final ValueChanged<Duration> onSeek;
|
|
||||||
const UoscTimeline({
|
|
||||||
super.key,
|
|
||||||
required this.position,
|
|
||||||
required this.duration,
|
|
||||||
this.buffered = Duration.zero,
|
|
||||||
this.chapters = const [],
|
|
||||||
this.expanded = true,
|
|
||||||
required this.onSeek,
|
|
||||||
});
|
|
||||||
|
|
||||||
static const height = 30.0;
|
|
||||||
static const collapsedHeight = 2.0;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<UoscTimeline> createState() => _UoscTimelineState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _UoscTimelineState extends State<UoscTimeline> {
|
|
||||||
double? _hoverX;
|
|
||||||
bool _dragging = false;
|
|
||||||
double _dragFraction = 0;
|
|
||||||
|
|
||||||
Duration _at(double fraction) => widget.duration * fraction.clamp(0.0, 1.0);
|
|
||||||
|
|
||||||
void _seekTo(double x, double width) {
|
|
||||||
if (widget.duration <= Duration.zero || width <= 0) return;
|
|
||||||
_dragFraction = (x / width).clamp(0.0, 1.0);
|
|
||||||
widget.onSeek(_at(_dragFraction));
|
|
||||||
}
|
|
||||||
|
|
||||||
void _drag(bool on) {
|
|
||||||
if (_dragging == on) return;
|
|
||||||
setState(() => _dragging = on);
|
|
||||||
UoscControls.maybeOf(context)?.hold(on);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void didUpdateWidget(UoscTimeline old) {
|
|
||||||
super.didUpdateWidget(old);
|
|
||||||
if (!widget.expanded && old.expanded) _hoverX = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() {
|
|
||||||
// A drag cut short by a rebuild must not keep the controls up.
|
|
||||||
if (_dragging) UoscControls.maybeOf(context)?.hold(false);
|
|
||||||
super.dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return LayoutBuilder(builder: (context, constraints) {
|
|
||||||
final width = constraints.maxWidth;
|
|
||||||
final expanded = widget.expanded;
|
|
||||||
final h = expanded ? UoscTimeline.height : UoscTimeline.collapsedHeight;
|
|
||||||
final played = _dragging ? _dragFraction : timelineFraction(widget.position, widget.duration);
|
|
||||||
final hoverX = expanded ? _hoverX : null;
|
|
||||||
final hoverAt = hoverX == null || width <= 0 ? null : _at(hoverX / width);
|
|
||||||
final hoverChapter = hoverAt == null ? null : chapterIndexAt(widget.chapters, hoverAt);
|
|
||||||
final hoverTitle = hoverChapter == null ? '' : widget.chapters[hoverChapter].title;
|
|
||||||
final withHours = widget.duration >= const Duration(hours: 1);
|
|
||||||
final marks = [
|
|
||||||
for (final c in widget.chapters)
|
|
||||||
if (c.start > Duration.zero && widget.duration > Duration.zero) c,
|
|
||||||
];
|
|
||||||
final bar = SizedBox(
|
|
||||||
key: const ValueKey('uosc-timeline'),
|
|
||||||
width: width,
|
|
||||||
height: h,
|
|
||||||
child: Stack(
|
|
||||||
clipBehavior: Clip.none,
|
|
||||||
children: [
|
|
||||||
Positioned.fill(
|
|
||||||
child: CustomPaint(
|
|
||||||
painter: UoscTimelinePainter(
|
|
||||||
played: played,
|
|
||||||
cache: (size) => cacheRect(size,
|
|
||||||
position: widget.position, buffered: widget.buffered, duration: widget.duration),
|
|
||||||
cacheKey: (widget.position, widget.buffered, widget.duration),
|
|
||||||
hoverX: _dragging ? null : hoverX,
|
|
||||||
hatched: expanded,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
for (final c in marks)
|
|
||||||
if (expanded)
|
|
||||||
Positioned(
|
|
||||||
key: ValueKey('uosc-chapter-${c.index}'),
|
|
||||||
left: width * timelineFraction(c.start, widget.duration) - 4,
|
|
||||||
top: -4,
|
|
||||||
width: 8,
|
|
||||||
height: 8,
|
|
||||||
child: IgnorePointer(
|
|
||||||
child: Transform.rotate(
|
|
||||||
angle: math.pi / 4,
|
|
||||||
child: Container(
|
|
||||||
margin: const EdgeInsets.all(1.2),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Colors.white,
|
|
||||||
border: Border.all(color: Colors.black54, width: 0.6),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
else
|
|
||||||
Positioned(
|
|
||||||
key: ValueKey('uosc-chapter-tick-${c.index}'),
|
|
||||||
left: width * timelineFraction(c.start, widget.duration) - 1,
|
|
||||||
top: -2,
|
|
||||||
width: 2,
|
|
||||||
height: h + 2,
|
|
||||||
child: const IgnorePointer(child: ColoredBox(color: Colors.white70)),
|
|
||||||
),
|
|
||||||
if (expanded) ...[
|
|
||||||
Positioned(
|
|
||||||
left: 4,
|
|
||||||
top: 0,
|
|
||||||
bottom: 0,
|
|
||||||
child: IgnorePointer(
|
|
||||||
child: Center(
|
|
||||||
child: UoscBox(formatUoscTime(_at(played), withHours: withHours),
|
|
||||||
key: const ValueKey('uosc-time'), color: UoscStyle.bar),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Positioned(
|
|
||||||
right: 4,
|
|
||||||
top: 0,
|
|
||||||
bottom: 0,
|
|
||||||
child: IgnorePointer(
|
|
||||||
child: Center(
|
|
||||||
child: UoscBox(formatUoscTime(widget.duration, withHours: withHours),
|
|
||||||
key: const ValueKey('uosc-duration'), color: UoscStyle.bar),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
if (hoverAt != null)
|
|
||||||
Positioned(
|
|
||||||
// Kept clear of the window edges (the tip is centred).
|
|
||||||
left: hoverX!.clamp(math.min(60.0, width / 2), math.max(width - 60, width / 2)),
|
|
||||||
bottom: h + 8,
|
|
||||||
child: IgnorePointer(
|
|
||||||
child: FractionalTranslation(
|
|
||||||
translation: const Offset(-0.5, 0),
|
|
||||||
child: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
spacing: 4,
|
|
||||||
children: [
|
|
||||||
if (hoverTitle.isNotEmpty) UoscBox(hoverTitle, key: const ValueKey('uosc-hover-chapter')),
|
|
||||||
UoscBox(formatUoscTime(hoverAt, withHours: withHours),
|
|
||||||
key: const ValueKey('uosc-hover-time')),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
if (!expanded) return IgnorePointer(child: bar);
|
|
||||||
return MouseRegion(
|
|
||||||
cursor: SystemMouseCursors.click,
|
|
||||||
onEnter: (e) => setState(() => _hoverX = e.localPosition.dx.clamp(0, width)),
|
|
||||||
onHover: (e) => setState(() => _hoverX = e.localPosition.dx.clamp(0, width)),
|
|
||||||
onExit: (_) => setState(() => _hoverX = null),
|
|
||||||
child: Listener(
|
|
||||||
behavior: HitTestBehavior.opaque,
|
|
||||||
onPointerDown: (e) {
|
|
||||||
_dragFraction = width <= 0 ? 0 : (e.localPosition.dx / width).clamp(0.0, 1.0);
|
|
||||||
_drag(true);
|
|
||||||
},
|
|
||||||
onPointerMove: (e) {
|
|
||||||
setState(() => _hoverX = e.localPosition.dx.clamp(0, width));
|
|
||||||
_seekTo(e.localPosition.dx, width);
|
|
||||||
},
|
|
||||||
onPointerUp: (e) {
|
|
||||||
_seekTo(e.localPosition.dx, width);
|
|
||||||
_drag(false);
|
|
||||||
},
|
|
||||||
onPointerCancel: (_) => _drag(false),
|
|
||||||
child: bar,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Background, cached range (hatched, or a faint band when collapsed),
|
|
||||||
/// the played part and the hover line.
|
|
||||||
class UoscTimelinePainter extends CustomPainter {
|
|
||||||
final double played;
|
|
||||||
final Rect? Function(Size size) cache;
|
|
||||||
/// What [cache] depends on (repaint when it changes).
|
|
||||||
final Object cacheKey;
|
|
||||||
final double? hoverX;
|
|
||||||
final bool hatched;
|
|
||||||
const UoscTimelinePainter({
|
|
||||||
required this.played,
|
|
||||||
required this.cache,
|
|
||||||
required this.cacheKey,
|
|
||||||
this.hoverX,
|
|
||||||
this.hatched = true,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
void paint(Canvas canvas, Size size) {
|
|
||||||
final all = Offset.zero & size;
|
|
||||||
canvas.drawRect(all, Paint()..color = UoscStyle.bar);
|
|
||||||
final c = cache(size);
|
|
||||||
if (c != null) {
|
|
||||||
if (hatched) {
|
|
||||||
canvas.save();
|
|
||||||
canvas.clipRect(c);
|
|
||||||
final stroke = Paint()
|
|
||||||
..color = const Color(0x40FFFFFF)
|
|
||||||
..strokeWidth = 1.5;
|
|
||||||
for (final (a, b) in hatchLines(c)) {
|
|
||||||
canvas.drawLine(a, b, stroke);
|
|
||||||
}
|
|
||||||
canvas.restore();
|
|
||||||
} else {
|
|
||||||
canvas.drawRect(c, Paint()..color = const Color(0x40FFFFFF));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
canvas.drawRect(Rect.fromLTWH(0, 0, size.width * played, size.height), Paint()..color = UoscStyle.fill);
|
|
||||||
final x = hoverX;
|
|
||||||
if (x != null) {
|
|
||||||
canvas.drawRect(Rect.fromLTWH(x - 0.5, 0, 1, size.height), Paint()..color = Colors.white70);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
bool shouldRepaint(UoscTimelinePainter old) =>
|
|
||||||
old.played != played || old.cacheKey != cacheKey || old.hoverX != hoverX || old.hatched != hatched;
|
|
||||||
}
|
|
||||||
@@ -1,8 +1,11 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart' show ValueListenable;
|
||||||
import 'package:flutter/gestures.dart';
|
import 'package:flutter/gestures.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:media_kit/media_kit.dart';
|
|
||||||
|
|
||||||
import '../playback/playback_controller.dart' show PlaybackController;
|
import '../playback/playback_controller.dart' show PlaybackController;
|
||||||
|
import '../widgets/app_menu.dart' show AppGlass;
|
||||||
|
|
||||||
/// The player's top volume (mpv's `volume-max`): past 100 % mpv amplifies.
|
/// The player's top volume (mpv's `volume-max`): past 100 % mpv amplifies.
|
||||||
const maxVolume = PlaybackController.maxVolume * 1.0;
|
const maxVolume = PlaybackController.maxVolume * 1.0;
|
||||||
@@ -10,9 +13,170 @@ const maxVolume = PlaybackController.maxVolume * 1.0;
|
|||||||
/// The part of the volume bar above 100 %.
|
/// The part of the volume bar above 100 %.
|
||||||
const boostColor = Color(0xFFFFB74D);
|
const boostColor = Color(0xFFFFB74D);
|
||||||
|
|
||||||
|
/// One wheel notch or arrow key.
|
||||||
|
const volumeStep = 5.0;
|
||||||
|
|
||||||
/// [volume] moved by [delta] (wheel, keys), kept within 0..[maxVolume].
|
/// [volume] moved by [delta] (wheel, keys), kept within 0..[maxVolume].
|
||||||
double stepVolume(double volume, double delta) => (volume + delta).clamp(0.0, maxVolume);
|
double stepVolume(double volume, double delta) => (volume + delta).clamp(0.0, maxVolume);
|
||||||
|
|
||||||
|
/// Turns wheel deltas into volume steps: a mouse notch (a big delta) is
|
||||||
|
/// one step, small smooth-scroll deltas add up to one. Mostly horizontal
|
||||||
|
/// scrolls (Shift+wheel, sideways pans) are no steps.
|
||||||
|
class WheelSteps {
|
||||||
|
// Flutter makes a notch 53 px on Linux, 60 on Windows (3 lines).
|
||||||
|
static const _notch = 50.0;
|
||||||
|
double _sum = 0;
|
||||||
|
|
||||||
|
/// Whether [e] is a vertical scroll (the only kind that steps).
|
||||||
|
static bool vertical(PointerSignalEvent e) =>
|
||||||
|
e is PointerScrollEvent && e.scrollDelta.dy != 0 && e.scrollDelta.dy.abs() > e.scrollDelta.dx.abs();
|
||||||
|
|
||||||
|
/// +1 louder (wheel up), -1 quieter, 0 not a step yet.
|
||||||
|
int take(PointerScrollEvent e) {
|
||||||
|
final dy = e.scrollDelta.dy;
|
||||||
|
if (dy.abs() >= _notch) {
|
||||||
|
_sum = 0;
|
||||||
|
return dy < 0 ? 1 : -1;
|
||||||
|
}
|
||||||
|
if (_sum != 0 && _sum.sign != dy.sign) _sum = 0;
|
||||||
|
_sum += dy;
|
||||||
|
if (_sum.abs() < _notch) return 0;
|
||||||
|
final step = _sum < 0 ? 1 : -1;
|
||||||
|
_sum = 0;
|
||||||
|
return step;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Claims [e] if it is a vertical scroll that nothing under the mouse
|
||||||
|
/// claimed first (a list, a menu), then calls [onStep] per step.
|
||||||
|
void handle(PointerSignalEvent e, ValueChanged<int> onStep) {
|
||||||
|
if (!vertical(e)) return;
|
||||||
|
GestureBinding.instance.pointerSignalResolver.register(e, (event) {
|
||||||
|
final step = take(event as PointerScrollEvent);
|
||||||
|
if (step != 0) onStep(step);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The wheel anywhere over [child] steps the volume ([onStep]: +1 / -1),
|
||||||
|
/// unless something under the mouse scrolls (it claims the event first)
|
||||||
|
/// or [enabled] is off.
|
||||||
|
class VolumeWheel extends StatefulWidget {
|
||||||
|
final ValueChanged<int> onStep;
|
||||||
|
final bool enabled;
|
||||||
|
final Widget child;
|
||||||
|
const VolumeWheel({super.key, required this.onStep, this.enabled = true, required this.child});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<VolumeWheel> createState() => _VolumeWheelState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _VolumeWheelState extends State<VolumeWheel> {
|
||||||
|
final _steps = WheelSteps();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) => Listener(
|
||||||
|
onPointerSignal: (e) {
|
||||||
|
if (widget.enabled) _steps.handle(e, widget.onStep);
|
||||||
|
},
|
||||||
|
child: widget.child,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shows [builder] for a second after each [trigger] tick (a wheel or
|
||||||
|
/// key volume step), fading in and out; ignores the mouse.
|
||||||
|
class VolumeFlash extends StatefulWidget {
|
||||||
|
final ValueListenable<int> trigger;
|
||||||
|
final WidgetBuilder builder;
|
||||||
|
const VolumeFlash({super.key, required this.trigger, required this.builder});
|
||||||
|
|
||||||
|
/// How long the readout stays after the last step.
|
||||||
|
static const hold = Duration(seconds: 1);
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<VolumeFlash> createState() => _VolumeFlashState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _VolumeFlashState extends State<VolumeFlash> {
|
||||||
|
bool _on = false;
|
||||||
|
Timer? _timer;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
widget.trigger.addListener(_flash);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didUpdateWidget(VolumeFlash old) {
|
||||||
|
super.didUpdateWidget(old);
|
||||||
|
if (old.trigger != widget.trigger) {
|
||||||
|
old.trigger.removeListener(_flash);
|
||||||
|
widget.trigger.addListener(_flash);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
widget.trigger.removeListener(_flash);
|
||||||
|
_timer?.cancel();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _flash() {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _on = true);
|
||||||
|
_timer?.cancel();
|
||||||
|
_timer = Timer(VolumeFlash.hold, () {
|
||||||
|
if (mounted) setState(() => _on = false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) => IgnorePointer(
|
||||||
|
child: AnimatedOpacity(
|
||||||
|
duration: const Duration(milliseconds: 150),
|
||||||
|
opacity: _on ? 1 : 0,
|
||||||
|
child: _on || _timer != null ? widget.builder(context) : const SizedBox.shrink(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The volume readout for [VolumeFlash] (both skins): a glass pill
|
||||||
|
/// (the player's pill look) with the icon, a [VolumeBar] and the
|
||||||
|
/// percentage.
|
||||||
|
class VolumeReadout extends StatelessWidget {
|
||||||
|
final double volume;
|
||||||
|
const VolumeReadout({super.key, required this.volume});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final v = volume.clamp(0.0, maxVolume);
|
||||||
|
return AppGlass.pill(
|
||||||
|
key: const ValueKey('volume-readout'),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(12, 4, 14, 4),
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(volumeIcon(v), size: 20, color: v > 100 ? boostColor : Colors.white),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
VolumeBar(volume: v, onChanged: (_) {}, width: 96),
|
||||||
|
const SizedBox(width: 10),
|
||||||
|
SizedBox(
|
||||||
|
width: 44,
|
||||||
|
child: Text(
|
||||||
|
'${v.round()} %',
|
||||||
|
textAlign: TextAlign.right,
|
||||||
|
style: const TextStyle(color: Colors.white, fontSize: 13, fontFeatures: [FontFeature.tabularFigures()]),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// A thin volume track over 0..[maxVolume]: filled up to the volume, the
|
/// A thin volume track over 0..[maxVolume]: filled up to the volume, the
|
||||||
/// part above 100 % in [boostColor], a tick at 100 %. Click or drag sets
|
/// part above 100 % in [boostColor], a tick at 100 %. Click or drag sets
|
||||||
/// it.
|
/// it.
|
||||||
@@ -61,78 +225,98 @@ class _VolumePainter extends CustomPainter {
|
|||||||
..strokeCap = StrokeCap.round;
|
..strokeCap = StrokeCap.round;
|
||||||
canvas.drawLine(Offset(0, y), Offset(size.width, y), line..color = trackColor);
|
canvas.drawLine(Offset(0, y), Offset(size.width, y), line..color = trackColor);
|
||||||
final full = x(100);
|
final full = x(100);
|
||||||
canvas.drawLine(Offset(full, y - 5), Offset(full, y + 5), Paint()
|
canvas.drawLine(
|
||||||
|
Offset(full, y - 5),
|
||||||
|
Offset(full, y + 5),
|
||||||
|
Paint()
|
||||||
..color = trackColor
|
..color = trackColor
|
||||||
..strokeWidth = 1.5);
|
..strokeWidth = 1.5,
|
||||||
|
);
|
||||||
if (volume > 0) canvas.drawLine(Offset(0, y), Offset(x(volume.clamp(0, 100)), y), line..color = color);
|
if (volume > 0) canvas.drawLine(Offset(0, y), Offset(x(volume.clamp(0, 100)), y), line..color = color);
|
||||||
if (volume > 100) canvas.drawLine(Offset(full, y), Offset(x(volume), y), line..color = boostColor);
|
if (volume > 100) canvas.drawLine(Offset(full, y), Offset(x(volume), y), line..color = boostColor);
|
||||||
canvas.drawCircle(Offset(x(volume), y), 5, Paint()..color = volume > 100 ? boostColor : color);
|
canvas.drawCircle(Offset(x(volume), y), 5, Paint()..color = volume > 100 ? boostColor : color);
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
bool shouldRepaint(_VolumePainter old) =>
|
bool shouldRepaint(_VolumePainter old) => old.volume != volume || old.color != color || old.trackColor != trackColor;
|
||||||
old.volume != volume || old.color != color || old.trackColor != trackColor;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Volume for the standard bar (instead of media_kit's, which stops at
|
/// The speaker icon for [volume].
|
||||||
/// 100): the icon mutes / unmutes, hovering shows a [VolumeBar], the
|
IconData volumeIcon(double volume) =>
|
||||||
/// wheel steps 5 %.
|
volume <= 0 ? Icons.volume_off_rounded : (volume < 50 ? Icons.volume_down_rounded : Icons.volume_up_rounded);
|
||||||
class VolumeButton extends StatefulWidget {
|
|
||||||
final Player player;
|
/// Builds a skin's button for the [VolumeControl].
|
||||||
final FocusNode? focusNode;
|
typedef VolumeButtonBuilder = Widget Function(
|
||||||
const VolumeButton({super.key, required this.player, this.focusNode});
|
BuildContext context,
|
||||||
|
IconData icon,
|
||||||
|
Color? color,
|
||||||
|
String tooltip,
|
||||||
|
VoidCallback onPressed,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// The bar's volume, in both skins: the skin's speaker button (click
|
||||||
|
/// mutes / unmutes), a [VolumeBar] sliding out on hover, the wheel on it
|
||||||
|
/// stepping [volumeStep] (claimed, so the player's wheel skips it).
|
||||||
|
class VolumeControl extends StatefulWidget {
|
||||||
|
/// 0..[maxVolume].
|
||||||
|
final double volume;
|
||||||
|
final ValueChanged<double> onChanged;
|
||||||
|
final VoidCallback onToggleMute;
|
||||||
|
final VolumeButtonBuilder button;
|
||||||
|
final Color sliderColor;
|
||||||
|
final Color trackColor;
|
||||||
|
final double sliderWidth;
|
||||||
|
const VolumeControl({
|
||||||
|
super.key,
|
||||||
|
required this.volume,
|
||||||
|
required this.onChanged,
|
||||||
|
required this.onToggleMute,
|
||||||
|
required this.button,
|
||||||
|
this.sliderColor = Colors.white,
|
||||||
|
this.trackColor = Colors.white30,
|
||||||
|
this.sliderWidth = 72,
|
||||||
|
});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<VolumeButton> createState() => _VolumeButtonState();
|
State<VolumeControl> createState() => _VolumeControlState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _VolumeButtonState extends State<VolumeButton> {
|
class _VolumeControlState extends State<VolumeControl> {
|
||||||
|
final _steps = WheelSteps();
|
||||||
bool _hover = false;
|
bool _hover = false;
|
||||||
double _beforeMute = 100;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final player = widget.player;
|
final v = widget.volume;
|
||||||
return StreamBuilder<double>(
|
|
||||||
stream: player.stream.volume,
|
|
||||||
initialData: player.state.volume,
|
|
||||||
builder: (context, snap) {
|
|
||||||
final v = snap.data ?? 100;
|
|
||||||
return MouseRegion(
|
return MouseRegion(
|
||||||
onEnter: (_) => setState(() => _hover = true),
|
onEnter: (_) => setState(() => _hover = true),
|
||||||
onExit: (_) => setState(() => _hover = false),
|
onExit: (_) => setState(() => _hover = false),
|
||||||
child: Listener(
|
child: Listener(
|
||||||
onPointerSignal: (e) {
|
onPointerSignal: (e) => _steps.handle(e, (step) => widget.onChanged(stepVolume(v, step * volumeStep))),
|
||||||
if (e is PointerScrollEvent && e.scrollDelta.dy != 0) {
|
|
||||||
player.setVolume(stepVolume(v, e.scrollDelta.dy < 0 ? 5 : -5));
|
|
||||||
}
|
|
||||||
},
|
|
||||||
child: Row(
|
child: Row(
|
||||||
|
key: const ValueKey('volume-control'),
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
const SizedBox(width: 4),
|
widget.button(
|
||||||
IconButton(
|
context,
|
||||||
key: const ValueKey('volume-button'),
|
volumeIcon(v),
|
||||||
focusNode: widget.focusNode,
|
v > 100 ? boostColor : null,
|
||||||
tooltip: 'Volume ${v.round()} %',
|
'Volume ${v.round()} % (scroll, ↑ / ↓)',
|
||||||
iconSize: 22,
|
widget.onToggleMute,
|
||||||
color: Colors.white,
|
|
||||||
onPressed: () {
|
|
||||||
if (v > 0) {
|
|
||||||
_beforeMute = v;
|
|
||||||
player.setVolume(0);
|
|
||||||
} else {
|
|
||||||
player.setVolume(_beforeMute <= 0 ? 100 : _beforeMute);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
icon: Icon(v <= 0 ? Icons.volume_off : (v < 50 ? Icons.volume_down : Icons.volume_up)),
|
|
||||||
),
|
),
|
||||||
AnimatedSize(
|
AnimatedSize(
|
||||||
duration: const Duration(milliseconds: 150),
|
duration: const Duration(milliseconds: 150),
|
||||||
child: _hover
|
child: _hover
|
||||||
? Padding(
|
? Padding(
|
||||||
padding: const EdgeInsets.only(left: 4, right: 12),
|
padding: const EdgeInsets.only(left: 4, right: 8),
|
||||||
child: VolumeBar(volume: v, onChanged: player.setVolume),
|
child: VolumeBar(
|
||||||
|
key: const ValueKey('volume-bar'),
|
||||||
|
volume: v,
|
||||||
|
onChanged: widget.onChanged,
|
||||||
|
width: widget.sliderWidth,
|
||||||
|
color: widget.sliderColor,
|
||||||
|
trackColor: widget.trackColor,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
: const SizedBox.shrink(),
|
: const SizedBox.shrink(),
|
||||||
),
|
),
|
||||||
@@ -140,7 +324,5 @@ class _VolumeButtonState extends State<VolumeButton> {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,196 +0,0 @@
|
|||||||
// Release file names -> series / season / episode, anitomy-style but small:
|
|
||||||
// enough to group a downloads folder into shows. Unknown shapes fall back to
|
|
||||||
// the cleaned name with no episode, never to a wrong number.
|
|
||||||
|
|
||||||
/// What a release file name says.
|
|
||||||
class ParsedName {
|
|
||||||
/// Title without group, season marker, episode, year or release tags.
|
|
||||||
final String series;
|
|
||||||
final int? season;
|
|
||||||
final int? episode;
|
|
||||||
/// Release group: leading `[Group]` or scene-style trailing `-GRP`.
|
|
||||||
final String? group;
|
|
||||||
/// Release year, taken out of [series] (movies, `Title (2019)`).
|
|
||||||
final int? year;
|
|
||||||
/// Non-episode marker (`NCOP1`, `NCED`, `OVA 2`, `Special`): such files
|
|
||||||
/// carry no [episode] so they never sort among the real ones.
|
|
||||||
final String? extra;
|
|
||||||
|
|
||||||
const ParsedName(
|
|
||||||
this.series, {
|
|
||||||
this.season,
|
|
||||||
this.episode,
|
|
||||||
this.group,
|
|
||||||
this.year,
|
|
||||||
this.extra,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// `S01E03`, `E25`, the [extra] marker, `S02` for a season pack, else ''.
|
|
||||||
String get label {
|
|
||||||
final s = season == null ? '' : 'S${season.toString().padLeft(2, '0')}';
|
|
||||||
if (episode != null) return '${s}E${episode.toString().padLeft(2, '0')}';
|
|
||||||
return extra ?? s;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Grouping key: case, punctuation and spacing do not split a series.
|
|
||||||
String get seriesKey => normalizeSeries(series);
|
|
||||||
|
|
||||||
@override
|
|
||||||
String toString() => 'ParsedName($series, s=$season, e=$episode, '
|
|
||||||
'group=$group, year=$year, extra=$extra)';
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Lowercase letters and digits of [s], single spaces between words.
|
|
||||||
String normalizeSeries(String s) => s
|
|
||||||
.toLowerCase()
|
|
||||||
.replaceAll(RegExp(r"['’`]"), '')
|
|
||||||
.replaceAll(RegExp(r'[^\p{L}\p{N}]+', unicode: true), ' ')
|
|
||||||
.trim();
|
|
||||||
|
|
||||||
// Release tags: the title ends where the first of these starts.
|
|
||||||
final _junk = RegExp(
|
|
||||||
r'\b(?:2160p|1440p|1080[pi]|720p|576p|480p|4K|UHD|[xh]\.?26[45]|HEVC|AVC|'
|
|
||||||
r'AV1|VP9|WEB(?:-?DL|-?Rip)?|BD(?:Rip|Remux)?|Blu-?Ray|BRRip|DVD(?:Rip)?|'
|
|
||||||
r'HDTV|HDR(?:10)?|DV|REMUX|AAC(?:\d\.\d)?|FLAC|Opus|DTS(?:-HD)?|E?-?AC-?3|'
|
|
||||||
r'DDP?\d?|TrueHD|Atmos|10-?bit|8-?bit|Hi10P?|PROPER|REPACK|Dual[ -]Audio|'
|
|
||||||
r'Multi(?:ple)?[ -]Subs?(?:titles?)?|AMZN|NF|CR|DSNP|HMAX|ATVP|'
|
|
||||||
r'Batch|Complete)\b',
|
|
||||||
caseSensitive: false,
|
|
||||||
);
|
|
||||||
final _ext = RegExp(r'\.(?=[a-z0-9]*[a-z])[a-z0-9]{2,4}$', caseSensitive: false);
|
|
||||||
final _leadingGroup = RegExp(r'^\s*\[([^\]]+)\]');
|
|
||||||
final _sceneGroup = RegExp(r'-([A-Za-z0-9]+)$');
|
|
||||||
final _bracketYear = RegExp(r'[(\[]((?:19|20)\d{2})[)\]]');
|
|
||||||
final _brackets = RegExp(r'\[[^\]]*\]|\([^)]*\)|\{[^}]*\}|【[^】]*】');
|
|
||||||
// S01E02, S01.E02, S1 E2; a batch `S01E01-E02` / `S01E01E02` keeps the first.
|
|
||||||
final _sxe = RegExp(r'\bS(\d{1,2})[ .]?E(\d{1,4})(?:v\d)?(?!\d)',
|
|
||||||
caseSensitive: false);
|
|
||||||
final _nxn = RegExp(r'\b(\d{1,2})x(\d{2,3})\b');
|
|
||||||
// Anime: `Title - 25`, `- 03v2`, `- 01-02` (batch keeps the first).
|
|
||||||
final _dashNumber = RegExp(r'\s[-–]\s(\d{1,4})(?:v\d)?(?=$|[\s\-~.])');
|
|
||||||
final _episodeWord = RegExp(
|
|
||||||
r'\b(?:Episode|Ep\.?|E)\s?(\d{1,4})(?:v\d)?\b',
|
|
||||||
caseSensitive: false,
|
|
||||||
);
|
|
||||||
// Extras: unambiguous words anywhere, short ones only right after the dash.
|
|
||||||
final _extraAnywhere = RegExp(
|
|
||||||
r'(?:^|\s)(NCOP|NCED|OVA|OAD|ONA)\s?(\d{1,2})?(?:v\d)?(?=$|\s)',
|
|
||||||
caseSensitive: false,
|
|
||||||
);
|
|
||||||
final _extraAfterDash = RegExp(
|
|
||||||
r'\s[-–]\s(OP|ED|SP|Specials?|Extras?|Recap|Preview|PV|Menu)\s?(\d{1,2})?'
|
|
||||||
r'(?:v\d)?(?=$|\s)',
|
|
||||||
caseSensitive: false,
|
|
||||||
);
|
|
||||||
final _seasonInTitle = RegExp(
|
|
||||||
r'\s(?:S(\d{1,2})|Season\s?(\d{1,2})|(\d{1,2})(?:st|nd|rd|th)\s+Season)\s*$',
|
|
||||||
caseSensitive: false,
|
|
||||||
);
|
|
||||||
final _trailingYear = RegExp(r'\s((?:19|20)\d{2})$');
|
|
||||||
|
|
||||||
/// Parses a file name (with or without the extension, no directories).
|
|
||||||
ParsedName parseReleaseName(String fileName) {
|
|
||||||
var s = fileName.replaceFirst(_ext, '').trim();
|
|
||||||
final original = s;
|
|
||||||
String? group = _leadingGroup.firstMatch(s)?.group(1)?.trim();
|
|
||||||
int? year;
|
|
||||||
final by = _bracketYear.firstMatch(s);
|
|
||||||
if (by != null) year = int.parse(by.group(1)!);
|
|
||||||
s = s.replaceAll(_brackets, ' ');
|
|
||||||
|
|
||||||
// Dots and underscores as separators (scene style), unless the name
|
|
||||||
// already has spaces and only the odd `Dr. Stone` dot.
|
|
||||||
final dotted = !s.contains(' ') || RegExp(r'\w\.\w').allMatches(s).length > 2;
|
|
||||||
if (dotted) {
|
|
||||||
// `...H264-GRP`, but not `...WEB-DL`.
|
|
||||||
final tags = _junk.allMatches(s);
|
|
||||||
if (group == null && tags.isNotEmpty && tags.last.end < s.length) {
|
|
||||||
final g = _sceneGroup.firstMatch(s);
|
|
||||||
if (g != null) {
|
|
||||||
group = g.group(1);
|
|
||||||
s = s.substring(0, g.start);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
s = s.replaceAll('.', ' ');
|
|
||||||
}
|
|
||||||
s = s.replaceAll('_', ' ').replaceAll(RegExp(r'\s+'), ' ').trim();
|
|
||||||
|
|
||||||
// Release tags end the interesting part.
|
|
||||||
final junk = _junk.firstMatch(s);
|
|
||||||
if (junk != null && junk.start > 0) s = s.substring(0, junk.start).trim();
|
|
||||||
|
|
||||||
int? season, episode;
|
|
||||||
String? extra;
|
|
||||||
var cut = s.length;
|
|
||||||
final extraMatch =
|
|
||||||
_extraAfterDash.firstMatch(s) ?? _extraAnywhere.firstMatch(s);
|
|
||||||
final sxe = _sxe.firstMatch(s);
|
|
||||||
if (extraMatch != null) {
|
|
||||||
final word = extraMatch.group(1)!;
|
|
||||||
final upper = word.length <= 4 ? word.toUpperCase() : _title(word);
|
|
||||||
// `OVA - 02`: the number may follow the dash instead.
|
|
||||||
final n = extraMatch.group(2) ??
|
|
||||||
_dashNumber.firstMatch(s.substring(extraMatch.end))?.group(1);
|
|
||||||
extra = n == null
|
|
||||||
? upper
|
|
||||||
: (upper.startsWith('NC') || upper.length <= 2)
|
|
||||||
? '$upper${int.parse(n)}'
|
|
||||||
: '$upper ${int.parse(n)}';
|
|
||||||
cut = extraMatch.start;
|
|
||||||
if (sxe != null && sxe.start < cut) {
|
|
||||||
season = int.parse(sxe.group(1)!);
|
|
||||||
cut = sxe.start;
|
|
||||||
}
|
|
||||||
} else if (sxe != null) {
|
|
||||||
season = int.parse(sxe.group(1)!);
|
|
||||||
episode = int.parse(sxe.group(2)!);
|
|
||||||
cut = sxe.start;
|
|
||||||
} else {
|
|
||||||
final nxn = _nxn.firstMatch(s);
|
|
||||||
if (nxn != null) {
|
|
||||||
season = int.parse(nxn.group(1)!);
|
|
||||||
episode = int.parse(nxn.group(2)!);
|
|
||||||
cut = nxn.start;
|
|
||||||
} else {
|
|
||||||
final m = _dashNumber.firstMatch(s) ?? _episodeWord.firstMatch(s);
|
|
||||||
if (m != null) {
|
|
||||||
episode = int.parse(m.group(1)!);
|
|
||||||
cut = m.start;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var series = s.substring(0, cut);
|
|
||||||
// Season pack or season marker kept in the title: `Title S2`,
|
|
||||||
// `Title Season 2`, `Title 2nd Season`, `Title.S01.1080p`.
|
|
||||||
final sIn = _seasonInTitle.firstMatch(series);
|
|
||||||
if (sIn != null) {
|
|
||||||
season ??= int.parse(sIn.group(1) ?? sIn.group(2) ?? sIn.group(3)!);
|
|
||||||
series = series.substring(0, sIn.start);
|
|
||||||
}
|
|
||||||
series = series.replaceAll(RegExp(r'[\s\-–:,~]+$'), '').trim();
|
|
||||||
// A trailing year is the release year, unless it is the whole title or
|
|
||||||
// too far ahead to be one (`Blade Runner 2049`).
|
|
||||||
final ty = _trailingYear.firstMatch(series);
|
|
||||||
if (ty != null) {
|
|
||||||
final y = int.parse(ty.group(1)!);
|
|
||||||
if (y <= DateTime.now().year + 1) {
|
|
||||||
year ??= y;
|
|
||||||
series = series.substring(0, ty.start).trim();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
series = series.replaceAll(RegExp(r'[\s\-–:,~]+$'), '').trim();
|
|
||||||
if (series.isEmpty) {
|
|
||||||
series = original.replaceAll(RegExp(r'[._]+'), ' ').trim();
|
|
||||||
}
|
|
||||||
return ParsedName(
|
|
||||||
series,
|
|
||||||
season: season,
|
|
||||||
episode: episode,
|
|
||||||
group: group,
|
|
||||||
year: year,
|
|
||||||
extra: extra,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
String _title(String w) => w[0].toUpperCase() + w.substring(1).toLowerCase();
|
|
||||||
@@ -1,16 +1,13 @@
|
|||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
import 'dart:isolate';
|
import 'dart:isolate';
|
||||||
|
|
||||||
import 'name_parser.dart';
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
// Folder scan for the Files source: videos with their parsed names,
|
export 'package:sync_relay_core/core.dart' show FileKind, LocalFile, kindOf, subtitleExtensions, videoExtensions;
|
||||||
// sidecar subtitles, everything else counted and hidden. The walk is
|
|
||||||
// synchronous I/O, so it runs in its own isolate.
|
|
||||||
|
|
||||||
const videoExtensions = {
|
// Folder scan for the Files source: the videos (grouped into shows by
|
||||||
'mkv', 'mp4', 'webm', 'avi', 'mov', 'm4v', 'ts', 'm2ts', 'wmv', 'flv', //
|
// core's `groupLocal`, L1), sidecar subtitles, everything else counted
|
||||||
};
|
// and hidden. The walk is synchronous I/O, so it runs in its own isolate.
|
||||||
const subtitleExtensions = {'ass', 'ssa', 'srt', 'vtt', 'sup'};
|
|
||||||
|
|
||||||
/// Files looked at per scan; past this the result is [FolderScan.truncated].
|
/// Files looked at per scan; past this the result is [FolderScan.truncated].
|
||||||
const maxScannedFiles = 20000;
|
const maxScannedFiles = 20000;
|
||||||
@@ -18,27 +15,8 @@ const maxScannedFiles = 20000;
|
|||||||
/// Samples and trailers under this size are hidden next to the real thing.
|
/// Samples and trailers under this size are hidden next to the real thing.
|
||||||
const _sampleMaxBytes = 300 << 20;
|
const _sampleMaxBytes = 300 << 20;
|
||||||
|
|
||||||
enum FileKind { video, subtitle, other }
|
|
||||||
|
|
||||||
FileKind kindOf(String path) {
|
|
||||||
final ext = _extension(_baseName(path));
|
|
||||||
if (videoExtensions.contains(ext)) return FileKind.video;
|
|
||||||
if (subtitleExtensions.contains(ext)) return FileKind.subtitle;
|
|
||||||
return FileKind.other;
|
|
||||||
}
|
|
||||||
|
|
||||||
class VideoFile {
|
|
||||||
final String path;
|
|
||||||
final int size;
|
|
||||||
final ParsedName parsed;
|
|
||||||
final DateTime modified;
|
|
||||||
const VideoFile(this.path, this.size, this.parsed, this.modified);
|
|
||||||
|
|
||||||
String get name => _baseName(path);
|
|
||||||
}
|
|
||||||
|
|
||||||
class FolderScan {
|
class FolderScan {
|
||||||
final List<VideoFile> videos;
|
final List<LocalFile> videos;
|
||||||
/// Non-video files and samples (subtitles and dot-entries not counted).
|
/// Non-video files and samples (subtitles and dot-entries not counted).
|
||||||
final int hiddenCount;
|
final int hiddenCount;
|
||||||
/// Up to 6 of the hidden file names, for "and N other files" hints.
|
/// Up to 6 of the hidden file names, for "and N other files" hints.
|
||||||
@@ -75,7 +53,7 @@ Future<FolderScan> scanFolder(String dir, {int maxFiles = maxScannedFiles}) =>
|
|||||||
|
|
||||||
/// The walk behind [scanFolder]; blocks, so call it from an isolate.
|
/// The walk behind [scanFolder]; blocks, so call it from an isolate.
|
||||||
FolderScan scanFolderSync(String dir, {int maxFiles = maxScannedFiles}) {
|
FolderScan scanFolderSync(String dir, {int maxFiles = maxScannedFiles}) {
|
||||||
final videos = <VideoFile>[];
|
final videos = <LocalFile>[];
|
||||||
final subs = <String>[];
|
final subs = <String>[];
|
||||||
final examples = <String>[];
|
final examples = <String>[];
|
||||||
var hidden = 0, seen = 0;
|
var hidden = 0, seen = 0;
|
||||||
@@ -123,8 +101,7 @@ FolderScan scanFolderSync(String dir, {int maxFiles = maxScannedFiles}) {
|
|||||||
if (examples.length < 6) examples.add(name);
|
if (examples.length < 6) examples.add(name);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
videos.add(VideoFile(e.path, size, parseReleaseName(name),
|
videos.add(LocalFile(e.path, size, stat?.modified ?? DateTime.fromMillisecondsSinceEpoch(0)));
|
||||||
stat?.modified ?? DateTime.fromMillisecondsSinceEpoch(0)));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return FolderScan(
|
return FolderScan(
|
||||||
@@ -138,7 +115,7 @@ FolderScan scanFolderSync(String dir, {int maxFiles = maxScannedFiles}) {
|
|||||||
|
|
||||||
/// Subtitles in the same folder whose name is the video's base name,
|
/// Subtitles in the same folder whose name is the video's base name,
|
||||||
/// optionally followed by `.lang` / `.forced` style suffixes.
|
/// optionally followed by `.lang` / `.forced` style suffixes.
|
||||||
Map<String, List<String>> _sidecars(List<VideoFile> videos, List<String> subs) {
|
Map<String, List<String>> _sidecars(List<LocalFile> videos, List<String> subs) {
|
||||||
final byStem = <String, List<String>>{};
|
final byStem = <String, List<String>>{};
|
||||||
for (final s in subs) {
|
for (final s in subs) {
|
||||||
final stem = _stripExtension(s);
|
final stem = _stripExtension(s);
|
||||||
@@ -163,93 +140,11 @@ Map<String, List<String>> _sidecars(List<VideoFile> videos, List<String> subs) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One show: its episodes in season/episode order plus its extras
|
|
||||||
/// (NCOP, OVA...) in name order.
|
|
||||||
class SeriesGroup {
|
|
||||||
/// Display title: the most common spelling among the files.
|
|
||||||
final String title;
|
|
||||||
final String key;
|
|
||||||
final List<VideoFile> episodes;
|
|
||||||
final List<VideoFile> extras;
|
|
||||||
const SeriesGroup(this.title, this.key, this.episodes, this.extras);
|
|
||||||
|
|
||||||
/// Distinct seasons, ascending; files without one count as season 1.
|
|
||||||
List<int> get seasons =>
|
|
||||||
({for (final e in episodes) e.parsed.season ?? 1}.toList()..sort());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// [groupBySeries] result: shows, and videos that are not episodes.
|
|
||||||
class GroupedVideos {
|
|
||||||
final List<SeriesGroup> series;
|
|
||||||
final List<VideoFile> loose;
|
|
||||||
const GroupedVideos(this.series, this.loose);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Groups videos with an episode number (or an extra marker) by
|
|
||||||
/// [ParsedName.seriesKey]; the rest (movies, clips) stay loose, by name.
|
|
||||||
/// An extra whose series has no episodes in the list is loose too.
|
|
||||||
GroupedVideos groupBySeries(Iterable<VideoFile> videos) {
|
|
||||||
final episodes = <String, List<VideoFile>>{};
|
|
||||||
final extras = <String, List<VideoFile>>{};
|
|
||||||
final loose = <VideoFile>[];
|
|
||||||
for (final v in videos) {
|
|
||||||
final p = v.parsed;
|
|
||||||
final key = p.seriesKey;
|
|
||||||
if (p.episode != null && key.isNotEmpty) {
|
|
||||||
episodes.putIfAbsent(key, () => []).add(v);
|
|
||||||
} else if (p.extra != null && key.isNotEmpty) {
|
|
||||||
extras.putIfAbsent(key, () => []).add(v);
|
|
||||||
} else {
|
|
||||||
loose.add(v);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (final e in extras.entries) {
|
|
||||||
if (!episodes.containsKey(e.key)) loose.addAll(e.value);
|
|
||||||
}
|
|
||||||
int byName(VideoFile a, VideoFile b) =>
|
|
||||||
a.name.toLowerCase().compareTo(b.name.toLowerCase());
|
|
||||||
final groups = [
|
|
||||||
for (final e in episodes.entries)
|
|
||||||
SeriesGroup(
|
|
||||||
_commonTitle(e.value),
|
|
||||||
e.key,
|
|
||||||
e.value..sort(_byEpisode),
|
|
||||||
(extras[e.key] ?? [])..sort(byName),
|
|
||||||
),
|
|
||||||
]..sort((a, b) => a.title.toLowerCase().compareTo(b.title.toLowerCase()));
|
|
||||||
return GroupedVideos(groups, loose..sort(byName));
|
|
||||||
}
|
|
||||||
|
|
||||||
int _byEpisode(VideoFile a, VideoFile b) {
|
|
||||||
final pa = a.parsed, pb = b.parsed;
|
|
||||||
final s = (pa.season ?? 1).compareTo(pb.season ?? 1);
|
|
||||||
if (s != 0) return s;
|
|
||||||
final e = pa.episode!.compareTo(pb.episode!);
|
|
||||||
if (e != 0) return e;
|
|
||||||
// Same episode twice (v2, another group): newest release first.
|
|
||||||
return b.name.compareTo(a.name);
|
|
||||||
}
|
|
||||||
|
|
||||||
String _commonTitle(List<VideoFile> files) {
|
|
||||||
final counts = <String, int>{};
|
|
||||||
for (final f in files) {
|
|
||||||
counts.update(f.parsed.series, (n) => n + 1, ifAbsent: () => 1);
|
|
||||||
}
|
|
||||||
return counts.entries
|
|
||||||
.reduce((a, b) => b.value > a.value ? b : a)
|
|
||||||
.key;
|
|
||||||
}
|
|
||||||
|
|
||||||
String _baseName(String path) {
|
String _baseName(String path) {
|
||||||
final i = path.lastIndexOf(RegExp(r'[/\\]'));
|
final i = path.lastIndexOf(RegExp(r'[/\\]'));
|
||||||
return i < 0 ? path : path.substring(i + 1);
|
return i < 0 ? path : path.substring(i + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
String _extension(String name) {
|
|
||||||
final dot = name.lastIndexOf('.');
|
|
||||||
return dot <= 0 ? '' : name.substring(dot + 1).toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
String _stripExtension(String path) {
|
String _stripExtension(String path) {
|
||||||
final dot = path.lastIndexOf('.');
|
final dot = path.lastIndexOf('.');
|
||||||
final sep = path.lastIndexOf(RegExp(r'[/\\]'));
|
final sep = path.lastIndexOf(RegExp(r'[/\\]'));
|
||||||
|
|||||||
@@ -4,9 +4,11 @@ import 'dart:io';
|
|||||||
|
|
||||||
import 'package:crypto/crypto.dart';
|
import 'package:crypto/crypto.dart';
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:media_kit/media_kit.dart';
|
|
||||||
import 'package:path_provider/path_provider.dart';
|
import 'package:path_provider/path_provider.dart';
|
||||||
|
|
||||||
|
import '../platform/desktop/media_kit_host.dart' show MediaKitHost;
|
||||||
|
import '../platform/ports/player_host.dart';
|
||||||
|
|
||||||
// Poster frames for the Files source, made by mpv itself (no ffmpeg on
|
// Poster frames for the Files source, made by mpv itself (no ffmpeg on
|
||||||
// users' machines; Windows ships only libmpv). A hidden player per file
|
// users' machines; Windows ships only libmpv). A hidden player per file
|
||||||
// with `vo=null`: mpv still keeps the last decoded frame, so
|
// with `vo=null`: mpv still keeps the last decoded frame, so
|
||||||
@@ -23,6 +25,9 @@ class Thumbnail {
|
|||||||
|
|
||||||
const thumbnailWidth = 480;
|
const thumbnailWidth = 480;
|
||||||
|
|
||||||
|
/// The players thumbnails are made with (the app's host, set in `main`).
|
||||||
|
PlayerHost thumbnailPlayers = MediaKitHost()..init();
|
||||||
|
|
||||||
/// Where thumbnails are cached; swapped in tests.
|
/// Where thumbnails are cached; swapped in tests.
|
||||||
Future<Directory> Function() thumbnailCacheRoot = getApplicationCacheDirectory;
|
Future<Directory> Function() thumbnailCacheRoot = getApplicationCacheDirectory;
|
||||||
|
|
||||||
@@ -33,15 +38,36 @@ const _timeout = Duration(seconds: 20);
|
|||||||
int _running = 0;
|
int _running = 0;
|
||||||
final _waiting = <Completer<void>>[];
|
final _waiting = <Completer<void>>[];
|
||||||
final _inFlight = <String, Future<Thumbnail?>>{};
|
final _inFlight = <String, Future<Thumbnail?>>{};
|
||||||
|
final _players = <HostedPlayer>{};
|
||||||
|
bool _closed = false;
|
||||||
|
|
||||||
|
/// App close: no new thumbnails, running ones stop at their next check
|
||||||
|
/// and dispose their player. Players still up after [deadline] are
|
||||||
|
/// disposed here, so no mpv outlives the engine.
|
||||||
|
Future<void> cancelAllThumbnails({
|
||||||
|
Duration deadline = const Duration(milliseconds: 800),
|
||||||
|
}) async {
|
||||||
|
_closed = true;
|
||||||
|
try {
|
||||||
|
await Future.wait(_inFlight.values.toList()).timeout(deadline);
|
||||||
|
} catch (_) {}
|
||||||
|
for (final p in _players.toList()) {
|
||||||
|
_players.remove(p);
|
||||||
|
try {
|
||||||
|
await thumbnailPlayers.dispose(p).timeout(deadline);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The cached or freshly made thumbnail of the video at [path], or null
|
/// The cached or freshly made thumbnail of the video at [path], or null
|
||||||
/// when it can't be made (not a video, unreadable, timed out, cancelled).
|
/// when it can't be made (not a video, unreadable, timed out, cancelled).
|
||||||
/// Never throws. [cancelled] is checked while queued and before the
|
/// Never throws. [cancelled] is checked while queued and before the
|
||||||
/// expensive steps: a scrolled-away tile returns null without decoding.
|
/// expensive steps: a scrolled-away tile returns null without decoding.
|
||||||
Future<Thumbnail?> thumbnailFor(String path, {bool Function()? cancelled}) {
|
Future<Thumbnail?> thumbnailFor(String path, {bool Function()? cancelled}) {
|
||||||
|
if (_closed) return Future.value(null);
|
||||||
final existing = _inFlight[path];
|
final existing = _inFlight[path];
|
||||||
if (existing != null) return existing;
|
if (existing != null) return existing;
|
||||||
final f = _thumbnailFor(path, cancelled ?? () => false).catchError((
|
final f = _thumbnailFor(path, () => _closed || (cancelled?.call() ?? false)).catchError((
|
||||||
Object e,
|
Object e,
|
||||||
StackTrace st,
|
StackTrace st,
|
||||||
) {
|
) {
|
||||||
@@ -126,18 +152,10 @@ Future<Thumbnail?> _generate(
|
|||||||
String out,
|
String out,
|
||||||
bool Function() cancelled,
|
bool Function() cancelled,
|
||||||
) async {
|
) async {
|
||||||
final player = Player(
|
final player = await thumbnailPlayers.create(PlayerRole.thumbnail);
|
||||||
configuration: const PlayerConfiguration(
|
_players.add(player);
|
||||||
vo: 'null',
|
|
||||||
muted: true,
|
|
||||||
osc: false,
|
|
||||||
libass: false,
|
|
||||||
title: 'thumbnail',
|
|
||||||
bufferSize: 4 << 20,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
try {
|
try {
|
||||||
final mpv = player.platform as NativePlayer;
|
final mpv = player;
|
||||||
for (final (k, v) in [
|
for (final (k, v) in [
|
||||||
('ao', 'null'),
|
('ao', 'null'),
|
||||||
('aid', 'no'),
|
('aid', 'no'),
|
||||||
@@ -154,7 +172,7 @@ Future<Thumbnail?> _generate(
|
|||||||
]) {
|
]) {
|
||||||
await mpv.setProperty(k, v);
|
await mpv.setProperty(k, v);
|
||||||
}
|
}
|
||||||
await player.open(Media(path), play: false);
|
await player.open(path);
|
||||||
final target = File(out);
|
final target = File(out);
|
||||||
final deadline = DateTime.now().add(_timeout);
|
final deadline = DateTime.now().add(_timeout);
|
||||||
while (DateTime.now().isBefore(deadline)) {
|
while (DateTime.now().isBefore(deadline)) {
|
||||||
@@ -176,6 +194,7 @@ Future<Thumbnail?> _generate(
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
} finally {
|
} finally {
|
||||||
await player.dispose();
|
// [cancelAllThumbnails] may have taken it already.
|
||||||
|
if (_players.remove(player)) await thumbnailPlayers.dispose(player);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,13 +2,13 @@ import 'dart:io';
|
|||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
import '../../shell/avatar.dart';
|
import '../../shell/avatar.dart';
|
||||||
import '../name_parser.dart';
|
|
||||||
import '../scanner.dart';
|
|
||||||
import 'thumb.dart';
|
import 'thumb.dart';
|
||||||
|
|
||||||
// The Files page's rows and cards: a series header, an episode row (also
|
// The Files page's rows and cards: an episode row (also used for Recent),
|
||||||
// used for Recent), a loose-video card, and the empty states.
|
// a loose-video card, and the empty states.
|
||||||
|
|
||||||
/// What a play control is doing right now.
|
/// What a play control is doing right now.
|
||||||
enum PlayState { idle, starting, playing }
|
enum PlayState { idle, starting, playing }
|
||||||
@@ -25,76 +25,8 @@ String parentName(String path) => baseName(File(path).parent.path);
|
|||||||
/// Cleaned title of a loose video: `Title (2019)`.
|
/// Cleaned title of a loose video: `Title (2019)`.
|
||||||
String cleanTitle(ParsedName p) => p.year == null ? p.series : '${p.series} (${p.year})';
|
String cleanTitle(ParsedName p) => p.year == null ? p.series : '${p.series} (${p.year})';
|
||||||
|
|
||||||
class SeriesHeader extends StatelessWidget {
|
/// One file as a row: an episode on a show's page, or a Recent entry
|
||||||
final SeriesGroup group;
|
/// ([indent] off).
|
||||||
final ThumbCache thumbs;
|
|
||||||
/// Its episodes are listed below; [onTap] opens or closes them.
|
|
||||||
final bool expanded;
|
|
||||||
final VoidCallback? onTap;
|
|
||||||
const SeriesHeader(
|
|
||||||
{super.key, required this.group, required this.thumbs, this.expanded = true, this.onTap});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final scheme = Theme.of(context).colorScheme;
|
|
||||||
final first = group.episodes.first;
|
|
||||||
final n = group.episodes.length;
|
|
||||||
final extras = group.extras.length;
|
|
||||||
final detail = [
|
|
||||||
'$n ${n == 1 ? 'episode' : 'episodes'}',
|
|
||||||
if (extras > 0) '$extras ${extras == 1 ? 'extra' : 'extras'}',
|
|
||||||
?first.parsed.group,
|
|
||||||
].join(' · ');
|
|
||||||
return Padding(
|
|
||||||
padding: const EdgeInsets.only(top: 14),
|
|
||||||
child: InkWell(
|
|
||||||
onTap: onTap,
|
|
||||||
borderRadius: BorderRadius.circular(10),
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
ClipRRect(
|
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
child: ThumbBuilder(
|
|
||||||
cache: thumbs,
|
|
||||||
path: first.path,
|
|
||||||
builder: (context, t, _) => ThumbImage(t, width: 96, height: 54),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 12),
|
|
||||||
Expanded(
|
|
||||||
child: Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text(group.title,
|
|
||||||
maxLines: 1,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
style: Theme.of(context).textTheme.titleMedium),
|
|
||||||
Text(detail,
|
|
||||||
maxLines: 1,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
style: TextStyle(color: scheme.onSurfaceVariant, fontSize: 12)),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (onTap != null)
|
|
||||||
AnimatedRotation(
|
|
||||||
turns: expanded ? 0.5 : 0,
|
|
||||||
duration: const Duration(milliseconds: 200),
|
|
||||||
child: Icon(Icons.expand_more, color: scheme.onSurfaceVariant),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One file as a row: an episode under its series header, or a Recent
|
|
||||||
/// entry ([title] given, [indent] off).
|
|
||||||
class FileRow extends StatelessWidget {
|
class FileRow extends StatelessWidget {
|
||||||
final String path;
|
final String path;
|
||||||
final String title;
|
final String title;
|
||||||
@@ -207,7 +139,7 @@ const videoCardTextHeight = 66.0;
|
|||||||
/// A loose video (movie, clip): 16:9 frame with its duration, then the
|
/// A loose video (movie, clip): 16:9 frame with its duration, then the
|
||||||
/// cleaned title and size.
|
/// cleaned title and size.
|
||||||
class VideoCard extends StatelessWidget {
|
class VideoCard extends StatelessWidget {
|
||||||
final VideoFile video;
|
final LocalEpisode video;
|
||||||
final PlayState state;
|
final PlayState state;
|
||||||
final ThumbCache thumbs;
|
final ThumbCache thumbs;
|
||||||
final VoidCallback? onTap;
|
final VoidCallback? onTap;
|
||||||
@@ -281,7 +213,7 @@ class VideoCard extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
Text(formatSize(video.size),
|
Text(formatSize(video.file.size),
|
||||||
style: TextStyle(color: scheme.onSurfaceVariant, fontSize: 12)),
|
style: TextStyle(color: scheme.onSurfaceVariant, fontSize: 12)),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -1,79 +1,95 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
|
|
||||||
import 'package:file_picker/file_picker.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:signals/signals_flutter.dart';
|
import 'package:signals/signals_flutter.dart';
|
||||||
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
|
import '../../library/show_matcher.dart';
|
||||||
import '../../shell/motion.dart';
|
import '../../shell/motion.dart';
|
||||||
|
import '../../platform/ports/folder_access.dart';
|
||||||
|
import '../../app/app_graph.dart';
|
||||||
|
import '../../watch/watch_history.dart';
|
||||||
|
import '../../widgets/app_menu.dart';
|
||||||
import '../folder_store.dart';
|
import '../folder_store.dart';
|
||||||
import '../name_parser.dart';
|
|
||||||
import '../scanner.dart';
|
import '../scanner.dart';
|
||||||
import 'file_tiles.dart';
|
import 'file_tiles.dart';
|
||||||
|
import 'library_view.dart';
|
||||||
import 'thumb.dart';
|
import 'thumb.dart';
|
||||||
|
|
||||||
export 'thumb.dart' show ThumbnailLoader;
|
export 'thumb.dart' show ThumbnailLoader;
|
||||||
|
|
||||||
// The Files source: watched folders on the left (chips on top when
|
// The Files source as a library: the watched folders on the left (chips
|
||||||
// narrow), the open one on the right grouped into series and loose
|
// on top when narrow): the Library (every folder together), Recent, then
|
||||||
// videos, or Recent. A folder is scanned when first opened and on Rescan;
|
// each folder. A library is shows and movies as poster cards, grouped by
|
||||||
// scans are kept for the app session. Series start collapsed; the ones
|
// the library's L1 and named by its L2 match, plus the videos that are
|
||||||
// opened stay open for the app session. Playing goes through [onPlay].
|
// neither; a show opens its own page. Folders are scanned when first
|
||||||
|
// needed and on Rescan; scans, the open place and the open show are kept
|
||||||
|
// for the app session. Playing goes through [onPlay].
|
||||||
|
|
||||||
/// Below this width the sidebar turns into chips above the list.
|
/// Below this width the sidebar turns into chips above the list.
|
||||||
const filesNarrowWidth = 700.0;
|
const filesNarrowWidth = 700.0;
|
||||||
|
|
||||||
|
/// The place that shows every watched folder together.
|
||||||
|
const libraryPlace = '\u0000library';
|
||||||
|
|
||||||
/// Scans kept for the app session, by folder.
|
/// Scans kept for the app session, by folder.
|
||||||
final _scans = <String, FolderScan>{};
|
final _scans = <String, FolderScan>{};
|
||||||
final _running = <String, Future<FolderScan>>{};
|
final _running = <String, Future<FolderScan>>{};
|
||||||
String? _lastOpen;
|
String? _lastOpen = libraryPlace;
|
||||||
/// Series opened this session, by `folder\nseries key`.
|
/// The show open in each place (by show key) for the app session.
|
||||||
final _expanded = <String>{};
|
final _openShows = <String, String>{};
|
||||||
final _showRequests = ValueNotifier(0);
|
final _showRequests = ValueNotifier(0);
|
||||||
|
|
||||||
/// Opens [dir] (null: Recent) in the Files page: now if one is showing,
|
/// Opens [dir] (null: Recent; [libraryPlace]: the library) in the Files
|
||||||
/// else when it next opens.
|
/// page: now if one is showing, else when it next opens.
|
||||||
void showFilesFolder(String? dir) {
|
void showFilesFolder(String? dir) {
|
||||||
_lastOpen = dir;
|
_lastOpen = dir;
|
||||||
_showRequests.value++;
|
_showRequests.value++;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Forgets the session's scans, open series and the open folder.
|
/// Forgets the session's scans, open shows and the open place.
|
||||||
@visibleForTesting
|
@visibleForTesting
|
||||||
void resetFilesPageSession() {
|
void resetFilesPageSession() {
|
||||||
_scans.clear();
|
_scans.clear();
|
||||||
_running.clear();
|
_running.clear();
|
||||||
_expanded.clear();
|
_openShows.clear();
|
||||||
_lastOpen = null;
|
_lastOpen = libraryPlace;
|
||||||
}
|
}
|
||||||
|
|
||||||
class FilesPage extends StatefulWidget {
|
class FilesPage extends StatefulWidget {
|
||||||
/// Nobody else watches (offline or solo): no relay notice.
|
/// Nobody else is in the server: no relay notice.
|
||||||
final bool solo;
|
final bool alone;
|
||||||
/// The file will stream from this computer through the server.
|
/// The file will stream from this computer through the server.
|
||||||
final bool relayed;
|
final bool relayed;
|
||||||
/// Plays [path] in the session; returns an error text, or null.
|
/// Plays [path] in the session; returns an error text, or null.
|
||||||
final Future<String?> Function(String path) onPlay;
|
final Future<String?> Function(String path) onPlay;
|
||||||
|
/// Adds [path] to Up next (right-click on a video); null: no server.
|
||||||
|
final Future<String?> Function(String path, {bool next})? onAddToQueue;
|
||||||
final String? nowPlayingPath;
|
final String? nowPlayingPath;
|
||||||
/// Defaults to [thumbnailFor].
|
/// Defaults to [thumbnailFor].
|
||||||
final ThumbnailLoader? thumbnails;
|
final ThumbnailLoader? thumbnails;
|
||||||
/// Defaults to [scanFolder].
|
/// Defaults to [FolderAccess.scan].
|
||||||
final Future<FolderScan> Function(String dir)? scan;
|
final Future<FolderScan> Function(String dir)? scan;
|
||||||
/// Defaults to [FolderStore.instance].
|
/// Defaults to [FolderStore.instance].
|
||||||
final FolderStore? store;
|
final FolderStore? store;
|
||||||
|
/// Defaults to the app's (`AppGraph.library`).
|
||||||
|
final ShowMatcher? matcher;
|
||||||
/// Default: the system folder / file dialogs.
|
/// Default: the system folder / file dialogs.
|
||||||
final Future<String?> Function()? pickFolder;
|
final Future<String?> Function()? pickFolder;
|
||||||
final Future<String?> Function()? pickVideo;
|
final Future<String?> Function()? pickVideo;
|
||||||
|
|
||||||
const FilesPage({
|
const FilesPage({
|
||||||
super.key,
|
super.key,
|
||||||
this.solo = false,
|
this.alone = false,
|
||||||
required this.relayed,
|
required this.relayed,
|
||||||
required this.onPlay,
|
required this.onPlay,
|
||||||
|
this.onAddToQueue,
|
||||||
this.nowPlayingPath,
|
this.nowPlayingPath,
|
||||||
this.thumbnails,
|
this.thumbnails,
|
||||||
this.scan,
|
this.scan,
|
||||||
this.store,
|
this.store,
|
||||||
|
this.matcher,
|
||||||
this.pickFolder,
|
this.pickFolder,
|
||||||
this.pickVideo,
|
this.pickVideo,
|
||||||
});
|
});
|
||||||
@@ -82,50 +98,57 @@ class FilesPage extends StatefulWidget {
|
|||||||
State<FilesPage> createState() => _FilesPageState();
|
State<FilesPage> createState() => _FilesPageState();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A scan grouped for display, made once per scan.
|
/// A place's scans grouped (L1), made once per set of scans.
|
||||||
class _Library {
|
class _Library {
|
||||||
final GroupedVideos grouped;
|
final List<FolderScan> scans;
|
||||||
final int subtitleFiles;
|
final LocalLibrary lib;
|
||||||
|
final Map<String, LocalEpisode> byPath;
|
||||||
|
|
||||||
_Library(FolderScan scan)
|
_Library(this.scans, List<String> roots)
|
||||||
: grouped = groupBySeries(scan.videos),
|
: lib = groupLocal([for (final s in scans) ...s.videos], roots: roots),
|
||||||
subtitleFiles = {for (final l in scan.subtitles.values) ...l}.length;
|
byPath = {} {
|
||||||
|
for (final e in lib.files) {
|
||||||
|
byPath[e.path] = e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Series rows in order: a header (video null), then, for the series
|
int get videos => scans.fold(0, (n, s) => n + s.videos.length);
|
||||||
/// [open] says, its episodes and extras.
|
int get hidden => scans.fold(0, (n, s) => n + s.hiddenCount);
|
||||||
List<(SeriesGroup, VideoFile?)> rows(bool Function(SeriesGroup g) open) => [
|
int get subtitleFiles => {
|
||||||
for (final g in grouped.series) ...[
|
for (final s in scans)
|
||||||
(g, null),
|
for (final l in s.subtitles.values) ...l
|
||||||
if (open(g))
|
}.length;
|
||||||
for (final v in [...g.episodes, ...g.extras]) (g, v),
|
bool get truncated => scans.any((s) => s.truncated);
|
||||||
],
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
final _libraries = Expando<_Library>();
|
|
||||||
|
|
||||||
class _FilesPageState extends State<FilesPage> {
|
class _FilesPageState extends State<FilesPage> {
|
||||||
|
FolderAccess get _folders => AppScope.of(context).ports.folders;
|
||||||
|
ShowMatcher get _matcher => widget.matcher ?? AppScope.of(context).library;
|
||||||
|
|
||||||
late final ThumbCache _thumbs =
|
late final ThumbCache _thumbs =
|
||||||
widget.thumbnails == null ? ThumbCache.shared : ThumbCache(widget.thumbnails!);
|
widget.thumbnails == null ? ThumbCache.shared : ThumbCache(widget.thumbnails!);
|
||||||
FolderStore get _store => widget.store ?? FolderStore.instance;
|
FolderStore get _store => widget.store ?? FolderStore.instance;
|
||||||
|
WatchHistory get _history => AppScope.of(context).watch.history;
|
||||||
|
|
||||||
/// Null: Recent.
|
/// Null: Recent; [libraryPlace]: every folder.
|
||||||
String? _open = _lastOpen;
|
String? _open = _lastOpen;
|
||||||
bool _showHidden = false;
|
bool _showHidden = false;
|
||||||
String? _starting;
|
String? _starting;
|
||||||
String? _error;
|
String? _error;
|
||||||
|
final _libs = <String, _Library>{};
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
_showRequests.addListener(_shown);
|
_showRequests.addListener(_shown);
|
||||||
|
unawaited(_matcher.ensureLoaded());
|
||||||
_store.ensureLoaded().then((_) {
|
_store.ensureLoaded().then((_) {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
final open = _open;
|
final open = _open;
|
||||||
if (open != null && !_store.folders.value.contains(open)) {
|
if (open != null && open != libraryPlace && !_store.folders.value.contains(open)) {
|
||||||
_select(null);
|
_select(libraryPlace);
|
||||||
} else if (open != null) {
|
} else {
|
||||||
_scan(open);
|
_scanFor(open);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -138,21 +161,34 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
|
|
||||||
void _shown() => _select(_lastOpen);
|
void _shown() => _select(_lastOpen);
|
||||||
|
|
||||||
Future<FolderScan> _runScan(String dir) => (widget.scan ?? scanFolder)(dir);
|
Future<FolderScan> _runScan(String dir) => (widget.scan ?? _folders.scan)(dir);
|
||||||
|
|
||||||
void _select(String? dir) {
|
/// The folders a place needs scanned.
|
||||||
|
List<String> _foldersOf(String? place) => place == null
|
||||||
|
? const []
|
||||||
|
: place == libraryPlace
|
||||||
|
? _store.folders.peek()
|
||||||
|
: [place];
|
||||||
|
|
||||||
|
void _scanFor(String? place) {
|
||||||
|
for (final f in _foldersOf(place)) {
|
||||||
|
if (!_scans.containsKey(f) && !_running.containsKey(f)) _scan(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _select(String? place) {
|
||||||
setState(() {
|
setState(() {
|
||||||
_open = _lastOpen = dir;
|
_open = _lastOpen = place;
|
||||||
_showHidden = false;
|
_showHidden = false;
|
||||||
});
|
});
|
||||||
if (dir != null && !_scans.containsKey(dir)) _scan(dir);
|
_scanFor(place);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _scan(String dir, {bool rescan = false}) async {
|
Future<void> _scan(String dir, {bool rescan = false}) async {
|
||||||
var f = _running[dir];
|
var f = _running[dir];
|
||||||
if (f == null || rescan) {
|
if (f == null || rescan) {
|
||||||
f = _running[dir] = _runScan(dir);
|
f = _running[dir] = _runScan(dir);
|
||||||
if (rescan) _thumbs.forget([for (final v in _scans[dir]?.videos ?? const <VideoFile>[]) v.path]);
|
if (rescan) _thumbs.forget([for (final v in _scans[dir]?.videos ?? const <LocalFile>[]) v.path]);
|
||||||
}
|
}
|
||||||
if (mounted) setState(() {});
|
if (mounted) setState(() {});
|
||||||
FolderScan result;
|
FolderScan result;
|
||||||
@@ -168,11 +204,31 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
if (mounted) setState(() {});
|
if (mounted) setState(() {});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The grouped library of [place], once its folders are scanned (the
|
||||||
|
/// library: those scanned so far).
|
||||||
|
_Library? _libraryOf(String place) {
|
||||||
|
final folders = _foldersOf(place);
|
||||||
|
final scans = [for (final f in folders) ?_scans[f]];
|
||||||
|
if (place != libraryPlace && scans.isEmpty) return null;
|
||||||
|
final known = _libs[place];
|
||||||
|
if (known != null && known.scans.length == scans.length && _same(known.scans, scans)) return known;
|
||||||
|
final lib = _libs[place] = _Library(scans, folders);
|
||||||
|
_matcher.remember(lib.lib);
|
||||||
|
return lib;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool _same(List<FolderScan> a, List<FolderScan> b) {
|
||||||
|
for (var i = 0; i < a.length; i++) {
|
||||||
|
if (!identical(a[i], b[i])) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _addFolder() async {
|
Future<void> _addFolder() async {
|
||||||
String? dir;
|
String? dir;
|
||||||
try {
|
try {
|
||||||
dir = await (widget.pickFolder ??
|
dir = await (widget.pickFolder ??
|
||||||
() => FilePicker.getDirectoryPath(dialogTitle: 'Add a folder with videos'))();
|
() => _folders.pickFolder(dialogTitle: 'Add a folder with videos'))();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
_showError('Folder dialog unavailable (${e.runtimeType})');
|
_showError('Folder dialog unavailable (${e.runtimeType})');
|
||||||
}
|
}
|
||||||
@@ -191,19 +247,16 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
if (path != null && mounted) await _play(path);
|
if (path != null && mounted) await _play(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
static Future<String?> _pickVideo() async {
|
Future<String?> _pickVideo() async {
|
||||||
final files = await FilePicker.pickFiles(
|
final files = await _folders.pickFiles(dialogTitle: 'Pick a video', extensions: videoExtensions.toList());
|
||||||
dialogTitle: 'Pick a video',
|
return files.firstOrNull;
|
||||||
type: FileType.custom,
|
|
||||||
allowedExtensions: videoExtensions.toList(),
|
|
||||||
);
|
|
||||||
return files.isEmpty ? null : files.first.path;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void _removeFolder(String dir) {
|
void _removeFolder(String dir) {
|
||||||
_store.removeFolder(dir);
|
_store.removeFolder(dir);
|
||||||
_scans.remove(dir);
|
_scans.remove(dir);
|
||||||
if (_open == dir) _select(null);
|
if (_open == dir) _select(libraryPlace);
|
||||||
|
setState(() {});
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _play(String path) async {
|
Future<void> _play(String path) async {
|
||||||
@@ -238,6 +291,58 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
|
|
||||||
VoidCallback _tapOf(String path) => () => _play(path);
|
VoidCallback _tapOf(String path) => () => _play(path);
|
||||||
|
|
||||||
|
/// Right-click on a video ([context]: its tile): Put it up, Add to
|
||||||
|
/// queue, Play next.
|
||||||
|
Future<void> _menu(BuildContext context, String path) async {
|
||||||
|
final add = widget.onAddToQueue;
|
||||||
|
if (add == null) return;
|
||||||
|
final pick = await showAppMenu<int>(context, items: [
|
||||||
|
AppMenuItem(value: 0, label: widget.alone ? 'Play' : 'Put it up'),
|
||||||
|
const AppMenuItem(value: 1, label: 'Add to queue'),
|
||||||
|
const AppMenuItem(value: 2, label: 'Play next'),
|
||||||
|
]);
|
||||||
|
if (pick == null || !mounted) return;
|
||||||
|
if (pick == 0) return _play(path);
|
||||||
|
String? error;
|
||||||
|
try {
|
||||||
|
error = await add(path, next: pick == 2);
|
||||||
|
} catch (e) {
|
||||||
|
error = '$e';
|
||||||
|
}
|
||||||
|
if (error != null) _showError(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [child] with the right-click menu (when there is a server).
|
||||||
|
Widget _menuable(String path, Widget child) => widget.onAddToQueue == null
|
||||||
|
? child
|
||||||
|
: KeyedSubtree(
|
||||||
|
key: ValueKey('menu:$path'),
|
||||||
|
child: Builder(
|
||||||
|
builder: (context) => GestureDetector(onSecondaryTap: () => _menu(context, path), child: child)));
|
||||||
|
|
||||||
|
late final _actions = FilesActions(
|
||||||
|
play: (p) => unawaited(_play(p)),
|
||||||
|
stateOf: _stateOf,
|
||||||
|
menuable: _menuable,
|
||||||
|
thumbs: _thumbs,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// The last episode of [show] watched here (the watch history: the
|
||||||
|
/// newest one watched to the end), else the last one opened (Recent), by
|
||||||
|
/// key.
|
||||||
|
String? _lastPlayed(_Library lib, LocalShow show) {
|
||||||
|
for (final (key, entry) in _history.entries) {
|
||||||
|
if (!entry.played || !key.value.startsWith('file:')) continue;
|
||||||
|
final e = lib.byPath[key.value.substring(5)];
|
||||||
|
if (e != null && e.showKey == show.key && e.kind == LocalKind.episode) return e.key;
|
||||||
|
}
|
||||||
|
for (final p in _store.recent.value) {
|
||||||
|
final e = lib.byPath[p];
|
||||||
|
if (e != null && e.showKey == show.key && e.kind == LocalKind.episode) return e.key;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) => LayoutBuilder(
|
Widget build(BuildContext context) => LayoutBuilder(
|
||||||
builder: (context, box) {
|
builder: (context, box) {
|
||||||
@@ -245,11 +350,14 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
return SignalBuilder(builder: (context) {
|
return SignalBuilder(builder: (context) {
|
||||||
final folders = _store.folders.value;
|
final folders = _store.folders.value;
|
||||||
final recent = _store.recent.value;
|
final recent = _store.recent.value;
|
||||||
final open = _open != null && folders.contains(_open) ? _open : null;
|
_matcher.revision.value;
|
||||||
|
_history.revision.value;
|
||||||
|
final open = _open == null || _open == libraryPlace || folders.contains(_open) ? _open : libraryPlace;
|
||||||
|
final showKey = open == null ? null : _openShows[open];
|
||||||
final main = fadeThrough(
|
final main = fadeThrough(
|
||||||
KeyedSubtree(
|
KeyedSubtree(
|
||||||
key: ValueKey(open ?? ''),
|
key: ValueKey('${open ?? ''}\n${showKey ?? ''}'),
|
||||||
child: _main(context, narrow, folders, recent, open),
|
child: _main(context, narrow, folders, recent, open, showKey),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
if (narrow) return main;
|
if (narrow) return main;
|
||||||
@@ -269,12 +377,23 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
Widget _sidebar(BuildContext context, List<String> folders, String? open) {
|
Widget _sidebar(BuildContext context, List<String> folders, String? open) {
|
||||||
final scheme = Theme.of(context).colorScheme;
|
final scheme = Theme.of(context).colorScheme;
|
||||||
final shape = RoundedRectangleBorder(borderRadius: BorderRadius.circular(10));
|
final shape = RoundedRectangleBorder(borderRadius: BorderRadius.circular(10));
|
||||||
|
Widget? status(String? s) =>
|
||||||
|
s == null ? null : Text(s, style: TextStyle(color: scheme.onSurfaceVariant, fontSize: 11));
|
||||||
return ListView(
|
return ListView(
|
||||||
padding: const EdgeInsets.fromLTRB(20, 20, 8, 20),
|
padding: const EdgeInsets.fromLTRB(20, 20, 8, 20),
|
||||||
children: [
|
children: [
|
||||||
const Text('Folders', style: TextStyle(fontWeight: FontWeight.w600)),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
ListTile(
|
ListTile(
|
||||||
|
key: const ValueKey('place:library'),
|
||||||
|
dense: true,
|
||||||
|
selected: open == libraryPlace,
|
||||||
|
shape: shape,
|
||||||
|
leading: const Icon(Icons.video_library_outlined, size: 18),
|
||||||
|
title: const Text('Library'),
|
||||||
|
subtitle: status(_libraryStatus(folders)),
|
||||||
|
onTap: () => _select(libraryPlace),
|
||||||
|
),
|
||||||
|
ListTile(
|
||||||
|
key: const ValueKey('place:recent'),
|
||||||
dense: true,
|
dense: true,
|
||||||
selected: open == null,
|
selected: open == null,
|
||||||
shape: shape,
|
shape: shape,
|
||||||
@@ -282,6 +401,9 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
title: const Text('Recent'),
|
title: const Text('Recent'),
|
||||||
onTap: () => _select(null),
|
onTap: () => _select(null),
|
||||||
),
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
const Text('Folders', style: TextStyle(fontWeight: FontWeight.w600)),
|
||||||
|
const SizedBox(height: 8),
|
||||||
for (final f in folders)
|
for (final f in folders)
|
||||||
ListTile(
|
ListTile(
|
||||||
key: ValueKey('folder:$f'),
|
key: ValueKey('folder:$f'),
|
||||||
@@ -290,10 +412,7 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
shape: shape,
|
shape: shape,
|
||||||
leading: const Icon(Icons.folder_outlined, size: 18),
|
leading: const Icon(Icons.folder_outlined, size: 18),
|
||||||
title: Text(baseName(f), maxLines: 1, overflow: TextOverflow.ellipsis),
|
title: Text(baseName(f), maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||||
subtitle: switch (_folderStatus(f)) {
|
subtitle: status(_folderStatus(f)),
|
||||||
final s? => Text(s, style: TextStyle(color: scheme.onSurfaceVariant, fontSize: 11)),
|
|
||||||
null => null,
|
|
||||||
},
|
|
||||||
trailing: IconButton(
|
trailing: IconButton(
|
||||||
tooltip: 'Remove folder',
|
tooltip: 'Remove folder',
|
||||||
icon: const Icon(Icons.close, size: 16),
|
icon: const Icon(Icons.close, size: 16),
|
||||||
@@ -331,19 +450,15 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
return n == null ? null : '$n ${n == 1 ? 'video' : 'videos'}';
|
return n == null ? null : '$n ${n == 1 ? 'video' : 'videos'}';
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _main(
|
String? _libraryStatus(List<String> folders) {
|
||||||
BuildContext context,
|
if (folders.any(_running.containsKey)) return 'scanning…';
|
||||||
bool narrow,
|
if (folders.isEmpty || folders.any((f) => !_scans.containsKey(f))) return null;
|
||||||
List<String> folders,
|
final n = _libraryOf(libraryPlace)?.lib.shows.length ?? 0;
|
||||||
List<String> recent,
|
return '$n ${n == 1 ? 'show' : 'shows'}';
|
||||||
String? open,
|
}
|
||||||
) {
|
|
||||||
final scan = open == null ? null : _scans[open];
|
List<Widget> _notices() => [
|
||||||
final scanning = open != null && _running.containsKey(open);
|
if (!widget.alone && widget.relayed) const _RelayNotice(),
|
||||||
final top = <Widget>[
|
|
||||||
_header(context, open),
|
|
||||||
if (narrow) _chips(folders, open),
|
|
||||||
if (!widget.solo && widget.relayed) const _RelayNotice(),
|
|
||||||
AnimatedSize(
|
AnimatedSize(
|
||||||
duration: easeTime,
|
duration: easeTime,
|
||||||
curve: ease,
|
curve: ease,
|
||||||
@@ -353,11 +468,59 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
: _ErrorBanner(_error!, onClose: () => setState(() => _error = null)),
|
: _ErrorBanner(_error!, onClose: () => setState(() => _error = null)),
|
||||||
),
|
),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
Widget _main(
|
||||||
|
BuildContext context,
|
||||||
|
bool narrow,
|
||||||
|
List<String> folders,
|
||||||
|
List<String> recent,
|
||||||
|
String? open,
|
||||||
|
String? showKey,
|
||||||
|
) {
|
||||||
|
final lib = open == null ? null : _libraryOf(open);
|
||||||
|
final show = showKey == null ? null : lib?.lib.show(showKey);
|
||||||
|
if (open != null && lib != null && show != null) {
|
||||||
|
return ShowPage(
|
||||||
|
key: ValueKey('show:$open:${show.key}'),
|
||||||
|
show: show,
|
||||||
|
matcher: _matcher,
|
||||||
|
actions: _actions,
|
||||||
|
lastPlayed: _lastPlayed(lib, show),
|
||||||
|
backLabel: open == libraryPlace ? 'Library' : baseName(open),
|
||||||
|
onBack: () => setState(() => _openShows.remove(open)),
|
||||||
|
top: [if (narrow) _chips(folders, open), ..._notices()],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final scanning = _foldersOf(open).any(_running.containsKey);
|
||||||
|
// A folder added elsewhere (a drop, the handoff) joins the library.
|
||||||
|
if (open == libraryPlace && folders.any((f) => !_scans.containsKey(f) && !_running.containsKey(f))) {
|
||||||
|
scheduleMicrotask(() {
|
||||||
|
if (mounted) _scanFor(libraryPlace);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
final top = <Widget>[
|
||||||
|
_header(context, open),
|
||||||
|
if (narrow) _chips(folders, open),
|
||||||
|
..._notices(),
|
||||||
|
];
|
||||||
final slivers = <Widget>[
|
final slivers = <Widget>[
|
||||||
SliverList.list(children: top),
|
SliverList.list(children: top),
|
||||||
if (open == null)
|
if (open == null)
|
||||||
..._recent(context, recent)
|
..._recent(context, recent)
|
||||||
else if (scan == null)
|
else if (open == libraryPlace && folders.isEmpty)
|
||||||
|
SliverToBoxAdapter(
|
||||||
|
child: FilesEmpty(
|
||||||
|
Icons.video_library_outlined,
|
||||||
|
'Your library is empty',
|
||||||
|
'Add a folder with your videos: shows, seasons and movies are found by their names.',
|
||||||
|
action: FilledButton.icon(
|
||||||
|
onPressed: _addFolder,
|
||||||
|
icon: const Icon(Icons.create_new_folder_outlined),
|
||||||
|
label: const Text('Add folder'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (lib == null)
|
||||||
const SliverToBoxAdapter(
|
const SliverToBoxAdapter(
|
||||||
child: Padding(
|
child: Padding(
|
||||||
padding: EdgeInsets.only(top: 60),
|
padding: EdgeInsets.only(top: 60),
|
||||||
@@ -365,7 +528,7 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
else
|
else
|
||||||
..._folder(context, open, scan, scanning),
|
..._library(context, open, lib, scanning),
|
||||||
];
|
];
|
||||||
return CustomScrollView(
|
return CustomScrollView(
|
||||||
slivers: [
|
slivers: [
|
||||||
@@ -379,25 +542,30 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
|
|
||||||
Widget _header(BuildContext context, String? open) {
|
Widget _header(BuildContext context, String? open) {
|
||||||
final scheme = Theme.of(context).colorScheme;
|
final scheme = Theme.of(context).colorScheme;
|
||||||
|
final (icon, title, sub) = switch (open) {
|
||||||
|
null => (Icons.history, 'Recent', null),
|
||||||
|
libraryPlace => (Icons.video_library, 'Library', null),
|
||||||
|
final dir => (Icons.folder, baseName(dir), dir),
|
||||||
|
};
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.only(bottom: 14),
|
padding: const EdgeInsets.only(bottom: 14),
|
||||||
child: Row(
|
child: Row(
|
||||||
children: [
|
children: [
|
||||||
Icon(open == null ? Icons.history : Icons.folder, color: scheme.primary),
|
Icon(icon, color: scheme.primary),
|
||||||
const SizedBox(width: 10),
|
const SizedBox(width: 10),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
Text(
|
Text(
|
||||||
open == null ? 'Recent' : baseName(open),
|
title,
|
||||||
maxLines: 1,
|
maxLines: 1,
|
||||||
overflow: TextOverflow.ellipsis,
|
overflow: TextOverflow.ellipsis,
|
||||||
style: Theme.of(context).textTheme.headlineSmall,
|
style: Theme.of(context).textTheme.headlineSmall,
|
||||||
),
|
),
|
||||||
if (open != null)
|
if (sub != null)
|
||||||
Text(
|
Text(
|
||||||
open,
|
sub,
|
||||||
maxLines: 1,
|
maxLines: 1,
|
||||||
overflow: TextOverflow.ellipsis,
|
overflow: TextOverflow.ellipsis,
|
||||||
style: TextStyle(color: scheme.onSurfaceVariant, fontSize: 12),
|
style: TextStyle(color: scheme.onSurfaceVariant, fontSize: 12),
|
||||||
@@ -416,6 +584,11 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
spacing: 8,
|
spacing: 8,
|
||||||
runSpacing: 8,
|
runSpacing: 8,
|
||||||
children: [
|
children: [
|
||||||
|
ChoiceChip(
|
||||||
|
label: const Text('Library'),
|
||||||
|
selected: open == libraryPlace,
|
||||||
|
onSelected: (_) => _select(libraryPlace),
|
||||||
|
),
|
||||||
ChoiceChip(
|
ChoiceChip(
|
||||||
label: const Text('Recent'),
|
label: const Text('Recent'),
|
||||||
selected: open == null,
|
selected: open == null,
|
||||||
@@ -468,34 +641,48 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
itemCount: recent.length,
|
itemCount: recent.length,
|
||||||
itemBuilder: (context, i) {
|
itemBuilder: (context, i) {
|
||||||
final path = recent[i];
|
final path = recent[i];
|
||||||
return _RecentRow(
|
return _menuable(
|
||||||
|
path,
|
||||||
|
_RecentRow(
|
||||||
key: ValueKey(path),
|
key: ValueKey(path),
|
||||||
path: path,
|
path: path,
|
||||||
|
matcher: _matcher,
|
||||||
state: _stateOf(path),
|
state: _stateOf(path),
|
||||||
thumbs: _thumbs,
|
thumbs: _thumbs,
|
||||||
onTap: _tapOf(path),
|
onTap: _tapOf(path),
|
||||||
onRemove: () => _store.removeRecent(path),
|
onRemove: () => _store.removeRecent(path),
|
||||||
);
|
));
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
List<Widget> _folder(BuildContext context, String dir, FolderScan scan, bool scanning) {
|
Widget _section(BuildContext context, String title, {String? count}) => Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 22, bottom: 10),
|
||||||
|
child: Row(children: [
|
||||||
|
Text(title, style: Theme.of(context).textTheme.titleMedium),
|
||||||
|
if (count != null) ...[
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Text(count, style: Theme.of(context).textTheme.bodySmall?.copyWith(color: Colors.grey)),
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
List<Widget> _library(BuildContext context, String place, _Library lib, bool scanning) {
|
||||||
final scheme = Theme.of(context).colorScheme;
|
final scheme = Theme.of(context).colorScheme;
|
||||||
final lib = _libraries[scan] ??= _Library(scan);
|
final l = lib.lib;
|
||||||
final series = lib.grouped.series.length;
|
final folderScan = place == libraryPlace ? null : _scans[place];
|
||||||
String count(int n, String one, String many) => '$n ${n == 1 ? one : many}';
|
String count(int n, String one, String many) => '$n ${n == 1 ? one : many}';
|
||||||
final summary = [
|
final summary = [
|
||||||
count(scan.videos.length, 'video', 'videos') + (series > 0 ? ' in $series series' : ''),
|
count(lib.videos, 'video', 'videos') +
|
||||||
if (scan.hiddenCount > 0)
|
(l.shows.isEmpty ? '' : ' in ${count(l.shows.length, 'show', 'shows')}'),
|
||||||
'${count(scan.hiddenCount, 'other file', 'other files')} hidden',
|
if (lib.hidden > 0) '${count(lib.hidden, 'other file', 'other files')} hidden',
|
||||||
if (lib.subtitleFiles > 0) count(lib.subtitleFiles, 'subtitle file', 'subtitle files'),
|
if (lib.subtitleFiles > 0) count(lib.subtitleFiles, 'subtitle file', 'subtitle files'),
|
||||||
if (scan.truncated) 'stopped after $maxScannedFiles files',
|
if (lib.truncated) 'stopped after $maxScannedFiles files',
|
||||||
].join(' · ');
|
].join(' · ');
|
||||||
final loose = lib.grouped.loose;
|
final folders = _foldersOf(place);
|
||||||
String seriesId(SeriesGroup g) => '$dir\n${g.key}';
|
final movies = l.movies;
|
||||||
final rows = lib.rows((g) => _expanded.contains(seriesId(g)));
|
final other = l.other;
|
||||||
return [
|
return [
|
||||||
SliverToBoxAdapter(
|
SliverToBoxAdapter(
|
||||||
child: Wrap(
|
child: Wrap(
|
||||||
@@ -504,7 +691,7 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
Icon(Icons.filter_alt_outlined, size: 16, color: scheme.onSurfaceVariant),
|
Icon(Icons.filter_alt_outlined, size: 16, color: scheme.onSurfaceVariant),
|
||||||
const SizedBox(width: 6),
|
const SizedBox(width: 6),
|
||||||
Text(summary, style: TextStyle(color: scheme.onSurfaceVariant, fontSize: 12)),
|
Text(summary, style: TextStyle(color: scheme.onSurfaceVariant, fontSize: 12)),
|
||||||
if (scan.hiddenCount > 0) ...[
|
if (folderScan != null && folderScan.hiddenCount > 0) ...[
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: () => setState(() => _showHidden = !_showHidden),
|
onPressed: () => setState(() => _showHidden = !_showHidden),
|
||||||
@@ -512,16 +699,22 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
TextButton.icon(
|
TextButton.icon(
|
||||||
onPressed: scanning ? null : () => _scan(dir, rescan: true),
|
onPressed: scanning
|
||||||
|
? null
|
||||||
|
: () {
|
||||||
|
for (final f in folders) {
|
||||||
|
_scan(f, rescan: true);
|
||||||
|
}
|
||||||
|
},
|
||||||
icon: scanning
|
icon: scanning
|
||||||
? const SizedBox.square(
|
? const SizedBox.square(dimension: 14, child: CircularProgressIndicator(strokeWidth: 2))
|
||||||
dimension: 14, child: CircularProgressIndicator(strokeWidth: 2))
|
|
||||||
: const Icon(Icons.refresh, size: 16),
|
: const Icon(Icons.refresh, size: 16),
|
||||||
label: Text(scanning ? 'Scanning…' : 'Rescan'),
|
label: Text(scanning ? 'Scanning…' : 'Rescan'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
if (folderScan != null)
|
||||||
SliverToBoxAdapter(
|
SliverToBoxAdapter(
|
||||||
child: AnimatedSize(
|
child: AnimatedSize(
|
||||||
duration: easeTime,
|
duration: easeTime,
|
||||||
@@ -531,7 +724,7 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
? const SizedBox(width: double.infinity)
|
? const SizedBox(width: double.infinity)
|
||||||
: Column(
|
: Column(
|
||||||
children: [
|
children: [
|
||||||
for (final f in scan.hiddenExamples)
|
for (final f in folderScan.hiddenExamples)
|
||||||
ListTile(
|
ListTile(
|
||||||
dense: true,
|
dense: true,
|
||||||
enabled: false,
|
enabled: false,
|
||||||
@@ -542,19 +735,19 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
style: const TextStyle(fontSize: 12),
|
style: const TextStyle(fontSize: 12),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
if (scan.hiddenCount > scan.hiddenExamples.length)
|
if (folderScan.hiddenCount > folderScan.hiddenExamples.length)
|
||||||
ListTile(
|
ListTile(
|
||||||
dense: true,
|
dense: true,
|
||||||
enabled: false,
|
enabled: false,
|
||||||
title: Text('and ${scan.hiddenCount - scan.hiddenExamples.length} more'),
|
title: Text('and ${folderScan.hiddenCount - folderScan.hiddenExamples.length} more'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
if (scan.videos.isEmpty)
|
if (lib.videos == 0)
|
||||||
SliverToBoxAdapter(
|
SliverToBoxAdapter(
|
||||||
child: Directory(dir).existsSync()
|
child: place == libraryPlace || _folders.folderExists(place)
|
||||||
? const FilesEmpty(
|
? const FilesEmpty(
|
||||||
Icons.search_off,
|
Icons.search_off,
|
||||||
'No videos here',
|
'No videos here',
|
||||||
@@ -566,44 +759,25 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
'It may have been moved, renamed or be on a drive that is not connected.',
|
'It may have been moved, renamed or be on a drive that is not connected.',
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
// Series: files whose names carry an episode number; a header
|
if (l.shows.isNotEmpty) ...[
|
||||||
// click opens or closes its episodes.
|
SliverToBoxAdapter(child: _section(context, 'Shows', count: '${l.shows.length}')),
|
||||||
SliverList.builder(
|
SliverGrid.builder(
|
||||||
itemCount: rows.length,
|
gridDelegate: posterGrid(),
|
||||||
itemBuilder: (context, i) {
|
itemCount: l.shows.length,
|
||||||
final (group, v) = rows[i];
|
itemBuilder: (context, i) => _showCard(place, lib, l.shows[i]),
|
||||||
if (v == null) {
|
|
||||||
final id = seriesId(group);
|
|
||||||
return SeriesHeader(
|
|
||||||
key: ValueKey('series:${group.key}'),
|
|
||||||
group: group,
|
|
||||||
thumbs: _thumbs,
|
|
||||||
expanded: _expanded.contains(id),
|
|
||||||
onTap: () => setState(() => _expanded.contains(id) ? _expanded.remove(id) : _expanded.add(id)),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return FileRow(
|
|
||||||
key: ValueKey(v.path),
|
|
||||||
path: v.path,
|
|
||||||
title: v.parsed.label.isEmpty ? v.parsed.series : v.parsed.label,
|
|
||||||
subtitle: v.name,
|
|
||||||
size: formatSize(v.size),
|
|
||||||
state: _stateOf(v.path),
|
|
||||||
thumbs: _thumbs,
|
|
||||||
onTap: _tapOf(v.path),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
),
|
||||||
// Everything else (movies, clips) as a thumbnail grid.
|
],
|
||||||
if (loose.isNotEmpty) ...[
|
if (movies.isNotEmpty) ...[
|
||||||
|
SliverToBoxAdapter(child: _section(context, 'Movies', count: '${movies.length}')),
|
||||||
|
SliverGrid.builder(
|
||||||
|
gridDelegate: posterGrid(),
|
||||||
|
itemCount: movies.length,
|
||||||
|
itemBuilder: (context, i) => _movieCard(movies[i]),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
if (other.isNotEmpty) ...[
|
||||||
SliverToBoxAdapter(
|
SliverToBoxAdapter(
|
||||||
child: Padding(
|
child: _section(context, l.shows.isEmpty && movies.isEmpty ? 'Videos' : 'Other videos'),
|
||||||
padding: const EdgeInsets.only(top: 22, bottom: 10),
|
|
||||||
child: Text(
|
|
||||||
series == 0 ? 'Videos' : 'Other videos',
|
|
||||||
style: Theme.of(context).textTheme.titleMedium,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
SliverLayoutBuilder(builder: (context, c) {
|
SliverLayoutBuilder(builder: (context, c) {
|
||||||
const gap = 12.0;
|
const gap = 12.0;
|
||||||
@@ -617,28 +791,78 @@ class _FilesPageState extends State<FilesPage> {
|
|||||||
crossAxisSpacing: gap,
|
crossAxisSpacing: gap,
|
||||||
mainAxisExtent: cardW * 9 / 16 + videoCardTextHeight,
|
mainAxisExtent: cardW * 9 / 16 + videoCardTextHeight,
|
||||||
),
|
),
|
||||||
itemCount: loose.length,
|
itemCount: other.length,
|
||||||
itemBuilder: (context, i) {
|
itemBuilder: (context, i) {
|
||||||
final v = loose[i];
|
final v = other[i];
|
||||||
return VideoCard(
|
return _menuable(
|
||||||
|
v.path,
|
||||||
|
VideoCard(
|
||||||
key: ValueKey(v.path),
|
key: ValueKey(v.path),
|
||||||
video: v,
|
video: v,
|
||||||
state: _stateOf(v.path),
|
state: _stateOf(v.path),
|
||||||
thumbs: _thumbs,
|
thumbs: _thumbs,
|
||||||
onTap: _tapOf(v.path),
|
onTap: _tapOf(v.path),
|
||||||
);
|
));
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Widget _showCard(String place, _Library lib, LocalShow show) {
|
||||||
|
final m = _matcher.showMatch(show);
|
||||||
|
final last = _lastPlayed(lib, show);
|
||||||
|
final String subtitle;
|
||||||
|
if (last == null) {
|
||||||
|
final n = show.episodeCount;
|
||||||
|
subtitle = '$n ${n == 1 ? 'episode' : 'episodes'}';
|
||||||
|
} else {
|
||||||
|
final next = show.nextAfter(last);
|
||||||
|
subtitle = next == null ? 'Watched to the end' : 'Next: ${episodeNumber(next.episode)}';
|
||||||
|
}
|
||||||
|
final playing = widget.nowPlayingPath != null && show.files.any((e) => e.path == widget.nowPlayingPath);
|
||||||
|
return PosterCard(
|
||||||
|
key: ValueKey('showcard:${show.key}'),
|
||||||
|
title: m?.entry.title ?? show.title,
|
||||||
|
subtitle: subtitle,
|
||||||
|
coverUrl: m?.entry.cover,
|
||||||
|
framePath: show.episodes.firstOrNull?.path,
|
||||||
|
thumbs: _thumbs,
|
||||||
|
playing: playing,
|
||||||
|
onShown: () => _matcher.want(show),
|
||||||
|
onTap: () => setState(() => _openShows[place] = show.key),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _movieCard(LocalEpisode movie) {
|
||||||
|
final m = _matcher.seasonMatch(movie);
|
||||||
|
return _menuable(
|
||||||
|
movie.path,
|
||||||
|
PosterCard(
|
||||||
|
key: ValueKey('moviecard:${movie.path}'),
|
||||||
|
title: m?.entry.title ?? (movie.parsed.year == null ? movie.title : '${movie.title} (${movie.parsed.year})'),
|
||||||
|
subtitle: [
|
||||||
|
if (movie.movieNumber != null) movie.label,
|
||||||
|
if (m?.entry.year != null) '${m!.entry.year}' else if (movie.parsed.year != null) '${movie.parsed.year}',
|
||||||
|
formatSize(movie.file.size),
|
||||||
|
].join(' · '),
|
||||||
|
coverUrl: m?.entry.cover,
|
||||||
|
framePath: movie.path,
|
||||||
|
thumbs: _thumbs,
|
||||||
|
playing: _stateOf(movie.path) == PlayState.playing,
|
||||||
|
onShown: () => _matcher.wantMovie(movie),
|
||||||
|
onTap: _tapOf(movie.path),
|
||||||
|
));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A Recent entry: `Series · S01E03` over the file name, or the cleaned
|
/// A Recent entry: `Show · E02` over the file name (the library's names
|
||||||
/// title over its folder; greyed when the file is gone.
|
/// when it knows the show), or the cleaned title over its folder; greyed
|
||||||
|
/// when the file is gone.
|
||||||
class _RecentRow extends StatefulWidget {
|
class _RecentRow extends StatefulWidget {
|
||||||
final String path;
|
final String path;
|
||||||
|
final ShowMatcher matcher;
|
||||||
final PlayState state;
|
final PlayState state;
|
||||||
final ThumbCache thumbs;
|
final ThumbCache thumbs;
|
||||||
final VoidCallback? onTap;
|
final VoidCallback? onTap;
|
||||||
@@ -646,6 +870,7 @@ class _RecentRow extends StatefulWidget {
|
|||||||
const _RecentRow({
|
const _RecentRow({
|
||||||
super.key,
|
super.key,
|
||||||
required this.path,
|
required this.path,
|
||||||
|
required this.matcher,
|
||||||
required this.state,
|
required this.state,
|
||||||
required this.thumbs,
|
required this.thumbs,
|
||||||
required this.onTap,
|
required this.onTap,
|
||||||
@@ -657,12 +882,14 @@ class _RecentRow extends StatefulWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _RecentRowState extends State<_RecentRow> {
|
class _RecentRowState extends State<_RecentRow> {
|
||||||
|
FolderAccess get _folders => AppScope.of(context).ports.folders;
|
||||||
|
|
||||||
FileStat? _stat;
|
FileStat? _stat;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
File(widget.path).stat().then((s) {
|
_folders.stat(widget.path).then((s) {
|
||||||
if (mounted) setState(() => _stat = s);
|
if (mounted) setState(() => _stat = s);
|
||||||
}, onError: (Object _) {});
|
}, onError: (Object _) {});
|
||||||
}
|
}
|
||||||
@@ -670,12 +897,14 @@ class _RecentRowState extends State<_RecentRow> {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final path = widget.path;
|
final path = widget.path;
|
||||||
final p = parseReleaseName(baseName(path));
|
final e = widget.matcher.episodeAt(path) ??
|
||||||
|
readLocalFile(LocalFile(path, 0, DateTime.fromMillisecondsSinceEpoch(0)));
|
||||||
final missing = _stat?.type == FileSystemEntityType.notFound;
|
final missing = _stat?.type == FileSystemEntityType.notFound;
|
||||||
final episode = p.episode != null || p.extra != null;
|
final episode = e.kind == LocalKind.episode || e.kind == LocalKind.extra;
|
||||||
|
final name = widget.matcher.seasonMatch(e)?.entry.title ?? e.title;
|
||||||
return FileRow(
|
return FileRow(
|
||||||
path: path,
|
path: path,
|
||||||
title: episode ? '${p.series} · ${p.label}' : cleanTitle(p),
|
title: episode ? '$name · ${e.label}' : (e.kind == LocalKind.other ? cleanTitle(e.parsed) : name),
|
||||||
subtitle: missing ? 'File not found' : (episode ? baseName(path) : parentName(path)),
|
subtitle: missing ? 'File not found' : (episode ? baseName(path) : parentName(path)),
|
||||||
size: _stat == null || missing ? null : formatSize(_stat!.size),
|
size: _stat == null || missing ? null : formatSize(_stat!.size),
|
||||||
state: widget.state,
|
state: widget.state,
|
||||||
|
|||||||
@@ -0,0 +1,712 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/rendering.dart';
|
||||||
|
import 'package:signals/signals_flutter.dart';
|
||||||
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
|
import '../../library/show_matcher.dart';
|
||||||
|
import '../../schedule/anilist.dart' show AniListEntry;
|
||||||
|
import '../../shell/avatar.dart' show Pill;
|
||||||
|
import 'file_tiles.dart';
|
||||||
|
import 'thumb.dart';
|
||||||
|
|
||||||
|
// The Files library: shows and movies as poster cards (like the Jellyfin
|
||||||
|
// browser's), a show's own page (banner, the next episode with what is
|
||||||
|
// missing on the way, seasons, extras, movies) and the corrections
|
||||||
|
// ("Wrong show?", "Episode numbers…"). Names and art come from the
|
||||||
|
// library's AniList match when there is one, else from the files.
|
||||||
|
|
||||||
|
/// What the page hands its views: playing, the right-click menu, the
|
||||||
|
/// thumbnails, what plays now.
|
||||||
|
class FilesActions {
|
||||||
|
final void Function(String path) play;
|
||||||
|
final PlayState Function(String path) stateOf;
|
||||||
|
final Widget Function(String path, Widget child) menuable;
|
||||||
|
final ThumbCache thumbs;
|
||||||
|
const FilesActions({required this.play, required this.stateOf, required this.menuable, required this.thumbs});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "66–107 aren't in your folders", "66 isn't in your folders".
|
||||||
|
String missingText(EpisodeGap gap) =>
|
||||||
|
gap.first == gap.last ? '${gap.label} isn\'t in your folders' : '${gap.label} aren\'t in your folders';
|
||||||
|
|
||||||
|
/// The next-episode prompt: "66–107 aren't in your folders — skip to
|
||||||
|
/// 108?", or at the start "1–55 … — start at 56?"; null when nothing is
|
||||||
|
/// skipped.
|
||||||
|
String? skipPrompt(LocalNext next, {required bool started}) {
|
||||||
|
final gap = next.skipped;
|
||||||
|
if (gap == null) return null;
|
||||||
|
final n = next.episode.episode;
|
||||||
|
return started ? '${missingText(gap)} — skip to $n?' : '${missingText(gap)} — start at $n?';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A show's label for an episode: `56`, `S3 E1`.
|
||||||
|
String episodeNumber(LocalEpisode e) =>
|
||||||
|
e.season == null ? '${e.episode}' : 'S${e.season} E${e.episode}';
|
||||||
|
|
||||||
|
/// The 2:3 picture of a show or movie: its AniList cover, else a frame of
|
||||||
|
/// [framePath].
|
||||||
|
class PosterImage extends StatelessWidget {
|
||||||
|
final String? url;
|
||||||
|
final String? framePath;
|
||||||
|
final ThumbCache thumbs;
|
||||||
|
const PosterImage({super.key, this.url, this.framePath, required this.thumbs});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final frame = framePath == null
|
||||||
|
? const ThumbImage(null)
|
||||||
|
: ThumbBuilder(cache: thumbs, path: framePath!, builder: (context, t, _) => ThumbImage(t));
|
||||||
|
final u = url;
|
||||||
|
if (u == null) return frame;
|
||||||
|
return Image.network(
|
||||||
|
u,
|
||||||
|
fit: BoxFit.cover,
|
||||||
|
gaplessPlayback: true,
|
||||||
|
errorBuilder: (_, _, _) => frame,
|
||||||
|
loadingBuilder: (context, child, progress) => progress == null ? child : frame,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A show (or movie) as a poster card: picture, title, one line under it.
|
||||||
|
class PosterCard extends StatefulWidget {
|
||||||
|
final String title;
|
||||||
|
final String subtitle;
|
||||||
|
final String? coverUrl;
|
||||||
|
final String? framePath;
|
||||||
|
final ThumbCache thumbs;
|
||||||
|
final VoidCallback onTap;
|
||||||
|
final bool playing;
|
||||||
|
/// Called once when the card is first built (the library matches what
|
||||||
|
/// is on screen).
|
||||||
|
final VoidCallback? onShown;
|
||||||
|
const PosterCard({
|
||||||
|
super.key,
|
||||||
|
required this.title,
|
||||||
|
required this.subtitle,
|
||||||
|
required this.thumbs,
|
||||||
|
required this.onTap,
|
||||||
|
this.coverUrl,
|
||||||
|
this.framePath,
|
||||||
|
this.playing = false,
|
||||||
|
this.onShown,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<PosterCard> createState() => _PosterCardState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _PosterCardState extends State<PosterCard> {
|
||||||
|
bool _hover = false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
widget.onShown?.call();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final scheme = Theme.of(context).colorScheme;
|
||||||
|
final t = Theme.of(context).textTheme;
|
||||||
|
return InkWell(
|
||||||
|
onTap: widget.onTap,
|
||||||
|
onHover: (h) => setState(() => _hover = h),
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: AnimatedContainer(
|
||||||
|
duration: const Duration(milliseconds: 150),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
border: Border.all(
|
||||||
|
color: widget.playing ? scheme.primary : (_hover ? scheme.onSurfaceVariant : Colors.transparent),
|
||||||
|
width: 2,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: ClipRRect(
|
||||||
|
borderRadius: BorderRadius.circular(10),
|
||||||
|
child: PosterImage(url: widget.coverUrl, framePath: widget.framePath, thumbs: widget.thumbs),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 6),
|
||||||
|
Text(widget.title,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: t.titleSmall?.copyWith(color: widget.playing ? scheme.primary : null)),
|
||||||
|
Text(widget.subtitle,
|
||||||
|
maxLines: 1, overflow: TextOverflow.ellipsis, style: t.bodySmall?.copyWith(color: Colors.grey)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Title and meta lines under a [PosterCard]'s picture.
|
||||||
|
const posterTextHeight = 46.0;
|
||||||
|
|
||||||
|
/// Poster cards in a grid: about 170 px wide each.
|
||||||
|
SliverGridDelegate posterGrid() => const _PosterGrid();
|
||||||
|
|
||||||
|
class _PosterGrid extends SliverGridDelegate {
|
||||||
|
const _PosterGrid();
|
||||||
|
|
||||||
|
@override
|
||||||
|
SliverGridLayout getLayout(SliverConstraints constraints) {
|
||||||
|
const gap = 12.0;
|
||||||
|
final w = constraints.crossAxisExtent;
|
||||||
|
final cols = (w / 170).floor().clamp(2, 12);
|
||||||
|
final cardW = (w - gap * (cols - 1)) / cols;
|
||||||
|
return SliverGridRegularTileLayout(
|
||||||
|
crossAxisCount: cols,
|
||||||
|
mainAxisStride: cardW * 1.5 + posterTextHeight + gap,
|
||||||
|
crossAxisStride: cardW + gap,
|
||||||
|
childMainAxisExtent: cardW * 1.5 + posterTextHeight,
|
||||||
|
childCrossAxisExtent: cardW,
|
||||||
|
reverseCrossAxis: false,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool shouldRelayout(covariant SliverGridDelegate oldDelegate) => false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One show's page: header (banner, proper name, what the files are,
|
||||||
|
/// the match), the next episode with what is missing on the way, the
|
||||||
|
/// season's episodes with their holes, extras and the show's movies.
|
||||||
|
class ShowPage extends StatefulWidget {
|
||||||
|
final LocalShow show;
|
||||||
|
final ShowMatcher matcher;
|
||||||
|
final FilesActions actions;
|
||||||
|
/// The last episode of this show played here ([LocalEpisode.key]).
|
||||||
|
final String? lastPlayed;
|
||||||
|
final String backLabel;
|
||||||
|
final VoidCallback onBack;
|
||||||
|
/// Notices above the page (the relay notice, errors).
|
||||||
|
final List<Widget> top;
|
||||||
|
const ShowPage({
|
||||||
|
super.key,
|
||||||
|
required this.show,
|
||||||
|
required this.matcher,
|
||||||
|
required this.actions,
|
||||||
|
required this.lastPlayed,
|
||||||
|
required this.backLabel,
|
||||||
|
required this.onBack,
|
||||||
|
this.top = const [],
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<ShowPage> createState() => _ShowPageState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ShowPageState extends State<ShowPage> {
|
||||||
|
int? _season;
|
||||||
|
bool _seasonPicked = false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
widget.matcher.want(widget.show);
|
||||||
|
}
|
||||||
|
|
||||||
|
LocalShow get show => widget.show;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) => SignalBuilder(builder: (context) {
|
||||||
|
widget.matcher.revision.value;
|
||||||
|
final busy = widget.matcher.busy.value.contains(show.key);
|
||||||
|
final m = widget.matcher.showMatch(show);
|
||||||
|
final next = show.nextAfter(widget.lastPlayed);
|
||||||
|
final seasons = show.seasons;
|
||||||
|
if (!_seasonPicked) _season = next?.episode.season ?? seasons.firstOrNull?.number;
|
||||||
|
final season = show.season(_season) ?? seasons.firstOrNull;
|
||||||
|
return CustomScrollView(
|
||||||
|
key: PageStorageKey('show:${show.key}'),
|
||||||
|
slivers: [
|
||||||
|
SliverPadding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(12, 12, 20, 24),
|
||||||
|
sliver: SliverMainAxisGroup(slivers: [
|
||||||
|
SliverToBoxAdapter(
|
||||||
|
child: Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: TextButton.icon(
|
||||||
|
onPressed: widget.onBack,
|
||||||
|
icon: const Icon(Icons.arrow_back, size: 18),
|
||||||
|
label: Text(widget.backLabel),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SliverList.list(children: widget.top),
|
||||||
|
SliverToBoxAdapter(child: _header(context, m, next, busy)),
|
||||||
|
if (seasons.length > 1)
|
||||||
|
SliverToBoxAdapter(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 14),
|
||||||
|
child: Wrap(spacing: 8, runSpacing: 8, children: [
|
||||||
|
for (final s in seasons)
|
||||||
|
ChoiceChip(
|
||||||
|
key: ValueKey('season:${s.number}'),
|
||||||
|
label: Text(s.title),
|
||||||
|
selected: identical(s, season),
|
||||||
|
onSelected: (_) => setState(() {
|
||||||
|
_season = s.number;
|
||||||
|
_seasonPicked = true;
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (season != null) ..._episodes(context, season),
|
||||||
|
if (show.extras.isNotEmpty) ...[
|
||||||
|
_section(context, 'Extras', show.extras.length),
|
||||||
|
SliverList.list(children: [for (final e in show.extras) _row(e, e.label, e.name)]),
|
||||||
|
],
|
||||||
|
if (show.movies.isNotEmpty) ...[
|
||||||
|
_section(context, show.movies.length == 1 ? 'Movie' : 'Movies', show.movies.length),
|
||||||
|
SliverList.list(children: [for (final e in show.movies) _row(e, e.label, e.name)]),
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
Widget _section(BuildContext context, String title, int n) => SliverToBoxAdapter(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 22, bottom: 6),
|
||||||
|
child: Row(children: [
|
||||||
|
Text(title, style: Theme.of(context).textTheme.titleMedium),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Text('$n', style: Theme.of(context).textTheme.bodySmall?.copyWith(color: Colors.grey)),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
Widget _row(LocalEpisode e, String title, String subtitle) => widget.actions.menuable(
|
||||||
|
e.path,
|
||||||
|
FileRow(
|
||||||
|
key: ValueKey(e.path),
|
||||||
|
path: e.path,
|
||||||
|
title: title,
|
||||||
|
subtitle: subtitle,
|
||||||
|
size: formatSize(e.file.size),
|
||||||
|
state: widget.actions.stateOf(e.path),
|
||||||
|
thumbs: widget.actions.thumbs,
|
||||||
|
onTap: () => widget.actions.play(e.path),
|
||||||
|
));
|
||||||
|
|
||||||
|
List<Widget> _episodes(BuildContext context, LocalSeason season) {
|
||||||
|
final rows = <Widget>[];
|
||||||
|
var expect = 1;
|
||||||
|
for (final e in season.episodes) {
|
||||||
|
final n = e.episode!;
|
||||||
|
final gap = season.gaps.where((g) => g.first >= expect && g.last < n).firstOrNull;
|
||||||
|
if (gap != null) rows.add(_GapRow(missingText(gap)));
|
||||||
|
if (n >= expect) expect = n + 1;
|
||||||
|
final offset = widget.matcher.offset(show.key, season.number);
|
||||||
|
final shown = n + offset;
|
||||||
|
final name = widget.matcher.episodeTitle(e);
|
||||||
|
// Like the Jellyfin browser's rows: "12. Name", else "Episode 12".
|
||||||
|
final title = name == null ? 'Episode $shown' : '$shown. $name';
|
||||||
|
rows.add(_row(e, title, e.name));
|
||||||
|
}
|
||||||
|
final tail = season.gaps.where((g) => g.first >= expect).firstOrNull;
|
||||||
|
if (tail != null) rows.add(_GapRow(missingText(tail)));
|
||||||
|
return [
|
||||||
|
_section(context, season.title, season.distinct.length),
|
||||||
|
SliverList.list(children: rows),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _header(BuildContext context, SeasonMatch? m, LocalNext? next, bool busy) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final t = theme.textTheme;
|
||||||
|
final scheme = theme.colorScheme;
|
||||||
|
final entry = m?.entry;
|
||||||
|
final title = entry?.title ?? show.title;
|
||||||
|
final count = show.episodeCount;
|
||||||
|
final meta = [
|
||||||
|
if (show.seasons.length > 1) '${show.seasons.length} seasons',
|
||||||
|
'$count ${count == 1 ? 'episode' : 'episodes'}',
|
||||||
|
if (show.extras.isNotEmpty) '${show.extras.length} ${show.extras.length == 1 ? 'extra' : 'extras'}',
|
||||||
|
if (show.movies.isNotEmpty) '${show.movies.length} ${show.movies.length == 1 ? 'movie' : 'movies'}',
|
||||||
|
?show.group,
|
||||||
|
if (show.folders.length > 1) 'in ${show.folders.length} folders',
|
||||||
|
].join(' · ');
|
||||||
|
final String matchLine;
|
||||||
|
if (entry != null) {
|
||||||
|
final what = [
|
||||||
|
if (entry.format.isNotEmpty) entry.format.replaceAll('_', ' '),
|
||||||
|
if (entry.year != null) '${entry.year}',
|
||||||
|
if (entry.episodes != null) '${entry.episodes} eps',
|
||||||
|
].join(', ');
|
||||||
|
matchLine = [
|
||||||
|
'AniList: ${entry.romaji.isNotEmpty && entry.romaji != title ? entry.romaji : entry.title}'
|
||||||
|
'${what.isEmpty ? '' : ' ($what)'}',
|
||||||
|
if (title != show.title) 'files say "${show.title}"',
|
||||||
|
].join(' · ');
|
||||||
|
} else {
|
||||||
|
matchLine = busy ? 'Looking it up on AniList…' : 'Not matched on AniList';
|
||||||
|
}
|
||||||
|
final started = widget.lastPlayed != null;
|
||||||
|
final prompt = next == null ? null : skipPrompt(next, started: started);
|
||||||
|
final nextLabel = next == null
|
||||||
|
? 'Watched to the end'
|
||||||
|
: next.skipped != null
|
||||||
|
? (started ? 'Skip to ${next.episode.episode}' : 'Start at ${next.episode.episode}')
|
||||||
|
: '${started ? 'Next' : 'Play'}: ${episodeNumber(next.episode)}';
|
||||||
|
return LayoutBuilder(builder: (context, box) {
|
||||||
|
final h = (box.maxWidth * 0.28).clamp(220.0, 340.0);
|
||||||
|
final cover = entry?.cover;
|
||||||
|
return ClipRRect(
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
child: SizedBox(
|
||||||
|
height: h,
|
||||||
|
child: Stack(fit: StackFit.expand, children: [
|
||||||
|
PosterImage(
|
||||||
|
url: entry?.banner ?? entry?.cover,
|
||||||
|
framePath: show.episodes.firstOrNull?.path,
|
||||||
|
thumbs: widget.actions.thumbs),
|
||||||
|
DecoratedBox(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
gradient: LinearGradient(
|
||||||
|
begin: Alignment.centerLeft,
|
||||||
|
end: Alignment.centerRight,
|
||||||
|
colors: [
|
||||||
|
scheme.surface.withValues(alpha: 0.96),
|
||||||
|
scheme.surface.withValues(alpha: 0.8),
|
||||||
|
scheme.surface.withValues(alpha: 0.15),
|
||||||
|
],
|
||||||
|
stops: const [0, 0.5, 1],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.all(20),
|
||||||
|
child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||||
|
if (cover != null && box.maxWidth > 560) ...[
|
||||||
|
ClipRRect(
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
child: SizedBox(
|
||||||
|
width: (h - 40) / 1.5,
|
||||||
|
child: PosterImage(url: cover, thumbs: widget.actions.thumbs),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 18),
|
||||||
|
],
|
||||||
|
Expanded(
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||||
|
Row(children: [
|
||||||
|
Flexible(
|
||||||
|
child: Text(title,
|
||||||
|
maxLines: 2, overflow: TextOverflow.ellipsis, style: t.headlineMedium),
|
||||||
|
),
|
||||||
|
if (m?.pinned != null) ...[
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Pill(m!.pinned == PinScope.folder ? 'pinned for this folder' : 'pinned', scheme.primary),
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
const SizedBox(height: 6),
|
||||||
|
Text(meta, style: t.bodyMedium?.copyWith(color: Colors.grey)),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
Text(matchLine,
|
||||||
|
maxLines: 2,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: t.bodySmall?.copyWith(color: scheme.onSurfaceVariant)),
|
||||||
|
if (prompt != null) ...[
|
||||||
|
const SizedBox(height: 10),
|
||||||
|
Row(children: [
|
||||||
|
Icon(Icons.info_outline, size: 16, color: scheme.tertiary),
|
||||||
|
const SizedBox(width: 6),
|
||||||
|
Flexible(child: Text(prompt, style: t.bodyMedium?.copyWith(color: scheme.tertiary))),
|
||||||
|
]),
|
||||||
|
],
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
Wrap(spacing: 8, runSpacing: 8, children: [
|
||||||
|
FilledButton.icon(
|
||||||
|
key: const ValueKey('show-next'),
|
||||||
|
onPressed: next == null ? null : () => widget.actions.play(next.episode.path),
|
||||||
|
icon: const Icon(Icons.play_arrow),
|
||||||
|
label: Text(nextLabel),
|
||||||
|
),
|
||||||
|
OutlinedButton.icon(
|
||||||
|
onPressed: () => showWrongShowDialog(context, show, widget.matcher),
|
||||||
|
icon: const Icon(Icons.manage_search, size: 18),
|
||||||
|
label: const Text('Wrong show?'),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => showEpisodeNumbersDialog(context, show, widget.matcher),
|
||||||
|
child: const Text('Episode numbers…'),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _GapRow extends StatelessWidget {
|
||||||
|
final String text;
|
||||||
|
const _GapRow(this.text);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final scheme = Theme.of(context).colorScheme;
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(20, 6, 8, 6),
|
||||||
|
child: Row(children: [
|
||||||
|
Icon(Icons.more_vert, size: 18, color: scheme.onSurfaceVariant),
|
||||||
|
const SizedBox(width: 10),
|
||||||
|
Expanded(
|
||||||
|
child: Text(text,
|
||||||
|
maxLines: 2,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(color: scheme.onSurfaceVariant, fontStyle: FontStyle.italic, fontSize: 13)),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Wrong show?": search AniList, pick the right entry, pin it for the
|
||||||
|
/// show everywhere or for one of its folders.
|
||||||
|
Future<void> showWrongShowDialog(BuildContext context, LocalShow show, ShowMatcher matcher) =>
|
||||||
|
showDialog<void>(context: context, builder: (context) => WrongShowDialog(show: show, matcher: matcher));
|
||||||
|
|
||||||
|
class WrongShowDialog extends StatefulWidget {
|
||||||
|
final LocalShow show;
|
||||||
|
final ShowMatcher matcher;
|
||||||
|
const WrongShowDialog({super.key, required this.show, required this.matcher});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<WrongShowDialog> createState() => _WrongShowDialogState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _WrongShowDialogState extends State<WrongShowDialog> {
|
||||||
|
late final _query = TextEditingController(text: widget.show.title.replaceAll(RegExp(r'[._]+'), ' '));
|
||||||
|
List<AniListEntry>? _hits;
|
||||||
|
String? _error;
|
||||||
|
bool _searching = false;
|
||||||
|
/// Null: the whole show; else one of its folders.
|
||||||
|
String? _folder;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_search();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_query.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _search() async {
|
||||||
|
setState(() {
|
||||||
|
_searching = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final hits = await widget.matcher.search(_query.text);
|
||||||
|
if (mounted) setState(() => _hits = hits);
|
||||||
|
} catch (e) {
|
||||||
|
if (mounted) setState(() => _error = 'AniList did not answer ($e)');
|
||||||
|
} finally {
|
||||||
|
if (mounted) setState(() => _searching = false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _pin(AniListEntry e) {
|
||||||
|
final folder = _folder;
|
||||||
|
folder == null ? widget.matcher.pinShow(widget.show.key, e) : widget.matcher.pinFolder(folder, e);
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final show = widget.show;
|
||||||
|
final m = widget.matcher;
|
||||||
|
final showPin = m.showPin(show.key);
|
||||||
|
final folderPins = [for (final f in show.folders) if (m.folderPin(f)?.folder == f) f];
|
||||||
|
final scheme = Theme.of(context).colorScheme;
|
||||||
|
return AlertDialog(
|
||||||
|
title: const Text('Wrong show?'),
|
||||||
|
content: SizedBox(
|
||||||
|
width: 520,
|
||||||
|
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||||
|
Text('Search AniList and pick what "${show.title}" really is. '
|
||||||
|
'A pin wins over the automatic match and survives rescans.',
|
||||||
|
style: TextStyle(color: scheme.onSurfaceVariant)),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
TextField(
|
||||||
|
controller: _query,
|
||||||
|
autofocus: true,
|
||||||
|
decoration: InputDecoration(
|
||||||
|
isDense: true,
|
||||||
|
border: const OutlineInputBorder(),
|
||||||
|
hintText: 'Title on AniList',
|
||||||
|
suffixIcon: IconButton(tooltip: 'Search', icon: const Icon(Icons.search), onPressed: _search),
|
||||||
|
),
|
||||||
|
onSubmitted: (_) => _search(),
|
||||||
|
),
|
||||||
|
if (show.folders.length > 1 || folderPins.isNotEmpty) ...[
|
||||||
|
const SizedBox(height: 10),
|
||||||
|
DropdownButton<String?>(
|
||||||
|
value: _folder,
|
||||||
|
isExpanded: true,
|
||||||
|
items: [
|
||||||
|
const DropdownMenuItem(value: null, child: Text('For this show everywhere')),
|
||||||
|
for (final f in show.folders)
|
||||||
|
DropdownMenuItem(value: f, child: Text('Only the folder "${baseName(f)}"', overflow: TextOverflow.ellipsis)),
|
||||||
|
],
|
||||||
|
onChanged: (v) => setState(() => _folder = v),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
ConstrainedBox(
|
||||||
|
constraints: const BoxConstraints(maxHeight: 340),
|
||||||
|
child: _searching && _hits == null
|
||||||
|
? const Padding(padding: EdgeInsets.all(24), child: Center(child: CircularProgressIndicator()))
|
||||||
|
: _error != null
|
||||||
|
? Text(_error!, style: TextStyle(color: scheme.error))
|
||||||
|
: (_hits ?? const []).isEmpty
|
||||||
|
? const Padding(padding: EdgeInsets.all(12), child: Text('Nothing found'))
|
||||||
|
: ListView(shrinkWrap: true, children: [
|
||||||
|
for (final e in _hits!)
|
||||||
|
ListTile(
|
||||||
|
key: ValueKey('hit:${e.id}'),
|
||||||
|
dense: true,
|
||||||
|
leading: SizedBox(
|
||||||
|
width: 32,
|
||||||
|
height: 48,
|
||||||
|
child: ClipRRect(
|
||||||
|
borderRadius: BorderRadius.circular(4),
|
||||||
|
child: e.coverSmall == null
|
||||||
|
? const ColoredBox(color: Colors.black26)
|
||||||
|
: Image.network(e.coverSmall!,
|
||||||
|
fit: BoxFit.cover,
|
||||||
|
errorBuilder: (_, _, _) => const ColoredBox(color: Colors.black26)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
title: Text(e.title, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||||
|
subtitle: Text([
|
||||||
|
if (e.romaji.isNotEmpty && e.romaji != e.title) e.romaji,
|
||||||
|
if (e.format.isNotEmpty) e.format.replaceAll('_', ' '),
|
||||||
|
if (e.year != null) '${e.year}',
|
||||||
|
if (e.episodes != null) '${e.episodes} eps',
|
||||||
|
].join(' · '), maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||||
|
onTap: () => _pin(e),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
if (showPin != null)
|
||||||
|
TextButton(
|
||||||
|
onPressed: () {
|
||||||
|
m.unpinShow(show.key);
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
},
|
||||||
|
child: const Text('Remove the pin'),
|
||||||
|
),
|
||||||
|
for (final f in folderPins)
|
||||||
|
TextButton(
|
||||||
|
onPressed: () {
|
||||||
|
m.unpinFolder(f);
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
},
|
||||||
|
child: Text('Unpin "${baseName(f)}"'),
|
||||||
|
),
|
||||||
|
TextButton(onPressed: () => Navigator.of(context).pop(), child: const Text('Cancel')),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Episode numbers…": which episode the first file of each season is
|
||||||
|
/// ("these files are episodes N..M").
|
||||||
|
Future<void> showEpisodeNumbersDialog(BuildContext context, LocalShow show, ShowMatcher matcher) =>
|
||||||
|
showDialog<void>(context: context, builder: (context) => _EpisodeNumbersDialog(show: show, matcher: matcher));
|
||||||
|
|
||||||
|
class _EpisodeNumbersDialog extends StatefulWidget {
|
||||||
|
final LocalShow show;
|
||||||
|
final ShowMatcher matcher;
|
||||||
|
const _EpisodeNumbersDialog({required this.show, required this.matcher});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_EpisodeNumbersDialog> createState() => _EpisodeNumbersDialogState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _EpisodeNumbersDialogState extends State<_EpisodeNumbersDialog> {
|
||||||
|
late final _fields = {
|
||||||
|
for (final s in widget.show.seasons)
|
||||||
|
s.number: TextEditingController(
|
||||||
|
text: '${s.distinct.first.episode! + widget.matcher.offset(widget.show.key, s.number)}'),
|
||||||
|
};
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
for (final c in _fields.values) {
|
||||||
|
c.dispose();
|
||||||
|
}
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _save() {
|
||||||
|
for (final s in widget.show.seasons) {
|
||||||
|
final first = s.distinct.first.episode!;
|
||||||
|
final want = int.tryParse(_fields[s.number]!.text.trim());
|
||||||
|
if (want != null && want > 0) widget.matcher.setOffset(widget.show.key, s.number, want - first);
|
||||||
|
}
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) => AlertDialog(
|
||||||
|
title: const Text('Episode numbers'),
|
||||||
|
content: SizedBox(
|
||||||
|
width: 420,
|
||||||
|
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||||
|
const Text('When the files count differently from AniList, say which episode the first file is; '
|
||||||
|
'the others follow.'),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
for (final s in widget.show.seasons)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 8),
|
||||||
|
child: Row(children: [
|
||||||
|
Expanded(
|
||||||
|
child: Text('${s.title}: the file numbered ${s.distinct.first.episode} is episode',
|
||||||
|
maxLines: 2),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
SizedBox(
|
||||||
|
width: 72,
|
||||||
|
child: TextField(
|
||||||
|
key: ValueKey('offset:${s.number}'),
|
||||||
|
controller: _fields[s.number],
|
||||||
|
keyboardType: TextInputType.number,
|
||||||
|
decoration: const InputDecoration(isDense: true, border: OutlineInputBorder()),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(onPressed: () => Navigator.of(context).pop(), child: const Text('Cancel')),
|
||||||
|
FilledButton(onPressed: _save, child: const Text('Save')),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -194,6 +194,13 @@ class JellyfinAccounts extends ChangeNotifier {
|
|||||||
JellyfinAccount? account(String serverId) =>
|
JellyfinAccount? account(String serverId) =>
|
||||||
_accounts.where((a) => a.serverId == serverId).firstOrNull;
|
_accounts.where((a) => a.serverId == serverId).firstOrNull;
|
||||||
|
|
||||||
|
/// [itemId]'s page in the web UI of linked server [serverId] ("Open in
|
||||||
|
/// Jellyfin"); null when that server is not linked here.
|
||||||
|
String? webUrlOf(String serverId, String itemId) {
|
||||||
|
final a = account(serverId);
|
||||||
|
return a == null ? null : jellyfinWebUrl(a.baseUrl, itemId, serverId: serverId);
|
||||||
|
}
|
||||||
|
|
||||||
/// The chosen default, else the first linked server.
|
/// The chosen default, else the first linked server.
|
||||||
JellyfinAccount? get defaultAccount =>
|
JellyfinAccount? get defaultAccount =>
|
||||||
(_defaultServerId == null ? null : account(_defaultServerId!)) ?? _accounts.firstOrNull;
|
(_defaultServerId == null ? null : account(_defaultServerId!)) ?? _accounts.firstOrNull;
|
||||||
@@ -543,6 +550,17 @@ class JellyfinAccounts extends ChangeNotifier {
|
|||||||
/// Drops cached browse results (refresh button, after a pick).
|
/// Drops cached browse results (refresh button, after a pick).
|
||||||
void invalidate(String serverId) => _clearMemo(serverId);
|
void invalidate(String serverId) => _clearMemo(serverId);
|
||||||
|
|
||||||
|
final _watched = StreamController<String>.broadcast();
|
||||||
|
|
||||||
|
/// Server ids whose watched state this app just changed (a stop report):
|
||||||
|
/// their cached lists are gone, and browse views reload.
|
||||||
|
Stream<String> get watched => _watched.stream;
|
||||||
|
|
||||||
|
void watchedChanged(String serverId) {
|
||||||
|
_clearMemo(serverId);
|
||||||
|
_watched.add(serverId);
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
_disposed = true;
|
_disposed = true;
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import 'package:sync_relay_core/core.dart';
|
|||||||
|
|
||||||
import 'accounts.dart';
|
import 'accounts.dart';
|
||||||
import 'format.dart';
|
import 'format.dart';
|
||||||
|
import '../widgets/app_menu.dart';
|
||||||
|
import '../widgets/copy_open.dart';
|
||||||
|
|
||||||
/// One level of the library browser's back stack.
|
/// One level of the library browser's back stack.
|
||||||
sealed class BrowseRoute {
|
sealed class BrowseRoute {
|
||||||
@@ -156,7 +158,14 @@ class BrowseController extends ChangeNotifier {
|
|||||||
final JellyfinAccounts accounts;
|
final JellyfinAccounts accounts;
|
||||||
/// Clock for the Continue row's age cut-off (tests pin it).
|
/// Clock for the Continue row's age cut-off (tests pin it).
|
||||||
final DateTime Function() now;
|
final DateTime Function() now;
|
||||||
BrowseController(this.accounts, {this.now = DateTime.now});
|
BrowseController(this.accounts, {this.now = DateTime.now}) {
|
||||||
|
// Back from watching: the rows show what was just watched.
|
||||||
|
_watchedSub = accounts.watched.listen((id) {
|
||||||
|
if (!_disposed && id == serverId) dataChanged();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
late final StreamSubscription<String> _watchedSub;
|
||||||
|
|
||||||
String? _serverId;
|
String? _serverId;
|
||||||
List<BrowseRoute> _stack = const [HomeRoute()];
|
List<BrowseRoute> _stack = const [HomeRoute()];
|
||||||
@@ -258,10 +267,19 @@ class BrowseController extends ChangeNotifier {
|
|||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
_disposed = true;
|
_disposed = true;
|
||||||
|
unawaited(_watchedSub.cancel());
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// An item's title to copy: an episode with its series ("Show · Name").
|
||||||
|
String jellyfinCopyTitle(JellyfinItem item) {
|
||||||
|
final series = item.seriesName;
|
||||||
|
return item.kind == JellyfinItemKind.episode && series != null && series.isNotEmpty
|
||||||
|
? '$series · ${item.name}'
|
||||||
|
: item.name;
|
||||||
|
}
|
||||||
|
|
||||||
/// What every browser page needs, provided by [JellyfinBrowser].
|
/// What every browser page needs, provided by [JellyfinBrowser].
|
||||||
class BrowseScope extends InheritedWidget {
|
class BrowseScope extends InheritedWidget {
|
||||||
final JellyfinAccounts accounts;
|
final JellyfinAccounts accounts;
|
||||||
@@ -274,6 +292,9 @@ class BrowseScope extends InheritedWidget {
|
|||||||
final ValueChanged<JellyfinItem> onSelect;
|
final ValueChanged<JellyfinItem> onSelect;
|
||||||
/// Double-click: put it up (a series: its next episode).
|
/// Double-click: put it up (a series: its next episode).
|
||||||
final ValueChanged<JellyfinItem> onPutUp;
|
final ValueChanged<JellyfinItem> onPutUp;
|
||||||
|
/// Adds it to Up next (with next: right after what plays); null: no
|
||||||
|
/// server (the cards' menu then only copies and opens).
|
||||||
|
final void Function(JellyfinItem item, {bool next})? onAddToQueue;
|
||||||
/// Home shows the library chips itself (the Library tab has them in its
|
/// Home shows the library chips itself (the Library tab has them in its
|
||||||
/// header instead).
|
/// header instead).
|
||||||
final bool libraryStrip;
|
final bool libraryStrip;
|
||||||
@@ -287,6 +308,7 @@ class BrowseScope extends InheritedWidget {
|
|||||||
required this.selectedItemId,
|
required this.selectedItemId,
|
||||||
required this.onSelect,
|
required this.onSelect,
|
||||||
required this.onPutUp,
|
required this.onPutUp,
|
||||||
|
this.onAddToQueue,
|
||||||
this.libraryStrip = true,
|
this.libraryStrip = true,
|
||||||
required super.child,
|
required super.child,
|
||||||
});
|
});
|
||||||
@@ -296,6 +318,33 @@ class BrowseScope extends InheritedWidget {
|
|||||||
|
|
||||||
void onOpen(BrowseRoute route) => controller.open(route);
|
void onOpen(BrowseRoute route) => controller.open(route);
|
||||||
|
|
||||||
|
/// Right-click on a card ([context]: the card): Put it up, Add to queue,
|
||||||
|
/// Play next (playable, in a server), Copy title, Open in Jellyfin.
|
||||||
|
Future<void> cardMenu(BuildContext context, JellyfinItem item) async {
|
||||||
|
final queue = isSelectable(item) ? onAddToQueue : null;
|
||||||
|
final pick = await showAppMenu<int>(context, items: [
|
||||||
|
if (queue != null) ...const [
|
||||||
|
AppMenuItem(value: 0, label: 'Put it up'),
|
||||||
|
AppMenuItem(value: 1, label: 'Add to queue'),
|
||||||
|
AppMenuItem(value: 2, label: 'Play next'),
|
||||||
|
],
|
||||||
|
const AppMenuItem(value: 3, label: ReuseText.copyTitle),
|
||||||
|
const AppMenuItem(value: 4, label: ReuseText.openInJellyfin),
|
||||||
|
]);
|
||||||
|
switch (pick) {
|
||||||
|
case 0:
|
||||||
|
onPutUp(item);
|
||||||
|
case 1:
|
||||||
|
queue!(item);
|
||||||
|
case 2:
|
||||||
|
queue!(item, next: true);
|
||||||
|
case 3:
|
||||||
|
if (context.mounted) await copyToClipboard(context, jellyfinCopyTitle(item), done: 'Title copied');
|
||||||
|
case 4:
|
||||||
|
if (context.mounted) await openLink(context, jellyfinWebUrl(client.baseUrl, item.id, serverId: account.serverId));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Cached browse call on this server.
|
/// Cached browse call on this server.
|
||||||
Future<T> load<T>(String key, Future<T> Function(JellyfinClient c) fn) =>
|
Future<T> load<T>(String key, Future<T> Function(JellyfinClient c) fn) =>
|
||||||
accounts.cached(account.serverId, key, () => fn(client));
|
accounts.cached(account.serverId, key, () => fn(client));
|
||||||
|
|||||||
@@ -30,6 +30,8 @@ class JellyfinBrowser extends StatefulWidget {
|
|||||||
final JellyfinSelection? selected;
|
final JellyfinSelection? selected;
|
||||||
final ValueChanged<JellyfinSelection> onSelect;
|
final ValueChanged<JellyfinSelection> onSelect;
|
||||||
final ValueChanged<JellyfinSelection> onPutUp;
|
final ValueChanged<JellyfinSelection> onPutUp;
|
||||||
|
/// Right-click on a card: Add to queue / Play next; null: no server.
|
||||||
|
final void Function(JellyfinSelection item, {bool next})? onAddToQueue;
|
||||||
final VoidCallback? onOpenIntegrations;
|
final VoidCallback? onOpenIntegrations;
|
||||||
final Duration searchDebounce;
|
final Duration searchDebounce;
|
||||||
/// Opens here instead of the remembered location (the series of the
|
/// Opens here instead of the remembered location (the series of the
|
||||||
@@ -43,6 +45,7 @@ class JellyfinBrowser extends StatefulWidget {
|
|||||||
required this.accounts,
|
required this.accounts,
|
||||||
required this.onSelect,
|
required this.onSelect,
|
||||||
required this.onPutUp,
|
required this.onPutUp,
|
||||||
|
this.onAddToQueue,
|
||||||
this.controller,
|
this.controller,
|
||||||
this.selected,
|
this.selected,
|
||||||
this.onOpenIntegrations,
|
this.onOpenIntegrations,
|
||||||
@@ -221,6 +224,10 @@ class _JellyfinBrowserState extends State<JellyfinBrowser> {
|
|||||||
selectedItemId: sel != null && sel.serverId == account.serverId ? sel.itemId : null,
|
selectedItemId: sel != null && sel.serverId == account.serverId ? sel.itemId : null,
|
||||||
onSelect: (item) => widget.onSelect(JellyfinSelection(account.serverId, item.id, item)),
|
onSelect: (item) => widget.onSelect(JellyfinSelection(account.serverId, item.id, item)),
|
||||||
onPutUp: (item) => widget.onPutUp(JellyfinSelection(account.serverId, item.id, item)),
|
onPutUp: (item) => widget.onPutUp(JellyfinSelection(account.serverId, item.id, item)),
|
||||||
|
onAddToQueue: widget.onAddToQueue == null
|
||||||
|
? null
|
||||||
|
: (item, {next = false}) =>
|
||||||
|
widget.onAddToQueue!(JellyfinSelection(account.serverId, item.id, item), next: next),
|
||||||
libraryStrip: widget.libraryStrip,
|
libraryStrip: widget.libraryStrip,
|
||||||
child: Focus(
|
child: Focus(
|
||||||
onKeyEvent: _onKey,
|
onKeyEvent: _onKey,
|
||||||
|
|||||||
@@ -186,6 +186,7 @@ class _MediaCardState extends State<MediaCard> {
|
|||||||
focusColor: Colors.transparent,
|
focusColor: Colors.transparent,
|
||||||
hoverColor: Colors.transparent,
|
hoverColor: Colors.transparent,
|
||||||
onTap: () => _tap(scope),
|
onTap: () => _tap(scope),
|
||||||
|
onSecondaryTap: () => scope.cardMenu(context, item),
|
||||||
onHover: (h) => setState(() => _hover = h),
|
onHover: (h) => setState(() => _hover = h),
|
||||||
onFocusChange: (f) => setState(() => _focus = f),
|
onFocusChange: (f) => setState(() => _focus = f),
|
||||||
child: Column(
|
child: Column(
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import 'package:flutter/material.dart';
|
|||||||
import 'package:sync_relay_core/core.dart';
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
import '../shell/motion.dart';
|
import '../shell/motion.dart';
|
||||||
|
import '../widgets/app_menu.dart';
|
||||||
|
import '../widgets/copy_open.dart';
|
||||||
import 'accounts.dart';
|
import 'accounts.dart';
|
||||||
import 'browse_scope.dart';
|
import 'browse_scope.dart';
|
||||||
import 'cards.dart' show doubleClickTime, kindIcon;
|
import 'cards.dart' show doubleClickTime, kindIcon;
|
||||||
@@ -33,25 +35,29 @@ typedef _Data = ({
|
|||||||
|
|
||||||
/// The selected card's details, at the right of the library: banner,
|
/// The selected card's details, at the right of the library: banner,
|
||||||
/// title, meta, "Put it up · S1E3" ("Play · S1E3" when watching
|
/// title, meta, "Put it up · S1E3" ("Play · S1E3" when watching
|
||||||
/// [solo]), mark watched / unwatched, remove from Continue, overview and,
|
/// [alone]), mark watched / unwatched, remove from Continue, overview and,
|
||||||
/// for a series or an episode, the episode list (click picks which
|
/// for a series or an episode, the episode list (click picks which
|
||||||
/// episode goes up, double-click puts it up). Reloads when the
|
/// episode goes up, double-click puts it up). Reloads when the
|
||||||
/// [controller]'s data version moves.
|
/// [controller]'s data version moves.
|
||||||
class JellyfinDetailsPanel extends StatefulWidget {
|
class JellyfinDetailsPanel extends StatefulWidget {
|
||||||
final BrowseController controller;
|
final BrowseController controller;
|
||||||
final JellyfinSelection selection;
|
final JellyfinSelection selection;
|
||||||
/// Nobody else watches (offline or solo): the button says Play.
|
/// Nobody else is in the server: the button says Play.
|
||||||
final bool solo;
|
final bool alone;
|
||||||
/// Puts [item] (playable) up; returns an error text, or null when sent.
|
/// Puts [item] (playable) up; returns an error text, or null when sent.
|
||||||
final Future<String?> Function(JellyfinSelection item) onPutUp;
|
final Future<String?> Function(JellyfinSelection item) onPutUp;
|
||||||
|
/// Adds [item] to Up next (with next: right after what plays); null: no
|
||||||
|
/// server, no queue actions.
|
||||||
|
final Future<String?> Function(JellyfinSelection item, {bool next})? onAddToQueue;
|
||||||
final VoidCallback onClose;
|
final VoidCallback onClose;
|
||||||
const JellyfinDetailsPanel({
|
const JellyfinDetailsPanel({
|
||||||
super.key,
|
super.key,
|
||||||
required this.controller,
|
required this.controller,
|
||||||
required this.selection,
|
required this.selection,
|
||||||
required this.onPutUp,
|
required this.onPutUp,
|
||||||
|
this.onAddToQueue,
|
||||||
required this.onClose,
|
required this.onClose,
|
||||||
this.solo = false,
|
this.alone = false,
|
||||||
});
|
});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -122,6 +128,55 @@ class _JellyfinDetailsPanelState extends State<JellyfinDetailsPanel> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _queue(JellyfinItem target, {bool next = false}) async {
|
||||||
|
final add = widget.onAddToQueue;
|
||||||
|
if (add == null || _busy) return;
|
||||||
|
setState(() {
|
||||||
|
_busy = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
String? error;
|
||||||
|
try {
|
||||||
|
error = await add(JellyfinSelection(_serverId, target.id, target), next: next);
|
||||||
|
} catch (e) {
|
||||||
|
error = '$e';
|
||||||
|
}
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_busy = false;
|
||||||
|
_error = error;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Right-click on an episode ([context]: its row): Put it up, Add to
|
||||||
|
/// queue, Play next (in a server), Copy title, Open in Jellyfin.
|
||||||
|
Future<void> _episodeMenu(BuildContext context, JellyfinItem e) async {
|
||||||
|
final queue = widget.onAddToQueue != null;
|
||||||
|
if (queue) setState(() => _targetId = e.id);
|
||||||
|
final client = _client;
|
||||||
|
final pick = await showAppMenu<int>(context, items: [
|
||||||
|
if (queue) ...[
|
||||||
|
AppMenuItem(value: 0, label: widget.alone ? 'Play' : 'Put it up'),
|
||||||
|
const AppMenuItem(value: 1, label: 'Add to queue'),
|
||||||
|
const AppMenuItem(value: 2, label: 'Play next'),
|
||||||
|
],
|
||||||
|
const AppMenuItem(value: 3, label: ReuseText.copyTitle),
|
||||||
|
if (client != null) const AppMenuItem(value: 4, label: ReuseText.openInJellyfin),
|
||||||
|
]);
|
||||||
|
switch (pick) {
|
||||||
|
case 0:
|
||||||
|
await _putUp(e);
|
||||||
|
case 1:
|
||||||
|
await _queue(e);
|
||||||
|
case 2:
|
||||||
|
await _queue(e, next: true);
|
||||||
|
case 3:
|
||||||
|
if (context.mounted) await copyToClipboard(context, jellyfinCopyTitle(e), done: 'Title copied');
|
||||||
|
case 4:
|
||||||
|
if (context.mounted) await openLink(context, jellyfinWebUrl(client!.baseUrl, e.id, serverId: _serverId));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Runs a watched-state change, then lets every row reload.
|
/// Runs a watched-state change, then lets every row reload.
|
||||||
Future<void> _change(Future<void> Function(JellyfinClient c) action) async {
|
Future<void> _change(Future<void> Function(JellyfinClient c) action) async {
|
||||||
final c = _client;
|
final c = _client;
|
||||||
@@ -253,7 +308,7 @@ class _JellyfinDetailsPanelState extends State<JellyfinDetailsPanel> {
|
|||||||
if (shown.communityRating != null) '★ ${shown.communityRating!.toStringAsFixed(1)}',
|
if (shown.communityRating != null) '★ ${shown.communityRating!.toStringAsFixed(1)}',
|
||||||
if (!isSeries && shown.userData.played) 'Watched',
|
if (!isSeries && shown.userData.played) 'Watched',
|
||||||
].join(' · ');
|
].join(' · ');
|
||||||
final verb = widget.solo ? 'Play' : 'Put it up';
|
final verb = widget.alone ? 'Play' : 'Put it up';
|
||||||
final label = playable != null && isSeries ? '$verb · ${playable.episodeLabel ?? playable.name}' : verb;
|
final label = playable != null && isSeries ? '$verb · ${playable.episodeLabel ?? playable.name}' : verb;
|
||||||
final inContinue = playable != null &&
|
final inContinue = playable != null &&
|
||||||
(playable.userData.isResumable || _c.continueKeys.contains(continueKey(playable)));
|
(playable.userData.isResumable || _c.continueKeys.contains(continueKey(playable)));
|
||||||
@@ -307,6 +362,16 @@ class _JellyfinDetailsPanelState extends State<JellyfinDetailsPanel> {
|
|||||||
: const Icon(Icons.play_arrow),
|
: const Icon(Icons.play_arrow),
|
||||||
label: Text(label, overflow: TextOverflow.ellipsis),
|
label: Text(label, overflow: TextOverflow.ellipsis),
|
||||||
),
|
),
|
||||||
|
if (playable != null && widget.onAddToQueue != null)
|
||||||
|
GestureDetector(
|
||||||
|
onSecondaryTap: _busy ? null : () => _queue(playable, next: true),
|
||||||
|
child: IconButton(
|
||||||
|
key: const ValueKey('details-add-queue'),
|
||||||
|
onPressed: _busy ? null : () => _queue(playable),
|
||||||
|
tooltip: 'Add to queue (right-click: play next)',
|
||||||
|
icon: const Icon(Icons.playlist_add_rounded),
|
||||||
|
),
|
||||||
|
),
|
||||||
if (playable != null)
|
if (playable != null)
|
||||||
IconButton(
|
IconButton(
|
||||||
key: const ValueKey('details-watched'),
|
key: const ValueKey('details-watched'),
|
||||||
@@ -328,6 +393,13 @@ class _JellyfinDetailsPanelState extends State<JellyfinDetailsPanel> {
|
|||||||
onPressed: () => _c.open(SeriesRoute(d.series!, seasonId: seasonId)),
|
onPressed: () => _c.open(SeriesRoute(d.series!, seasonId: seasonId)),
|
||||||
icon: const Icon(Icons.open_in_new),
|
icon: const Icon(Icons.open_in_new),
|
||||||
),
|
),
|
||||||
|
if (client != null)
|
||||||
|
IconButton(
|
||||||
|
key: const ValueKey('details-open-jellyfin'),
|
||||||
|
tooltip: ReuseText.openInJellyfin,
|
||||||
|
onPressed: () => openLink(context, jellyfinWebUrl(client.baseUrl, shown.id, serverId: _serverId)),
|
||||||
|
icon: const Icon(Icons.open_in_browser_rounded),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
if (_error != null) ...[
|
if (_error != null) ...[
|
||||||
@@ -392,18 +464,14 @@ class _JellyfinDetailsPanelState extends State<JellyfinDetailsPanel> {
|
|||||||
children: [
|
children: [
|
||||||
const Expanded(child: Text('Episodes', style: TextStyle(fontWeight: FontWeight.w600))),
|
const Expanded(child: Text('Episodes', style: TextStyle(fontWeight: FontWeight.w600))),
|
||||||
if (seasons.length > 1)
|
if (seasons.length > 1)
|
||||||
DropdownButton<String>(
|
Flexible(
|
||||||
|
child: AppSelect<String?>(
|
||||||
key: const ValueKey('details-season'),
|
key: const ValueKey('details-season'),
|
||||||
value: seasonId,
|
value: seasonId,
|
||||||
isDense: true,
|
items: [for (final s in seasons) (s.id, s.name)],
|
||||||
underline: const SizedBox.shrink(),
|
|
||||||
borderRadius: BorderRadius.circular(10),
|
|
||||||
items: [
|
|
||||||
for (final s in seasons)
|
|
||||||
DropdownMenuItem(value: s.id, child: Text(s.name, overflow: TextOverflow.ellipsis)),
|
|
||||||
],
|
|
||||||
onChanged: (id) => setState(() => _seasonId = id),
|
onChanged: (id) => setState(() => _seasonId = id),
|
||||||
),
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -416,10 +484,12 @@ class _JellyfinDetailsPanelState extends State<JellyfinDetailsPanel> {
|
|||||||
return Material(
|
return Material(
|
||||||
color: isTarget ? scheme.primary.withValues(alpha: 0.10) : Colors.transparent,
|
color: isTarget ? scheme.primary.withValues(alpha: 0.10) : Colors.transparent,
|
||||||
borderRadius: BorderRadius.circular(8),
|
borderRadius: BorderRadius.circular(8),
|
||||||
child: InkWell(
|
// The row's own context: its menu opens at the row.
|
||||||
|
child: Builder(builder: (context) => InkWell(
|
||||||
key: ValueKey('details-episode-${e.id}'),
|
key: ValueKey('details-episode-${e.id}'),
|
||||||
borderRadius: BorderRadius.circular(8),
|
borderRadius: BorderRadius.circular(8),
|
||||||
onTap: () => _tapEpisode(e),
|
onTap: () => _tapEpisode(e),
|
||||||
|
onSecondaryTap: () => _episodeMenu(context, e),
|
||||||
child: Padding(
|
child: Padding(
|
||||||
padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 4),
|
padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 4),
|
||||||
child: Row(
|
child: Row(
|
||||||
@@ -464,7 +534,7 @@ class _JellyfinDetailsPanelState extends State<JellyfinDetailsPanel> {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
)),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import 'package:sync_relay_core/core.dart';
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
|
import '../library/media_refs.dart';
|
||||||
import '../screens/home/picked_media.dart';
|
import '../screens/home/picked_media.dart';
|
||||||
import 'accounts.dart';
|
import 'accounts.dart';
|
||||||
|
|
||||||
@@ -89,5 +90,6 @@ JellyfinMedia pickFor(JellyfinAccount account, JellyfinItem item) {
|
|||||||
title: item.name,
|
title: item.name,
|
||||||
subtitle: subtitle,
|
subtitle: subtitle,
|
||||||
runtime: item.runTime,
|
runtime: item.runTime,
|
||||||
|
ref: jellyfinMediaRef(item),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,7 @@ import 'package:signals/signals_flutter.dart';
|
|||||||
import 'package:sync_relay_core/core.dart';
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
import '../state/settings.dart';
|
import '../state/settings.dart';
|
||||||
|
import '../widgets/app_menu.dart';
|
||||||
import 'browse_scope.dart';
|
import 'browse_scope.dart';
|
||||||
import 'cards.dart';
|
import 'cards.dart';
|
||||||
import 'home_rows.dart';
|
import 'home_rows.dart';
|
||||||
@@ -184,18 +185,18 @@ class _LatestRow extends StatelessWidget {
|
|||||||
onPressed: () => scope.onOpen(LibraryRoute(view, sort: 'added')),
|
onPressed: () => scope.onOpen(LibraryRoute(view, sort: 'added')),
|
||||||
child: const Text('Show all'),
|
child: const Text('Show all'),
|
||||||
),
|
),
|
||||||
PopupMenuButton<void>(
|
AppMenuButton<bool>(
|
||||||
key: ValueKey('latest-menu-${view.id}'),
|
key: ValueKey('latest-menu-${view.id}'),
|
||||||
tooltip: 'Row options',
|
tooltip: 'Row options',
|
||||||
icon: const Icon(Icons.more_vert, size: 18),
|
items: () => [
|
||||||
itemBuilder: (context) => [
|
AppMenuItem(
|
||||||
CheckedPopupMenuItem(
|
|
||||||
key: const ValueKey('hide-rereleases'),
|
key: const ValueKey('hide-rereleases'),
|
||||||
|
value: !hide,
|
||||||
checked: hide,
|
checked: hide,
|
||||||
onTap: () => AppSettings.instance.setHideReReleases(!hide),
|
label: 'Hide re-releases in Latest',
|
||||||
child: const Text('Hide re-releases in Latest'),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
onSelected: AppSettings.instance.setHideReReleases,
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ class JellyfinPickerSource extends StatefulWidget {
|
|||||||
final JellyfinSelection? selected;
|
final JellyfinSelection? selected;
|
||||||
final ValueChanged<JellyfinSelection> onSelect;
|
final ValueChanged<JellyfinSelection> onSelect;
|
||||||
final ValueChanged<JellyfinSelection> onPutUp;
|
final ValueChanged<JellyfinSelection> onPutUp;
|
||||||
|
final void Function(JellyfinSelection item, {bool next})? onAddToQueue;
|
||||||
final VoidCallback? onOpenIntegrations;
|
final VoidCallback? onOpenIntegrations;
|
||||||
final BrowseStart? start;
|
final BrowseStart? start;
|
||||||
final bool libraryStrip;
|
final bool libraryStrip;
|
||||||
@@ -25,6 +26,7 @@ class JellyfinPickerSource extends StatefulWidget {
|
|||||||
required this.accounts,
|
required this.accounts,
|
||||||
required this.onSelect,
|
required this.onSelect,
|
||||||
required this.onPutUp,
|
required this.onPutUp,
|
||||||
|
this.onAddToQueue,
|
||||||
this.controller,
|
this.controller,
|
||||||
this.selected,
|
this.selected,
|
||||||
this.onOpenIntegrations,
|
this.onOpenIntegrations,
|
||||||
@@ -61,6 +63,7 @@ class _JellyfinPickerSourceState extends State<JellyfinPickerSource> {
|
|||||||
selected: widget.selected,
|
selected: widget.selected,
|
||||||
onSelect: widget.onSelect,
|
onSelect: widget.onSelect,
|
||||||
onPutUp: widget.onPutUp,
|
onPutUp: widget.onPutUp,
|
||||||
|
onAddToQueue: widget.onAddToQueue,
|
||||||
onOpenIntegrations: widget.onOpenIntegrations,
|
onOpenIntegrations: widget.onOpenIntegrations,
|
||||||
start: widget.start,
|
start: widget.start,
|
||||||
libraryStrip: widget.libraryStrip,
|
libraryStrip: widget.libraryStrip,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
import 'dart:math' as math;
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:sync_relay_core/core.dart';
|
import 'package:sync_relay_core/core.dart';
|
||||||
@@ -24,6 +25,15 @@ class PlayerSnapshot {
|
|||||||
/// go out one after another; a failure is logged and handed to [onError]
|
/// go out one after another; a failure is logged and handed to [onError]
|
||||||
/// (the session shows one quiet toast) and never touches playback. A 401
|
/// (the session shows one quiet toast) and never touches playback. A 401
|
||||||
/// calls [onUnauthorized] and ends reporting.
|
/// calls [onUnauthorized] and ends reporting.
|
||||||
|
///
|
||||||
|
/// Watched or not is [WatchSession]'s rule (time In, D3), not Jellyfin's
|
||||||
|
/// position percentages (see ARCHITECTURE.md "Watch tracking"): the
|
||||||
|
/// session's watch tracker feeds [watch] and this reporter only reads its
|
||||||
|
/// verdict. An item played before ([playedBefore]) stays played
|
||||||
|
/// (re-marked after Playing, Progress without a position, Stopped without
|
||||||
|
/// one, then marked played again); otherwise Progress leaves the position
|
||||||
|
/// out past [_noPositionFrom] of the runtime so Jellyfin cannot mark it
|
||||||
|
/// played on its own, and Stopped carries what the rule says.
|
||||||
class JellyfinProgressReporter {
|
class JellyfinProgressReporter {
|
||||||
final JellyfinClient client;
|
final JellyfinClient client;
|
||||||
final String itemId;
|
final String itemId;
|
||||||
@@ -34,20 +44,44 @@ class JellyfinProgressReporter {
|
|||||||
final void Function(Object error)? onError;
|
final void Function(Object error)? onError;
|
||||||
final VoidCallback? onUnauthorized;
|
final VoidCallback? onUnauthorized;
|
||||||
|
|
||||||
|
/// What this viewer watched of the item while it was open here (fed by
|
||||||
|
/// the watch tracker, not by this reporter).
|
||||||
|
final WatchSession watch;
|
||||||
|
|
||||||
JellyfinProgressReporter({
|
JellyfinProgressReporter({
|
||||||
required this.client,
|
required this.client,
|
||||||
required this.itemId,
|
required this.itemId,
|
||||||
required this.source,
|
required this.source,
|
||||||
required this.playSessionId,
|
required this.playSessionId,
|
||||||
|
bool playedBefore = false,
|
||||||
|
int resumeTicksBefore = 0,
|
||||||
this.interval = const Duration(seconds: 10),
|
this.interval = const Duration(seconds: 10),
|
||||||
this.onError,
|
this.onError,
|
||||||
this.onUnauthorized,
|
this.onUnauthorized,
|
||||||
|
this.onStopped,
|
||||||
|
WatchSession? watch,
|
||||||
DateTime Function()? clock,
|
DateTime Function()? clock,
|
||||||
}) : _clock = clock ?? DateTime.now;
|
}) : _clock = clock ?? DateTime.now,
|
||||||
|
_keepPlayed = playedBefore,
|
||||||
|
_runtime = (source.runTimeTicks ?? 0) / jellyfinTicksPerSecond,
|
||||||
|
watch = (watch ?? WatchSession())
|
||||||
|
..playedBefore = playedBefore
|
||||||
|
..resumeBefore = resumeTicksBefore / jellyfinTicksPerSecond;
|
||||||
|
|
||||||
|
/// Past this share of the runtime Progress carries no position: Jellyfin
|
||||||
|
/// marks an item played past its "max resume" share (90 % by default).
|
||||||
|
static const _noPositionFrom = 0.85;
|
||||||
|
|
||||||
|
/// After Stopped (and a mark played) went out: the item's watched
|
||||||
|
/// state on the server may differ from what lists show.
|
||||||
|
final void Function()? onStopped;
|
||||||
|
|
||||||
Future<void> _chain = Future.value();
|
Future<void> _chain = Future.value();
|
||||||
bool _playing = false;
|
bool _playing = false;
|
||||||
bool _dead = false;
|
bool _dead = false;
|
||||||
|
bool _keepPlayed;
|
||||||
|
double _runtime;
|
||||||
|
double? _endingStart;
|
||||||
PlayerSnapshot? _last;
|
PlayerSnapshot? _last;
|
||||||
DateTime? _lastAt;
|
DateTime? _lastAt;
|
||||||
DateTime? _lastSentAt;
|
DateTime? _lastSentAt;
|
||||||
@@ -55,13 +89,23 @@ class JellyfinProgressReporter {
|
|||||||
/// Between [start] and [stop].
|
/// Between [start] and [stop].
|
||||||
bool get active => _playing && !_dead;
|
bool get active => _playing && !_dead;
|
||||||
|
|
||||||
|
/// The item counts as played here (before, or by the rule at a stop).
|
||||||
|
bool get keepsPlayed => _keepPlayed;
|
||||||
|
|
||||||
|
/// The player's duration (used when Jellyfin gave no runtime) and where
|
||||||
|
/// the ending starts (Outro segment / ED chapter), seconds.
|
||||||
|
void timeline({double duration = 0, double? endingStart}) {
|
||||||
|
if ((source.runTimeTicks ?? 0) <= 0 && duration > 0) _runtime = duration;
|
||||||
|
_endingStart = endingStart;
|
||||||
|
}
|
||||||
|
|
||||||
/// The report body for [s]: ticks, pause, and mpv's aid/sid mapped to
|
/// The report body for [s]: ticks, pause, and mpv's aid/sid mapped to
|
||||||
/// Jellyfin stream indices (-1 = subtitles off).
|
/// Jellyfin stream indices (-1 = subtitles off).
|
||||||
JellyfinPlaybackReport reportFor(PlayerSnapshot s) => JellyfinPlaybackReport(
|
JellyfinPlaybackReport reportFor(PlayerSnapshot s, {bool withPosition = true}) => JellyfinPlaybackReport(
|
||||||
itemId: itemId,
|
itemId: itemId,
|
||||||
mediaSourceId: source.id,
|
mediaSourceId: source.id,
|
||||||
playSessionId: playSessionId,
|
playSessionId: playSessionId,
|
||||||
positionTicks: (s.position * jellyfinTicksPerSecond).round(),
|
positionTicks: withPosition ? _ticks(s.position) : null,
|
||||||
isPaused: s.paused,
|
isPaused: s.paused,
|
||||||
audioStreamIndex: s.aid == null
|
audioStreamIndex: s.aid == null
|
||||||
? null
|
? null
|
||||||
@@ -71,13 +115,23 @@ class JellyfinProgressReporter {
|
|||||||
: source.jellyfinIndexForMpvTrack(JellyfinStreamType.subtitle, s.sid!),
|
: source.jellyfinIndexForMpvTrack(JellyfinStreamType.subtitle, s.sid!),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
static int _ticks(double secs) => (secs * jellyfinTicksPerSecond).round();
|
||||||
|
|
||||||
|
/// Progress may carry the position: not for a played item, not without
|
||||||
|
/// a runtime and not near the end (either would let Jellyfin decide).
|
||||||
|
bool _progressPosition(double position) =>
|
||||||
|
!_keepPlayed && _runtime > 0 && position < _noPositionFrom * _runtime;
|
||||||
|
|
||||||
/// Playing: once the media is open. Again after [stop] (played to the
|
/// Playing: once the media is open. Again after [stop] (played to the
|
||||||
/// end, then someone seeked back) starts reporting anew.
|
/// end, then someone seeked back) starts reporting anew. A played item
|
||||||
|
/// is marked played again right after (Jellyfin up to 10.11 clears it
|
||||||
|
/// on Playing).
|
||||||
void start(PlayerSnapshot s) {
|
void start(PlayerSnapshot s) {
|
||||||
if (_playing || _dead) return;
|
if (_playing || _dead) return;
|
||||||
_playing = true;
|
_playing = true;
|
||||||
_mark(s);
|
_mark(s);
|
||||||
_send('Playing', () => client.reportPlaybackStart(reportFor(s)));
|
_send('Playing', () => client.reportPlaybackStart(reportFor(s)));
|
||||||
|
if (_keepPlayed) _send('played', () => client.markPlayed(itemId));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Progress when due (see the class doc).
|
/// Progress when due (see the class doc).
|
||||||
@@ -99,16 +153,43 @@ class JellyfinProgressReporter {
|
|||||||
_lastAt = now;
|
_lastAt = now;
|
||||||
if (!due) return;
|
if (!due) return;
|
||||||
_lastSentAt = now;
|
_lastSentAt = now;
|
||||||
_send('Progress', () => client.reportPlaybackProgress(reportFor(s)));
|
final report = reportFor(s, withPosition: _progressPosition(s.position));
|
||||||
|
_send('Progress', () => client.reportPlaybackProgress(report));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stopped (swap, leave, kick, window close, played to the end).
|
/// Stopped (swap, leave, kick, window close, played to the end), as
|
||||||
|
/// [WatchSession.verdict] says: played (or kept played) -> no position,
|
||||||
|
/// then marked played; a peek -> the resume point from before; part way
|
||||||
|
/// -> the position, held under [_noPositionFrom] of the runtime.
|
||||||
/// Completes when it and everything before it went out.
|
/// Completes when it and everything before it went out.
|
||||||
Future<void> stop(PlayerSnapshot s) {
|
Future<void> stop(PlayerSnapshot s) {
|
||||||
if (!_playing || _dead) return _chain;
|
if (!_playing || _dead) return _chain;
|
||||||
_playing = false;
|
_playing = false;
|
||||||
_send('Stopped', () => client.reportPlaybackStopped(reportFor(s)));
|
final v = _keepPlayed
|
||||||
return _chain;
|
? const WatchVerdict(WatchOutcome.keepPlayed)
|
||||||
|
: watch.verdict(runtime: _runtime, endingStart: _endingStart);
|
||||||
|
debugPrint('jellyfin $itemId: $v (${watch.credited.round()} s In of ${_runtime.round()} s)');
|
||||||
|
final int? ticks;
|
||||||
|
switch (v.outcome) {
|
||||||
|
case WatchOutcome.played || WatchOutcome.keepPlayed:
|
||||||
|
_keepPlayed = true;
|
||||||
|
ticks = null;
|
||||||
|
case WatchOutcome.peek:
|
||||||
|
ticks = _ticks(watch.resumeBefore);
|
||||||
|
case WatchOutcome.partial:
|
||||||
|
final at = v.resumeAt ?? s.position;
|
||||||
|
ticks = _ticks(_runtime > 0 ? math.min(at, _noPositionFrom * _runtime) : at);
|
||||||
|
}
|
||||||
|
final report = JellyfinPlaybackReport(
|
||||||
|
itemId: itemId, mediaSourceId: source.id, playSessionId: playSessionId, positionTicks: ticks);
|
||||||
|
_send('Stopped', () => client.reportPlaybackStopped(report));
|
||||||
|
if (ticks == null) {
|
||||||
|
_send('played', () => client.markPlayed(itemId));
|
||||||
|
// Marking played keeps a resume point Progress left (Continue would
|
||||||
|
// still list it, "3 min left"): clear it.
|
||||||
|
_send('resume cleared', () => client.clearResumePosition(itemId));
|
||||||
|
}
|
||||||
|
return _chain = _chain.then((_) => onStopped?.call());
|
||||||
}
|
}
|
||||||
|
|
||||||
void _mark(PlayerSnapshot s) {
|
void _mark(PlayerSnapshot s) {
|
||||||
|
|||||||
@@ -375,6 +375,7 @@ class _EpisodeTileState extends State<EpisodeTile> {
|
|||||||
key: ValueKey('episode-${e.id}'),
|
key: ValueKey('episode-${e.id}'),
|
||||||
focusColor: Colors.transparent,
|
focusColor: Colors.transparent,
|
||||||
onTap: () => _tap(scope),
|
onTap: () => _tap(scope),
|
||||||
|
onSecondaryTap: () => scope.cardMenu(context, widget.episode),
|
||||||
onHover: (h) => setState(() => _hover = h),
|
onHover: (h) => setState(() => _hover = h),
|
||||||
onFocusChange: (f) => setState(() => _focus = f),
|
onFocusChange: (f) => setState(() => _focus = f),
|
||||||
child: Padding(
|
child: Padding(
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import 'package:sync_relay_core/core.dart';
|
|||||||
import '../screens/home/picked_media.dart';
|
import '../screens/home/picked_media.dart';
|
||||||
import 'accounts.dart';
|
import 'accounts.dart';
|
||||||
import 'format.dart';
|
import 'format.dart';
|
||||||
|
import '../library/media_refs.dart';
|
||||||
|
|
||||||
// Jellyfin media in a session: turning picks and pasted links into refs
|
// Jellyfin media in a session: turning picks and pasted links into refs
|
||||||
// (the wire carries only `{serverId, itemId, ...}`), the hosted server's
|
// (the wire carries only `{serverId, itemId, ...}`), the hosted server's
|
||||||
@@ -27,7 +28,8 @@ HelloMedia mediaForPick(JellyfinMedia m) => HelloMedia(
|
|||||||
name: m.title.isEmpty ? 'Jellyfin item' : m.title,
|
name: m.title.isEmpty ? 'Jellyfin item' : m.title,
|
||||||
size: 0,
|
size: 0,
|
||||||
duration: 0,
|
duration: 0,
|
||||||
jellyfin: refForPick(m));
|
jellyfin: refForPick(m),
|
||||||
|
ref: m.ref ?? jellyfinPickRef(m.title, m.subtitle));
|
||||||
|
|
||||||
/// The pick a ref stands for on a linked server (for highlighting it in
|
/// The pick a ref stands for on a linked server (for highlighting it in
|
||||||
/// the browser); null when this install has no account there.
|
/// the browser); null when this install has no account there.
|
||||||
@@ -77,7 +79,8 @@ final _sourceId = RegExp(r'^[A-Za-z0-9-]{1,64}$');
|
|||||||
/// is one.
|
/// is one.
|
||||||
Future<HelloMedia> mediaForLink(JellyfinAccounts accounts, String url,
|
Future<HelloMedia> mediaForLink(JellyfinAccounts accounts, String url,
|
||||||
{Duration timeout = const Duration(seconds: 6)}) async {
|
{Duration timeout = const Duration(seconds: 6)}) async {
|
||||||
final plain = HelloMedia(name: linkName(url), size: 0, duration: 0, url: url);
|
final name = linkName(url);
|
||||||
|
final plain = HelloMedia(name: name, size: 0, duration: 0, url: url, ref: linkMediaRef(name));
|
||||||
final link = parseJellyfinLink(url);
|
final link = parseJellyfinLink(url);
|
||||||
if (link == null) return plain;
|
if (link == null) return plain;
|
||||||
await accounts.ensureLoaded();
|
await accounts.ensureLoaded();
|
||||||
@@ -102,9 +105,11 @@ Future<HelloMedia> mediaForLink(JellyfinAccounts accounts, String url,
|
|||||||
);
|
);
|
||||||
final account = accounts.account(serverId);
|
final account = accounts.account(serverId);
|
||||||
final client = accounts.clientFor(serverId);
|
final client = accounts.clientFor(serverId);
|
||||||
|
MediaRef? what;
|
||||||
if (account != null && client != null) {
|
if (account != null && client != null) {
|
||||||
try {
|
try {
|
||||||
final pick = pickFor(account, await client.item(link.itemId).timeout(timeout));
|
final pick = pickFor(account, await client.item(link.itemId).timeout(timeout));
|
||||||
|
what = pick.ref;
|
||||||
ref = refForPick(JellyfinMedia(
|
ref = refForPick(JellyfinMedia(
|
||||||
serverId: serverId,
|
serverId: serverId,
|
||||||
baseUrl: account.baseUrl,
|
baseUrl: account.baseUrl,
|
||||||
@@ -119,7 +124,11 @@ Future<HelloMedia> mediaForLink(JellyfinAccounts accounts, String url,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
return HelloMedia(
|
return HelloMedia(
|
||||||
name: ref.title.isEmpty ? 'Jellyfin item' : ref.title, size: 0, duration: 0, jellyfin: ref);
|
name: ref.title.isEmpty ? 'Jellyfin item' : ref.title,
|
||||||
|
size: 0,
|
||||||
|
duration: 0,
|
||||||
|
jellyfin: ref,
|
||||||
|
ref: what ?? jellyfinPickRef(ref.title, ref.subtitle ?? ''));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Display name for a link: last path segment, decoded, never the query
|
/// Display name for a link: last path segment, decoded, never the query
|
||||||
@@ -138,27 +147,28 @@ String linkName(String url) {
|
|||||||
return uri.host.isNotEmpty ? uri.host : 'link';
|
return uri.host.isNotEmpty ? uri.host : 'link';
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The hosted server's relay login: the account for [serverId] (the
|
/// The hosted server's relay logins: one per linked Jellyfin account
|
||||||
/// hosted item's server), else the default account, when its token is not
|
/// whose token is not known to be expired (the default account first),
|
||||||
/// known to be expired. The device fields are exactly the ones this app
|
/// so `/j` relays an item with its own server's login. The device fields
|
||||||
/// sends with that token ([JellyfinAccounts.clientInfo]): Jellyfin rewrites
|
/// are exactly the ones this app sends with those tokens
|
||||||
/// a token's device from the request header, so the relay must not differ.
|
/// ([JellyfinAccounts.clientInfo]): Jellyfin rewrites a token's device
|
||||||
JellyfinCredential? relayCredentialFor(JellyfinAccounts accounts, {String? serverId}) {
|
/// from the request header, so the relay must not differ.
|
||||||
bool usable(JellyfinAccount? a) =>
|
List<JellyfinCredential> relayCredentialsFor(JellyfinAccounts accounts) {
|
||||||
a != null && accounts.statusOf(a.serverId) != JellyfinAccountStatus.expired;
|
|
||||||
var a = serverId == null ? null : accounts.account(serverId);
|
|
||||||
if (!usable(a)) a = accounts.defaultAccount;
|
|
||||||
if (!usable(a)) return null;
|
|
||||||
final info = accounts.clientInfo;
|
final info = accounts.clientInfo;
|
||||||
return JellyfinCredential(
|
final first = accounts.defaultAccount;
|
||||||
baseUrl: a!.baseUrl,
|
return [
|
||||||
|
for (final a in [?first, ...accounts.accounts.where((a) => a.serverId != first?.serverId)])
|
||||||
|
if (accounts.statusOf(a.serverId) != JellyfinAccountStatus.expired)
|
||||||
|
JellyfinCredential(
|
||||||
|
baseUrl: a.baseUrl,
|
||||||
serverId: a.serverId,
|
serverId: a.serverId,
|
||||||
token: a.token,
|
token: a.token,
|
||||||
client: info.client,
|
client: info.client,
|
||||||
device: info.device,
|
device: info.device,
|
||||||
deviceId: info.deviceId,
|
deviceId: info.deviceId,
|
||||||
version: info.version,
|
version: info.version,
|
||||||
);
|
),
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `/j/...` URL of the current Jellyfin media on the host this client
|
/// `/j/...` URL of the current Jellyfin media on the host this client
|
||||||
@@ -318,10 +328,11 @@ Future<({EpisodeLink? previous, EpisodeLink? next})> findAdjacentEpisodes(OwnPla
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// When the floating "Next episode" pill appears: at [endingStart] (the
|
/// Where the "Next episode" pill's window starts: at [endingStart] (the
|
||||||
/// ED: Jellyfin Outro segment or ED-titled chapter, see `endingRange`)
|
/// ED: Jellyfin Outro segment or ED-titled chapter, see `endingRange`)
|
||||||
/// when one is known inside [runtime], else the last two minutes of
|
/// when one is known inside [runtime], else the last two minutes of
|
||||||
/// [runtime] (all of it for shorter media).
|
/// [runtime] (all of it for shorter media). The pill shows only while the
|
||||||
|
/// controls are up (`PillGate`), so a guessed window costs nothing.
|
||||||
Duration nextPromptStart(JellyfinItem? item, Duration runtime, {Duration? endingStart}) {
|
Duration nextPromptStart(JellyfinItem? item, Duration runtime, {Duration? endingStart}) {
|
||||||
if (endingStart != null && endingStart > Duration.zero && endingStart < runtime) {
|
if (endingStart != null && endingStart > Duration.zero && endingStart < runtime) {
|
||||||
return endingStart;
|
return endingStart;
|
||||||
@@ -329,26 +340,3 @@ Duration nextPromptStart(JellyfinItem? item, Duration runtime, {Duration? ending
|
|||||||
const lead = Duration(minutes: 2);
|
const lead = Duration(minutes: 2);
|
||||||
return runtime > lead ? runtime - lead : Duration.zero;
|
return runtime > lead ? runtime - lead : Duration.zero;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Who performs the auto-advance swap, so several counting clients do not
|
|
||||||
/// swap twice: the lowest member id among members that play the item with
|
|
||||||
/// their own account (`jf[serverId] == true`, not stale, not out). Only what every
|
|
||||||
/// client sees in `state` decides (who put the item up is not in it: a
|
|
||||||
/// late joiner never saw that swap), so all clients agree.
|
|
||||||
String? autoAdvanceSwapper(List<MemberView> members, String serverId) {
|
|
||||||
final eligible = [
|
|
||||||
for (final m in members)
|
|
||||||
if (!m.stale && !m.out && m.jf[serverId] == true) m
|
|
||||||
];
|
|
||||||
if (eligible.isEmpty) return null;
|
|
||||||
eligible.sort((a, b) => compareMemberIds(a.id, b.id));
|
|
||||||
return eligible.first.id;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// "m2" before "m10": numeric suffix order, then plain text.
|
|
||||||
int compareMemberIds(String a, String b) {
|
|
||||||
final na = int.tryParse(a.replaceFirst(RegExp(r'^\D+'), ''));
|
|
||||||
final nb = int.tryParse(b.replaceFirst(RegExp(r'^\D+'), ''));
|
|
||||||
if (na != null && nb != null && na != nb) return na.compareTo(nb);
|
|
||||||
return a.compareTo(b);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:hive_ce/hive.dart';
|
||||||
|
|
||||||
|
// Where the library's matches live (device-owned, one Hive box): AniList
|
||||||
|
// entries seen, automatic matches, the user's pins and episode offsets.
|
||||||
|
// Plain JSON-ish values under string keys; reads are synchronous once
|
||||||
|
// loaded, writes go through.
|
||||||
|
|
||||||
|
const libraryBoxName = 'library';
|
||||||
|
|
||||||
|
abstract interface class LibraryStore {
|
||||||
|
/// Loads the stored values (once).
|
||||||
|
Future<void> ensureLoaded();
|
||||||
|
Object? get(String key);
|
||||||
|
void put(String key, Object value);
|
||||||
|
void delete(String key);
|
||||||
|
|
||||||
|
/// Every key starting with [prefix].
|
||||||
|
Iterable<String> keys(String prefix);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For tests and as the fallback when Hive is not available.
|
||||||
|
class MemoryLibraryStore implements LibraryStore {
|
||||||
|
final Map<String, Object> values;
|
||||||
|
MemoryLibraryStore([Map<String, Object>? values]) : values = values ?? {};
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> ensureLoaded() async {}
|
||||||
|
@override
|
||||||
|
Object? get(String key) => values[key];
|
||||||
|
@override
|
||||||
|
void put(String key, Object value) => values[key] = value;
|
||||||
|
@override
|
||||||
|
void delete(String key) => values.remove(key);
|
||||||
|
@override
|
||||||
|
Iterable<String> keys(String prefix) => values.keys.where((k) => k.startsWith(prefix)).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `library` box; until it opens (or when it cannot) it acts as an
|
||||||
|
/// empty memory store, so matching still works for the run.
|
||||||
|
class HiveLibraryStore implements LibraryStore {
|
||||||
|
Box? _box;
|
||||||
|
final _memory = MemoryLibraryStore();
|
||||||
|
Future<void>? _load;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> ensureLoaded() => _load ??= () async {
|
||||||
|
try {
|
||||||
|
final box = _box = await Hive.openBox(libraryBoxName);
|
||||||
|
// Writes made before the box opened.
|
||||||
|
for (final e in _memory.values.entries) {
|
||||||
|
await box.put(e.key, e.value);
|
||||||
|
}
|
||||||
|
_memory.values.clear();
|
||||||
|
} catch (e, st) {
|
||||||
|
debugPrint('open library store failed: $e\n$st');
|
||||||
|
}
|
||||||
|
}();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Object? get(String key) => _box?.get(key) ?? _memory.get(key);
|
||||||
|
|
||||||
|
@override
|
||||||
|
void put(String key, Object value) {
|
||||||
|
final box = _box;
|
||||||
|
if (box == null) return _memory.put(key, value);
|
||||||
|
box.put(key, value).catchError((Object e) => debugPrint('library store put $key: $e'));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void delete(String key) {
|
||||||
|
_memory.delete(key);
|
||||||
|
_box?.delete(key).catchError((Object e) => debugPrint('library store delete $key: $e'));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Iterable<String> keys(String prefix) => [
|
||||||
|
...?_box?.keys.whereType<String>().where((k) => k.startsWith(prefix)),
|
||||||
|
..._memory.keys(prefix),
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
|
import '../files/scanner.dart' show FolderScan;
|
||||||
|
import 'show_matcher.dart';
|
||||||
|
|
||||||
|
// The next episode of a local show (the library's `nextAfter`, numbers
|
||||||
|
// skipped on the way included): what continues a file this app put up
|
||||||
|
// (see ARCHITECTURE.md "What's next").
|
||||||
|
|
||||||
|
/// [path]'s next episode: from the library the Files page saw this run
|
||||||
|
/// ([ShowMatcher.showAt]), else from the file's own folder read now (one
|
||||||
|
/// [scan], grouped by `groupLocal` with that folder's name as a hint). Null when there is none (the last
|
||||||
|
/// episode, not an episode, an unreadable folder).
|
||||||
|
class LocalNextFinder {
|
||||||
|
final ShowMatcher matcher;
|
||||||
|
final Future<FolderScan> Function(String dir) scan;
|
||||||
|
LocalNextFinder({required this.matcher, required this.scan});
|
||||||
|
|
||||||
|
Future<LocalNext?> nextAfter(String path) async {
|
||||||
|
var show = matcher.showAt(path);
|
||||||
|
if (show == null) {
|
||||||
|
final dir = File(path).parent.path;
|
||||||
|
final found = await scan(dir);
|
||||||
|
// The folder itself is a hint (a bare `01.mkv` in `Bleach`).
|
||||||
|
final lib = groupLocal(found.videos, roots: [Directory(dir).parent.path]);
|
||||||
|
show = lib.shows.where((s) => s.files.any((e) => e.path == path)).firstOrNull;
|
||||||
|
}
|
||||||
|
final at = show?.files.where((e) => e.path == path).firstOrNull;
|
||||||
|
if (show == null || at == null || at.kind != LocalKind.episode) return null;
|
||||||
|
return show.nextAfter(at.key);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
|
// `media.ref` (PROTOCOL.md "Media identity") for each source: what a media
|
||||||
|
// is, independent of where its bytes come from. Local files get theirs
|
||||||
|
// from the library (`ShowMatcher.refFor`, L1 + L2); these are the other
|
||||||
|
// two: Jellyfin items by their provider ids, links best effort from their
|
||||||
|
// name.
|
||||||
|
|
||||||
|
/// A Jellyfin episode, movie or video: kind, series (or movie) title,
|
||||||
|
/// season and episode as Jellyfin numbers them, and the AniList / TVDB ids
|
||||||
|
/// its metadata plugins set ([series]' when given: an episode's own ids
|
||||||
|
/// are the episode's, not the show's). Null for anything that is not
|
||||||
|
/// played (series, seasons, folders).
|
||||||
|
MediaRef? jellyfinMediaRef(JellyfinItem item, {JellyfinItem? series}) {
|
||||||
|
final kind = switch (item.kind) {
|
||||||
|
JellyfinItemKind.episode => 'episode',
|
||||||
|
JellyfinItemKind.movie || JellyfinItemKind.video => 'movie',
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
if (kind == null) return null;
|
||||||
|
final episode = kind == 'episode';
|
||||||
|
// An episode's Tvdb id names the episode; the show's comes from the
|
||||||
|
// series item. AniList ids are only ever set on shows and movies.
|
||||||
|
final owner = episode ? series : item;
|
||||||
|
final special = episode && item.parentIndexNumber == 0;
|
||||||
|
return MediaRef(
|
||||||
|
kind: special ? 'extra' : kind,
|
||||||
|
title: episode ? (item.seriesName ?? series?.name ?? item.name) : item.name,
|
||||||
|
anilistId: owner?.providerId('AniList'),
|
||||||
|
tvdbId: owner?.providerId('Tvdb'),
|
||||||
|
season: episode && !special ? item.parentIndexNumber : null,
|
||||||
|
ep: episode && !special ? item.indexNumber : null,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
final _sxe = RegExp(r'S(\d{1,3})\s?E(\d{1,4})$', caseSensitive: false);
|
||||||
|
|
||||||
|
/// A picked Jellyfin item from its card's lines alone ([title], and
|
||||||
|
/// [subtitle] "Series · S1E6" for episodes, the year for movies): kind,
|
||||||
|
/// title and numbers, no ids.
|
||||||
|
MediaRef jellyfinPickRef(String title, String subtitle) {
|
||||||
|
final sub = subtitle.trim();
|
||||||
|
final cut = sub.lastIndexOf(' · ');
|
||||||
|
final label = cut < 0 ? sub : sub.substring(cut + 3).trim();
|
||||||
|
final m = _sxe.firstMatch(label);
|
||||||
|
if (m == null) return MediaRef(kind: 'movie', title: title);
|
||||||
|
final season = int.parse(m.group(1)!);
|
||||||
|
return MediaRef(
|
||||||
|
kind: season == 0 ? 'extra' : 'episode',
|
||||||
|
title: cut < 0 ? title : sub.substring(0, cut).trim(),
|
||||||
|
season: season == 0 ? null : season,
|
||||||
|
ep: season == 0 ? null : int.parse(m.group(2)!),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A link, best effort: its name read like a release name (`Show - 05`
|
||||||
|
/// is an episode, `OP1` an extra); anything else a movie of that title.
|
||||||
|
MediaRef linkMediaRef(String name) {
|
||||||
|
final p = parseReleaseName(name);
|
||||||
|
final title = p.series.trim().isEmpty ? name.trim() : p.series.trim();
|
||||||
|
return switch (p.kind) {
|
||||||
|
ReleaseKind.episode => MediaRef(
|
||||||
|
kind: 'episode',
|
||||||
|
title: title,
|
||||||
|
season: p.season,
|
||||||
|
ep: p.season == null ? null : p.episode,
|
||||||
|
absolute: p.season == null ? p.episode : null),
|
||||||
|
ReleaseKind.extra => MediaRef(kind: 'extra', title: title, season: p.season),
|
||||||
|
ReleaseKind.movie || ReleaseKind.other => MediaRef(kind: 'movie', title: title),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The episode line a ref gives (`S3 E13`, `E108`), or null (movies;
|
||||||
|
/// extras keep the name's own marker).
|
||||||
|
String? refEpisodeLine(MediaRef ref) {
|
||||||
|
if (ref.kind != 'episode') return null;
|
||||||
|
if (ref.season != null && ref.ep != null) return 'S${ref.season} E${ref.ep}';
|
||||||
|
final n = ref.absolute ?? ref.ep ?? ref.anilistEp;
|
||||||
|
return n == null ? null : 'E$n';
|
||||||
|
}
|
||||||
@@ -0,0 +1,666 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart' show debugPrint, visibleForTesting;
|
||||||
|
import 'package:signals/signals.dart';
|
||||||
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
|
import '../schedule/anilist.dart';
|
||||||
|
import '../schedule/animeflow.dart';
|
||||||
|
import 'library_store.dart';
|
||||||
|
|
||||||
|
// L2 of the library (ARCHITECTURE.md "Media identity"): local shows (L1)
|
||||||
|
// matched to AniList, device-owned and cached. A season of a show is
|
||||||
|
// searched once (title and synonyms, the season's number or name as
|
||||||
|
// hints) and the answer kept by show key, season and season name; its
|
||||||
|
// episodes map onto AniList entries along the run (a season AniList
|
||||||
|
// splits into cours continues on the SEQUEL entry), or onto AnimeFlow's
|
||||||
|
// `anilist_map` when signed in. The user's pins (a show everywhere, or one
|
||||||
|
// folder) and episode offsets override everything and survive rescans.
|
||||||
|
// Requests are lazy (only for shows on screen), one at a time and spaced
|
||||||
|
// out for AniList's rate limit; everything answers offline from the cache.
|
||||||
|
|
||||||
|
/// Where AnimeFlow places an AniList entry: the TVDB season runs of its
|
||||||
|
/// series ([AniListRun]) and the series' TVDB id.
|
||||||
|
class FlowShow {
|
||||||
|
final List<AniListRun> runs;
|
||||||
|
final int? tvdbId;
|
||||||
|
const FlowShow(this.runs, {this.tvdbId});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// AnimeFlow's knowledge of a show, when signed in.
|
||||||
|
abstract interface class FlowLookup {
|
||||||
|
/// The series [anilistId] belongs to; null when AnimeFlow has none (or
|
||||||
|
/// cannot be asked).
|
||||||
|
Future<FlowShow?> forAniList(int anilistId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [FlowLookup] over the AnimeFlow app API (`/library`, `/series`), read
|
||||||
|
/// once per app run.
|
||||||
|
class AnimeFlowLookup implements FlowLookup {
|
||||||
|
final AnimeFlowClient client;
|
||||||
|
AnimeFlowLookup(this.client);
|
||||||
|
|
||||||
|
Future<(List<AnimeFlowLibraryItem>, List<AnimeFlowSeries>)>? _load;
|
||||||
|
|
||||||
|
Future<(List<AnimeFlowLibraryItem>, List<AnimeFlowSeries>)> _fetch() async =>
|
||||||
|
(await client.library(), await client.series());
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<FlowShow?> forAniList(int anilistId) async {
|
||||||
|
final load = _load ??= _fetch();
|
||||||
|
final (List<AnimeFlowLibraryItem>, List<AnimeFlowSeries>) data;
|
||||||
|
try {
|
||||||
|
data = await load;
|
||||||
|
} catch (e) {
|
||||||
|
_load = null;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
final (library, series) = data;
|
||||||
|
for (final item in library) {
|
||||||
|
final has = item.anilistMap.any((r) => r.anilistId == anilistId) || item.anilistIds.values.contains(anilistId);
|
||||||
|
if (!has) continue;
|
||||||
|
final s = series
|
||||||
|
.where((s) =>
|
||||||
|
(item.seriesId != null && s.seriesId == item.seriesId) ||
|
||||||
|
(s.jellyfinSeriesId != null && s.jellyfinSeriesId == item.jellyfinSeriesId))
|
||||||
|
.firstOrNull;
|
||||||
|
return FlowShow(item.anilistMap, tvdbId: s?.tvdbId);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a pin covers.
|
||||||
|
enum PinScope { show, folder }
|
||||||
|
|
||||||
|
/// The AniList entry a season (or a movie, or an extra's show) is.
|
||||||
|
class SeasonMatch {
|
||||||
|
final AniListEntry entry;
|
||||||
|
|
||||||
|
/// Set by the user ("Wrong show?"), not by the search.
|
||||||
|
final PinScope? pinned;
|
||||||
|
const SeasonMatch(this.entry, {this.pinned});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An episode on AniList.
|
||||||
|
class EpisodeTarget {
|
||||||
|
final int anilistId;
|
||||||
|
final int? anilistEp;
|
||||||
|
const EpisodeTarget(this.anilistId, this.anilistEp);
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool operator ==(Object other) => other is EpisodeTarget && other.anilistId == anilistId && other.anilistEp == anilistEp;
|
||||||
|
@override
|
||||||
|
int get hashCode => Object.hash(anilistId, anilistEp);
|
||||||
|
@override
|
||||||
|
String toString() => 'EpisodeTarget($anilistId, $anilistEp)';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The library's L2: see the file comment. Made by the composition root.
|
||||||
|
class ShowMatcher {
|
||||||
|
ShowMatcher({
|
||||||
|
required this.store,
|
||||||
|
required this.aniList,
|
||||||
|
this.flow,
|
||||||
|
this.spacing = const Duration(milliseconds: 800),
|
||||||
|
this.retryNoneAfter = const Duration(days: 3),
|
||||||
|
DateTime Function()? now,
|
||||||
|
Future<void> Function(Duration)? delay,
|
||||||
|
}) : _now = now ?? DateTime.now,
|
||||||
|
_delay = delay ?? Future<void>.delayed;
|
||||||
|
|
||||||
|
final LibraryStore store;
|
||||||
|
final AniListLookup aniList;
|
||||||
|
final FlowLookup? flow;
|
||||||
|
|
||||||
|
/// Between two AniList requests.
|
||||||
|
final Duration spacing;
|
||||||
|
|
||||||
|
/// A search that found nothing is asked again after this.
|
||||||
|
final Duration retryNoneAfter;
|
||||||
|
final DateTime Function() _now;
|
||||||
|
final Future<void> Function(Duration) _delay;
|
||||||
|
|
||||||
|
/// Bumps whenever something new is known (a match, an entry, a pin).
|
||||||
|
final revision = signal(0);
|
||||||
|
|
||||||
|
/// Shows being matched right now, by show key.
|
||||||
|
final busy = signal<Set<String>>(const {});
|
||||||
|
|
||||||
|
// Files seen in scans this run, for refs of files put up.
|
||||||
|
final _byPath = <String, LocalEpisode>{};
|
||||||
|
final _showByPath = <String, LocalShow>{};
|
||||||
|
final _entries = <int, AniListEntry>{};
|
||||||
|
final _flows = <int, FlowShow?>{};
|
||||||
|
final _jobs = <String, Future<void> Function()>{};
|
||||||
|
final _failed = <String, DateTime>{};
|
||||||
|
bool _pumping = false;
|
||||||
|
DateTime? _lastRequest;
|
||||||
|
DateTime? _pausedUntil;
|
||||||
|
|
||||||
|
/// Loads the cache (once); reads before it finishes see nothing.
|
||||||
|
Future<void> ensureLoaded() => store.ensureLoaded().then((_) => _bump());
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- keys
|
||||||
|
|
||||||
|
static String matchKey(String showKey, int? season, String? seasonName) =>
|
||||||
|
'$showKey|${season ?? ''}|${normalizeSeries(seasonName ?? '')}';
|
||||||
|
|
||||||
|
static String _movieKey(LocalEpisode e) => '${e.showKey}|movie|${e.movieNumber ?? ''}';
|
||||||
|
|
||||||
|
String _keyOf(LocalEpisode e) =>
|
||||||
|
e.kind == LocalKind.movie ? _movieKey(e) : matchKey(e.showKey, e.season, e.seasonName);
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- reads
|
||||||
|
|
||||||
|
/// Remembers [library]'s files, so [refForPath] and [showAt] know
|
||||||
|
/// their show.
|
||||||
|
void remember(LocalLibrary library) {
|
||||||
|
for (final e in library.files) {
|
||||||
|
_byPath[e.path] = e;
|
||||||
|
}
|
||||||
|
for (final s in library.shows) {
|
||||||
|
for (final e in s.files) {
|
||||||
|
_showByPath[e.path] = s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The show the file at [path] belongs to, as seen in a scan this run.
|
||||||
|
LocalShow? showAt(String path) => _showByPath[path];
|
||||||
|
|
||||||
|
AniListEntry? entry(int id) {
|
||||||
|
final known = _entries[id];
|
||||||
|
if (known != null) return known;
|
||||||
|
final raw = store.get('entry:$id');
|
||||||
|
final e = raw is Map ? AniListEntry.fromJson(raw['e']) : null;
|
||||||
|
if (e != null) _entries[id] = e;
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The user's pin for [showKey] (everywhere), if any.
|
||||||
|
int? showPin(String showKey) => _int(store.get('pin:show:$showKey'));
|
||||||
|
|
||||||
|
/// The pin of [folder] or the nearest folder above it, if any.
|
||||||
|
({String folder, int id})? folderPin(String folder) {
|
||||||
|
var f = folder;
|
||||||
|
while (f.isNotEmpty) {
|
||||||
|
final id = _int(store.get('pin:folder:$f'));
|
||||||
|
if (id != null) return (folder: f, id: id);
|
||||||
|
final cut = f.lastIndexOf(RegExp(r'[/\\]'));
|
||||||
|
if (cut <= 0) break;
|
||||||
|
f = f.substring(0, cut);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "These files are episodes N..": added to every file's number of
|
||||||
|
/// [showKey]'s season [season].
|
||||||
|
int offset(String showKey, int? season) => _int(store.get('offset:$showKey|${season ?? ''}')) ?? 0;
|
||||||
|
|
||||||
|
/// The entry [e]'s season (or movie, or the show of an extra) is: a
|
||||||
|
/// folder pin, else the show's pin, else the search's answer.
|
||||||
|
SeasonMatch? seasonMatch(LocalEpisode e) {
|
||||||
|
if (e.kind == LocalKind.other) return null;
|
||||||
|
final fp = folderPin(e.folder);
|
||||||
|
if (fp != null) {
|
||||||
|
final en = entry(fp.id);
|
||||||
|
return en == null ? null : SeasonMatch(en, pinned: PinScope.folder);
|
||||||
|
}
|
||||||
|
final sp = showPin(e.showKey);
|
||||||
|
if (sp != null) {
|
||||||
|
final en = entry(sp);
|
||||||
|
return en == null ? null : SeasonMatch(en, pinned: PinScope.show);
|
||||||
|
}
|
||||||
|
final auto = store.get('auto:${_keyOf(e)}');
|
||||||
|
final id = auto is Map ? _int(auto['id']) : null;
|
||||||
|
if (id == null) {
|
||||||
|
// An extra of no matched season: the show's first one.
|
||||||
|
if (e.kind == LocalKind.extra && e.season != null) {
|
||||||
|
return seasonMatch(LocalEpisode(
|
||||||
|
file: e.file, parsed: e.parsed, kind: LocalKind.extra, showKey: e.showKey, title: e.title, extra: e.extra));
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
final en = entry(id);
|
||||||
|
return en == null ? null : SeasonMatch(en);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the show is as a whole: its first season's match (else a
|
||||||
|
/// movie's or an extra's).
|
||||||
|
SeasonMatch? showMatch(LocalShow show) {
|
||||||
|
for (final e in [
|
||||||
|
for (final s in show.seasons) s.episodes.first,
|
||||||
|
...show.movies,
|
||||||
|
...show.extras,
|
||||||
|
]) {
|
||||||
|
final m = seasonMatch(e);
|
||||||
|
if (m != null) return m;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The proper name of [show]: its match's title, else as found.
|
||||||
|
String titleOf(LocalShow show) => showMatch(show)?.entry.title ?? show.title;
|
||||||
|
|
||||||
|
/// The AniList entry and episode [e] is; for extras and movies only the
|
||||||
|
/// entry. Null before a match.
|
||||||
|
EpisodeTarget? target(LocalEpisode e) {
|
||||||
|
final m = seasonMatch(e);
|
||||||
|
if (m == null) return null;
|
||||||
|
if (e.kind != LocalKind.episode) return EpisodeTarget(m.entry.id, null);
|
||||||
|
final n = e.episode! + offset(e.showKey, e.season);
|
||||||
|
if (n < 1) return EpisodeTarget(m.entry.id, null);
|
||||||
|
final fs = _flowOf(m.entry.id);
|
||||||
|
if (fs != null && e.season != null) {
|
||||||
|
final runs = fs.runs.where((r) => r.season == e.season && r.firstEpisode <= n).toList()
|
||||||
|
..sort((a, b) => b.firstEpisode.compareTo(a.firstEpisode));
|
||||||
|
if (runs.isNotEmpty) return EpisodeTarget(runs.first.anilistId, n - runs.first.offset);
|
||||||
|
}
|
||||||
|
// Along the run: past an entry's episodes, its sequel's.
|
||||||
|
var cur = m.entry;
|
||||||
|
var k = n;
|
||||||
|
for (var hop = 0; hop < 30; hop++) {
|
||||||
|
final count = cur.episodes;
|
||||||
|
final next = cur.sequel;
|
||||||
|
if (count == null || k <= count || next == null) break;
|
||||||
|
k -= count;
|
||||||
|
final nx = entry(next);
|
||||||
|
if (nx == null) {
|
||||||
|
_wantEntry(next);
|
||||||
|
return EpisodeTarget(next, k);
|
||||||
|
}
|
||||||
|
cur = nx;
|
||||||
|
}
|
||||||
|
return EpisodeTarget(cur.id, k);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// AniList's title of [e]'s episode, when it knows one.
|
||||||
|
String? episodeTitle(LocalEpisode e) {
|
||||||
|
final t = target(e);
|
||||||
|
final ep = t?.anilistEp;
|
||||||
|
if (t == null || ep == null) return null;
|
||||||
|
return entry(t.anilistId)?.episodeTitles[ep];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What [e] is on the wire (`media.ref`): the match when there is one,
|
||||||
|
/// else what L1 read (kind, title, numbers).
|
||||||
|
MediaRef refFor(LocalEpisode e) {
|
||||||
|
final m = seasonMatch(e);
|
||||||
|
final t = target(e);
|
||||||
|
final n = e.episode == null ? null : e.episode! + offset(e.showKey, e.season);
|
||||||
|
final tvdb = m == null ? null : _flowOf(m.entry.id)?.tvdbId;
|
||||||
|
return MediaRef(
|
||||||
|
kind: switch (e.kind) {
|
||||||
|
LocalKind.episode => 'episode',
|
||||||
|
LocalKind.extra => 'extra',
|
||||||
|
LocalKind.movie || LocalKind.other => 'movie',
|
||||||
|
},
|
||||||
|
title: m?.entry.title ?? e.title,
|
||||||
|
anilistId: t?.anilistId ?? m?.entry.id,
|
||||||
|
anilistEp: t?.anilistEp,
|
||||||
|
tvdbId: tvdb,
|
||||||
|
season: e.kind == LocalKind.episode ? e.season : null,
|
||||||
|
ep: e.kind == LocalKind.episode && e.season != null ? n : null,
|
||||||
|
absolute: e.kind == LocalKind.episode && e.season == null ? n : null,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [refFor] the file at [path]: as seen in a scan this run, else read
|
||||||
|
/// from its name and folder alone.
|
||||||
|
MediaRef refForPath(String path) =>
|
||||||
|
refFor(_byPath[path] ?? readLocalFile(LocalFile(path, 0, DateTime.fromMillisecondsSinceEpoch(0))));
|
||||||
|
|
||||||
|
/// The library's reading of [path] (null: not seen in a scan this run).
|
||||||
|
LocalEpisode? episodeAt(String path) => _byPath[path];
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- matching
|
||||||
|
|
||||||
|
/// Matches [show]'s seasons and movies that have no answer yet, in the
|
||||||
|
/// background (see the file comment).
|
||||||
|
void want(LocalShow show) {
|
||||||
|
final seen = <String>{};
|
||||||
|
for (final e in [
|
||||||
|
for (final s in show.seasons) s.episodes.first,
|
||||||
|
...show.movies,
|
||||||
|
if (show.seasons.isEmpty) ...show.extras.take(1),
|
||||||
|
]) {
|
||||||
|
final key = _keyOf(e);
|
||||||
|
if (!seen.add(key)) continue;
|
||||||
|
final pinned = folderPin(e.folder)?.id ?? showPin(e.showKey);
|
||||||
|
if (pinned != null) {
|
||||||
|
if (entry(pinned) == null) _wantEntry(pinned);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
_wantMatch(key, show, e);
|
||||||
|
}
|
||||||
|
final m = showMatch(show);
|
||||||
|
if (m != null) _wantFlow(m.entry.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [want] for each standalone movie of [library] and each of [shows].
|
||||||
|
void wantMovie(LocalEpisode movie) {
|
||||||
|
if (movie.kind != LocalKind.movie) return;
|
||||||
|
_wantMatch(_movieKey(movie), null, movie);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _wantMatch(String key, LocalShow? show, LocalEpisode e) {
|
||||||
|
final auto = store.get('auto:$key');
|
||||||
|
if (auto is Map) {
|
||||||
|
final id = _int(auto['id']);
|
||||||
|
if (id != null) {
|
||||||
|
if (entry(id) == null) _wantEntry(id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final at = _int(auto['at']) ?? 0;
|
||||||
|
if (_now().difference(DateTime.fromMillisecondsSinceEpoch(at)) < retryNoneAfter) return;
|
||||||
|
}
|
||||||
|
if (_recentlyFailed(key)) return;
|
||||||
|
_enqueue('match:$key', () => _match(key, show?.title ?? e.title, e));
|
||||||
|
_setBusy(e.showKey, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _wantEntry(int id) {
|
||||||
|
if (_recentlyFailed('entry:$id')) return;
|
||||||
|
_enqueue('entry:$id', () async {
|
||||||
|
final en = await _ask(() => aniList.anime(id));
|
||||||
|
if (en != null) _keepEntry(en);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void _wantFlow(int id) {
|
||||||
|
final f = flow;
|
||||||
|
if (f == null || _flows.containsKey(id)) return;
|
||||||
|
final stored = store.get('flow:$id');
|
||||||
|
if (stored is Map) {
|
||||||
|
_flows[id] = _flowFromJson(stored);
|
||||||
|
final at = _int(stored['at']) ?? 0;
|
||||||
|
if (_now().difference(DateTime.fromMillisecondsSinceEpoch(at)) < const Duration(days: 1)) return;
|
||||||
|
} else {
|
||||||
|
_flows[id] = null;
|
||||||
|
}
|
||||||
|
unawaited(f.forAniList(id).then((fs) {
|
||||||
|
if (fs == null) return;
|
||||||
|
_flows[id] = fs;
|
||||||
|
store.put('flow:$id', {
|
||||||
|
'at': _now().millisecondsSinceEpoch,
|
||||||
|
'tvdb': fs.tvdbId,
|
||||||
|
'runs': [
|
||||||
|
for (final r in fs.runs) [r.season, r.anilistId, r.firstEpisode, r.offset]
|
||||||
|
],
|
||||||
|
});
|
||||||
|
_bump();
|
||||||
|
}).catchError((Object e) => debugPrint('library: animeflow lookup $id: $e')));
|
||||||
|
}
|
||||||
|
|
||||||
|
FlowShow? _flowOf(int id) {
|
||||||
|
if (!_flows.containsKey(id)) {
|
||||||
|
final stored = store.get('flow:$id');
|
||||||
|
if (stored is Map) _flows[id] = _flowFromJson(stored);
|
||||||
|
}
|
||||||
|
return _flows[id];
|
||||||
|
}
|
||||||
|
|
||||||
|
static FlowShow? _flowFromJson(Map j) {
|
||||||
|
final runs = <AniListRun>[];
|
||||||
|
final raw = j['runs'];
|
||||||
|
if (raw is List) {
|
||||||
|
for (final r in raw) {
|
||||||
|
if (r is List && r.length == 4 && r.every((v) => v is int)) {
|
||||||
|
runs.add(AniListRun(
|
||||||
|
season: r[0] as int, anilistId: r[1] as int, firstEpisode: r[2] as int, offset: r[3] as int));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return runs.isEmpty ? null : FlowShow(runs, tvdbId: _int(j['tvdb']));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One search for the season [e] stands for; keeps the best entry (or
|
||||||
|
/// "none") under [key].
|
||||||
|
Future<void> _match(String key, String title, LocalEpisode e) async {
|
||||||
|
try {
|
||||||
|
final plain = title.replaceAll(RegExp(r'[._]+'), ' ').replaceAll(RegExp(r'\s+'), ' ').trim();
|
||||||
|
final movie = e.kind == LocalKind.movie;
|
||||||
|
final season = movie ? null : e.season;
|
||||||
|
final name = movie ? null : e.seasonName;
|
||||||
|
final query = [
|
||||||
|
plain,
|
||||||
|
if (name != null) name else if (season != null && season > 1) 'season $season',
|
||||||
|
].join(' ');
|
||||||
|
var hits = await _ask(() => aniList.searchAnime(query));
|
||||||
|
var best = pickMatch(hits, title: plain, season: season, seasonName: name, movie: movie);
|
||||||
|
if (best == null && query != plain) {
|
||||||
|
hits = await _ask(() => aniList.searchAnime(plain));
|
||||||
|
best = pickMatch(hits, title: plain, season: season, seasonName: name, movie: movie);
|
||||||
|
// Found the show but not the season: walk its sequels.
|
||||||
|
if (best != null && season != null && season > 1 && name == null && seasonMarker(best) != season) {
|
||||||
|
var cur = best;
|
||||||
|
for (var hop = 1; hop < season; hop++) {
|
||||||
|
final next = cur.sequel;
|
||||||
|
if (next == null) break;
|
||||||
|
final nx = entry(next) ?? await _ask(() => aniList.anime(next));
|
||||||
|
if (nx == null) break;
|
||||||
|
_keepEntry(nx);
|
||||||
|
cur = nx;
|
||||||
|
}
|
||||||
|
best = cur;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (final h in hits) {
|
||||||
|
if (h.id == best?.id) _keepEntry(h);
|
||||||
|
}
|
||||||
|
store.put('auto:$key', {'id': best?.id, 'at': _now().millisecondsSinceEpoch});
|
||||||
|
if (best != null) _wantFlow(best.id);
|
||||||
|
_bump();
|
||||||
|
} finally {
|
||||||
|
_setBusy(e.showKey, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Wrong show?": AniList's answers for [query], best first.
|
||||||
|
Future<List<AniListEntry>> search(String query) async {
|
||||||
|
final hits = await _ask(() => aniList.searchAnime(query));
|
||||||
|
return hits;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- corrections
|
||||||
|
|
||||||
|
/// Pins [showKey] to [e] everywhere (every folder, every rescan).
|
||||||
|
void pinShow(String showKey, AniListEntry e) {
|
||||||
|
_keepEntry(e);
|
||||||
|
store.put('pin:show:$showKey', e.id);
|
||||||
|
_wantFlow(e.id);
|
||||||
|
_bump();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pins every video in [folder] (and below) to [e].
|
||||||
|
void pinFolder(String folder, AniListEntry e) {
|
||||||
|
_keepEntry(e);
|
||||||
|
store.put('pin:folder:$folder', e.id);
|
||||||
|
_wantFlow(e.id);
|
||||||
|
_bump();
|
||||||
|
}
|
||||||
|
|
||||||
|
void unpinShow(String showKey) {
|
||||||
|
store.delete('pin:show:$showKey');
|
||||||
|
_bump();
|
||||||
|
}
|
||||||
|
|
||||||
|
void unpinFolder(String folder) {
|
||||||
|
store.delete('pin:folder:$folder');
|
||||||
|
_bump();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "These files are episodes N..": [offset] is added to the file
|
||||||
|
/// numbers of [showKey]'s season [season] (0 removes it).
|
||||||
|
void setOffset(String showKey, int? season, int offset) {
|
||||||
|
final key = 'offset:$showKey|${season ?? ''}';
|
||||||
|
offset == 0 ? store.delete(key) : store.put(key, offset);
|
||||||
|
_bump();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Forgets the automatic match of [show] so it is searched again.
|
||||||
|
void rematch(LocalShow show) {
|
||||||
|
for (final k in store.keys('auto:${show.key}|').toList()) {
|
||||||
|
store.delete(k);
|
||||||
|
}
|
||||||
|
want(show);
|
||||||
|
_bump();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- plumbing
|
||||||
|
|
||||||
|
void _keepEntry(AniListEntry e) {
|
||||||
|
_entries[e.id] = e;
|
||||||
|
store.put('entry:${e.id}', {'at': _now().millisecondsSinceEpoch, 'e': e.toJson()});
|
||||||
|
_bump();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _bump() => revision.value++;
|
||||||
|
|
||||||
|
void _setBusy(String showKey, bool on) {
|
||||||
|
final now = {...busy.peek()};
|
||||||
|
if (on ? now.add(showKey) : now.remove(showKey)) busy.value = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _recentlyFailed(String key) {
|
||||||
|
final at = _failed[key];
|
||||||
|
return at != null && _now().difference(at) < const Duration(minutes: 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _enqueue(String key, Future<void> Function() job) {
|
||||||
|
if (_jobs.containsKey(key)) return;
|
||||||
|
_jobs[key] = () => job().catchError((Object e) {
|
||||||
|
_failed[key] = _now();
|
||||||
|
debugPrint('library: $key failed: $e');
|
||||||
|
if (e is AniListException && e.isRateLimited) _pausedUntil = _now().add(const Duration(minutes: 1));
|
||||||
|
});
|
||||||
|
if (!_pumping) unawaited(_pump());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pump() async {
|
||||||
|
_pumping = true;
|
||||||
|
try {
|
||||||
|
while (_jobs.isNotEmpty) {
|
||||||
|
final key = _jobs.keys.first;
|
||||||
|
final job = _jobs[key]!;
|
||||||
|
await job();
|
||||||
|
_jobs.remove(key);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
_pumping = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One AniList request, spaced from the last one (and after a rate
|
||||||
|
/// limit's pause).
|
||||||
|
Future<T> _ask<T>(Future<T> Function() request) async {
|
||||||
|
final paused = _pausedUntil;
|
||||||
|
if (paused != null && paused.isAfter(_now())) await _delay(paused.difference(_now()));
|
||||||
|
final last = _lastRequest;
|
||||||
|
if (last != null) {
|
||||||
|
final wait = spacing - _now().difference(last);
|
||||||
|
if (wait > Duration.zero) await _delay(wait);
|
||||||
|
}
|
||||||
|
_lastRequest = _now();
|
||||||
|
return request();
|
||||||
|
}
|
||||||
|
|
||||||
|
@visibleForTesting
|
||||||
|
bool get idle => _jobs.isEmpty && !_pumping;
|
||||||
|
|
||||||
|
static int? _int(Object? v) => v is int ? v : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ scoring
|
||||||
|
|
||||||
|
/// The season number an entry's names carry (`Season 2`, `2nd Season`,
|
||||||
|
/// `Part 2` is not one); null when none does.
|
||||||
|
int? seasonMarker(AniListEntry e) {
|
||||||
|
for (final n in e.names) {
|
||||||
|
final s = _seasonOf(normalizeSeries(n));
|
||||||
|
if (s != null) return s;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
final _seasonWords = RegExp(r'\b(?:season (\d{1,2})|(\d{1,2})(?:st|nd|rd|th) season|s(\d{1,2}))\b');
|
||||||
|
final _roman = {'ii': 2, 'iii': 3, 'iv': 4, 'v': 5, 'vi': 6};
|
||||||
|
|
||||||
|
int? _seasonOf(String normalized) {
|
||||||
|
final m = _seasonWords.firstMatch(normalized);
|
||||||
|
if (m != null) return int.parse(m.group(1) ?? m.group(2) ?? m.group(3)!);
|
||||||
|
final last = normalized.split(' ').last;
|
||||||
|
return _roman[last];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How alike two normalized titles are, 0..1.
|
||||||
|
double titleSimilarity(String a, String b) {
|
||||||
|
if (a.isEmpty || b.isEmpty) return 0;
|
||||||
|
if (a == b) return 1;
|
||||||
|
final short = a.length <= b.length ? a : b;
|
||||||
|
final long = a.length <= b.length ? b : a;
|
||||||
|
final ratio = short.length / long.length;
|
||||||
|
if (long.startsWith('$short ')) return 0.8 + 0.2 * ratio;
|
||||||
|
if (long.contains(' $short ') || long.endsWith(' $short')) return 0.6 + 0.2 * ratio;
|
||||||
|
// Dice over letter pairs, spaces ignored.
|
||||||
|
Set<String> pairs(String s) {
|
||||||
|
final t = s.replaceAll(' ', '');
|
||||||
|
return {for (var i = 0; i + 1 < t.length; i++) t.substring(i, i + 2)};
|
||||||
|
}
|
||||||
|
|
||||||
|
final pa = pairs(a), pb = pairs(b);
|
||||||
|
if (pa.isEmpty || pb.isEmpty) return 0;
|
||||||
|
return 2 * pa.intersection(pb).length / (pa.length + pb.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Scores [e] as the answer for a show called [title] (its season
|
||||||
|
/// [season] or its season named [seasonName]; a [movie]); [rank]: its
|
||||||
|
/// place in AniList's own order.
|
||||||
|
double scoreMatch(AniListEntry e,
|
||||||
|
{required String title, int? season, String? seasonName, bool movie = false, int rank = 0}) {
|
||||||
|
final q = normalizeSeries(title);
|
||||||
|
final full = seasonName == null ? q : normalizeSeries('$title $seasonName');
|
||||||
|
var best = 0.0;
|
||||||
|
for (final n in e.names) {
|
||||||
|
final nn = normalizeSeries(n);
|
||||||
|
final s = [titleSimilarity(nn, q), titleSimilarity(nn, full)].reduce((a, b) => a > b ? a : b);
|
||||||
|
if (s > best) best = s;
|
||||||
|
}
|
||||||
|
var score = best;
|
||||||
|
if (seasonName != null) {
|
||||||
|
final sub = normalizeSeries(seasonName);
|
||||||
|
if (e.names.any((n) => normalizeSeries(n).contains(sub))) score += 0.25;
|
||||||
|
} else if (!movie) {
|
||||||
|
final wanted = season ?? 1;
|
||||||
|
final marker = seasonMarker(e);
|
||||||
|
if (marker != null && marker == wanted) {
|
||||||
|
score += 0.2;
|
||||||
|
} else if (marker != null) {
|
||||||
|
score -= 0.25;
|
||||||
|
} else if (wanted > 1) {
|
||||||
|
score -= 0.1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (movie) {
|
||||||
|
score += e.isMovie ? 0.15 : -0.25;
|
||||||
|
} else {
|
||||||
|
score += e.isSeries ? 0.05 : (e.isMovie ? -0.3 : -0.1);
|
||||||
|
}
|
||||||
|
return score - rank * 0.02;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The best of [hits] for a show called [title], if any is good enough.
|
||||||
|
AniListEntry? pickMatch(List<AniListEntry> hits,
|
||||||
|
{required String title, int? season, String? seasonName, bool movie = false}) {
|
||||||
|
AniListEntry? best;
|
||||||
|
var bestScore = 0.55;
|
||||||
|
for (var i = 0; i < hits.length; i++) {
|
||||||
|
final s = scoreMatch(hits[i], title: title, season: season, seasonName: seasonName, movie: movie, rank: i);
|
||||||
|
if (s > bestScore) {
|
||||||
|
best = hits[i];
|
||||||
|
bestScore = s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
|
import '../screens/home/ui.dart' show appName, displayVersion;
|
||||||
|
import 'ports/app_dirs.dart';
|
||||||
|
import '../app/app_graph.dart';
|
||||||
|
|
||||||
|
// The app's log on disk (<app support>/logs/app-YYYY-MM-DD.log; core's
|
||||||
|
// logging.dart writes, rotates and redacts it), debugPrint routed into it,
|
||||||
|
// and the "Copy diagnostics" text of Settings → About.
|
||||||
|
|
||||||
|
final _appLog = createLogger('app');
|
||||||
|
|
||||||
|
/// The logs folder, once [startAppLogging] ran.
|
||||||
|
String? appLogDir;
|
||||||
|
|
||||||
|
/// Opens the log files in [dirs]' log folder and routes `debugPrint` and
|
||||||
|
/// uncaught errors into the log.
|
||||||
|
Future<void> startAppLogging(AppDirs dirs) async {
|
||||||
|
try {
|
||||||
|
if (startLogFiles(dirs.logs) != null) appLogDir = dirs.logs;
|
||||||
|
} catch (e) {
|
||||||
|
_appLog.warning('no log files: $e');
|
||||||
|
}
|
||||||
|
// Everything the app prints for diagnosis lands in the file too (the
|
||||||
|
// log's console output replaces the print).
|
||||||
|
debugPrint = (String? message, {int? wrapWidth}) {
|
||||||
|
if (message == null || message.isEmpty) return;
|
||||||
|
final bad = RegExp(r'fail|error|crash|exception', caseSensitive: false).hasMatch(message);
|
||||||
|
bad ? _appLog.warning(message) : _appLog.info(message);
|
||||||
|
};
|
||||||
|
PlatformDispatcher.instance.onError = (error, stack) {
|
||||||
|
_appLog.severe('uncaught: $error', error, stack);
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
_appLog.info('$appName ${displayVersion()} on ${Platform.operatingSystem} '
|
||||||
|
'${Platform.operatingSystemVersion}, pid $pid, Dart ${Platform.version.split(' ').first}'
|
||||||
|
'${dirs.profile == null ? '' : ', profile ${dirs.profile}'}');
|
||||||
|
for (final line in dirs.migrated) {
|
||||||
|
_appLog.info(line);
|
||||||
|
}
|
||||||
|
final bad = AppDirs.invalidProfile(Platform.environment);
|
||||||
|
if (bad != null) _appLog.warning('$profileEnv="$bad" ignored: use letters, digits, - and _ (at most 32)');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The text "Copy diagnostics" gives: versions, then the last [since] of
|
||||||
|
/// the app log (its hosted server's records included), already redacted;
|
||||||
|
/// with [sessionLog], the server's session log of the same hours after it
|
||||||
|
/// (every member's shared lines and the server's, merged).
|
||||||
|
Future<String> diagnosticsText(AppGraph graph, {Duration since = const Duration(hours: 6), bool sessionLog = false}) async {
|
||||||
|
final b = StringBuffer()
|
||||||
|
..writeln('$appName ${displayVersion()}')
|
||||||
|
..writeln('OS: ${Platform.operatingSystem} ${Platform.operatingSystemVersion}')
|
||||||
|
..writeln('Dart: ${Platform.version.split(' ').first}');
|
||||||
|
try {
|
||||||
|
final mpv = await graph.coordinator.playback.mpvVersion().timeout(const Duration(seconds: 2));
|
||||||
|
b.writeln('mpv: ${mpv ?? 'no player yet'}');
|
||||||
|
} catch (_) {
|
||||||
|
b.writeln('mpv: unknown');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final y = await graph.ports.links.ytDlp.timeout(const Duration(seconds: 2));
|
||||||
|
final cookies = y.cookies.read(count: false);
|
||||||
|
b.writeln('yt-dlp: ${y.version ?? 'not ready'}${y.lastError == null ? '' : ' (${y.lastError})'}, '
|
||||||
|
'cookies: ${cookies == null ? 'none' : 'set'}');
|
||||||
|
} catch (_) {
|
||||||
|
b.writeln('yt-dlp: unknown');
|
||||||
|
}
|
||||||
|
final files = logFiles;
|
||||||
|
b.writeln('Log: ${files?.currentPath ?? 'none (console only)'}');
|
||||||
|
b.writeln('--- last ${since.inHours} h of the log ---');
|
||||||
|
b.write(files?.recent(since) ?? '');
|
||||||
|
if (sessionLog) {
|
||||||
|
final server = await graph.coordinator.sessionLog(hours: since.inHours);
|
||||||
|
b
|
||||||
|
..writeln()
|
||||||
|
..writeln("--- last ${since.inHours} h of the server's session log ---")
|
||||||
|
..write(server ?? "(none: the server keeps no session log, or it couldn't be reached)");
|
||||||
|
}
|
||||||
|
return redactLog(b.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Saves [text] next to the logs as `diagnostics-<time>.txt`; its path,
|
||||||
|
/// or null when it could not be written.
|
||||||
|
Future<String?> saveDiagnostics(String text) async {
|
||||||
|
final dir = appLogDir;
|
||||||
|
if (dir == null) return null;
|
||||||
|
final t = DateTime.now();
|
||||||
|
String two(int n) => n.toString().padLeft(2, '0');
|
||||||
|
final path = '$dir${Platform.pathSeparator}diagnostics-${t.year}${two(t.month)}${two(t.day)}-'
|
||||||
|
'${two(t.hour)}${two(t.minute)}${two(t.second)}.txt';
|
||||||
|
try {
|
||||||
|
// Older ones go after the log files' week.
|
||||||
|
for (final e in Directory(dir).listSync()) {
|
||||||
|
if (e is File &&
|
||||||
|
e.uri.pathSegments.last.startsWith('diagnostics-') &&
|
||||||
|
t.difference(e.statSync().modified) > const Duration(days: 7)) {
|
||||||
|
e.deleteSync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await File(path).writeAsString(text);
|
||||||
|
return path;
|
||||||
|
} catch (e) {
|
||||||
|
_appLog.warning('cannot save diagnostics: $e');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
|
||||||
|
import '../files/thumbnails.dart';
|
||||||
|
import '../app/app_graph.dart';
|
||||||
|
|
||||||
|
// The one way out of the app (close button, Alt+F4, Update and restart).
|
||||||
|
// Order matters: every mpv player goes before the engine does (a live one
|
||||||
|
// calls a dead Dart callback), then the network goodbye, then the window
|
||||||
|
// closes through the platform's normal path so the engine is torn down
|
||||||
|
// inside the message loop. The runners end the process right after
|
||||||
|
// (`linux/runner/main.cc`, `windows/runner/main.cpp`).
|
||||||
|
|
||||||
|
bool _shuttingDown = false;
|
||||||
|
|
||||||
|
/// True once [shutDownApp] started.
|
||||||
|
bool get shuttingDown => _shuttingDown;
|
||||||
|
|
||||||
|
/// The systems the close stops; `main` hands them over once.
|
||||||
|
AppGraph? _graph;
|
||||||
|
|
||||||
|
/// Makes [graph] the one [shutDownApp] stops and returns the close
|
||||||
|
/// request handler for the window.
|
||||||
|
Future<void> Function() closeAppWith(AppGraph graph) {
|
||||||
|
_graph = graph;
|
||||||
|
return shutDownApp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hides the window, releases every player and the sound device, leaves
|
||||||
|
/// (the `bye` goes out first, so others see "left" at once; then your
|
||||||
|
/// server stops), runs [beforeQuit], then closes the window. [restart]
|
||||||
|
/// (Update and restart) leaves without the `bye`: the member stays
|
||||||
|
/// `gone`, and the restarted app, same client id, takes it back within
|
||||||
|
/// the grace. Every step is bounded; a second call does nothing.
|
||||||
|
Future<void> shutDownApp({Future<void> Function()? beforeQuit, bool restart = false}) async {
|
||||||
|
final graph = _graph;
|
||||||
|
if (_shuttingDown || graph == null) return;
|
||||||
|
_shuttingDown = true;
|
||||||
|
final shell = graph.ports.shell;
|
||||||
|
final total = Stopwatch()..start();
|
||||||
|
await _step('window save', shell.saveWindow(), const Duration(milliseconds: 500));
|
||||||
|
await _step('hide', shell.hide(), const Duration(milliseconds: 500));
|
||||||
|
await Future.wait([
|
||||||
|
_step('players', graph.coordinator.releasePlayers(), const Duration(seconds: 3)),
|
||||||
|
_step('thumbnails', cancelAllThumbnails(), const Duration(milliseconds: 1500)),
|
||||||
|
_step('sounds', graph.sfx.dispose(), const Duration(milliseconds: 500)),
|
||||||
|
]);
|
||||||
|
// The host owns the disposal order: anything still alive goes now.
|
||||||
|
await _step('all players', graph.ports.players.disposeAll(), const Duration(milliseconds: 1500));
|
||||||
|
// Windows: media_kit_video frees a player's video output on a thread of
|
||||||
|
// its own after dispose returns; it must be done before the engine
|
||||||
|
// stops, or the plugin's teardown waits on it for good.
|
||||||
|
if (Platform.isWindows) await Future.delayed(const Duration(milliseconds: 300));
|
||||||
|
// Jellyfin stop report, last diagnostics, the bye (flushed), then your
|
||||||
|
// server: 3 s in all.
|
||||||
|
await _step('leave', graph.navigation.leave(bye: !restart), const Duration(milliseconds: 2500));
|
||||||
|
await _step('server stop', graph.yourServer.stop(), const Duration(milliseconds: 500));
|
||||||
|
if (beforeQuit != null) await _step('before quit', beforeQuit(), const Duration(seconds: 3));
|
||||||
|
debugPrint('close: ready to quit after ${total.elapsedMilliseconds} ms');
|
||||||
|
await shell.quit();
|
||||||
|
// The engine stops with the window, so this only fires when the close
|
||||||
|
// did not go through. A kill, not exit(): no exit handlers (NVIDIA's
|
||||||
|
// EGL one segfaults, Windows DLL detach can hang).
|
||||||
|
Timer(const Duration(seconds: 3), () {
|
||||||
|
debugPrint('close: the window did not close; ending the process');
|
||||||
|
Process.killPid(pid, ProcessSignal.sigkill);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _step(String what, Future<void>? f, Duration limit) async {
|
||||||
|
if (f == null) return;
|
||||||
|
final sw = Stopwatch()..start();
|
||||||
|
try {
|
||||||
|
await f.timeout(limit);
|
||||||
|
} on TimeoutException {
|
||||||
|
debugPrint('close: $what did not finish in ${limit.inMilliseconds} ms');
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('close: $what failed: $e');
|
||||||
|
}
|
||||||
|
if (sw.elapsedMilliseconds > 200) debugPrint('close: $what took ${sw.elapsedMilliseconds} ms');
|
||||||
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter_soloud/flutter_soloud.dart';
|
||||||
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
|
final _log = createLogger('sound');
|
||||||
|
|
||||||
|
/// What [SoundEngine] needs from an audio library: [SoLoudBackend] in the
|
||||||
|
/// app, a fake in tests. A sound handle is whatever [load] returns.
|
||||||
|
abstract class AudioBackend {
|
||||||
|
Future<void> init();
|
||||||
|
/// Decodes [wav] (a whole WAV file) into memory under [name].
|
||||||
|
Future<Object> load(String name, Uint8List wav);
|
||||||
|
/// Starts one voice of [sound] at [volume] (linear gain, 0..1); voices
|
||||||
|
/// overlap.
|
||||||
|
void play(Object sound, double volume);
|
||||||
|
Future<void> unload(Object sound);
|
||||||
|
Future<void> deinit();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// flutter_soloud (SoLoud mixing into miniaudio's output device).
|
||||||
|
class SoLoudBackend implements AudioBackend {
|
||||||
|
SoLoud get _s => SoLoud.instance;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> init() => _s.init();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<Object> load(String name, Uint8List wav) => _s.loadMem(name, wav);
|
||||||
|
|
||||||
|
@override
|
||||||
|
void play(Object sound, double volume) => _s.play(sound as AudioSource, volume: volume);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> unload(Object sound) => _s.disposeSource(sound as AudioSource);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> deinit() => _s.deinitAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The app's short in-memory sounds. The audio device opens on [warmUp] or
|
||||||
|
/// the first [play]; if it can't (no device, a broken driver) the engine
|
||||||
|
/// logs once and every play is silently dropped. Each sound is loaded once
|
||||||
|
/// per slot from the WAV bytes its renderer gives; a new key in a slot
|
||||||
|
/// replaces (and frees) what the slot held.
|
||||||
|
class SoundEngine {
|
||||||
|
final AudioBackend _backend;
|
||||||
|
SoundEngine({AudioBackend? backend}) : _backend = backend ?? SoLoudBackend();
|
||||||
|
|
||||||
|
Future<bool>? _ready;
|
||||||
|
var _disposed = false;
|
||||||
|
|
||||||
|
/// A file that exists only while the audio device is opening (set by the
|
||||||
|
/// app). Found at the next start, the last open took the app down (a
|
||||||
|
/// native crash in the driver or miniaudio, seen on Windows): sounds stay
|
||||||
|
/// off rather than crash every start, until [retry] (Settings' preview).
|
||||||
|
String? crashMark;
|
||||||
|
var _skipped = false;
|
||||||
|
/// Per slot: the loaded key and its sound (null: failed to load).
|
||||||
|
final Map<String, (String, Future<Object?>)> _slots = {};
|
||||||
|
/// Load names are unique: SoLoud hands back the old sound for a name it
|
||||||
|
/// already holds, which would defeat a re-render.
|
||||||
|
var _loads = 0;
|
||||||
|
|
||||||
|
/// Opens the audio device now, so the first sound has no wait.
|
||||||
|
Future<bool> warmUp() => _ready ??= _init();
|
||||||
|
|
||||||
|
Future<bool> _init() async {
|
||||||
|
if (_disposed) return false;
|
||||||
|
final mark = crashMark == null ? null : File(crashMark!);
|
||||||
|
try {
|
||||||
|
if (mark != null && mark.existsSync()) {
|
||||||
|
_skipped = true;
|
||||||
|
_log.warning('no sounds: opening the audio device crashed the app last time '
|
||||||
|
'(${mark.path}); a sound preview in Settings tries again');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
mark?.writeAsStringSync('opening the audio device');
|
||||||
|
} catch (_) {}
|
||||||
|
_log.info('opening the audio device');
|
||||||
|
try {
|
||||||
|
await _backend.init();
|
||||||
|
_log.info('audio device open');
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
_log.warning('no sounds: audio init failed: $e');
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
if (mark != null && mark.existsSync()) mark.deleteSync();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens the device again after a crash mark kept sounds off (the user
|
||||||
|
/// asked for a sound). A real crash leaves the mark again.
|
||||||
|
void retry() {
|
||||||
|
if (!_skipped) return;
|
||||||
|
_skipped = false;
|
||||||
|
try {
|
||||||
|
final m = crashMark;
|
||||||
|
if (m != null) File(m).deleteSync();
|
||||||
|
} catch (_) {}
|
||||||
|
_ready = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Plays the sound of [slot] at [volume] (linear gain). [key] names what
|
||||||
|
/// [wav] renders: the same key reuses the loaded sound; another key, or
|
||||||
|
/// [fresh], renders and loads it again.
|
||||||
|
Future<void> play(String slot, String key, Future<Uint8List> Function() wav,
|
||||||
|
{required double volume, bool fresh = false}) async {
|
||||||
|
if (_disposed || volume <= 0) return;
|
||||||
|
if (!await warmUp() || _disposed) return;
|
||||||
|
var held = _slots[slot];
|
||||||
|
if (held == null || held.$1 != key || fresh) {
|
||||||
|
if (held != null) unawaited(_unload(held.$2));
|
||||||
|
held = (key, _load(key, wav));
|
||||||
|
_slots[slot] = held;
|
||||||
|
}
|
||||||
|
final sound = await held.$2;
|
||||||
|
if (sound == null) {
|
||||||
|
// Retry on the next play.
|
||||||
|
if (identical(_slots[slot], held)) _slots.remove(slot);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (_disposed || !identical(_slots[slot], held)) return;
|
||||||
|
try {
|
||||||
|
_backend.play(sound, volume.clamp(0.0, 1.0));
|
||||||
|
} catch (e) {
|
||||||
|
_log.warning('sound $key: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Object?> _load(String key, Future<Uint8List> Function() wav) async {
|
||||||
|
try {
|
||||||
|
return await _backend.load('$key#${_loads++}', await wav());
|
||||||
|
} catch (e) {
|
||||||
|
_log.warning('sound $key: $e');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _unload(Future<Object?> sound) async {
|
||||||
|
try {
|
||||||
|
final s = await sound;
|
||||||
|
if (s != null && !_disposed) await _backend.unload(s);
|
||||||
|
} catch (e) {
|
||||||
|
_log.fine('unload: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Frees every sound and closes the audio device. Plays after it are
|
||||||
|
/// dropped.
|
||||||
|
Future<void> dispose() async {
|
||||||
|
if (_disposed) return;
|
||||||
|
_disposed = true;
|
||||||
|
_slots.clear();
|
||||||
|
final ready = _ready;
|
||||||
|
if (ready == null || !await ready) return;
|
||||||
|
try {
|
||||||
|
// Deinit frees the loaded sounds with the engine.
|
||||||
|
await _backend.deinit();
|
||||||
|
} catch (e) {
|
||||||
|
_log.warning('audio deinit: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
// First start of the renamed app (Starsync, app id dev.foxyz.starsync):
|
||||||
|
// copy what the old names left, never move, so a 1.2.x install keeps
|
||||||
|
// working next to it. Runs once (the marker file), then never again.
|
||||||
|
|
||||||
|
/// Written into the new support folder once the migration ran (whether or
|
||||||
|
/// not anything was found): `migratedFrom` (the old support folder or
|
||||||
|
/// null), `hiveFrom` (the folder the boxes came from or null), `boxes`,
|
||||||
|
/// `files`.
|
||||||
|
const migrationMarker = 'migration.json';
|
||||||
|
|
||||||
|
/// The Hive boxes the app opens, by name (settings, connect form, Files,
|
||||||
|
/// Jellyfin sign-ins, track choices). Only these leave the documents
|
||||||
|
/// folder, which other apps' boxes share.
|
||||||
|
const appHiveBoxes = ['settings', 'connect_form', 'files', 'jellyfin', 'track_prefs'];
|
||||||
|
|
||||||
|
/// Support folders of the old names for the new [support] folder, the
|
||||||
|
/// most likely first. Linux: `$XDG_DATA_HOME/moe.senkochan.watch_together`
|
||||||
|
/// (the GTK application id up to 1.2.x), then `watch_together` (the
|
||||||
|
/// executable name path_provider falls back to). Windows:
|
||||||
|
/// `%APPDATA%\com.example\watch_together` (company and product name of
|
||||||
|
/// the exe up to 1.2.x).
|
||||||
|
List<String> legacySupportDirs(String support, {bool? windows}) {
|
||||||
|
final win = windows ?? Platform.isWindows;
|
||||||
|
final sep = win ? r'\' : '/';
|
||||||
|
String parent(String p) {
|
||||||
|
final norm = p.endsWith(sep) ? p.substring(0, p.length - 1) : p;
|
||||||
|
final i = norm.lastIndexOf(sep);
|
||||||
|
return i <= 0 ? norm : norm.substring(0, i);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (win) return ['${parent(parent(support))}${sep}com.example${sep}watch_together'];
|
||||||
|
final share = parent(support);
|
||||||
|
return ['$share${sep}moe.senkochan.watch_together', '$share${sep}watch_together'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Copies the first existing [oldSupport] folder into [support] and the
|
||||||
|
/// [appHiveBoxes] (`.hive` and `.lock`) from [documents] into [hive],
|
||||||
|
/// skipping anything already there; the originals stay. Once per support
|
||||||
|
/// folder ([migrationMarker]). Returns one log line per thing copied
|
||||||
|
/// (paths and counts, never contents); empty when it ran before.
|
||||||
|
Future<List<String>> migrateLegacyData(
|
||||||
|
{required String support, required String hive, required List<String> oldSupport, String? documents}) async {
|
||||||
|
final sep = Platform.pathSeparator;
|
||||||
|
final marker = File('$support$sep$migrationMarker');
|
||||||
|
if (marker.existsSync()) return const [];
|
||||||
|
final lines = <String>[];
|
||||||
|
String? from;
|
||||||
|
var files = 0;
|
||||||
|
for (final old in oldSupport) {
|
||||||
|
final dir = Directory(old);
|
||||||
|
if (!dir.existsSync() || _same(old, support)) continue;
|
||||||
|
files = await _copyTree(dir, Directory(support));
|
||||||
|
from = old;
|
||||||
|
lines.add('migration: copied $files files from $old to $support');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
final boxes = <String>[];
|
||||||
|
if (documents != null && Directory(documents).existsSync() && !_same(documents, hive)) {
|
||||||
|
await Directory(hive).create(recursive: true);
|
||||||
|
for (final box in appHiveBoxes) {
|
||||||
|
for (final ext in const ['hive', 'lock']) {
|
||||||
|
final src = File('$documents$sep$box.$ext');
|
||||||
|
final dst = File('$hive$sep$box.$ext');
|
||||||
|
if (!src.existsSync() || dst.existsSync()) continue;
|
||||||
|
await src.copy(dst.path);
|
||||||
|
if (ext == 'hive') boxes.add(box);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (boxes.isNotEmpty) {
|
||||||
|
lines.add('migration: copied ${boxes.length} Hive boxes (${boxes.join(', ')}) from $documents to $hive');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (lines.isEmpty) lines.add('migration: no data from before the rename');
|
||||||
|
await Directory(support).create(recursive: true);
|
||||||
|
await marker.writeAsString(jsonEncode({
|
||||||
|
'migratedFrom': from,
|
||||||
|
'hiveFrom': boxes.isEmpty ? null : documents,
|
||||||
|
'boxes': boxes,
|
||||||
|
'files': files,
|
||||||
|
}));
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _same(String a, String b) {
|
||||||
|
try {
|
||||||
|
return FileSystemEntity.identicalSync(a, b);
|
||||||
|
} catch (_) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Files (File.copy keeps the mode on POSIX: cookies.txt stays 0600, yt-dlp
|
||||||
|
// executable) and symlinks as they are; existing targets win.
|
||||||
|
Future<int> _copyTree(Directory from, Directory to) async {
|
||||||
|
var n = 0;
|
||||||
|
await to.create(recursive: true);
|
||||||
|
await for (final e in from.list(recursive: true, followLinks: false)) {
|
||||||
|
final target = '${to.path}${e.path.substring(from.path.length)}';
|
||||||
|
if (e is Directory) {
|
||||||
|
await Directory(target).create(recursive: true);
|
||||||
|
} else if (await FileSystemEntity.type(target, followLinks: false) != FileSystemEntityType.notFound) {
|
||||||
|
continue;
|
||||||
|
} else if (e is Link) {
|
||||||
|
await Directory(File(target).parent.path).create(recursive: true);
|
||||||
|
await Link(target).create(await e.target());
|
||||||
|
} else if (e is File) {
|
||||||
|
await Directory(File(target).parent.path).create(recursive: true);
|
||||||
|
await e.copy(target);
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
File renamed without changes.
@@ -0,0 +1,35 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:path_provider/path_provider.dart';
|
||||||
|
|
||||||
|
import '../data_migration.dart';
|
||||||
|
import '../ports/app_dirs.dart';
|
||||||
|
|
||||||
|
/// The desktop's [AppDirsPort]: the app support folder from path_provider
|
||||||
|
/// (Linux `$XDG_DATA_HOME/dev.foxyz.starsync`, Windows
|
||||||
|
/// `%APPDATA%\foxyz\Starsync`); on the first start it copies the data of
|
||||||
|
/// the old names in ([migrateLegacyData]). Needs Flutter's binding.
|
||||||
|
class DesktopAppDirs implements AppDirsPort {
|
||||||
|
const DesktopAppDirs();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<AppDirs> resolve() async {
|
||||||
|
final support = (await getApplicationSupportDirectory()).path;
|
||||||
|
final base = AppDirs.fromEnv(support: support, env: const {});
|
||||||
|
List<String> migrated;
|
||||||
|
try {
|
||||||
|
String? documents;
|
||||||
|
try {
|
||||||
|
// Where Hive.initFlutter() kept the boxes up to 1.2.x.
|
||||||
|
documents = (await getApplicationDocumentsDirectory()).path;
|
||||||
|
} catch (_) {}
|
||||||
|
migrated = await migrateLegacyData(
|
||||||
|
support: support, hive: base.hive, oldSupport: legacySupportDirs(support), documents: documents);
|
||||||
|
} catch (e) {
|
||||||
|
migrated = ['migration failed: $e'];
|
||||||
|
}
|
||||||
|
final dirs = AppDirs.fromEnv(support: support, env: Platform.environment, migrated: migrated);
|
||||||
|
await Directory(dirs.hive).create(recursive: true);
|
||||||
|
return dirs;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:file_picker/file_picker.dart';
|
||||||
|
|
||||||
|
import '../../files/scanner.dart';
|
||||||
|
import '../ports/folder_access.dart';
|
||||||
|
import '../ports/url_opener.dart';
|
||||||
|
|
||||||
|
/// [FolderAccess] on a desktop file system: file_picker's dialogs, the
|
||||||
|
/// [scanFolder] walk, the file manager through [UrlOpener].
|
||||||
|
class DesktopFolders implements FolderAccess {
|
||||||
|
final UrlOpener urls;
|
||||||
|
const DesktopFolders(this.urls);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> pickFolder({required String dialogTitle}) => FilePicker.getDirectoryPath(dialogTitle: dialogTitle);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<String>> pickFiles({required String dialogTitle, required List<String> extensions}) async {
|
||||||
|
final files = await FilePicker.pickFiles(
|
||||||
|
dialogTitle: dialogTitle,
|
||||||
|
type: FileType.custom,
|
||||||
|
allowedExtensions: extensions,
|
||||||
|
);
|
||||||
|
return [for (final f in files) ?f.path];
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<FolderScan> scan(String dir) => scanFolder(dir);
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool folderExists(String dir) => Directory(dir).existsSync();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<FileStat> stat(String path) => File(path).stat();
|
||||||
|
|
||||||
|
// The file manager opens a folder path the way a browser opens a link.
|
||||||
|
@override
|
||||||
|
Future<bool> reveal(String dir) => urls.open(Uri.directory(dir).toString());
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||||
|
|
||||||
|
import '../desktop_entry.dart' show appId;
|
||||||
|
import '../ports/system_notifications.dart';
|
||||||
|
|
||||||
|
/// [SystemNotifications] on the desktop, through flutter_local_notifications'
|
||||||
|
/// platform plugins (used directly, not through its facade, so the platform
|
||||||
|
/// is picked by the OS and not by Flutter's target platform):
|
||||||
|
/// - Linux: `org.freedesktop.Notifications` over D-Bus (pure Dart), with the
|
||||||
|
/// app's icon (the bundled PNG, else the launcher entry's icon by name);
|
||||||
|
/// a click is the notification's default action.
|
||||||
|
/// - Windows: toast notifications (WinRT), the app's name and icon, a click
|
||||||
|
/// activates the app while it runs (an unpackaged app has no history).
|
||||||
|
/// Silent: the app plays its own sound for the same notice. Anything that
|
||||||
|
/// fails (no notification daemon, no session bus) is logged and dropped.
|
||||||
|
class DesktopNotifications implements SystemNotifications {
|
||||||
|
DesktopNotifications({this.appName = 'Starsync'});
|
||||||
|
|
||||||
|
final String appName;
|
||||||
|
void Function(String payload)? _onClick;
|
||||||
|
Future<bool>? _ready;
|
||||||
|
LinuxFlutterLocalNotificationsPlugin? _linux;
|
||||||
|
FlutterLocalNotificationsWindows? _windows;
|
||||||
|
// Tag -> id, so a notification with the same tag replaces the last one.
|
||||||
|
final _ids = <String, int>{};
|
||||||
|
int _next = 1;
|
||||||
|
|
||||||
|
@override
|
||||||
|
set onClick(void Function(String payload)? handler) => _onClick = handler;
|
||||||
|
|
||||||
|
void _clicked(NotificationResponse r) => _onClick?.call(r.payload ?? '');
|
||||||
|
|
||||||
|
/// The bundled 256 px icon next to the executable (a release or a
|
||||||
|
/// `flutter run` build), else the icon the launcher entry installed.
|
||||||
|
static LinuxNotificationIcon _linuxIcon() {
|
||||||
|
final exe = File(Platform.resolvedExecutable).parent.path;
|
||||||
|
final png = File('$exe/data/flutter_assets/assets/icon/icon_256.png');
|
||||||
|
return png.existsSync() ? FilePathLinuxIcon(png.path) : ThemeLinuxIcon(appId);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<bool> _init() => _ready ??= () async {
|
||||||
|
try {
|
||||||
|
if (Platform.isLinux) {
|
||||||
|
final p = _linux = LinuxFlutterLocalNotificationsPlugin();
|
||||||
|
return await p.initialize(
|
||||||
|
settings: LinuxInitializationSettings(defaultActionName: 'Open', defaultIcon: _linuxIcon()),
|
||||||
|
onDidReceiveNotificationResponse: _clicked,
|
||||||
|
) ??
|
||||||
|
false;
|
||||||
|
}
|
||||||
|
if (Platform.isWindows) {
|
||||||
|
final exe = File(Platform.resolvedExecutable).parent.path;
|
||||||
|
final icon = File('$exe/data/flutter_assets/assets/icon/icon_256.png');
|
||||||
|
final p = _windows = FlutterLocalNotificationsWindows();
|
||||||
|
return await p.initialize(
|
||||||
|
settings: WindowsInitializationSettings(
|
||||||
|
appName: appName,
|
||||||
|
appUserModelId: 'Foxyz.Starsync',
|
||||||
|
guid: '6c0f4b4e-3e8a-4b8e-9d0c-5a7f2b1e9c31',
|
||||||
|
iconPath: icon.existsSync() ? icon.path : null,
|
||||||
|
),
|
||||||
|
onDidReceiveNotificationResponse: _clicked,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('system notifications unavailable: $e');
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> show({required String title, required String body, String tag = '', String payload = ''}) async {
|
||||||
|
if (!await _init()) return;
|
||||||
|
final id = tag.isEmpty ? _next++ : _ids[tag] ??= _next++;
|
||||||
|
try {
|
||||||
|
if (_linux case final p?) {
|
||||||
|
await p.show(
|
||||||
|
id: id,
|
||||||
|
title: title,
|
||||||
|
body: body,
|
||||||
|
payload: payload,
|
||||||
|
notificationDetails: const LinuxNotificationDetails(suppressSound: true),
|
||||||
|
);
|
||||||
|
} else if (_windows case final p?) {
|
||||||
|
await p.show(
|
||||||
|
id: id,
|
||||||
|
title: title,
|
||||||
|
body: body,
|
||||||
|
payload: payload,
|
||||||
|
notificationDetails: WindowsNotificationDetails(audio: WindowsNotificationAudio.silent()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('system notification failed: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import '../../playback/yt_dlp_app.dart';
|
||||||
|
import '../ports/ports.dart';
|
||||||
|
import 'desktop_folders.dart';
|
||||||
|
import 'desktop_notifications.dart';
|
||||||
|
import 'desktop_shell.dart';
|
||||||
|
import 'desktop_urls.dart';
|
||||||
|
import 'media_kit_host.dart';
|
||||||
|
|
||||||
|
/// The desktop's [Ports].
|
||||||
|
Ports desktopPorts() {
|
||||||
|
const urls = DesktopUrls();
|
||||||
|
return Ports(
|
||||||
|
shell: DesktopShell(),
|
||||||
|
urls: urls,
|
||||||
|
folders: const DesktopFolders(urls),
|
||||||
|
links: AppYtDlp.instance,
|
||||||
|
notifications: DesktopNotifications(),
|
||||||
|
players: MediaKitHost(),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/widgets.dart';
|
||||||
|
import 'package:fox_utils/fox_utils.dart' show ClipboardX, DesktopDropX, DropTarget;
|
||||||
|
import 'package:hive_ce_flutter/hive_flutter.dart';
|
||||||
|
import 'package:window_manager/window_manager.dart';
|
||||||
|
|
||||||
|
import '../../state/settings.dart' show settingsBoxName;
|
||||||
|
import 'attention.dart';
|
||||||
|
import '../ports/shell_port.dart';
|
||||||
|
import 'window_memory.dart';
|
||||||
|
|
||||||
|
/// [ShellPort] on Linux and Windows: window_manager for the window,
|
||||||
|
/// [WindowMemory] for its size and place, the runner's channel for
|
||||||
|
/// attention, fox_utils for drops and the clipboard.
|
||||||
|
class DesktopShell implements ShellPort {
|
||||||
|
WindowMemory? _memory;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> start({required String title, required Future<void> Function() onCloseRequest}) async {
|
||||||
|
await windowManager.ensureInitialized();
|
||||||
|
await windowManager.setPreventClose(true);
|
||||||
|
final memory = _memory = WindowMemory(Hive.isBoxOpen(settingsBoxName) ? Hive.box(settingsBoxName) : null);
|
||||||
|
windowManager.addListener(_CloseGuard(onCloseRequest));
|
||||||
|
final windowOptions = WindowOptions(
|
||||||
|
size: memory.size,
|
||||||
|
minimumSize: const Size(160, 90),
|
||||||
|
center: !memory.hasPosition,
|
||||||
|
backgroundColor: const Color(0xFF000000),
|
||||||
|
titleBarStyle: TitleBarStyle.hidden,
|
||||||
|
title: title,
|
||||||
|
);
|
||||||
|
unawaited(windowManager.waitUntilReadyToShow(windowOptions, () async {
|
||||||
|
await memory.restore();
|
||||||
|
await windowManager.show();
|
||||||
|
await windowManager.focus();
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> setFullScreen(bool on) => windowManager.setFullScreen(on);
|
||||||
|
@override
|
||||||
|
Future<void> minimize() => windowManager.minimize();
|
||||||
|
@override
|
||||||
|
Future<bool> isMaximized() => windowManager.isMaximized();
|
||||||
|
@override
|
||||||
|
Future<void> maximize() => windowManager.maximize();
|
||||||
|
@override
|
||||||
|
Future<void> unmaximize() => windowManager.unmaximize();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void Function() watchMaximized(void Function(bool maximized) onChange) {
|
||||||
|
final l = _MaximizeWatch(onChange);
|
||||||
|
windowManager.addListener(l);
|
||||||
|
return () => windowManager.removeListener(l);
|
||||||
|
}
|
||||||
|
|
||||||
|
final _activity = <void Function(WindowActivity)>{};
|
||||||
|
|
||||||
|
@override
|
||||||
|
void Function() watchActivity(void Function(WindowActivity activity) onChange) {
|
||||||
|
final l = _ActivityWatch(onChange);
|
||||||
|
_activity.add(onChange);
|
||||||
|
windowManager.addListener(l);
|
||||||
|
return () {
|
||||||
|
_activity.remove(onChange);
|
||||||
|
windowManager.removeListener(l);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> startDragging() => windowManager.startDragging();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> requestClose() => windowManager.close();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> saveWindow() async => _memory?.save();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> hide() async {
|
||||||
|
// window_manager has no hide event: tell the watchers here.
|
||||||
|
for (final f in [..._activity]) {
|
||||||
|
f(WindowActivity.hidden);
|
||||||
|
}
|
||||||
|
await windowManager.hide();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> quit() async {
|
||||||
|
try {
|
||||||
|
await windowManager.setPreventClose(false);
|
||||||
|
await windowManager.close();
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('window close failed: $e');
|
||||||
|
await windowManager.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> focus() async {
|
||||||
|
try {
|
||||||
|
if (await windowManager.isMinimized()) await windowManager.restore();
|
||||||
|
if (!await windowManager.isVisible()) await windowManager.show();
|
||||||
|
await windowManager.focus();
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('window focus failed: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> requestAttention() => requestWindowAttention();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<Paste> readPaste() async {
|
||||||
|
var files = const <String>[];
|
||||||
|
String? text;
|
||||||
|
try {
|
||||||
|
files = await ClipboardX.readFiles();
|
||||||
|
} catch (_) {}
|
||||||
|
if (files.isEmpty) {
|
||||||
|
try {
|
||||||
|
text = await ClipboardX.readText();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
return (files: files, text: text);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget dropTarget({
|
||||||
|
Key? key,
|
||||||
|
bool enable = true,
|
||||||
|
VoidCallback? onEnter,
|
||||||
|
VoidCallback? onExit,
|
||||||
|
required void Function(List<String> paths, Offset at) onDrop,
|
||||||
|
required Widget child,
|
||||||
|
}) =>
|
||||||
|
DropTarget(
|
||||||
|
key: key,
|
||||||
|
enable: enable,
|
||||||
|
onDragEntered: onEnter == null ? null : (_) => onEnter(),
|
||||||
|
onDragExited: onExit == null ? null : (_) => onExit(),
|
||||||
|
onDragDone: (d) => onDrop(DesktopDropX.pathsOf(d.files), d.localPosition),
|
||||||
|
child: child,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close button / Alt+F4 run the orderly close instead.
|
||||||
|
class _CloseGuard with WindowListener {
|
||||||
|
final Future<void> Function() onClose;
|
||||||
|
_CloseGuard(this.onClose);
|
||||||
|
@override
|
||||||
|
void onWindowClose() => unawaited(onClose());
|
||||||
|
}
|
||||||
|
|
||||||
|
class _MaximizeWatch with WindowListener {
|
||||||
|
final void Function(bool) onChange;
|
||||||
|
_MaximizeWatch(this.onChange);
|
||||||
|
@override
|
||||||
|
void onWindowMaximize() => onChange(true);
|
||||||
|
@override
|
||||||
|
void onWindowUnmaximize() => onChange(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Focus, blur, minimise and restore as [WindowActivity] (a restored
|
||||||
|
/// window is shown; its focus event follows when it gets the keyboard).
|
||||||
|
class _ActivityWatch with WindowListener {
|
||||||
|
final void Function(WindowActivity) onChange;
|
||||||
|
_ActivityWatch(this.onChange);
|
||||||
|
@override
|
||||||
|
void onWindowFocus() => onChange(WindowActivity.focused);
|
||||||
|
@override
|
||||||
|
void onWindowBlur() => onChange(WindowActivity.unfocused);
|
||||||
|
@override
|
||||||
|
void onWindowMinimize() => onChange(WindowActivity.minimised);
|
||||||
|
@override
|
||||||
|
void onWindowRestore() => onChange(WindowActivity.unfocused);
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import '../ports/url_opener.dart';
|
||||||
|
|
||||||
|
/// [UrlOpener] without url_launcher: `xdg-open`, `open` or Windows'
|
||||||
|
/// `url.dll` handler.
|
||||||
|
class DesktopUrls implements UrlOpener {
|
||||||
|
const DesktopUrls();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> open(String url) async {
|
||||||
|
try {
|
||||||
|
final ProcessResult r;
|
||||||
|
if (Platform.isWindows) {
|
||||||
|
r = await Process.run('rundll32', ['url.dll,FileProtocolHandler', url]);
|
||||||
|
} else if (Platform.isMacOS) {
|
||||||
|
r = await Process.run('open', [url]);
|
||||||
|
} else {
|
||||||
|
r = await Process.run('xdg-open', [url]);
|
||||||
|
}
|
||||||
|
return r.exitCode == 0;
|
||||||
|
} catch (_) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,513 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:ffi' show Int8;
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:ffi/ffi.dart' show StringUtf8Pointer, malloc;
|
||||||
|
import 'package:flutter/widgets.dart';
|
||||||
|
import 'package:media_kit/media_kit.dart';
|
||||||
|
import 'package:media_kit_video/media_kit_video.dart';
|
||||||
|
import 'package:signals/signals.dart';
|
||||||
|
import 'package:sync_relay_core/core.dart' show LogThrottle, createLogger;
|
||||||
|
|
||||||
|
import '../../state/settings.dart';
|
||||||
|
import '../ports/player_host.dart';
|
||||||
|
|
||||||
|
// The desktop's players: media_kit over libmpv. Everything mpv-specific
|
||||||
|
// that is not about one media lives here: the cache and HTTP pins, hwdec,
|
||||||
|
// mpv's log level (media_kit has no API for it: `mpv_request_log_messages`
|
||||||
|
// on its handle), the render-mode probe and its diagnostics, mpv's log into
|
||||||
|
// the app log, and the order players are torn down in.
|
||||||
|
|
||||||
|
/// Read-ahead target: about two minutes rides out short outages and makes
|
||||||
|
/// skipping an intro instant.
|
||||||
|
const readAheadSecs = 150;
|
||||||
|
|
||||||
|
/// Forward demuxer cache of a session player. Holds [readAheadSecs] up to
|
||||||
|
/// ~14 Mbit/s (a 1.4 GB / 24 min file is ~8); higher bitrates get less
|
||||||
|
/// time. In RAM: `cache-on-disk=no` (media_kit sets it on without a
|
||||||
|
/// cache-dir, and mpv warned "Failed to create file cache." per open).
|
||||||
|
const sessionAheadBytes = 256 * 1024 * 1024;
|
||||||
|
|
||||||
|
/// Back buffer (media_kit sets it to bufferSize too): enough for a short
|
||||||
|
/// seek back without holding another 256 MiB.
|
||||||
|
const sessionBackBytes = 64 * 1024 * 1024;
|
||||||
|
|
||||||
|
/// The preload's forward cache: its first seconds and the container's
|
||||||
|
/// index, at little memory. Raised to [sessionAheadBytes] when promoted.
|
||||||
|
const preloadAheadBytes = 48 * 1024 * 1024;
|
||||||
|
const preloadBackBytes = 8 * 1024 * 1024;
|
||||||
|
|
||||||
|
/// mpv's `volume-max` (its default is 130): the volume controls go this
|
||||||
|
/// far, past 100 % amplified.
|
||||||
|
const mpvMaxVolume = 150;
|
||||||
|
|
||||||
|
/// mpv's log level for session players. media_kit drains mpv's log on the
|
||||||
|
/// UI thread one line at a time, so a chatty level (ffmpeg retrying a
|
||||||
|
/// refused request logs every attempt) can starve the UI: warnings and
|
||||||
|
/// errors only, except during the render-mode probe, which needs mpv's
|
||||||
|
/// verbose GL init lines.
|
||||||
|
const sessionLogLevel = 'warn';
|
||||||
|
|
||||||
|
/// ffmpeg's HTTP options (mpv `stream-lavf-o`, comma form): reconnect after
|
||||||
|
/// a dropped connection, also on a streamed (growing) relay response, and a
|
||||||
|
/// server error (5xx) while connecting; a refused request (4xx) fails at
|
||||||
|
/// once. At most 3 tries per read, 4 s apart at most.
|
||||||
|
const streamLavfOptions = 'reconnect_streamed=1,reconnect_on_http_error=5xx,'
|
||||||
|
'reconnect_delay_max=4,reconnect_max_retries=3';
|
||||||
|
|
||||||
|
/// mpv echoes numbers in its own format (`150` reads back `150.000000`).
|
||||||
|
bool pinMatches(String wanted, String got) {
|
||||||
|
if (wanted == got) return true;
|
||||||
|
final a = double.tryParse(wanted), b = double.tryParse(got);
|
||||||
|
return a != null && b != null && a == b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `VideoController` behind [video], for the `Video` widget (the only
|
||||||
|
/// media_kit use outside this file).
|
||||||
|
VideoController videoControllerOf(HostedVideo video) => (video as _MkVideo).controller;
|
||||||
|
|
||||||
|
final _mpvLog = createLogger('mpv');
|
||||||
|
|
||||||
|
class MediaKitHost implements PlayerHost {
|
||||||
|
/// The hwdec setting ([AppSettings.hwdec] by default).
|
||||||
|
final String? Function() _hwdecSetting;
|
||||||
|
MediaKitHost({String? Function()? hwdecSetting})
|
||||||
|
: _hwdecSetting = hwdecSetting ?? (() => AppSettings.instance.hwdec.peek());
|
||||||
|
|
||||||
|
final _live = <_MkPlayer>{};
|
||||||
|
final _renderMode = signal(RenderMode.unknown);
|
||||||
|
final _http = StreamController<String>.broadcast();
|
||||||
|
final _throttle = LogThrottle(burst: 5);
|
||||||
|
Future<void> _retiring = Future.value();
|
||||||
|
var _closing = false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
final List<String> pinMismatches = [];
|
||||||
|
|
||||||
|
@override
|
||||||
|
void init() => MediaKit.ensureInitialized();
|
||||||
|
|
||||||
|
@override
|
||||||
|
ReadonlySignal<RenderMode> get renderMode => _renderMode;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<String> get httpErrors => _http.stream;
|
||||||
|
|
||||||
|
@override
|
||||||
|
int get live => _live.length;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> get retiring => _retiring;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String? get hwdec {
|
||||||
|
final env = Platform.environment['SYNC_RELAY_HWDEC'];
|
||||||
|
if (env != null && env.isNotEmpty) return env;
|
||||||
|
return _hwdecSetting();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<HostedPlayer> create(PlayerRole role, {bool muted = false}) async {
|
||||||
|
if (_closing) throw StateError('closing: no new players');
|
||||||
|
final mk = _SyncPlayer(
|
||||||
|
configuration: switch (role) {
|
||||||
|
PlayerRole.session => PlayerConfiguration(
|
||||||
|
bufferSize: sessionAheadBytes,
|
||||||
|
libass: true,
|
||||||
|
vo: Platform.environment['SYNC_RELAY_VO'],
|
||||||
|
logLevel: MPVLogLevel.warn),
|
||||||
|
PlayerRole.preload => PlayerConfiguration(
|
||||||
|
bufferSize: preloadAheadBytes,
|
||||||
|
libass: true,
|
||||||
|
vo: Platform.environment['SYNC_RELAY_VO'],
|
||||||
|
logLevel: MPVLogLevel.error),
|
||||||
|
PlayerRole.thumbnail => const PlayerConfiguration(
|
||||||
|
vo: 'null', muted: true, osc: false, libass: false, title: 'thumbnail', bufferSize: 4 << 20),
|
||||||
|
});
|
||||||
|
final p = _MkPlayer(this, mk, role);
|
||||||
|
_live.add(p);
|
||||||
|
if (role != PlayerRole.thumbnail) {
|
||||||
|
p._logSub = p.logs.listen((l) => _route(p, l));
|
||||||
|
final mismatches = <String>[];
|
||||||
|
await _pinCache(p, role, mismatches);
|
||||||
|
if (await p.pin('volume-max', '$mpvMaxVolume') case final m?) mismatches.add(m);
|
||||||
|
if (muted || role == PlayerRole.preload) {
|
||||||
|
if (await p.pin('mute', 'yes') case final m?) mismatches.add(m);
|
||||||
|
}
|
||||||
|
if (role == PlayerRole.session) {
|
||||||
|
pinMismatches
|
||||||
|
..clear()
|
||||||
|
..addAll(mismatches);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> promote(HostedPlayer p) async {
|
||||||
|
final mk = p as _MkPlayer;
|
||||||
|
mk._role = PlayerRole.session;
|
||||||
|
mk.setLogLevel(sessionLogLevel);
|
||||||
|
final mismatches = <String>[];
|
||||||
|
if (await p.pin('mute', 'no') case final m?) mismatches.add(m);
|
||||||
|
await _pinCache(mk, PlayerRole.session, mismatches);
|
||||||
|
pinMismatches
|
||||||
|
..clear()
|
||||||
|
..addAll(mismatches);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pinCache(_MkPlayer p, PlayerRole role, List<String> out) async {
|
||||||
|
final session = role == PlayerRole.session;
|
||||||
|
for (final (k, v) in [
|
||||||
|
('demuxer-readahead-secs', '$readAheadSecs'),
|
||||||
|
('cache-secs', '$readAheadSecs'),
|
||||||
|
('demuxer-max-bytes', '${session ? sessionAheadBytes : preloadAheadBytes}'),
|
||||||
|
('demuxer-max-back-bytes', '${session ? sessionBackBytes : preloadBackBytes}'),
|
||||||
|
('cache-on-disk', 'no'),
|
||||||
|
if (hwdec case final h?) ('hwdec', h),
|
||||||
|
('stream-lavf-o', streamLavfOptions),
|
||||||
|
// Pages are resolved by the app's own yt-dlp (the media pipeline):
|
||||||
|
// mpv's Lua hook never runs one.
|
||||||
|
('ytdl', 'no'),
|
||||||
|
]) {
|
||||||
|
if (await p.pin(k, v) case final m?) out.add(m);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
HostedVideo video(HostedPlayer player, {bool probe = false}) {
|
||||||
|
final p = player as _MkPlayer;
|
||||||
|
if (probe) {
|
||||||
|
_logRenderEnv();
|
||||||
|
p.setLogLevel('v'); // back to the session level at the probe's end
|
||||||
|
}
|
||||||
|
// media_kit's video output sets hwdec itself on attach ('auto' unless
|
||||||
|
// configured), which used to override SYNC_RELAY_HWDEC.
|
||||||
|
final controller = VideoController(p.mk, configuration: VideoControllerConfiguration(hwdec: hwdec));
|
||||||
|
final v = _MkVideo(p, controller);
|
||||||
|
// mpv gets `vo=libmpv` before the output's render context exists; a
|
||||||
|
// media opened in between fails its video output ("No render context
|
||||||
|
// set") and plays black. Opens wait for the output (seen on X11, where
|
||||||
|
// the context comes up later, when joining with media already up).
|
||||||
|
p._videoReady = controller.platform.future
|
||||||
|
.then((_) {})
|
||||||
|
.timeout(const Duration(seconds: 5), onTimeout: () {})
|
||||||
|
.catchError((Object _) {});
|
||||||
|
if (probe) unawaited(_probeRender(p, v));
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ the log
|
||||||
|
|
||||||
|
// mpv's warnings and errors to the app log, a few per kind at a time (a
|
||||||
|
// refused request makes ffmpeg retry and warn on every try); ffmpeg's
|
||||||
|
// HTTP status to [httpErrors]; the GL init lines while probing.
|
||||||
|
void _route(_MkPlayer p, PlayerLogLine log) {
|
||||||
|
if (log.prefix == 'ffmpeg') {
|
||||||
|
final http = RegExp(r'HTTP error \d{3}.*').firstMatch(log.text);
|
||||||
|
if (http != null) _http.add(http[0]!.trim());
|
||||||
|
}
|
||||||
|
if (log.prefix == 'libmpv_render') {
|
||||||
|
if (_glInfo.hasMatch(log.text)) _mpvLog.info('render: [libmpv_render] ${log.text.trim()}');
|
||||||
|
if (log.text.contains('suspected software renderer')) {
|
||||||
|
_probeMode = RenderMode.softwareGl;
|
||||||
|
_renderMode.value = RenderMode.softwareGl;
|
||||||
|
} else if (log.text.startsWith('GL_VERSION') && p._probing && _probeMode == RenderMode.unknown) {
|
||||||
|
_probeMode = RenderMode.gpu;
|
||||||
|
_renderMode.value = RenderMode.gpu;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final level = log.level;
|
||||||
|
if (level != 'warn' && !log.isError) return;
|
||||||
|
final text = log.text.trim();
|
||||||
|
if (text.isEmpty) return;
|
||||||
|
final who = p.role == PlayerRole.preload ? 'preload ' : '';
|
||||||
|
final pass = _throttle.allow('$who${log.prefix} $level ${text.length > 40 ? text.substring(0, 40) : text}');
|
||||||
|
if (pass == null) return;
|
||||||
|
final line = '$pass$who[${log.prefix}] $text';
|
||||||
|
level == 'warn' ? _mpvLog.info(line) : _mpvLog.warning(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
// mpv's GL init lines (`GL_VENDOR='...'`, `Detected desktop OpenGL 4.6.`).
|
||||||
|
static final _glInfo =
|
||||||
|
RegExp(r'^\s*(GL_(VENDOR|RENDERER|VERSION|SHADING_LANGUAGE_VERSION)=|Detected (GLES|desktop OpenGL))');
|
||||||
|
|
||||||
|
// Once per app start: what decides how media_kit and mpv render (the
|
||||||
|
// display server, Flutter's and Mesa's overrides). Not secrets.
|
||||||
|
static bool _renderEnvLogged = false;
|
||||||
|
static void _logRenderEnv() {
|
||||||
|
if (_renderEnvLogged || !Platform.isLinux) return;
|
||||||
|
_renderEnvLogged = true;
|
||||||
|
const names = [
|
||||||
|
'XDG_SESSION_TYPE',
|
||||||
|
'WAYLAND_DISPLAY',
|
||||||
|
'DISPLAY',
|
||||||
|
'GDK_BACKEND',
|
||||||
|
'FLUTTER_LINUX_RENDERER',
|
||||||
|
'LIBGL_ALWAYS_SOFTWARE',
|
||||||
|
'__EGL_VENDOR_LIBRARY_FILENAMES',
|
||||||
|
];
|
||||||
|
final env = Platform.environment;
|
||||||
|
_mpvLog.info('render env: ${[for (final n in names) '$n=${env[n] ?? '-'}'].join(' ')}');
|
||||||
|
}
|
||||||
|
|
||||||
|
RenderMode _probeMode = RenderMode.unknown;
|
||||||
|
|
||||||
|
// media_kit's Linux/Windows video output creates mpv's render context
|
||||||
|
// while the controller is created: OpenGL when it can, else the software
|
||||||
|
// renderer, which never logs GL init (and ignores shaders). No GL line
|
||||||
|
// within 1.5 s of the output being up means software.
|
||||||
|
Future<void> _probeRender(_MkPlayer p, _MkVideo v) async {
|
||||||
|
p._probing = true;
|
||||||
|
_probeMode = RenderMode.unknown;
|
||||||
|
try {
|
||||||
|
await v.controller.platform.future;
|
||||||
|
await Future.delayed(const Duration(milliseconds: 1500));
|
||||||
|
} catch (_) {
|
||||||
|
return;
|
||||||
|
} finally {
|
||||||
|
p._probing = false;
|
||||||
|
if (!p.disposed) p.setLogLevel(sessionLogLevel);
|
||||||
|
}
|
||||||
|
if (p.disposed) return;
|
||||||
|
final mode = _probeMode;
|
||||||
|
if (mode != RenderMode.unknown) {
|
||||||
|
_renderMode.value = mode;
|
||||||
|
_mpvLog.info('render: ${mode.name} (${mode == RenderMode.gpu ? 'OpenGL on the GPU' : 'OpenGL on the CPU'})');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_renderMode.value = RenderMode.software;
|
||||||
|
_mpvLog.info("render: software (no GL init logged: media_kit's own fallback; "
|
||||||
|
'its reason is on stderr, "media_kit: VideoOutput: ..." when run from a terminal)');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Once per player, after its first frame: the decoder mpv picked; the
|
||||||
|
// first time per app start also mpv's and ffmpeg's versions.
|
||||||
|
static bool _versionsLogged = false;
|
||||||
|
Future<void> _logFirstFrame(_MkPlayer p) async {
|
||||||
|
try {
|
||||||
|
final current = await p.getProperty('hwdec-current');
|
||||||
|
final wanted = await p.getProperty('hwdec');
|
||||||
|
_mpvLog.info('render: first frame ${p.state.width}x${p.state.height}, '
|
||||||
|
'hwdec-current=${current.isEmpty ? 'no' : current} (hwdec=$wanted), mode ${_renderMode.peek().name}');
|
||||||
|
if (!_versionsLogged) {
|
||||||
|
_versionsLogged = true;
|
||||||
|
_mpvLog.info('render: ${await versions(p)}');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('first frame info: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> versions(HostedPlayer player) async {
|
||||||
|
try {
|
||||||
|
return '${await player.getProperty('mpv-version')}, ffmpeg ${await player.getProperty('ffmpeg-version')}';
|
||||||
|
} catch (_) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --------------------------------------------------------- tear-down
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> retire(HostedPlayer player) {
|
||||||
|
final p = player as _MkPlayer;
|
||||||
|
p._retired = true;
|
||||||
|
unawaited(p.mk.pause().catchError((_) {}));
|
||||||
|
return _retiring = () async {
|
||||||
|
await _settleUi();
|
||||||
|
await dispose(p);
|
||||||
|
}();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> dispose(HostedPlayer player) async {
|
||||||
|
final p = player as _MkPlayer;
|
||||||
|
if (!_live.remove(p)) return;
|
||||||
|
p._retired = true;
|
||||||
|
await p._logSub?.cancel();
|
||||||
|
try {
|
||||||
|
await p.mk.dispose();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> disposeAll({Duration each = const Duration(milliseconds: 1500)}) async {
|
||||||
|
_closing = true;
|
||||||
|
await Future.wait([
|
||||||
|
for (final p in _live.toList()) dispose(p).timeout(each).catchError((Object _) {}),
|
||||||
|
]);
|
||||||
|
_closing = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Two frames: one may already be mid-build when the view drops the
|
||||||
|
// output. Then the length of a route pop (the fullscreen route holds its
|
||||||
|
// own `Video` and leaves animated). Bounded, since a hidden window
|
||||||
|
// renders no frames; headless tests have no binding and skip it all.
|
||||||
|
static Future<void> _settleUi() async {
|
||||||
|
try {
|
||||||
|
for (var i = 0; i < 2; i++) {
|
||||||
|
await WidgetsBinding.instance.endOfFrame.timeout(const Duration(milliseconds: 300));
|
||||||
|
}
|
||||||
|
await Future.delayed(const Duration(milliseconds: 350));
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A [Player] whose public [seek] belongs to the user. media_kit's controls
|
||||||
|
/// call `player.seek`; with [onUserSeek] set those calls become explicit
|
||||||
|
/// events for the sync layer instead of moving mpv behind its back.
|
||||||
|
class _SyncPlayer extends Player {
|
||||||
|
_SyncPlayer({super.configuration});
|
||||||
|
|
||||||
|
void Function(Duration position)? onUserSeek;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> seek(Duration duration) async {
|
||||||
|
final hook = onUserSeek;
|
||||||
|
if (hook == null) return super.seek(duration);
|
||||||
|
hook(duration);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> syncSeek(Duration duration) => super.seek(duration);
|
||||||
|
}
|
||||||
|
|
||||||
|
class _MkPlayer implements HostedPlayer {
|
||||||
|
final MediaKitHost host;
|
||||||
|
final _SyncPlayer mk;
|
||||||
|
PlayerRole _role;
|
||||||
|
_MkPlayer(this.host, this.mk, this._role) {
|
||||||
|
_firstFrame = mk.stream.width.listen((w) {
|
||||||
|
if (w == null || w <= 0 || _role == PlayerRole.thumbnail) return;
|
||||||
|
unawaited(_firstFrame?.cancel());
|
||||||
|
unawaited(host._logFirstFrame(this));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
StreamSubscription<PlayerLogLine>? _logSub;
|
||||||
|
StreamSubscription<int?>? _firstFrame;
|
||||||
|
bool _probing = false;
|
||||||
|
bool _retired = false;
|
||||||
|
Future<void>? _videoReady; // set once a video output is attached
|
||||||
|
|
||||||
|
dynamic get _mpv => mk.platform;
|
||||||
|
|
||||||
|
@override
|
||||||
|
PlayerRole get role => _role;
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool get disposed => _retired;
|
||||||
|
|
||||||
|
@override
|
||||||
|
HostedPlayerState get state {
|
||||||
|
final s = mk.state;
|
||||||
|
return HostedPlayerState(
|
||||||
|
position: s.position,
|
||||||
|
duration: s.duration,
|
||||||
|
buffer: s.buffer,
|
||||||
|
volume: s.volume,
|
||||||
|
playing: s.playing,
|
||||||
|
completed: s.completed,
|
||||||
|
width: s.width,
|
||||||
|
height: s.height,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<Duration> get positionStream => mk.stream.position;
|
||||||
|
@override
|
||||||
|
Stream<Duration> get durationStream => mk.stream.duration;
|
||||||
|
@override
|
||||||
|
Stream<Duration> get bufferStream => mk.stream.buffer;
|
||||||
|
@override
|
||||||
|
Stream<double> get volumeStream => mk.stream.volume;
|
||||||
|
@override
|
||||||
|
Stream<bool> get completedStream => mk.stream.completed;
|
||||||
|
@override
|
||||||
|
Stream<int?> get widthStream => mk.stream.width;
|
||||||
|
@override
|
||||||
|
Stream<PlayerLogLine> get logs => mk.stream.log.map((l) => PlayerLogLine(l.prefix, l.level, l.text));
|
||||||
|
|
||||||
|
@override
|
||||||
|
void Function(Duration position)? get onUserSeek => mk.onUserSeek;
|
||||||
|
@override
|
||||||
|
set onUserSeek(void Function(Duration position)? f) => mk.onUserSeek = f;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> open(String url, {Map<String, String> headers = const {}, bool play = false}) async {
|
||||||
|
if (_videoReady case final ready?) await ready;
|
||||||
|
// An empty map, not null: media_kit caches headers per URI.
|
||||||
|
await mk.open(Media(url, httpHeaders: headers), play: play);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> play() => mk.play();
|
||||||
|
@override
|
||||||
|
Future<void> pause() => mk.pause();
|
||||||
|
@override
|
||||||
|
Future<void> stop() => mk.stop();
|
||||||
|
@override
|
||||||
|
Future<void> seek(Duration position) => mk.seek(position);
|
||||||
|
@override
|
||||||
|
Future<void> syncSeek(Duration position) => mk.syncSeek(position);
|
||||||
|
@override
|
||||||
|
Future<void> setRate(double rate) => mk.setRate(rate);
|
||||||
|
@override
|
||||||
|
Future<void> setVolume(double volume) => mk.setVolume(volume);
|
||||||
|
|
||||||
|
// media_kit has no public property API: a guarded dynamic call on
|
||||||
|
// `player.platform` (its NativePlayer).
|
||||||
|
@override
|
||||||
|
Future<void> setProperty(String name, String value) async => await _mpv?.setProperty(name, value);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String> getProperty(String name) async => '${await _mpv?.getProperty(name)}';
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> observeProperty(String name, Future<void> Function(String value) onChange) async =>
|
||||||
|
await _mpv?.observeProperty(name, onChange);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> command(List<String> args) async => await _mpv?.command(args);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> pin(String name, String value) async {
|
||||||
|
try {
|
||||||
|
await setProperty(name, value);
|
||||||
|
final got = await getProperty(name);
|
||||||
|
if (pinMatches(value, got)) return null;
|
||||||
|
debugPrint('pin $name=$value not applied, mpv has "$got"');
|
||||||
|
return '$name: $value -> $got';
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('pin $name=$value failed: $e');
|
||||||
|
return '$name: $value -> error $e';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// mpv_request_log_messages on media_kit's handle.
|
||||||
|
@override
|
||||||
|
void setLogLevel(String level) {
|
||||||
|
try {
|
||||||
|
final dynamic platform = mk.platform;
|
||||||
|
final name = level.toNativeUtf8();
|
||||||
|
try {
|
||||||
|
platform.mpv.mpv_request_log_messages(platform.ctx, name.cast<Int8>());
|
||||||
|
} finally {
|
||||||
|
malloc.free(name);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('mpv log level $level not set: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _MkVideo implements HostedVideo {
|
||||||
|
@override
|
||||||
|
final _MkPlayer player;
|
||||||
|
final VideoController controller;
|
||||||
|
_MkVideo(this.player, this.controller);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> get ready => controller.platform.future;
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
import 'dart:ui';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:hive_ce_flutter/hive_flutter.dart';
|
||||||
|
import 'package:screen_retriever/screen_retriever.dart';
|
||||||
|
import 'package:window_manager/window_manager.dart';
|
||||||
|
|
||||||
|
/// The window's size, position and maximized state across restarts (and
|
||||||
|
/// hot restarts), in the settings box. The size and position kept are
|
||||||
|
/// the normal (unmaximized) ones; fullscreen is never saved or restored.
|
||||||
|
/// Wayland lets no app place its own window, so there only the size and
|
||||||
|
/// maximized state come back (the compositor decides the position).
|
||||||
|
class WindowMemory with WindowListener {
|
||||||
|
static const _key = 'windowBounds';
|
||||||
|
static const defaultSize = Size(1280, 720);
|
||||||
|
|
||||||
|
// Null when the settings box failed to open: defaults, nothing saved.
|
||||||
|
final Box? _box;
|
||||||
|
Timer? _save;
|
||||||
|
WindowMemory(this._box);
|
||||||
|
|
||||||
|
static bool get _canPlace => !(Platform.isLinux && Platform.environment['WAYLAND_DISPLAY'] != null);
|
||||||
|
|
||||||
|
Map? get _saved => _box?.get(_key) is Map ? _box!.get(_key) as Map : null;
|
||||||
|
|
||||||
|
/// The size to open at: the last normal size, else [defaultSize].
|
||||||
|
Size get size {
|
||||||
|
final s = _saved;
|
||||||
|
final w = s?['w'], h = s?['h'];
|
||||||
|
return w is num && h is num && w >= 160 && h >= 90 ? Size(w.toDouble(), h.toDouble()) : defaultSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a saved position exists to place the window at (else center).
|
||||||
|
bool get hasPosition => _canPlace && _saved?['x'] is num && _saved?['y'] is num;
|
||||||
|
|
||||||
|
/// After the window shows: back to the saved position when it still
|
||||||
|
/// lands on a connected display, maximized when it was; then listens.
|
||||||
|
Future<void> restore() async {
|
||||||
|
final s = _saved;
|
||||||
|
try {
|
||||||
|
if (s != null && hasPosition) {
|
||||||
|
final rect = Offset((s['x'] as num).toDouble(), (s['y'] as num).toDouble()) & size;
|
||||||
|
if (await _onSomeDisplay(rect)) {
|
||||||
|
await windowManager.setPosition(rect.topLeft);
|
||||||
|
} else {
|
||||||
|
await windowManager.center();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (s?['max'] == true) await windowManager.maximize();
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('window restore failed: $e');
|
||||||
|
}
|
||||||
|
windowManager.addListener(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
// At least a 100×50 corner of the title area on a display's visible area.
|
||||||
|
static Future<bool> _onSomeDisplay(Rect r) async {
|
||||||
|
final grip = Rect.fromLTWH(r.left, r.top, r.width.clamp(0, 100).toDouble(), 50);
|
||||||
|
for (final d in await screenRetriever.getAllDisplays()) {
|
||||||
|
final area = (d.visiblePosition ?? Offset.zero) & (d.visibleSize ?? d.size);
|
||||||
|
if (area.overlaps(grip)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void _later() {
|
||||||
|
_save?.cancel();
|
||||||
|
_save = Timer(const Duration(milliseconds: 400), () => unawaited(save()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes the current state now (also on close).
|
||||||
|
Future<void> save() async {
|
||||||
|
_save?.cancel();
|
||||||
|
final box = _box;
|
||||||
|
if (box == null) return;
|
||||||
|
try {
|
||||||
|
if (await windowManager.isFullScreen() || await windowManager.isMinimized()) return;
|
||||||
|
final max = await windowManager.isMaximized();
|
||||||
|
final s = Map<String, Object?>.of((_saved ?? const {}).cast<String, Object?>());
|
||||||
|
s['max'] = max;
|
||||||
|
if (!max) {
|
||||||
|
final b = await windowManager.getBounds();
|
||||||
|
s['w'] = b.width;
|
||||||
|
s['h'] = b.height;
|
||||||
|
if (_canPlace) {
|
||||||
|
s['x'] = b.left;
|
||||||
|
s['y'] = b.top;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await box.put(_key, s);
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('window save failed: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onWindowResized() => _later();
|
||||||
|
@override
|
||||||
|
void onWindowMoved() => _later();
|
||||||
|
@override
|
||||||
|
void onWindowMaximize() => _later();
|
||||||
|
@override
|
||||||
|
void onWindowUnmaximize() => _later();
|
||||||
|
}
|
||||||
@@ -5,16 +5,24 @@ import 'package:sync_relay_core/core.dart' show findInstallRoot;
|
|||||||
|
|
||||||
/// The app's id: GTK's application id, so the Wayland `app_id` the
|
/// The app's id: GTK's application id, so the Wayland `app_id` the
|
||||||
/// compositor matches to [desktopFileName] for the window's icon.
|
/// compositor matches to [desktopFileName] for the window's icon.
|
||||||
const appId = 'moe.senkochan.watch_together';
|
const appId = 'dev.foxyz.starsync';
|
||||||
const desktopFileName = '$appId.desktop';
|
const desktopFileName = '$appId.desktop';
|
||||||
|
|
||||||
|
/// The app id up to 1.2.x: its entry and icons are removed (only those
|
||||||
|
/// exact files, which that version wrote).
|
||||||
|
const legacyAppId = 'moe.senkochan.watch_together';
|
||||||
|
|
||||||
|
const _iconSizes = [16, 32, 48, 64, 128, 256, 512];
|
||||||
|
|
||||||
/// Linux release installs (an unpacked tarball) carry no launcher entry, so
|
/// Linux release installs (an unpacked tarball) carry no launcher entry, so
|
||||||
/// Wayland shows a generic icon. On start: write the `.desktop` file into
|
/// Wayland shows a generic icon. On start: write the `.desktop` file into
|
||||||
/// `~/.local/share/applications` (Exec = this binary) and the icon into
|
/// `~/.local/share/applications` (Exec = this binary) and the icon into
|
||||||
/// the hicolor theme, only when something changed (a moved install, a new
|
/// the hicolor theme, only when something changed (a moved install, a new
|
||||||
/// icon). Never in debug runs; failures only log.
|
/// icon). The entry and icons of [legacyAppId] go. Never in debug runs
|
||||||
Future<void> installDesktopEntry({String? executable, String? dataHome, String? home}) async {
|
/// (unless [force], for tests); failures only log.
|
||||||
if (!Platform.isLinux || kDebugMode) return;
|
Future<void> installDesktopEntry(
|
||||||
|
{String? executable, String? dataHome, String? home, @visibleForTesting bool force = false}) async {
|
||||||
|
if (!Platform.isLinux || (kDebugMode && !force)) return;
|
||||||
try {
|
try {
|
||||||
final exe = executable ?? Platform.resolvedExecutable;
|
final exe = executable ?? Platform.resolvedExecutable;
|
||||||
final root = findInstallRoot(exe, windows: false);
|
final root = findInstallRoot(exe, windows: false);
|
||||||
@@ -22,7 +30,8 @@ Future<void> installDesktopEntry({String? executable, String? dataHome, String?
|
|||||||
final share = dataHome ?? Platform.environment['XDG_DATA_HOME'] ??
|
final share = dataHome ?? Platform.environment['XDG_DATA_HOME'] ??
|
||||||
'${home ?? Platform.environment['HOME']}/.local/share';
|
'${home ?? Platform.environment['HOME']}/.local/share';
|
||||||
final icons = '${root.path}/data/flutter_assets/assets/icon';
|
final icons = '${root.path}/data/flutter_assets/assets/icon';
|
||||||
for (final size in const [16, 32, 48, 64, 128, 256, 512]) {
|
await _removeLegacy(share);
|
||||||
|
for (final size in _iconSizes) {
|
||||||
final src = File('$icons/icon_$size.png');
|
final src = File('$icons/icon_$size.png');
|
||||||
if (!src.existsSync()) continue;
|
if (!src.existsSync()) continue;
|
||||||
final dst = File('$share/icons/hicolor/${size}x$size/apps/$appId.png');
|
final dst = File('$share/icons/hicolor/${size}x$size/apps/$appId.png');
|
||||||
@@ -40,6 +49,21 @@ Future<void> installDesktopEntry({String? executable, String? dataHome, String?
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _removeLegacy(String share) async {
|
||||||
|
for (final f in [
|
||||||
|
File('$share/applications/$legacyAppId.desktop'),
|
||||||
|
for (final size in _iconSizes) File('$share/icons/hicolor/${size}x$size/apps/$legacyAppId.png'),
|
||||||
|
]) {
|
||||||
|
if (!f.existsSync()) continue;
|
||||||
|
try {
|
||||||
|
await f.delete();
|
||||||
|
debugPrint('desktop entry: removed ${f.path}');
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('desktop entry: cannot remove ${f.path}: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@visibleForTesting
|
@visibleForTesting
|
||||||
String desktopEntryText(String exe) => '''[Desktop Entry]
|
String desktopEntryText(String exe) => '''[Desktop Entry]
|
||||||
Type=Application
|
Type=Application
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
/// The environment variable that picks a separate profile (DEVELOPMENT.md
|
||||||
|
/// "Dev loop": two instances on one machine).
|
||||||
|
const profileEnv = 'STARSYNC_PROFILE';
|
||||||
|
|
||||||
|
/// Where the app keeps its own files, resolved once in `main` through an
|
||||||
|
/// [AppDirsPort] and handed on from there.
|
||||||
|
///
|
||||||
|
/// Everything lives in the app support folder: Hive's boxes in
|
||||||
|
/// `<app support>/hive`, the logs in `<app support>/logs`. With
|
||||||
|
/// `STARSYNC_PROFILE=<name>` (letters, digits, `-`, `_`; at most 32) the
|
||||||
|
/// per-install data moves to `<app support>/profiles/<name>/`: the Hive
|
||||||
|
/// boxes (settings and so the profile, connect form, window bounds,
|
||||||
|
/// folders, Jellyfin sign-ins; the client id from restructure step 1 on)
|
||||||
|
/// under `hive/`, the logs under `logs/`. Downloads and caches stay
|
||||||
|
/// shared: yt-dlp and its cookies, the extracted shaders, thumbnails, the
|
||||||
|
/// AniList cache.
|
||||||
|
class AppDirs {
|
||||||
|
/// The profile name; null for the normal app.
|
||||||
|
final String? profile;
|
||||||
|
/// The app support folder (yt-dlp, shaders; Hive and logs without a
|
||||||
|
/// profile).
|
||||||
|
final String support;
|
||||||
|
/// Hive's folder.
|
||||||
|
final String hive;
|
||||||
|
/// The app's log folder.
|
||||||
|
final String logs;
|
||||||
|
/// What resolving copied over from before the rename, one line each
|
||||||
|
/// (paths and counts), for the log once it is open.
|
||||||
|
final List<String> migrated;
|
||||||
|
|
||||||
|
const AppDirs(
|
||||||
|
{required this.profile,
|
||||||
|
required this.support,
|
||||||
|
required this.hive,
|
||||||
|
required this.logs,
|
||||||
|
this.migrated = const []});
|
||||||
|
|
||||||
|
/// The layout for [support] (the app support folder) and [env]; an
|
||||||
|
/// invalid profile name is ignored ([invalidProfile] says which).
|
||||||
|
static AppDirs fromEnv(
|
||||||
|
{required String support, required Map<String, String> env, List<String> migrated = const []}) {
|
||||||
|
final sep = Platform.pathSeparator;
|
||||||
|
final name = validProfile(env[profileEnv]);
|
||||||
|
final root = name == null ? support : '$support${sep}profiles$sep$name';
|
||||||
|
return AppDirs(
|
||||||
|
profile: name, support: support, hive: '$root${sep}hive', logs: '$root${sep}logs', migrated: migrated);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [raw] when it is a usable profile name, else null.
|
||||||
|
static String? validProfile(String? raw) {
|
||||||
|
final v = raw?.trim() ?? '';
|
||||||
|
return RegExp(r'^[A-Za-z0-9_-]{1,32}$').hasMatch(v) ? v : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The env value when it is set but not a usable name (for a warning).
|
||||||
|
static String? invalidProfile(Map<String, String> env) {
|
||||||
|
final raw = env[profileEnv];
|
||||||
|
return raw != null && raw.trim().isNotEmpty && validProfile(raw) == null ? raw : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finds the app's folders on this platform (and, the first time, brings
|
||||||
|
/// over the data of the names before the rename).
|
||||||
|
abstract interface class AppDirsPort {
|
||||||
|
/// The layout for this process; its Hive folder exists afterwards.
|
||||||
|
Future<AppDirs> resolve();
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import 'dart:io' show FileStat;
|
||||||
|
|
||||||
|
import '../../files/scanner.dart' show FolderScan;
|
||||||
|
|
||||||
|
/// The user's folders and files: picking them, listing videos, looking a
|
||||||
|
/// path up. Paths for now; a platform without them (Android's tree URIs)
|
||||||
|
/// brings its own implementation.
|
||||||
|
abstract interface class FolderAccess {
|
||||||
|
/// The system folder dialog; null when cancelled.
|
||||||
|
Future<String?> pickFolder({required String dialogTitle});
|
||||||
|
|
||||||
|
/// The system file dialog limited to [extensions]; the picked paths
|
||||||
|
/// (empty when cancelled).
|
||||||
|
Future<List<String>> pickFiles({required String dialogTitle, required List<String> extensions});
|
||||||
|
|
||||||
|
/// The videos under [dir] (see [FolderScan]); never throws.
|
||||||
|
Future<FolderScan> scan(String dir);
|
||||||
|
|
||||||
|
/// Whether the folder [dir] exists.
|
||||||
|
bool folderExists(String dir);
|
||||||
|
|
||||||
|
/// Size and dates of [path]; throws when it is gone.
|
||||||
|
Future<FileStat> stat(String path);
|
||||||
|
|
||||||
|
/// Shows the folder [dir] in the file manager; false when nothing
|
||||||
|
/// opened it.
|
||||||
|
Future<bool> reveal(String dir);
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import 'package:sync_relay_core/core.dart' show LinkProbe, YtDlp;
|
||||||
|
|
||||||
|
/// Web page links: what they are and how they play, through the app's
|
||||||
|
/// yt-dlp (a process on desktop).
|
||||||
|
abstract interface class LinkResolver {
|
||||||
|
/// The yt-dlp behind it (relaying a link, cookies, the hosted server's
|
||||||
|
/// shared folder).
|
||||||
|
Future<YtDlp> get ytDlp;
|
||||||
|
|
||||||
|
/// Gets it ready in the background (download on first run, updates).
|
||||||
|
void warmUp();
|
||||||
|
|
||||||
|
/// This device opens web pages itself (the media plan's `resolve`
|
||||||
|
/// capability). Desktop: always (yt-dlp is downloaded when first
|
||||||
|
/// needed); a device without it gets pages passed on by someone else.
|
||||||
|
bool get resolvesLinks;
|
||||||
|
|
||||||
|
/// What [url] is, remembered for a while ([keep]); [fresh] asks again.
|
||||||
|
Future<LinkProbe> probe(String url, {Duration keep, bool fresh});
|
||||||
|
|
||||||
|
/// [url] no longer needs keeping longer than usual.
|
||||||
|
void release(String url);
|
||||||
|
}
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:signals/signals.dart';
|
||||||
|
|
||||||
|
// The media players as the app sees them: mpv instances, their video
|
||||||
|
// outputs, how the video is rendered, mpv's log and the order players are
|
||||||
|
// torn down in. Desktop: media_kit over libmpv
|
||||||
|
// (`platform/desktop/media_kit_host.dart`); nothing else in the app
|
||||||
|
// touches media_kit except the `Video` widget glue.
|
||||||
|
|
||||||
|
/// How the video output renders (shaders need [gpu]).
|
||||||
|
enum RenderMode {
|
||||||
|
unknown,
|
||||||
|
|
||||||
|
/// OpenGL on a real GPU: shaders work.
|
||||||
|
gpu,
|
||||||
|
|
||||||
|
/// OpenGL on a software rasterizer (llvmpipe): shaders crawl.
|
||||||
|
softwareGl,
|
||||||
|
|
||||||
|
/// The video output's own software fallback: shaders are ignored.
|
||||||
|
software,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a player is for: its cache, log level and log routing.
|
||||||
|
enum PlayerRole {
|
||||||
|
/// The session's player (and a fresh one per media): full cache, mpv log
|
||||||
|
/// at `warn` into the app log.
|
||||||
|
session,
|
||||||
|
|
||||||
|
/// The hidden player holding what plays next: small cache, muted, log
|
||||||
|
/// at `error`.
|
||||||
|
preload,
|
||||||
|
|
||||||
|
/// A poster frame for Files: no audio or video output, no cache, no log.
|
||||||
|
thumbnail,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One line of mpv's log.
|
||||||
|
class PlayerLogLine {
|
||||||
|
final String prefix;
|
||||||
|
final String level;
|
||||||
|
final String text;
|
||||||
|
const PlayerLogLine(this.prefix, this.level, this.text);
|
||||||
|
|
||||||
|
bool get isError => level == 'error' || level == 'fatal';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A snapshot of a player's state.
|
||||||
|
class HostedPlayerState {
|
||||||
|
final Duration position;
|
||||||
|
final Duration duration;
|
||||||
|
|
||||||
|
/// End of the cached range (mpv `demuxer-cache-time`).
|
||||||
|
final Duration buffer;
|
||||||
|
final double volume;
|
||||||
|
final bool playing;
|
||||||
|
|
||||||
|
/// At the end of the file.
|
||||||
|
final bool completed;
|
||||||
|
final int? width;
|
||||||
|
final int? height;
|
||||||
|
const HostedPlayerState({
|
||||||
|
this.position = Duration.zero,
|
||||||
|
this.duration = Duration.zero,
|
||||||
|
this.buffer = Duration.zero,
|
||||||
|
this.volume = 100,
|
||||||
|
this.playing = false,
|
||||||
|
this.completed = false,
|
||||||
|
this.width,
|
||||||
|
this.height,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One mpv player. Each media gets its own (see ARCHITECTURE "Player
|
||||||
|
/// lifecycle"); [PlayerHost.retire] / [PlayerHost.disposeAll] end it.
|
||||||
|
abstract interface class HostedPlayer {
|
||||||
|
PlayerRole get role;
|
||||||
|
HostedPlayerState get state;
|
||||||
|
Stream<Duration> get positionStream;
|
||||||
|
Stream<Duration> get durationStream;
|
||||||
|
Stream<Duration> get bufferStream;
|
||||||
|
Stream<double> get volumeStream;
|
||||||
|
Stream<bool> get completedStream;
|
||||||
|
Stream<int?> get widthStream;
|
||||||
|
|
||||||
|
/// mpv's log lines at the player's level.
|
||||||
|
Stream<PlayerLogLine> get logs;
|
||||||
|
|
||||||
|
/// The player is gone (disposed or being disposed): commands do nothing.
|
||||||
|
bool get disposed;
|
||||||
|
|
||||||
|
/// Seeks from the video widget's own controls land here instead of in
|
||||||
|
/// mpv when set ([seek] goes through it too); [syncSeek] always moves
|
||||||
|
/// mpv.
|
||||||
|
void Function(Duration position)? onUserSeek;
|
||||||
|
|
||||||
|
/// Opens [url] (with [headers] on every request), paused unless [play].
|
||||||
|
Future<void> open(String url, {Map<String, String> headers = const {}, bool play = false});
|
||||||
|
Future<void> play();
|
||||||
|
Future<void> pause();
|
||||||
|
Future<void> stop();
|
||||||
|
|
||||||
|
/// A user seek: through [onUserSeek] when set, else [syncSeek].
|
||||||
|
Future<void> seek(Duration position);
|
||||||
|
|
||||||
|
/// Moves mpv (sync corrections, scrub preview).
|
||||||
|
Future<void> syncSeek(Duration position);
|
||||||
|
Future<void> setRate(double rate);
|
||||||
|
Future<void> setVolume(double volume);
|
||||||
|
Future<void> setProperty(String name, String value);
|
||||||
|
Future<String> getProperty(String name);
|
||||||
|
Future<void> observeProperty(String name, Future<void> Function(String value) onChange);
|
||||||
|
Future<void> command(List<String> args);
|
||||||
|
|
||||||
|
/// Sets [name] and reads it back: null when mpv took [value], else
|
||||||
|
/// `name: value -> got` (mpv ignores invalid values silently).
|
||||||
|
Future<String?> pin(String name, String value);
|
||||||
|
|
||||||
|
/// mpv's log level for this player (`warn`, `v`, ...).
|
||||||
|
void setLogLevel(String level);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A player's video output (a texture the `Video` widget shows).
|
||||||
|
abstract interface class HostedVideo {
|
||||||
|
HostedPlayer get player;
|
||||||
|
|
||||||
|
/// Completes once the output is up (its texture registered).
|
||||||
|
Future<void> get ready;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates, owns and disposes the app's players. One per app (the
|
||||||
|
/// composition root's `Ports`); tests make their own.
|
||||||
|
abstract interface class PlayerHost {
|
||||||
|
/// Once at start, before any player.
|
||||||
|
void init();
|
||||||
|
|
||||||
|
/// A new player for [role], set up before it is returned to the caller's
|
||||||
|
/// first await: cache, pins ([pinMismatches]), hwdec, log level.
|
||||||
|
Future<HostedPlayer> create(PlayerRole role, {bool muted = false});
|
||||||
|
|
||||||
|
/// [player] (a preload) becomes a session player: unmuted, the full
|
||||||
|
/// cache pins, the session's log level.
|
||||||
|
Future<void> promote(HostedPlayer player);
|
||||||
|
|
||||||
|
/// [player]'s video output, with the hwdec policy. [probe]: listen to
|
||||||
|
/// mpv's render init to learn [renderMode] (the first output of an app
|
||||||
|
/// start).
|
||||||
|
HostedVideo video(HostedPlayer player, {bool probe = false});
|
||||||
|
|
||||||
|
/// How video renders, as last learned (kept after leaving).
|
||||||
|
ReadonlySignal<RenderMode> get renderMode;
|
||||||
|
|
||||||
|
/// mpv `hwdec` for new players: env `SYNC_RELAY_HWDEC` wins over the
|
||||||
|
/// setting (Windows' auto is `auto-copy`).
|
||||||
|
String? get hwdec;
|
||||||
|
|
||||||
|
/// Pins that did not take on the last session player created.
|
||||||
|
List<String> get pinMismatches;
|
||||||
|
|
||||||
|
/// ffmpeg's HTTP errors (`HTTP error 403 Forbidden`), from whichever
|
||||||
|
/// player ffmpeg logs through (one per process).
|
||||||
|
Stream<String> get httpErrors;
|
||||||
|
|
||||||
|
/// `mpv-version` and `ffmpeg-version` of [player], for diagnostics.
|
||||||
|
Future<String?> versions(HostedPlayer player);
|
||||||
|
|
||||||
|
/// Ends [player] once the view let go of its texture (two frames and a
|
||||||
|
/// route pop); at most one retiring player lingers, a new [create] of a
|
||||||
|
/// session player waits for it ([retiring]).
|
||||||
|
Future<void> retire(HostedPlayer player);
|
||||||
|
|
||||||
|
/// The last retire, until done.
|
||||||
|
Future<void> get retiring;
|
||||||
|
|
||||||
|
/// Disposes [player] at once (no view showed it).
|
||||||
|
Future<void> dispose(HostedPlayer player);
|
||||||
|
|
||||||
|
/// App close: every live player goes, each bounded by [each], before
|
||||||
|
/// the engine does (a live mpv calls back into a dead isolate).
|
||||||
|
Future<void> disposeAll({Duration each});
|
||||||
|
|
||||||
|
/// Live players, for tests and the close.
|
||||||
|
int get live;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [log] says the media could not be opened: before a [duration] is known,
|
||||||
|
/// mpv's fatal "nothing to play" or a demuxer error.
|
||||||
|
bool mpvLoadFailed(PlayerLogLine log, Duration duration) {
|
||||||
|
return duration == Duration.zero &&
|
||||||
|
((log.prefix == 'cplayer' && log.level == 'fatal') || (log.prefix == 'demux' && log.level == 'error'));
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import 'folder_access.dart';
|
||||||
|
import 'link_resolver.dart';
|
||||||
|
import 'player_host.dart';
|
||||||
|
import 'shell_port.dart';
|
||||||
|
import 'system_notifications.dart';
|
||||||
|
import 'url_opener.dart';
|
||||||
|
|
||||||
|
export 'app_dirs.dart';
|
||||||
|
export 'folder_access.dart';
|
||||||
|
export 'link_resolver.dart';
|
||||||
|
export 'player_host.dart';
|
||||||
|
export 'shell_port.dart';
|
||||||
|
export 'system_notifications.dart';
|
||||||
|
export 'url_opener.dart';
|
||||||
|
|
||||||
|
/// The platform as the app sees it: one set, made in the composition
|
||||||
|
/// root ([AppGraph]) and handed on from there.
|
||||||
|
class Ports {
|
||||||
|
final ShellPort shell;
|
||||||
|
final UrlOpener urls;
|
||||||
|
final FolderAccess folders;
|
||||||
|
final LinkResolver links;
|
||||||
|
final SystemNotifications notifications;
|
||||||
|
/// The media players (mpv): created, rendered and disposed here.
|
||||||
|
final PlayerHost players;
|
||||||
|
const Ports({
|
||||||
|
required this.shell,
|
||||||
|
required this.urls,
|
||||||
|
required this.folders,
|
||||||
|
required this.links,
|
||||||
|
required this.notifications,
|
||||||
|
required this.players,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import 'package:flutter/widgets.dart';
|
||||||
|
|
||||||
|
import 'window_activity.dart';
|
||||||
|
|
||||||
|
export 'window_activity.dart';
|
||||||
|
|
||||||
|
/// What the clipboard holds for a paste: its files, else its text.
|
||||||
|
typedef Paste = ({List<String> files, String? text});
|
||||||
|
|
||||||
|
/// The app window and what the desktop hands it (drops, pastes). The
|
||||||
|
/// desktop implementation wraps window_manager and fox_utils
|
||||||
|
/// ([DesktopShell]); another platform brings its own.
|
||||||
|
abstract interface class ShellPort {
|
||||||
|
/// Before the first frame: the window shown at its remembered size and
|
||||||
|
/// place; a close request (close button, Alt+F4) runs [onCloseRequest]
|
||||||
|
/// instead of closing.
|
||||||
|
Future<void> start({required String title, required Future<void> Function() onCloseRequest});
|
||||||
|
|
||||||
|
Future<void> setFullScreen(bool on);
|
||||||
|
Future<void> minimize();
|
||||||
|
Future<bool> isMaximized();
|
||||||
|
Future<void> maximize();
|
||||||
|
Future<void> unmaximize();
|
||||||
|
|
||||||
|
/// Calls [onChange] whenever the window is maximized or restored;
|
||||||
|
/// returns the call that stops it.
|
||||||
|
void Function() watchMaximized(void Function(bool maximized) onChange);
|
||||||
|
|
||||||
|
/// Calls [onChange] whenever the window gains or loses the focus, is
|
||||||
|
/// minimised, restored or hidden; returns the call that stops it.
|
||||||
|
void Function() watchActivity(void Function(WindowActivity activity) onChange);
|
||||||
|
|
||||||
|
/// Moves the window with the pointer (a press on the title area).
|
||||||
|
Future<void> startDragging();
|
||||||
|
|
||||||
|
/// Asks to close the window: the same path as the close button.
|
||||||
|
Future<void> requestClose();
|
||||||
|
|
||||||
|
/// The way out: remembers the window, hides it ([hide]), and later
|
||||||
|
/// closes it for good ([quit]).
|
||||||
|
Future<void> saveWindow();
|
||||||
|
Future<void> hide();
|
||||||
|
Future<void> quit();
|
||||||
|
|
||||||
|
/// Brings the window up and gives it the focus (restored when
|
||||||
|
/// minimised, shown when hidden): a click on a system notification.
|
||||||
|
Future<void> focus();
|
||||||
|
|
||||||
|
/// Points the desktop at the window when it is not focused (taskbar
|
||||||
|
/// flash, urgency hint); nothing when it is.
|
||||||
|
Future<void> requestAttention();
|
||||||
|
|
||||||
|
/// The clipboard's files, else its text (Ctrl+V outside a text field).
|
||||||
|
Future<Paste> readPaste();
|
||||||
|
|
||||||
|
/// [child] taking dropped files ([onDrop]: their paths and where they
|
||||||
|
/// landed); [enable] off lets drops through.
|
||||||
|
Widget dropTarget({
|
||||||
|
Key? key,
|
||||||
|
bool enable = true,
|
||||||
|
VoidCallback? onEnter,
|
||||||
|
VoidCallback? onExit,
|
||||||
|
required void Function(List<String> paths, Offset at) onDrop,
|
||||||
|
required Widget child,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
/// Notifications outside the window (the desktop's notification center,
|
||||||
|
/// Android's shade). The Notifier decides what goes out here (see
|
||||||
|
/// `noticeFor`); the port only shows them and reports clicks.
|
||||||
|
abstract interface class SystemNotifications {
|
||||||
|
/// Shows [title] / [body] with the app's name and icon; one with the
|
||||||
|
/// same [tag] replaces it. [payload] comes back to [onClick].
|
||||||
|
Future<void> show({required String title, required String body, String tag = '', String payload = ''});
|
||||||
|
|
||||||
|
/// Called with a notification's payload when the user clicks it (set
|
||||||
|
/// once, by the Notifier).
|
||||||
|
set onClick(void Function(String payload)? handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shows nothing (tests, platforms without one).
|
||||||
|
class NoSystemNotifications implements SystemNotifications {
|
||||||
|
const NoSystemNotifications();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> show({required String title, required String body, String tag = '', String payload = ''}) async {}
|
||||||
|
|
||||||
|
@override
|
||||||
|
set onClick(void Function(String payload)? handler) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
/// Opens links outside the app.
|
||||||
|
abstract interface class UrlOpener {
|
||||||
|
/// Opens [url] with the system's handler (a browser for web links, the
|
||||||
|
/// file manager for a `file:` folder); false when nothing opened it.
|
||||||
|
Future<bool> open(String url);
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
/// Where the app window stands ([ShellPort.watchActivity]): auto sit-out
|
||||||
|
/// and the Notifier (system notifications while it is not focused) read
|
||||||
|
/// it. Pure Dart.
|
||||||
|
enum WindowActivity {
|
||||||
|
/// The window has the keyboard focus.
|
||||||
|
focused,
|
||||||
|
|
||||||
|
/// Shown, but another window has the focus.
|
||||||
|
unfocused,
|
||||||
|
|
||||||
|
/// Minimised to the taskbar.
|
||||||
|
minimised,
|
||||||
|
|
||||||
|
/// Hidden (closing, or a platform that hides instead of minimising).
|
||||||
|
hidden;
|
||||||
|
|
||||||
|
/// Not in front of the user: notices go out as system notifications.
|
||||||
|
bool get background => this != focused;
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart' show debugPrint;
|
||||||
|
|
||||||
|
import '../app/app_graph.dart';
|
||||||
|
import 'app_shutdown.dart';
|
||||||
|
import 'ports/player_host.dart';
|
||||||
|
|
||||||
|
// The close smoke run (CI, `tool/smoke_windows.ps1` / `tool/smoke_linux.sh`):
|
||||||
|
// env `STARSYNC_SMOKE=<media file>` makes the app, once up, open that file
|
||||||
|
// in a session player with a video output through the media pipeline,
|
||||||
|
// play a second and close the normal way ([shutDownApp]). Progress goes to
|
||||||
|
// `STARSYNC_SMOKE_OUT` (one line per step: `start`, `opened <ms> render=<mode>`,
|
||||||
|
// `closing`, or `skip <why>` / `fail <why>`), so the script can tell a
|
||||||
|
// runner that cannot show a window (skip) from a close that hangs or
|
||||||
|
// leaves a process behind (fail).
|
||||||
|
|
||||||
|
/// The smoke run's media, or null for a normal start.
|
||||||
|
String? get smokeMedia {
|
||||||
|
final m = Platform.environment['STARSYNC_SMOKE'];
|
||||||
|
return m == null || m.isEmpty ? null : m;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> runSmoke(AppGraph graph, String media) async {
|
||||||
|
final outPath = Platform.environment['STARSYNC_SMOKE_OUT'];
|
||||||
|
void step(String line) {
|
||||||
|
debugPrint('smoke: $line'); // into the app log too
|
||||||
|
if (outPath == null || outPath.isEmpty) return;
|
||||||
|
try {
|
||||||
|
File(outPath).writeAsStringSync('$line\n', mode: FileMode.append, flush: true);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
step('start');
|
||||||
|
final sw = Stopwatch()..start();
|
||||||
|
final pipe = graph.coordinator.media;
|
||||||
|
try {
|
||||||
|
if (!await File(media).exists()) {
|
||||||
|
step('fail no media file at $media');
|
||||||
|
} else {
|
||||||
|
await pipe.start();
|
||||||
|
await pipe.playback.setVolume(0);
|
||||||
|
// The video output the session view would make: the render path
|
||||||
|
// (EGL / ANGLE) is what breaks on some machines.
|
||||||
|
final video = pipe.playback.video;
|
||||||
|
await video.ready.timeout(const Duration(seconds: 15));
|
||||||
|
final ok = await pipe.open(media);
|
||||||
|
final end = DateTime.now().add(const Duration(seconds: 20));
|
||||||
|
while (ok && pipe.playback.durationSecs <= 0 && DateTime.now().isBefore(end)) {
|
||||||
|
await Future.delayed(const Duration(milliseconds: 100));
|
||||||
|
}
|
||||||
|
if (pipe.playback.durationSecs <= 0) {
|
||||||
|
step('fail the media did not open in 20 s');
|
||||||
|
} else {
|
||||||
|
await pipe.playback.player.play();
|
||||||
|
await Future.delayed(const Duration(seconds: 1));
|
||||||
|
final mode = graph.ports.players.renderMode.peek();
|
||||||
|
step('opened ${sw.elapsedMilliseconds} render=${mode.name}');
|
||||||
|
if (mode == RenderMode.unknown) await Future.delayed(const Duration(seconds: 2));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} on TimeoutException {
|
||||||
|
step('skip the video output did not come up (no display for this runner?)');
|
||||||
|
} catch (e) {
|
||||||
|
step('fail $e');
|
||||||
|
}
|
||||||
|
step('closing');
|
||||||
|
await shutDownApp();
|
||||||
|
}
|
||||||
@@ -1,120 +0,0 @@
|
|||||||
import 'dart:typed_data';
|
|
||||||
|
|
||||||
/// FNV-1a over a 15x15 grid of RGB(A) pixels in the central half of an
|
|
||||||
/// image. Used on a small capture of what the compositor shows: the
|
|
||||||
/// centre is video, the edges carry the (changing) control overlays.
|
|
||||||
int hashCenterPixels(ByteData rgba, int width, int height) {
|
|
||||||
var x = 0x811c9dc5;
|
|
||||||
if (width <= 0 || height <= 0) return x;
|
|
||||||
for (var gy = 1; gy < 16; gy++) {
|
|
||||||
for (var gx = 1; gx < 16; gx++) {
|
|
||||||
final px = (width * (0.25 + 0.5 * gx / 16)).floor();
|
|
||||||
final py = (height * (0.25 + 0.5 * gy / 16)).floor();
|
|
||||||
final o = (py * width + px) * 4;
|
|
||||||
if (o + 3 > rgba.lengthInBytes) continue;
|
|
||||||
for (var c = 0; c < 3; c++) {
|
|
||||||
x = ((x ^ rgba.getUint8(o + c)) * 0x01000193) & 0xffffffff;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return x;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// FNV-1a over ~4k bytes spread evenly across a raw frame (mpv
|
|
||||||
/// `screenshot-raw`); dimension-agnostic, enough to tell frames apart.
|
|
||||||
int hashSpread(Uint8List bytes) {
|
|
||||||
var x = 0x811c9dc5;
|
|
||||||
if (bytes.isEmpty) return x;
|
|
||||||
final step = bytes.length <= 4096 ? 1 : bytes.length ~/ 4096;
|
|
||||||
for (var i = 0; i < bytes.length; i += step) {
|
|
||||||
x = ((x ^ bytes[i]) * 0x01000193) & 0xffffffff;
|
|
||||||
}
|
|
||||||
return x;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One sample of player state, taken about once a second.
|
|
||||||
class FrameSample {
|
|
||||||
final DateTime at;
|
|
||||||
final double position;
|
|
||||||
|
|
||||||
/// Fingerprint of the picture currently shown on screen; null when it
|
|
||||||
/// cannot be captured (no view, hidden window, headless).
|
|
||||||
final int? frames;
|
|
||||||
|
|
||||||
/// Playing, not buffering, rate > 0, video track present, window
|
|
||||||
/// visible. Anything else disarms the watchdog.
|
|
||||||
final bool eligible;
|
|
||||||
const FrameSample({
|
|
||||||
required this.at,
|
|
||||||
required this.position,
|
|
||||||
required this.frames,
|
|
||||||
required this.eligible,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Detects a frozen picture: position advances normally but the shown
|
|
||||||
/// picture stands still for [stallAfter]. Seeks (position jumps), pauses,
|
|
||||||
/// buffering and missing captures all reset the stall clock. A hit is a
|
|
||||||
/// suspicion only — a still scene looks the same — so the caller confirms
|
|
||||||
/// it against the decoder and calls [dismiss] when it was a still scene.
|
|
||||||
/// Fires at most once until the picture is seen moving again for
|
|
||||||
/// [rearmAfter], so a player that stays (or soon gets) frozen after a
|
|
||||||
/// reload does not reload in a loop. [reset] keeps that latch.
|
|
||||||
class FrameWatchdog {
|
|
||||||
static const stallAfter = Duration(seconds: 3);
|
|
||||||
static const rearmAfter = Duration(seconds: 10);
|
|
||||||
|
|
||||||
FrameSample? _last;
|
|
||||||
DateTime? _stallSince;
|
|
||||||
DateTime? _healthySince;
|
|
||||||
bool _fired = false;
|
|
||||||
|
|
||||||
void reset() {
|
|
||||||
_last = null;
|
|
||||||
_stallSince = null;
|
|
||||||
_healthySince = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The last hit was a still scene: re-arm, but wait a full
|
|
||||||
/// [stallAfter] before suspecting again.
|
|
||||||
void dismiss() {
|
|
||||||
_fired = false;
|
|
||||||
_stallSince = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns true exactly when a freeze is suspected.
|
|
||||||
bool feed(FrameSample s) {
|
|
||||||
final last = _last;
|
|
||||||
_last = s;
|
|
||||||
if (!s.eligible || s.frames == null || last == null ||
|
|
||||||
!last.eligible || last.frames == null) {
|
|
||||||
_stallSince = null;
|
|
||||||
_healthySince = null;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (s.frames != last.frames) {
|
|
||||||
_stallSince = null;
|
|
||||||
_healthySince ??= last.at;
|
|
||||||
if (s.at.difference(_healthySince!) >= rearmAfter) _fired = false;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
_healthySince = null;
|
|
||||||
final wall = s.at.difference(last.at).inMilliseconds / 1000.0;
|
|
||||||
final moved = s.position - last.position;
|
|
||||||
// Normal playback only: a jump (seek) or a standstill (stall, the
|
|
||||||
// position itself stuck) is not a frozen picture.
|
|
||||||
final normal = wall > 0 && moved > wall * 0.5 && moved < wall * 2 + 0.5;
|
|
||||||
if (!normal) {
|
|
||||||
_stallSince = null;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
_stallSince ??= last.at;
|
|
||||||
if (_fired) return false;
|
|
||||||
if (s.at.difference(_stallSince!) >= stallAfter) {
|
|
||||||
_fired = true;
|
|
||||||
_stallSince = null;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -4,19 +4,19 @@ import 'dart:io';
|
|||||||
import 'package:path_provider/path_provider.dart';
|
import 'package:path_provider/path_provider.dart';
|
||||||
import 'package:sync_relay_core/core.dart';
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
/// mpv's `ytdl-format` for links every player opens itself.
|
import '../platform/ports/link_resolver.dart';
|
||||||
const ytdlFormat = 'bv*[height<=1080]+ba/b';
|
|
||||||
|
|
||||||
/// The app's yt-dlp (see [YtDlp]): in the app-support folder, shared with
|
/// The app's yt-dlp (see [YtDlp]): in the app-support folder, shared with
|
||||||
/// the hosted server. [probe] remembers what pasted links are for a while,
|
/// the hosted server. [probe] remembers what pasted links are for a while,
|
||||||
/// so the Link preview and the swap ask once.
|
/// so the Link preview and the swap ask once.
|
||||||
class AppYtDlp {
|
class AppYtDlp implements LinkResolver {
|
||||||
static final instance = AppYtDlp();
|
static final instance = AppYtDlp();
|
||||||
|
|
||||||
/// [ytDlp]: a given one (tests); default in the app-support folder.
|
/// [ytDlp]: a given one (tests); default in the app-support folder.
|
||||||
AppYtDlp([YtDlp? ytDlp]) : _ytDlp = ytDlp == null ? null : Future.value(ytDlp);
|
AppYtDlp([YtDlp? ytDlp]) : _ytDlp = ytDlp == null ? null : Future.value(ytDlp);
|
||||||
|
|
||||||
Future<YtDlp>? _ytDlp;
|
Future<YtDlp>? _ytDlp;
|
||||||
|
@override
|
||||||
Future<YtDlp> get ytDlp => _ytDlp ??= () async {
|
Future<YtDlp> get ytDlp => _ytDlp ??= () async {
|
||||||
final base = await getApplicationSupportDirectory();
|
final base = await getApplicationSupportDirectory();
|
||||||
return YtDlp(dir(base.path));
|
return YtDlp(dir(base.path));
|
||||||
@@ -26,32 +26,52 @@ class AppYtDlp {
|
|||||||
|
|
||||||
/// Gets yt-dlp ready in the background (download on first run, a daily
|
/// Gets yt-dlp ready in the background (download on first run, a daily
|
||||||
/// update check afterwards).
|
/// update check afterwards).
|
||||||
|
@override
|
||||||
|
bool get resolvesLinks => true;
|
||||||
|
|
||||||
|
@override
|
||||||
void warmUp() => unawaited(ytDlp.then((y) => y.ensure()).catchError((_) => null));
|
void warmUp() => unawaited(ytDlp.then((y) => y.ensure()).catchError((_) => null));
|
||||||
|
|
||||||
/// mpv's `ytdl-raw-options` for the cookies in the yt-dlp folder ('' for
|
final _probes = <String, ({DateTime at, DateTime until, Future<LinkProbe> f})>{};
|
||||||
/// none; see [YtDlpCookies]).
|
|
||||||
Future<String> mpvRawOptions() async {
|
|
||||||
try {
|
|
||||||
return (await ytDlp).cookies.mpvRawOptions();
|
|
||||||
} catch (_) {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
final _probes = <String, (DateTime, Future<LinkProbe>)>{};
|
|
||||||
static const _probeTtl = Duration(minutes: 10);
|
static const _probeTtl = Duration(minutes: 10);
|
||||||
|
|
||||||
Future<LinkProbe> probe(String url) {
|
/// What [url] is, from memory while it is kept (10 minutes from when it
|
||||||
|
/// was probed; [keep] keeps it longer, for Up next's first item, which
|
||||||
|
/// is probed again before that runs out). [fresh] probes again: the
|
||||||
|
/// remembered result stays until the new one is in, and stays when the
|
||||||
|
/// new one fails.
|
||||||
|
@override
|
||||||
|
Future<LinkProbe> probe(String url, {Duration keep = _probeTtl, bool fresh = false}) {
|
||||||
final now = DateTime.now();
|
final now = DateTime.now();
|
||||||
_probes.removeWhere((_, v) => now.difference(v.$1) > _probeTtl);
|
_probes.removeWhere((_, v) => now.isAfter(v.until));
|
||||||
final hit = _probes[url];
|
final hit = _probes[url];
|
||||||
if (hit != null) return hit.$2;
|
if (hit != null && !fresh) {
|
||||||
|
final longer = hit.at.add(keep);
|
||||||
|
if (longer.isAfter(hit.until)) _probes[url] = (at: hit.at, until: longer, f: hit.f);
|
||||||
|
return hit.f;
|
||||||
|
}
|
||||||
final f = ytDlp.then((y) => probeLink(Uri.parse(url), ytDlp: y));
|
final f = ytDlp.then((y) => probeLink(Uri.parse(url), ytDlp: y));
|
||||||
_probes[url] = (now, f);
|
final until = now.add(keep);
|
||||||
|
if (hit == null) {
|
||||||
|
_probes[url] = (at: now, until: until, f: f);
|
||||||
f.catchError((Object _) {
|
f.catchError((Object _) {
|
||||||
_probes.remove(url);
|
if (_probes[url]?.f == f) _probes.remove(url);
|
||||||
return LinkProbe.file(Uri(), -1);
|
return LinkProbe.file(Uri(), -1);
|
||||||
});
|
});
|
||||||
|
} else {
|
||||||
|
f.then<void>((_) {
|
||||||
|
_probes[url] = (at: now, until: until, f: f);
|
||||||
|
}, onError: (Object _) {});
|
||||||
|
}
|
||||||
return f;
|
return f;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// [url] no longer needs keeping longer: back to the usual 10 minutes.
|
||||||
|
@override
|
||||||
|
void release(String url) {
|
||||||
|
final hit = _probes[url];
|
||||||
|
if (hit == null) return;
|
||||||
|
final usual = hit.at.add(_probeTtl);
|
||||||
|
if (usual.isBefore(hit.until)) _probes[url] = (at: hit.at, until: usual, f: hit.f);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,887 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
import 'dart:math';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:signals/signals_flutter.dart';
|
||||||
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
|
import '../files/thumbnails.dart';
|
||||||
|
import '../jellyfin/accounts.dart';
|
||||||
|
import '../jellyfin/format.dart' show pickFor;
|
||||||
|
import '../jellyfin/session_media.dart';
|
||||||
|
import '../library/media_refs.dart';
|
||||||
|
import '../screens/home/picked_media.dart';
|
||||||
|
import '../session/app_events.dart' show AddedToUpNext;
|
||||||
|
import '../session/media_art.dart';
|
||||||
|
import '../session/session_coordinator.dart';
|
||||||
|
import '../sync/avatar_cache.dart';
|
||||||
|
|
||||||
|
// What's next on this app (see ARCHITECTURE.md "What's next" and "Up
|
||||||
|
// next"): the server's queue as signals (Up next and its continuation),
|
||||||
|
// adding to it (probed, with a picture), the continuation of what this
|
||||||
|
// app put up (the next Jellyfin episode, the next file of a local show),
|
||||||
|
// the server's countdown as the end card shows it, putting an item up
|
||||||
|
// when the server asks this app (`queuePlay`), and keeping the item that
|
||||||
|
// plays next ready (the media pipeline prepares it).
|
||||||
|
|
||||||
|
/// The end-of-media card for the first item (Up next's, else the
|
||||||
|
/// continuation). [secondsLeft]: the server's countdown (`state.advance`);
|
||||||
|
/// null when none runs (cancelled, or nothing counts down), then the card
|
||||||
|
/// offers Play now only. [waitingFor]: the countdown ran out and the one
|
||||||
|
/// who puts the item up is not here (its name).
|
||||||
|
class UpNextCountdown {
|
||||||
|
final int mediaId;
|
||||||
|
final QueueItem item;
|
||||||
|
final int? secondsLeft;
|
||||||
|
final String? waitingFor;
|
||||||
|
const UpNextCountdown({required this.mediaId, required this.item, this.secondsLeft, this.waitingFor});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first item's readiness on this app.
|
||||||
|
enum WarmState { idle, warming, ready, failed }
|
||||||
|
|
||||||
|
class QueueController {
|
||||||
|
final SessionCoordinator coord;
|
||||||
|
QueueController(this.coord);
|
||||||
|
|
||||||
|
/// Queued items' pictures by hash, from `/i/`.
|
||||||
|
late final PictureCache thumbs = PictureCache(coord.connection.client,
|
||||||
|
route: 'i', keep: RelayConstants.maxQueueItems + 8, live: (s) => [for (final q in s.queue) q.thumb]);
|
||||||
|
|
||||||
|
/// Up next, in order, without the continuation (empty when nothing is
|
||||||
|
/// queued or not in a server).
|
||||||
|
late final Computed<List<QueueItem>> items = computed(
|
||||||
|
() => [for (final q in coord.serverState.value?.queue ?? const <QueueItem>[]) if (!q.auto) q]);
|
||||||
|
|
||||||
|
/// The continuation of what plays (`auto`: the next episode), shared by
|
||||||
|
/// everyone; null when none.
|
||||||
|
late final Computed<QueueItem?> continues =
|
||||||
|
computed(() => coord.serverState.value?.queue.where((q) => q.auto).firstOrNull);
|
||||||
|
|
||||||
|
/// What plays next: Up next's first item, else the continuation.
|
||||||
|
late final Computed<QueueItem?> head = computed(() => coord.serverState.value?.queue.firstOrNull);
|
||||||
|
|
||||||
|
/// The end card while the media has ended with something next (see
|
||||||
|
/// [UpNextCountdown]).
|
||||||
|
final countdown = signal<UpNextCountdown?>(null);
|
||||||
|
|
||||||
|
/// The first item's id and how ready it is here (null: nothing to get
|
||||||
|
/// ready on this app).
|
||||||
|
final warm = signal<({String id, WarmState state})?>(null);
|
||||||
|
|
||||||
|
/// The next episodes of the Jellyfin series playing, on an app that
|
||||||
|
/// plays it with its own account (the first one is what continues it;
|
||||||
|
/// the rest show greyed under "Continues with", "+" adds one).
|
||||||
|
final continuation = signal<List<EpisodeLink>>(const []);
|
||||||
|
|
||||||
|
/// The mediaId whose continuation was cleared (by anyone: `cancel`).
|
||||||
|
final _hiddenFor = signal(-1);
|
||||||
|
|
||||||
|
/// The queue popover is open: the Up next button holds the controls up.
|
||||||
|
final popoverOpen = signal(false);
|
||||||
|
|
||||||
|
// What adder-only items stand for, by their key (a link passed on from
|
||||||
|
// here, a file here). Never leaves this app.
|
||||||
|
final Map<String, ({PickedMedia pick, DateTime at})> _local = {};
|
||||||
|
final Map<String, DateTime> _performing = {};
|
||||||
|
Timer? _timer;
|
||||||
|
bool _attached = false;
|
||||||
|
// The mediaId whose continuation this app added (or is adding).
|
||||||
|
int _continuedFor = -1;
|
||||||
|
// A restarted server waits for what played (that mediaId) to come back.
|
||||||
|
int _restoreFrom = -1;
|
||||||
|
String _continuationFor = '';
|
||||||
|
final _random = Random.secure();
|
||||||
|
|
||||||
|
String get _me => coord.connection.memberId;
|
||||||
|
|
||||||
|
void attach() {
|
||||||
|
if (_attached) return;
|
||||||
|
_attached = true;
|
||||||
|
coord.connection.states.listen(_onState);
|
||||||
|
// `cancel` from anyone: no continuation for that media any more.
|
||||||
|
coord.connection.feeds.listen((f) {
|
||||||
|
final id = coord.serverState.peek()?.mediaId;
|
||||||
|
if (f.action == 'advance-cancel' && id != null) _hiddenFor.value = id;
|
||||||
|
});
|
||||||
|
effect(() {
|
||||||
|
final next = coord.nextEpisode.value;
|
||||||
|
final plan = coord.jellyfinPlan.value;
|
||||||
|
unawaited(_loadContinuation(next, plan));
|
||||||
|
});
|
||||||
|
// What continues this media becomes known (the next episode found, a
|
||||||
|
// file of ours up): add it.
|
||||||
|
effect(() {
|
||||||
|
coord.nextEpisode.value;
|
||||||
|
coord.ownFile.value;
|
||||||
|
untracked(() => _continue(coord.serverState.peek()));
|
||||||
|
});
|
||||||
|
// The state decides what to get ready; the media playing having
|
||||||
|
// started (or sitting out) lets the preload go.
|
||||||
|
effect(() {
|
||||||
|
coord.settledMediaId.value;
|
||||||
|
coord.selfAway.value;
|
||||||
|
final r = coord.serverState.value;
|
||||||
|
untracked(() => _warm(r));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- adding
|
||||||
|
|
||||||
|
/// Adds [pick] to Up next (at the end, or with [next] right after what
|
||||||
|
/// plays). A link is probed first and refused like Put it up when it
|
||||||
|
/// will not play. Returns an error text, or null when sent.
|
||||||
|
Future<String?> add(PickedMedia pick, {bool next = false}) async {
|
||||||
|
coord.markInput();
|
||||||
|
if (coord.serverState.peek() == null) return 'not in a server';
|
||||||
|
if (coord.stateStale.peek()) return 'reconnecting — add it again once back';
|
||||||
|
if (items.peek().length >= RelayConstants.maxQueueItems) {
|
||||||
|
return 'Up next is full (${RelayConstants.maxQueueItems} items)';
|
||||||
|
}
|
||||||
|
final ({QueueItem item, Uint8List? thumb}) built;
|
||||||
|
try {
|
||||||
|
final b = await _build(pick);
|
||||||
|
if (b is String) return b;
|
||||||
|
built = b as ({QueueItem item, Uint8List? thumb});
|
||||||
|
} catch (e) {
|
||||||
|
return "couldn't add it: $e";
|
||||||
|
}
|
||||||
|
final item = built.item;
|
||||||
|
if (item.key.isNotEmpty) _local[item.key] = (pick: pick, at: DateTime.now());
|
||||||
|
final thumb = built.thumb;
|
||||||
|
coord.connection.sendQueue(QueueIntent.add(item, next: next, thumb: thumb == null ? '' : base64Encode(thumb)));
|
||||||
|
coord.notify(AddedToUpNext(item.title));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A continuation episode becomes an Up next item.
|
||||||
|
Future<String?> promote(EpisodeLink e) => add(e.pick);
|
||||||
|
|
||||||
|
/// The item, or an error text.
|
||||||
|
Future<Object> _build(PickedMedia pick) async {
|
||||||
|
switch (pick) {
|
||||||
|
case JellyfinMedia():
|
||||||
|
final accounts = coord.jellyfin;
|
||||||
|
if (accounts.account(pick.serverId) == null) return 'that Jellyfin server is not linked any more';
|
||||||
|
if (accounts.statusOf(pick.serverId) == JellyfinAccountStatus.expired) {
|
||||||
|
return 'Jellyfin sign-in expired — reconnect it in Settings → Jellyfin & integrations';
|
||||||
|
}
|
||||||
|
final client = accounts.clientFor(pick.serverId);
|
||||||
|
final thumb = client == null ? null : await _jellyfinThumb(client, pick.itemId);
|
||||||
|
return (
|
||||||
|
item: QueueItem(
|
||||||
|
media: mediaForPick(pick),
|
||||||
|
how: QueueHow.jellyfin,
|
||||||
|
title: pick.title,
|
||||||
|
sub: pick.subtitle,
|
||||||
|
duration: (pick.runtime?.inMilliseconds ?? 0) / 1000,
|
||||||
|
),
|
||||||
|
thumb: thumb,
|
||||||
|
);
|
||||||
|
case FileMedia(:final path):
|
||||||
|
final file = File(path);
|
||||||
|
if (!await file.exists()) return 'file not found — check the path';
|
||||||
|
final name = pick.label;
|
||||||
|
final parsed = parseReleaseName(name);
|
||||||
|
final shot = await thumbnailFor(path);
|
||||||
|
Uint8List? thumb;
|
||||||
|
if (shot != null) {
|
||||||
|
try {
|
||||||
|
final bytes = await File(shot.imagePath).readAsBytes();
|
||||||
|
if (bytes.length <= RelayConstants.maxPosterBytes) thumb = bytes;
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
// The library's name for it when it knows the show (what friends
|
||||||
|
// see in Up next), else the release name's.
|
||||||
|
final what = coord.fileRef?.call(path);
|
||||||
|
final ep = what != null && what.kind == 'episode'
|
||||||
|
? (refEpisodeLine(what) ?? '').replaceAll(' ', '')
|
||||||
|
: [
|
||||||
|
if (parsed.season != null) 'S${parsed.season}',
|
||||||
|
if (parsed.episode != null) 'E${parsed.episode}',
|
||||||
|
if (parsed.episode == null) ?parsed.extra,
|
||||||
|
].join();
|
||||||
|
final title = what != null && what.title.isNotEmpty ? what.title : parsed.series.trim();
|
||||||
|
return (
|
||||||
|
item: QueueItem(
|
||||||
|
media: HelloMedia(name: name, size: await file.length(), duration: 0, ref: what),
|
||||||
|
how: QueueHow.file,
|
||||||
|
title: title.isEmpty ? name : title,
|
||||||
|
sub: ep,
|
||||||
|
duration: (shot?.duration.inMilliseconds ?? 0) / 1000,
|
||||||
|
key: _newKey(),
|
||||||
|
),
|
||||||
|
thumb: thumb,
|
||||||
|
);
|
||||||
|
case LinkMedia(:final url, :final anyway):
|
||||||
|
// Alone, a link plays direct: there is nobody to pass it on to.
|
||||||
|
final relay = coord.alone.peek() ? LinkRelay.direct : pick.relay;
|
||||||
|
final linked = await mediaForLink(coord.jellyfin, url);
|
||||||
|
final ref = linked.jellyfin;
|
||||||
|
if (ref != null) {
|
||||||
|
return (
|
||||||
|
item: QueueItem(
|
||||||
|
media: linked,
|
||||||
|
how: QueueHow.jellyfin,
|
||||||
|
title: ref.title.isEmpty ? linked.name : ref.title,
|
||||||
|
sub: ref.subtitle ?? '',
|
||||||
|
duration: ref.runtimeSecs ?? 0),
|
||||||
|
thumb: null,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
LinkProbe? probe;
|
||||||
|
String? probeError;
|
||||||
|
try {
|
||||||
|
probe = await coord.ytDlp.probe(url).timeout(const Duration(seconds: 45));
|
||||||
|
} catch (e) {
|
||||||
|
probeError = '$e';
|
||||||
|
}
|
||||||
|
final problem = probe == null ? playErrorText(probeError ?? '') : probe.problem;
|
||||||
|
if (problem != null && !anyway) return problem;
|
||||||
|
if (relay == LinkRelay.me) {
|
||||||
|
if (probe == null) return problem ?? "couldn't reach the site";
|
||||||
|
final relayProblem = probe.relayProblem;
|
||||||
|
if (relayProblem != null) return relayProblem;
|
||||||
|
}
|
||||||
|
if (relay == LinkRelay.server && !coord.serverHasPassword) return 'server fetch needs a server password';
|
||||||
|
if (relay == LinkRelay.server && probe != null && probe.isPage && probe.info != null) {
|
||||||
|
final relayProblem = probe.relayProblem;
|
||||||
|
if (relayProblem != null) return relayProblem;
|
||||||
|
}
|
||||||
|
final uri = Uri.tryParse(url) ?? Uri();
|
||||||
|
final info = probe?.info;
|
||||||
|
final title = probe?.title ?? linked.name;
|
||||||
|
final site = info == null
|
||||||
|
? uri.host
|
||||||
|
: (info.uploader.isNotEmpty ? info.uploader : (info.extractor.isNotEmpty ? info.extractor : uri.host));
|
||||||
|
final thumbUrl = info?.thumbnail == null ? null : Uri.tryParse(info!.thumbnail!);
|
||||||
|
final thumb = thumbUrl == null ? null : (await thumbnailArt(thumbUrl))?.poster;
|
||||||
|
final how = switch (relay) {
|
||||||
|
LinkRelay.direct => QueueHow.direct,
|
||||||
|
LinkRelay.server => QueueHow.server,
|
||||||
|
LinkRelay.me => QueueHow.through,
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
item: QueueItem(
|
||||||
|
media: HelloMedia(
|
||||||
|
name: title,
|
||||||
|
size: 0,
|
||||||
|
duration: 0,
|
||||||
|
url: how == QueueHow.through ? null : url,
|
||||||
|
relay: how == QueueHow.server ? const MediaRelay(fetch: true) : null,
|
||||||
|
ref: linkMediaRef(title)),
|
||||||
|
how: how,
|
||||||
|
title: title,
|
||||||
|
sub: site,
|
||||||
|
duration: info?.duration ?? 0,
|
||||||
|
key: how == QueueHow.through ? _newKey() : '',
|
||||||
|
),
|
||||||
|
thumb: thumb,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String _newKey() => [for (var i = 0; i < 12; i++) _random.nextInt(256).toRadixString(16).padLeft(2, '0')].join();
|
||||||
|
|
||||||
|
/// A wide picture of a Jellyfin item: an episode's own still, else the
|
||||||
|
/// item's (or series') thumb or backdrop, else its poster.
|
||||||
|
Future<Uint8List?> _jellyfinThumb(JellyfinClient client, String itemId) async {
|
||||||
|
try {
|
||||||
|
final item = await client.item(itemId).timeout(const Duration(seconds: 10));
|
||||||
|
final ref = (item.kind == JellyfinItemKind.episode ? item.ownImage(JellyfinImageType.primary) : null) ??
|
||||||
|
item.image(JellyfinImageType.thumb) ??
|
||||||
|
item.image(JellyfinImageType.backdrop) ??
|
||||||
|
item.image(JellyfinImageType.primary);
|
||||||
|
if (ref == null) return null;
|
||||||
|
return await fetchImage(
|
||||||
|
client.imageUrl(ref, maxWidth: 480, quality: 80), client.authHeaders, RelayConstants.maxPosterBytes);
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('queue: no Jellyfin picture for $itemId: $e');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [item]'s link as this app may hand it out (Copy link, Open in
|
||||||
|
/// browser): a link everyone opens (it is in the state), or a link this
|
||||||
|
/// app passes on (its adder). Null otherwise: a server-fetched link stays
|
||||||
|
/// with the server, another member's passed-on link with them.
|
||||||
|
String? linkOf(QueueItem item) => switch (item.how) {
|
||||||
|
QueueHow.direct => item.media.url,
|
||||||
|
QueueHow.through when item.by == _me => switch (_local[item.key]?.pick) {
|
||||||
|
LinkMedia(:final url) => url,
|
||||||
|
_ => null,
|
||||||
|
},
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// [item]'s page on its Jellyfin server, when that server is linked here.
|
||||||
|
String? jellyfinPageOf(QueueItem item) {
|
||||||
|
final ref = item.media.jellyfin;
|
||||||
|
return ref == null ? null : coord.jellyfin.webUrlOf(ref.serverId, ref.itemId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ editing
|
||||||
|
|
||||||
|
void move(String id, int to) {
|
||||||
|
coord.markInput();
|
||||||
|
coord.connection.sendQueue(QueueIntent.move(id, to));
|
||||||
|
}
|
||||||
|
|
||||||
|
void remove(String id) {
|
||||||
|
coord.markInput();
|
||||||
|
coord.connection.sendQueue(QueueIntent.remove(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Plays [id] now: this app puts it up when it is the one that can,
|
||||||
|
/// else it asks the server, and the app that can puts it up.
|
||||||
|
void playNow(String id) {
|
||||||
|
coord.markInput();
|
||||||
|
final r = coord.serverState.peek();
|
||||||
|
final item = r?.queue.where((q) => q.id == id).firstOrNull;
|
||||||
|
if (r == null || item == null) return;
|
||||||
|
if (queuePerformer(item, r.members).id == _me) {
|
||||||
|
_perform(item);
|
||||||
|
} else {
|
||||||
|
coord.connection.sendQueue(QueueIntent.play(id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Plays what comes next now (Up next's first item, else the
|
||||||
|
/// continuation).
|
||||||
|
void skip() {
|
||||||
|
final first = head.peek();
|
||||||
|
if (first != null) playNow(first.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancel on the end card: the countdown stops for everyone, and the
|
||||||
|
/// continuation goes (`cancel`).
|
||||||
|
void cancelCountdown() {
|
||||||
|
coord.markInput();
|
||||||
|
coord.connection.sendQueue(const QueueIntent.cancel());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Clear" under "Continues with": the continuation of what plays goes
|
||||||
|
/// for everyone (`cancel`) and does not come back for this media.
|
||||||
|
void clearContinuation() {
|
||||||
|
final id = coord.serverState.peek()?.mediaId;
|
||||||
|
if (id != null) _hiddenFor.value = id;
|
||||||
|
cancelCountdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The further episodes of [continuation] (after the one that continues
|
||||||
|
/// what plays), unless it was cleared for the media playing.
|
||||||
|
late final Computed<List<EpisodeLink>> shownContinuation = computed(() {
|
||||||
|
final id = coord.serverState.value?.mediaId;
|
||||||
|
if (id == null || _hiddenFor.value == id) return const <EpisodeLink>[];
|
||||||
|
final auto = continues.value?.media.jellyfin?.itemId;
|
||||||
|
return [for (final e in continuation.value) if (e.item.id != auto) e];
|
||||||
|
});
|
||||||
|
|
||||||
|
// --------------------------------------------------------- per state
|
||||||
|
|
||||||
|
void _onState(StateBroadcast r) {
|
||||||
|
_lastState = r;
|
||||||
|
// What played came back after a restart under a new mediaId: a
|
||||||
|
// continuation cleared for it stays cleared.
|
||||||
|
if (_restoreFrom != -1 && r.media != null && _hiddenFor.peek() == _restoreFrom) _hiddenFor.value = r.mediaId;
|
||||||
|
_prune(r);
|
||||||
|
// The server asks for an item (a countdown ran out, Play now from
|
||||||
|
// another app, nothing up yet): the app that puts it up does.
|
||||||
|
final play = r.queuePlay;
|
||||||
|
if (play != null) {
|
||||||
|
final item = r.queue.where((q) => q.id == play).firstOrNull;
|
||||||
|
if (item != null && queuePerformer(item, r.members).id == _me) _perform(item);
|
||||||
|
}
|
||||||
|
_syncCountdown(r);
|
||||||
|
_continue(r);
|
||||||
|
_warm(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Forgets what no longer matters: performing marks after a minute (a
|
||||||
|
/// swap that never landed may be tried again), local picks no longer
|
||||||
|
/// queued.
|
||||||
|
void _prune(StateBroadcast r) {
|
||||||
|
final now = DateTime.now();
|
||||||
|
_performing.removeWhere((_, at) => now.difference(at) > const Duration(minutes: 1));
|
||||||
|
final keys = {for (final q in r.queue) q.key};
|
||||||
|
// Kept while a restarted server waits for what played: Up next comes
|
||||||
|
// back with it.
|
||||||
|
if (_restoreFrom == -1) {
|
||||||
|
_local.removeWhere((k, v) => !keys.contains(k) && now.difference(v.at) > const Duration(minutes: 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The end card from the server's state: the media ended with something
|
||||||
|
/// next; the seconds of `state.advance` move on with a 1 s timer.
|
||||||
|
void _syncCountdown(StateBroadcast r) {
|
||||||
|
final head = r.queue.firstOrNull;
|
||||||
|
if (r.transport != 'finished' || head == null || r.media == null) {
|
||||||
|
_timer?.cancel();
|
||||||
|
_timer = null;
|
||||||
|
if (countdown.peek() != null) countdown.value = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final a = r.advance != null && r.advance!.id == head.id ? r.advance : null;
|
||||||
|
int? left;
|
||||||
|
String? waiting;
|
||||||
|
if (a != null) {
|
||||||
|
left = advanceSecondsLeft(a, coord.connection.serverNow());
|
||||||
|
if (left == 0 && queuePerformer(head, r.members).id == null) {
|
||||||
|
waiting = r.members.where((m) => m.id == head.by).firstOrNull?.name ?? head.byName;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
countdown.value = UpNextCountdown(mediaId: r.mediaId, item: head, secondsLeft: left, waitingFor: waiting);
|
||||||
|
if (a == null) {
|
||||||
|
_timer?.cancel();
|
||||||
|
_timer = null;
|
||||||
|
} else {
|
||||||
|
_timer ??= Timer.periodic(const Duration(seconds: 1), (_) {
|
||||||
|
final now = coord.serverState.peek();
|
||||||
|
if (now != null) _syncCountdown(now);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ restart
|
||||||
|
|
||||||
|
/// The server restarted without media; what played ([mediaId]) is being
|
||||||
|
/// offered back (-1: that is over).
|
||||||
|
void restoreFrom(int mediaId) => _restoreFrom = mediaId;
|
||||||
|
|
||||||
|
/// What played is back after a server restart: Up next as [before] had
|
||||||
|
/// it comes back too. The app whose offer won ([winner]) adds the items
|
||||||
|
/// anyone can put up (links everyone opens, Jellyfin items); every app
|
||||||
|
/// its own links passed on and files (only it has them; [self] is its
|
||||||
|
/// member id then). A server-fetched link's address stayed with the old
|
||||||
|
/// server, so it is gone; the continuation comes back as usual.
|
||||||
|
void restoreAfterRestart(StateBroadcast before, String self, {required bool winner}) {
|
||||||
|
for (final q in before.queue) {
|
||||||
|
if (q.auto) continue;
|
||||||
|
final ok = switch (q.how) {
|
||||||
|
QueueHow.direct || QueueHow.jellyfin => winner,
|
||||||
|
QueueHow.through || QueueHow.file => self.isNotEmpty && q.by == self && _local.containsKey(q.key),
|
||||||
|
QueueHow.server => false,
|
||||||
|
};
|
||||||
|
if (!ok) continue;
|
||||||
|
final local = _local[q.key];
|
||||||
|
if (local != null) _local[q.key] = (pick: local.pick, at: DateTime.now());
|
||||||
|
final thumb = thumbs.bytesFor(q.thumb);
|
||||||
|
coord.connection.sendQueue(QueueIntent.add(
|
||||||
|
QueueItem(media: q.media, how: q.how, title: q.title, sub: q.sub, duration: q.duration, key: q.key),
|
||||||
|
thumb: thumb == null ? '' : base64Encode(thumb)));
|
||||||
|
}
|
||||||
|
_restoreFrom = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------- continuation
|
||||||
|
|
||||||
|
/// Adds what continues the media playing (`auto`, PROTOCOL.md "Queue")
|
||||||
|
/// when this app may ([mayAddContinuation]: it put it up, or that
|
||||||
|
/// member is not in and this is the first who is), knows what comes
|
||||||
|
/// next, and it is not there or cancelled yet; with the setting on. A
|
||||||
|
/// Jellyfin episode played with this app's account continues with the
|
||||||
|
/// series' next one, a file this app put up with the next episode of its
|
||||||
|
/// show in the library (numbers skipped on the way said in its line).
|
||||||
|
void _continue(StateBroadcast? r) {
|
||||||
|
if (r == null || r.media == null || !coord.settings.autoAdvance.peek()) return;
|
||||||
|
final id = r.mediaId;
|
||||||
|
if (_continuedFor == id || _hiddenFor.peek() == id) return;
|
||||||
|
if (r.queue.any((q) => q.auto && q.forMedia == id)) {
|
||||||
|
_continuedFor = id;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final swapBy = r.media?['swapBy'];
|
||||||
|
if (!mayAddContinuation(_me, swapBy is String ? swapBy : null, r.members)) return;
|
||||||
|
final ref = refOfStateMedia(r.media);
|
||||||
|
final next = coord.nextEpisode.peek();
|
||||||
|
if (ref != null) {
|
||||||
|
if (next == null || !sameJellyfinItem(ref, coord.currentRef.peek())) return;
|
||||||
|
_continuedFor = id;
|
||||||
|
unawaited(_addContinuation(id, next.pick));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final own = coord.ownFile.peek();
|
||||||
|
final finder = coord.nextFile;
|
||||||
|
if (own == null || own.$1 != id || finder == null) return;
|
||||||
|
_continuedFor = id;
|
||||||
|
unawaited(() async {
|
||||||
|
try {
|
||||||
|
final n = await finder(own.$2);
|
||||||
|
if (n == null) return;
|
||||||
|
final gap = n.skipped;
|
||||||
|
await _addContinuation(id, FileMedia(n.episode.path),
|
||||||
|
note: gap == null ? null : 'skips ${gap.label}');
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('queue: what continues ${own.$2}: $e');
|
||||||
|
}
|
||||||
|
}());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _addContinuation(int mediaId, PickedMedia pick, {String? note}) async {
|
||||||
|
try {
|
||||||
|
final b = await _build(pick);
|
||||||
|
if (b is! ({QueueItem item, Uint8List? thumb})) return;
|
||||||
|
final r = coord.serverState.peek();
|
||||||
|
if (r == null || r.mediaId != mediaId || _hiddenFor.peek() == mediaId) return;
|
||||||
|
final sub = [b.item.sub, ?note].where((s) => s.isNotEmpty).join(' · ');
|
||||||
|
final item = b.item.copyWith(auto: true, forMedia: mediaId, sub: sub);
|
||||||
|
if (item.key.isNotEmpty) _local[item.key] = (pick: pick, at: DateTime.now());
|
||||||
|
final thumb = b.thumb;
|
||||||
|
coord.connection.sendQueue(QueueIntent.add(item, thumb: thumb == null ? '' : base64Encode(thumb)));
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('queue: adding what continues media $mediaId: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Puts [item] up from here (once per item while it is in flight).
|
||||||
|
/// When it cannot play after all, it is taken off with the reason.
|
||||||
|
void _perform(QueueItem item) {
|
||||||
|
if (_performing.containsKey(item.id)) return;
|
||||||
|
_performing[item.id] = DateTime.now();
|
||||||
|
unawaited(() async {
|
||||||
|
String? error;
|
||||||
|
try {
|
||||||
|
error = await _swapTo(item);
|
||||||
|
} catch (e) {
|
||||||
|
error = '$e';
|
||||||
|
}
|
||||||
|
if (error != null) {
|
||||||
|
debugPrint('queue: ${item.id} cannot go up: $error');
|
||||||
|
coord.connection.sendQueue(QueueIntent.remove(item.id, why: "couldn't play it ($error)"));
|
||||||
|
}
|
||||||
|
}());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<String?> _swapTo(QueueItem item) async {
|
||||||
|
switch (item.how) {
|
||||||
|
case QueueHow.jellyfin:
|
||||||
|
final ref = item.media.jellyfin;
|
||||||
|
final pick = ref == null ? null : pickForRef(coord.jellyfin, ref);
|
||||||
|
if (pick == null) return 'no Jellyfin account here for it';
|
||||||
|
coord.swapJellyfin(pick, queueId: item.id);
|
||||||
|
return null;
|
||||||
|
case QueueHow.direct:
|
||||||
|
final url = item.media.url;
|
||||||
|
if (url == null) return 'no link';
|
||||||
|
// Each viewer opens it: one computer's probe does not decide.
|
||||||
|
return coord.swapLink(url, relay: LinkRelay.direct, anyway: true, queueId: item.id);
|
||||||
|
case QueueHow.server:
|
||||||
|
coord.swapQueued(HelloMedia(name: item.title, size: 0, duration: 0, relay: const MediaRelay(fetch: true)),
|
||||||
|
item.id,
|
||||||
|
art: thumbs.bytesFor(item.thumb));
|
||||||
|
return null;
|
||||||
|
case QueueHow.through:
|
||||||
|
case QueueHow.file:
|
||||||
|
final local = _local[item.key];
|
||||||
|
if (local == null) return "it isn't on this computer any more";
|
||||||
|
// Only this app can pass it on, and a member sitting out has
|
||||||
|
// nothing open: back first.
|
||||||
|
if (coord.selfAway.peek()) coord.joinBack();
|
||||||
|
return coord.swapPicked(local.pick, queueId: item.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ warming
|
||||||
|
|
||||||
|
/// How long a warm result is kept, when it is resolved again, and when a
|
||||||
|
/// failed one is tried again.
|
||||||
|
static const _warmKeep = Duration(minutes: 35);
|
||||||
|
static const _warmRefresh = Duration(minutes: 30);
|
||||||
|
static const _warmRetry = Duration(minutes: 2);
|
||||||
|
|
||||||
|
String _warmKey = '';
|
||||||
|
String? _warmUrl;
|
||||||
|
Timer? _warmTimer;
|
||||||
|
int _warmGen = 0;
|
||||||
|
// What the preload player should hold once the media playing has
|
||||||
|
// started (null: nothing); [_preloadFresh]: open it again (a link's
|
||||||
|
// refresh).
|
||||||
|
({String url, Map<String, String>? headers})? _preloadWant;
|
||||||
|
bool _preloadFresh = false;
|
||||||
|
String _preloadKey = '';
|
||||||
|
bool _preloadBusy = false;
|
||||||
|
bool _preloadOk = true;
|
||||||
|
int _preloadGen = 0;
|
||||||
|
StateBroadcast? _lastState;
|
||||||
|
|
||||||
|
bool _ownAccount(String serverId) =>
|
||||||
|
coord.jellyfin.account(serverId) != null && coord.jellyfin.statusOf(serverId) != JellyfinAccountStatus.expired;
|
||||||
|
|
||||||
|
/// What this app gets ready: the first item of the queue (Up next's,
|
||||||
|
/// else the continuation). Every app does, each its own copy (see
|
||||||
|
/// [_WarmTarget]); while sitting out only the probe of a link this app
|
||||||
|
/// puts up (its swap reads it). Null: nothing.
|
||||||
|
_WarmTarget? _warmTarget(StateBroadcast? r) {
|
||||||
|
final t = _warmTargetHere(r);
|
||||||
|
if (t == null || !coord.selfAway.peek()) return t;
|
||||||
|
return t.probe == null ? null : _WarmTarget(t.id, probe: t.probe);
|
||||||
|
}
|
||||||
|
|
||||||
|
_WarmTarget? _warmTargetHere(StateBroadcast? r) {
|
||||||
|
if (r == null) return null;
|
||||||
|
final head = r.queue.firstOrNull;
|
||||||
|
if (head != null) {
|
||||||
|
final performer = queuePerformer(head, r.members).id == _me;
|
||||||
|
final local = _local[head.key]?.pick;
|
||||||
|
// The server's warm relay of the item, once bytes can flow: what
|
||||||
|
// everyone without their own copy preloads.
|
||||||
|
final relay = head.media.relay;
|
||||||
|
final warmUrl = relay != null && relay.live ? coord.media.warmRelayUrl(head, relay) : null;
|
||||||
|
switch (head.how) {
|
||||||
|
case QueueHow.jellyfin:
|
||||||
|
final ref = head.media.jellyfin;
|
||||||
|
if (ref == null) return null;
|
||||||
|
if (_ownAccount(ref.serverId)) return _WarmTarget(head.id, ref: ref);
|
||||||
|
// No account here: the server's login passes it on (`/j`), else
|
||||||
|
// the warm relay a member with an account feeds.
|
||||||
|
final open = r.relayNext ? coord.jellyfinRelayUrl(ref) : warmUrl;
|
||||||
|
return open == null ? null : _WarmTarget(head.id, open: open);
|
||||||
|
case QueueHow.direct:
|
||||||
|
final url = head.media.url;
|
||||||
|
if (url == null) return null;
|
||||||
|
return _WarmTarget(head.id, probe: performer ? url : null, open: url);
|
||||||
|
case QueueHow.through:
|
||||||
|
// Only its adder has the link (and feeds the warm relay).
|
||||||
|
if (!performer) return warmUrl == null ? null : _WarmTarget(head.id, open: warmUrl);
|
||||||
|
final url = local is LinkMedia ? local.url : null;
|
||||||
|
return _WarmTarget(head.id, probe: url, open: url);
|
||||||
|
case QueueHow.file:
|
||||||
|
if (!performer) return warmUrl == null ? null : _WarmTarget(head.id, open: warmUrl);
|
||||||
|
// The host's own file plays from its `/m` URL once it is up.
|
||||||
|
return _WarmTarget(head.id, open: local is FileMedia && coord.hostFile == null ? local.path : null);
|
||||||
|
case QueueHow.server:
|
||||||
|
// The server fetches it into its warm relay; everyone preloads that.
|
||||||
|
if (warmUrl != null) return _WarmTarget(head.id, open: warmUrl);
|
||||||
|
return performer ? _WarmTarget(head.id) : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keeps the one item that plays next ready on this app, so a skip or
|
||||||
|
/// the end of what plays starts it at once: a link probed when this app
|
||||||
|
/// puts it up (`AppYtDlp.probe`, kept while it stays first), a Jellyfin
|
||||||
|
/// item resolved with this app's account
|
||||||
|
/// ([SessionCoordinator.warmJellyfin]), and then opened in the hidden
|
||||||
|
/// preload player ([MediaPipeline.prepare]) once the media
|
||||||
|
/// playing has started. Done as soon as it is first, again before that
|
||||||
|
/// runs out, dropped when it is no longer first.
|
||||||
|
void _warm(StateBroadcast? r) {
|
||||||
|
_feedWarm(r);
|
||||||
|
final t = _warmTarget(r);
|
||||||
|
final key = t?.key ?? '';
|
||||||
|
if (key != _warmKey) {
|
||||||
|
_dropWarm(r);
|
||||||
|
_warmKey = key;
|
||||||
|
if (t == null) {
|
||||||
|
if (warm.peek() != null) warm.value = null;
|
||||||
|
} else if (t.empty) {
|
||||||
|
warm.value = (id: t.id, state: WarmState.ready);
|
||||||
|
} else {
|
||||||
|
warm.value = (id: t.id, state: WarmState.warming);
|
||||||
|
_resolveWarm(t, fresh: false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_syncPreload(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The warm relay this app feeds (`<queue id>|<token>`), started once.
|
||||||
|
String _fedWarm = '';
|
||||||
|
|
||||||
|
/// Feeds the server's warm relay of Up next's first item from here when
|
||||||
|
/// it names this member as its source (a link passed on, a file), or a
|
||||||
|
/// Jellyfin item this app puts up with its own account when the server
|
||||||
|
/// asks for a source; see [RelayFeeder.feedWarm]. The server
|
||||||
|
/// drops the relay (and with it the source) once the item is no longer
|
||||||
|
/// first.
|
||||||
|
void _feedWarm(StateBroadcast? r) {
|
||||||
|
final head = r?.queue.firstOrNull;
|
||||||
|
final relay = head?.media.relay;
|
||||||
|
if (r == null || head == null || relay == null || relay.fetch) return;
|
||||||
|
final key = '${head.id}|${coord.connection.token}';
|
||||||
|
if (key == _fedWarm) return;
|
||||||
|
switch (head.how) {
|
||||||
|
case QueueHow.through:
|
||||||
|
case QueueHow.file:
|
||||||
|
if (relay.source != _me) return;
|
||||||
|
final pick = _local[head.key]?.pick;
|
||||||
|
if (pick is FileMedia) {
|
||||||
|
_fedWarm = key;
|
||||||
|
coord.media.feeder.feedWarm(head.id, RelayMedia.single(FileRelayBytes(File(pick.path))));
|
||||||
|
} else if (pick is LinkMedia) {
|
||||||
|
_fedWarm = key;
|
||||||
|
unawaited(() async {
|
||||||
|
try {
|
||||||
|
// The probe [_resolveWarm] keeps: no second yt-dlp run.
|
||||||
|
final probe = await coord.ytDlp.probe(pick.url, keep: _warmKeep).timeout(const Duration(seconds: 60));
|
||||||
|
final y = await coord.ytDlp.ytDlp;
|
||||||
|
if (_fedWarm != key) return;
|
||||||
|
coord.media.feeder.feedWarm(head.id, LinkRelayMedia(Uri.parse(pick.url), ytDlp: y, probe: probe));
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('queue: feeding ${head.id}: $e');
|
||||||
|
}
|
||||||
|
}());
|
||||||
|
}
|
||||||
|
case QueueHow.jellyfin:
|
||||||
|
final ref = head.media.jellyfin;
|
||||||
|
if (ref == null || (relay.source.isNotEmpty && relay.source != _me)) return;
|
||||||
|
if (queuePerformer(head, r.members).id != _me) return;
|
||||||
|
// Resolved with this app's account by [_resolveWarm].
|
||||||
|
final w = coord.warmJellyfin;
|
||||||
|
if (w == null || !sameJellyfinItem(w.ref, ref)) return;
|
||||||
|
_fedWarm = key;
|
||||||
|
coord.media.feeder.feedWarm(
|
||||||
|
head.id, RelayMedia.single(HttpRelayBytes(Uri.parse(w.plan.url), headers: w.plan.headers)));
|
||||||
|
case QueueHow.direct:
|
||||||
|
case QueueHow.server:
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _dropWarm(StateBroadcast? r) {
|
||||||
|
_warmTimer?.cancel();
|
||||||
|
_warmTimer = null;
|
||||||
|
_warmGen++;
|
||||||
|
_preloadWant = null;
|
||||||
|
final url = _warmUrl;
|
||||||
|
_warmUrl = null;
|
||||||
|
if (url != null) coord.ytDlp.release(url);
|
||||||
|
// Kept while it is what just went up: that open takes it.
|
||||||
|
final w = coord.warmJellyfin;
|
||||||
|
if (w != null && !sameJellyfinItem(w.ref, refOfStateMedia(r?.media))) coord.warmJellyfin = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
void _resolveWarm(_WarmTarget t, {required bool fresh}) {
|
||||||
|
final gen = ++_warmGen;
|
||||||
|
unawaited(() async {
|
||||||
|
var ok = true;
|
||||||
|
({String url, Map<String, String>? headers})? open;
|
||||||
|
try {
|
||||||
|
final probe = t.probe, ref = t.ref, url = t.open;
|
||||||
|
if (probe != null) {
|
||||||
|
_warmUrl = probe;
|
||||||
|
final p = await coord.ytDlp.probe(probe, keep: _warmKeep, fresh: fresh).timeout(const Duration(seconds: 60));
|
||||||
|
ok = p.problem == null;
|
||||||
|
}
|
||||||
|
if (ref != null) {
|
||||||
|
final plan = await resolveJellyfinRef(coord.jellyfin, ref, relay: false, relayUrl: null);
|
||||||
|
if (gen != _warmGen) return;
|
||||||
|
ok = plan is OwnPlay;
|
||||||
|
if (plan is OwnPlay) {
|
||||||
|
coord.warmJellyfin = (ref: ref, plan: plan, until: DateTime.now().add(_warmKeep));
|
||||||
|
open = (url: plan.url, headers: plan.headers);
|
||||||
|
_feedWarm(coord.serverState.peek());
|
||||||
|
}
|
||||||
|
} else if (url != null && ok) {
|
||||||
|
open = (url: url, headers: null);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
ok = false;
|
||||||
|
debugPrint('queue: getting ${t.id} ready: $e');
|
||||||
|
}
|
||||||
|
if (gen != _warmGen) return;
|
||||||
|
_preloadWant = ok ? open : null;
|
||||||
|
// A refresh opens a link again (a page's stream URLs expire); the
|
||||||
|
// same Jellyfin stream stays as it is.
|
||||||
|
_preloadFresh = fresh && ok && t.ref == null && open != null;
|
||||||
|
final waits = ok && open != null && coord.media.preloadEnabled;
|
||||||
|
warm.value = (id: t.id, state: !ok ? WarmState.failed : (waits ? WarmState.warming : WarmState.ready));
|
||||||
|
_syncPreload(coord.serverState.peek());
|
||||||
|
_warmTimer = Timer(ok ? _warmRefresh : _warmRetry, () => _resolveWarm(t, fresh: true));
|
||||||
|
}());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Puts [_preloadWant] in the preload player, or drops what it holds;
|
||||||
|
/// only once the media playing has started (its own open goes first,
|
||||||
|
/// and a preload a swap is about to take is never replaced before), at
|
||||||
|
/// once while sitting out (nothing preloads then).
|
||||||
|
void _syncPreload(StateBroadcast? r) {
|
||||||
|
// The newest state seen here: the coordinator's lags behind while the
|
||||||
|
// same `state` is still being handed to it.
|
||||||
|
final seen = _lastState;
|
||||||
|
if (r == null || (seen != null && seen.mediaId > r.mediaId)) r = seen;
|
||||||
|
if (r == null) return;
|
||||||
|
final out = coord.selfAway.peek();
|
||||||
|
if (!out && r.media != null && coord.settledMediaId.peek() != r.mediaId) return;
|
||||||
|
final want = out ? null : _preloadWant;
|
||||||
|
final media = coord.media;
|
||||||
|
if (want == null) {
|
||||||
|
_preloadKey = '';
|
||||||
|
_preloadGen++;
|
||||||
|
if (media.preloadUrl != null) unawaited(media.dropPrepared());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!media.preloadEnabled) return;
|
||||||
|
final key = '${want.url}|${want.headers}';
|
||||||
|
final fresh = _preloadFresh;
|
||||||
|
// Asked for already: in flight, there, or failed (tried again with the
|
||||||
|
// next refresh). One that went away (Reload video) is asked again.
|
||||||
|
if (!fresh && key == _preloadKey && (_preloadBusy || !_preloadOk || media.preloadUrl == want.url)) return;
|
||||||
|
_preloadFresh = false;
|
||||||
|
_preloadKey = key;
|
||||||
|
_preloadBusy = true;
|
||||||
|
final gen = ++_preloadGen;
|
||||||
|
final id = warm.peek()?.id;
|
||||||
|
unawaited(coord.media.prepare(want.url, headers: want.headers, fresh: fresh).then((ok) {
|
||||||
|
if (gen != _preloadGen) return;
|
||||||
|
_preloadBusy = false;
|
||||||
|
_preloadOk = ok;
|
||||||
|
// A preload that fails leaves the usual open: nothing to say.
|
||||||
|
if (!ok) debugPrint('queue: preload of $id failed');
|
||||||
|
final w = warm.peek();
|
||||||
|
if (w != null && w.id == id && w.state == WarmState.warming) {
|
||||||
|
warm.value = (id: w.id, state: WarmState.ready);
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------- continuation
|
||||||
|
|
||||||
|
/// The next few episodes after the one playing (own account only).
|
||||||
|
Future<void> _loadContinuation(EpisodeLink? next, JellyfinPlan? plan) async {
|
||||||
|
if (next == null || plan is! OwnPlay) {
|
||||||
|
_continuationFor = '';
|
||||||
|
if (continuation.peek().isNotEmpty) continuation.value = const [];
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final key = '${plan.account.serverId}/${next.item.id}';
|
||||||
|
if (key == _continuationFor) return;
|
||||||
|
_continuationFor = key;
|
||||||
|
continuation.value = [next];
|
||||||
|
final seriesId = next.item.seriesId;
|
||||||
|
if (seriesId == null) return;
|
||||||
|
try {
|
||||||
|
final list = await coord.jellyfin.cached(
|
||||||
|
plan.account.serverId, 'episodes:$seriesId', () => plan.client.episodes(seriesId));
|
||||||
|
if (_continuationFor != key) return;
|
||||||
|
final more = [next];
|
||||||
|
var at = next.item;
|
||||||
|
while (more.length < 4) {
|
||||||
|
final after = episodeAfter(list, at.id);
|
||||||
|
if (after == null) break;
|
||||||
|
more.add(EpisodeLink(after, pickFor(plan.account, after)));
|
||||||
|
at = after;
|
||||||
|
}
|
||||||
|
continuation.value = more;
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('queue: continuation of $seriesId: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What [QueueController] gets ready for one item on this app: [probe] a
|
||||||
|
/// link (the app that puts it up), resolve [ref] with this app's own
|
||||||
|
/// account, and preload [open] (or the resolved stream). None of it:
|
||||||
|
/// nothing to do here, and it is ready ([empty]).
|
||||||
|
class _WarmTarget {
|
||||||
|
final String id;
|
||||||
|
final String? probe;
|
||||||
|
final JellyfinRef? ref;
|
||||||
|
final String? open;
|
||||||
|
const _WarmTarget(this.id, {this.probe, this.ref, this.open});
|
||||||
|
|
||||||
|
bool get empty => probe == null && ref == null && open == null;
|
||||||
|
String get key => '$id|$probe|$open|${ref?.serverId}/${ref?.itemId}/${ref?.mediaSourceId}';
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
|
// Up next's words for an item. Who puts an item up is core's
|
||||||
|
// `queuePerformer` (whats_next.dart), read the same by the server and
|
||||||
|
// every app.
|
||||||
|
|
||||||
|
/// How [item] plays, in a few words for its row: "through Foxyz" (you:
|
||||||
|
/// "through you"), "server fetches", "everyone fetches", "Jellyfin",
|
||||||
|
/// "Foxyz's file".
|
||||||
|
String queueHowLabel(QueueItem item, {required String selfId}) {
|
||||||
|
final mine = item.by == selfId && selfId.isNotEmpty;
|
||||||
|
final who = mine ? 'you' : (item.byName.isEmpty ? 'who added it' : item.byName);
|
||||||
|
return switch (item.how) {
|
||||||
|
QueueHow.through => 'through $who',
|
||||||
|
QueueHow.file => mine ? 'your file' : "$who's file",
|
||||||
|
QueueHow.server => 'server fetches',
|
||||||
|
QueueHow.direct => 'everyone fetches',
|
||||||
|
QueueHow.jellyfin => 'Jellyfin',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "1:23:45" / "23:45" for [secs]; empty when unknown.
|
||||||
|
String queueClock(double secs) {
|
||||||
|
if (secs <= 0) return '';
|
||||||
|
final s = secs.round();
|
||||||
|
final h = s ~/ 3600, m = (s % 3600) ~/ 60, r = s % 60;
|
||||||
|
String two(int v) => v.toString().padLeft(2, '0');
|
||||||
|
return h > 0 ? '$h:${two(m)}:${two(r)}' : '$m:${two(r)}';
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -8,8 +8,10 @@ import 'package:sync_relay_core/core.dart';
|
|||||||
|
|
||||||
|
|
||||||
// AniList airing schedule (public GraphQL, no login): every episode airing
|
// AniList airing schedule (public GraphQL, no login): every episode airing
|
||||||
// in a time range, with covers, banners and popularity; and a title search
|
// in a time range, with covers, banners and popularity; a title search
|
||||||
// (cover + banner of a show, for the media art of files and links).
|
// (cover + banner of a show, for the media art of files and links); and
|
||||||
|
// the library's lookups (search with synonyms and relations, one entry by
|
||||||
|
// id; see ARCHITECTURE.md "Media identity").
|
||||||
//
|
//
|
||||||
// AniList allows ~90 requests/min (sometimes degraded to 30), so the raw
|
// AniList allows ~90 requests/min (sometimes degraded to 30), so the raw
|
||||||
// pages are cached: in memory for 10 min (tab switches) and on disk for an
|
// pages are cached: in memory for 10 min (tab switches) and on disk for an
|
||||||
@@ -105,6 +107,177 @@ class AniListMedia {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// An anime as the library matches it ([AniListClient.searchAnime],
|
||||||
|
/// [AniListClient.anime]): titles and synonyms to match on, its format
|
||||||
|
/// and length, art, and the next TV entry of its run ([sequel]) to number
|
||||||
|
/// across split seasons and cours. JSON round-trips for the library's
|
||||||
|
/// cache ([toJson]).
|
||||||
|
class AniListEntry {
|
||||||
|
final int id;
|
||||||
|
final String romaji;
|
||||||
|
final String english;
|
||||||
|
final String native;
|
||||||
|
final List<String> synonyms;
|
||||||
|
/// `TV`, `TV_SHORT`, `MOVIE`, `OVA`, `ONA`, `SPECIAL`, `MUSIC`; '' unknown.
|
||||||
|
final String format;
|
||||||
|
/// Null while it airs with no announced count.
|
||||||
|
final int? episodes;
|
||||||
|
final int? year;
|
||||||
|
final String? cover;
|
||||||
|
final String? coverSmall;
|
||||||
|
final String? banner;
|
||||||
|
/// The next TV / TV_SHORT / ONA entry (`SEQUEL` relation).
|
||||||
|
final int? sequel;
|
||||||
|
final int? prequel;
|
||||||
|
/// Episode titles AniList knows (its streaming episodes), by number.
|
||||||
|
final Map<int, String> episodeTitles;
|
||||||
|
|
||||||
|
const AniListEntry({
|
||||||
|
required this.id,
|
||||||
|
this.romaji = '',
|
||||||
|
this.english = '',
|
||||||
|
this.native = '',
|
||||||
|
this.synonyms = const [],
|
||||||
|
this.format = '',
|
||||||
|
this.episodes,
|
||||||
|
this.year,
|
||||||
|
this.cover,
|
||||||
|
this.coverSmall,
|
||||||
|
this.banner,
|
||||||
|
this.sequel,
|
||||||
|
this.prequel,
|
||||||
|
this.episodeTitles = const {},
|
||||||
|
});
|
||||||
|
|
||||||
|
/// English title, else romaji.
|
||||||
|
String get title => english.isNotEmpty ? english : (romaji.isNotEmpty ? romaji : native);
|
||||||
|
|
||||||
|
/// Every name it goes by, for matching.
|
||||||
|
List<String> get names => [
|
||||||
|
for (final t in [english, romaji, native, ...synonyms])
|
||||||
|
if (t.trim().isNotEmpty) t,
|
||||||
|
];
|
||||||
|
|
||||||
|
bool get isMovie => format == 'MOVIE';
|
||||||
|
|
||||||
|
/// A run of episodes a season or cour is made of.
|
||||||
|
bool get isSeries => format == 'TV' || format == 'TV_SHORT' || format == 'ONA';
|
||||||
|
|
||||||
|
static const graphQLFields = 'id title{romaji english native} synonyms format episodes seasonYear '
|
||||||
|
'coverImage{extraLarge large} bannerImage '
|
||||||
|
'relations{edges{relationType node{id format type}}} streamingEpisodes{title}';
|
||||||
|
|
||||||
|
static final _streamingTitle = RegExp(r'^\s*(?:Episode|Ep\.?)\s*(\d{1,4})\s*[-–:]\s*(.+)$', caseSensitive: false);
|
||||||
|
|
||||||
|
/// From an AniList `Media` object; null when it has no id.
|
||||||
|
static AniListEntry? fromGraphQL(Object? m) {
|
||||||
|
if (m is! Map || m['id'] is! int) return null;
|
||||||
|
String str(Object? v) => v is String ? v : '';
|
||||||
|
final t = m['title'] is Map ? m['title'] as Map : const {};
|
||||||
|
final cov = m['coverImage'] is Map ? m['coverImage'] as Map : const {};
|
||||||
|
final large = cov['large'] is String ? cov['large'] as String : null;
|
||||||
|
int? related(String type) {
|
||||||
|
final edges = m['relations'] is Map ? (m['relations'] as Map)['edges'] : null;
|
||||||
|
if (edges is! List) return null;
|
||||||
|
for (final e in edges) {
|
||||||
|
if (e is! Map || e['relationType'] != type) continue;
|
||||||
|
final node = e['node'];
|
||||||
|
if (node is Map && node['id'] is int && node['type'] != 'MANGA' &&
|
||||||
|
const {'TV', 'TV_SHORT', 'ONA'}.contains(node['format'])) {
|
||||||
|
return node['id'] as int;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
final titles = <int, String>{};
|
||||||
|
final streaming = m['streamingEpisodes'];
|
||||||
|
if (streaming is List) {
|
||||||
|
for (final s in streaming) {
|
||||||
|
final match = s is Map && s['title'] is String ? _streamingTitle.firstMatch(s['title'] as String) : null;
|
||||||
|
if (match != null) titles.putIfAbsent(int.parse(match.group(1)!), () => match.group(2)!.trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return AniListEntry(
|
||||||
|
id: m['id'] as int,
|
||||||
|
romaji: str(t['romaji']),
|
||||||
|
english: str(t['english']),
|
||||||
|
native: str(t['native']),
|
||||||
|
synonyms: [
|
||||||
|
if (m['synonyms'] is List)
|
||||||
|
for (final s in m['synonyms'] as List)
|
||||||
|
if (s is String && s.trim().isNotEmpty) s.trim(),
|
||||||
|
],
|
||||||
|
format: str(m['format']),
|
||||||
|
episodes: m['episodes'] is int ? m['episodes'] as int : null,
|
||||||
|
year: m['seasonYear'] is int ? m['seasonYear'] as int : null,
|
||||||
|
cover: cov['extraLarge'] is String ? cov['extraLarge'] as String : large,
|
||||||
|
coverSmall: large,
|
||||||
|
banner: m['bannerImage'] is String ? m['bannerImage'] as String : null,
|
||||||
|
sequel: related('SEQUEL'),
|
||||||
|
prequel: related('PREQUEL'),
|
||||||
|
episodeTitles: titles,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object?> toJson() => {
|
||||||
|
'id': id,
|
||||||
|
'romaji': romaji,
|
||||||
|
'english': english,
|
||||||
|
'native': native,
|
||||||
|
'synonyms': synonyms,
|
||||||
|
'format': format,
|
||||||
|
'episodes': episodes,
|
||||||
|
'year': year,
|
||||||
|
'cover': cover,
|
||||||
|
'coverSmall': coverSmall,
|
||||||
|
'banner': banner,
|
||||||
|
'sequel': sequel,
|
||||||
|
'prequel': prequel,
|
||||||
|
'episodeTitles': {for (final e in episodeTitles.entries) '${e.key}': e.value},
|
||||||
|
};
|
||||||
|
|
||||||
|
static AniListEntry? fromJson(Object? j) {
|
||||||
|
if (j is! Map || j['id'] is! int) return null;
|
||||||
|
String str(Object? v) => v is String ? v : '';
|
||||||
|
String? opt(Object? v) => v is String ? v : null;
|
||||||
|
int? n(Object? v) => v is int ? v : null;
|
||||||
|
final titles = j['episodeTitles'];
|
||||||
|
return AniListEntry(
|
||||||
|
id: j['id'] as int,
|
||||||
|
romaji: str(j['romaji']),
|
||||||
|
english: str(j['english']),
|
||||||
|
native: str(j['native']),
|
||||||
|
synonyms: [if (j['synonyms'] is List) ...(j['synonyms'] as List).whereType<String>()],
|
||||||
|
format: str(j['format']),
|
||||||
|
episodes: n(j['episodes']),
|
||||||
|
year: n(j['year']),
|
||||||
|
cover: opt(j['cover']),
|
||||||
|
coverSmall: opt(j['coverSmall']),
|
||||||
|
banner: opt(j['banner']),
|
||||||
|
sequel: n(j['sequel']),
|
||||||
|
prequel: n(j['prequel']),
|
||||||
|
episodeTitles: {
|
||||||
|
if (titles is Map)
|
||||||
|
for (final e in titles.entries)
|
||||||
|
if (int.tryParse('${e.key}') case final k? when e.value is String) k: e.value as String,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => 'AniListEntry($id "$title" $format ${episodes ?? '?'} eps)';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the library asks AniList ([AniListClient]; tests fake it).
|
||||||
|
abstract interface class AniListLookup {
|
||||||
|
/// Anime matching [query], AniList's best first.
|
||||||
|
Future<List<AniListEntry>> searchAnime(String query);
|
||||||
|
|
||||||
|
/// One anime by id; null when AniList has none.
|
||||||
|
Future<AniListEntry?> anime(int id);
|
||||||
|
}
|
||||||
|
|
||||||
/// "#e4a15d" -> opaque [Color]; anything else -> null.
|
/// "#e4a15d" -> opaque [Color]; anything else -> null.
|
||||||
Color? parseHexColor(Object? s) {
|
Color? parseHexColor(Object? s) {
|
||||||
if (s is! String || s.length != 7 || !s.startsWith('#')) return null;
|
if (s is! String || s.length != 7 || !s.startsWith('#')) return null;
|
||||||
@@ -142,7 +315,7 @@ class _Cached {
|
|||||||
const _Cached(this.fetched, this.from, this.to, this.raw);
|
const _Cached(this.fetched, this.from, this.to, this.raw);
|
||||||
}
|
}
|
||||||
|
|
||||||
class AniListClient {
|
class AniListClient implements AniListLookup {
|
||||||
AniListClient({
|
AniListClient({
|
||||||
String url = aniListDefaultUrl,
|
String url = aniListDefaultUrl,
|
||||||
HttpClient? http,
|
HttpClient? http,
|
||||||
@@ -158,7 +331,7 @@ class AniListClient {
|
|||||||
_cacheDir = cacheDir ?? _defaultCacheDir,
|
_cacheDir = cacheDir ?? _defaultCacheDir,
|
||||||
_delay = delay ?? Future<void>.delayed,
|
_delay = delay ?? Future<void>.delayed,
|
||||||
_now = now ?? DateTime.now,
|
_now = now ?? DateTime.now,
|
||||||
userAgent = userAgent ?? 'watch-together/$appVersion';
|
userAgent = userAgent ?? 'Starsync/$appVersion';
|
||||||
|
|
||||||
final Uri url;
|
final Uri url;
|
||||||
final Duration memoryTtl;
|
final Duration memoryTtl;
|
||||||
@@ -306,6 +479,49 @@ coverImage{extraLarge large} bannerImage}}''';
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static final _listQuery = 'query(\$search:String){Page(perPage:8){media(search:\$search,type:ANIME,'
|
||||||
|
'isAdult:false,sort:SEARCH_MATCH){${AniListEntry.graphQLFields}}}}';
|
||||||
|
static final _byIdQuery = 'query(\$id:Int){Media(id:\$id,type:ANIME){${AniListEntry.graphQLFields}}}';
|
||||||
|
|
||||||
|
/// Up to 8 anime matching [query], AniList's best first (the library's
|
||||||
|
/// matching and its "Wrong show?" search). Not cached here: the library
|
||||||
|
/// keeps what it needs.
|
||||||
|
@override
|
||||||
|
Future<List<AniListEntry>> searchAnime(String query) async {
|
||||||
|
final q = query.trim();
|
||||||
|
if (q.isEmpty) return const [];
|
||||||
|
final (data, _, _) = await _graphql(_listQuery, {'search': q});
|
||||||
|
final page = data?['Page'];
|
||||||
|
final media = page is Map ? page['media'] : null;
|
||||||
|
return [if (media is List) for (final m in media) ?AniListEntry.fromGraphQL(m)];
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<AniListEntry?> anime(int id) async {
|
||||||
|
try {
|
||||||
|
final (data, _, _) = await _graphql(_byIdQuery, {'id': id});
|
||||||
|
return AniListEntry.fromGraphQL(data?['Media']);
|
||||||
|
} on AniListException catch (e) {
|
||||||
|
if (e.statusCode == 404) return null;
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static const byIdArtQuery = r'''
|
||||||
|
query($id:Int){Media(id:$id,type:ANIME){id title{romaji english} coverImage{extraLarge large} bannerImage}}''';
|
||||||
|
|
||||||
|
/// Cover and banner of AniList entry [id] (the media art of a file the
|
||||||
|
/// library matched); null when there is none.
|
||||||
|
Future<AniListMedia?> mediaById(int id) async {
|
||||||
|
try {
|
||||||
|
final (data, _, _) = await _graphql(byIdArtQuery, {'id': id});
|
||||||
|
return AniListMedia.fromJson(data?['Media']);
|
||||||
|
} on AniListException catch (e) {
|
||||||
|
if (e.statusCode == 404) return null;
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
static String _errorText(Object? j) {
|
static String _errorText(Object? j) {
|
||||||
final errs = j is Map ? j['errors'] : null;
|
final errs = j is Map ? j['errors'] : null;
|
||||||
if (errs is! List || errs.isEmpty) return '';
|
if (errs is! List || errs.isEmpty) return '';
|
||||||
|
|||||||
@@ -198,6 +198,8 @@ class AnimeFlowEpisode {
|
|||||||
final int episode;
|
final int episode;
|
||||||
final int? absolute;
|
final int? absolute;
|
||||||
final String? title;
|
final String? title;
|
||||||
|
/// Date-only: midnight Japan time of the broadcast day. Compare it as a
|
||||||
|
/// Japan day (`sameAirDay` in schedule_model.dart), never a local one.
|
||||||
final DateTime? airDate;
|
final DateTime? airDate;
|
||||||
/// The AniList entry of this episode's season (one AnimeFlow series may
|
/// The AniList entry of this episode's season (one AnimeFlow series may
|
||||||
/// span several AniList entries).
|
/// span several AniList entries).
|
||||||
@@ -208,8 +210,11 @@ class AnimeFlowEpisode {
|
|||||||
final EpisodeStatus status;
|
final EpisodeStatus status;
|
||||||
/// 0..1, only while downloading.
|
/// 0..1, only while downloading.
|
||||||
final double? progress;
|
final double? progress;
|
||||||
/// Only when failed.
|
/// Why it failed; for a missing one with rejected releases, a
|
||||||
|
/// ready-to-show sentence ("2 release(s) found, rejected: …").
|
||||||
final String? reason;
|
final String? reason;
|
||||||
|
/// Last search for a monitored, not yet downloaded episode.
|
||||||
|
final DateTime? lastSearchedAt;
|
||||||
|
|
||||||
const AnimeFlowEpisode({
|
const AnimeFlowEpisode({
|
||||||
required this.season,
|
required this.season,
|
||||||
@@ -222,6 +227,7 @@ class AnimeFlowEpisode {
|
|||||||
required this.status,
|
required this.status,
|
||||||
this.progress,
|
this.progress,
|
||||||
this.reason,
|
this.reason,
|
||||||
|
this.lastSearchedAt,
|
||||||
});
|
});
|
||||||
|
|
||||||
static AnimeFlowEpisode fromJson(Map j) => AnimeFlowEpisode(
|
static AnimeFlowEpisode fromJson(Map j) => AnimeFlowEpisode(
|
||||||
@@ -237,6 +243,7 @@ class AnimeFlowEpisode {
|
|||||||
status: EpisodeStatus.parse(j['status']),
|
status: EpisodeStatus.parse(j['status']),
|
||||||
progress: (j['progress'] as num?)?.toDouble(),
|
progress: (j['progress'] as num?)?.toDouble(),
|
||||||
reason: _str(j['reason']),
|
reason: _str(j['reason']),
|
||||||
|
lastSearchedAt: _time(j['last_searched_at']),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -467,7 +474,7 @@ class AnimeFlowClient {
|
|||||||
_ownsHttp = http == null,
|
_ownsHttp = http == null,
|
||||||
_delay = delay ?? Future<void>.delayed,
|
_delay = delay ?? Future<void>.delayed,
|
||||||
_now = now ?? DateTime.now,
|
_now = now ?? DateTime.now,
|
||||||
userAgent = userAgent ?? 'watch-together/$appVersion';
|
userAgent = userAgent ?? 'Starsync/$appVersion';
|
||||||
|
|
||||||
/// Authenticated with the linked Jellyfin account on the same domain
|
/// Authenticated with the linked Jellyfin account on the same domain
|
||||||
/// (see [tokenFor]), looked up on every call so a re-link applies.
|
/// (see [tokenFor]), looked up on every call so a re-link applies.
|
||||||
|
|||||||
@@ -12,8 +12,12 @@ enum ScheduleStatus {
|
|||||||
available,
|
available,
|
||||||
downloading,
|
downloading,
|
||||||
upcoming,
|
upcoming,
|
||||||
|
/// AnimeFlow's `missing`: aired, monitored, no release grabbed yet;
|
||||||
|
/// AnimeFlow grabs it by itself once one appears (nothing to request).
|
||||||
|
/// Also an aired episode of a tracked series AnimeFlow has no row for.
|
||||||
missing,
|
missing,
|
||||||
failed,
|
failed,
|
||||||
|
/// AnimeFlow does not monitor it: the only status worth a Request.
|
||||||
unmonitored,
|
unmonitored,
|
||||||
/// AnimeFlow does not track this series (or is unreachable).
|
/// AnimeFlow does not track this series (or is unreachable).
|
||||||
notTracked,
|
notTracked,
|
||||||
@@ -44,8 +48,10 @@ class ScheduleEntry {
|
|||||||
final ScheduleStatus status;
|
final ScheduleStatus status;
|
||||||
/// 0..1 while downloading.
|
/// 0..1 while downloading.
|
||||||
final double? progress;
|
final double? progress;
|
||||||
/// Why it failed.
|
/// Why it failed, or (missing) why the releases found were rejected.
|
||||||
final String? reason;
|
final String? reason;
|
||||||
|
/// AnimeFlow's last search for it (missing).
|
||||||
|
final DateTime? lastSearchedAt;
|
||||||
/// AnimeFlow tracks the series.
|
/// AnimeFlow tracks the series.
|
||||||
final bool tracked;
|
final bool tracked;
|
||||||
/// AnimeFlow's series id (requests).
|
/// AnimeFlow's series id (requests).
|
||||||
@@ -53,11 +59,15 @@ class ScheduleEntry {
|
|||||||
/// The AnimeFlow season of the matched episode (requests); untracked
|
/// The AnimeFlow season of the matched episode (requests); untracked
|
||||||
/// on Jellyfin: the TVDB season of the AniList entry.
|
/// on Jellyfin: the TVDB season of the AniList entry.
|
||||||
final int? season;
|
final int? season;
|
||||||
/// Untracked on Jellyfin: the TVDB episode number in [season] (AniList
|
/// The TVDB episode number in [season]: tracked, AnimeFlow's own;
|
||||||
/// episode + the `anilist_map` run's offset).
|
/// untracked on Jellyfin, AniList episode + the `anilist_map` run's
|
||||||
|
/// offset.
|
||||||
final int? jellyfinEpisode;
|
final int? jellyfinEpisode;
|
||||||
/// Play target once available.
|
/// Play target once available.
|
||||||
final String? jellyfinSeriesId;
|
final String? jellyfinSeriesId;
|
||||||
|
/// This user's progress on the Jellyfin episode ([confirmOnJellyfin]);
|
||||||
|
/// null when it is not on Jellyfin or was not looked up.
|
||||||
|
final EpisodeWatch? watch;
|
||||||
/// The series is on Jellyfin (tracked or not).
|
/// The series is on Jellyfin (tracked or not).
|
||||||
bool get onJellyfin => jellyfinSeriesId != null;
|
bool get onJellyfin => jellyfinSeriesId != null;
|
||||||
|
|
||||||
@@ -66,23 +76,27 @@ class ScheduleEntry {
|
|||||||
required this.status,
|
required this.status,
|
||||||
this.progress,
|
this.progress,
|
||||||
this.reason,
|
this.reason,
|
||||||
|
this.lastSearchedAt,
|
||||||
this.tracked = false,
|
this.tracked = false,
|
||||||
this.seriesId,
|
this.seriesId,
|
||||||
this.season,
|
this.season,
|
||||||
this.jellyfinEpisode,
|
this.jellyfinEpisode,
|
||||||
this.jellyfinSeriesId,
|
this.jellyfinSeriesId,
|
||||||
|
this.watch,
|
||||||
});
|
});
|
||||||
|
|
||||||
ScheduleEntry withStatus(ScheduleStatus s) => ScheduleEntry(
|
ScheduleEntry copyWith({ScheduleStatus? status, EpisodeWatch? watch}) => ScheduleEntry(
|
||||||
airing: airing,
|
airing: airing,
|
||||||
status: s,
|
status: status ?? this.status,
|
||||||
progress: progress,
|
progress: progress,
|
||||||
reason: reason,
|
reason: reason,
|
||||||
|
lastSearchedAt: lastSearchedAt,
|
||||||
tracked: tracked,
|
tracked: tracked,
|
||||||
seriesId: seriesId,
|
seriesId: seriesId,
|
||||||
season: season,
|
season: season,
|
||||||
jellyfinEpisode: jellyfinEpisode,
|
jellyfinEpisode: jellyfinEpisode,
|
||||||
jellyfinSeriesId: jellyfinSeriesId,
|
jellyfinSeriesId: jellyfinSeriesId,
|
||||||
|
watch: watch ?? this.watch,
|
||||||
);
|
);
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -95,11 +109,59 @@ ScheduleEntry untrackedEntry(Airing a, DateTime now) => ScheduleEntry(
|
|||||||
status: a.airingAt.isAfter(now) ? ScheduleStatus.upcoming : ScheduleStatus.notTracked,
|
status: a.airingAt.isAfter(now) ? ScheduleStatus.upcoming : ScheduleStatus.notTracked,
|
||||||
);
|
);
|
||||||
|
|
||||||
String _day(DateTime d) {
|
/// This user's state of a Jellyfin episode (its `UserData`).
|
||||||
final l = d.toLocal();
|
class EpisodeWatch {
|
||||||
return '${l.year}-${l.month}-${l.day}';
|
final bool played;
|
||||||
|
/// 0..1: the resume point of a partly watched episode (0 = none).
|
||||||
|
final double progress;
|
||||||
|
const EpisodeWatch({this.played = false, this.progress = 0});
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool operator ==(Object other) => other is EpisodeWatch && other.played == played && other.progress == progress;
|
||||||
|
@override
|
||||||
|
int get hashCode => Object.hash(played, progress);
|
||||||
|
@override
|
||||||
|
String toString() => 'EpisodeWatch(${played ? 'played' : '$progress'})';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One episode Jellyfin has of a series, as the schedule needs it.
|
||||||
|
class JellyfinEpisodeRef {
|
||||||
|
final int season;
|
||||||
|
final int episode;
|
||||||
|
/// Jellyfin's date-only premiere date.
|
||||||
|
final DateTime? premiere;
|
||||||
|
final EpisodeWatch watch;
|
||||||
|
const JellyfinEpisodeRef(this.season, this.episode, {this.premiere, this.watch = const EpisodeWatch()});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Air dates (AnimeFlow's `air_date`, Jellyfin's premiere date) are
|
||||||
|
// date-only: the Japanese broadcast day, sent as midnight Japan time (or
|
||||||
|
// midnight UTC by older servers). Both land on the right day read as a
|
||||||
|
// Japan (UTC+9, no DST) calendar day, never as a local one: midnight JST
|
||||||
|
// is the evening before in Europe and America.
|
||||||
|
const _jst = Duration(hours: 9);
|
||||||
|
|
||||||
|
/// The Japan calendar day of [t].
|
||||||
|
DateTime _jstDay(DateTime t) {
|
||||||
|
final j = t.toUtc().add(_jst);
|
||||||
|
return DateTime.utc(j.year, j.month, j.day);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _dayKey(DateTime d) => '${d.year}-${d.month}-${d.day}';
|
||||||
|
|
||||||
|
/// The Japan days whose air date fits a broadcast at [airingAt]: its own
|
||||||
|
/// and, for a late-night slot (before 05:00 JST, "25:30"), the evening
|
||||||
|
/// before, which listings often give.
|
||||||
|
List<DateTime> _airDays(DateTime airingAt) {
|
||||||
|
final j = airingAt.toUtc().add(_jst);
|
||||||
|
final d = DateTime.utc(j.year, j.month, j.day);
|
||||||
|
return [d, if (j.hour < 5) DateTime.utc(j.year, j.month, j.day - 1)];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The date-only [airDate] is the broadcast day of [airingAt] (see
|
||||||
|
/// [_airDays]).
|
||||||
|
bool sameAirDay(DateTime airDate, DateTime airingAt) => _airDays(airingAt).contains(_jstDay(airDate));
|
||||||
|
|
||||||
class _SeriesRef {
|
class _SeriesRef {
|
||||||
final int seriesId;
|
final int seriesId;
|
||||||
final String? jellyfinSeriesId;
|
final String? jellyfinSeriesId;
|
||||||
@@ -155,7 +217,7 @@ List<ScheduleEntry> matchSchedule(
|
|||||||
}
|
}
|
||||||
byEp.putIfAbsent('$id#${e.episode}', () => it);
|
byEp.putIfAbsent('$id#${e.episode}', () => it);
|
||||||
if (e.absolute != null) byAbs.putIfAbsent('$id#${e.absolute}', () => it);
|
if (e.absolute != null) byAbs.putIfAbsent('$id#${e.absolute}', () => it);
|
||||||
if (e.airDate != null) byDay.putIfAbsent('$id@${_day(e.airDate!)}', () => it);
|
if (e.airDate != null) byDay.putIfAbsent('$id@${_dayKey(_jstDay(e.airDate!))}', () => it);
|
||||||
}
|
}
|
||||||
return [
|
return [
|
||||||
for (final a in airings)
|
for (final a in airings)
|
||||||
@@ -164,17 +226,21 @@ List<ScheduleEntry> matchSchedule(
|
|||||||
final ref = refs[id];
|
final ref = refs[id];
|
||||||
final it = numbered.contains(id)
|
final it = numbered.contains(id)
|
||||||
? byAni['$id#${a.episode}']
|
? byAni['$id#${a.episode}']
|
||||||
: byEp['$id#${a.episode}'] ?? byAbs['$id#${a.episode}'] ?? byDay['$id@${_day(a.airingAt)}'];
|
: byEp['$id#${a.episode}'] ??
|
||||||
|
byAbs['$id#${a.episode}'] ??
|
||||||
|
_airDays(a.airingAt).map((d) => byDay['$id@${_dayKey(d)}']).nonNulls.firstOrNull;
|
||||||
if (it != null) {
|
if (it != null) {
|
||||||
final e = it.episode;
|
final e = it.episode;
|
||||||
return ScheduleEntry(
|
return ScheduleEntry(
|
||||||
airing: a,
|
airing: a,
|
||||||
status: ScheduleStatus.of(e.status),
|
status: ScheduleStatus.of(e.status),
|
||||||
progress: e.status == EpisodeStatus.downloading ? e.progress : null,
|
progress: e.status == EpisodeStatus.downloading ? e.progress : null,
|
||||||
reason: e.status == EpisodeStatus.failed ? e.reason : null,
|
reason: e.status == EpisodeStatus.failed || e.status == EpisodeStatus.missing ? e.reason : null,
|
||||||
|
lastSearchedAt: e.lastSearchedAt,
|
||||||
tracked: true,
|
tracked: true,
|
||||||
seriesId: it.seriesId,
|
seriesId: it.seriesId,
|
||||||
season: e.season,
|
season: e.season,
|
||||||
|
jellyfinEpisode: e.episode,
|
||||||
jellyfinSeriesId: it.jellyfinSeriesId ?? ref?.jellyfinSeriesId ?? lib[id]?.$1,
|
jellyfinSeriesId: it.jellyfinSeriesId ?? ref?.jellyfinSeriesId ?? lib[id]?.$1,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -200,26 +266,45 @@ List<ScheduleEntry> matchSchedule(
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Checks [matchSchedule]'s [ScheduleStatus.inLibrary] entries (series
|
/// The episodes [confirmOnJellyfin] looks up: on Jellyfin, untracked
|
||||||
/// on Jellyfin) against the episodes Jellyfin has: [episodes] maps a
|
/// ([ScheduleStatus.inLibrary]) or available through AnimeFlow.
|
||||||
/// Jellyfin series id to its (season, episode) numbers. Found stays
|
bool needsJellyfinLookup(ScheduleEntry e) =>
|
||||||
/// inLibrary, absent becomes [ScheduleStatus.notOnJellyfin], a series
|
e.jellyfinSeriesId != null && (e.status == ScheduleStatus.inLibrary || e.status == ScheduleStatus.available);
|
||||||
/// missing from [episodes] (not looked up) [ScheduleStatus.aired].
|
|
||||||
List<ScheduleEntry> confirmOnJellyfin(List<ScheduleEntry> entries, Map<String, Set<(int, int)>> episodes) => [
|
/// Checks [matchSchedule]'s entries against the episodes Jellyfin has:
|
||||||
|
/// [episodes] maps a Jellyfin series id to its episodes. An
|
||||||
|
/// [ScheduleStatus.inLibrary] one found stays inLibrary, absent becomes
|
||||||
|
/// [ScheduleStatus.notOnJellyfin], a series missing from [episodes] (not
|
||||||
|
/// looked up) [ScheduleStatus.aired]. Found episodes (inLibrary or
|
||||||
|
/// available) get this user's [ScheduleEntry.watch]: (season, episode),
|
||||||
|
/// else the one premiered that day.
|
||||||
|
List<ScheduleEntry> confirmOnJellyfin(List<ScheduleEntry> entries, Map<String, List<JellyfinEpisodeRef>> episodes) => [
|
||||||
for (final e in entries)
|
for (final e in entries)
|
||||||
if (e.status != ScheduleStatus.inLibrary)
|
if (!needsJellyfinLookup(e))
|
||||||
e
|
e
|
||||||
else
|
else
|
||||||
switch (episodes[e.jellyfinSeriesId]) {
|
switch ((episodes[e.jellyfinSeriesId], e.status)) {
|
||||||
null => e.withStatus(ScheduleStatus.aired),
|
(null, ScheduleStatus.inLibrary) => e.copyWith(status: ScheduleStatus.aired),
|
||||||
final have when have.contains((e.season, e.jellyfinEpisode)) => e,
|
(null, _) => e,
|
||||||
_ => e.withStatus(ScheduleStatus.notOnJellyfin),
|
(final have?, _) => switch (_episodeOf(have, e)) {
|
||||||
|
final x? => e.copyWith(watch: x.watch),
|
||||||
|
null when e.status == ScheduleStatus.inLibrary => e.copyWith(status: ScheduleStatus.notOnJellyfin),
|
||||||
|
null => e,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
/// The (season, episode) numbers Jellyfin has of a series; null when it
|
JellyfinEpisodeRef? _episodeOf(List<JellyfinEpisodeRef> have, ScheduleEntry e) {
|
||||||
/// cannot tell (no linked account for that server).
|
final byNumber = have.where((x) => x.season == e.season && x.episode == e.jellyfinEpisode).firstOrNull;
|
||||||
typedef JellyfinEpisodeLookup = Future<Set<(int, int)>?> Function(String jellyfinSeriesId);
|
if (byNumber != null || !e.tracked) return byNumber;
|
||||||
|
// AnimeFlow's numbering missed (specials, renumbered seasons): the
|
||||||
|
// episode premiered that day, when only one did.
|
||||||
|
return have.where((x) => x.premiere != null && sameAirDay(x.premiere!, e.airing.airingAt)).singleOrNull;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The episodes Jellyfin has of a series, as the linked account sees
|
||||||
|
/// them; null when it cannot tell (no linked account for that server).
|
||||||
|
typedef JellyfinEpisodeLookup = Future<List<JellyfinEpisodeRef>?> Function(String jellyfinSeriesId);
|
||||||
|
|
||||||
/// One loaded window. Errors are display text; [entries] is empty only
|
/// One loaded window. Errors are display text; [entries] is empty only
|
||||||
/// when AniList failed with nothing cached.
|
/// when AniList failed with nothing cached.
|
||||||
@@ -262,8 +347,9 @@ class ScheduleRepository {
|
|||||||
final AniListClient aniList;
|
final AniListClient aniList;
|
||||||
/// Null = not configured (AniList only).
|
/// Null = not configured (AniList only).
|
||||||
final AnimeFlowClient? animeFlow;
|
final AnimeFlowClient? animeFlow;
|
||||||
/// Confirms "on Jellyfin" per episode ([confirmOnJellyfin]); null =
|
/// Confirms "on Jellyfin" and this user's watched state per episode
|
||||||
/// never confirmed (aired entries read [ScheduleStatus.aired]).
|
/// ([confirmOnJellyfin]); null = never confirmed (aired entries read
|
||||||
|
/// [ScheduleStatus.aired], nothing shows as watched).
|
||||||
final JellyfinEpisodeLookup? jellyfinEpisodes;
|
final JellyfinEpisodeLookup? jellyfinEpisodes;
|
||||||
final DateTime Function() _now;
|
final DateTime Function() _now;
|
||||||
|
|
||||||
@@ -303,15 +389,16 @@ class ScheduleRepository {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Looks up the episodes of every series an inLibrary entry is on, in
|
/// Looks up the episodes of every series an entry on Jellyfin is on
|
||||||
/// parallel; a failed or impossible lookup leaves that series out.
|
/// ([needsJellyfinLookup]), in parallel, one request per series; a
|
||||||
|
/// failed or impossible lookup leaves that series out.
|
||||||
Future<List<ScheduleEntry>> _confirm(List<ScheduleEntry> entries) async {
|
Future<List<ScheduleEntry>> _confirm(List<ScheduleEntry> entries) async {
|
||||||
final lookup = jellyfinEpisodes;
|
final lookup = jellyfinEpisodes;
|
||||||
final ids = {
|
final ids = {
|
||||||
for (final e in entries)
|
for (final e in entries)
|
||||||
if (e.status == ScheduleStatus.inLibrary && e.jellyfinSeriesId != null) e.jellyfinSeriesId!,
|
if (needsJellyfinLookup(e)) e.jellyfinSeriesId!,
|
||||||
};
|
};
|
||||||
final found = <String, Set<(int, int)>>{};
|
final found = <String, List<JellyfinEpisodeRef>>{};
|
||||||
if (lookup != null) {
|
if (lookup != null) {
|
||||||
await Future.wait([
|
await Future.wait([
|
||||||
for (final id in ids)
|
for (final id in ids)
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import 'package:sync_relay_core/core.dart';
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
import '../../jellyfin/accounts.dart';
|
import '../../jellyfin/accounts.dart';
|
||||||
import '../../jellyfin/format.dart' show pickFor;
|
import '../../jellyfin/format.dart' show pickFor, progressOf;
|
||||||
import '../../screens/home/picked_media.dart';
|
import '../../screens/home/picked_media.dart';
|
||||||
import '../anilist.dart';
|
import '../anilist.dart';
|
||||||
import '../animeflow.dart';
|
import '../animeflow.dart';
|
||||||
@@ -47,14 +47,9 @@ String friendlyError(Object e) => switch (e) {
|
|||||||
_ => '$e',
|
_ => '$e',
|
||||||
};
|
};
|
||||||
|
|
||||||
bool _sameDay(DateTime a, DateTime b) {
|
|
||||||
final x = a.toLocal(), y = b.toLocal();
|
|
||||||
return x.year == y.year && x.month == y.month && x.day == y.day;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// AnimeFlow's episode for [e] (its season and numbering), from the
|
/// AnimeFlow's episode for [e] (its season and numbering), from the
|
||||||
/// series detail: same AniList id and episode, else absolute number, else
|
/// series detail: same AniList id and episode, else absolute number, else
|
||||||
/// the same air day. Null when the entry is not tracked or nothing fits.
|
/// the same air day ([sameAirDay]). Null when the entry is not tracked or nothing fits.
|
||||||
Future<AnimeFlowEpisode?> flowEpisodeFor(AnimeFlowClient client, ScheduleEntry e) async {
|
Future<AnimeFlowEpisode?> flowEpisodeFor(AnimeFlowClient client, ScheduleEntry e) async {
|
||||||
final id = e.seriesId;
|
final id = e.seriesId;
|
||||||
if (id == null) return null;
|
if (id == null) return null;
|
||||||
@@ -63,7 +58,7 @@ Future<AnimeFlowEpisode?> flowEpisodeFor(AnimeFlowClient client, ScheduleEntry e
|
|||||||
final mine = eps.where((x) => x.anilistId == null || x.anilistId == a.anilistId).toList();
|
final mine = eps.where((x) => x.anilistId == null || x.anilistId == a.anilistId).toList();
|
||||||
return mine.where((x) => x.anilistId == a.anilistId && x.episode == a.episode).firstOrNull ??
|
return mine.where((x) => x.anilistId == a.anilistId && x.episode == a.episode).firstOrNull ??
|
||||||
mine.where((x) => x.absolute == a.episode).firstOrNull ??
|
mine.where((x) => x.absolute == a.episode).firstOrNull ??
|
||||||
mine.where((x) => x.airDate != null && _sameDay(x.airDate!, a.airingAt)).firstOrNull;
|
mine.where((x) => x.airDate != null && sameAirDay(x.airDate!, a.airingAt)).firstOrNull;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The (season, episode) AnimeFlow uses for [e]; falls back to the
|
/// The (season, episode) AnimeFlow uses for [e]; falls back to the
|
||||||
@@ -112,11 +107,13 @@ JellyfinAccount? jellyfinAccountFor(JellyfinAccounts accounts, AnimeFlowClient?
|
|||||||
return accounts.defaultAccount;
|
return accounts.defaultAccount;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The (season, episode) numbers of the episodes Jellyfin has of
|
/// The episodes Jellyfin has of [jellyfinSeriesId] (numbers, premiere
|
||||||
/// [jellyfinSeriesId], seen by the account AnimeFlow's ids belong to
|
/// date, this user's watched state), seen by the account AnimeFlow's ids
|
||||||
/// ([jellyfinAccountFor]); null without a linked account. One request per
|
/// belong to ([jellyfinAccountFor]): the user's own; null without a
|
||||||
/// series, memoised a few minutes ([JellyfinAccounts.cached]).
|
/// linked account. One request per series, memoised a few minutes
|
||||||
Future<Set<(int, int)>?> jellyfinEpisodeNumbers(
|
/// ([JellyfinAccounts.cached]; a stop report drops it,
|
||||||
|
/// [JellyfinAccounts.watched]).
|
||||||
|
Future<List<JellyfinEpisodeRef>?> jellyfinScheduleEpisodes(
|
||||||
JellyfinAccounts accounts,
|
JellyfinAccounts accounts,
|
||||||
AnimeFlowClient? flow,
|
AnimeFlowClient? flow,
|
||||||
String jellyfinSeriesId,
|
String jellyfinSeriesId,
|
||||||
@@ -125,10 +122,20 @@ Future<Set<(int, int)>?> jellyfinEpisodeNumbers(
|
|||||||
final account = jellyfinAccountFor(accounts, flow);
|
final account = jellyfinAccountFor(accounts, flow);
|
||||||
final client = account == null ? null : accounts.clientFor(account.serverId);
|
final client = account == null ? null : accounts.clientFor(account.serverId);
|
||||||
if (account == null || client == null) return null;
|
if (account == null || client == null) return null;
|
||||||
return accounts.cached(account.serverId, 'schedule-episodes:$jellyfinSeriesId', () async => {
|
return accounts.cached(
|
||||||
|
account.serverId,
|
||||||
|
'schedule-episodes:$jellyfinSeriesId',
|
||||||
|
() async => [
|
||||||
for (final x in await client.episodes(jellyfinSeriesId))
|
for (final x in await client.episodes(jellyfinSeriesId))
|
||||||
if (x.parentIndexNumber != null && x.indexNumber != null) (x.parentIndexNumber!, x.indexNumber!),
|
if (x.parentIndexNumber != null && x.indexNumber != null)
|
||||||
});
|
JellyfinEpisodeRef(
|
||||||
|
x.parentIndexNumber!,
|
||||||
|
x.indexNumber!,
|
||||||
|
premiere: x.premiereDate,
|
||||||
|
watch: EpisodeWatch(played: x.userData.played, progress: x.userData.played ? 0 : progressOf(x)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The Jellyfin episode of an available [e] as a media pick. Throws
|
/// The Jellyfin episode of an available [e] as a media pick. Throws
|
||||||
@@ -153,7 +160,7 @@ Future<JellyfinMedia> resolveJellyfinEpisode(JellyfinAccounts accounts, AnimeFlo
|
|||||||
final a = e.airing;
|
final a = e.airing;
|
||||||
final item =
|
final item =
|
||||||
eps.where((x) => x.parentIndexNumber == n.season && x.indexNumber == n.episode).firstOrNull ??
|
eps.where((x) => x.parentIndexNumber == n.season && x.indexNumber == n.episode).firstOrNull ??
|
||||||
eps.where((x) => x.premiereDate != null && _sameDay(x.premiereDate!, a.airingAt)).singleOrNull ??
|
eps.where((x) => x.premiereDate != null && sameAirDay(x.premiereDate!, a.airingAt)).singleOrNull ??
|
||||||
eps.where((x) => x.indexNumber == a.episode).singleOrNull;
|
eps.where((x) => x.indexNumber == a.episode).singleOrNull;
|
||||||
if (item == null) {
|
if (item == null) {
|
||||||
throw ScheduleActionException('Episode ${a.episode} of ${a.title} is not on Jellyfin yet');
|
throw ScheduleActionException('Episode ${a.episode} of ${a.title} is not on Jellyfin yet');
|
||||||
|
|||||||
@@ -4,16 +4,16 @@ import 'package:flutter/material.dart';
|
|||||||
import '../schedule_model.dart';
|
import '../schedule_model.dart';
|
||||||
|
|
||||||
// One day of the Schedule board and its airing cards: cover poster on the
|
// One day of the Schedule board and its airing cards: cover poster on the
|
||||||
// left (air time on it, download progress under it), title, episode and
|
// left (air time on it, download progress or this user's watch progress
|
||||||
// status on the right, one full-width action below. Compact mode is a
|
// under it, a check once watched), title, episode and status on the
|
||||||
// slim row.
|
// right, one full-width action below. Compact mode is a slim row.
|
||||||
|
|
||||||
/// What a card's action does, decided by the page.
|
/// What a card's action does, decided by the page.
|
||||||
enum CardAction {
|
enum CardAction {
|
||||||
none,
|
none,
|
||||||
putUp,
|
putUp,
|
||||||
|
|
||||||
/// Available, nobody else watching (offline or solo): plays it here.
|
/// Available, nobody else in the server: plays it here.
|
||||||
play,
|
play,
|
||||||
request,
|
request,
|
||||||
requestSeries,
|
requestSeries,
|
||||||
@@ -35,8 +35,29 @@ String countdownText(DateTime at, DateTime now) {
|
|||||||
return 'in ${d.inMinutes}m';
|
return 'in ${d.inMinutes}m';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Aired, tracked, no release yet: AnimeFlow downloads it by itself.
|
||||||
|
bool _waiting(ScheduleEntry e, DateTime now) =>
|
||||||
|
e.status == ScheduleStatus.missing ||
|
||||||
|
(e.status == ScheduleStatus.upcoming && e.tracked && !e.airing.airingAt.isAfter(now));
|
||||||
|
|
||||||
|
const waitingHint = 'Aired in Japan; downloads automatically when a release appears';
|
||||||
|
|
||||||
|
String _ago(DateTime t, DateTime now) {
|
||||||
|
final m = now.difference(t).inMinutes;
|
||||||
|
return m < 1 ? 'just now' : m < 60 ? '$m min ago' : '${m ~/ 60} h ago';
|
||||||
|
}
|
||||||
|
|
||||||
/// Status line: text, colour, icon.
|
/// Status line: text, colour, icon.
|
||||||
(String, Color, IconData) statusBadge(ScheduleEntry e, DateTime now) => switch (e.status) {
|
(String, Color, IconData) statusBadge(ScheduleEntry e, DateTime now) => _waiting(e, now)
|
||||||
|
? e.reason != null
|
||||||
|
// Releases exist but AnimeFlow rejected them (the hint says why).
|
||||||
|
? ('release rejected', Colors.orangeAccent, Icons.block)
|
||||||
|
: (
|
||||||
|
e.lastSearchedAt == null ? 'waiting for release' : 'waiting · searched ${_ago(e.lastSearchedAt!, now)}',
|
||||||
|
Colors.amber.shade200,
|
||||||
|
Icons.hourglass_top,
|
||||||
|
)
|
||||||
|
: switch (e.status) {
|
||||||
ScheduleStatus.available => ('on Jellyfin', Colors.greenAccent, Icons.check_circle),
|
ScheduleStatus.available => ('on Jellyfin', Colors.greenAccent, Icons.check_circle),
|
||||||
ScheduleStatus.downloading => (
|
ScheduleStatus.downloading => (
|
||||||
e.progress == null ? 'downloading' : 'downloading ${(e.progress! * 100).round()}%',
|
e.progress == null ? 'downloading' : 'downloading ${(e.progress! * 100).round()}%',
|
||||||
@@ -44,14 +65,25 @@ String countdownText(DateTime at, DateTime now) {
|
|||||||
Icons.downloading,
|
Icons.downloading,
|
||||||
),
|
),
|
||||||
ScheduleStatus.upcoming => (countdownText(e.airing.airingAt, now), Colors.amber, Icons.schedule),
|
ScheduleStatus.upcoming => (countdownText(e.airing.airingAt, now), Colors.amber, Icons.schedule),
|
||||||
ScheduleStatus.missing => ('missing', Colors.orangeAccent, Icons.report_gmailerrorred),
|
ScheduleStatus.missing => ('waiting for release', Colors.amber.shade200, Icons.hourglass_top),
|
||||||
ScheduleStatus.failed => ('failed${e.reason == null ? '' : ' · ${e.reason}'}', Colors.redAccent, Icons.error_outline),
|
ScheduleStatus.failed => (
|
||||||
|
'failed${e.reason == null ? '' : ' · ${e.reason}'}',
|
||||||
|
Colors.redAccent,
|
||||||
|
Icons.error_outline,
|
||||||
|
),
|
||||||
ScheduleStatus.unmonitored => ('not monitored', Colors.grey, Icons.visibility_off_outlined),
|
ScheduleStatus.unmonitored => ('not monitored', Colors.grey, Icons.visibility_off_outlined),
|
||||||
ScheduleStatus.notTracked => ('not in AnimeFlow', Colors.grey, Icons.public),
|
ScheduleStatus.notTracked => ('not in AnimeFlow', Colors.grey, Icons.public),
|
||||||
ScheduleStatus.inLibrary => ('on Jellyfin', Colors.greenAccent, Icons.video_library_outlined),
|
ScheduleStatus.inLibrary => ('on Jellyfin', Colors.greenAccent, Icons.video_library_outlined),
|
||||||
ScheduleStatus.notOnJellyfin => ('aired · not on Jellyfin yet', Colors.grey, Icons.hourglass_empty),
|
ScheduleStatus.notOnJellyfin => ('aired · not on Jellyfin yet', Colors.grey, Icons.hourglass_empty),
|
||||||
ScheduleStatus.aired => ('aired', Colors.grey, Icons.done),
|
ScheduleStatus.aired => ('aired', Colors.grey, Icons.done),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// What the status line means, when its text alone does not say.
|
||||||
|
String? statusHint(ScheduleEntry e, DateTime now) => !_waiting(e, now)
|
||||||
|
? null
|
||||||
|
: e.reason != null
|
||||||
|
? '${e.reason}${e.lastSearchedAt == null ? '' : ' · searched ${_ago(e.lastSearchedAt!, now)}'}'
|
||||||
|
: waitingHint;
|
||||||
|
|
||||||
class DayColumn extends StatelessWidget {
|
class DayColumn extends StatelessWidget {
|
||||||
final DateTime day;
|
final DateTime day;
|
||||||
@@ -137,6 +169,9 @@ class AiringCard extends StatelessWidget {
|
|||||||
final bool busy;
|
final bool busy;
|
||||||
final VoidCallback onAction;
|
final VoidCallback onAction;
|
||||||
|
|
||||||
|
/// Right-click ([context]: the card): the page's menu; null: none.
|
||||||
|
final void Function(BuildContext context)? onMenu;
|
||||||
|
|
||||||
const AiringCard({
|
const AiringCard({
|
||||||
super.key,
|
super.key,
|
||||||
required this.entry,
|
required this.entry,
|
||||||
@@ -146,6 +181,7 @@ class AiringCard extends StatelessWidget {
|
|||||||
required this.onAction,
|
required this.onAction,
|
||||||
this.disabledHint,
|
this.disabledHint,
|
||||||
this.busy = false,
|
this.busy = false,
|
||||||
|
this.onMenu,
|
||||||
});
|
});
|
||||||
|
|
||||||
String get _id => '${entry.airing.anilistId}-${entry.airing.episode}';
|
String get _id => '${entry.airing.anilistId}-${entry.airing.episode}';
|
||||||
@@ -153,6 +189,56 @@ class AiringCard extends StatelessWidget {
|
|||||||
Widget _image(String? url, Widget fallback) =>
|
Widget _image(String? url, Widget fallback) =>
|
||||||
url == null ? fallback : Image.network(url, fit: BoxFit.cover, errorBuilder: (_, _, _) => fallback);
|
url == null ? fallback : Image.network(url, fit: BoxFit.cover, errorBuilder: (_, _, _) => fallback);
|
||||||
|
|
||||||
|
static Widget _hinted(String? hint, Widget child) => hint == null ? child : Tooltip(message: hint, child: child);
|
||||||
|
|
||||||
|
bool get _played => entry.watch?.played ?? false;
|
||||||
|
|
||||||
|
/// A watched episode's cover is a little dimmer.
|
||||||
|
Widget _dimmed(Widget cover) => _played ? Opacity(opacity: 0.6, child: cover) : cover;
|
||||||
|
|
||||||
|
/// This user's state of the episode on Jellyfin: the library cards'
|
||||||
|
/// green check once watched, else a thin bar to the resume point.
|
||||||
|
List<Widget> _watchMarks({bool small = false}) {
|
||||||
|
final w = entry.watch;
|
||||||
|
if (w == null) return const [];
|
||||||
|
if (w.played) {
|
||||||
|
final size = small ? 16.0 : 22.0;
|
||||||
|
return [
|
||||||
|
Positioned(
|
||||||
|
top: small ? 2 : 4,
|
||||||
|
right: small ? 2 : 4,
|
||||||
|
child: Tooltip(
|
||||||
|
message: 'Watched',
|
||||||
|
child: Container(
|
||||||
|
key: ValueKey('watched-$_id'),
|
||||||
|
constraints: BoxConstraints(minWidth: size, minHeight: size),
|
||||||
|
alignment: Alignment.center,
|
||||||
|
decoration: BoxDecoration(color: const Color(0xCC1B5E20), borderRadius: BorderRadius.circular(size / 2)),
|
||||||
|
child: Icon(Icons.check, size: small ? 11 : 14, color: Colors.white),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
if (w.progress <= 0) return const [];
|
||||||
|
return [
|
||||||
|
Positioned(
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
bottom: 0,
|
||||||
|
child: Tooltip(
|
||||||
|
message: '${(w.progress * 100).round()}% watched',
|
||||||
|
child: LinearProgressIndicator(
|
||||||
|
key: ValueKey('watch-progress-$_id'),
|
||||||
|
value: w.progress,
|
||||||
|
minHeight: small ? 2 : 3,
|
||||||
|
backgroundColor: Colors.black54,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
Widget? _button(BuildContext context) {
|
Widget? _button(BuildContext context) {
|
||||||
final enabled = disabledHint == null && !busy;
|
final enabled = disabledHint == null && !busy;
|
||||||
final spinner = const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2));
|
final spinner = const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2));
|
||||||
@@ -180,6 +266,7 @@ class AiringCard extends StatelessWidget {
|
|||||||
final scheme = Theme.of(context).colorScheme;
|
final scheme = Theme.of(context).colorScheme;
|
||||||
final a = entry.airing;
|
final a = entry.airing;
|
||||||
final (label, color, icon) = statusBadge(entry, now);
|
final (label, color, icon) = statusBadge(entry, now);
|
||||||
|
final hint = statusHint(entry, now);
|
||||||
final time = clockText(a.airingAt);
|
final time = clockText(a.airingAt);
|
||||||
final tintColor = a.color ?? Colors.blueGrey;
|
final tintColor = a.color ?? Colors.blueGrey;
|
||||||
final tint = DecoratedBox(
|
final tint = DecoratedBox(
|
||||||
@@ -191,7 +278,11 @@ class AiringCard extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
final tap = (action == CardAction.putUp || action == CardAction.play) && disabledHint == null && !busy ? onAction : null;
|
final tap = (action == CardAction.putUp || action == CardAction.play) && disabledHint == null && !busy
|
||||||
|
? onAction
|
||||||
|
: null;
|
||||||
|
final onMenu = this.onMenu;
|
||||||
|
final menu = onMenu == null || busy ? null : () => onMenu(context);
|
||||||
if (compact) {
|
if (compact) {
|
||||||
final requestable = action == CardAction.request || action == CardAction.requestSeries;
|
final requestable = action == CardAction.request || action == CardAction.requestSeries;
|
||||||
return Material(
|
return Material(
|
||||||
@@ -201,13 +292,21 @@ class AiringCard extends StatelessWidget {
|
|||||||
child: InkWell(
|
child: InkWell(
|
||||||
borderRadius: BorderRadius.circular(10),
|
borderRadius: BorderRadius.circular(10),
|
||||||
onTap: tap,
|
onTap: tap,
|
||||||
|
onSecondaryTap: menu,
|
||||||
child: Padding(
|
child: Padding(
|
||||||
padding: const EdgeInsets.all(6),
|
padding: const EdgeInsets.all(6),
|
||||||
child: Row(
|
child: Row(
|
||||||
children: [
|
children: [
|
||||||
ClipRRect(
|
ClipRRect(
|
||||||
borderRadius: BorderRadius.circular(6),
|
borderRadius: BorderRadius.circular(6),
|
||||||
child: SizedBox(width: 34, height: 48, child: _image(a.cover, tint)),
|
child: SizedBox(
|
||||||
|
width: 34,
|
||||||
|
height: 48,
|
||||||
|
child: Stack(
|
||||||
|
fit: StackFit.expand,
|
||||||
|
children: [_dimmed(_image(a.cover, tint)), ..._watchMarks(small: true)],
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
Expanded(
|
Expanded(
|
||||||
@@ -237,7 +336,7 @@ class AiringCard extends StatelessWidget {
|
|||||||
)
|
)
|
||||||
else
|
else
|
||||||
Tooltip(
|
Tooltip(
|
||||||
message: label,
|
message: hint == null ? label : '$label: $hint',
|
||||||
child: Icon(icon, size: 16, color: color),
|
child: Icon(icon, size: 16, color: color),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@@ -255,6 +354,7 @@ class AiringCard extends StatelessWidget {
|
|||||||
clipBehavior: Clip.antiAlias,
|
clipBehavior: Clip.antiAlias,
|
||||||
child: InkWell(
|
child: InkWell(
|
||||||
onTap: tap,
|
onTap: tap,
|
||||||
|
onSecondaryTap: menu,
|
||||||
child: Padding(
|
child: Padding(
|
||||||
padding: const EdgeInsets.all(8),
|
padding: const EdgeInsets.all(8),
|
||||||
child: Column(
|
child: Column(
|
||||||
@@ -271,7 +371,7 @@ class AiringCard extends StatelessWidget {
|
|||||||
child: Stack(
|
child: Stack(
|
||||||
fit: StackFit.expand,
|
fit: StackFit.expand,
|
||||||
children: [
|
children: [
|
||||||
_image(a.cover, tint),
|
_dimmed(_image(a.cover, tint)),
|
||||||
Positioned(
|
Positioned(
|
||||||
left: 4,
|
left: 4,
|
||||||
top: 4,
|
top: 4,
|
||||||
@@ -287,6 +387,7 @@ class AiringCard extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
..._watchMarks(),
|
||||||
if (entry.status == ScheduleStatus.downloading)
|
if (entry.status == ScheduleStatus.downloading)
|
||||||
Positioned(
|
Positioned(
|
||||||
left: 0,
|
left: 0,
|
||||||
@@ -323,6 +424,8 @@ class AiringCard extends StatelessWidget {
|
|||||||
style: TextStyle(color: scheme.onSurfaceVariant, fontSize: 12),
|
style: TextStyle(color: scheme.onSurfaceVariant, fontSize: 12),
|
||||||
),
|
),
|
||||||
const Spacer(),
|
const Spacer(),
|
||||||
|
_hinted(
|
||||||
|
hint,
|
||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
Icon(icon, size: 14, color: color),
|
Icon(icon, size: 14, color: color),
|
||||||
@@ -337,6 +440,7 @@ class AiringCard extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import '../../jellyfin/accounts.dart';
|
|||||||
import '../../screens/home/picked_media.dart';
|
import '../../screens/home/picked_media.dart';
|
||||||
import '../../shell/avatar.dart';
|
import '../../shell/avatar.dart';
|
||||||
import '../../shell/motion.dart';
|
import '../../shell/motion.dart';
|
||||||
|
import '../../widgets/app_menu.dart';
|
||||||
import '../anilist.dart';
|
import '../anilist.dart';
|
||||||
import '../animeflow.dart';
|
import '../animeflow.dart';
|
||||||
import '../schedule_model.dart';
|
import '../schedule_model.dart';
|
||||||
@@ -15,18 +16,22 @@ import 'schedule_card.dart';
|
|||||||
|
|
||||||
// The Schedule tab: one column per day from last week's Monday to four
|
// The Schedule tab: one column per day from last week's Monday to four
|
||||||
// weeks out (AniList), each airing with what AnimeFlow has of it, and the
|
// weeks out (AniList), each airing with what AnimeFlow has of it, and the
|
||||||
// one thing to do about it (put it up, request it). Refreshes every
|
// one thing to do about it (put it up, request it; right-click an
|
||||||
// minute while visible; ETags keep that cheap.
|
// available one to queue it). Refreshes every minute while visible; ETags
|
||||||
|
// keep that cheap. Episodes on Jellyfin show this user's watched state,
|
||||||
|
// reloaded after a playback stops (JellyfinAccounts.watched).
|
||||||
|
|
||||||
enum ScheduleFilter { jellyfin, all }
|
enum ScheduleFilter { jellyfin, all }
|
||||||
|
|
||||||
class SchedulePage extends StatefulWidget {
|
class SchedulePage extends StatefulWidget {
|
||||||
/// Nobody else watches (offline or solo): available episodes say Play
|
/// Nobody else is in the server (D9): available episodes say Play.
|
||||||
/// (offline that starts a solo session).
|
final bool alone;
|
||||||
final bool solo;
|
|
||||||
|
|
||||||
/// Puts a Jellyfin episode up in the server; returns an error to show.
|
/// Puts a Jellyfin episode up in the server; returns an error to show.
|
||||||
final Future<String?> Function(JellyfinMedia pick) onPutUp;
|
final Future<String?> Function(JellyfinMedia pick) onPutUp;
|
||||||
|
|
||||||
|
/// Adds an episode to Up next; null: no server, the cards have no menu.
|
||||||
|
final AddToQueue? onAddToQueue;
|
||||||
final void Function(String message) onToast;
|
final void Function(String message) onToast;
|
||||||
|
|
||||||
/// Null = the page makes (and closes) its own.
|
/// Null = the page makes (and closes) its own.
|
||||||
@@ -37,8 +42,9 @@ class SchedulePage extends StatefulWidget {
|
|||||||
|
|
||||||
const SchedulePage({
|
const SchedulePage({
|
||||||
super.key,
|
super.key,
|
||||||
this.solo = false,
|
this.alone = false,
|
||||||
required this.onPutUp,
|
required this.onPutUp,
|
||||||
|
this.onAddToQueue,
|
||||||
required this.onToast,
|
required this.onToast,
|
||||||
this.repository,
|
this.repository,
|
||||||
this.accounts,
|
this.accounts,
|
||||||
@@ -64,6 +70,7 @@ class _SchedulePageState extends State<SchedulePage> {
|
|||||||
bool _refreshing = false;
|
bool _refreshing = false;
|
||||||
int _gen = 0;
|
int _gen = 0;
|
||||||
Timer? _timer;
|
Timer? _timer;
|
||||||
|
StreamSubscription<String>? _watchedSub;
|
||||||
final _scroll = ScrollController();
|
final _scroll = ScrollController();
|
||||||
bool _jumped = false;
|
bool _jumped = false;
|
||||||
|
|
||||||
@@ -75,7 +82,6 @@ class _SchedulePageState extends State<SchedulePage> {
|
|||||||
/// The sheet stays built while it slides out.
|
/// The sheet stays built while it slides out.
|
||||||
bool _sheetBuilt = false;
|
bool _sheetBuilt = false;
|
||||||
|
|
||||||
|
|
||||||
/// Requested in this run: "anilistId#episode" or "series:anilistId".
|
/// Requested in this run: "anilistId#episode" or "series:anilistId".
|
||||||
final _requested = <String>{};
|
final _requested = <String>{};
|
||||||
|
|
||||||
@@ -100,6 +106,11 @@ class _SchedulePageState extends State<SchedulePage> {
|
|||||||
_timer = Timer.periodic(SchedulePage.refreshEvery, (_) {
|
_timer = Timer.periodic(SchedulePage.refreshEvery, (_) {
|
||||||
if (mounted && !_refreshing && TickerMode.valuesOf(context).enabled) _load();
|
if (mounted && !_refreshing && TickerMode.valuesOf(context).enabled) _load();
|
||||||
});
|
});
|
||||||
|
// Back from watching: the cards' watched marks follow (the stop report
|
||||||
|
// already dropped the cached episode lists).
|
||||||
|
_watchedSub = _accounts.watched.listen((_) {
|
||||||
|
if (mounted) _load();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
ScheduleRepository _ownRepo() {
|
ScheduleRepository _ownRepo() {
|
||||||
@@ -107,13 +118,14 @@ class _SchedulePageState extends State<SchedulePage> {
|
|||||||
return ScheduleRepository(
|
return ScheduleRepository(
|
||||||
aniList: AniListClient(),
|
aniList: AniListClient(),
|
||||||
animeFlow: flow,
|
animeFlow: flow,
|
||||||
jellyfinEpisodes: (id) => jellyfinEpisodeNumbers(_accounts, flow, id),
|
jellyfinEpisodes: (id) => jellyfinScheduleEpisodes(_accounts, flow, id),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
_timer?.cancel();
|
_timer?.cancel();
|
||||||
|
_watchedSub?.cancel();
|
||||||
_scroll.dispose();
|
_scroll.dispose();
|
||||||
if (_ownsRepo) {
|
if (_ownsRepo) {
|
||||||
_repo.aniList.close();
|
_repo.aniList.close();
|
||||||
@@ -215,16 +227,17 @@ class _SchedulePageState extends State<SchedulePage> {
|
|||||||
|
|
||||||
(CardAction, String?) _actionFor(ScheduleEntry e) {
|
(CardAction, String?) _actionFor(ScheduleEntry e) {
|
||||||
if (e.status == ScheduleStatus.available || e.status == ScheduleStatus.inLibrary) {
|
if (e.status == ScheduleStatus.available || e.status == ScheduleStatus.inLibrary) {
|
||||||
final put = widget.solo ? CardAction.play : CardAction.putUp;
|
final put = widget.alone ? CardAction.play : CardAction.putUp;
|
||||||
if (e.jellyfinSeriesId == null) return (put, 'Not linked to a Jellyfin series yet');
|
if (e.jellyfinSeriesId == null) return (put, 'Not linked to a Jellyfin series yet');
|
||||||
return (put, null);
|
return (put, null);
|
||||||
}
|
}
|
||||||
final me = _me;
|
final me = _me;
|
||||||
final CardAction kind;
|
final CardAction kind;
|
||||||
if (e.tracked) {
|
if (e.tracked) {
|
||||||
kind = e.status == ScheduleStatus.missing || e.status == ScheduleStatus.failed
|
// Only an unmonitored episode is worth asking for: AnimeFlow grabs
|
||||||
? CardAction.request
|
// a missing one (no release yet) by itself once a release appears,
|
||||||
: CardAction.none;
|
// and retries a failed one.
|
||||||
|
kind = e.status == ScheduleStatus.unmonitored ? CardAction.request : CardAction.none;
|
||||||
} else {
|
} else {
|
||||||
// On Jellyfin already (owner added it by hand): nothing to request.
|
// On Jellyfin already (owner added it by hand): nothing to request.
|
||||||
kind = me != null && !e.onJellyfin ? CardAction.requestSeries : CardAction.none;
|
kind = me != null && !e.onJellyfin ? CardAction.requestSeries : CardAction.none;
|
||||||
@@ -267,6 +280,32 @@ class _SchedulePageState extends State<SchedulePage> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Right-click on an available episode ([context]: its card): Put it
|
||||||
|
/// up, Add to queue, Play next.
|
||||||
|
Future<void> _menu(BuildContext context, ScheduleEntry e) async {
|
||||||
|
final add = widget.onAddToQueue;
|
||||||
|
if (add == null) return;
|
||||||
|
final pick = await showAppMenu<int>(context, items: [
|
||||||
|
AppMenuItem(value: 0, label: widget.alone ? 'Play' : 'Put it up'),
|
||||||
|
const AppMenuItem(value: 1, label: 'Add to queue'),
|
||||||
|
const AppMenuItem(value: 2, label: 'Play next'),
|
||||||
|
]);
|
||||||
|
if (pick == null || !mounted) return;
|
||||||
|
if (pick == 0) return _putUp(e);
|
||||||
|
final key = 'play:${_key(e)}';
|
||||||
|
if (_busy.contains(key)) return;
|
||||||
|
setState(() => _busy.add(key));
|
||||||
|
try {
|
||||||
|
final media = await resolveJellyfinEpisode(_accounts, _flow, e);
|
||||||
|
final err = await add(media, next: pick == 2);
|
||||||
|
if (err != null) _toast(err);
|
||||||
|
} catch (err) {
|
||||||
|
_toast(friendlyError(err));
|
||||||
|
} finally {
|
||||||
|
if (mounted) setState(() => _busy.remove(key));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _request(ScheduleEntry e) async {
|
Future<void> _request(ScheduleEntry e) async {
|
||||||
final c = _flow;
|
final c = _flow;
|
||||||
if (c == null) return;
|
if (c == null) return;
|
||||||
@@ -520,6 +559,9 @@ class _SchedulePageState extends State<SchedulePage> {
|
|||||||
disabledHint: hint,
|
disabledHint: hint,
|
||||||
busy: busy,
|
busy: busy,
|
||||||
onAction: () => _onAction(e, action),
|
onAction: () => _onAction(e, action),
|
||||||
|
onMenu: widget.onAddToQueue != null && (action == CardAction.putUp || action == CardAction.play) && hint == null
|
||||||
|
? (context) => _menu(context, e)
|
||||||
|
: null,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,44 +1,27 @@
|
|||||||
import 'dart:io';
|
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter/services.dart';
|
import 'package:signals/signals_flutter.dart';
|
||||||
import 'package:sync_relay_core/core.dart';
|
|
||||||
|
|
||||||
|
import '../../platform/app_log.dart';
|
||||||
|
import '../../shell/mark_problem.dart';
|
||||||
|
import '../../app/app_graph.dart';
|
||||||
|
import '../../state/settings.dart';
|
||||||
import '../../update/update_controller.dart';
|
import '../../update/update_controller.dart';
|
||||||
|
import '../../widgets/app_menu.dart';
|
||||||
|
import '../../widgets/copy_open.dart';
|
||||||
import 'settings_page.dart';
|
import 'settings_page.dart';
|
||||||
import 'ui.dart';
|
import 'ui.dart';
|
||||||
import 'update_indicator.dart';
|
import 'update_indicator.dart';
|
||||||
|
|
||||||
/// Opens [url] in the default browser (no url_launcher dependency).
|
/// The Minimal player skin's credit (README says the same).
|
||||||
Future<bool> openInBrowser(String url) async {
|
const uoscCredit = 'Player timeline and controls inspired by uosc by tomasklaen, LGPL-2.1 '
|
||||||
try {
|
'(github.com/tomasklaen/uosc).';
|
||||||
final ProcessResult r;
|
|
||||||
if (Platform.isWindows) {
|
|
||||||
r = await Process.run('rundll32', ['url.dll,FileProtocolHandler', url]);
|
|
||||||
} else if (Platform.isMacOS) {
|
|
||||||
r = await Process.run('open', [url]);
|
|
||||||
} else {
|
|
||||||
r = await Process.run('xdg-open', [url]);
|
|
||||||
}
|
|
||||||
return r.exitCode == 0;
|
|
||||||
} catch (_) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Name, version, update state and the source link (Settings → About).
|
/// Name, version, update state, the source link and the logs (Settings →
|
||||||
|
/// About).
|
||||||
class AboutPanel extends StatelessWidget {
|
class AboutPanel extends StatelessWidget {
|
||||||
final UpdateController? updates;
|
final UpdateController? updates;
|
||||||
const AboutPanel({super.key, this.updates});
|
const AboutPanel({super.key, this.updates});
|
||||||
|
|
||||||
Future<void> _open(BuildContext context) async {
|
|
||||||
final messenger = ScaffoldMessenger.maybeOf(context);
|
|
||||||
if (await openInBrowser(repoUrl)) return;
|
|
||||||
await Clipboard.setData(const ClipboardData(text: repoUrl));
|
|
||||||
messenger?.showSnackBar(
|
|
||||||
const SnackBar(content: Text('Could not open a browser — link copied')));
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final t = Theme.of(context).textTheme;
|
final t = Theme.of(context).textTheme;
|
||||||
@@ -49,7 +32,7 @@ class AboutPanel extends StatelessWidget {
|
|||||||
children: [
|
children: [
|
||||||
Text(appName, style: t.titleLarge),
|
Text(appName, style: t.titleLarge),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
SelectableText('Version $appVersion',
|
SelectableText('Version ${displayVersion()}',
|
||||||
style: t.bodyMedium?.copyWith(color: Colors.grey)),
|
style: t.bodyMedium?.copyWith(color: Colors.grey)),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
UpdateStatusLine(controller: updates),
|
UpdateStatusLine(controller: updates),
|
||||||
@@ -58,20 +41,90 @@ class AboutPanel extends StatelessWidget {
|
|||||||
children: [
|
children: [
|
||||||
Expanded(child: SelectableText(repoUrl, style: t.bodySmall)),
|
Expanded(child: SelectableText(repoUrl, style: t.bodySmall)),
|
||||||
IconButton(
|
IconButton(
|
||||||
tooltip: 'Copy link',
|
tooltip: ReuseText.copyLink,
|
||||||
icon: const Icon(Icons.copy, size: 18),
|
icon: const Icon(Icons.copy, size: 18),
|
||||||
onPressed: () =>
|
onPressed: () => copyToClipboard(context, repoUrl, done: 'Link copied'),
|
||||||
Clipboard.setData(const ClipboardData(text: repoUrl)),
|
|
||||||
),
|
),
|
||||||
FilledButton.tonalIcon(
|
FilledButton.tonalIcon(
|
||||||
onPressed: () => _open(context),
|
onPressed: () => openLink(context, repoUrl),
|
||||||
icon: const Icon(Icons.open_in_new, size: 18),
|
icon: const Icon(Icons.open_in_new, size: 18),
|
||||||
label: const Text('Source'),
|
label: const Text('Source'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text(uoscCredit, key: const ValueKey('uosc-credit'), style: t.bodySmall?.copyWith(color: Colors.grey)),
|
||||||
|
const SizedBox(height: kGap),
|
||||||
|
Text('Something went wrong? Copy diagnostics and send them to whoever helps you: '
|
||||||
|
'versions and the last hours of the log, passwords, tokens and cookies left out. '
|
||||||
|
'In a session it can add the server\'s session log, everyone\'s lines merged. '
|
||||||
|
'Mark a problem (Ctrl+Shift+B) when it happens so the spot is easy to find.',
|
||||||
|
style: t.bodySmall?.copyWith(color: Colors.grey)),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
runSpacing: 8,
|
||||||
|
children: [
|
||||||
|
Builder(
|
||||||
|
builder: (context) => FilledButton.tonalIcon(
|
||||||
|
key: const ValueKey('copy-diagnostics'),
|
||||||
|
onPressed: () => _copyDiagnostics(context),
|
||||||
|
icon: const Icon(Icons.bug_report_outlined, size: 18),
|
||||||
|
label: const Text('Copy diagnostics'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const MarkProblemButton(outlined: true),
|
||||||
|
OutlinedButton.icon(
|
||||||
|
onPressed: appLogDir == null ? null : () => _openLogs(context),
|
||||||
|
icon: const Icon(Icons.folder_open, size: 18),
|
||||||
|
label: const Text('Open logs folder'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
SignalBuilder(
|
||||||
|
builder: (context) => SwitchListTile(
|
||||||
|
key: const ValueKey('share-diagnostics'),
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
title: const Text('Share diagnostics with the server'),
|
||||||
|
subtitle: const Text('In a session, this app\'s log goes to the server\'s session log, '
|
||||||
|
'merged with everyone\'s, so a problem can be read afterwards. Never chat; '
|
||||||
|
'passwords and tokens left out. Off: only a problem you mark is sent.'),
|
||||||
|
value: AppSettings.instance.shareDiagnostics.value,
|
||||||
|
onChanged: AppSettings.instance.setShareDiagnostics,
|
||||||
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// In a session it asks whether to add the server's session log.
|
||||||
|
static Future<void> _copyDiagnostics(BuildContext context) async {
|
||||||
|
var withServer = false;
|
||||||
|
final graph = AppScope.of(context);
|
||||||
|
if (graph.navigation.online.peek()) {
|
||||||
|
final pick = await showAppMenu<bool>(context, items: const [
|
||||||
|
AppMenuItem(value: false, label: "This app's log"),
|
||||||
|
AppMenuItem(value: true, label: "This app's and the server's session log"),
|
||||||
|
]);
|
||||||
|
if (pick == null) return;
|
||||||
|
withServer = pick;
|
||||||
|
}
|
||||||
|
final text = await diagnosticsText(graph, sessionLog: withServer);
|
||||||
|
final saved = await saveDiagnostics(text);
|
||||||
|
if (!context.mounted) return;
|
||||||
|
await copyToClipboard(context, text,
|
||||||
|
done: saved == null ? 'Diagnostics copied' : 'Diagnostics copied (also saved in the logs folder)');
|
||||||
|
}
|
||||||
|
|
||||||
|
static Future<void> _openLogs(BuildContext context) async {
|
||||||
|
final dir = appLogDir;
|
||||||
|
if (dir == null) return;
|
||||||
|
final folders = AppScope.of(context).ports.folders;
|
||||||
|
if (!await folders.reveal(dir)) {
|
||||||
|
if (!context.mounted) return;
|
||||||
|
await copyToClipboard(context, dir, done: "Couldn't open it — folder path copied");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,25 +1,36 @@
|
|||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
|
|
||||||
|
import '../../session/connection.dart' show connectErrorText;
|
||||||
|
import '../../session/identity.dart';
|
||||||
|
import '../../session/navigation.dart';
|
||||||
import '../../session/session_coordinator.dart';
|
import '../../session/session_coordinator.dart';
|
||||||
import '../../state/session_state.dart';
|
import '../../state/connect_prefs.dart';
|
||||||
import 'profile.dart';
|
import '../../sync/sync_client.dart' show HelloRefused;
|
||||||
|
import 'health_probe.dart' show VersionGateRefused;
|
||||||
|
|
||||||
/// What a card shows under its fields after a failed attempt.
|
/// What the Join card shows under its fields after a failed attempt.
|
||||||
|
/// [offerUpdate]: this app is the older one (the version gate), so the
|
||||||
|
/// card offers the updater.
|
||||||
class CardError {
|
class CardError {
|
||||||
final String title;
|
final String title;
|
||||||
final String message;
|
final String message;
|
||||||
const CardError(this.title, this.message);
|
final bool offerUpdate;
|
||||||
|
const CardError(this.title, this.message, {this.offerUpdate = false});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Host/Join submit state for the strip's two connect cards. One attempt at a time;
|
/// The Join card's submit state, owned by the shell so an attempt and its
|
||||||
/// [cancel] abandons it via [SessionState.cancelPending].
|
/// error outlive the card. One attempt at a time; [cancel] abandons it
|
||||||
|
/// ([Navigation.cancelPending]).
|
||||||
class ConnectFlow extends ChangeNotifier {
|
class ConnectFlow extends ChangeNotifier {
|
||||||
ConnectFlow({SessionState? session}) : _session = session ?? SessionState.instance;
|
ConnectFlow({required this.navigation, required this.forms, this.profile});
|
||||||
final SessionState _session;
|
final Navigation navigation;
|
||||||
|
final ConnectStore forms;
|
||||||
|
/// Name and picture for the hello (default: the app's).
|
||||||
|
final Profile? profile;
|
||||||
|
|
||||||
ConnectMode? busy;
|
bool busy = false;
|
||||||
final errors = <ConnectMode, CardError?>{};
|
CardError? error;
|
||||||
final notices = <ConnectMode, String?>{};
|
String? notice;
|
||||||
int _attempt = 0;
|
int _attempt = 0;
|
||||||
bool _disposed = false;
|
bool _disposed = false;
|
||||||
|
|
||||||
@@ -33,114 +44,101 @@ class ConnectFlow extends ChangeNotifier {
|
|||||||
if (!_disposed) notifyListeners();
|
if (!_disposed) notifyListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
void showError(ConnectMode mode, CardError error) {
|
void showError(CardError e) {
|
||||||
errors[mode] = error;
|
error = e;
|
||||||
notices[mode] = null;
|
notice = null;
|
||||||
_notify();
|
_notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
void clearError(ConnectMode mode) {
|
void clearError() {
|
||||||
if (errors[mode] == null && notices[mode] == null) return;
|
if (error == null && notice == null) return;
|
||||||
errors[mode] = null;
|
error = null;
|
||||||
notices[mode] = null;
|
notice = null;
|
||||||
_notify();
|
_notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Validates and builds the params; throws [FormatException] with a
|
/// Validates and builds the params; throws [FormatException] with a
|
||||||
/// user-facing message. [avatar] is the base64 picture (the profile's).
|
/// user-facing message. [avatar] is the base64 picture (the profile's).
|
||||||
/// Hosting puts nothing up: what to watch is picked in the library.
|
static ConnectParams buildParams(ConnectForm f, {String avatar = ''}) {
|
||||||
static ConnectParams buildParams(ConnectMode mode, ConnectForm f, {String avatar = ''}) {
|
final port = int.tryParse(f.port.trim());
|
||||||
final rawPort = mode == ConnectMode.host ? f.hostPort : f.port;
|
|
||||||
final port = int.tryParse(rawPort.trim());
|
|
||||||
if (port == null || port <= 0 || port > 65535) {
|
if (port == null || port <= 0 || port > 65535) {
|
||||||
throw const FormatException('port must be 1–65535');
|
throw const FormatException('port must be 1–65535');
|
||||||
}
|
}
|
||||||
if (f.name.trim().isEmpty) {
|
if (f.name.trim().isEmpty) {
|
||||||
throw const FormatException('set your display name first (click your avatar at the top left)');
|
throw const FormatException('set your display name first (click your avatar at the top left)');
|
||||||
}
|
}
|
||||||
if (mode == ConnectMode.join && f.host.trim().isEmpty) {
|
if (f.host.trim().isEmpty) {
|
||||||
throw const FormatException('enter the server address');
|
throw const FormatException('enter the server address');
|
||||||
}
|
}
|
||||||
return ConnectParams(
|
return ConnectParams(host: f.host.trim(), port: port, secret: f.secret, name: f.name.trim(), avatar: avatar);
|
||||||
host: f.host.trim(),
|
|
||||||
port: port,
|
|
||||||
secret: mode == ConnectMode.host ? f.hostSecret : f.secret,
|
|
||||||
name: f.name.trim(),
|
|
||||||
avatar: avatar,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// [edit] fills the card's fields into a copy of the last form, so the
|
/// [edit] fills the card's fields into a copy of the form; the form is
|
||||||
/// other card's saved values survive.
|
/// saved whatever happens (a failed join is when the user wants it back).
|
||||||
Future<void> submit(ConnectMode mode, void Function(ConnectForm f) edit) async {
|
Future<void> submit(void Function(ConnectForm f) edit) async {
|
||||||
if (busy != null) return;
|
if (busy) return;
|
||||||
final myAttempt = ++_attempt;
|
final myAttempt = ++_attempt;
|
||||||
final form = _session.lastForm.copy();
|
final form = forms.form.copy();
|
||||||
edit(form);
|
edit(form);
|
||||||
form.name = form.name.trim();
|
form.name = form.name.trim();
|
||||||
form.host = form.host.trim();
|
form.host = form.host.trim();
|
||||||
busy = mode;
|
busy = true;
|
||||||
errors[mode] = null;
|
error = null;
|
||||||
notices[mode] = null;
|
notice = null;
|
||||||
_notify();
|
_notify();
|
||||||
|
|
||||||
ConnectParams params;
|
ConnectParams params;
|
||||||
try {
|
try {
|
||||||
final profile = Profile.instance;
|
final profile = this.profile ?? Profile.instance;
|
||||||
await profile.ensureLoaded();
|
await profile.ensureLoaded();
|
||||||
params = buildParams(mode, form, avatar: profile.avatarBase64());
|
params = buildParams(form, avatar: profile.avatarBase64());
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (myAttempt != _attempt) return;
|
if (myAttempt != _attempt) return;
|
||||||
busy = null;
|
busy = false;
|
||||||
errors[mode] = CardError('Check the form',
|
error = CardError('Check the form', e is FormatException ? e.message : 'check the form and try again');
|
||||||
e is FormatException ? e.message : 'check the form and try again');
|
|
||||||
_notify();
|
_notify();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final fromSolo = mode == ConnectMode.host && _session.solo.value;
|
forms.form
|
||||||
|
..host = form.host
|
||||||
|
..port = form.port
|
||||||
|
..secret = form.secret;
|
||||||
try {
|
try {
|
||||||
if (mode == ConnectMode.host) {
|
await navigation.join(params);
|
||||||
await _session.host(params, form);
|
|
||||||
} else {
|
|
||||||
await _session.join(params, form);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (myAttempt != _attempt) return;
|
if (myAttempt != _attempt) return;
|
||||||
busy = null;
|
busy = false;
|
||||||
errors[mode] = CardError('Could not connect', '$e');
|
// In plain words: the version gate (who has to update), a refusal
|
||||||
|
// (an older host, a wrong password, another window), offline.
|
||||||
|
error = switch (e) {
|
||||||
|
VersionGateRefused(:final message, :final youUpdate) =>
|
||||||
|
CardError("Versions don't match", message, offerUpdate: youUpdate),
|
||||||
|
HelloRefused() => CardError('Could not connect', connectErrorText(e)),
|
||||||
|
_ => CardError('Could not connect', '$e'),
|
||||||
|
};
|
||||||
_notify();
|
_notify();
|
||||||
|
await forms.saveQuietly();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (myAttempt != _attempt) {
|
if (myAttempt != _attempt) {
|
||||||
// Cancelled after it got through: back out (an Invite: back to solo).
|
// Cancelled after it got through: back home.
|
||||||
try {
|
try {
|
||||||
if (fromSolo) {
|
await navigation.goHome();
|
||||||
await _session.cancelInvite();
|
|
||||||
} else {
|
|
||||||
await _session.leave();
|
|
||||||
await _session.stopServer();
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
busy = null;
|
busy = false;
|
||||||
_notify();
|
_notify();
|
||||||
await _session.rememberServer(RecentServer(
|
|
||||||
hosted: mode == ConnectMode.host,
|
|
||||||
host: mode == ConnectMode.host ? '' : form.host,
|
|
||||||
port: mode == ConnectMode.host ? form.hostPort.trim() : form.port.trim(),
|
|
||||||
secret: mode == ConnectMode.host ? form.hostSecret : form.secret,
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> cancel() async {
|
Future<void> cancel() async {
|
||||||
final mode = busy;
|
final was = busy;
|
||||||
_attempt++;
|
_attempt++;
|
||||||
try {
|
try {
|
||||||
await _session.cancelPending();
|
await navigation.cancelPending();
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
busy = null;
|
busy = false;
|
||||||
if (mode != null) notices[mode] = 'Cancelled';
|
if (was) notice = 'Cancelled';
|
||||||
_notify();
|
_notify();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,21 +1,20 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
import '../../state/session_state.dart';
|
import '../../update/update_controller.dart';
|
||||||
import 'connect_flow.dart';
|
import 'connect_flow.dart';
|
||||||
import 'ui.dart';
|
import 'ui.dart';
|
||||||
|
import 'update_indicator.dart' show runUpdateCheck;
|
||||||
|
|
||||||
/// The submit button for one [ConnectMode], swapped for a progress bar and
|
/// The Join button, swapped for a progress bar and Cancel while the
|
||||||
/// Cancel while that attempt runs. Disabled while the other mode is busy.
|
/// attempt runs.
|
||||||
class ConnectButton extends StatelessWidget {
|
class ConnectButton extends StatelessWidget {
|
||||||
final ConnectFlow flow;
|
final ConnectFlow flow;
|
||||||
final ConnectMode mode;
|
|
||||||
final String label;
|
final String label;
|
||||||
final VoidCallback onSubmit;
|
final VoidCallback onSubmit;
|
||||||
final bool expand;
|
final bool expand;
|
||||||
const ConnectButton({
|
const ConnectButton({
|
||||||
super.key,
|
super.key,
|
||||||
required this.flow,
|
required this.flow,
|
||||||
required this.mode,
|
|
||||||
required this.label,
|
required this.label,
|
||||||
required this.onSubmit,
|
required this.onSubmit,
|
||||||
this.expand = false,
|
this.expand = false,
|
||||||
@@ -23,8 +22,7 @@ class ConnectButton extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final busyHere = flow.busy == mode;
|
if (flow.busy) {
|
||||||
if (busyHere) {
|
|
||||||
return SizedBox(
|
return SizedBox(
|
||||||
width: expand ? null : 220,
|
width: expand ? null : 220,
|
||||||
child: Column(
|
child: Column(
|
||||||
@@ -35,10 +33,7 @@ class ConnectButton extends StatelessWidget {
|
|||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
Expanded(
|
Expanded(child: Text('Connecting…', style: Theme.of(context).textTheme.bodySmall)),
|
||||||
child: Text(mode == ConnectMode.host ? 'Starting server…' : 'Connecting…',
|
|
||||||
style: Theme.of(context).textTheme.bodySmall),
|
|
||||||
),
|
|
||||||
TextButton(onPressed: flow.cancel, child: const Text('Cancel')),
|
TextButton(onPressed: flow.cancel, child: const Text('Cancel')),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -46,35 +41,48 @@ class ConnectButton extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
final button = FilledButton(
|
final button = FilledButton(onPressed: onSubmit, child: Text(label));
|
||||||
onPressed: flow.busy != null ? null : onSubmit,
|
|
||||||
child: Text(label),
|
|
||||||
);
|
|
||||||
return expand ? SizedBox(width: double.infinity, child: button) : button;
|
return expand ? SizedBox(width: double.infinity, child: button) : button;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Last error or notice for [mode], or nothing.
|
/// The last error or notice, or nothing. A version gate that says this
|
||||||
|
/// app is the older one offers the update ([updates], default the app's
|
||||||
|
/// [UpdateController]).
|
||||||
class ConnectFeedback extends StatelessWidget {
|
class ConnectFeedback extends StatelessWidget {
|
||||||
final ConnectFlow flow;
|
final ConnectFlow flow;
|
||||||
final ConnectMode mode;
|
final UpdateController? updates;
|
||||||
const ConnectFeedback({super.key, required this.flow, required this.mode});
|
const ConnectFeedback({super.key, required this.flow, this.updates});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final error = flow.errors[mode];
|
final error = flow.error;
|
||||||
final notice = flow.notices[mode];
|
final notice = flow.notice;
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.only(top: 12),
|
padding: const EdgeInsets.only(top: 12),
|
||||||
child: ErrorBox(title: error.title, message: error.message),
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
ErrorBox(title: error.title, message: error.message),
|
||||||
|
if (error.offerUpdate)
|
||||||
|
Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: TextButton.icon(
|
||||||
|
key: const ValueKey('join-update'),
|
||||||
|
onPressed: () => runUpdateCheck(updates, true),
|
||||||
|
icon: const Icon(Icons.system_update_alt, size: 16),
|
||||||
|
label: const Text('Check for the update'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (notice != null) {
|
if (notice != null) {
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.only(top: 12),
|
padding: const EdgeInsets.only(top: 12),
|
||||||
child: Text(notice,
|
child: Text(notice, style: Theme.of(context).textTheme.bodySmall?.copyWith(color: Colors.grey)),
|
||||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(color: Colors.grey)),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return const SizedBox.shrink();
|
return const SizedBox.shrink();
|
||||||
|
|||||||
@@ -10,34 +10,76 @@ typedef HealthGetter = Future<String> Function(Uri uri);
|
|||||||
const healthPollEvery = Duration(seconds: 10);
|
const healthPollEvery = Duration(seconds: 10);
|
||||||
const _timeout = Duration(seconds: 4);
|
const _timeout = Duration(seconds: 4);
|
||||||
|
|
||||||
/// What a recent-server tile shows: unknown until the first probe answers.
|
/// Whether this app and a server have a wire version in common.
|
||||||
|
enum VersionFit {
|
||||||
|
/// Their ranges meet: the join can go ahead.
|
||||||
|
ok,
|
||||||
|
/// The server's newest version is older than anything this app speaks.
|
||||||
|
theyUpdate,
|
||||||
|
/// The server's oldest version is newer than anything this app speaks.
|
||||||
|
youUpdate,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [VersionFit] of a server that speaks [min] .. [max] (`/health`
|
||||||
|
/// `protoMin` / `protoMax`), against this build's
|
||||||
|
/// [RelayConstants.protoMin] .. [RelayConstants.protoMax].
|
||||||
|
VersionFit versionFit(int min, int max,
|
||||||
|
{int ownMin = RelayConstants.protoMin, int ownMax = RelayConstants.protoMax}) {
|
||||||
|
if (max < ownMin) return VersionFit.theyUpdate;
|
||||||
|
if (min > ownMax) return VersionFit.youUpdate;
|
||||||
|
return VersionFit.ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a recent-server row and the version gate read from `/health`:
|
||||||
|
/// unknown until the first probe answers.
|
||||||
class ServerHealth {
|
class ServerHealth {
|
||||||
final bool online;
|
final bool online;
|
||||||
final String name;
|
final String name;
|
||||||
final int? proto;
|
/// The server's wire range (`protoMin` .. `protoMax`; a server too old
|
||||||
|
/// to say has only `proto`, used for both). Null when it says nothing.
|
||||||
|
final int? protoMin;
|
||||||
|
final int? protoMax;
|
||||||
final int viewers;
|
final int viewers;
|
||||||
|
/// Its Starsync version (`version`), '' from a server too old to say.
|
||||||
|
final String version;
|
||||||
const ServerHealth.offline()
|
const ServerHealth.offline()
|
||||||
: online = false,
|
: online = false,
|
||||||
name = '',
|
name = '',
|
||||||
proto = null,
|
protoMin = null,
|
||||||
viewers = 0;
|
protoMax = null,
|
||||||
const ServerHealth.online({required this.name, this.proto, this.viewers = 0})
|
viewers = 0,
|
||||||
|
version = '';
|
||||||
|
const ServerHealth.online({required this.name, this.protoMin, this.protoMax, this.viewers = 0, this.version = ''})
|
||||||
: online = true;
|
: online = true;
|
||||||
|
|
||||||
/// True when the server speaks another protocol than this build.
|
/// Null while unknown (offline, or no version given).
|
||||||
bool get needsUpdate =>
|
VersionFit? get fit {
|
||||||
online && proto != null && proto != RelayConstants.protoVersion;
|
final min = protoMin, max = protoMax;
|
||||||
|
if (!online || min == null || max == null) return null;
|
||||||
|
return versionFit(min, max);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when the server and this app have no version in common.
|
||||||
|
bool get needsUpdate => fit != null && fit != VersionFit.ok;
|
||||||
|
|
||||||
|
/// The server's own name for people ('' for the dedicated server's
|
||||||
|
/// default `server`).
|
||||||
|
String get label => name.isNotEmpty && name != 'server' ? name : '';
|
||||||
|
|
||||||
/// Lenient parse of `GET /health`; anything unexpected reads as offline.
|
/// Lenient parse of `GET /health`; anything unexpected reads as offline.
|
||||||
static ServerHealth parse(String body) {
|
static ServerHealth parse(String body) {
|
||||||
try {
|
try {
|
||||||
final j = jsonDecode(body);
|
final j = jsonDecode(body);
|
||||||
if (j is! Map || j['ok'] != true) return const ServerHealth.offline();
|
if (j is! Map || j['ok'] != true) return const ServerHealth.offline();
|
||||||
final name = j['name'], proto = j['proto'], viewers = j['viewers'];
|
final name = j['name'], proto = j['proto'], viewers = j['viewers'], version = j['version'];
|
||||||
|
final min = j['protoMin'], max = j['protoMax'];
|
||||||
|
final p = proto is num ? proto.toInt() : null;
|
||||||
return ServerHealth.online(
|
return ServerHealth.online(
|
||||||
name: name is String ? name.trim() : '',
|
name: name is String ? name.trim() : '',
|
||||||
proto: proto is num ? proto.toInt() : null,
|
protoMin: min is num ? min.toInt() : p,
|
||||||
|
protoMax: max is num ? max.toInt() : p,
|
||||||
viewers: viewers is num ? viewers.toInt() : 0,
|
viewers: viewers is num ? viewers.toInt() : 0,
|
||||||
|
version: version is String ? version.trim() : '',
|
||||||
);
|
);
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
return const ServerHealth.offline();
|
return const ServerHealth.offline();
|
||||||
@@ -45,6 +87,26 @@ class ServerHealth {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The version gate's message for a server that does not fit: who has
|
||||||
|
/// to update, in plain words ("Bob's server runs Starsync 1.2.1 — they
|
||||||
|
/// need to update").
|
||||||
|
String versionGateText(ServerHealth h) {
|
||||||
|
final who = h.label.isNotEmpty ? h.label : 'The server';
|
||||||
|
final runs = h.version.isNotEmpty ? '$who runs Starsync ${h.version}' : '$who runs ${h.fit == VersionFit.youUpdate ? 'a newer' : 'an older'} Starsync';
|
||||||
|
return h.fit == VersionFit.youUpdate ? '$runs — you need to update' : '$runs — they need to update';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A join stopped before connecting: the server and this app have no
|
||||||
|
/// version in common ([versionGateText]). [youUpdate]: this app is the
|
||||||
|
/// older one, so the updater can help.
|
||||||
|
class VersionGateRefused implements Exception {
|
||||||
|
final String message;
|
||||||
|
final bool youUpdate;
|
||||||
|
const VersionGateRefused(this.message, {required this.youUpdate});
|
||||||
|
@override
|
||||||
|
String toString() => message;
|
||||||
|
}
|
||||||
|
|
||||||
Uri healthUri(String host, String port) {
|
Uri healthUri(String host, String port) {
|
||||||
final h = host.trim();
|
final h = host.trim();
|
||||||
// Bare IPv6 literals need brackets in a URL.
|
// Bare IPv6 literals need brackets in a URL.
|
||||||
|
|||||||
@@ -27,7 +27,8 @@ class MediaPickerController extends ChangeNotifier {
|
|||||||
final TextEditingController link;
|
final TextEditingController link;
|
||||||
final TextEditingController file;
|
final TextEditingController file;
|
||||||
MediaKind _source;
|
MediaKind _source;
|
||||||
LinkRelay _linkRelay = LinkRelay.direct;
|
// Through me unless picked otherwise (Library → Link).
|
||||||
|
LinkRelay _linkRelay = LinkRelay.me;
|
||||||
JellyfinMedia? _jellyfin;
|
JellyfinMedia? _jellyfin;
|
||||||
JellyfinSelection? _selected;
|
JellyfinSelection? _selected;
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import 'package:sync_relay_core/core.dart' show MediaRef;
|
||||||
|
|
||||||
/// What the media picker selected. Null selection = nothing (hosting
|
/// What the media picker selected. Null selection = nothing (hosting
|
||||||
/// without media is allowed).
|
/// without media is allowed).
|
||||||
sealed class PickedMedia {
|
sealed class PickedMedia {
|
||||||
@@ -72,6 +74,9 @@ final class JellyfinMedia extends PickedMedia {
|
|||||||
/// "Series · S1E6" for episodes, the year for movies; may be empty.
|
/// "Series · S1E6" for episodes, the year for movies; may be empty.
|
||||||
final String subtitle;
|
final String subtitle;
|
||||||
final Duration? runtime;
|
final Duration? runtime;
|
||||||
|
/// What it is (`media.ref`), when it was picked from the item itself
|
||||||
|
/// (with its provider ids); not stored, not part of equality.
|
||||||
|
final MediaRef? ref;
|
||||||
const JellyfinMedia({
|
const JellyfinMedia({
|
||||||
required this.serverId,
|
required this.serverId,
|
||||||
required this.baseUrl,
|
required this.baseUrl,
|
||||||
@@ -80,6 +85,7 @@ final class JellyfinMedia extends PickedMedia {
|
|||||||
required this.title,
|
required this.title,
|
||||||
this.subtitle = '',
|
this.subtitle = '',
|
||||||
this.runtime,
|
this.runtime,
|
||||||
|
this.ref,
|
||||||
});
|
});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -122,3 +128,7 @@ final class JellyfinMedia extends PickedMedia {
|
|||||||
@override
|
@override
|
||||||
String toString() => 'JellyfinMedia($serverId/$itemId "$title")';
|
String toString() => 'JellyfinMedia($serverId/$itemId "$title")';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Adds a pick to Up next (with [next]: right after what plays); returns
|
||||||
|
/// an error text, or null when sent. Null where there is no server.
|
||||||
|
typedef AddToQueue = Future<String?> Function(PickedMedia media, {bool next});
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import 'package:file_picker/file_picker.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:signals/signals_flutter.dart';
|
import 'package:signals/signals_flutter.dart';
|
||||||
|
|
||||||
|
import '../../app/app_graph.dart';
|
||||||
import '../../state/settings.dart';
|
import '../../state/settings.dart';
|
||||||
import '../../update/update_controller.dart';
|
import '../../update/update_controller.dart';
|
||||||
import 'ui.dart';
|
import 'ui.dart';
|
||||||
@@ -12,7 +12,7 @@ import 'update_indicator.dart';
|
|||||||
const sessionShortcuts = [
|
const sessionShortcuts = [
|
||||||
('Space', 'Toggle ready'),
|
('Space', 'Toggle ready'),
|
||||||
('← / →', 'Seek back / forward 10 s'),
|
('← / →', 'Seek back / forward 10 s'),
|
||||||
('↑ / ↓', 'Volume up / down (up to 150 %)'),
|
('↑ / ↓, wheel', 'Volume up / down (up to 150 %)'),
|
||||||
('Shift+→', 'Skip 1:30 (for everyone)'),
|
('Shift+→', 'Skip 1:30 (for everyone)'),
|
||||||
('PgUp / PgDn', 'Previous / next chapter'),
|
('PgUp / PgDn', 'Previous / next chapter'),
|
||||||
('F', 'Toggle fullscreen'),
|
('F', 'Toggle fullscreen'),
|
||||||
@@ -23,6 +23,7 @@ const sessionShortcuts = [
|
|||||||
('Ctrl+1…6', 'Shaders: Anime4K mode A, B, C, A+A, B+B, C+A'),
|
('Ctrl+1…6', 'Shaders: Anime4K mode A, B, C, A+A, B+B, C+A'),
|
||||||
('Ctrl+0', 'Shaders off'),
|
('Ctrl+0', 'Shaders off'),
|
||||||
('Esc', 'Close the panel or fullscreen, shrink the player, then ask to leave'),
|
('Esc', 'Close the panel or fullscreen, shrink the player, then ask to leave'),
|
||||||
|
('Ctrl+Shift+B', 'Mark a problem in the session log (anywhere)'),
|
||||||
];
|
];
|
||||||
|
|
||||||
/// One titled card of the Settings tab (rounded Material, so list tiles
|
/// One titled card of the Settings tab (rounded Material, so list tiles
|
||||||
@@ -87,13 +88,13 @@ class SettingsHintCard extends StatelessWidget {
|
|||||||
class CustomShaderFiles extends StatelessWidget {
|
class CustomShaderFiles extends StatelessWidget {
|
||||||
const CustomShaderFiles({super.key});
|
const CustomShaderFiles({super.key});
|
||||||
|
|
||||||
Future<void> _addFiles() async {
|
Future<void> _addFiles(BuildContext context) async {
|
||||||
final List<PlatformFile> files;
|
final folders = AppScope.of(context).ports.folders;
|
||||||
|
final List<String> files;
|
||||||
try {
|
try {
|
||||||
files = await FilePicker.pickFiles(
|
files = await folders.pickFiles(
|
||||||
dialogTitle: 'Pick mpv GLSL shaders',
|
dialogTitle: 'Pick mpv GLSL shaders',
|
||||||
type: FileType.custom,
|
extensions: const ['glsl', 'hook'],
|
||||||
allowedExtensions: const ['glsl', 'hook'],
|
|
||||||
);
|
);
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
return;
|
return;
|
||||||
@@ -101,8 +102,8 @@ class CustomShaderFiles extends StatelessWidget {
|
|||||||
final s = AppSettings.instance;
|
final s = AppSettings.instance;
|
||||||
final current = s.customShaders.peek();
|
final current = s.customShaders.peek();
|
||||||
final added = [
|
final added = [
|
||||||
for (final f in files)
|
for (final p in files)
|
||||||
if (f.path case final p? when !current.contains(p)) p,
|
if (!current.contains(p)) p,
|
||||||
];
|
];
|
||||||
if (added.isNotEmpty) s.setCustomShaders([...current, ...added]);
|
if (added.isNotEmpty) s.setCustomShaders([...current, ...added]);
|
||||||
}
|
}
|
||||||
@@ -123,7 +124,7 @@ class CustomShaderFiles extends StatelessWidget {
|
|||||||
style: muted),
|
style: muted),
|
||||||
),
|
),
|
||||||
TextButton.icon(
|
TextButton.icon(
|
||||||
onPressed: _addFiles,
|
onPressed: () => _addFiles(context),
|
||||||
icon: const Icon(Icons.add, size: 18),
|
icon: const Icon(Icons.add, size: 18),
|
||||||
label: const Text('Add .glsl files'),
|
label: const Text('Add .glsl files'),
|
||||||
),
|
),
|
||||||
@@ -197,8 +198,8 @@ class UpdateSettings extends StatelessWidget {
|
|||||||
builder: (context) => SwitchListTile(
|
builder: (context) => SwitchListTile(
|
||||||
key: const ValueKey('auto-check-updates'),
|
key: const ValueKey('auto-check-updates'),
|
||||||
contentPadding: EdgeInsets.zero,
|
contentPadding: EdgeInsets.zero,
|
||||||
title: const Text('Check for updates on start'),
|
title: const Text('Check for updates automatically'),
|
||||||
subtitle: const Text('Looks for a new version when the app opens; nothing installs without asking'),
|
subtitle: const Text('When the app opens and every few hours; nothing installs without asking'),
|
||||||
value: s.autoCheckUpdates.value,
|
value: s.autoCheckUpdates.value,
|
||||||
onChanged: s.setAutoCheckUpdates,
|
onChanged: s.setAutoCheckUpdates,
|
||||||
),
|
),
|
||||||
@@ -219,8 +220,8 @@ class AutoAdvanceSetting extends StatelessWidget {
|
|||||||
key: const ValueKey('auto-advance'),
|
key: const ValueKey('auto-advance'),
|
||||||
contentPadding: EdgeInsets.zero,
|
contentPadding: EdgeInsets.zero,
|
||||||
title: const Text('Play the next episode automatically'),
|
title: const Text('Play the next episode automatically'),
|
||||||
subtitle: const Text('When a Jellyfin episode ends, a 10 s countdown puts up the next one; '
|
subtitle: const Text('When you put up an episode (Jellyfin, or a file of a show in Files), the next one '
|
||||||
'anyone can cancel it'),
|
'continues it after a 10 s countdown everyone sees; anyone can cancel it'),
|
||||||
value: s.autoAdvance.value,
|
value: s.autoAdvance.value,
|
||||||
onChanged: s.setAutoAdvance,
|
onChanged: s.setAutoAdvance,
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -1,10 +1,31 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:sync_relay_core/core.dart' show appVersion, isDevBuild;
|
||||||
|
|
||||||
/// Product name (working title). Change it here only.
|
/// Product name (working title). Change it here only.
|
||||||
const appName = 'Starsync';
|
const appName = 'Starsync';
|
||||||
|
|
||||||
const repoUrl = 'https://git.senkochan.moe/Foxyz/sync_replay_project';
|
const repoUrl = 'https://git.senkochan.moe/Foxyz/sync_replay_project';
|
||||||
|
|
||||||
|
/// The pubspec's version: the Flutter tool defines it for every build and
|
||||||
|
/// run (`flutter run` too).
|
||||||
|
const _pubspecVersion = String.fromEnvironment('FLUTTER_BUILD_NAME');
|
||||||
|
|
||||||
|
/// The short commit a packaged build was made from (`tool/package_linux.sh`;
|
||||||
|
/// `-dirty` with uncommitted changes); empty otherwise.
|
||||||
|
const _gitCommit = String.fromEnvironment('GIT_COMMIT');
|
||||||
|
|
||||||
|
/// The version to show: a release's own ("1.1.2"), a test build's with its
|
||||||
|
/// commit ("1.1.3-dev.12 · 1a2b3c4"), and for a dev run (no `APP_VERSION`)
|
||||||
|
/// the pubspec's with "dev" ("1.1.2 · dev run").
|
||||||
|
String displayVersion({String version = appVersion, String pubspec = _pubspecVersion, String commit = _gitCommit}) {
|
||||||
|
if (version == '0.0.0-dev') return pubspec.isEmpty ? 'dev run' : '$pubspec · dev run';
|
||||||
|
return isDevBuild(version) && commit.isNotEmpty ? '$version · $commit' : version;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The version in a few characters, always on screen (under the strip's
|
||||||
|
/// Settings tab): "1.2.1", "1.2.1-dev.2", "dev run".
|
||||||
|
String shortVersion({String version = appVersion}) => version == '0.0.0-dev' ? 'dev run' : version;
|
||||||
|
|
||||||
const kRadius = 12.0;
|
const kRadius = 12.0;
|
||||||
const kGap = 16.0;
|
const kGap = 16.0;
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +1,17 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:sync_relay_core/core.dart' show isDevBuild;
|
||||||
|
|
||||||
import '../../update/update_controller.dart';
|
import '../../update/update_controller.dart';
|
||||||
import '../../widgets/update_banner.dart';
|
import '../../widgets/update_banner.dart';
|
||||||
import 'ui.dart';
|
import 'ui.dart';
|
||||||
|
|
||||||
/// Compact "Update vX" pill for the party strip; hidden until there is
|
/// The band across the top of the window while an update is up for
|
||||||
/// something to install. Click opens the full [UpdateBanner].
|
/// grabs: "Starsync 1.2.1 is ready", its notes, Update and restart and
|
||||||
class UpdateIndicator extends StatelessWidget {
|
/// Later (gone until the next check or start). The shell keeps it off
|
||||||
|
/// the full player while a video is on ([AppShell]).
|
||||||
|
class UpdateBar extends StatelessWidget {
|
||||||
final UpdateController? controller;
|
final UpdateController? controller;
|
||||||
const UpdateIndicator({super.key, this.controller});
|
const UpdateBar({super.key, this.controller});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
@@ -21,34 +24,102 @@ class UpdateIndicator extends StatelessWidget {
|
|||||||
return const SizedBox.shrink();
|
return const SizedBox.shrink();
|
||||||
}
|
}
|
||||||
final scheme = Theme.of(context).colorScheme;
|
final scheme = Theme.of(context).colorScheme;
|
||||||
|
final alert = m.isRequired || s.phase == UpdatePhase.failed;
|
||||||
|
final fg = alert ? scheme.onErrorContainer : scheme.onPrimaryContainer;
|
||||||
|
final current = c.currentVersion;
|
||||||
|
// A release (not a test build) that is behind: say which it runs.
|
||||||
|
final behind = isDevBuild(current) ? null : 'You are running $current';
|
||||||
|
final String title;
|
||||||
|
String detail;
|
||||||
|
switch (s.phase) {
|
||||||
|
case UpdatePhase.downloading:
|
||||||
|
title = 'Downloading $appName ${m.version}… ${((s.progress ?? 0) * 100).round()}%';
|
||||||
|
detail = '';
|
||||||
|
case UpdatePhase.applying:
|
||||||
|
title = 'Installing $appName ${m.version}…';
|
||||||
|
detail = '';
|
||||||
|
case UpdatePhase.restarting:
|
||||||
|
title = 'Restarting into $appName ${m.version}…';
|
||||||
|
detail = '';
|
||||||
|
case UpdatePhase.failed:
|
||||||
|
title = 'Update to $appName ${m.version} failed';
|
||||||
|
detail = '${s.error}';
|
||||||
|
case UpdatePhase.available || UpdatePhase.idle:
|
||||||
|
if (!s.canInstall) {
|
||||||
|
title = 'This copy of $appName is older than the latest release (${m.version})';
|
||||||
|
detail = 'Download the new release and replace this folder by hand';
|
||||||
|
} else if (m.isRequired) {
|
||||||
|
title = '$appName ${m.version} is required to join servers on it';
|
||||||
|
detail = m.notes;
|
||||||
|
} else {
|
||||||
|
title = '$appName ${m.version} is ready';
|
||||||
|
detail = m.notes;
|
||||||
|
}
|
||||||
|
detail = [?behind, detail].where((t) => t.isNotEmpty).join(' · ');
|
||||||
|
}
|
||||||
final busy = s.phase == UpdatePhase.downloading ||
|
final busy = s.phase == UpdatePhase.downloading ||
|
||||||
s.phase == UpdatePhase.applying ||
|
s.phase == UpdatePhase.applying ||
|
||||||
s.phase == UpdatePhase.restarting;
|
s.phase == UpdatePhase.restarting;
|
||||||
final label = switch (s.phase) {
|
return Material(
|
||||||
UpdatePhase.downloading =>
|
key: const ValueKey('update-bar'),
|
||||||
'Updating ${((s.progress ?? 0) * 100).round()}%',
|
color: alert ? scheme.errorContainer : scheme.primaryContainer,
|
||||||
UpdatePhase.applying => 'Installing…',
|
child: Padding(
|
||||||
UpdatePhase.restarting => 'Restarting…',
|
padding: const EdgeInsets.fromLTRB(16, 8, 12, 8),
|
||||||
UpdatePhase.failed => 'Update failed',
|
child: Row(
|
||||||
_ => m.isRequired ? 'Required update' : 'Update v${m.version}',
|
children: [
|
||||||
};
|
if (busy)
|
||||||
return Tooltip(
|
SizedBox.square(
|
||||||
message: 'Show update',
|
dimension: 18,
|
||||||
child: FilledButton.tonalIcon(
|
child: CircularProgressIndicator(
|
||||||
style: FilledButton.styleFrom(
|
strokeWidth: 2,
|
||||||
backgroundColor: m.isRequired || s.phase == UpdatePhase.failed
|
color: fg,
|
||||||
? scheme.errorContainer
|
value: s.phase == UpdatePhase.downloading ? s.progress : null,
|
||||||
: null,
|
),
|
||||||
visualDensity: VisualDensity.compact,
|
)
|
||||||
|
else
|
||||||
|
Icon(Icons.system_update_alt, size: 20, color: fg),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Text(title,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(color: fg, fontWeight: FontWeight.w600)),
|
||||||
|
if (detail.isNotEmpty)
|
||||||
|
Tooltip(
|
||||||
|
message: detail,
|
||||||
|
waitDuration: const Duration(milliseconds: 600),
|
||||||
|
child: Text(detail,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(color: fg.withValues(alpha: 0.8), fontSize: 12)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (!busy) ...[
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
if (!m.isRequired)
|
||||||
|
TextButton(
|
||||||
|
key: const ValueKey('update-later'),
|
||||||
|
style: TextButton.styleFrom(foregroundColor: fg),
|
||||||
|
onPressed: c.dismiss,
|
||||||
|
child: const Text('Later'),
|
||||||
|
),
|
||||||
|
if (s.canInstall) ...[
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
FilledButton(
|
||||||
|
key: const ValueKey('update-install'),
|
||||||
|
onPressed: c.install,
|
||||||
|
child: Text(s.phase == UpdatePhase.failed ? 'Retry' : 'Update and restart'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
],
|
||||||
),
|
),
|
||||||
onPressed: () => showUpdateDialog(context, controller: c),
|
|
||||||
icon: busy
|
|
||||||
? const SizedBox(
|
|
||||||
width: 14,
|
|
||||||
height: 14,
|
|
||||||
child: CircularProgressIndicator(strokeWidth: 2))
|
|
||||||
: const Icon(Icons.system_update_alt, size: 18),
|
|
||||||
label: Text(label),
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
@@ -85,6 +156,9 @@ Future<void> showUpdateDialog(BuildContext context, {UpdateController? controlle
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How often a running app looks again (auto-check on).
|
||||||
|
const updateCheckEvery = Duration(hours: 4);
|
||||||
|
|
||||||
enum UpdateCheck { notRun, checking, done }
|
enum UpdateCheck { notRun, checking, done }
|
||||||
|
|
||||||
/// Progress of this run's update check, for Settings/About wording.
|
/// Progress of this run's update check, for Settings/About wording.
|
||||||
|
|||||||
@@ -1,44 +1,13 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
import '../../jellyfin/session_media.dart';
|
import '../../jellyfin/session_media.dart';
|
||||||
import '../../session/session_coordinator.dart' show AutoAdvance, autoAdvanceSecs;
|
|
||||||
import 'player_controls.dart' show FloatingPill;
|
import 'player_controls.dart' show FloatingPill;
|
||||||
|
|
||||||
// Jellyfin pieces of the session player. Plain widgets fed by the
|
// Jellyfin pieces of the session player. Plain widgets fed by the
|
||||||
// coordinator's signals, so tests can pump them without the player.
|
// coordinator's signals, so tests can pump them without the player.
|
||||||
|
|
||||||
/// Previous / next episode in the video controls. Nothing when there is
|
/// Floating "Next episode ›" from the ED (or the last two minutes), while
|
||||||
/// no such episode or this viewer cannot put it up (no account).
|
/// the controls are up (`PillGate`): faint at rest, lit on hover.
|
||||||
class EpisodeSkipButton extends StatelessWidget {
|
|
||||||
final EpisodeLink? episode;
|
|
||||||
final bool next;
|
|
||||||
final VoidCallback onPressed;
|
|
||||||
final FocusNode? focusNode;
|
|
||||||
const EpisodeSkipButton(
|
|
||||||
{super.key, required this.episode, required this.next, required this.onPressed, this.focusNode});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final e = episode;
|
|
||||||
if (e == null) return const SizedBox.shrink();
|
|
||||||
return Tooltip(
|
|
||||||
message: '${next ? 'Next' : 'Previous'}: ${e.label} (${next ? '> or Shift+N' : '< or Shift+P'})',
|
|
||||||
child: IconButton(
|
|
||||||
key: ValueKey(next ? 'episode-next' : 'episode-previous'),
|
|
||||||
focusNode: focusNode,
|
|
||||||
color: Colors.white,
|
|
||||||
iconSize: 22,
|
|
||||||
visualDensity: VisualDensity.compact,
|
|
||||||
icon: Icon(next ? Icons.skip_next_rounded : Icons.skip_previous_rounded),
|
|
||||||
onPressed: onPressed,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Floating "Next episode ›" from the ED (or the last two minutes):
|
|
||||||
/// faint at rest, lit on hover. Lives outside the auto-hiding controls, so
|
|
||||||
/// it shows in fullscreen and with the controls hidden.
|
|
||||||
class NextEpisodePill extends StatelessWidget {
|
class NextEpisodePill extends StatelessWidget {
|
||||||
final EpisodeLink episode;
|
final EpisodeLink episode;
|
||||||
final VoidCallback onPressed;
|
final VoidCallback onPressed;
|
||||||
@@ -53,71 +22,6 @@ class NextEpisodePill extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// At the end of an episode: "Next: S1E7 title" with Play now, and while
|
|
||||||
/// the auto-advance countdown runs, the seconds left and Cancel.
|
|
||||||
class EndOfEpisodeCard extends StatelessWidget {
|
|
||||||
final EpisodeLink next;
|
|
||||||
final AutoAdvance? countdown;
|
|
||||||
final VoidCallback onPlayNow;
|
|
||||||
final VoidCallback onCancel;
|
|
||||||
const EndOfEpisodeCard({
|
|
||||||
super.key,
|
|
||||||
required this.next,
|
|
||||||
required this.countdown,
|
|
||||||
required this.onPlayNow,
|
|
||||||
required this.onCancel,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final t = Theme.of(context).textTheme;
|
|
||||||
final c = countdown;
|
|
||||||
return Card(
|
|
||||||
key: const ValueKey('end-of-episode'),
|
|
||||||
color: Colors.black.withValues(alpha: 0.85),
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.fromLTRB(16, 12, 12, 12),
|
|
||||||
child: ConstrainedBox(
|
|
||||||
constraints: const BoxConstraints(maxWidth: 380),
|
|
||||||
child: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text(c == null ? 'Up next' : 'Next episode in ${c.secondsLeft} s',
|
|
||||||
style: t.labelLarge?.copyWith(color: Colors.white70)),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
Text('Next: ${next.label}',
|
|
||||||
maxLines: 2, overflow: TextOverflow.ellipsis, style: t.titleMedium),
|
|
||||||
if (c != null) ...[
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
LinearProgressIndicator(value: c.secondsLeft / autoAdvanceSecs),
|
|
||||||
],
|
|
||||||
const SizedBox(height: 10),
|
|
||||||
Row(
|
|
||||||
mainAxisAlignment: MainAxisAlignment.end,
|
|
||||||
children: [
|
|
||||||
if (c != null)
|
|
||||||
TextButton(
|
|
||||||
key: const ValueKey('auto-advance-cancel'),
|
|
||||||
onPressed: onCancel,
|
|
||||||
child: const Text('Cancel')),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
FilledButton.icon(
|
|
||||||
key: const ValueKey('play-next'),
|
|
||||||
onPressed: onPlayNow,
|
|
||||||
icon: const Icon(Icons.skip_next_rounded, size: 18),
|
|
||||||
label: Text(c == null ? 'Play next' : 'Play now'),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// This viewer cannot play the Jellyfin media: say why and offer to link
|
/// This viewer cannot play the Jellyfin media: say why and offer to link
|
||||||
/// an account (never a silent stall).
|
/// an account (never a silent stall).
|
||||||
class JellyfinBlockedCard extends StatelessWidget {
|
class JellyfinBlockedCard extends StatelessWidget {
|
||||||
@@ -166,25 +70,3 @@ class JellyfinBlockedCard extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Small member-list badge: plays the Jellyfin item through the host.
|
|
||||||
class ViaHostBadge extends StatelessWidget {
|
|
||||||
const ViaHostBadge({super.key});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return Tooltip(
|
|
||||||
message: 'No Jellyfin account here: watches through the host',
|
|
||||||
child: Container(
|
|
||||||
key: const ValueKey('via-host'),
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Colors.white10,
|
|
||||||
borderRadius: BorderRadius.circular(999),
|
|
||||||
border: Border.all(color: Colors.white24),
|
|
||||||
),
|
|
||||||
child: const Text('via host', style: TextStyle(fontSize: 10, color: Colors.white70)),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,534 +1,19 @@
|
|||||||
import 'dart:async';
|
|
||||||
import 'dart:math' as math;
|
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:media_kit/media_kit.dart';
|
|
||||||
import 'package:sync_relay_core/core.dart' show JellyfinStreamType;
|
|
||||||
|
|
||||||
import '../../jellyfin/track_prefs.dart' show MpvTrack;
|
|
||||||
import '../../playback/media_marks.dart';
|
import '../../playback/media_marks.dart';
|
||||||
|
import '../../widgets/app_menu.dart' show AppGlass;
|
||||||
|
|
||||||
// Session control-bar pieces built on the playback signals (chapters,
|
// The player's floating action pills (Skip OP / ED / 1:30, Next episode):
|
||||||
// tracks, skip offers): the seek bar with chapter marks, the chapter and
|
// plain widgets fed by values and callbacks, so tests pump them without a
|
||||||
// track menus, the 1:30 skip button and the floating skip pill. Plain
|
// player. They live in the action area, outside the controls.
|
||||||
// widgets fed by values and callbacks, so tests pump them without a player.
|
|
||||||
|
|
||||||
/// Keeps media_kit's desktop controls shown, as a mouse hover would.
|
/// The player's action pill (Next episode, Skip OP / ED / 1:30): the
|
||||||
/// While a seek bar drag runs no hover events arrive, and the controls
|
/// status pill's glass ([AppGlass.pill]) at [height], faint at rest, lit
|
||||||
/// would hide (and unmount the bar) mid-drag. A guarded dynamic call on
|
/// on hover. Lives in the player's action area, outside the auto-hiding
|
||||||
/// the private controls state; nothing happens outside those controls.
|
/// controls (also in fullscreen); `PillGate` shows it with them.
|
||||||
void keepVideoControlsAwake(BuildContext context) {
|
|
||||||
context.visitAncestorElements((e) {
|
|
||||||
if (e is StatefulElement &&
|
|
||||||
e.state.runtimeType.toString() == '_MaterialDesktopVideoControlsState') {
|
|
||||||
try {
|
|
||||||
(e.state as dynamic).onHover();
|
|
||||||
} catch (_) {}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The seek bar: played / buffered track, a diamond at each chapter start
|
|
||||||
/// (not the one at 0), and on hover the time with the chapter title above
|
|
||||||
/// it. Like media_kit's bar it reports a seek on every drag move and on
|
|
||||||
/// release ([onSeek]); the session routes those through the user-seek path
|
|
||||||
/// (debounced, everyone follows).
|
|
||||||
class ChapterSeekBar extends StatefulWidget {
|
|
||||||
final Duration position;
|
|
||||||
final Duration duration;
|
|
||||||
final Duration buffer;
|
|
||||||
final List<MediaChapter> chapters;
|
|
||||||
final ValueChanged<Duration> onSeek;
|
|
||||||
/// Any pointer activity on the bar (keeps the controls up).
|
|
||||||
final VoidCallback? onActivity;
|
|
||||||
const ChapterSeekBar({
|
|
||||||
super.key,
|
|
||||||
required this.position,
|
|
||||||
required this.duration,
|
|
||||||
this.buffer = Duration.zero,
|
|
||||||
this.chapters = const [],
|
|
||||||
required this.onSeek,
|
|
||||||
this.onActivity,
|
|
||||||
});
|
|
||||||
|
|
||||||
static const height = 28.0;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<ChapterSeekBar> createState() => _ChapterSeekBarState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _ChapterSeekBarState extends State<ChapterSeekBar> {
|
|
||||||
double? _hoverX;
|
|
||||||
bool _dragging = false;
|
|
||||||
double _dragFraction = 0;
|
|
||||||
|
|
||||||
double _fraction(Duration d) {
|
|
||||||
final total = widget.duration.inMicroseconds;
|
|
||||||
if (total <= 0) return 0;
|
|
||||||
return (d.inMicroseconds / total).clamp(0.0, 1.0);
|
|
||||||
}
|
|
||||||
|
|
||||||
Duration _at(double fraction) => widget.duration * fraction.clamp(0.0, 1.0);
|
|
||||||
|
|
||||||
void _seekTo(double x, double width) {
|
|
||||||
if (widget.duration <= Duration.zero || width <= 0) return;
|
|
||||||
_dragFraction = (x / width).clamp(0.0, 1.0);
|
|
||||||
widget.onSeek(_at(_dragFraction));
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final primary = Theme.of(context).colorScheme.primary;
|
|
||||||
return LayoutBuilder(builder: (context, constraints) {
|
|
||||||
final width = constraints.maxWidth;
|
|
||||||
final active = _hoverX != null || _dragging;
|
|
||||||
final barHeight = active ? 5.0 : 3.0;
|
|
||||||
final played = _dragging ? _dragFraction : _fraction(widget.position);
|
|
||||||
const mid = ChapterSeekBar.height / 2;
|
|
||||||
final hoverX = _hoverX;
|
|
||||||
final hoverAt = hoverX == null || width <= 0 ? null : _at(hoverX / width);
|
|
||||||
final hoverChapter = hoverAt == null ? null : chapterIndexAt(widget.chapters, hoverAt);
|
|
||||||
final hoverTitle = hoverChapter == null ? '' : widget.chapters[hoverChapter].title;
|
|
||||||
return MouseRegion(
|
|
||||||
cursor: SystemMouseCursors.click,
|
|
||||||
onEnter: (e) => setState(() => _hoverX = e.localPosition.dx.clamp(0, width)),
|
|
||||||
onHover: (e) {
|
|
||||||
setState(() => _hoverX = e.localPosition.dx.clamp(0, width));
|
|
||||||
widget.onActivity?.call();
|
|
||||||
},
|
|
||||||
onExit: (_) => setState(() => _hoverX = null),
|
|
||||||
child: Listener(
|
|
||||||
behavior: HitTestBehavior.opaque,
|
|
||||||
onPointerDown: (e) {
|
|
||||||
widget.onActivity?.call();
|
|
||||||
setState(() {
|
|
||||||
_dragging = true;
|
|
||||||
_dragFraction = width <= 0 ? 0 : (e.localPosition.dx / width).clamp(0.0, 1.0);
|
|
||||||
});
|
|
||||||
},
|
|
||||||
onPointerMove: (e) {
|
|
||||||
widget.onActivity?.call();
|
|
||||||
setState(() => _hoverX = e.localPosition.dx.clamp(0, width));
|
|
||||||
_seekTo(e.localPosition.dx, width);
|
|
||||||
},
|
|
||||||
onPointerUp: (e) {
|
|
||||||
_seekTo(e.localPosition.dx, width);
|
|
||||||
setState(() => _dragging = false);
|
|
||||||
widget.onActivity?.call();
|
|
||||||
},
|
|
||||||
onPointerCancel: (_) => setState(() => _dragging = false),
|
|
||||||
child: SizedBox(
|
|
||||||
key: const ValueKey('seek-bar'),
|
|
||||||
width: width,
|
|
||||||
height: ChapterSeekBar.height,
|
|
||||||
child: Stack(
|
|
||||||
clipBehavior: Clip.none,
|
|
||||||
children: [
|
|
||||||
Positioned(
|
|
||||||
left: 0,
|
|
||||||
right: 0,
|
|
||||||
top: mid - barHeight / 2,
|
|
||||||
height: barHeight,
|
|
||||||
child: Container(color: Colors.white24),
|
|
||||||
),
|
|
||||||
Positioned(
|
|
||||||
left: 0,
|
|
||||||
top: mid - barHeight / 2,
|
|
||||||
height: barHeight,
|
|
||||||
width: width * _fraction(widget.buffer),
|
|
||||||
child: Container(color: Colors.white24),
|
|
||||||
),
|
|
||||||
if (hoverX != null && !_dragging)
|
|
||||||
Positioned(
|
|
||||||
left: 0,
|
|
||||||
top: mid - barHeight / 2,
|
|
||||||
height: barHeight,
|
|
||||||
width: hoverX,
|
|
||||||
child: Container(color: Colors.white24),
|
|
||||||
),
|
|
||||||
Positioned(
|
|
||||||
left: 0,
|
|
||||||
top: mid - barHeight / 2,
|
|
||||||
height: barHeight,
|
|
||||||
width: width * played,
|
|
||||||
child: Container(color: primary),
|
|
||||||
),
|
|
||||||
for (final c in widget.chapters)
|
|
||||||
if (c.start > Duration.zero && widget.duration > Duration.zero)
|
|
||||||
Positioned(
|
|
||||||
key: ValueKey('chapter-mark-${c.index}'),
|
|
||||||
left: width * _fraction(c.start) - 4,
|
|
||||||
top: mid - 4,
|
|
||||||
width: 8,
|
|
||||||
height: 8,
|
|
||||||
child: IgnorePointer(
|
|
||||||
child: Transform.rotate(
|
|
||||||
angle: math.pi / 4,
|
|
||||||
child: Container(
|
|
||||||
margin: const EdgeInsets.all(1),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Colors.white,
|
|
||||||
border: Border.all(color: Colors.black54, width: 0.8),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (active)
|
|
||||||
Positioned(
|
|
||||||
left: width * played - 6,
|
|
||||||
top: mid - 6,
|
|
||||||
width: 12,
|
|
||||||
height: 12,
|
|
||||||
child: IgnorePointer(
|
|
||||||
child: DecoratedBox(
|
|
||||||
decoration: BoxDecoration(color: primary, shape: BoxShape.circle),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (hoverAt != null)
|
|
||||||
Positioned(
|
|
||||||
// Kept clear of the window edges (the tip is centred).
|
|
||||||
left: hoverX!.clamp(math.min(60.0, width / 2), math.max(width - 60, width / 2)),
|
|
||||||
bottom: ChapterSeekBar.height - 2,
|
|
||||||
child: IgnorePointer(
|
|
||||||
child: FractionalTranslation(
|
|
||||||
translation: const Offset(-0.5, 0),
|
|
||||||
child: _HoverTip(title: hoverTitle, time: formatClock(hoverAt)),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class _HoverTip extends StatelessWidget {
|
|
||||||
final String title;
|
|
||||||
final String time;
|
|
||||||
const _HoverTip({required this.title, required this.time});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return Container(
|
|
||||||
constraints: const BoxConstraints(maxWidth: 320),
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Colors.black.withValues(alpha: 0.8),
|
|
||||||
borderRadius: BorderRadius.circular(6),
|
|
||||||
),
|
|
||||||
child: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
if (title.isNotEmpty)
|
|
||||||
Text(title,
|
|
||||||
key: const ValueKey('seek-hover-chapter'),
|
|
||||||
maxLines: 1,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
style: const TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600)),
|
|
||||||
Text(time,
|
|
||||||
key: const ValueKey('seek-hover-time'),
|
|
||||||
style: const TextStyle(color: Colors.white70, fontSize: 11)),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// [ChapterSeekBar] on a live player: position, duration and buffer from
|
|
||||||
/// its streams. Seeks go to `player.seek`, which the session's
|
|
||||||
/// `SyncPlayer` turns into user seeks.
|
|
||||||
class PlayerSeekBar extends StatefulWidget {
|
|
||||||
final Player player;
|
|
||||||
final List<MediaChapter> chapters;
|
|
||||||
const PlayerSeekBar({super.key, required this.player, required this.chapters});
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<PlayerSeekBar> createState() => _PlayerSeekBarState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _PlayerSeekBarState extends State<PlayerSeekBar> {
|
|
||||||
final List<StreamSubscription<Object>> _subs = [];
|
|
||||||
late Duration _position, _duration, _buffer;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
_listen();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void didUpdateWidget(PlayerSeekBar old) {
|
|
||||||
super.didUpdateWidget(old);
|
|
||||||
if (!identical(old.player, widget.player)) {
|
|
||||||
_cancel();
|
|
||||||
_listen();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _listen() {
|
|
||||||
final p = widget.player;
|
|
||||||
_position = p.state.position;
|
|
||||||
_duration = p.state.duration;
|
|
||||||
_buffer = p.state.buffer;
|
|
||||||
void set(VoidCallback f) {
|
|
||||||
if (mounted) setState(f);
|
|
||||||
}
|
|
||||||
|
|
||||||
_subs.addAll([
|
|
||||||
p.stream.position.listen((d) => set(() => _position = d)),
|
|
||||||
p.stream.duration.listen((d) => set(() => _duration = d)),
|
|
||||||
p.stream.buffer.listen((d) => set(() => _buffer = d)),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
void _cancel() {
|
|
||||||
for (final s in _subs) {
|
|
||||||
s.cancel();
|
|
||||||
}
|
|
||||||
_subs.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() {
|
|
||||||
_cancel();
|
|
||||||
super.dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return ChapterSeekBar(
|
|
||||||
position: _position,
|
|
||||||
duration: _duration,
|
|
||||||
buffer: _buffer,
|
|
||||||
chapters: widget.chapters,
|
|
||||||
onSeek: (d) => widget.player.seek(d),
|
|
||||||
onActivity: () => keepVideoControlsAwake(context),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
RelativeRect _menuPosition(BuildContext context) {
|
|
||||||
final button = context.findRenderObject() as RenderBox;
|
|
||||||
final overlay = Navigator.of(context).overlay!.context.findRenderObject() as RenderBox;
|
|
||||||
return RelativeRect.fromRect(
|
|
||||||
Rect.fromPoints(
|
|
||||||
button.localToGlobal(Offset.zero, ancestor: overlay),
|
|
||||||
button.localToGlobal(button.size.bottomRight(Offset.zero), ancestor: overlay),
|
|
||||||
),
|
|
||||||
Offset.zero & overlay.size,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Control-bar icon with a small count in the corner.
|
|
||||||
class _BadgedIcon extends StatelessWidget {
|
|
||||||
final IconData icon;
|
|
||||||
final int count;
|
|
||||||
const _BadgedIcon(this.icon, this.count);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return Stack(
|
|
||||||
clipBehavior: Clip.none,
|
|
||||||
children: [
|
|
||||||
Icon(icon),
|
|
||||||
if (count > 0)
|
|
||||||
Positioned(
|
|
||||||
right: -7,
|
|
||||||
top: -5,
|
|
||||||
child: Container(
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 0.5),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Theme.of(context).colorScheme.primary,
|
|
||||||
borderRadius: BorderRadius.circular(999),
|
|
||||||
),
|
|
||||||
child: Text('$count',
|
|
||||||
style: const TextStyle(color: Colors.white, fontSize: 9, fontWeight: FontWeight.bold)),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Chapter list for the controls: current chapter checked, a pick seeks
|
|
||||||
/// to its start. Nothing when the file has no chapters.
|
|
||||||
class ChaptersControlButton extends StatelessWidget {
|
|
||||||
final List<MediaChapter> chapters;
|
|
||||||
final int? current;
|
|
||||||
final ValueChanged<MediaChapter> onPick;
|
|
||||||
final FocusNode? focusNode;
|
|
||||||
final ValueChanged<bool>? onMenuOpen;
|
|
||||||
const ChaptersControlButton({
|
|
||||||
super.key,
|
|
||||||
required this.chapters,
|
|
||||||
required this.current,
|
|
||||||
required this.onPick,
|
|
||||||
this.focusNode,
|
|
||||||
this.onMenuOpen,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
if (chapters.isEmpty) return const SizedBox.shrink();
|
|
||||||
return Tooltip(
|
|
||||||
message: 'Chapters (PgUp / PgDn)',
|
|
||||||
child: IconButton(
|
|
||||||
key: const ValueKey('chapters-button'),
|
|
||||||
focusNode: focusNode,
|
|
||||||
color: Colors.white,
|
|
||||||
iconSize: 20,
|
|
||||||
visualDensity: VisualDensity.compact,
|
|
||||||
icon: _BadgedIcon(Icons.format_list_bulleted, chapters.length),
|
|
||||||
onPressed: () => _open(context),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _open(BuildContext context) async {
|
|
||||||
final position = _menuPosition(context);
|
|
||||||
onMenuOpen?.call(true);
|
|
||||||
final pick = await showMenu<MediaChapter>(
|
|
||||||
context: context,
|
|
||||||
position: position,
|
|
||||||
popUpAnimationStyle: AnimationStyle.noAnimation,
|
|
||||||
constraints: const BoxConstraints(minWidth: 240, maxWidth: 420),
|
|
||||||
items: [
|
|
||||||
for (final c in chapters)
|
|
||||||
CheckedPopupMenuItem(
|
|
||||||
value: c,
|
|
||||||
checked: c.index == current,
|
|
||||||
height: 36,
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: Text(c.title.isEmpty ? 'Chapter ${c.index + 1}' : c.title,
|
|
||||||
maxLines: 1, overflow: TextOverflow.ellipsis),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 12),
|
|
||||||
Text(formatClock(c.start), style: const TextStyle(fontSize: 12, color: Colors.grey)),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
onMenuOpen?.call(false);
|
|
||||||
if (pick != null) onPick(pick);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A track pick from [TrackMenuButton]: audio id, subtitle id, or off.
|
|
||||||
typedef TrackPick = ({int? aid, int? sid, bool subtitlesOff});
|
|
||||||
|
|
||||||
/// Audio or subtitle menu for the controls bar (the count of tracks on the
|
|
||||||
/// icon): "Japanese · E-AC3 2.0 · title", mpv's selection checked,
|
|
||||||
/// subtitles with Off. The choice is remembered for the next Jellyfin item
|
|
||||||
/// (per viewer).
|
|
||||||
class TrackMenuButton extends StatelessWidget {
|
|
||||||
final JellyfinStreamType type;
|
|
||||||
/// All tracks; only those of [type] are listed.
|
|
||||||
final List<MpvTrack> tracks;
|
|
||||||
final void Function(TrackPick pick) onPick;
|
|
||||||
final FocusNode? focusNode;
|
|
||||||
final ValueChanged<bool>? onMenuOpen;
|
|
||||||
const TrackMenuButton({
|
|
||||||
super.key,
|
|
||||||
required this.type,
|
|
||||||
required this.tracks,
|
|
||||||
required this.onPick,
|
|
||||||
this.focusNode,
|
|
||||||
this.onMenuOpen,
|
|
||||||
});
|
|
||||||
|
|
||||||
bool get _audio => type == JellyfinStreamType.audio;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final list = tracks.where((t) => t.type == type).toList();
|
|
||||||
return Tooltip(
|
|
||||||
message: _audio ? 'Audio' : 'Subtitles',
|
|
||||||
child: IconButton(
|
|
||||||
key: ValueKey(_audio ? 'audio-button' : 'subtitles-button'),
|
|
||||||
focusNode: focusNode,
|
|
||||||
color: Colors.white,
|
|
||||||
iconSize: 20,
|
|
||||||
visualDensity: VisualDensity.compact,
|
|
||||||
icon: _BadgedIcon(_audio ? Icons.audiotrack_outlined : Icons.subtitles_outlined, list.length),
|
|
||||||
onPressed: () => _open(context, list),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _open(BuildContext context, List<MpvTrack> list) async {
|
|
||||||
final position = _menuPosition(context);
|
|
||||||
onMenuOpen?.call(true);
|
|
||||||
final pick = await showMenu<TrackPick>(
|
|
||||||
context: context,
|
|
||||||
position: position,
|
|
||||||
popUpAnimationStyle: AnimationStyle.noAnimation,
|
|
||||||
constraints: const BoxConstraints(minWidth: 280, maxWidth: 460),
|
|
||||||
items: [
|
|
||||||
if (!_audio)
|
|
||||||
CheckedPopupMenuItem(
|
|
||||||
value: (aid: null, sid: null, subtitlesOff: true),
|
|
||||||
checked: !list.any((t) => t.selected),
|
|
||||||
height: 36,
|
|
||||||
child: const Text('Off'),
|
|
||||||
),
|
|
||||||
if (_audio && list.isEmpty)
|
|
||||||
const PopupMenuItem(enabled: false, height: 32, child: Text('None')),
|
|
||||||
for (final t in list)
|
|
||||||
CheckedPopupMenuItem(
|
|
||||||
value: _audio
|
|
||||||
? (aid: t.id, sid: null, subtitlesOff: false)
|
|
||||||
: (aid: null, sid: t.id, subtitlesOff: false),
|
|
||||||
checked: t.selected,
|
|
||||||
height: 36,
|
|
||||||
child: Text(t.label, maxLines: 1, overflow: TextOverflow.ellipsis),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
onMenuOpen?.call(false);
|
|
||||||
if (pick != null) onPick(pick);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// "1:30" in the controls: skip forward [fallbackSkip] (Shift+Right).
|
|
||||||
class SkipForwardButton extends StatelessWidget {
|
|
||||||
final VoidCallback onPressed;
|
|
||||||
final FocusNode? focusNode;
|
|
||||||
const SkipForwardButton({super.key, required this.onPressed, this.focusNode});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return Tooltip(
|
|
||||||
message: 'Skip 1:30 for everyone (Shift+Right)',
|
|
||||||
child: TextButton.icon(
|
|
||||||
key: const ValueKey('skip-forward-button'),
|
|
||||||
focusNode: focusNode,
|
|
||||||
style: TextButton.styleFrom(
|
|
||||||
foregroundColor: Colors.white,
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
|
||||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
|
||||||
),
|
|
||||||
onPressed: onPressed,
|
|
||||||
icon: const Icon(Icons.fast_forward_rounded, size: 16),
|
|
||||||
label: const Text('1:30', style: TextStyle(fontSize: 12)),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Floating pill over the video (Next episode, Skip OP / ED / 1:30):
|
|
||||||
/// faint at rest, lit on hover. Lives outside the auto-hiding controls, so
|
|
||||||
/// it shows in fullscreen and with the controls hidden.
|
|
||||||
class FloatingPill extends StatefulWidget {
|
class FloatingPill extends StatefulWidget {
|
||||||
|
/// Every action pill's height: the status pill's without avatars.
|
||||||
|
static const height = 44.0;
|
||||||
final String label;
|
final String label;
|
||||||
final String tooltip;
|
final String tooltip;
|
||||||
final IconData icon;
|
final IconData icon;
|
||||||
@@ -540,7 +25,7 @@ class FloatingPill extends StatefulWidget {
|
|||||||
required this.label,
|
required this.label,
|
||||||
required this.tooltip,
|
required this.tooltip,
|
||||||
required this.onPressed,
|
required this.onPressed,
|
||||||
this.icon = Icons.chevron_right,
|
this.icon = Icons.chevron_right_rounded,
|
||||||
this.tapKey,
|
this.tapKey,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -553,38 +38,31 @@ class _FloatingPillState extends State<FloatingPill> {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final primary = Theme.of(context).colorScheme.primary;
|
const fade = Duration(milliseconds: 150);
|
||||||
return MouseRegion(
|
return MouseRegion(
|
||||||
cursor: SystemMouseCursors.click,
|
cursor: SystemMouseCursors.click,
|
||||||
onEnter: (_) => setState(() => _hover = true),
|
onEnter: (_) => setState(() => _hover = true),
|
||||||
onExit: (_) => setState(() => _hover = false),
|
onExit: (_) => setState(() => _hover = false),
|
||||||
child: Tooltip(
|
child: Tooltip(
|
||||||
message: widget.tooltip,
|
message: widget.tooltip,
|
||||||
child: AnimatedScale(
|
|
||||||
duration: const Duration(milliseconds: 150),
|
|
||||||
scale: _hover ? 1.06 : 1,
|
|
||||||
child: AnimatedOpacity(
|
child: AnimatedOpacity(
|
||||||
duration: const Duration(milliseconds: 150),
|
duration: fade,
|
||||||
opacity: _hover ? 1 : 0.45,
|
opacity: _hover ? 1 : 0.45,
|
||||||
child: GestureDetector(
|
child: GestureDetector(
|
||||||
key: widget.tapKey,
|
key: widget.tapKey,
|
||||||
onTap: widget.onPressed,
|
onTap: widget.onPressed,
|
||||||
|
child: AppGlass.pill(
|
||||||
child: AnimatedContainer(
|
child: AnimatedContainer(
|
||||||
duration: const Duration(milliseconds: 150),
|
duration: fade,
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 9),
|
height: FloatingPill.height,
|
||||||
decoration: BoxDecoration(
|
padding: const EdgeInsets.only(left: 16, right: 12),
|
||||||
color: Colors.black.withValues(alpha: 0.75),
|
color: _hover ? Colors.white12 : Colors.transparent,
|
||||||
borderRadius: BorderRadius.circular(999),
|
|
||||||
border: Border.all(color: _hover ? primary : Colors.white24),
|
|
||||||
boxShadow: _hover
|
|
||||||
? [BoxShadow(color: primary.withValues(alpha: 0.45), blurRadius: 16)]
|
|
||||||
: const [],
|
|
||||||
),
|
|
||||||
child: Row(
|
child: Row(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
Text(widget.label, style: const TextStyle(color: Colors.white, fontSize: 13)),
|
Text(widget.label,
|
||||||
const SizedBox(width: 4),
|
style: const TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w600)),
|
||||||
|
const SizedBox(width: 6),
|
||||||
Icon(widget.icon, color: Colors.white, size: 18),
|
Icon(widget.icon, color: Colors.white, size: 18),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -0,0 +1,305 @@
|
|||||||
|
import 'package:sync_relay_core/core.dart' show FeedMessage;
|
||||||
|
|
||||||
|
// Everything that may become a toast, a sound, an attention request or an
|
||||||
|
// activity-log line, as one sealed type. Code that has news emits an
|
||||||
|
// event ([Notifier.notify]); only the notifier decides what the user sees
|
||||||
|
// and hears. Pure Dart (no Flutter): it can move to core with the policy.
|
||||||
|
|
||||||
|
sealed class AppEvent {
|
||||||
|
const AppEvent();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- feed
|
||||||
|
|
||||||
|
/// A server `feed` line (see PROTOCOL.md, `feed.action`); every one lands
|
||||||
|
/// in the activity log.
|
||||||
|
sealed class FeedEvent extends AppEvent {
|
||||||
|
final FeedMessage feed;
|
||||||
|
/// This member is the actor (its own chat, ready, queue add...).
|
||||||
|
final bool own;
|
||||||
|
const FeedEvent(this.feed, {this.own = false});
|
||||||
|
|
||||||
|
String get actor => feed.actor;
|
||||||
|
|
||||||
|
/// [feed] as its typed event. [selfId]: this member's id (people are
|
||||||
|
/// matched by `actorId` / `targetId`, never by name); [readyCount]:
|
||||||
|
/// members ready in the latest state (the pitch of a `ready` sound);
|
||||||
|
/// [queueThumb]: the picture hash of the Up next item a `queue-add`
|
||||||
|
/// added (from the state that came with it), '' when none.
|
||||||
|
factory FeedEvent.of(FeedMessage f, {String selfId = '', int readyCount = 0, String queueThumb = ''}) {
|
||||||
|
bool isSelf(String id) => selfId.isNotEmpty && id == selfId;
|
||||||
|
final own = isSelf(f.actorId);
|
||||||
|
return switch (f.action) {
|
||||||
|
'join' => MemberJoined(f, own: own),
|
||||||
|
'leave' => MemberLeft(f, own: own),
|
||||||
|
'gone' => MemberGone(f, own: own),
|
||||||
|
'return' => MemberReturned(f, own: own),
|
||||||
|
'away' => MemberSatOut(f,
|
||||||
|
own: own,
|
||||||
|
atYou: isSelf(f.targetId) && !isSelf(f.actorId),
|
||||||
|
autoSelf: isSelf(f.actorId) && f.targetId.isEmpty && f.reason.isNotEmpty),
|
||||||
|
'in' => MemberBack(f, own: own),
|
||||||
|
'ready' => ReadyChanged(f, own: own, ready: true, readyIndex: readyCount),
|
||||||
|
'unready' => ReadyChanged(f, own: own, ready: false),
|
||||||
|
'force-ready' => ForcedReady(f, own: own, ready: true),
|
||||||
|
'force-unready' => ForcedReady(f, own: own, ready: false),
|
||||||
|
'force-play' => ForcedTransport(f, own: own, play: true),
|
||||||
|
'force-hold' => ForcedTransport(f, own: own, play: false),
|
||||||
|
'swap' => MediaSwapped(f, own: own),
|
||||||
|
'seek' => Seeked(f, own: own),
|
||||||
|
'pause' => Paused(f, own: own),
|
||||||
|
'resume' => Resumed(f, own: own),
|
||||||
|
'finished' => Finished(f, own: own),
|
||||||
|
'chat' => ChatPosted(f, own: own),
|
||||||
|
'rename' => MemberRenamed(f, own: own),
|
||||||
|
'avatar' => AvatarChanged(f, own: own),
|
||||||
|
'queue-add' => QueueAdded(f, own: own, thumb: queueThumb),
|
||||||
|
'queue-remove' => QueueRemoved(f, own: own),
|
||||||
|
'queue-skip' => QueueSkipped(f, own: own),
|
||||||
|
'fetch-fail' => FetchFailed(f, own: own),
|
||||||
|
_ => OtherFeed(f, own: own),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class MemberJoined extends FeedEvent {
|
||||||
|
const MemberJoined(super.feed, {super.own});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Left for good (`reason` `bye`: the app closed or Leave; `grace`: gone
|
||||||
|
/// too long).
|
||||||
|
class MemberLeft extends FeedEvent {
|
||||||
|
const MemberLeft(super.feed, {super.own});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lost signal: gone for a while, kept in its grace period.
|
||||||
|
class MemberGone extends FeedEvent {
|
||||||
|
const MemberGone(super.feed, {super.own});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Back within its grace after a [MemberGone].
|
||||||
|
class MemberReturned extends FeedEvent {
|
||||||
|
const MemberReturned(super.feed, {super.own});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Someone sat out (`away`: the actor itself, or `target` sat out by the
|
||||||
|
/// actor; `reason` `idle` / `minimised` for an automatic one); [atYou]:
|
||||||
|
/// someone else sat this member out; [autoSelf]: this app's auto sit-out
|
||||||
|
/// set this member away.
|
||||||
|
class MemberSatOut extends FeedEvent {
|
||||||
|
final bool atYou;
|
||||||
|
final bool autoSelf;
|
||||||
|
const MemberSatOut(super.feed, {super.own, this.atYou = false, this.autoSelf = false});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Back from sitting out (`in`).
|
||||||
|
class MemberBack extends FeedEvent {
|
||||||
|
const MemberBack(super.feed, {super.own});
|
||||||
|
}
|
||||||
|
|
||||||
|
class ReadyChanged extends FeedEvent {
|
||||||
|
final bool ready;
|
||||||
|
/// Members ready when it came (pitch of the ready sound).
|
||||||
|
final int readyIndex;
|
||||||
|
const ReadyChanged(super.feed, {super.own, required this.ready, this.readyIndex = 0});
|
||||||
|
}
|
||||||
|
|
||||||
|
class ForcedReady extends FeedEvent {
|
||||||
|
final bool ready;
|
||||||
|
const ForcedReady(super.feed, {super.own, required this.ready});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Force play / hold.
|
||||||
|
class ForcedTransport extends FeedEvent {
|
||||||
|
final bool play;
|
||||||
|
const ForcedTransport(super.feed, {super.own, required this.play});
|
||||||
|
}
|
||||||
|
|
||||||
|
class MediaSwapped extends FeedEvent {
|
||||||
|
const MediaSwapped(super.feed, {super.own});
|
||||||
|
}
|
||||||
|
|
||||||
|
class Seeked extends FeedEvent {
|
||||||
|
const Seeked(super.feed, {super.own});
|
||||||
|
}
|
||||||
|
|
||||||
|
class Paused extends FeedEvent {
|
||||||
|
const Paused(super.feed, {super.own});
|
||||||
|
}
|
||||||
|
|
||||||
|
class Resumed extends FeedEvent {
|
||||||
|
const Resumed(super.feed, {super.own});
|
||||||
|
}
|
||||||
|
|
||||||
|
class Finished extends FeedEvent {
|
||||||
|
const Finished(super.feed, {super.own});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A chat message (`reason` carries the text); [own]: this member sent it.
|
||||||
|
class ChatPosted extends FeedEvent {
|
||||||
|
const ChatPosted(super.feed, {super.own});
|
||||||
|
}
|
||||||
|
|
||||||
|
class MemberRenamed extends FeedEvent {
|
||||||
|
const MemberRenamed(super.feed, {super.own});
|
||||||
|
}
|
||||||
|
|
||||||
|
class AvatarChanged extends FeedEvent {
|
||||||
|
const AvatarChanged(super.feed, {super.own});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Someone added an item to Up next (`target` its title); [thumb]: the
|
||||||
|
/// item's picture hash ('' when none).
|
||||||
|
class QueueAdded extends FeedEvent {
|
||||||
|
final String thumb;
|
||||||
|
const QueueAdded(super.feed, {super.own, this.thumb = ''});
|
||||||
|
}
|
||||||
|
|
||||||
|
class QueueRemoved extends FeedEvent {
|
||||||
|
const QueueRemoved(super.feed, {super.own});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Up next skipped an item (`target` its title, `reason` why).
|
||||||
|
class QueueSkipped extends FeedEvent {
|
||||||
|
const QueueSkipped(super.feed, {super.own});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The server could not fetch the current media.
|
||||||
|
class FetchFailed extends FeedEvent {
|
||||||
|
const FetchFailed(super.feed, {super.own});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An action this app does not know (a newer server).
|
||||||
|
class OtherFeed extends FeedEvent {
|
||||||
|
const OtherFeed(super.feed, {super.own});
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------- session
|
||||||
|
|
||||||
|
/// Someone poked this member.
|
||||||
|
class Nudged extends AppEvent {
|
||||||
|
/// Their name; '' when unknown.
|
||||||
|
final String name;
|
||||||
|
const Nudged(this.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Another member's player cannot open the current media.
|
||||||
|
class MemberCantPlay extends AppEvent {
|
||||||
|
final String name;
|
||||||
|
final String error;
|
||||||
|
const MemberCantPlay(this.name, this.error);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This member passes the video on slower than it plays.
|
||||||
|
class SlowSource extends AppEvent {
|
||||||
|
final String text;
|
||||||
|
const SlowSource(this.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This member started passing the video on through the server.
|
||||||
|
class RelayStarted extends AppEvent {
|
||||||
|
const RelayStarted();
|
||||||
|
}
|
||||||
|
|
||||||
|
class RelayFailed extends AppEvent {
|
||||||
|
final String error;
|
||||||
|
const RelayFailed(this.error);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The connection to the server dropped and stayed down a few seconds
|
||||||
|
/// (once per drop).
|
||||||
|
class ConnectionLost extends AppEvent {
|
||||||
|
const ConnectionLost();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// It came back after [ConnectionLost].
|
||||||
|
class ConnectionBack extends AppEvent {
|
||||||
|
const ConnectionBack();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The server refused something this app sent (`err`: Up next is full, a
|
||||||
|
/// forbidden action...).
|
||||||
|
class ServerRefused extends AppEvent {
|
||||||
|
final String text;
|
||||||
|
const ServerRefused(this.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The member passing the current video on has been gone a few seconds
|
||||||
|
/// ([left]: it left the server); viewers play what the server has.
|
||||||
|
class RelaySourceDropped extends AppEvent {
|
||||||
|
final String name;
|
||||||
|
final bool left;
|
||||||
|
const RelaySourceDropped(this.name, {this.left = false});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The current media started playing for the first time ("starting
|
||||||
|
/// now"; [title]: what plays, '' when unknown).
|
||||||
|
class PlaybackStarted extends AppEvent {
|
||||||
|
final String title;
|
||||||
|
const PlaybackStarted(this.title);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A reconnect found the server restarted (another `welcome.instance`).
|
||||||
|
class ServerRestarted extends AppEvent {
|
||||||
|
const ServerRestarted();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Another window of this install took the member over (`replaced`).
|
||||||
|
class Replaced extends AppEvent {
|
||||||
|
const Replaced();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Jellyfin progress reports fail (once per media).
|
||||||
|
class JellyfinProgressFailed extends AppEvent {
|
||||||
|
final bool signInExpired;
|
||||||
|
const JellyfinProgressFailed({required this.signInExpired});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ app
|
||||||
|
|
||||||
|
/// The player's shader message (a preset change, shaders turned off).
|
||||||
|
class ShaderMessage extends AppEvent {
|
||||||
|
final String text;
|
||||||
|
const ShaderMessage(this.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This app added an item to Up next.
|
||||||
|
class AddedToUpNext extends AppEvent {
|
||||||
|
final String title;
|
||||||
|
const AddedToUpNext(this.title);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Putting something up or adding it to Up next failed ([text]: why).
|
||||||
|
class ActionFailed extends AppEvent {
|
||||||
|
final String text;
|
||||||
|
const ActionFailed(this.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Schedule tab's request results and errors.
|
||||||
|
class ScheduleResult extends AppEvent {
|
||||||
|
final String text;
|
||||||
|
const ScheduleResult(this.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Mark a problem" done; [inSession]: in the server's session log.
|
||||||
|
class ProblemMarked extends AppEvent {
|
||||||
|
final bool inSession;
|
||||||
|
const ProblemMarked({required this.inSession});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Something went on the clipboard ([text]: the confirmation, e.g.
|
||||||
|
/// "Link copied").
|
||||||
|
class Copied extends AppEvent {
|
||||||
|
final String text;
|
||||||
|
const Copied(this.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
class CopyFailed extends AppEvent {
|
||||||
|
const CopyFailed();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A newer release is out (the update band shows it).
|
||||||
|
class UpdateAvailable extends AppEvent {
|
||||||
|
final String version;
|
||||||
|
const UpdateAvailable(this.version);
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import 'package:sync_relay_core/core.dart' show Presence, PresenceReason;
|
||||||
|
|
||||||
|
import '../platform/ports/shell_port.dart' show WindowActivity;
|
||||||
|
|
||||||
|
/// The auto sit-out timings, in one place.
|
||||||
|
abstract final class AutoSitOutTimes {
|
||||||
|
/// Not playing and no input for this long: away (`idle`). Watching
|
||||||
|
/// counts as activity, so a pause after a long watch starts fresh.
|
||||||
|
static const idle = Duration(minutes: 5);
|
||||||
|
|
||||||
|
/// Minimised (or hidden) for this long, playing or not: away
|
||||||
|
/// (`minimised`).
|
||||||
|
static const minimised = Duration(minutes: 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What [AutoSitOut.tick] asks the session to do.
|
||||||
|
sealed class AutoSitOutStep {
|
||||||
|
const AutoSitOutStep();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Nothing to do.
|
||||||
|
final class AutoStay extends AutoSitOutStep {
|
||||||
|
const AutoStay();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sit this member out (`presence` `away` with [reason]).
|
||||||
|
final class AutoAway extends AutoSitOutStep {
|
||||||
|
final PresenceReason reason;
|
||||||
|
const AutoAway(this.reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bring this member back `in`: it was set away automatically and the
|
||||||
|
/// user is back.
|
||||||
|
final class AutoBack extends AutoSitOutStep {
|
||||||
|
const AutoBack();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Auto sit-out: idle for
|
||||||
|
/// [AutoSitOutTimes.idle] while nothing plays, or minimised for
|
||||||
|
/// [AutoSitOutTimes.minimised] (playing or not), sets this member away;
|
||||||
|
/// input or the window's focus brings it back, but only from an away
|
||||||
|
/// this set ([autoAway]); a manual away (own or someone else's) stays.
|
||||||
|
/// Never when alone (nobody to hold up or to tell). Pure: the session
|
||||||
|
/// feeds it input, window changes and a 1 s [tick].
|
||||||
|
class AutoSitOut {
|
||||||
|
final Duration idleAfter;
|
||||||
|
final Duration minimisedAfter;
|
||||||
|
AutoSitOut(DateTime now,
|
||||||
|
{this.idleAfter = AutoSitOutTimes.idle, this.minimisedAfter = AutoSitOutTimes.minimised})
|
||||||
|
: _lastActive = now;
|
||||||
|
|
||||||
|
DateTime _lastActive;
|
||||||
|
DateTime? _minimisedSince;
|
||||||
|
bool _activitySinceAway = false;
|
||||||
|
bool _autoAway = false;
|
||||||
|
// An away sent, not yet seen in a state.
|
||||||
|
DateTime? _sentAt;
|
||||||
|
static const _echoWait = Duration(seconds: 10);
|
||||||
|
|
||||||
|
/// The member is away because this set it (not by hand, not someone
|
||||||
|
/// else).
|
||||||
|
bool get autoAway => _autoAway;
|
||||||
|
|
||||||
|
/// Keyboard, mouse or any action in the app.
|
||||||
|
void input(DateTime now) {
|
||||||
|
_lastActive = now;
|
||||||
|
_activitySinceAway = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The window's focus or visibility changed.
|
||||||
|
void window(WindowActivity a, DateTime now) {
|
||||||
|
switch (a) {
|
||||||
|
case WindowActivity.minimised:
|
||||||
|
case WindowActivity.hidden:
|
||||||
|
_minimisedSince ??= now;
|
||||||
|
case WindowActivity.focused:
|
||||||
|
_minimisedSince = null;
|
||||||
|
input(now);
|
||||||
|
case WindowActivity.unfocused:
|
||||||
|
_minimisedSince = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The user sat out (or came back) by hand: an away is no longer ours.
|
||||||
|
void manual() {
|
||||||
|
_autoAway = false;
|
||||||
|
_sentAt = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Once a second. [self]: this member's presence in the latest state
|
||||||
|
/// (null: not in one); [alone]: nobody else connected ([isAlone]);
|
||||||
|
/// [enabled]: the setting.
|
||||||
|
AutoSitOutStep tick(DateTime now,
|
||||||
|
{required Presence? self, required bool playing, required bool alone, required bool enabled}) {
|
||||||
|
if (playing) _lastActive = now;
|
||||||
|
if (self == null || self == Presence.gone) return const AutoStay();
|
||||||
|
if (self != Presence.away) {
|
||||||
|
final sent = _sentAt;
|
||||||
|
if (sent != null && now.difference(sent) < _echoWait) return const AutoStay();
|
||||||
|
_sentAt = null;
|
||||||
|
_autoAway = false;
|
||||||
|
} else {
|
||||||
|
_sentAt = null;
|
||||||
|
if (_autoAway && _activitySinceAway && _minimisedSince == null) {
|
||||||
|
_autoAway = false;
|
||||||
|
return const AutoBack();
|
||||||
|
}
|
||||||
|
return const AutoStay();
|
||||||
|
}
|
||||||
|
if (!enabled || alone) return const AutoStay();
|
||||||
|
final since = _minimisedSince;
|
||||||
|
final PresenceReason? reason;
|
||||||
|
if (since != null && now.difference(since) >= minimisedAfter) {
|
||||||
|
reason = PresenceReason.minimised;
|
||||||
|
} else if (!playing && now.difference(_lastActive) >= idleAfter) {
|
||||||
|
reason = PresenceReason.idle;
|
||||||
|
} else {
|
||||||
|
reason = null;
|
||||||
|
}
|
||||||
|
if (reason == null) return const AutoStay();
|
||||||
|
_autoAway = true;
|
||||||
|
_activitySinceAway = false;
|
||||||
|
_sentAt = now;
|
||||||
|
return AutoAway(reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,716 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
import 'dart:math';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart' show debugPrint;
|
||||||
|
import 'package:signals/signals_core.dart';
|
||||||
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
|
import '../screens/home/ui.dart' show appName, displayVersion;
|
||||||
|
import '../state/settings.dart';
|
||||||
|
import '../sync/sync_client.dart';
|
||||||
|
import 'app_events.dart';
|
||||||
|
import 'identity.dart' show ClientIdentity;
|
||||||
|
|
||||||
|
/// Thrown when a connect is superseded by cancel/leave before it finished.
|
||||||
|
class ConnectCancelled implements Exception {
|
||||||
|
const ConnectCancelled();
|
||||||
|
@override
|
||||||
|
String toString() => 'connection cancelled';
|
||||||
|
}
|
||||||
|
|
||||||
|
class ConnectParams {
|
||||||
|
final String host;
|
||||||
|
final int port;
|
||||||
|
final String secret;
|
||||||
|
final String name;
|
||||||
|
final String avatar;
|
||||||
|
final String mediaPath;
|
||||||
|
final String linkUrl;
|
||||||
|
/// Sent in hello by the hosting app's own client (see AppConfig.hostKey).
|
||||||
|
final String hostKey;
|
||||||
|
/// Put up with a `swap` right after joining (a Jellyfin ref or a link);
|
||||||
|
/// wins over [linkUrl].
|
||||||
|
final HelloMedia? media;
|
||||||
|
const ConnectParams({
|
||||||
|
required this.host,
|
||||||
|
required this.port,
|
||||||
|
required this.secret,
|
||||||
|
required this.name,
|
||||||
|
this.avatar = '',
|
||||||
|
this.mediaPath = '',
|
||||||
|
this.linkUrl = '',
|
||||||
|
this.hostKey = '',
|
||||||
|
this.media,
|
||||||
|
});
|
||||||
|
|
||||||
|
ConnectParams withMedia(HelloMedia? media) => ConnectParams(
|
||||||
|
host: host,
|
||||||
|
port: port,
|
||||||
|
secret: secret,
|
||||||
|
name: name,
|
||||||
|
avatar: avatar,
|
||||||
|
mediaPath: mediaPath,
|
||||||
|
linkUrl: media == null ? linkUrl : '',
|
||||||
|
hostKey: hostKey,
|
||||||
|
media: media,
|
||||||
|
);
|
||||||
|
|
||||||
|
ConnectParams withProfile({String? name, String? avatar}) => ConnectParams(
|
||||||
|
host: host,
|
||||||
|
port: port,
|
||||||
|
secret: secret,
|
||||||
|
name: name ?? this.name,
|
||||||
|
avatar: avatar ?? this.avatar,
|
||||||
|
mediaPath: mediaPath,
|
||||||
|
linkUrl: linkUrl,
|
||||||
|
hostKey: hostKey,
|
||||||
|
media: media,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the [Connection] is. Each change is a new value (a repeat is
|
||||||
|
/// notified too).
|
||||||
|
sealed class ConnState {
|
||||||
|
const ConnState();
|
||||||
|
|
||||||
|
/// The reconnect loop runs ([ConnLost] or [ConnReconnecting]).
|
||||||
|
bool get retrying => false;
|
||||||
|
|
||||||
|
/// A welcomed socket is up ([ConnOnline] or [ConnUnstable]): what the
|
||||||
|
/// server says is current.
|
||||||
|
bool get online => false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Not connected and not trying: before the first connect, after leave,
|
||||||
|
/// cancel or "stop reconnecting".
|
||||||
|
final class ConnClosed extends ConnState {
|
||||||
|
const ConnClosed();
|
||||||
|
@override
|
||||||
|
String toString() => 'closed';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first dial of a session (hello sent, waiting for welcome).
|
||||||
|
final class ConnConnecting extends ConnState {
|
||||||
|
const ConnConnecting();
|
||||||
|
@override
|
||||||
|
String toString() => 'connecting';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Welcome received; frames arrive.
|
||||||
|
final class ConnOnline extends ConnState {
|
||||||
|
const ConnOnline();
|
||||||
|
@override
|
||||||
|
bool get online => true;
|
||||||
|
@override
|
||||||
|
String toString() => 'online';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Still the same socket, but nothing came for [Connection.unstableAfter]
|
||||||
|
/// (the server sends a state every second): the link may be dying. Back
|
||||||
|
/// to [ConnOnline] with the next frame, [ConnLost] at
|
||||||
|
/// [Connection.silenceLimit].
|
||||||
|
final class ConnUnstable extends ConnState {
|
||||||
|
const ConnUnstable();
|
||||||
|
@override
|
||||||
|
bool get online => true;
|
||||||
|
@override
|
||||||
|
String toString() => 'unstable';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dropped (the socket closed, or nothing came for
|
||||||
|
/// [Connection.silenceLimit]); the next attempt is scheduled. The session
|
||||||
|
/// keeps what it had (the last state, the player, a relay it serves).
|
||||||
|
final class ConnLost extends ConnState {
|
||||||
|
const ConnLost();
|
||||||
|
@override
|
||||||
|
bool get retrying => true;
|
||||||
|
@override
|
||||||
|
String toString() => 'lost';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reconnect attempt [attempt] (1 is the first after the drop) is
|
||||||
|
/// dialling; after it failed it stays until the next one, unless the
|
||||||
|
/// socket's close said [ConnLost] meanwhile.
|
||||||
|
final class ConnReconnecting extends ConnState {
|
||||||
|
final int attempt;
|
||||||
|
const ConnReconnecting(this.attempt);
|
||||||
|
@override
|
||||||
|
bool get retrying => true;
|
||||||
|
@override
|
||||||
|
String toString() => 'reconnecting($attempt)';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The server refused this app; nothing retries. [code]: `version` or
|
||||||
|
/// `secret` when the server said so, `closed` when the host stopped
|
||||||
|
/// sharing (close 4016), else empty (offline, timeout,
|
||||||
|
/// anything else on the first dial); [message]: in plain words
|
||||||
|
/// ([connectErrorText]).
|
||||||
|
final class ConnRefused extends ConnState {
|
||||||
|
final String code;
|
||||||
|
final String message;
|
||||||
|
const ConnRefused(this.code, this.message);
|
||||||
|
@override
|
||||||
|
String toString() => 'refused($code: $message)';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Another connection of this install holds the member (`err` `replaced`,
|
||||||
|
/// close 4013, or this hello was `stale`): Starsync was opened in another
|
||||||
|
/// window. Nothing retries ("Retry" takes the member back).
|
||||||
|
final class ConnReplaced extends ConnState {
|
||||||
|
const ConnReplaced();
|
||||||
|
String get message => replacedText;
|
||||||
|
@override
|
||||||
|
String toString() => 'replaced';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [ConnReplaced] in plain words.
|
||||||
|
const replacedText = 'Starsync was opened in another window';
|
||||||
|
|
||||||
|
/// `ConnRefused('closed')`: the host closed their server to friends
|
||||||
|
/// (close 4016).
|
||||||
|
const stoppedSharingText = 'the host stopped sharing their server';
|
||||||
|
|
||||||
|
/// A version refusal in plain words: [err] is the server's `err`
|
||||||
|
/// `version` (its range in `min`/`max`), or a proto 15 server's codeless
|
||||||
|
/// `proto mismatch`, which is always an older host.
|
||||||
|
String versionText(ErrorFrame? err) {
|
||||||
|
final max = err?.max, min = err?.min;
|
||||||
|
if (err?.code == null || (max != null && max < RelayConstants.protoMin)) {
|
||||||
|
return 'the host runs an older Starsync — they need to update';
|
||||||
|
}
|
||||||
|
if (min != null && min > RelayConstants.protoMax) return 'the host runs a newer Starsync — update the app';
|
||||||
|
return 'the host runs a different Starsync version — update both apps';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A failed dial in plain words.
|
||||||
|
String connectErrorText(Object e) {
|
||||||
|
if (e is HelloRefused) {
|
||||||
|
final err = e.error;
|
||||||
|
if (err != null && err.code == null && err.message.contains('proto mismatch')) return versionText(err);
|
||||||
|
return switch (e.code) {
|
||||||
|
ErrCode.version => versionText(err),
|
||||||
|
ErrCode.secret => 'wrong server password (401)',
|
||||||
|
ErrCode.replaced || ErrCode.stale => replacedText,
|
||||||
|
_ => 'refused: ${err?.message ?? 'closed (${e.closeCode})'}',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
final msg = '$e';
|
||||||
|
if (msg.contains('SocketException') || msg.contains('Connection refused')) {
|
||||||
|
return 'host offline — check address and port';
|
||||||
|
}
|
||||||
|
return 'connect failed: $e';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The terminal state a failed dial leaves, or null when another attempt
|
||||||
|
/// may work.
|
||||||
|
ConnState? _terminalFor(Object e, {required bool first}) {
|
||||||
|
if (e is HelloRefused) {
|
||||||
|
final err = e.error;
|
||||||
|
if (err != null && err.code == null && err.message.contains('proto mismatch')) {
|
||||||
|
return ConnRefused('version', versionText(err));
|
||||||
|
}
|
||||||
|
switch (e.code) {
|
||||||
|
case ErrCode.replaced:
|
||||||
|
case ErrCode.stale:
|
||||||
|
return const ConnReplaced();
|
||||||
|
case ErrCode.version:
|
||||||
|
return ConnRefused('version', connectErrorText(e));
|
||||||
|
case ErrCode.secret:
|
||||||
|
return ConnRefused('secret', connectErrorText(e));
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return first ? ConnRefused('', connectErrorText(e)) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a hello says about this install besides the connect form.
|
||||||
|
typedef HelloIdentity = ({String client, int seq, ClientCaps caps, int? feedAfter});
|
||||||
|
|
||||||
|
/// Builds the `hello` for [params]. Injectable so later protocol versions
|
||||||
|
/// add fields without changing [Connection].
|
||||||
|
typedef HelloBuilder = HelloMessage Function(ConnectParams params, HelloIdentity id);
|
||||||
|
|
||||||
|
/// Protocol 16's hello: this build's version range, the install's client
|
||||||
|
/// id and connection count, the app version, platform and what it can do;
|
||||||
|
/// `feedAfter` on a reconnect to the same server.
|
||||||
|
HelloMessage defaultHello(ConnectParams params, HelloIdentity id) => HelloMessage(
|
||||||
|
proto: RelayConstants.protoMax,
|
||||||
|
protoMin: RelayConstants.protoMin,
|
||||||
|
secret: params.secret,
|
||||||
|
user: HelloUser(name: params.name, avatar: params.avatar),
|
||||||
|
hostKey: params.hostKey,
|
||||||
|
client: id.client,
|
||||||
|
seq: id.seq,
|
||||||
|
app: appVersion,
|
||||||
|
platform: Platform.operatingSystem,
|
||||||
|
caps: id.caps,
|
||||||
|
feedAfter: id.feedAfter,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// How a welcome relates to the member this app held before.
|
||||||
|
typedef Rejoin = ({
|
||||||
|
/// A reconnect of the running session (not its first dial).
|
||||||
|
bool reconnect,
|
||||||
|
/// `welcome.resumed`: the same member, everything kept.
|
||||||
|
bool resumed,
|
||||||
|
/// The same server boot as the last welcome (`welcome.instance`).
|
||||||
|
bool sameServer,
|
||||||
|
/// The token the session held before this welcome ('' on the first).
|
||||||
|
String oldToken,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The session's part of a welcome, called before its state goes out
|
||||||
|
/// (see [Connection.onWelcome]).
|
||||||
|
typedef WelcomeHandler = void Function(WelcomeMessage welcome, Rejoin rejoin);
|
||||||
|
|
||||||
|
/// The link to the server: the [SyncClient] socket, the first connect,
|
||||||
|
/// reconnects (backoff with jitter between attempts, epochs that make a
|
||||||
|
/// cancelled attempt stale), the silence policy ("unstable" after
|
||||||
|
/// [unstableAfter] without a frame, lost at [silenceLimit]), the 1 s
|
||||||
|
/// heartbeat (clock ping, which also keeps this member under the
|
||||||
|
/// server's silence limit, and diagnostics), the connection lost/back
|
||||||
|
/// events and [state]. The install's identity rides in every hello
|
||||||
|
/// ([identity]); what a welcome means to the session is its [onWelcome].
|
||||||
|
class Connection {
|
||||||
|
final SyncClient client;
|
||||||
|
/// Where [ConnectionLost] / [ConnectionBack] go (the Notifier).
|
||||||
|
final void Function(AppEvent event) _notify;
|
||||||
|
/// Builds each dial's hello.
|
||||||
|
final HelloBuilder hello;
|
||||||
|
/// `hello.client` / `hello.seq` (the stored one in the app; a fresh
|
||||||
|
/// in-memory one by default, so every test connection is its own
|
||||||
|
/// install).
|
||||||
|
final ClientIdentity identity;
|
||||||
|
/// `hello.caps` at each dial (the session sets it).
|
||||||
|
ClientCaps Function() caps;
|
||||||
|
/// Wait before the first reconnect attempt; it doubles per failed
|
||||||
|
/// attempt up to [maxReconnectDelay], each with ±20 % jitter.
|
||||||
|
final Duration reconnectDelay;
|
||||||
|
final Duration maxReconnectDelay;
|
||||||
|
/// No frame for this long: [ConnUnstable].
|
||||||
|
final Duration unstableAfter;
|
||||||
|
/// No frame for this long means the connection is lost.
|
||||||
|
final Duration silenceLimit;
|
||||||
|
/// The lost sound plays only once a drop lasted this long (a quick
|
||||||
|
/// reconnect says nothing, and no lost/back pair per flap).
|
||||||
|
final Duration lostSoundAfter;
|
||||||
|
/// The clock the silence and the lost sound are measured on (UTC; a
|
||||||
|
/// test passes a fake one). The heartbeat that checks it stays a real
|
||||||
|
/// 1 s timer.
|
||||||
|
final DateTime Function() now;
|
||||||
|
final Random _random;
|
||||||
|
|
||||||
|
Connection(
|
||||||
|
{void Function(AppEvent event)? notify,
|
||||||
|
SyncClient? client,
|
||||||
|
this.hello = defaultHello,
|
||||||
|
ClientIdentity? identity,
|
||||||
|
ClientCaps Function()? caps,
|
||||||
|
this.reconnectDelay = const Duration(seconds: 1),
|
||||||
|
this.maxReconnectDelay = const Duration(seconds: 15),
|
||||||
|
this.unstableAfter = const Duration(seconds: 3),
|
||||||
|
this.silenceLimit = const Duration(seconds: 9),
|
||||||
|
this.lostSoundAfter = const Duration(seconds: 4),
|
||||||
|
DateTime Function()? now,
|
||||||
|
Random? random})
|
||||||
|
: _notify = notify ?? ((_) {}),
|
||||||
|
now = now ?? _utcNow,
|
||||||
|
identity = identity ?? ClientIdentity.ephemeral(),
|
||||||
|
caps = caps ?? (() => const ClientCaps(source: true)),
|
||||||
|
_random = random ?? Random(),
|
||||||
|
client = client ?? SyncClient() {
|
||||||
|
this.client.onFrame = () => _lastFrameAt = this.now();
|
||||||
|
_subs = [
|
||||||
|
this.client.status.listen(_onStatus),
|
||||||
|
this.client.errors.listen(_onError),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
late final List<StreamSubscription> _subs;
|
||||||
|
|
||||||
|
static DateTime _utcNow() => DateTime.now().toUtc();
|
||||||
|
|
||||||
|
final _state = signal<ConnState>(const ConnClosed());
|
||||||
|
/// Every change is notified, a repeat too.
|
||||||
|
ReadonlySignal<ConnState> get state => _state;
|
||||||
|
|
||||||
|
/// Set by the session (see [WelcomeHandler]).
|
||||||
|
WelcomeHandler? onWelcome;
|
||||||
|
|
||||||
|
/// This app's log lines to the server's session log (Settings: "Share
|
||||||
|
/// diagnostics with the server"), and "Mark a problem". Runs from
|
||||||
|
/// [begin] to [close].
|
||||||
|
late final DiagUploader diag = DiagUploader(
|
||||||
|
target: _diagTarget, version: '$appName ${displayVersion()} on ${Platform.operatingSystem}');
|
||||||
|
|
||||||
|
DiagTarget? _diagTarget() {
|
||||||
|
final uri = client.wsUri;
|
||||||
|
if (client.token.isEmpty || uri == null || !client.clockSync.hasSample) return null;
|
||||||
|
return (base: DiagUploader.baseOf(uri), token: client.token, offsetMs: client.clockSync.offsetMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
ConnectParams? _params;
|
||||||
|
/// The last connect's parameters (with [updateProfile]'s changes); a
|
||||||
|
/// reconnect dials with them.
|
||||||
|
ConnectParams? get params => _params;
|
||||||
|
|
||||||
|
// Bumped by every connect/leave/cancel/retry: stale attempts no-op.
|
||||||
|
int _epoch = 0;
|
||||||
|
Timer? _reconnectTimer;
|
||||||
|
Timer? _heartbeat;
|
||||||
|
// Set by close/cancel/a terminal refusal: no reconnect, no lost detection.
|
||||||
|
bool _closed = false;
|
||||||
|
bool _everOnline = false;
|
||||||
|
/// The connection-lost sound played; the reconnected one answers it once.
|
||||||
|
bool _lostSounded = false;
|
||||||
|
DateTime? _lastFrameAt;
|
||||||
|
/// When the current drop began (the last frame for a silent link).
|
||||||
|
DateTime? _droppedAt;
|
||||||
|
int _attempt = 0;
|
||||||
|
/// Non-terminal `err` frames, in plain words.
|
||||||
|
final _errorTexts = StreamController<String>.broadcast();
|
||||||
|
|
||||||
|
// The socket and what the server said, read through.
|
||||||
|
Stream<StateBroadcast> get states => client.states;
|
||||||
|
/// Feed entries, chat included; replayed ones after a reconnect.
|
||||||
|
Stream<FeedMessage> get feeds => client.feeds;
|
||||||
|
Stream<NudgeNotice> get nudges => client.nudges;
|
||||||
|
/// `err` frames after the welcome (a `replaced` one ends the connection
|
||||||
|
/// instead).
|
||||||
|
Stream<String> get errors => _errorTexts.stream;
|
||||||
|
String get token => client.token;
|
||||||
|
String get memberId => client.memberId;
|
||||||
|
/// This member's `/j/...` URL from `welcome`.
|
||||||
|
String? get relayUrl => client.relayUrl;
|
||||||
|
StateBroadcast? get lastState => client.lastState;
|
||||||
|
/// Now on the server's clock (the ping/pong clock offset).
|
||||||
|
DateTime serverNow() => client.serverNow();
|
||||||
|
|
||||||
|
void sendReady(bool ready, {String source = 'manual'}) => client.sendReady(ready, source: source);
|
||||||
|
void sendForce(String target, bool ready) => client.sendForce(target, ready);
|
||||||
|
void sendSeek(double position, {int seq = 0}) => client.sendSeek(position, seq: seq);
|
||||||
|
void sendSwap(HelloMedia media, {String? queueId, SwapRestore? restore}) =>
|
||||||
|
client.sendSwap(media, queueId: queueId, restore: restore);
|
||||||
|
void sendQueue(QueueIntent intent) => client.sendQueue(intent);
|
||||||
|
void sendReport({
|
||||||
|
required double position,
|
||||||
|
required double buffered,
|
||||||
|
required int eventId,
|
||||||
|
double duration = 0,
|
||||||
|
int mediaId = 0,
|
||||||
|
Map<String, bool>? jf,
|
||||||
|
String error = '',
|
||||||
|
}) =>
|
||||||
|
client.sendReport(
|
||||||
|
position: position,
|
||||||
|
buffered: buffered,
|
||||||
|
eventId: eventId,
|
||||||
|
duration: duration,
|
||||||
|
mediaId: mediaId,
|
||||||
|
jf: jf,
|
||||||
|
error: error);
|
||||||
|
void sendChat(String text) => client.sendChat(text);
|
||||||
|
void sendArt(int mediaId, {String? poster, String? banner}) =>
|
||||||
|
client.sendArt(mediaId, poster: poster, banner: banner);
|
||||||
|
void sendPresence(PresenceIntent intent) => client.sendPresence(intent);
|
||||||
|
void sendNudge(String target) => client.sendNudge(target);
|
||||||
|
|
||||||
|
/// Name and/or picture change for everyone now; reconnects send them too.
|
||||||
|
void updateProfile({String? name, String? avatar}) {
|
||||||
|
_params = _params?.withProfile(name: name, avatar: avatar);
|
||||||
|
client.sendProfile(name: name, avatar: avatar);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A new epoch: attempts in flight become stale, a scheduled reconnect
|
||||||
|
/// is dropped. Returns it.
|
||||||
|
int invalidate() {
|
||||||
|
_epoch++;
|
||||||
|
_reconnectTimer?.cancel();
|
||||||
|
_reconnectTimer = null;
|
||||||
|
return _epoch;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// False once a cancel, retry, leave or new connect followed [epoch].
|
||||||
|
bool isCurrent(int epoch) => epoch == _epoch;
|
||||||
|
|
||||||
|
/// A new session with [params]: forgets the last one's server and
|
||||||
|
/// starts the diagnostics. [dial] connects.
|
||||||
|
void begin(ConnectParams params) {
|
||||||
|
_params = params;
|
||||||
|
_closed = false;
|
||||||
|
_everOnline = false;
|
||||||
|
_lostSounded = false;
|
||||||
|
_droppedAt = null;
|
||||||
|
_attempt = 0;
|
||||||
|
diag
|
||||||
|
..share = AppSettings.instance.shareDiagnostics.peek()
|
||||||
|
..start();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first dial of the session [begin] started. Throws
|
||||||
|
/// [ConnectCancelled] when [epoch] went stale meanwhile (whoever bumped
|
||||||
|
/// it also closed the socket); any other failure leaves [state] refused
|
||||||
|
/// (or replaced).
|
||||||
|
Future<WelcomeMessage> dial(int epoch) async {
|
||||||
|
final params = _params!;
|
||||||
|
_set(const ConnConnecting());
|
||||||
|
try {
|
||||||
|
final welcome = await _connect(params, reconnect: false);
|
||||||
|
if (epoch != _epoch) throw const ConnectCancelled();
|
||||||
|
_online();
|
||||||
|
return welcome;
|
||||||
|
} catch (e) {
|
||||||
|
if (epoch != _epoch) throw const ConnectCancelled();
|
||||||
|
debugPrint('connect failed: $e');
|
||||||
|
_set(_terminalFor(e, first: true)!);
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<WelcomeMessage> _connect(ConnectParams params, {required bool reconnect}) {
|
||||||
|
final oldToken = client.token;
|
||||||
|
final before = client.instance;
|
||||||
|
final id = (
|
||||||
|
client: identity.clientId,
|
||||||
|
seq: identity.nextSeq(),
|
||||||
|
caps: caps(),
|
||||||
|
feedAfter: reconnect && before.isNotEmpty && client.lastFeedSeq > 0 ? client.lastFeedSeq : null,
|
||||||
|
);
|
||||||
|
return client.connectWith(
|
||||||
|
wsUri: _wsUri(params),
|
||||||
|
hello: hello(params, id),
|
||||||
|
onWelcome: (w) {
|
||||||
|
_lastFrameAt = now();
|
||||||
|
onWelcome?.call(w, (
|
||||||
|
reconnect: reconnect,
|
||||||
|
resumed: w.resumed,
|
||||||
|
sameServer: before.isNotEmpty && before == w.instance,
|
||||||
|
oldToken: oldToken,
|
||||||
|
));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static Uri _wsUri(ConnectParams p) => Uri.parse('ws://${p.host}:${p.port}/sync');
|
||||||
|
|
||||||
|
void _online() {
|
||||||
|
_attempt = 0;
|
||||||
|
_everOnline = true;
|
||||||
|
_droppedAt = null;
|
||||||
|
if (_lostSounded) {
|
||||||
|
_lostSounded = false;
|
||||||
|
_notify(const ConnectionBack());
|
||||||
|
}
|
||||||
|
_lastFrameAt = now();
|
||||||
|
_set(const ConnOnline());
|
||||||
|
_heartbeat ??= Timer.periodic(const Duration(seconds: 1), (_) => _beat());
|
||||||
|
}
|
||||||
|
|
||||||
|
void _set(ConnState s) => _state.set(s, force: true);
|
||||||
|
|
||||||
|
void _onStatus(SyncStatus s) {
|
||||||
|
// Before the first welcome a close is just the dial failing; during a
|
||||||
|
// reconnect attempt the attempt reports it. A socket error (a reset
|
||||||
|
// link) may come without a close.
|
||||||
|
if (s != SyncStatus.closed && s != SyncStatus.error) return;
|
||||||
|
if (_closed || !_everOnline || !_state.peek().online) return;
|
||||||
|
switch (s == SyncStatus.closed ? client.closeCode : null) {
|
||||||
|
case CloseCodes.replaced:
|
||||||
|
case CloseCodes.stale:
|
||||||
|
_end(const ConnReplaced());
|
||||||
|
case CloseCodes.version:
|
||||||
|
_end(ConnRefused('version', versionText(null)));
|
||||||
|
case CloseCodes.secret:
|
||||||
|
_end(const ConnRefused('secret', 'wrong server password (401)'));
|
||||||
|
case CloseCodes.closed:
|
||||||
|
_end(const ConnRefused('closed', stoppedSharingText));
|
||||||
|
default:
|
||||||
|
_dropped(now());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onError(ErrorFrame e) {
|
||||||
|
if (e.code == ErrCode.replaced) {
|
||||||
|
_end(const ConnReplaced());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!_errorTexts.isClosed) _errorTexts.add(e.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A terminal state: no more attempts, the socket goes.
|
||||||
|
void _end(ConnState s) {
|
||||||
|
debugPrint('connection ended: $s');
|
||||||
|
_halt(s);
|
||||||
|
unawaited(client.drop());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lost since [since]: the socket goes, a reconnect is scheduled (unless
|
||||||
|
/// one already is or dials).
|
||||||
|
void _dropped(DateTime since) {
|
||||||
|
if (_closed || _state.peek().retrying) return;
|
||||||
|
_droppedAt = since;
|
||||||
|
unawaited(client.drop());
|
||||||
|
scheduleReconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every second once online: a ping (a clock sample; it also keeps this
|
||||||
|
/// member under the server's silence limit while nothing else is sent),
|
||||||
|
/// the diagnostics, the silence check and the delayed lost sound.
|
||||||
|
void _beat() {
|
||||||
|
final t = now();
|
||||||
|
final s = _state.peek();
|
||||||
|
if (s.online) client.sendPing();
|
||||||
|
diag
|
||||||
|
..share = AppSettings.instance.shareDiagnostics.peek()
|
||||||
|
..tick();
|
||||||
|
if (_closed) return;
|
||||||
|
final last = _lastFrameAt;
|
||||||
|
if (s.online && last != null) {
|
||||||
|
final quiet = t.difference(last);
|
||||||
|
if (quiet >= silenceLimit) {
|
||||||
|
debugPrint('connection: nothing for ${quiet.inSeconds} s; reconnecting');
|
||||||
|
_dropped(last);
|
||||||
|
} else if (quiet >= unstableAfter) {
|
||||||
|
if (s is ConnOnline) _set(const ConnUnstable());
|
||||||
|
} else if (s is ConnUnstable) {
|
||||||
|
_set(const ConnOnline());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final since = _droppedAt;
|
||||||
|
if (_state.peek().retrying && since != null && !_lostSounded && t.difference(since) >= lostSoundAfter) {
|
||||||
|
_lostSounded = true;
|
||||||
|
_notify(const ConnectionLost());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reconnect after the backoff ([state] lost), unless closed, never
|
||||||
|
/// online (unless [manual]) or already retrying.
|
||||||
|
void scheduleReconnect({bool manual = false}) {
|
||||||
|
if (_closed || _params == null) return;
|
||||||
|
if (!manual && !_everOnline) return;
|
||||||
|
if (_state.peek().retrying) return;
|
||||||
|
_droppedAt ??= now();
|
||||||
|
_set(const ConnLost());
|
||||||
|
_armReconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The wait before attempt [attempt] (1 = the first after a drop).
|
||||||
|
Duration delayFor(int attempt) {
|
||||||
|
final base = reconnectDelay.inMilliseconds * pow(2, max(0, attempt - 1));
|
||||||
|
final capped = min(base.toDouble(), maxReconnectDelay.inMilliseconds.toDouble());
|
||||||
|
return Duration(milliseconds: (capped * (0.8 + 0.4 * _random.nextDouble())).round());
|
||||||
|
}
|
||||||
|
|
||||||
|
void _armReconnect() {
|
||||||
|
final epoch = _epoch;
|
||||||
|
_reconnectTimer?.cancel();
|
||||||
|
_reconnectTimer = Timer(delayFor(_attempt + 1), () => _reconnect(epoch));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One reconnect attempt. An attempt from an older epoch must not touch
|
||||||
|
/// state (it would kill the newer connection).
|
||||||
|
Future<void> _reconnect(int epoch) async {
|
||||||
|
_reconnectTimer = null;
|
||||||
|
bool stale() => epoch != _epoch;
|
||||||
|
final params = _params;
|
||||||
|
if (stale() || params == null || _closed) return;
|
||||||
|
try {
|
||||||
|
_set(ConnReconnecting(++_attempt));
|
||||||
|
await _connect(params, reconnect: true);
|
||||||
|
// Whoever bumped the epoch also closed (or replaced) the socket.
|
||||||
|
if (stale()) return;
|
||||||
|
_online();
|
||||||
|
} catch (e) {
|
||||||
|
if (stale()) return;
|
||||||
|
debugPrint('reconnect failed: $e');
|
||||||
|
final end = _terminalFor(e, first: false);
|
||||||
|
if (end != null) {
|
||||||
|
_end(end);
|
||||||
|
} else {
|
||||||
|
_retryAfterFailure(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _retryAfterFailure(Object e) {
|
||||||
|
if (_closed) {
|
||||||
|
_set(const ConnClosed());
|
||||||
|
} else if (!_everOnline) {
|
||||||
|
// Only a manual retry before any welcome gets here.
|
||||||
|
_set(_terminalFor(e, first: true)!);
|
||||||
|
} else {
|
||||||
|
if (!_state.peek().retrying) _set(const ConnLost());
|
||||||
|
_armReconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Stop reconnecting": no more attempts; one dialling is aborted.
|
||||||
|
void cancelReconnect() {
|
||||||
|
_halt(const ConnClosed());
|
||||||
|
unawaited(client.drop());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancel during setup: aborts the dial.
|
||||||
|
Future<void> cancelConnect() async {
|
||||||
|
_halt(const ConnClosed());
|
||||||
|
try {
|
||||||
|
await client.drop();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _halt(ConnState s) {
|
||||||
|
_closed = true;
|
||||||
|
invalidate();
|
||||||
|
_heartbeat?.cancel();
|
||||||
|
_heartbeat = null;
|
||||||
|
_set(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Retry": a reconnect after the first backoff whatever the state
|
||||||
|
/// (after [ConnReplaced] it takes the member back from the other
|
||||||
|
/// window). False without a session to retry.
|
||||||
|
bool retry() {
|
||||||
|
if (_params == null) return false;
|
||||||
|
invalidate();
|
||||||
|
_closed = false;
|
||||||
|
_attempt = 0;
|
||||||
|
_set(const ConnClosed());
|
||||||
|
scheduleReconnect(manual: true);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// No more reconnects or silence checks, [state] closed; the socket
|
||||||
|
/// stays until [close] (the session's last words still go out).
|
||||||
|
void stop() {
|
||||||
|
_closed = true;
|
||||||
|
_reconnectTimer?.cancel();
|
||||||
|
_reconnectTimer = null;
|
||||||
|
_heartbeat?.cancel();
|
||||||
|
_heartbeat = null;
|
||||||
|
_set(const ConnClosed());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [stop], the last diagnostics (before the token goes), with [bye] the
|
||||||
|
/// member's `bye` (flushed: the server's close is awaited briefly), then
|
||||||
|
/// the socket.
|
||||||
|
Future<void> close({bool bye = false}) async {
|
||||||
|
stop();
|
||||||
|
await diag.stop();
|
||||||
|
// A welcomed socket still open (a dead one costs the short wait).
|
||||||
|
if (bye && client.isOpen && client.token.isNotEmpty) await client.sendBye();
|
||||||
|
try {
|
||||||
|
await client.disconnect();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> dispose() async {
|
||||||
|
stop();
|
||||||
|
for (final s in _subs) {
|
||||||
|
await s.cancel();
|
||||||
|
}
|
||||||
|
await _errorTexts.close();
|
||||||
|
await client.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,338 @@
|
|||||||
|
import 'package:sync_relay_core/core.dart';
|
||||||
|
|
||||||
|
import '../jellyfin/session_media.dart';
|
||||||
|
import 'party.dart';
|
||||||
|
|
||||||
|
// Who fetches the current media and how it spreads, from the state alone:
|
||||||
|
// the members card's source line and each member's route and buffer.
|
||||||
|
|
||||||
|
/// `media.relay` of a state, or null when the media is not relayed.
|
||||||
|
MediaRelay? stateMediaRelay(StateBroadcast state) {
|
||||||
|
final r = state.media?['relay'];
|
||||||
|
return r is Map ? MediaRelay.fromJson(Map<String, Object?>.from(r)) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "4.1 MB/s", "850 kB/s".
|
||||||
|
String formatRate(int bytesPerSec) {
|
||||||
|
if (bytesPerSec >= 1000000) {
|
||||||
|
final mb = bytesPerSec / 1e6;
|
||||||
|
return '${mb.toStringAsFixed(mb >= 10 ? 0 : 1)} MB/s';
|
||||||
|
}
|
||||||
|
return '${(bytesPerSec / 1000).round()} kB/s';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the current media reaches the party.
|
||||||
|
enum DeliveryKind {
|
||||||
|
/// A link every app opens itself.
|
||||||
|
link,
|
||||||
|
/// The hosting app's file, read by everyone from its server.
|
||||||
|
hostFile,
|
||||||
|
/// A file the dedicated server was started with.
|
||||||
|
serverFile,
|
||||||
|
/// A member's machine passes it on through the server.
|
||||||
|
memberRelay,
|
||||||
|
/// The server reads the link itself.
|
||||||
|
serverFetch,
|
||||||
|
/// Jellyfin: own accounts, the server's login for the rest.
|
||||||
|
jellyfin,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How a member gets the bytes.
|
||||||
|
enum DeliveryRoute {
|
||||||
|
/// It serves them (a relay source, the host's file).
|
||||||
|
source,
|
||||||
|
/// It reads them from the server.
|
||||||
|
server,
|
||||||
|
/// It fetches them itself (a link, its own Jellyfin account).
|
||||||
|
direct,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum BufferHealth { good, low, starving }
|
||||||
|
|
||||||
|
/// The relay source's condition.
|
||||||
|
enum SourceState {
|
||||||
|
ok,
|
||||||
|
/// Measured slower than the media's bitrate.
|
||||||
|
slow,
|
||||||
|
/// Its channel is down (or the server has not read the link yet).
|
||||||
|
waiting,
|
||||||
|
/// The source member's connection dropped (`gone`, within its grace):
|
||||||
|
/// viewers play what the server has.
|
||||||
|
gone,
|
||||||
|
/// It left the server.
|
||||||
|
left,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Members' names by id, kept after they leave: "Foxyz left" needs the
|
||||||
|
/// name the state no longer has.
|
||||||
|
class MemberNames {
|
||||||
|
final _names = <String, String>{};
|
||||||
|
|
||||||
|
void observe(StateBroadcast r) {
|
||||||
|
if (_names.length > 256) _names.clear();
|
||||||
|
for (final m in r.members) {
|
||||||
|
_names[m.id] = m.name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String? operator [](String id) => _names[id];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The member [m]'s route and buffer.
|
||||||
|
class MemberDelivery {
|
||||||
|
/// Null when unknown (a Jellyfin member that has not reported yet).
|
||||||
|
final DeliveryRoute? route;
|
||||||
|
final DeliveryKind kind;
|
||||||
|
/// Bytes per second the server sends it lately.
|
||||||
|
final int rate;
|
||||||
|
/// Null when it does not count: sitting out, reconnecting, cannot play.
|
||||||
|
final BufferHealth? health;
|
||||||
|
final double buffered;
|
||||||
|
/// The media is a Jellyfin item (direct = its own account).
|
||||||
|
final bool jellyfin;
|
||||||
|
const MemberDelivery({
|
||||||
|
required this.route,
|
||||||
|
required this.kind,
|
||||||
|
this.jellyfin = false,
|
||||||
|
required this.rate,
|
||||||
|
required this.health,
|
||||||
|
required this.buffered,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// "via server · 3.2 MB/s", "direct", "passes it on"; empty when unknown.
|
||||||
|
String get short => switch (route) {
|
||||||
|
DeliveryRoute.source => kind == DeliveryKind.hostFile ? 'hosts the file' : 'passes it on',
|
||||||
|
DeliveryRoute.server => rate > 0 ? 'via server · ${formatRate(rate)}' : 'via server',
|
||||||
|
DeliveryRoute.direct => jellyfin ? 'own Jellyfin account' : 'direct',
|
||||||
|
null => '',
|
||||||
|
};
|
||||||
|
|
||||||
|
/// [short] and the buffer: "via server · 3.2 MB/s · 45 s buffered".
|
||||||
|
String get detail => [
|
||||||
|
if (short.isNotEmpty) short,
|
||||||
|
if (health != null) health == BufferHealth.starving ? 'buffer empty' : '${buffered.round()} s buffered',
|
||||||
|
].join(' · ');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The current media's path for everyone: what the members card's source
|
||||||
|
/// line says.
|
||||||
|
class Delivery {
|
||||||
|
final DeliveryKind kind;
|
||||||
|
/// The member serving it ([DeliveryKind.memberRelay], [DeliveryKind.hostFile]); empty otherwise.
|
||||||
|
final String sourceId;
|
||||||
|
final String sourceName;
|
||||||
|
final bool sourceIsSelf;
|
||||||
|
final SourceState state;
|
||||||
|
/// [SourceState.gone]: since when; and the time the line is read at.
|
||||||
|
final DateTime? goneSince;
|
||||||
|
final DateTime? at;
|
||||||
|
/// `media.relay.rate` / `need` (0 unknown).
|
||||||
|
final int rate, need;
|
||||||
|
/// Members (not sitting out, not the source) reading from the server,
|
||||||
|
/// and fetching it themselves.
|
||||||
|
final int viaServer, direct;
|
||||||
|
const Delivery({
|
||||||
|
required this.kind,
|
||||||
|
this.sourceId = '',
|
||||||
|
this.sourceName = '',
|
||||||
|
this.sourceIsSelf = false,
|
||||||
|
this.state = SourceState.ok,
|
||||||
|
this.goneSince,
|
||||||
|
this.at,
|
||||||
|
this.rate = 0,
|
||||||
|
this.need = 0,
|
||||||
|
this.viaServer = 0,
|
||||||
|
this.direct = 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
bool get relayed => kind == DeliveryKind.memberRelay || kind == DeliveryKind.serverFetch;
|
||||||
|
|
||||||
|
/// Rate against bitrate, both known: 1 = exactly what the media needs.
|
||||||
|
double? get headroom => rate > 0 && need > 0 ? rate / need : null;
|
||||||
|
|
||||||
|
String get title {
|
||||||
|
final who = sourceIsSelf ? 'You' : sourceName;
|
||||||
|
switch (kind) {
|
||||||
|
case DeliveryKind.link:
|
||||||
|
return 'Everyone plays the link directly';
|
||||||
|
case DeliveryKind.serverFile:
|
||||||
|
return 'The server has the file';
|
||||||
|
case DeliveryKind.hostFile:
|
||||||
|
return sourceIsSelf ? 'You host the file' : '$who hosts the file';
|
||||||
|
case DeliveryKind.jellyfin:
|
||||||
|
return viaServer == 0 ? 'Everyone streams it from Jellyfin' : 'From Jellyfin';
|
||||||
|
case DeliveryKind.serverFetch:
|
||||||
|
return switch (state) {
|
||||||
|
SourceState.waiting => 'The server is getting the video…',
|
||||||
|
SourceState.slow => 'The server fetches it slower than it plays',
|
||||||
|
_ => 'The server fetches it',
|
||||||
|
};
|
||||||
|
case DeliveryKind.memberRelay:
|
||||||
|
return switch (state) {
|
||||||
|
SourceState.left => '$sourceName left — playing what the server has',
|
||||||
|
SourceState.gone => sourceIsSelf
|
||||||
|
? 'Reconnecting you to the server…'
|
||||||
|
: "$sourceName's connection dropped — playing what the server has${_for()}",
|
||||||
|
SourceState.waiting => sourceIsSelf ? 'Reconnecting you to the server…' : 'Waiting for $who to reconnect',
|
||||||
|
SourceState.slow => sourceIsSelf ? 'Your upload is slower than the video' : "$who's upload is slower than the video",
|
||||||
|
SourceState.ok => sourceIsSelf ? 'You pass it on through the server' : '$who passes it on through the server',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String _for() {
|
||||||
|
final since = goneSince, now = at;
|
||||||
|
if (since == null || now == null || now.difference(since).inMinutes < 1) return '';
|
||||||
|
return ' (${sinceText(since, now)})';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "3 through the server · 4.1 MB/s, needs 2.3 MB/s"; empty when
|
||||||
|
/// there is nothing to add.
|
||||||
|
String get detail {
|
||||||
|
final parts = <String>[
|
||||||
|
if (direct > 0 && (kind == DeliveryKind.jellyfin || kind == DeliveryKind.memberRelay))
|
||||||
|
'$direct with their own account',
|
||||||
|
if (viaServer > 0 && kind != DeliveryKind.link) '$viaServer through the server',
|
||||||
|
if (rate > 0 && state != SourceState.left && state != SourceState.gone) need > 0 ? '${formatRate(rate)}, needs ${formatRate(need)}' : formatRate(rate),
|
||||||
|
];
|
||||||
|
return parts.join(' · ');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The hover text: what the numbers mean.
|
||||||
|
String get explain => switch (kind) {
|
||||||
|
DeliveryKind.memberRelay || DeliveryKind.serverFetch => [
|
||||||
|
if (rate > 0)
|
||||||
|
'${kind == DeliveryKind.serverFetch ? 'The server gets' : sourceIsSelf ? 'You send' : '$sourceName sends'} '
|
||||||
|
'${formatRate(rate)} while the server asks for more.',
|
||||||
|
if (need > 0) 'The video averages ${formatRate(need)}.',
|
||||||
|
if (state == SourceState.slow) 'Slower than the video: the others will pause to buffer.',
|
||||||
|
if (rate == 0) 'The speed shows once bytes have flowed for a few seconds.',
|
||||||
|
].join(' '),
|
||||||
|
DeliveryKind.hostFile || DeliveryKind.serverFile => 'Everyone else reads the file from the server.',
|
||||||
|
DeliveryKind.jellyfin => 'Members with an account on that Jellyfin stream it themselves; '
|
||||||
|
'the rest through the server.',
|
||||||
|
DeliveryKind.link => 'Each app opens the link itself; the server only keeps time.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The current media's [Delivery]; null with nothing up or nobody else in
|
||||||
|
/// the server. [names] remembers a source that left; [now] reads how long
|
||||||
|
/// a gone source has been gone.
|
||||||
|
Delivery? deliveryOf(StateBroadcast r, {required String selfId, MemberNames? names, DateTime? now}) {
|
||||||
|
final media = r.media;
|
||||||
|
if (media == null || r.members.length < 2) return null;
|
||||||
|
final rel = media['relay'];
|
||||||
|
final relay = rel is Map ? MediaRelay.fromJson(Map<String, Object?>.from(rel)) : null;
|
||||||
|
final ref = refOfStateMedia(media);
|
||||||
|
final url = media['url'];
|
||||||
|
final kind = relay != null
|
||||||
|
? (relay.fetch ? DeliveryKind.serverFetch : DeliveryKind.memberRelay)
|
||||||
|
: ref != null
|
||||||
|
? DeliveryKind.jellyfin
|
||||||
|
: url is String && url.isNotEmpty
|
||||||
|
? DeliveryKind.link
|
||||||
|
: r.members.any((m) => m.host)
|
||||||
|
? DeliveryKind.hostFile
|
||||||
|
: DeliveryKind.serverFile;
|
||||||
|
final sourceId = switch (kind) {
|
||||||
|
DeliveryKind.memberRelay => relay!.source,
|
||||||
|
DeliveryKind.hostFile => r.members.firstWhere((m) => m.host).id,
|
||||||
|
_ => '',
|
||||||
|
};
|
||||||
|
final source = r.members.where((m) => m.id == sourceId).firstOrNull;
|
||||||
|
var via = 0, direct = 0;
|
||||||
|
for (final m in r.members) {
|
||||||
|
if (!isPresent(m) || m.id == sourceId) continue;
|
||||||
|
switch (routeOf(m, kind, sourceId, ref, r.relay)) {
|
||||||
|
case DeliveryRoute.server:
|
||||||
|
via++;
|
||||||
|
case DeliveryRoute.direct:
|
||||||
|
direct++;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A Jellyfin item that everyone streams with their own account: the
|
||||||
|
// relay stands by, nothing goes through it.
|
||||||
|
if (kind == DeliveryKind.memberRelay && ref != null && via == 0 && source != null) {
|
||||||
|
return Delivery(kind: DeliveryKind.jellyfin, direct: direct);
|
||||||
|
}
|
||||||
|
final state = relay == null
|
||||||
|
? SourceState.ok
|
||||||
|
: kind == DeliveryKind.memberRelay && source == null
|
||||||
|
? SourceState.left
|
||||||
|
: kind == DeliveryKind.memberRelay && (relay.sourceGone || source?.presence == Presence.gone)
|
||||||
|
? SourceState.gone
|
||||||
|
: !relay.live
|
||||||
|
? SourceState.waiting
|
||||||
|
: relay.slow
|
||||||
|
? SourceState.slow
|
||||||
|
: SourceState.ok;
|
||||||
|
return Delivery(
|
||||||
|
kind: kind,
|
||||||
|
sourceId: sourceId,
|
||||||
|
sourceName: source?.name ?? names?[sourceId] ?? 'The member passing it on',
|
||||||
|
sourceIsSelf: sourceId.isNotEmpty && sourceId == selfId,
|
||||||
|
state: state,
|
||||||
|
goneSince: state == SourceState.gone ? relay?.sourceGoneSince ?? source?.goneSince : null,
|
||||||
|
at: now ?? DateTime.now().toUtc(),
|
||||||
|
rate: relay?.rate ?? 0,
|
||||||
|
need: relay?.need ?? 0,
|
||||||
|
viaServer: via,
|
||||||
|
direct: direct,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How [m] gets media of [kind] served by [sourceId]. Jellyfin: by its
|
||||||
|
/// last `report.jf` for [ref]'s server ([jellyfinRelay]: the server can
|
||||||
|
/// relay it); null before it reported.
|
||||||
|
DeliveryRoute? routeOf(MemberView m, DeliveryKind kind, String sourceId, JellyfinRef? ref, bool jellyfinRelay) {
|
||||||
|
if (sourceId.isNotEmpty && m.id == sourceId) return DeliveryRoute.source;
|
||||||
|
switch (kind) {
|
||||||
|
case DeliveryKind.link:
|
||||||
|
return DeliveryRoute.direct;
|
||||||
|
case DeliveryKind.hostFile:
|
||||||
|
case DeliveryKind.serverFile:
|
||||||
|
case DeliveryKind.serverFetch:
|
||||||
|
return DeliveryRoute.server;
|
||||||
|
case DeliveryKind.memberRelay:
|
||||||
|
case DeliveryKind.jellyfin:
|
||||||
|
final own = ref == null ? null : m.jf[ref.serverId];
|
||||||
|
if (own == true) return DeliveryRoute.direct;
|
||||||
|
if (kind == DeliveryKind.memberRelay) return DeliveryRoute.server;
|
||||||
|
return own == false && jellyfinRelay ? DeliveryRoute.server : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [m]'s route and buffer for [d] (from [deliveryOf] on [r]).
|
||||||
|
MemberDelivery memberDeliveryOf(MemberView m, StateBroadcast r, Delivery d) {
|
||||||
|
final counts = countsForReady(m);
|
||||||
|
final need = r.bufferNeed;
|
||||||
|
final ref = refOfStateMedia(r.media);
|
||||||
|
final health = !counts
|
||||||
|
? null
|
||||||
|
: m.buffered >= need
|
||||||
|
? BufferHealth.good
|
||||||
|
: r.transport == 'playing' && m.buffered < 1
|
||||||
|
? BufferHealth.starving
|
||||||
|
: BufferHealth.low;
|
||||||
|
return MemberDelivery(
|
||||||
|
route: m.presence == Presence.away ? null : routeOf(m, d.kind, d.sourceId, ref, r.relay),
|
||||||
|
kind: d.kind,
|
||||||
|
jellyfin: ref != null,
|
||||||
|
rate: m.rate,
|
||||||
|
health: health,
|
||||||
|
buffered: m.buffered,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the source is told once per media when it is too slow; null
|
||||||
|
/// while it keeps up (or this member is not the source).
|
||||||
|
String? slowSourceWarning(StateBroadcast r, String selfId) {
|
||||||
|
final rel = r.media?['relay'];
|
||||||
|
if (rel is! Map || selfId.isEmpty) return null;
|
||||||
|
final relay = MediaRelay.fromJson(Map<String, Object?>.from(rel));
|
||||||
|
if (relay.source != selfId || !relay.slow) return null;
|
||||||
|
return 'Your upload (${formatRate(relay.rate)}) is slower than this video needs '
|
||||||
|
'(${formatRate(relay.need)}): the others will pause to buffer now and then.';
|
||||||
|
}
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
enum HealthSeverity { ok, info, warn, error }
|
|
||||||
|
|
||||||
class HealthStatus {
|
|
||||||
final HealthSeverity severity;
|
|
||||||
final String message;
|
|
||||||
const HealthStatus(this.severity, this.message);
|
|
||||||
}
|
|
||||||
+81
-17
@@ -1,13 +1,82 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
|
import 'dart:math';
|
||||||
import 'dart:typed_data';
|
import 'dart:typed_data';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:hive_ce/hive.dart';
|
||||||
import 'package:signals/signals_flutter.dart';
|
import 'package:signals/signals_flutter.dart';
|
||||||
|
import 'package:sync_relay_core/core.dart' show validClientId;
|
||||||
|
|
||||||
import '../../state/connect_prefs.dart';
|
import '../state/connect_prefs.dart';
|
||||||
import '../../state/session_state.dart';
|
import '../state/settings.dart' show settingsBoxName;
|
||||||
import '../../widgets/avatar_pipeline.dart';
|
import '../widgets/avatar_pipeline.dart';
|
||||||
|
|
||||||
|
// Who this app is: to the server (the per-install client id and its
|
||||||
|
// rising connection count, [ClientIdentity]) and to people (name, picture
|
||||||
|
// and colour, [Profile]).
|
||||||
|
|
||||||
|
/// `hello.client` and `hello.seq` (PROTOCOL.md "Presence"): a random id
|
||||||
|
/// per install, kept in the settings box (so per data folder, and per
|
||||||
|
/// `STARSYNC_PROFILE`), and a number that rises with every connection this
|
||||||
|
/// install makes. A server maps the id to one lasting member; the higher
|
||||||
|
/// `seq` wins when two windows of the same install connect.
|
||||||
|
class ClientIdentity {
|
||||||
|
static const _keyClient = 'clientId';
|
||||||
|
static const _keySeq = 'clientSeq';
|
||||||
|
|
||||||
|
final Box? _box;
|
||||||
|
ClientIdentity._(this._box, this.clientId, this._seq);
|
||||||
|
|
||||||
|
/// The id: 22 characters of base64url (16 random bytes). Private: never
|
||||||
|
/// shown, never logged.
|
||||||
|
final String clientId;
|
||||||
|
int _seq;
|
||||||
|
|
||||||
|
/// The last `seq` handed out.
|
||||||
|
int get seq => _seq;
|
||||||
|
|
||||||
|
/// The stored identity (the settings box, once open); one is made and
|
||||||
|
/// stored on first use. Without the box (tests, no store): [ephemeral].
|
||||||
|
factory ClientIdentity.stored() {
|
||||||
|
final box = Hive.isBoxOpen(settingsBoxName) ? Hive.box(settingsBoxName) : null;
|
||||||
|
if (box == null) return ClientIdentity.ephemeral();
|
||||||
|
var id = box.get(_keyClient);
|
||||||
|
if (id is! String || !validClientId(id)) {
|
||||||
|
id = newClientId();
|
||||||
|
unawaited(_put(box, _keyClient, id));
|
||||||
|
}
|
||||||
|
final seq = box.get(_keySeq);
|
||||||
|
return ClientIdentity._(box, id, seq is int && seq > 0 ? seq : 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A fresh id kept in memory only (each test coordinator is its own
|
||||||
|
/// install).
|
||||||
|
factory ClientIdentity.ephemeral() => ClientIdentity._(null, newClientId(), 0);
|
||||||
|
|
||||||
|
/// The `seq` for the next hello: one higher than any before, stored at
|
||||||
|
/// once.
|
||||||
|
int nextSeq() {
|
||||||
|
_seq++;
|
||||||
|
final box = _box;
|
||||||
|
if (box != null) unawaited(_put(box, _keySeq, _seq));
|
||||||
|
return _seq;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Future<void> _put(Box box, String key, Object value) async {
|
||||||
|
try {
|
||||||
|
await box.put(key, value);
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('save $key failed: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 16 random bytes as 22 characters of base64url.
|
||||||
|
static String newClientId() {
|
||||||
|
final r = Random.secure();
|
||||||
|
return base64Url.encode([for (var i = 0; i < 16; i++) r.nextInt(256)]).replaceAll('=', '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Colours offered in the profile card; the first is the default.
|
/// Colours offered in the profile card; the first is the default.
|
||||||
const profileColors = <Color>[
|
const profileColors = <Color>[
|
||||||
@@ -26,17 +95,11 @@ const _keyColor = 'profileColor';
|
|||||||
/// avatar = removed). Swappable so tests can watch it.
|
/// avatar = removed). Swappable so tests can watch it.
|
||||||
typedef ProfilePush = void Function({String? name, String? avatar});
|
typedef ProfilePush = void Function({String? name, String? avatar});
|
||||||
|
|
||||||
/// The one place a profile change reaches the server.
|
/// Display name, picture and colour of this app's user. Backed by the
|
||||||
void pushProfileToSession({String? name, String? avatar}) {
|
/// connect form ([forms]: the name) and the connect-form box (the cropped
|
||||||
final session = SessionState.instance;
|
|
||||||
if (session.route.peek() != AppRoute.session) return;
|
|
||||||
session.coordinator.updateProfile(name: name, avatar: avatar);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Display name, picture and colour of this app's user. Backed by
|
|
||||||
/// [SessionState.lastForm] (name) and the connect-form box (the cropped
|
|
||||||
/// 256 px PNG and the colour); every change is persisted, and while in a
|
/// 256 px PNG and the colour); every change is persisted, and while in a
|
||||||
/// server it is pushed through [push] so everyone sees it at once.
|
/// server it is pushed through [push] so everyone sees it at once. The
|
||||||
|
/// composition root sets both.
|
||||||
class Profile {
|
class Profile {
|
||||||
static final Profile instance = Profile._();
|
static final Profile instance = Profile._();
|
||||||
Profile._();
|
Profile._();
|
||||||
@@ -46,7 +109,8 @@ class Profile {
|
|||||||
final picture = signal<Uint8List?>(null);
|
final picture = signal<Uint8List?>(null);
|
||||||
final color = signal<Color>(profileColors.first);
|
final color = signal<Color>(profileColors.first);
|
||||||
final error = signal<String?>(null);
|
final error = signal<String?>(null);
|
||||||
ProfilePush push = pushProfileToSession;
|
ProfilePush push = ({String? name, String? avatar}) {};
|
||||||
|
ConnectStore forms = ConnectStore();
|
||||||
bool _loaded = false;
|
bool _loaded = false;
|
||||||
Timer? _nameTimer;
|
Timer? _nameTimer;
|
||||||
|
|
||||||
@@ -61,7 +125,7 @@ class Profile {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _load() async {
|
Future<void> _load() async {
|
||||||
final form = SessionState.instance.lastForm;
|
final form = forms.form;
|
||||||
name.value = form.name;
|
name.value = form.name;
|
||||||
try {
|
try {
|
||||||
final box = connectFormBoxIfOpen() ?? await openConnectFormBox();
|
final box = connectFormBoxIfOpen() ?? await openConnectFormBox();
|
||||||
@@ -92,7 +156,7 @@ class Profile {
|
|||||||
final v = value.trim();
|
final v = value.trim();
|
||||||
if (v.isEmpty || v == name.peek()) return;
|
if (v.isEmpty || v == name.peek()) return;
|
||||||
name.value = v;
|
name.value = v;
|
||||||
SessionState.instance.lastForm.name = v;
|
forms.form.name = v;
|
||||||
unawaited(_save());
|
unawaited(_save());
|
||||||
// Typing renames once it settles, not on every key.
|
// Typing renames once it settles, not on every key.
|
||||||
_nameTimer?.cancel();
|
_nameTimer?.cancel();
|
||||||
@@ -117,7 +181,7 @@ class Profile {
|
|||||||
|
|
||||||
Future<void> _save() async {
|
Future<void> _save() async {
|
||||||
try {
|
try {
|
||||||
await SessionState.instance.saveForm();
|
await forms.save();
|
||||||
final box = connectFormBoxIfOpen() ?? await openConnectFormBox();
|
final box = connectFormBoxIfOpen() ?? await openConnectFormBox();
|
||||||
final png = picture.peek();
|
final png = picture.peek();
|
||||||
await box.putAll({
|
await box.putAll({
|
||||||
Loaded 100 of 455 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user