Skip to content

Commit

Permalink
Fix flutter build, service worker
Browse files Browse the repository at this point in the history
  • Loading branch information
HeHang0 committed Jan 9, 2024
1 parent ac44d17 commit 5b15cf0
Show file tree
Hide file tree
Showing 20 changed files with 232 additions and 121 deletions.
15 changes: 15 additions & 0 deletions .github/workflows/web.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,26 @@ jobs:
- name: Setup MSBuild
uses: microsoft/setup-msbuild@v1

- name: Setup JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
cache: gradle

- name: Setup Flutter
uses: subosito/flutter-action@v2

- name: Build
run: |
powershell
Remove-Item windows\logo.ico -Force -ErrorAction SilentlyContinue
Remove-Item web\public\logo.png -Force -ErrorAction SilentlyContinue
Remove-Item web\public\logo-circle.png -Force -ErrorAction SilentlyContinue
Remove-Item mobile\assets -Force -Recurse -ErrorAction SilentlyContinue
copy resources\logo.ico windows\logo.ico
copy resources\logo.png web\public\logo.png
copy resources\logo-circle.png web\public\logo-circle.png
cd web
yarn
yarn build:zip
Expand All @@ -45,6 +59,7 @@ jobs:
msbuild Musiche.sln -t:"Restore;Build" /p:Configuration=Release /p:Platform="Any CPU"
msbuild Musiche.sln -t:"Restore;Build;Publish" /p:Configuration=Release /p:Platform="Any CPU" /p:PublishProfile="Properties\PublishProfiles\net6.0.pubxml" /p:TargetFramework=net6.0-windows
cd ..\mobile
Copy-Item ..\web\dist assets -Force -Recurse
flutter build apk --release
cd ..
copy windows\bin\Release\net472\Musiche.exe web\dist\Musiche.exe -ErrorAction SilentlyContinue
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,11 @@
import android.content.ServiceConnection;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.util.Size;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;

