Skip to content

Commit

Permalink
Remove websocket send dark
Browse files Browse the repository at this point in the history
  • Loading branch information
HeHang0 committed Mar 26, 2024
1 parent 0440b68 commit 504df01
Show file tree
Hide file tree
Showing 13 changed files with 153 additions and 156 deletions.
14 changes: 10 additions & 4 deletions mobile/lib/audio/audio_play.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import 'package:audio_service/audio_service.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_volume_controller/flutter_volume_controller.dart';
import 'package:just_audio/just_audio.dart';
import 'package:musiche/utils/android_channel.dart';
import 'package:musiche/log/logger.dart';

import 'music_item.dart';
import 'music_play_request.dart';
Expand All @@ -15,6 +15,7 @@ enum LoopType {
loop, random, order, single
}
class AudioPlay extends BaseAudioHandler {
static const String _tag = "AudioPlay";
late final AudioPlayer _audioPlayer;
late final StreamController<MusicItem> _onLoverChanged;
Stream<PlayerState> get onPlayerStateChanged => _audioPlayer.playerStateStream;
Expand Down Expand Up @@ -100,6 +101,7 @@ class AudioPlay extends BaseAudioHandler {
playUrl(url);
} else {
_musicPlayRequest?.playlist.remove(music);
Logger.i(_tag, "music cannot get url");
skipToNext();
}
}
Expand All @@ -119,8 +121,13 @@ class AudioPlay extends BaseAudioHandler {
Future<void> seek(Duration position) async {
_audioPlayer.seek(position);
}
Timer? _autoPlayDelay;
@override
Future<void> skipToNext() async {
_autoPlayDelay?.cancel();
_autoPlayDelay = Timer(const Duration(milliseconds: 50), _next);
}
void _next(){
if((_musicPlayRequest?.playlist.length ?? 0) == 0 || _loopType == LoopType.single){
playCurrent();
return;
Expand Down Expand Up @@ -149,15 +156,14 @@ class AudioPlay extends BaseAudioHandler {
Future<void> skipToPrevious() async {
playIndex(_lastIndex);
}

_onPlayerStateChanged(PlayerState state) async {
setMediaMeta();
if(_audioPlayer.playerState.processingState == ProcessingState.completed || _audioPlayer.playerState.processingState == ProcessingState.idle) {
if(_audioPlayer.playerState.processingState == ProcessingState.completed) {
Logger.i(_tag, "onPlayerStateChanged completed");
skipToNext();
}
}

bool _firstLoadPosition = false;
Future<void> _onPositionChanged(Duration position) async {
if(kIsWeb) return;
_setMediaControls();
Expand Down
1 change: 0 additions & 1 deletion mobile/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
ServerManager.changeTheme(MediaQuery.of(context).platformBrightness == Brightness.dark);
return MaterialApp(//WebViewApp(//)
home: !kIsWeb && Platform.isMacOS ? null : const WebViewApp(),
// theme: ThemeData(colorScheme: const ColorScheme.light()),
Expand Down
4 changes: 0 additions & 4 deletions mobile/lib/server/server_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,4 @@ class ServerManager {
}
});
}

static void changeTheme(bool isDark) {
_websocketHandler?.changeTheme(isDark);
}
}
12 changes: 0 additions & 12 deletions mobile/lib/server/websocket_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ class WebSocketHandler extends Handler with TrayListener, WindowListener impleme
static const String _tag = "MusicheWebSocketHandler";
final Set<WebSocket> webSockets = <WebSocket>{};
static const String _channelMediaOperate = "media-operate";
static bool _dark = false;
WebSocketHandler(super.audioPlay) {
audioPlay.onPlayerStateChanged.listen(_onPlayerStateChanged);
audioPlay.onPositionChanged.listen(_onPositionChanged);
Expand Down Expand Up @@ -136,11 +135,6 @@ class WebSocketHandler extends Handler with TrayListener, WindowListener impleme
trayManager.popUpContextMenu();
}

void changeTheme(bool isDark) {
_dark = isDark;
sendMessage('{"type": "dark", "data": $isDark}');
}

_onMediaOperate(dynamic action){
if(action is String) {
switch(action){
Expand Down Expand Up @@ -198,12 +192,6 @@ class WebSocketHandler extends Handler with TrayListener, WindowListener impleme
webSockets.add(webSocket);
webSocket.listen((dynamic data) {
Logger.i(_tag, 'WebSocket received: $data');
if(data is! String) return;
switch(data.trim()){
case "/dark":
sendMessage('{"type": "dark", "data": $_dark}');
break;
}
}, onDone: () {
webSockets.remove(webSocket);
});
Expand Down
66 changes: 66 additions & 0 deletions mobile/lib/utils/dark_mode_script.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
class DarkModeScript{
static String getScript(bool dark){
return """
class DarkModeMediaQueryList {
_matches;
_query = '(prefers-color-scheme: dark)';
_eventList = new Set();
onchange = null;
constructor(matches) {
this._matches = matches;
}
get media() {
return this._query;
}
get matches() {
return this._matches;
}
updateMatches(matches) {
if (this._matches === matches) return;
this._matches = matches;
this.dispatchEvent(new Event('change'));
}
addListener(callback) {
if (!callback) return;
this._eventList.add(callback);
}
removeListener(callback) {
if (!callback) return;
this._eventList.delete(callback);
}
addEventListener(type, listener, _options) {
if (type !== 'change') return;
if (typeof listener !== 'function') return;
this._eventList.add(listener);
}
removeEventListener(type, listener, _options) {
if (type !== 'change') return;
if (typeof listener !== 'function') return;
this._eventList.delete(listener);
}
dispatchEvent(event) {
const _event = {
...event,
matches: this._matches,
media: this._query
};
if (event.type === 'change') {
for (const callback of this._eventList) {
callback.call(this, _event);
}
}
this.onchange && this.onchange.call(this, _event);
return true;
}
}
window.originMatchMedia = window.matchMedia;
window.customDarkModeMediaQueryList = new DarkModeMediaQueryList(${dark ? 'true' : 'false'});
window.matchMedia = function (query) {
if (query === '(prefers-color-scheme: dark)') {
return customDarkModeMediaQueryList;
}
return originMatchMedia(query);
};
""";
}
}
13 changes: 11 additions & 2 deletions mobile/lib/webview.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'dart:async';
import 'dart:collection';
import 'dart:io';

import 'package:flutter/foundation.dart';
Expand All @@ -8,6 +9,7 @@ import 'package:musiche/log/logger.dart';
import 'package:musiche/server/file_handler.dart';
import 'package:musiche/server/server_manager.dart';
import 'package:musiche/utils/android_channel.dart';
import 'package:musiche/utils/dark_mode_script.dart';
import 'package:url_launcher/url_launcher_string.dart';


Expand All @@ -34,11 +36,16 @@ class _WebViewAppState extends State<WebViewApp> with WidgetsBindingObserver {
supportZoom: false,
scrollBarStyle: ScrollBarStyle.SCROLLBARS_OUTSIDE_OVERLAY
);
UnmodifiableListView<UserScript>? userScripts;
@override
void initState() {
super.initState();
if (!kIsWeb && Platform.isAndroid) {
InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);
bool dark = WidgetsBinding.instance.platformDispatcher.platformBrightness == Brightness.dark;
userScripts = UnmodifiableListView<UserScript>([
UserScript(source: DarkModeScript.getScript(dark), injectionTime: UserScriptInjectionTime.AT_DOCUMENT_END)
]);
}
WidgetsBinding.instance.addObserver(this);
}
Expand All @@ -52,7 +59,8 @@ class _WebViewAppState extends State<WebViewApp> with WidgetsBindingObserver {
@override
void didChangePlatformBrightness() {
super.didChangePlatformBrightness();
ServerManager.changeTheme(MediaQuery.of(context).platformBrightness == Brightness.dark);
bool dark = MediaQuery.of(context).platformBrightness == Brightness.dark;
webViewController?.evaluateJavascript(source: 'window.customDarkModeMediaQueryList && window.customDarkModeMediaQueryList.updateMatches(${!dark ? 'true' : 'false'})');
}

@override
Expand Down Expand Up @@ -160,7 +168,8 @@ class _WebViewAppState extends State<WebViewApp> with WidgetsBindingObserver {
onProgressChanged: _onProgressChanged,
onConsoleMessage: _onConsoleMessage,
onPermissionRequest: _onPermissionRequest,
onReceivedServerTrustAuthRequest: _onReceivedServerTrustAuthRequest
onReceivedServerTrustAuthRequest: _onReceivedServerTrustAuthRequest,
initialUserScripts: userScripts,
)
);
}
Expand Down
5 changes: 3 additions & 2 deletions web/src/components/Footer.vue
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ const play = usePlayStore();
@touchstart="play.playStatus.disableUpdateVolume = true"
@change="play.changeVolume"
vertical
height="70px"
height="150px"
:show-tooltip="false"
style="width: 30px" />
</el-popover>
Expand Down Expand Up @@ -446,7 +446,6 @@ const play = usePlayStore();
<style lang="less">
.music-footer-volume-popover {
transform: translateY(10px);
&::before,
&::after {
content: ' ';
Expand All @@ -460,10 +459,12 @@ const play = usePlayStore();
&::before {
background-color: var(--music-background);
border-radius: var(--el-popover-border-radius);
}
&::after {
background-color: var(--music-footer-background);
border-radius: var(--el-popover-border-radius);
}
.el-popper__arrow {
Expand Down
7 changes: 5 additions & 2 deletions web/src/components/Header.vue
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ function changeMusicType(type: MusicType) {
onUnmounted(unWatch);
</script>
<template>
<el-header class="music-header">
<el-header
class="music-header"
:style="setting.currentMusicTypeShow ? '' : '--header-height:40px'">
<div class="music-header-content">
<el-button
v-if="canBack"
Expand Down Expand Up @@ -81,7 +83,8 @@ onUnmounted(unWatch);
</template>
<style lang="less" scoped>
.music-header {
height: calc(80px + var(--sat));
--header-height: 80px;
height: calc(var(--header-height) + var(--sat));
transition: padding 0.5s;
--el-header-height: 80px;
--el-header-padding: 0;
Expand Down
1 change: 1 addition & 0 deletions web/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import 'default-passive-events';

import 'element-plus/theme-chalk/dark/css-vars.css';
import 'element-plus/theme-chalk/el-message-box.css';
Expand Down
22 changes: 5 additions & 17 deletions web/src/stores/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,6 @@ export class MusicConnection {
constructor() {
this.init();
this.registerShortcut();
watch(() => this.setting.autoAppTheme, this.autoAppThemeChange.bind(this));
}

autoAppThemeChange() {
if (this.setting.autoAppTheme) {
this.sendWsMessage('/dark');
}
}

async init() {
Expand All @@ -55,16 +48,15 @@ export class MusicConnection {
this.config.storage && storage.setRemoteMode(true);
this.config.lyric && LyricManager.setRemoteMode(true);
this.config.file && local.setRemoteMode(true);
await this.play.initValue(this.config);
await this.setting.initValue(this.config);
const storages = await storage.getAll();
await this.play.initValue(this.config, storages);
await this.setting.initValue(this.config, storages);
await import('../style/main.css');
if (!isMobile) import('default-passive-events');
document.documentElement.style.opacity = '1';
console.log('musiche loaded');
this.webSocketClient = http.wsClient(
this.wsMessage.bind(this),
this.wsClose.bind(this),
this.autoAppThemeChange.bind(this)
this.wsClose.bind(this)
);
if (this.setting.pageValue.savePlayProgress) {
try {
Expand Down Expand Up @@ -206,18 +198,14 @@ export class MusicConnection {
this.play.addMyLove([this.play.music], exist);
}
break;
case 'dark':
this.setting.updateDarkMode(Boolean(result.data));
break;
}
} catch {}
}
wsClose() {
setTimeout(() => {
this.webSocketClient = http.wsClient(
this.wsMessage.bind(this),
this.wsClose.bind(this),
this.autoAppThemeChange.bind(this)
this.wsClose.bind(this)
);
}, 1000);
}
Expand Down
Loading

0 comments on commit 504df01

Please sign in to comment.