Skip to content

Commit

Permalink
Replacing injection with api
Browse files Browse the repository at this point in the history
  • Loading branch information
HeHang0 committed Mar 19, 2024
1 parent 43ceb82 commit 06d8e14
Show file tree
Hide file tree
Showing 32 changed files with 684 additions and 356 deletions.
46 changes: 45 additions & 1 deletion mobile/lib/server/http_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import 'package:musiche/server/proxy_request_data.dart';
import 'package:musiche/server/proxy_response_data.dart';
import 'package:musiche/utils/android_channel.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../audio/media_metadata.dart';
import '../utils/os_version.dart';
Expand All @@ -23,7 +24,8 @@ import 'handler.dart';
class HttpHandler extends Handler implements IHandler {
static const String _tag = 'MusicheHttpHandler';
Map<String, RouterCall> routers = <String, RouterCall>{};
HttpHandler(super.audioPlay){
final SharedPreferences? sharedPreferences;
HttpHandler(super.audioPlay, this.sharedPreferences){
routers.addEntries([
MapEntry("*", _handleIndex),
MapEntry("config", _handleConfig),
Expand All @@ -37,6 +39,8 @@ class HttpHandler extends Handler implements IHandler {
MapEntry("progress", _setProgress),
MapEntry("volume", _setVolume),
MapEntry("status", _getStatus),
MapEntry("storages", _getAllStorages),
MapEntry("storage", _storage),
MapEntry("theme", _setTheme),
MapEntry("window", _voidRouter),
MapEntry("hotkey", _voidRouter),
Expand Down Expand Up @@ -83,6 +87,14 @@ class HttpHandler extends Handler implements IHandler {

Future<void> _handleConfig(HttpRequest request) async {
Map<String, dynamic> result = <String, dynamic>{};
result["remote"] = true;
result["storage"] = true;
result["file"] = true;
result["list"] = false;
result["client"] = false;
result["lyric"] = Platform.isAndroid;
result["shortcut"] = false;
result["gpu"] = false;
request.response.statusCode = HttpStatus.ok;
request.response.headers.contentType = ContentType.json;
request.response.write(jsonEncode(result));
Expand Down Expand Up @@ -144,6 +156,38 @@ class HttpHandler extends Handler implements IHandler {
return "text/html";
}

Future<void> _getAllStorages(HttpRequest request) async {
Map<String, dynamic> result = <String, dynamic>{};
sharedPreferences?.getKeys().forEach((key) {
result[key] = sharedPreferences!.getString(key);
});
request.response.statusCode = HttpStatus.ok;
request.response.write(jsonEncode(result));
}

Future<void> _storage(HttpRequest request) async {
String key = (request.uri.queryParameters["key"] ?? "").trim();
if(key.isEmpty) {
request.response.statusCode = HttpStatus.ok;
request.response.write("");
return;
}
String result = "";
switch(request.method.toUpperCase()){
case "GET":
result = sharedPreferences?.getString(key) ?? "";
break;
case "POST":
sharedPreferences?.setString(key, await _readBody(request));
break;
case "DELETE":
sharedPreferences?.remove(key);
break;
}
request.response.statusCode = HttpStatus.ok;
request.response.write(result.trim());
}

Future<void> _getVersion(HttpRequest request) async {
String result = await rootBundle.loadString("assets/version");
request.response.statusCode = HttpStatus.ok;
Expand Down
9 changes: 8 additions & 1 deletion mobile/lib/server/server_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:musiche/log/logger.dart';
import 'package:musiche/server/websocket_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../audio/audio_play.dart';
import '../utils/network.dart';
Expand All @@ -20,7 +21,13 @@ class ServerManager {
static Future<void> startServer() async {
if(_server != null) return;
AudioPlay audioPlay = AudioPlay();
HttpHandler httpHandler = HttpHandler(audioPlay);
SharedPreferences? sharedPreferences;
try{
sharedPreferences = await SharedPreferences.getInstance();
}catch(e){
Logger.e(_tag, "init shared preferences error", error: e);
}
HttpHandler httpHandler = HttpHandler(audioPlay, sharedPreferences);
_websocketHandler = WebSocketHandler(audioPlay);
_port = kDebugMode ? 54621 : await Network.findAvailablePort();
InternetAddress address = kDebugMode ? InternetAddress.anyIPv4 : InternetAddress.loopbackIPv4;
Expand Down
8 changes: 3 additions & 5 deletions mobile/lib/webview_macos.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'package:musiche/log/logger.dart';
import 'package:musiche/server/server_manager.dart';
import 'package:webview_all/webview_all.dart';


class WebViewMacOSApp extends StatefulWidget {
Expand All @@ -17,9 +16,8 @@ class _WebViewMacOSAppState extends State<WebViewMacOSApp> with WidgetsBindingOb
static const String _tag = "MusicWebViewMacOS";
final GlobalKey webViewKey = GlobalKey();
static final String _url = "http://127.0.0.1:${ServerManager.port}/index.html";//kDebugMode ? "http://192.168.3.2:5173" :
double _opacity = 1;
double _opacity = 0;
Timer? _delayShow;
// late Webview webViewMacOS;
@override
void initState() {
super.initState();
Expand Down Expand Up @@ -59,9 +57,9 @@ class _WebViewMacOSAppState extends State<WebViewMacOSApp> with WidgetsBindingOb

@override
Widget build(BuildContext context) {
return Opacity(
return const Opacity(
opacity: 1,
child: Webview(url: _url),
// child: Webview(url: _url),
);
}
}
4 changes: 0 additions & 4 deletions mobile/linux/flutter/generated_plugin_registrant.cc
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,9 @@
#include "generated_plugin_registrant.h"

#include <url_launcher_linux/url_launcher_plugin.h>
#include <webf/webf_plugin.h>

void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin");
url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar);
g_autoptr(FlPluginRegistrar) webf_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "WebfPlugin");
webf_plugin_register_with_registrar(webf_registrar);
}
1 change: 0 additions & 1 deletion mobile/linux/flutter/generated_plugins.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

list(APPEND FLUTTER_PLUGIN_LIST
url_launcher_linux
webf
)

list(APPEND FLUTTER_FFI_PLUGIN_LIST
Expand Down
2 changes: 0 additions & 2 deletions mobile/macos/Flutter/GeneratedPluginRegistrant.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import just_audio
import path_provider_foundation
import shared_preferences_foundation
import url_launcher_macos
import webf

func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
AudioSessionPlugin.register(with: registry.registrar(forPlugin: "AudioSessionPlugin"))
Expand All @@ -22,5 +21,4 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin"))
WebFPlugin.register(with: registry.registrar(forPlugin: "WebFPlugin"))
}
4 changes: 2 additions & 2 deletions mobile/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,16 @@ dependencies:
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
webview_all: ^0.4.1
device_info_plus: ^9.1.1
file_picker: ^6.1.1
flutter_inappwebview: ^6.0.0
id3tag: ^0.2.0
just_audio: ^0.9.36
logger: ^2.0.2+1
path_provider: ^2.1.1
permission_handler: ^11.1.0
shared_preferences: ^2.2.2
url_launcher: ^6.2.2
device_info_plus: ^9.1.1

dev_dependencies:
flutter_test:
Expand Down
14 changes: 5 additions & 9 deletions web/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,12 @@ import Footer from './components/Footer.vue';
import CurrentList from './components/CurrentList.vue';
import PlayDetail from './components/PlayDetail.vue';
import WindowHelper from './components/WindowHelper.vue';
import { webView2Services } from './utils/utils';
import { MusicConnection } from './stores/connection';
import { usePlayStore } from './stores/play';
import { useSettingStore } from './stores/setting';
import { LogoImage } from './utils/logo';
import { fixPwaForIOS, isWindows } from './utils/utils';
import { registerServiceWorker } from './sw/register';
if (!webView2Services.enabled) registerServiceWorker();
import { fixPwaForIOS } from './utils/utils';
import { webView2Services } from './utils/files';
const play = usePlayStore();
const setting = useSettingStore();
document.addEventListener(
Expand All @@ -32,12 +29,11 @@ document.addEventListener(
},
true
);
new MusicConnection(webView2Services.enabled && isWindows);
let rootClass = webView2Services.enabled ? 'webview-host' : '';
const connection = new MusicConnection();
let rootClass = connection.config.remote ? 'webview-host' : '';
onMounted(() => {
fixPwaForIOS();
console.log('musiche loaded');
document.addEventListener('load', () => {});
});
</script>

Expand Down Expand Up @@ -66,7 +62,7 @@ onMounted(() => {
</el-container>
<Footer v-show="play.musicList.length > 0" />
<PlayDetail />
<WindowHelper v-if="webView2Services.enabled" />
<WindowHelper v-if="webView2Services.specialService" />
</el-container>
</template>

Expand Down
5 changes: 3 additions & 2 deletions web/src/components/Header.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { Search } from '@element-plus/icons-vue';
import { useSettingStore } from '../stores/setting';
import { MusicType } from '../utils/type';
import { isWindows, webView2Services } from '../utils/utils';
import { isWindows } from '../utils/utils';
import { webView2Services } from '../utils/files';
import MusicTypeEle from './MusicType.vue';
import WindowControls from './WindowControls.vue';
Expand Down Expand Up @@ -70,7 +71,7 @@ onUnmounted(unWatch);
</div>
<div
class="music-header-operate"
v-if="isWindows && webView2Services.enabled">
v-if="isWindows && webView2Services.specialService">
<!-- <span class="music-icon" @click="push('/setting')" title="设置">
</span> -->
Expand Down
6 changes: 3 additions & 3 deletions web/src/components/MusicList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import CloudMusicImage from '../assets/images/cloud-music.webp';
import QQMusicImage from '../assets/images/qq-music.png';
import MiguMusicImage from '../assets/images/migu-music.webp';
import { useSettingStore } from '../stores/setting';
import { isMobile, messageOption, webView2Services } from '../utils/utils';
import { isMobile, messageOption } from '../utils/utils';
import { ElMessage } from 'element-plus';
interface Props {
list: Music[];
Expand Down Expand Up @@ -70,7 +70,7 @@ async function downloadMusic(music?: Music) {
if (!music && !selectedMusic) return;
music = music || selectedMusic!;
const url = await api.downloadUrl(music);
if (url && (!webView2Services.enabled || isMobile)) {
if (url && !setting.config.remote) {
const downloadLink = document.createElement('a');
downloadLink.href = url;
downloadLink.download = `${music.name} - ${music.singer}.mp3`;
Expand All @@ -79,7 +79,7 @@ async function downloadMusic(music?: Music) {
downloadLink.click();
downloadLink.remove();
} else {
ElMessage(messageOption('当前音乐无法下载'));
ElMessage(messageOption('暂不支持'));
}
}
Expand Down
5 changes: 3 additions & 2 deletions web/src/components/PlayDetail.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { useThrottleFn } from '@vueuse/core';
import { usePlayStore } from '../stores/play';
import { ThemeColorManager } from '../utils/color';
import { isMobile, isWindows, webView2Services } from '../utils/utils';
import { isMobile } from '../utils/utils';
import { webView2Services } from '../utils/files';
import Footer from './Footer.vue';
import WindowControls from './WindowControls.vue';
Expand Down Expand Up @@ -194,7 +195,7 @@ watch(() => play.playDetailShow, setTheme);
</el-dropdown-menu>
</template>
</el-dropdown>
<WindowControls v-if="isWindows && webView2Services.enabled" />
<WindowControls v-if="webView2Services.specialService" />
</div>
</div>
<div
Expand Down
8 changes: 8 additions & 0 deletions web/src/components/SideMenu.vue
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,14 @@ function toHome() {
<span>{{ item.name }}</span>
</el-menu-item>
</template>
<el-menu-item
index="/local"
id="/local"
v-if="setting.config.file || Boolean((window as any).showDirectoryPicker)"
:class="route.meta.key == 'local' ? 'is-active' : ''">
<span class="music-icon">乐</span>
<span>本地音乐</span>
</el-menu-item>
<el-divider></el-divider>
<el-sub-menu index="favorite">
<template #title>
Expand Down
7 changes: 5 additions & 2 deletions web/src/components/WindowHelper.vue
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
<script lang="ts" setup>
import { isWindows, webView2Services } from '../utils/utils';
import { webView2Services } from '../utils/files';
import { isWindows } from '../utils/utils';
function startResize(direction: number, e?: MouseEvent) {
if (e && e.button == 0 && e.buttons == 1)
webView2Services.specialService?.ResizeWindow(direction);
}
</script>
<template>
<div v-if="isWindows && webView2Services.enabled" class="music-window-helper">
<div
v-if="isWindows && webView2Services.specialService"
class="music-window-helper">
<div
class="music-window-helper-drag"
style="-webkit-app-region: drag"></div>
Expand Down
4 changes: 1 addition & 3 deletions web/src/router/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
type RouteRecordRaw
} from 'vue-router';
import Recommend from '../views/recommend.vue';
import { webView2Services } from '../utils/utils';

const routers: RouteRecordRaw[] = [
{
Expand Down Expand Up @@ -78,8 +77,7 @@ const routers: RouteRecordRaw[] = [
meta: {
key: 'local',
icon: '乐',
show:
webView2Services.enabled || Boolean((window as any).showDirectoryPicker)
show: false
},
component: () => import(`../views/local.vue`)
},
Expand Down
Loading

0 comments on commit 06d8e14

Please sign in to comment.