-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.tsx
323 lines (271 loc) · 8.31 KB
/
App.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
*/
import React, { useState } from 'react';
import type { PropsWithChildren } from 'react';
import {
Alert,
Button,
Linking,
Modal,
NativeModules,
PermissionsAndroid,
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
ToastAndroid,
useColorScheme,
View,
} from 'react-native';
import * as Progress from 'react-native-progress';
import {
ExternalStorageDirectoryPath,
DocumentDirectoryPath,
downloadFile,
mkdir
} from 'react-native-fs';
import { unzip, unzipAssets, subscribe } from 'react-native-zip-archive'
let DOMParser = require('react-native-html-parser').DOMParser;
class ParsedUrl {
rawString: string;
protocol: string;
domain: string;
path: string;
constructor(rawString: string) {
this.rawString = rawString;
let endOfProtocol = this.rawString.indexOf('://');
if (endOfProtocol < 0) {
this.protocol = "";
this.domain = "";
this.path = "";
return;
}
this.protocol = this.rawString.substring(0, endOfProtocol);
let endOfDomain = this.rawString.indexOf('/', endOfProtocol + 3);
if (endOfDomain < 0) {
this.domain = this.rawString.substring(endOfProtocol + 3);
this.path = "";
return;
}
this.domain = this.rawString.substring(endOfProtocol + 3, endOfDomain);
this.path = this.rawString.substring(endOfDomain + 1);
}
};
async function fetchJSON(url: string) {
let response = await fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
},
});
let json = await response.json();
return json;
}
type BeatSaverMapMetaData = {
downloadUrl: string;
}
function parseBeatSaverMapMetaData(data: any) {
let versions = data['versions'];
let selectedVersion = versions[0];
let downloadUrl = selectedVersion['downloadURL'];
let metaData: BeatSaverMapMetaData = { downloadUrl: downloadUrl };
return metaData;
}
async function requestStoragePermission() {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: '存储空间权限',
message:
'Music Bridge 需要将曲谱写入到光之乐团的自定义歌曲文件夹中。',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
console.log(granted);
return granted == PermissionsAndroid.RESULTS.GRANTED;
};
async function importBeatSaverMapToLightBand(mapId: string, folder: string = 'MusicBridge') {
console.debug(`beatsaver map downloading: ${mapId}`);
let json = await fetchJSON(`https://beatsaver.com/api/maps/id/${mapId}`);
let url = parseBeatSaverMapMetaData(json).downloadUrl;
let downloadedMapsPath = `${DocumentDirectoryPath}/downloaded/maps`;
await mkdir(downloadedMapsPath);
let path = `${downloadedMapsPath}/${mapId}.zip`;
let downloadResult = await downloadFile({ fromUrl: url, toFile: path }).promise;
if (downloadResult.statusCode != 200)
throw new Error("Failed to download");
let customMusicBasePath = `${ExternalStorageDirectoryPath}/Android/data/com.StarRiverVR.LightBand/files/CustomMusic`;
let mapPath = `${customMusicBasePath}/${folder}/${mapId}`;
await mkdir(mapPath);
await unzip(path, mapPath);
console.debug(`beatsaver map downloaded: ${mapId}`);
}
type BeatSaverPlaylistMetaData = {
title: string,
maps: string[]
}
async function parseBeatSaverPlaylistMetaData(json: any): Promise<BeatSaverPlaylistMetaData> {
let title = json['playlistTitle'];
let songsInfo = json['songs'];
var maps: string[] = [];
for (let song of songsInfo) {
maps.push(song['key'])
}
return {
title: title,
maps: maps
}
}
async function importBeatSaverPlaylistToLightBand(url: string, progressCallback: ((arg0: number) => any) | undefined = undefined) {
console.debug(`beatsaver playlist downloading: ${url}`);
let json = await fetchJSON(url);
let meta = await parseBeatSaverPlaylistMetaData(json);
var countDone = 0;
for (let map of meta.maps) {
await importBeatSaverMapToLightBand(map, meta.title);
countDone += 1;
if (progressCallback) progressCallback(countDone / meta.maps.length)
}
console.debug(`beatsaver playlist downloaded: ${url}`);
}
type ImportPlaylistWindowProps = {
progress: number;
};
function ImportPlaylistWindow(props: ImportPlaylistWindowProps): JSX.Element {
return (
<SafeAreaView>
<Text style={styles.title}>Import Playlist</Text>
<Progress.Bar
width={null}
height={12}
borderRadius={8}
indeterminate={false}
progress={props.progress}
/>
</SafeAreaView>
)
}
function ImportMapWindow(): JSX.Element {
return (
<SafeAreaView>
<Text style={styles.title}>Import Map</Text>
<Progress.Circle indeterminate={true} size={120} thickness={9} />
</SafeAreaView>
)
}
function HintWindow(): JSX.Element {
return (
<SafeAreaView>
<Text style={styles.title}>Music Bridge</Text>
<Text style={styles.content}>点击 BeatSavers 网站上的 One Click 按钮来导入歌曲或播放列表</Text>
<View style={styles.button}>
<Button title='打开 BeatSaver' onPress={() => { Linking.openURL('https://beatsaver.com/') }} />
</View>
<View style={styles.button}>
<Button title='打开浏览器' onPress={() => {
NativeModules.ReactNativeHelper.navigateToBrowser();
}} />
</View>
</SafeAreaView>
);
}
async function forwardInitialUrl(syncState: AppCriticalState, setState: (arg: AppState) => any) {
let url = await Linking.getInitialURL();
if (url == null) return;
onLinking({ url: url }, syncState, setState);
}
function onLinking(event: { url: string }, syncState: AppCriticalState, setState: (arg: AppState) => any) {
console.debug(`onLinking: url=${event.url}`)
if (syncState.status != ApplicationStatus.Free) {
console.debug(`app is busy: ${syncState.status}`);
ToastAndroid.show("app is busy", 0.5);
return;
}
let url = new ParsedUrl(event.url);
let newStatus = url.protocol == 'beatsaver' ? ApplicationStatus.DownloadingBeatSaverMap : ApplicationStatus.DownloadingBeatSaverPlaylist;
syncState.status = newStatus;
async function download() {
setState({ status: newStatus, progress: 0 })
try {
await requestStoragePermission();
if (url.protocol == 'beatsaver') {
await importBeatSaverMapToLightBand(url.domain);
} else if (url.protocol == 'bsplaylist') {
await importBeatSaverPlaylistToLightBand(url.path, (progress) => {
setState({ status: newStatus, progress: progress })
});
} else {
console.error(`invalid url: ${url}`)
}
ToastAndroid.show('下载完成', 0.5);
} catch (error) {
console.error('error: ', error);
Alert.alert('错误', '没能成功下载')
console.log('alert done')
} finally {
console.debug('download finalized');
syncState.status = ApplicationStatus.Free;
setState({ status: ApplicationStatus.Free, progress: 0 });
}
}
download();
}
enum ApplicationStatus {
Free,
DownloadingBeatSaverPlaylist,
DownloadingBeatSaverMap,
}
type AppCriticalState = {
status: ApplicationStatus
}
type AppState = {
status: ApplicationStatus,
progress: number
}
var applicationIsInitialized: boolean = false;
function App(): JSX.Element {
let [state, setState] = useState({
status: ApplicationStatus.Free,
progress: 0
})
let syncState: AppCriticalState = {
status: state.status
}
if (!applicationIsInitialized) {
applicationIsInitialized = true;
Linking.addEventListener('url', (event) => onLinking(event, syncState, setState))
forwardInitialUrl(syncState, setState);
} else {
console.debug('skip initialization')
}
return (
<SafeAreaView style={styles.rootWindow}>
{state.status == ApplicationStatus.Free && <HintWindow />}
{state.status == ApplicationStatus.DownloadingBeatSaverPlaylist && <ImportPlaylistWindow progress={state.progress} />}
{state.status == ApplicationStatus.DownloadingBeatSaverMap && <ImportMapWindow />}
</SafeAreaView>
);
}
const styles = StyleSheet.create({
rootWindow: {
margin: 24
},
title: {
fontSize: 24,
fontWeight: '600',
},
content: {
fontSize: 16
},
button: {
margin: 16
}
});
export default App;