dsh-cloudmusic-player 0.5.0 → 0.7.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,190 @@
1
+ param(
2
+ [Parameter(Mandatory=$true)][string]$Action,
3
+ [int]$SeekMs = 0,
4
+ [string]$AumidPattern = 'msedge\.exe|chrome\.exe|firefox\.exe|MSWebView2|msedgewebview2'
5
+ )
6
+
7
+ $ErrorActionPreference = 'Stop'
8
+
9
+ # PowerShell 5.1 writes console output in the system ANSI codepage (GBK on zh-CN);
10
+ # force UTF-8 so Node (which decodes stdout as UTF-8) reads CJK titles correctly.
11
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
12
+
13
+ function Out-Json([hashtable]$obj) {
14
+ [Console]::Out.WriteLine(($obj | ConvertTo-Json -Compress -Depth 6))
15
+ [Console]::Out.Flush()
16
+ }
17
+
18
+ try {
19
+ Add-Type -AssemblyName System.Runtime.WindowsRuntime -ErrorAction Stop
20
+ } catch {
21
+ Out-Json @{ ok=$false; error='smtc-unavailable'; detail=('add-type failed: ' + $_.Exception.Message) }
22
+ exit 0
23
+ }
24
+
25
+ # Must use DOUBLE quotes: "IAsyncOperation``1" -> one literal backtick -> matches runtime IAsyncOperation`1
26
+ $asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object {
27
+ $_.Name -eq "AsTask" -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq "IAsyncOperation``1"
28
+ })[0]
29
+
30
+ function Await($winRtTask, $resultType) {
31
+ $asTask = $asTaskGeneric.MakeGenericMethod($resultType)
32
+ $netTask = $asTask.Invoke($null, @($winRtTask))
33
+ $netTask.Wait(-1) | Out-Null
34
+ $netTask.Result
35
+ }
36
+
37
+ try {
38
+ [Windows.Media.Control.GlobalSystemMediaTransportControlsSessionManager,Windows.Media.Control,ContentType=WindowsRuntime] | Out-Null
39
+ [Windows.Media.Control.GlobalSystemMediaTransportControlsSessionMediaProperties,Windows.Media.Control,ContentType=WindowsRuntime] | Out-Null
40
+
41
+ $mgr = Await ([Windows.Media.Control.GlobalSystemMediaTransportControlsSessionManager]::RequestAsync()) ([Windows.Media.Control.GlobalSystemMediaTransportControlsSessionManager])
42
+ if ($null -eq $mgr) { Out-Json @{ ok=$false; error='smtc-unavailable'; detail='no session manager' }; exit 0 }
43
+
44
+ $sessions = @($mgr.GetSessions())
45
+ if ($sessions.Count -eq 0) { Out-Json @{ ok=$false; error='no-browser-music-session' }; exit 0 }
46
+
47
+ # Strict filter: browser AUMID + non-empty title. Never fall back to "only one session".
48
+ # PlaybackType==1 (Music) is NOT enough: video pages (Bilibili/YouTube) also report 1.
49
+ # Real differentiators measured on this machine:
50
+ # - a music track has a non-empty Artist (the singer); a video page leaves it blank;
51
+ # - a video title carries a site marker e.g. "_bilibili" / "youtube" (ASCII only here:
52
+ # this .ps1 must stay pure ASCII, PowerShell 5.1 reads it as ANSI/GBK otherwise).
53
+ # Score candidates and pick the best instead of "first match wins".
54
+ $videoMarkers = @('bilibili','youtube','youtu.be','acfun','nicovideo')
55
+ $target = $null
56
+ $targetProps = $null
57
+ $bestScore = -1
58
+ # Chromium reports only ONE SMTC session per browser. If a video page steals the
59
+ # focus, the music track's session disappears from SMTC even though its audio is
60
+ # still playing. For CONTROL actions (play/pause/toggle/...), the only channel that
61
+ # can still reach the browser's actual media is that single session, so keep the
62
+ # first browser session as a fallback even when its metadata looks like a video.
63
+ # STATE actions keep the strict music-only rule (Node side has sticky fallback).
64
+ $controlTarget = $null
65
+ $controlProps = $null
66
+ foreach ($s in $sessions) {
67
+ $aumid = [string]$s.SourceAppUserModelId
68
+ if ($aumid -notmatch $AumidPattern) { continue }
69
+ $props = $null
70
+ try { $props = Await ($s.TryGetMediaPropertiesAsync()) ([Windows.Media.Control.GlobalSystemMediaTransportControlsSessionMediaProperties]) } catch { }
71
+ if ($null -eq $props) { continue }
72
+ $title = [string]$props.Title
73
+ if ([string]::IsNullOrWhiteSpace($title)) { continue }
74
+ $pt = 0
75
+ try { $pt = [int]$props.PlaybackType } catch { $pt = 0 }
76
+ $artist = [string]$props.Artist
77
+
78
+ # Record the loose candidate for control fallback (video titles included).
79
+ if ($null -eq $controlTarget) {
80
+ $controlTarget = $s
81
+ $controlProps = @{ props=$props; pt=$pt; title=$title; artist=$artist }
82
+ }
83
+
84
+ # Hard reject obvious video-site titles (ASCII markers only) for STATE.
85
+ $lower = $title.ToLowerInvariant()
86
+ $isVideo = $false
87
+ foreach ($m in $videoMarkers) { if ($lower.Contains($m)) { $isVideo = $true; break } }
88
+ if ($isVideo) { continue }
89
+
90
+ # A non-empty artist is the strong "this is music" signal.
91
+ # No artist + clean title is only a weak candidate (used when nothing better exists).
92
+ $pb = $s.GetPlaybackInfo()
93
+ $isPlaying = ($null -ne $pb -and [string]$pb.PlaybackStatus -eq 'Playing')
94
+ if (-not [string]::IsNullOrWhiteSpace($artist)) {
95
+ $score = $(if ($isPlaying) { 3 } else { 2 })
96
+ } else {
97
+ $score = 1
98
+ }
99
+ if ($score -gt $bestScore) {
100
+ $bestScore = $score
101
+ $target = $s
102
+ $targetProps = @{ props=$props; pt=$pt; title=$title; artist=$artist }
103
+ }
104
+ }
105
+
106
+ if ($null -eq $target) {
107
+ # No music session. For control actions, fall back to the loose browser session
108
+ # so pause/play still reach the browser's real media (the music audio may still
109
+ # be playing under a video session's metadata). STATE keeps strict behavior.
110
+ if ($Action -ne 'state' -and $null -ne $controlTarget) {
111
+ $target = $controlTarget
112
+ $targetProps = $controlProps
113
+ } else {
114
+ Out-Json @{ ok=$false; error='no-browser-music-session' }; exit 0
115
+ }
116
+ }
117
+
118
+ if ($Action -eq 'state') {
119
+ $pb = $target.GetPlaybackInfo()
120
+ $tl = $target.GetTimelineProperties()
121
+ $pos = 0.0; $end = 0.0
122
+ try { $pos = [double]$tl.Position.TotalSeconds } catch { }
123
+ try { $end = [double]$tl.EndTime.TotalSeconds } catch { }
124
+ $ctl = $pb.Controls
125
+ Out-Json @{
126
+ ok=$true
127
+ title=$targetProps.title
128
+ artist=$targetProps.artist
129
+ album=([string]$targetProps.props.AlbumTitle)
130
+ status=([string]$pb.PlaybackStatus)
131
+ pos=$pos
132
+ end=$end
133
+ aumid=([string]$target.SourceAppUserModelId)
134
+ playbackType=$targetProps.pt
135
+ canPlay=[bool]$ctl.IsPlayEnabled
136
+ canPause=[bool]$ctl.IsPauseEnabled
137
+ canNext=[bool]$ctl.IsNextEnabled
138
+ canPrev=[bool]$ctl.IsPreviousEnabled
139
+ canSeek=[bool]$ctl.IsPlaybackPositionEnabled
140
+ }
141
+ exit 0
142
+ }
143
+
144
+ $done = $false
145
+ switch ($Action) {
146
+ 'play' { $done = [bool](Await ($target.TryPlayAsync()) ([bool])) }
147
+ 'pause' { $done = [bool](Await ($target.TryPauseAsync()) ([bool])) }
148
+ 'toggle'{ $done = [bool](Await ($target.TryTogglePlayPauseAsync()) ([bool])) }
149
+ 'next' { $done = [bool](Await ($target.TrySkipNextAsync()) ([bool])) }
150
+ 'prev' { $done = [bool](Await ($target.TrySkipPreviousAsync()) ([bool])) }
151
+ 'seek' {
152
+ $ticks = [long]$SeekMs * 10000
153
+ $done = [bool](Await ($target.TryChangePlaybackPositionAsync($ticks)) ([bool]))
154
+ }
155
+ default { Out-Json @{ ok=$false; error='unknown-action'; detail=$Action }; exit 0 }
156
+ }
157
+ if ($done) {
158
+ # Control and read back state in the SAME process: the caller uses this
159
+ # snapshot as the post-action state, avoiding a second ~280ms PowerShell
160
+ # cold start for the follow-up state() call.
161
+ $pb = $target.GetPlaybackInfo()
162
+ $tl = $target.GetTimelineProperties()
163
+ $pos = 0.0; $end = 0.0
164
+ try { $pos = [double]$tl.Position.TotalSeconds } catch { }
165
+ try { $end = [double]$tl.EndTime.TotalSeconds } catch { }
166
+ $ctl = $pb.Controls
167
+ Out-Json @{
168
+ ok=$true
169
+ action=$Action
170
+ title=$targetProps.title
171
+ artist=$targetProps.artist
172
+ album=([string]$targetProps.props.AlbumTitle)
173
+ status=([string]$pb.PlaybackStatus)
174
+ pos=$pos
175
+ end=$end
176
+ aumid=([string]$target.SourceAppUserModelId)
177
+ playbackType=$targetProps.pt
178
+ canPlay=[bool]$ctl.IsPlayEnabled
179
+ canPause=[bool]$ctl.IsPauseEnabled
180
+ canNext=[bool]$ctl.IsNextEnabled
181
+ canPrev=[bool]$ctl.IsPreviousEnabled
182
+ canSeek=[bool]$ctl.IsPlaybackPositionEnabled
183
+ }
184
+ }
185
+ else { Out-Json @{ ok=$false; error='smtc-control-failed'; detail=$Action } }
186
+ exit 0
187
+ } catch {
188
+ Out-Json @{ ok=$false; error='smtc-error'; detail=$_.Exception.Message }
189
+ exit 0
190
+ }