Expand Down Expand Up @@ -116,6 +111,7 @@ private void onMethodCall(MethodCall call, MethodChannel.Result result){

private void updateMetaData(boolean playing, Integer position){
if(position == null) return;
if(!playing && isServiceNotRunning(mBinding.getApplicationContext(), LyricService.class)) return;
Intent intent = new Intent(mBinding.getApplicationContext(), NotificationService.class);
intent.putExtra("playing", playing);
intent.putExtra("position", position.intValue());
Expand All @@ -126,6 +122,7 @@ private void updateMetaData(boolean playing, Integer position){
private void updateMetaData(
String title, String artist, String album, String artwork,
boolean playing, boolean lover, Integer position, Integer duration) {
if(!playing && isServiceNotRunning(mBinding.getApplicationContext(), LyricService.class)) return;
Intent intent = new Intent(mBinding.getApplicationContext(), NotificationService.class);
intent.putExtra("playing", playing);
intent.putExtra("lover", lover);
Expand Down Expand Up @@ -233,23 +230,23 @@ private void updateLyricOptions(boolean show, String title, Integer fontSize, bo
}

private void updateLyricLine(String line){
if(!isServiceRunning(mBinding.getApplicationContext(), LyricService.class)) return;
if(isServiceNotRunning(mBinding.getApplicationContext(), LyricService.class)) return;
Intent intent = new Intent(mBinding.getApplicationContext(), LyricService.class);
intent.putExtra("action", "line");
intent.putExtra("line", line);
mBinding.getApplicationContext().startService(intent);
}

public static boolean isServiceRunning(Context context, Class<?> serviceClass) {
public static boolean isServiceNotRunning(Context context, Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (manager != null) {
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
return false;
}
}
}
return false;
return true;
}

@Override
Expand Down
3 changes: 2 additions & 1 deletion web/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ env.d.ts
PingFang-SC-Regular.otf
tsconfig.tsbuildinfo
web.zip
/public/version
/public/version
stats.html
2 changes: 1 addition & 1 deletion web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@
"jszip": "^3.10.1",
"less": "*",
"npm-run-all": "*",
"rollup-plugin-visualizer": "^5.12.0",
"typescript": "*",
"unplugin-auto-import": "*",
"unplugin-vue-components": "*",
"vite": "*",
"vite-plugin-pwa": "^0.16.7",
"vue-tsc": "*"
}
}
67 changes: 67 additions & 0 deletions web/public/worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
const CACHE_NAME = 'musiche-cache';

const cacheFirst = [
/(.*?)\.(html|js|json|css|png|jpg|jpeg|woff2|webm|webp)/i,
/\/proxy\?url=[\S]+/i
];
const routerPattern =
/\/(recommend|yours|ranking|search|playlist|album|lover|recent|local|created|setting|version$)/i;

self.addEventListener('install', event => {
event.waitUntil(caches.open(CACHE_NAME));
});

self.addEventListener('activate', event => {
event.waitUntil(self.skipWaiting());
});

async function cacheThenNetwork(request) {
const requestUrl = new URL(request.url).toString();
let willCache = false;
if (!requestUrl.search) {
}
for (let i = 0; i < cacheFirst.length; i++) {
if (cacheFirst[i].test(requestUrl)) {
willCache = true;
break;
}
}
const cache = await caches.open(CACHE_NAME);
const cachedResponse = await cache.match(request);
if (cachedResponse) {
return cachedResponse;
}
const response = await fetch(request);
const cacheRouter =
response.headers.get('content-type')?.includes('text/html') &&
routerPattern.test(requestUrl);
if (
requestUrl.startsWith('http') &&
(cacheRouter || (willCache && response.ok))
) {
try {
const cache = await caches.open(CACHE_NAME);
cache.put(request, response.clone());
} catch (error) {
console.error('Failed to cache the response:', error);
}
}
return response;
}

self.addEventListener('fetch', event => {
event.respondWith(cacheThenNetwork(event.request));
});

async function clearAllCache() {
const cache = await caches.open(CACHE_NAME);
const keys = await cache.keys();
keys.forEach(key => {
cache.delete(key);
});
self.skipWaiting();
}

self.addEventListener('update', event => {
event.waitUntil(clearAllCache());
});
28 changes: 27 additions & 1 deletion web/scripts/fix.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import path from 'path';
import fs from 'fs';
import { createHash } from 'crypto';
import { Plugin } from 'vite';

function fixJSMediaTagsError() {
Expand Down Expand Up @@ -30,7 +31,31 @@ export const FixJSMediaTagsErrorPlugin = function () {
};
};

export function getHash(text: Buffer | string, length = 8): string {
const h = createHash('sha256')
.update(text)
.digest('hex')
.substring(0, length);
if (length <= 64) return h;
return h.padEnd(length, '_');
}

function fixWorkerJS(): string {
const distPath = path.resolve('dist');
const workerPath = path.resolve(distPath, 'worker.js');
if (fs.existsSync(workerPath)) {
const workerJS = fs.readFileSync(workerPath, { encoding: 'utf8' });
const hash = getHash(workerJS);
const workerName = `worker-${hash}.js`;
const workerNamePath = path.resolve(distPath, workerName);
fs.renameSync(workerPath, workerNamePath);
return `window.serviceWorkerJS = "${workerName}";`;
}
return '';
}

function transformIndexHtmlHandler(html: string) {
const workerJS = fixWorkerJS();
let indexJS = '';
const matchIndexJS =
/[\s]*<script.+?src="\.*([\S]+index[\S]+\.js)"[^>]*>[\s]*<\/script>.*[\n]*/;
Expand All @@ -45,7 +70,7 @@ function transformIndexHtmlHandler(html: string) {
}
let indexCSS = '';
const matchIndexCSS =
/[\s]*<link[\s]+rel="stylesheet"[\s]+href="\.*([\S]+index[\S]+\.css)"[^>]*>.*[\n]*/;
/[\s]*<link[\s]+rel="stylesheet"[\s]*[\S]*[\s]*href="\.*([\S]+index[\S]+\.css)"[^>]*>.*[\n]*/;
if (matchIndexCSS.test(html)) {
indexCSS = `
const indexStyle = document.createElement('link');
Expand All @@ -64,6 +89,7 @@ function transformIndexHtmlHandler(html: string) {
if(iconLink) iconLink.href = routerPrefix + '/logo-circle.png';
const manifestLink = document.querySelector('link[rel="manifest"]');
if(manifestLink) manifestLink.href = location.origin + routerPrefix + '/manifest.json';
${workerJS}
${indexJS}${indexCSS}
document.getElementById('musiche-script-fix').remove();
</script>
Expand Down
30 changes: 14 additions & 16 deletions web/src/components/player/ColorfulMode.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<script lang="ts" setup>
import { onMounted, onUnmounted, ref, watch } from 'vue';
import { onMounted, onUnmounted, ref } from 'vue';
import Lyric from './Lyric.vue';
import Disc2Image from '../../assets/images/disc3.png';
import SmokeVideo from '../../assets/videos/smoke.webm';
Expand All @@ -15,7 +15,6 @@ const props = withDefaults(defineProps<Props>(), {
tools: true
});
// const colors = ['#ab3c46', '#b78a62', '#b36159', '#727272'];
let colorBase = 0;
const play = usePlayStore();
const setting = useSettingStore();
Expand Down Expand Up @@ -61,12 +60,6 @@ function setColor(
) {
themeColor.value = `rgb(${rBase + r}, ${gBase + g}, ${bBase + b})`;
}
watch(
() => play.playStatus.playing,
value => {
console.log(value);
}
);
let colorInterval: any = null;
onMounted(() => {
setTimeout(() => {
Expand Down Expand Up @@ -161,11 +154,12 @@ onUnmounted(() => clearInterval(colorInterval));
position: fixed;
left: 50%;
top: 0;
height: 80px;
line-height: 80px;
height: calc(var(--sat) + 80px);
line-height: calc(var(--sat) + 80px);
width: calc(100% - 200px);
text-align: center;
transform: translateX(-50%);
transition: width 0.5s;
opacity: 0;
& > span {
font-size: 18px;
Expand All @@ -185,6 +179,7 @@ onUnmounted(() => clearInterval(colorInterval));
width: 50%;
aspect-ratio: 1 / 1;
max-height: 80vh;
max-width: 80vh;
position: absolute;
left: 25%;
top: 50%;
Expand All @@ -208,18 +203,19 @@ onUnmounted(() => clearInterval(colorInterval));
left: 50%;
width: auto;
height: 50%;
max-height: 100vw;
top: 25%;
}
}
&-lyric {
width: 45%;
width: calc(50% - 20px);
height: 100%;
position: absolute;
right: 0;
top: 0;
color: white;
@media (orientation: portrait) {
height: 45%;
height: calc(50% - 20px);
width: 100%;
bottom: 0;
top: unset;
Expand Down Expand Up @@ -258,14 +254,16 @@ onUnmounted(() => clearInterval(colorInterval));
mask: radial-gradient(
circle at 50% 50%,
rgba(0, 0, 0, 1) 50%,
rgba(0, 0, 0, 0.1) 60%,
rgba(0, 0, 0, 0) 60%
rgba(0, 0, 0, 0.2) 60%,
rgba(0, 0, 0, 0.1) 70%,
rgba(0, 0, 0, 0) 100%
);
-webkit-mask: radial-gradient(
circle at 50% 50%,
rgba(0, 0, 0, 1) 50%,
rgba(0, 0, 0, 0.1) 60%,
rgba(0, 0, 0, 0) 60%
rgba(0, 0, 0, 0.2) 60%,
rgba(0, 0, 0, 0.1) 70%,
rgba(0, 0, 0, 0) 100%
);
}
}
Expand Down
14 changes: 11 additions & 3 deletions web/src/components/player/PolarBearMode.vue
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import PlayingVideo from '../../assets/videos/playing.webm';
import { LogoImage } from '../../utils/logo';
import { usePlayStore } from '../../stores/play';
import { Ref, onMounted, onUnmounted, ref, watch } from 'vue';
import Snowflakes from 'magic-snowflakes';
import Lyric from './Lyric.vue';
import Snowflakes from 'magic-snowflakes';
interface Props {
tools?: boolean;
Expand All @@ -18,6 +18,13 @@ const props = withDefaults(defineProps<Props>(), {
tools: true
});
let getSnowflakes = async () => {
const snowflakes = await import('magic-snowflakes');
const result = snowflakes.default;
getSnowflakes = () => Promise.resolve(result);
return result;
};
const play = usePlayStore();
const videoSrc = ref(play.playStatus.playing ? PlayingVideo : PausedVideo);
const videoLoop = ref(true);
Expand Down Expand Up @@ -52,8 +59,9 @@ watch(
}
);
let snowflakes: Snowflakes | null = null;
onMounted(() => {
snowflakes = new Snowflakes({
onMounted(async () => {
const Snow = await getSnowflakes();
snowflakes = new Snow({
color: '#ffffffba',
container: snowContainer.value,
autoResize: true,
Expand Down
Loading

0 comments on commit 5b15cf0

Please sign in to comment.