diff --git a/Cargo.lock b/Cargo.lock index f2d0432..a5a5916 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2226,7 +2226,7 @@ dependencies = [ [[package]] name = "mulberry" -version = "2.0.6" +version = "2.0.4" dependencies = [ "base64 0.22.1", "chrono", diff --git a/Cargo.toml b/Cargo.toml index 5bdd222..b136d7a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mulberry" -version = "2.0.6" +version = "2.0.4" edition = "2021" description = "A Material You music player for Linux" license = "MIT" diff --git a/README.md b/README.md index 0542b60..743f11d 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Your library, tabbed playlists, synced lyrics and a colour-matched "now playing" panel, in one small native app. -[Download](https://astar76.com/git/astar76/Mulberry/releases/latest) · +[Download](https://archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry/releases/latest) · [Build from source](#build-from-source) · [Shortcuts](#keyboard-shortcuts) @@ -67,14 +67,14 @@ focus mode (F11), compact and hidden now-playing layouts, a floating bass-reacti ### From a release -Downloads are on the [Releases page](https://astar76.com/git/astar76/Mulberry/releases); check them against `SHA256SUMS-`. The Linux builds +Downloads are on the [Releases page](https://archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry/releases); check them against `SHA256SUMS-`. The Linux builds are made on Arch Linux and need a recent glibc (the version is named in the packages and checked by the installer), so they run on Arch and other up-to-date distributions; on older ones, build from source. - **Arch Linux:** `sudo pacman -U Mulberry--arch-x86_64.pkg.tar.zst` (package `mulberry-bin`; remove it with `sudo pacman -R mulberry-bin`). `packaging/arch/PKGBUILD` builds the same package from the release. - **Debian, Ubuntu and other apt systems:** `sudo apt install ./Mulberry--amd64.deb`. -- **Nix:** `nix profile install git+https://astar76.com/git/astar76/Mulberry` (this repo is a flake), or `callPackage ./packaging/nix { }`. +- **Nix:** `nix profile install git+https://archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry` (this repo is a flake), or `callPackage ./packaging/nix { }`. - **Any distribution:** unpack `Mulberry--Linux-x86_64.tar.gz` and run `sh install.sh` inside (your home, `~/.local`, no root) or `sh install.sh --system` (`/usr/local`). `sh uninstall.sh` removes it; `--purge` also deletes settings and data. `installer.sh` from this repo does the same next to a downloaded tar.gz or AppImage. diff --git a/android/AndroidManifest.xml b/android/AndroidManifest.xml deleted file mode 100644 index 369d059..0000000 --- a/android/AndroidManifest.xml +++ /dev/null @@ -1,139 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/android/VERSION b/android/VERSION deleted file mode 100644 index 157e54f..0000000 --- a/android/VERSION +++ /dev/null @@ -1 +0,0 @@ -2.0.6 diff --git a/android/VERSION_CODE b/android/VERSION_CODE deleted file mode 100644 index 45a4fb7..0000000 --- a/android/VERSION_CODE +++ /dev/null @@ -1 +0,0 @@ -8 diff --git a/android/build.sh b/android/build.sh deleted file mode 100755 index 7ca4af0..0000000 --- a/android/build.sh +++ /dev/null @@ -1,70 +0,0 @@ -#!/bin/bash -# Sources in src/ and res/ were recovered (jadx) from the Android 1.2.2 APK, whose original project was lost; -# methods the decompiler broke were rewritten by hand and are marked "Rewritten by hand". -# Builds Mulberry for Android with the plain SDK tools (aapt2, javac, d8, apksigner), no Gradle. -# Outputs dist/Mulberry--Android.apk, signed with the release keystore in $KEYSTORE. -# Needs: a JDK, and the SDK at $ANDROID_HOME with platforms;android-34 and build-tools;35.0.0: -# sdkmanager "platforms;android-34" "build-tools;35.0.0" -set -euo pipefail -cd "$(dirname "$0")" - -VERSION=${VERSION:-$(cat VERSION)} -VERSION_CODE=${VERSION_CODE:-$(cat VERSION_CODE)} -ANDROID_HOME=${ANDROID_HOME:-$HOME/.local/opt/android-sdk} -BT=${BT:-$ANDROID_HOME/build-tools/35.0.0} -PLATFORM=${PLATFORM:-$ANDROID_HOME/platforms/android-34/android.jar} -OUT=${OUT:-$HOME/.cache/mulberry-android/build} -KEYDIR=${KEYDIR:-$HOME/.config/mulberry-android} -KEYSTORE=${KEYSTORE:-$KEYDIR/release.jks} -KEYPASS_FILE=${KEYPASS_FILE:-$KEYDIR/keystore.pass} -APK=dist/Mulberry-$VERSION-Android.apk -LIBS=${LIBS:-$HOME/.cache/mulberry-android/libs} -JAT=$LIBS/jaudiotagger-2.0.3.jar -JAT_SHA256=b558a96bb256f957bb471d1f33d8f10240282ce44050ff52d628e48661e396f7 - -for f in "$BT/aapt2" "$BT/d8" "$BT/zipalign" "$BT/apksigner" "$PLATFORM"; do - [ -e "$f" ] || { echo "missing $f (see the header of this script)" >&2; exit 1; } -done - -if [ ! -f "$JAT" ]; then - echo "== fetching jaudiotagger" - mkdir -p "$LIBS" - curl -fsSL -o "$JAT.part" https://repo1.maven.org/maven2/org/jaudiotagger/2.0.3/jaudiotagger-2.0.3.jar - mv "$JAT.part" "$JAT" -fi -echo "$JAT_SHA256 $JAT" | sha256sum -c --quiet - || { echo "bad checksum: $JAT" >&2; exit 1; } - -if [ ! -f "$KEYSTORE" ]; then - echo "!! no release keystore at $KEYSTORE: making a new one." - echo "!! APKs signed with it cannot update ones signed with another key. Back it up." - mkdir -p "$KEYDIR"; chmod 700 "$KEYDIR" - head -c 24 /dev/urandom | base64 | tr -d '/+=' > "$KEYPASS_FILE"; chmod 600 "$KEYPASS_FILE" - keytool -genkeypair -keystore "$KEYSTORE" -storetype PKCS12 -alias mulberry -keyalg RSA -keysize 4096 \ - -validity 10000 -dname "CN=Mulberry, O=Mulberry" -storepass:file "$KEYPASS_FILE" >/dev/null - chmod 600 "$KEYSTORE" -fi - -rm -rf "$OUT" -mkdir -p "$OUT/gen" "$OUT/classes" "$OUT/dex" dist - -echo "== resources" -"$BT/aapt2" compile --dir res -o "$OUT/res.zip" -"$BT/aapt2" link -I "$PLATFORM" --manifest AndroidManifest.xml --java "$OUT/gen" \ - --version-code "$VERSION_CODE" --version-name "$VERSION" \ - -o "$OUT/unsigned.apk" "$OUT/res.zip" - -echo "== java" -javac -nowarn -Xlint:none -encoding UTF-8 -source 17 -target 17 -cp "$PLATFORM:$JAT" -d "$OUT/classes" \ - $(find src "$OUT/gen" -name '*.java') 2> "$OUT/javac.log" || { cat "$OUT/javac.log" >&2; echo "javac failed" >&2; exit 1; } - -echo "== dex" -"$BT/d8" --release --min-api 24 --lib "$PLATFORM" --output "$OUT/dex" \ - $(find "$OUT/classes" -name '*.class') "$JAT" 2> "$OUT/d8.log" || { cat "$OUT/d8.log" >&2; echo "d8 failed" >&2; exit 1; } -(cd "$OUT/dex" && zip -q "$OUT/unsigned.apk" classes*.dex) - -echo "== sign" -"$BT/zipalign" -f -p 4 "$OUT/unsigned.apk" "$OUT/aligned.apk" -"$BT/apksigner" -J-enable-native-access=ALL-UNNAMED sign --ks "$KEYSTORE" --ks-pass "file:$KEYPASS_FILE" --out "$APK" "$OUT/aligned.apk" -"$BT/apksigner" -J-enable-native-access=ALL-UNNAMED verify "$APK" -rm -f "$APK.idsig" -echo "== $APK ($(du -h "$APK" | cut -f1))" diff --git a/android/res/drawable/ic_add.xml b/android/res/drawable/ic_add.xml deleted file mode 100644 index ab3b5f2..0000000 --- a/android/res/drawable/ic_add.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_album.xml b/android/res/drawable/ic_album.xml deleted file mode 100644 index 9bcc55b..0000000 --- a/android/res/drawable/ic_album.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_arrow_back.xml b/android/res/drawable/ic_arrow_back.xml deleted file mode 100644 index 7374728..0000000 --- a/android/res/drawable/ic_arrow_back.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_artist.xml b/android/res/drawable/ic_artist.xml deleted file mode 100644 index b0e9f7a..0000000 --- a/android/res/drawable/ic_artist.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_auto_awesome.xml b/android/res/drawable/ic_auto_awesome.xml deleted file mode 100644 index 2d955d9..0000000 --- a/android/res/drawable/ic_auto_awesome.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_check.xml b/android/res/drawable/ic_check.xml deleted file mode 100644 index 61ae63d..0000000 --- a/android/res/drawable/ic_check.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_clear_all.xml b/android/res/drawable/ic_clear_all.xml deleted file mode 100644 index f9fb662..0000000 --- a/android/res/drawable/ic_clear_all.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_close.xml b/android/res/drawable/ic_close.xml deleted file mode 100644 index 0dde35a..0000000 --- a/android/res/drawable/ic_close.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_cloud_download.xml b/android/res/drawable/ic_cloud_download.xml deleted file mode 100644 index bc8d877..0000000 --- a/android/res/drawable/ic_cloud_download.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_content_copy.xml b/android/res/drawable/ic_content_copy.xml deleted file mode 100644 index 61dd28b..0000000 --- a/android/res/drawable/ic_content_copy.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_delete.xml b/android/res/drawable/ic_delete.xml deleted file mode 100644 index 01329a8..0000000 --- a/android/res/drawable/ic_delete.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_download.xml b/android/res/drawable/ic_download.xml deleted file mode 100644 index 44071ec..0000000 --- a/android/res/drawable/ic_download.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_drag_indicator.xml b/android/res/drawable/ic_drag_indicator.xml deleted file mode 100644 index 2e6b18a..0000000 --- a/android/res/drawable/ic_drag_indicator.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_edit.xml b/android/res/drawable/ic_edit.xml deleted file mode 100644 index e354405..0000000 --- a/android/res/drawable/ic_edit.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_expand_more.xml b/android/res/drawable/ic_expand_more.xml deleted file mode 100644 index 4420c65..0000000 --- a/android/res/drawable/ic_expand_more.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_favorite.xml b/android/res/drawable/ic_favorite.xml deleted file mode 100644 index 603ac66..0000000 --- a/android/res/drawable/ic_favorite.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_favorite_fill.xml b/android/res/drawable/ic_favorite_fill.xml deleted file mode 100644 index 8865b79..0000000 --- a/android/res/drawable/ic_favorite_fill.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_file_open.xml b/android/res/drawable/ic_file_open.xml deleted file mode 100644 index b18f009..0000000 --- a/android/res/drawable/ic_file_open.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_fingerprint.xml b/android/res/drawable/ic_fingerprint.xml deleted file mode 100644 index eaecf1c..0000000 --- a/android/res/drawable/ic_fingerprint.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_folder.xml b/android/res/drawable/ic_folder.xml deleted file mode 100644 index b43ec02..0000000 --- a/android/res/drawable/ic_folder.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_folder_open.xml b/android/res/drawable/ic_folder_open.xml deleted file mode 100644 index e687e88..0000000 --- a/android/res/drawable/ic_folder_open.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_graphic_eq.xml b/android/res/drawable/ic_graphic_eq.xml deleted file mode 100644 index e9b0e39..0000000 --- a/android/res/drawable/ic_graphic_eq.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_history.xml b/android/res/drawable/ic_history.xml deleted file mode 100644 index 0cdd682..0000000 --- a/android/res/drawable/ic_history.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_image.xml b/android/res/drawable/ic_image.xml deleted file mode 100644 index 12dd328..0000000 --- a/android/res/drawable/ic_image.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_info.xml b/android/res/drawable/ic_info.xml deleted file mode 100644 index 8d7501b..0000000 --- a/android/res/drawable/ic_info.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_label.xml b/android/res/drawable/ic_label.xml deleted file mode 100644 index 1d31503..0000000 --- a/android/res/drawable/ic_label.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_launcher_fg.xml b/android/res/drawable/ic_launcher_fg.xml deleted file mode 100644 index 7019c8f..0000000 --- a/android/res/drawable/ic_launcher_fg.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - diff --git a/android/res/drawable/ic_launcher_mono.xml b/android/res/drawable/ic_launcher_mono.xml deleted file mode 100644 index 8cd0583..0000000 --- a/android/res/drawable/ic_launcher_mono.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_library_music.xml b/android/res/drawable/ic_library_music.xml deleted file mode 100644 index 6ef3e37..0000000 --- a/android/res/drawable/ic_library_music.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_link.xml b/android/res/drawable/ic_link.xml deleted file mode 100644 index 5bd03d9..0000000 --- a/android/res/drawable/ic_link.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_lyrics.xml b/android/res/drawable/ic_lyrics.xml deleted file mode 100644 index 4e2ee32..0000000 --- a/android/res/drawable/ic_lyrics.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_more_vert.xml b/android/res/drawable/ic_more_vert.xml deleted file mode 100644 index b6f2662..0000000 --- a/android/res/drawable/ic_more_vert.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_music_note.xml b/android/res/drawable/ic_music_note.xml deleted file mode 100644 index 70d78b3..0000000 --- a/android/res/drawable/ic_music_note.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_palette.xml b/android/res/drawable/ic_palette.xml deleted file mode 100644 index ef001a1..0000000 --- a/android/res/drawable/ic_palette.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_pause_fill.xml b/android/res/drawable/ic_pause_fill.xml deleted file mode 100644 index a02245f..0000000 --- a/android/res/drawable/ic_pause_fill.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_person.xml b/android/res/drawable/ic_person.xml deleted file mode 100644 index 3678cb4..0000000 --- a/android/res/drawable/ic_person.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_play_arrow_fill.xml b/android/res/drawable/ic_play_arrow_fill.xml deleted file mode 100644 index 012b5c6..0000000 --- a/android/res/drawable/ic_play_arrow_fill.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_playlist_add.xml b/android/res/drawable/ic_playlist_add.xml deleted file mode 100644 index 514829b..0000000 --- a/android/res/drawable/ic_playlist_add.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_queue_music.xml b/android/res/drawable/ic_queue_music.xml deleted file mode 100644 index 614db43..0000000 --- a/android/res/drawable/ic_queue_music.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_queue_play_next.xml b/android/res/drawable/ic_queue_play_next.xml deleted file mode 100644 index a740fc9..0000000 --- a/android/res/drawable/ic_queue_play_next.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_radio.xml b/android/res/drawable/ic_radio.xml deleted file mode 100644 index 85342d4..0000000 --- a/android/res/drawable/ic_radio.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_refresh.xml b/android/res/drawable/ic_refresh.xml deleted file mode 100644 index 36fe6d3..0000000 --- a/android/res/drawable/ic_refresh.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_repeat.xml b/android/res/drawable/ic_repeat.xml deleted file mode 100644 index 559a716..0000000 --- a/android/res/drawable/ic_repeat.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_repeat_one.xml b/android/res/drawable/ic_repeat_one.xml deleted file mode 100644 index a9848f0..0000000 --- a/android/res/drawable/ic_repeat_one.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_save.xml b/android/res/drawable/ic_save.xml deleted file mode 100644 index cbac360..0000000 --- a/android/res/drawable/ic_save.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_scrobble.xml b/android/res/drawable/ic_scrobble.xml deleted file mode 100644 index 0cc4f05..0000000 --- a/android/res/drawable/ic_scrobble.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_search.xml b/android/res/drawable/ic_search.xml deleted file mode 100644 index 68fecbe..0000000 --- a/android/res/drawable/ic_search.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_settings.xml b/android/res/drawable/ic_settings.xml deleted file mode 100644 index 40635f2..0000000 --- a/android/res/drawable/ic_settings.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_shuffle.xml b/android/res/drawable/ic_shuffle.xml deleted file mode 100644 index 2b49c84..0000000 --- a/android/res/drawable/ic_shuffle.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_skip_next_fill.xml b/android/res/drawable/ic_skip_next_fill.xml deleted file mode 100644 index 7dfa01d..0000000 --- a/android/res/drawable/ic_skip_next_fill.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_skip_previous_fill.xml b/android/res/drawable/ic_skip_previous_fill.xml deleted file mode 100644 index 233370e..0000000 --- a/android/res/drawable/ic_skip_previous_fill.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_sort.xml b/android/res/drawable/ic_sort.xml deleted file mode 100644 index 9a98288..0000000 --- a/android/res/drawable/ic_sort.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_star.xml b/android/res/drawable/ic_star.xml deleted file mode 100644 index 1301f59..0000000 --- a/android/res/drawable/ic_star.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_star_fill.xml b/android/res/drawable/ic_star_fill.xml deleted file mode 100644 index 856bab5..0000000 --- a/android/res/drawable/ic_star_fill.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_stop_fill.xml b/android/res/drawable/ic_stop_fill.xml deleted file mode 100644 index 10a6b38..0000000 --- a/android/res/drawable/ic_stop_fill.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_text_snippet.xml b/android/res/drawable/ic_text_snippet.xml deleted file mode 100644 index c207701..0000000 --- a/android/res/drawable/ic_text_snippet.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_trending_up.xml b/android/res/drawable/ic_trending_up.xml deleted file mode 100644 index 384a49b..0000000 --- a/android/res/drawable/ic_trending_up.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_tune.xml b/android/res/drawable/ic_tune.xml deleted file mode 100644 index 299fb73..0000000 --- a/android/res/drawable/ic_tune.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_upload.xml b/android/res/drawable/ic_upload.xml deleted file mode 100644 index 170ac0d..0000000 --- a/android/res/drawable/ic_upload.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/ic_visibility.xml b/android/res/drawable/ic_visibility.xml deleted file mode 100644 index 41d04f5..0000000 --- a/android/res/drawable/ic_visibility.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - diff --git a/android/res/drawable/w_bar_bg.xml b/android/res/drawable/w_bar_bg.xml deleted file mode 100644 index 62b4e6a..0000000 --- a/android/res/drawable/w_bar_bg.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/android/res/drawable/w_bg.xml b/android/res/drawable/w_bg.xml deleted file mode 100644 index 6d673c5..0000000 --- a/android/res/drawable/w_bg.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/android/res/drawable/w_card_bg.xml b/android/res/drawable/w_card_bg.xml deleted file mode 100644 index bed9b33..0000000 --- a/android/res/drawable/w_card_bg.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/android/res/drawable/w_circle.xml b/android/res/drawable/w_circle.xml deleted file mode 100644 index 27397d8..0000000 --- a/android/res/drawable/w_circle.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/android/res/drawable/w_pill.xml b/android/res/drawable/w_pill.xml deleted file mode 100644 index 3fdd671..0000000 --- a/android/res/drawable/w_pill.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/android/res/layout/widget_compact.xml b/android/res/layout/widget_compact.xml deleted file mode 100644 index fdcb6a3..0000000 --- a/android/res/layout/widget_compact.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - - - - - - - - diff --git a/android/res/layout/widget_large.xml b/android/res/layout/widget_large.xml deleted file mode 100644 index db4f8a4..0000000 --- a/android/res/layout/widget_large.xml +++ /dev/null @@ -1,205 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/android/res/layout/widget_lyrics.xml b/android/res/layout/widget_lyrics.xml deleted file mode 100644 index 20da913..0000000 --- a/android/res/layout/widget_lyrics.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - - - - - - - - - - - diff --git a/android/res/layout/widget_medium.xml b/android/res/layout/widget_medium.xml deleted file mode 100644 index f6160d6..0000000 --- a/android/res/layout/widget_medium.xml +++ /dev/null @@ -1,164 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/android/res/layout/widget_medium_tall.xml b/android/res/layout/widget_medium_tall.xml deleted file mode 100644 index 9120d98..0000000 --- a/android/res/layout/widget_medium_tall.xml +++ /dev/null @@ -1,205 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/android/res/layout/widget_shape.xml b/android/res/layout/widget_shape.xml deleted file mode 100644 index e418e4b..0000000 --- a/android/res/layout/widget_shape.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - diff --git a/android/res/mipmap-anydpi-v26/ic_launcher.xml b/android/res/mipmap-anydpi-v26/ic_launcher.xml deleted file mode 100644 index d5125c7..0000000 --- a/android/res/mipmap-anydpi-v26/ic_launcher.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/android/res/mipmap-hdpi-v4/ic_launcher.png b/android/res/mipmap-hdpi-v4/ic_launcher.png deleted file mode 100644 index a96c105..0000000 Binary files a/android/res/mipmap-hdpi-v4/ic_launcher.png and /dev/null differ diff --git a/android/res/mipmap-mdpi-v4/ic_launcher.png b/android/res/mipmap-mdpi-v4/ic_launcher.png deleted file mode 100644 index 28a3563..0000000 Binary files a/android/res/mipmap-mdpi-v4/ic_launcher.png and /dev/null differ diff --git a/android/res/mipmap-xhdpi-v4/ic_launcher.png b/android/res/mipmap-xhdpi-v4/ic_launcher.png deleted file mode 100644 index 9ea8ac4..0000000 Binary files a/android/res/mipmap-xhdpi-v4/ic_launcher.png and /dev/null differ diff --git a/android/res/mipmap-xxhdpi-v4/ic_launcher.png b/android/res/mipmap-xxhdpi-v4/ic_launcher.png deleted file mode 100644 index c2da8c4..0000000 Binary files a/android/res/mipmap-xxhdpi-v4/ic_launcher.png and /dev/null differ diff --git a/android/res/mipmap-xxxhdpi-v4/ic_launcher.png b/android/res/mipmap-xxxhdpi-v4/ic_launcher.png deleted file mode 100644 index b89825d..0000000 Binary files a/android/res/mipmap-xxxhdpi-v4/ic_launcher.png and /dev/null differ diff --git a/android/res/values-night-v31/colors.xml b/android/res/values-night-v31/colors.xml deleted file mode 100644 index 1e6cc6f..0000000 --- a/android/res/values-night-v31/colors.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - @android:color/system_neutral1_900 - @android:color/system_neutral1_900 - @android:color/system_neutral1_800 - @android:color/system_neutral1_100 - @android:color/system_neutral2_200 - @android:color/system_accent1_200 - @android:color/system_accent1_800 - @android:color/system_accent2_700 - @android:color/system_accent2_100 - diff --git a/android/res/values-night-v8/colors.xml b/android/res/values-night-v8/colors.xml deleted file mode 100644 index 17314a5..0000000 --- a/android/res/values-night-v8/colors.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - #ff141218 - #ff1d1b20 - #ff2b2930 - #ffe6e0e9 - #ffcac4d0 - #ffd0bcff - #ff381e72 - #ff4a4458 - #ffe8def8 - diff --git a/android/res/values-v31/colors.xml b/android/res/values-v31/colors.xml deleted file mode 100644 index 1d7dd1a..0000000 --- a/android/res/values-v31/colors.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - @android:color/system_neutral1_10 - @android:color/system_neutral1_50 - @android:color/system_accent2_100 - @android:color/system_neutral1_900 - @android:color/system_neutral2_700 - @android:color/system_accent1_600 - @android:color/system_accent1_0 - @android:color/system_accent2_100 - @android:color/system_accent2_900 - diff --git a/android/res/values/colors.xml b/android/res/values/colors.xml deleted file mode 100644 index cdd078d..0000000 --- a/android/res/values/colors.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - #ff3c101d - #fffef7ff - #fff3edf7 - #ffe8def8 - #ff1d1b20 - #ff49454f - #ff65558f - #ffffffff - #ffe8def8 - #ff1d192b - diff --git a/android/res/values/drawables.xml b/android/res/values/drawables.xml deleted file mode 100644 index 045e125..0000000 --- a/android/res/values/drawables.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/android/res/values/ids.xml b/android/res/values/ids.xml deleted file mode 100644 index bf142ce..0000000 --- a/android/res/values/ids.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/android/res/values/strings.xml b/android/res/values/strings.xml deleted file mode 100644 index 0aeaa25..0000000 --- a/android/res/values/strings.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - Mulberry - Big lyrics card with cover, progress and controls - Cookie cover, wavy progress and controls - A slim player bar - Synced lyrics of the playing song - A transparent shape that morphs and jumps with the bass - diff --git a/android/res/values/styles.xml b/android/res/values/styles.xml deleted file mode 100644 index f14ac33..0000000 --- a/android/res/values/styles.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - diff --git a/android/res/xml/widget_compact.xml b/android/res/xml/widget_compact.xml deleted file mode 100644 index b09ef61..0000000 --- a/android/res/xml/widget_compact.xml +++ /dev/null @@ -1,14 +0,0 @@ - - diff --git a/android/res/xml/widget_large.xml b/android/res/xml/widget_large.xml deleted file mode 100644 index 483a94d..0000000 --- a/android/res/xml/widget_large.xml +++ /dev/null @@ -1,14 +0,0 @@ - - diff --git a/android/res/xml/widget_lyrics.xml b/android/res/xml/widget_lyrics.xml deleted file mode 100644 index 049fab1..0000000 --- a/android/res/xml/widget_lyrics.xml +++ /dev/null @@ -1,14 +0,0 @@ - - diff --git a/android/res/xml/widget_medium.xml b/android/res/xml/widget_medium.xml deleted file mode 100644 index b41446e..0000000 --- a/android/res/xml/widget_medium.xml +++ /dev/null @@ -1,14 +0,0 @@ - - diff --git a/android/res/xml/widget_shape.xml b/android/res/xml/widget_shape.xml deleted file mode 100644 index d3a7190..0000000 --- a/android/res/xml/widget_shape.xml +++ /dev/null @@ -1,14 +0,0 @@ - - diff --git a/android/src/com/mulberry/player/App.java b/android/src/com/mulberry/player/App.java deleted file mode 100644 index b963e05..0000000 --- a/android/src/com/mulberry/player/App.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.mulberry.player; - -import android.app.ActivityManager; -import android.app.Application; -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.content.SharedPreferences; -import android.os.Build; -import android.os.Handler; -import android.os.Looper; -import android.os.Process; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; - -/* JADX INFO: loaded from: classes.dex */ -public class App extends Application { - public static final String CHANNEL = "playback"; - public static ExecutorService HEAVY; - public static App I; - public static ExecutorService IO; - public static Handler MAIN; - static volatile boolean lowPowerFlag; - static volatile boolean visualizerFlag; - public Library library; - public boolean lowRam; - public Palette palette; - private SharedPreferences.OnSharedPreferenceChangeListener prefWatch; - public Prefs prefs; - - @Override // android.app.Application - public void onCreate() { - super.onCreate(); - I = this; - MAIN = new Handler(Looper.getMainLooper()); - IO = Executors.newFixedThreadPool(3, factory("mulberry-io", 10)); - HEAVY = Executors.newSingleThreadExecutor(factory("mulberry-decode", 19)); - this.prefs = new Prefs(this); - ActivityManager activityManager = (ActivityManager) getSystemService("activity"); - this.lowRam = activityManager != null && (activityManager.isLowRamDevice() || (Runtime.getRuntime().availableProcessors() <= 4 && activityManager.getMemoryClass() <= 192)); - if (!this.prefs.contains(Prefs.LOW_POWER)) { - this.prefs.setBool(Prefs.LOW_POWER, this.lowRam); - } - cacheFlags(); - this.prefWatch = new SharedPreferences.OnSharedPreferenceChangeListener() { // from class: com.mulberry.player.App.1 - @Override // android.content.SharedPreferences.OnSharedPreferenceChangeListener - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String str) { - App.this.cacheFlags(); - } - }; - this.prefs.raw().registerOnSharedPreferenceChangeListener(this.prefWatch); - this.palette = Palette.build(this, null); - this.library = new Library(this); - createChannel(); - } - - private static ThreadFactory factory(final String str, final int i) { - return new ThreadFactory() { // from class: com.mulberry.player.App.2 - int n = 0; - - @Override // java.util.concurrent.ThreadFactory - public Thread newThread(final Runnable runnable) { - Runnable runnable2 = new Runnable() { // from class: com.mulberry.player.App.2.1 - @Override // java.lang.Runnable - public void run() { - Process.setThreadPriority(i); - runnable.run(); - } - }; - StringBuilder sbAppend = new StringBuilder().append(str).append("-"); - int i2 = this.n; - this.n = i2 + 1; - Thread thread = new Thread(runnable2, sbAppend.append(i2).toString()); - thread.setDaemon(true); - return thread; - } - }; - } - - private void createChannel() { - if (Build.VERSION.SDK_INT >= 26) { - NotificationChannel notificationChannel = new NotificationChannel(CHANNEL, "Playback", 2); - notificationChannel.setDescription("Now playing controls"); - notificationChannel.setShowBadge(false); - notificationChannel.setSound(null, null); - notificationChannel.enableVibration(false); - NotificationManager notificationManager = (NotificationManager) getSystemService("notification"); - if (notificationManager != null) { - notificationManager.createNotificationChannel(notificationChannel); - } - } - } - - public static void ui(Runnable runnable) { - MAIN.post(runnable); - } - - void cacheFlags() { - lowPowerFlag = this.prefs.getBool(Prefs.LOW_POWER, false); - visualizerFlag = this.prefs.getBool(Prefs.VISUALIZER, true); - } - - public static boolean lowPower() { - return lowPowerFlag; - } -} diff --git a/android/src/com/mulberry/player/BassShapeView.java b/android/src/com/mulberry/player/BassShapeView.java deleted file mode 100644 index ed127a4..0000000 --- a/android/src/com/mulberry/player/BassShapeView.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.mulberry.player; - -import android.content.Context; -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Path; -import android.view.View; - -/* JADX INFO: loaded from: classes.dex */ -public class BassShapeView extends View implements Ticker.Client { - private final Shapes.Animator anim; - private boolean attached; - private final Paint p; - private final Path path; - private MusicService svc; - private boolean ticking; - - public BassShapeView(Context context) { - super(context); - this.p = new Paint(1); - this.path = new Path(); - this.anim = new Shapes.Animator(); - } - - public void setService(MusicService musicService) { - this.svc = musicService; - } - - public void setPlaying(boolean z) { - this.anim.playing = z; - ensure(); - } - - void ensure() { - boolean z = this.attached && isShown() && getWindowVisibility() == 0 && (this.anim.playing || !this.anim.settled()); - if (!z || this.ticking) { - if (z || !this.ticking) { - return; - } - Ticker.remove(this); - this.ticking = false; - return; - } - Ticker.add(this); - this.ticking = true; - } - - @Override // android.view.View - protected void onAttachedToWindow() { - super.onAttachedToWindow(); - this.attached = true; - ensure(); - } - - @Override // android.view.View - protected void onDetachedFromWindow() { - super.onDetachedFromWindow(); - this.attached = false; - ensure(); - } - - @Override // android.view.View - protected void onVisibilityChanged(View view, int i) { - super.onVisibilityChanged(view, i); - ensure(); - } - - @Override // android.view.View - protected void onWindowVisibilityChanged(int i) { - super.onWindowVisibilityChanged(i); - ensure(); - } - - @Override // com.mulberry.player.Ticker.Client - public void frame(float f, long j) { - float fBass = -1.0f; - if (this.anim.playing && this.svc != null && this.svc.spectrum != null) { - fBass = this.svc.spectrum.bass(this.svc.positionFast()); - } - this.anim.step(f, fBass); - invalidate(); - if (this.anim.settled()) { - ensure(); - } - } - - @Override // android.view.View - protected void onDraw(Canvas canvas) { - Palette palette = App.I.palette; - float width = getWidth() / 2.0f; - float height = getHeight() / 2.0f; - this.anim.draw(canvas, width, height, Math.min(width, height) * 0.86f, Palette.alpha(palette.primaryContainer, 0.94f), palette.primary, palette.primary, this.p, this.path); - } -} diff --git a/android/src/com/mulberry/player/ChunkId3.java b/android/src/com/mulberry/player/ChunkId3.java deleted file mode 100644 index cfa32df..0000000 --- a/android/src/com/mulberry/player/ChunkId3.java +++ /dev/null @@ -1,377 +0,0 @@ -package com.mulberry.player; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.RandomAccessFile; -import java.nio.ByteBuffer; -import java.nio.channels.Channels; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import org.jaudiotagger.tag.id3.AbstractID3v2Tag; -import org.jaudiotagger.tag.id3.ID3v22Tag; -import org.jaudiotagger.tag.id3.ID3v23Tag; -import org.jaudiotagger.tag.id3.ID3v24Tag; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; -import org.jaudiotagger.tag.id3.valuepair.TextEncoding; -import org.jaudiotagger.tag.mp4.atom.Mp4DataBox; - -/* JADX INFO: loaded from: classes.dex */ -public final class ChunkId3 { - private ChunkId3() { - } - - static final class Chunk { - String id; - long offset; - long size; - - Chunk() { - } - } - - static final class Container { - boolean riff; - String form = FrameBodyCOMM.DEFAULT; - final List chunks = new ArrayList(); - - Container() { - } - } - - static Container scan(RandomAccessFile randomAccessFile) throws IOException { - long j; - randomAccessFile.seek(0L); - byte[] bArr = new byte[12]; - randomAccessFile.readFully(bArr); - String str = new String(bArr, 0, 4, TextEncoding.CHARSET_ISO_8859_1); - Container container = new Container(); - if ("RIFF".equals(str)) { - container.riff = true; - } else if (!"FORM".equals(str)) { - throw new IOException("not a WAV/AIFF file"); - } - container.form = new String(bArr, 8, 4, TextEncoding.CHARSET_ISO_8859_1); - long j2 = 12; - long length = randomAccessFile.length(); - byte[] bArr2 = new byte[8]; - do { - j = j2; - if (8 + j > length) { - break; - } - randomAccessFile.seek(j); - randomAccessFile.readFully(bArr2); - Chunk chunk = new Chunk(); - chunk.id = new String(bArr2, 0, 4, TextEncoding.CHARSET_ISO_8859_1); - chunk.offset = j; - chunk.size = container.riff ? ((long) OggOpus.le32(bArr2, 4)) & 4294967295L : ((long) OggOpus.be32(bArr2, 4)) & 4294967295L; - container.chunks.add(chunk); - j2 = 8 + j + chunk.size + (chunk.size & 1); - } while (j2 > j); - return container; - } - - static boolean isId3(String str) { - return "id3 ".equals(str) || "ID3 ".equals(str) || "ID32".equals(str); - } - - static AbstractID3v2Tag parseId3(byte[] bArr) { - if (bArr.length < 10 || bArr[0] != 73 || bArr[1] != 68 || bArr[2] != 51) { - return null; - } - try { - ByteBuffer byteBufferWrap = ByteBuffer.wrap(bArr); - if (bArr[3] == 4) { - return new ID3v24Tag(byteBufferWrap, ""); - } else if (bArr[3] == 3) { - return new ID3v23Tag(byteBufferWrap, ""); - } else if (bArr[3] == 2) { - return new ID3v22Tag(byteBufferWrap, ""); - } - return null; - } catch (Throwable th) { - return null; - } - } - - static boolean isAac(File file) { - String strExtOf = TagCore.extOf(file); - return "aac".equals(strExtOf) || "adts".equals(strExtOf); - } - - public static TagCore.Info read(File file) throws Exception { - AbstractID3v2Tag id3; - TagCore.Info info = new TagCore.Info(); - RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); - AbstractID3v2Tag abstractID3v2Tag = null; - try { - if (isAac(file)) { - int iPrefixLen = prefixLen(randomAccessFile); - if (iPrefixLen > 0) { - byte[] bArr = new byte[iPrefixLen]; - randomAccessFile.seek(0L); - randomAccessFile.readFully(bArr); - id3 = parseId3(bArr); - } else { - id3 = null; - } - info.format = "AAC (ADTS)"; - } else { - Container containerScan = scan(randomAccessFile); - Iterator it = containerScan.chunks.iterator(); - while (true) { - if (!it.hasNext()) { - id3 = abstractID3v2Tag; - break; - } - Chunk next = it.next(); - if (!isId3(next.id) || next.size >= 67108864) { - id3 = abstractID3v2Tag; - } else { - byte[] bArr2 = new byte[(int) next.size]; - randomAccessFile.seek(next.offset + 8); - randomAccessFile.readFully(bArr2); - id3 = parseId3(bArr2); - if (id3 != null) { - break; - } - } - abstractID3v2Tag = id3; - } - audioInfo(randomAccessFile, containerScan, info); - } - TagCore.fillInfo(id3, info); - return info; - } finally { - randomAccessFile.close(); - } - } - - static void audioInfo(RandomAccessFile randomAccessFile, Container container, TagCore.Info info) throws IOException { - long jBe32; - String strValueOf; - long j = 0; - int iExtended = 0; - int i = 0; - int i2 = 0; - long j2 = 0; - Iterator it = container.chunks.iterator(); - while (true) { - jBe32 = j2; - if (!it.hasNext()) { - break; - } - Chunk next = it.next(); - if (container.riff && "fmt ".equals(next.id) && next.size >= 16) { - byte[] bArr = new byte[16]; - randomAccessFile.seek(next.offset + 8); - randomAccessFile.readFully(bArr); - i = (bArr[2] & 255) | ((bArr[3] & 255) << 8); - iExtended = OggOpus.le32(bArr, 4); - i2 = (bArr[14] & 255) | ((bArr[15] & 255) << 8); - } else if (container.riff && Mp4DataBox.IDENTIFIER.equals(next.id)) { - j = next.size; - } else if (!container.riff && "COMM".equals(next.id) && next.size >= 18) { - byte[] bArr2 = new byte[18]; - randomAccessFile.seek(next.offset + 8); - randomAccessFile.readFully(bArr2); - i = ((bArr2[0] & 255) << 8) | (bArr2[1] & 255); - jBe32 = ((long) OggOpus.be32(bArr2, 2)) & 4294967295L; - i2 = (bArr2[7] & 255) | ((bArr2[6] & 255) << 8); - iExtended = (int) extended(bArr2, 8); - } - j2 = jBe32; - } - info.format = container.riff ? "WAV" : "AIFF"; - info.sampleRate = iExtended; - if (i == 1) { - strValueOf = "mono"; - } else { - strValueOf = i == 2 ? "stereo" : String.valueOf(i); - } - info.channels = strValueOf; - if (container.riff && iExtended > 0 && i > 0 && i2 > 0) { - jBe32 = j / (((long) i) * ((long) ((i2 + 7) / 8))); - } - if (iExtended > 0) { - info.lengthSec = (int) (jBe32 / ((long) iExtended)); - } - if (iExtended <= 0 || i2 <= 0) { - return; - } - info.bitrate = String.valueOf(((((long) iExtended) * ((long) i)) * ((long) i2)) / 1000); - } - - static double extended(byte[] bArr, int i) { - int i2 = (bArr[i + 1] & 255) | ((bArr[i] & 127) << 8); - long j = 0; - for (int i3 = 0; i3 < 8; i3++) { - j = (j << 8) | ((long) (bArr[i + 2 + i3] & 255)); - } - if (i2 == 0 && j == 0) { - return 0.0d; - } - return Math.pow(2.0d, (i2 - 16383) - 52) * (j >>> 11); - } - - static int prefixLen(RandomAccessFile randomAccessFile) throws IOException { - randomAccessFile.seek(0L); - byte[] bArr = new byte[10]; - if (randomAccessFile.read(bArr) >= 10 && bArr[0] == 73 && bArr[1] == 68 && bArr[2] == 51) { - return (((bArr[6] & 127) << 21) | ((bArr[7] & 127) << 14) | ((bArr[8] & 127) << 7) | (bArr[9] & 127)) + 10 + ((bArr[5] & 16) == 0 ? 0 : 10); - } - return 0; - } - - public static void write(File file, Map map, byte[] bArr, String str, boolean z, String str2) throws Exception { - int i; - Container container; - AbstractID3v2Tag id3; - ID3v24Tag iD3v24Tag; - long j; - RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); - File file2 = new File(file.getPath() + ".mbtmp"); - AbstractID3v2Tag id4 = null; - try { - try { - if (isAac(file)) { - int iPrefixLen = prefixLen(randomAccessFile); - if (iPrefixLen > 0) { - byte[] bArr2 = new byte[iPrefixLen]; - randomAccessFile.seek(0L); - randomAccessFile.readFully(bArr2); - id4 = parseId3(bArr2); - i = iPrefixLen; - container = null; - } else { - i = iPrefixLen; - container = null; - } - } else { - Container containerScan = scan(randomAccessFile); - AbstractID3v2Tag abstractID3v2Tag = null; - for (Chunk chunk : containerScan.chunks) { - if (isId3(chunk.id) && chunk.size < 67108864 && abstractID3v2Tag == null) { - byte[] bArr3 = new byte[(int) chunk.size]; - randomAccessFile.seek(chunk.offset + 8); - randomAccessFile.readFully(bArr3); - id3 = parseId3(bArr3); - } else { - id3 = abstractID3v2Tag; - } - abstractID3v2Tag = id3; - } - i = 0; - container = containerScan; - id4 = abstractID3v2Tag; - } - if (id4 == null) { - iD3v24Tag = new ID3v24Tag(); - } else { - iD3v24Tag = id4 instanceof ID3v24Tag ? (ID3v24Tag) id4 : new ID3v24Tag(id4); - } - TagCore.apply(iD3v24Tag, map, bArr, str, 0, 0, z, str2); - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - iD3v24Tag.write(Channels.newChannel(byteArrayOutputStream)); - byte[] byteArray = byteArrayOutputStream.toByteArray(); - FileOutputStream fileOutputStream = new FileOutputStream(file2); - try { - if (container == null) { - fileOutputStream.write(byteArray); - copy(randomAccessFile, i, randomAccessFile.length() - ((long) i), fileOutputStream); - } else { - long j2 = 4; - ArrayList arrayList = new ArrayList(); - for (Chunk chunk2 : container.chunks) { - if (isId3(chunk2.id)) { - j = j2; - } else { - arrayList.add(chunk2); - j = (chunk2.size & 1) + 8 + chunk2.size + j2; - } - j2 = j; - } - long length = byteArray.length; - long j3 = j2 + (length & 1) + 8 + length; - if (j3 > 4294967295L) { - throw new IOException("file too large for RIFF/FORM"); - } - byte[] bArr4 = new byte[12]; - System.arraycopy((container.riff ? "RIFF" : "FORM").getBytes(TextEncoding.CHARSET_ISO_8859_1), 0, bArr4, 0, 4); - size(bArr4, 4, (int) j3, container.riff); - System.arraycopy(container.form.getBytes(TextEncoding.CHARSET_ISO_8859_1), 0, bArr4, 8, 4); - fileOutputStream.write(bArr4); - for (Chunk chunk3 : arrayList) { - copy(randomAccessFile, chunk3.offset, 8 + chunk3.size + (chunk3.size & 1), fileOutputStream); - } - byte[] bArr5 = new byte[8]; - System.arraycopy((container.riff ? "id3 " : "ID3 ").getBytes(TextEncoding.CHARSET_ISO_8859_1), 0, bArr5, 0, 4); - size(bArr5, 4, byteArray.length, container.riff); - fileOutputStream.write(bArr5); - fileOutputStream.write(byteArray); - if ((byteArray.length & 1) == 1) { - fileOutputStream.write(0); - } - } - fileOutputStream.close(); - randomAccessFile.close(); - if (!file.delete() || !file2.renameTo(file)) { - FileInputStream fileInputStream = new FileInputStream(file2); - FileOutputStream fileOutputStream2 = new FileOutputStream(file); - byte[] bArr6 = new byte[262144]; - while (true) { - int i2 = fileInputStream.read(bArr6); - if (i2 <= 0) { - fileInputStream.close(); - fileOutputStream2.close(); - file2.delete(); - return; - } - fileOutputStream2.write(bArr6, 0, i2); - } - } - } catch (Throwable th) { - fileOutputStream.close(); - throw th; - } - } catch (Exception e) { - file2.delete(); - throw e; - } - } catch (Throwable th2) { - randomAccessFile.close(); - throw th2; - } - } - - static void size(byte[] bArr, int i, int i2, boolean z) { - if (!z) { - bArr[i] = (byte) (i2 >> 24); - bArr[i + 1] = (byte) (i2 >> 16); - bArr[i + 2] = (byte) (i2 >> 8); - bArr[i + 3] = (byte) i2; - return; - } - OggOpus.put32(bArr, i, i2); - } - - static void copy(RandomAccessFile randomAccessFile, long j, long j2, OutputStream outputStream) throws IOException { - int i; - long length = randomAccessFile.length(); - if (j + j2 > length) { - j2 = Math.max(0L, length - j); - } - randomAccessFile.seek(j); - byte[] bArr = new byte[262144]; - while (j2 > 0 && (i = randomAccessFile.read(bArr, 0, (int) Math.min(bArr.length, j2))) > 0) { - outputStream.write(bArr, 0, i); - j2 -= (long) i; - } - } -} diff --git a/android/src/com/mulberry/player/CookieView.java b/android/src/com/mulberry/player/CookieView.java deleted file mode 100644 index c559ed7..0000000 --- a/android/src/com/mulberry/player/CookieView.java +++ /dev/null @@ -1,180 +0,0 @@ -package com.mulberry.player; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.BitmapShader; -import android.graphics.Canvas; -import android.graphics.Matrix; -import android.graphics.Paint; -import android.graphics.Path; -import android.graphics.Shader; -import android.graphics.drawable.Drawable; -import android.view.View; - -/* JADX INFO: loaded from: classes.dex */ -public class CookieView extends View implements Ticker.Client { - private Drawable albumIcon; - private float appear; - private boolean attached; - private final Paint barPaint; - private float bass; - private Bitmap cover; - private final float[] lv; - private final Matrix m; - private final Paint paint; - private final Path path; - private boolean playing; - private float pulse; - private float rot; - private BitmapShader shader; - private Bitmap shaderFor; - public boolean small; - private float spin; - private MusicService svc; - private final float[] target; - private boolean ticking; - - public CookieView(Context context) { - super(context); - this.paint = new Paint(3); - this.barPaint = new Paint(1); - this.path = new Path(); - this.m = new Matrix(); - this.lv = new float[48]; - this.target = new float[48]; - this.appear = 1.0f; - } - - public void setService(MusicService musicService) { - this.svc = musicService; - } - - public void setCover(Bitmap bitmap) { - if (bitmap != this.cover) { - this.cover = bitmap; - this.appear = 0.0f; - ensureTick(); - } - invalidate(); - } - - public void setPlaying(boolean z) { - this.playing = z; - ensureTick(); - } - - boolean bars() { - return Spectrum.enabled(); - } - - void ensureTick() { - boolean z = this.attached && isShown() && getWindowVisibility() == 0 && (this.playing || this.spin > 0.01f || this.appear < 1.0f || this.pulse > 0.01f); - if (!z || this.ticking) { - if (z || !this.ticking) { - return; - } - Ticker.remove(this); - this.ticking = false; - return; - } - Ticker.add(this); - this.ticking = true; - } - - @Override // android.view.View - protected void onAttachedToWindow() { - super.onAttachedToWindow(); - this.attached = true; - ensureTick(); - } - - @Override // android.view.View - protected void onDetachedFromWindow() { - super.onDetachedFromWindow(); - this.attached = false; - ensureTick(); - } - - @Override // android.view.View - protected void onVisibilityChanged(View view, int i) { - super.onVisibilityChanged(view, i); - ensureTick(); - } - - @Override // android.view.View - protected void onWindowVisibilityChanged(int i) { - super.onWindowVisibilityChanged(i); - ensureTick(); - } - - @Override // com.mulberry.player.Ticker.Client - public void frame(float f, long j) { - this.spin = ((((!this.playing || App.lowPower()) ? 0.0f : 1.0f) - this.spin) * Math.min(1.0f, 2.5f * f)) + this.spin; - this.rot += this.spin * f * 0.22f; - if (this.appear < 1.0f) { - this.appear = Math.min(1.0f, this.appear + (2.8f * f)); - } - boolean z = this.svc != null && bars() && this.playing && this.svc.spectrum != null && this.svc.spectrum.levels(this.svc.positionFast(), this.target); - float f2 = 0.0f; - for (int i = 0; i < this.lv.length; i++) { - float f3 = z ? this.target[i] : 0.0f; - float f4 = f3 > this.lv[i] ? 0.55f : 0.16f; - float[] fArr = this.lv; - fArr[i] = ((f3 - this.lv[i]) * Math.min(1.0f, f4 * f * 60.0f)) + fArr[i]; - if (i < 4) { - f2 += this.lv[i]; - } - } - this.bass = f2 / 4.0f; - this.pulse += ((z ? 1.8f * Math.max(0.0f, this.bass - 0.45f) : 0.0f) - this.pulse) * Math.min(1.0f, 14.0f * f); - invalidate(); - if (this.playing || this.spin >= 0.01f || this.appear < 1.0f || this.pulse >= 0.01f) { - return; - } - ensureTick(); - } - - @Override // android.view.View - protected void onMeasure(int i, int i2) { - int iMin = Math.min(View.MeasureSpec.getSize(i), View.MeasureSpec.getSize(i2)); - if (View.MeasureSpec.getMode(i2) == 0) { - iMin = View.MeasureSpec.getSize(i); - } - setMeasuredDimension(iMin, iMin); - } - - @Override // android.view.View - protected void onDraw(Canvas canvas) { - float fMin = Math.min(getWidth(), getHeight()); - float width = getWidth() / 2.0f; - float height = getHeight() / 2.0f; - float f = (fMin / 2.0f) - 2.0f; - boolean zBars = bars(); - float f2 = (zBars ? 0.72f : 0.97f) * f; - float f3 = zBars ? 0.06f : 0.045f; - float f4 = (0.9f + (0.1f * (1.0f - ((1.0f - this.appear) * (1.0f - this.appear))))) * (1.0f + (0.045f * this.pulse)) * f2; - Palette palette = App.I.palette; - if (zBars) { - Draw.bars(canvas, width, height, f4, f3, this.rot, (f - (f2 * 1.06f)) - (f * 0.04f), this.lv, this.small ? 44 : 72, palette.primary, this.small ? Math.max(Ui.dpf(getContext(), 1.6f), fMin / 50.0f) : Math.max(Ui.dpf(getContext(), 2.6f), fMin / 85.0f), this.barPaint); - } - Draw.cookie(this.path, width, height, f4, f3, this.rot); - this.paint.setAlpha(255); - if (this.cover != this.shaderFor) { - this.shaderFor = this.cover; - this.shader = this.cover == null ? null : new BitmapShader(this.cover, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); - } - Draw.cookieCover(canvas, this.path, this.cover, this.shader, width, height, f4, this.paint, palette.primaryContainer, this.m); - if (this.cover == null) { - if (this.albumIcon == null) { - this.albumIcon = getContext().getDrawable(R.drawable.ic_album).mutate(); - } - Drawable drawable = this.albumIcon; - if (drawable != null) { - int i = (int) (f4 * 0.8f); - drawable.setTint(palette.onPrimaryContainer); - drawable.setBounds((int) (width - (i / 2.0f)), (int) (height - (i / 2.0f)), (int) (width + (i / 2.0f)), (int) (height + (i / 2.0f))); - drawable.draw(canvas); - } - } - } -} diff --git a/android/src/com/mulberry/player/Covers.java b/android/src/com/mulberry/player/Covers.java deleted file mode 100644 index a641f6c..0000000 --- a/android/src/com/mulberry/player/Covers.java +++ /dev/null @@ -1,390 +0,0 @@ -package com.mulberry.player; - -import android.content.ContentResolver; -import android.content.ContentUris; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.media.MediaMetadataRetriever; -import android.net.Uri; -import android.os.Build; -import android.os.Process; -import android.provider.MediaStore; -import android.util.LruCache; -import android.util.Size; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.LinkedBlockingDeque; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; -import org.jaudiotagger.tag.mp4.atom.Mp4DataBox; -import org.jaudiotagger.tag.mp4.atom.Mp4NameBox; -import org.json.JSONArray; -import org.json.JSONObject; - -/* JADX INFO: loaded from: classes.dex */ -public final class Covers { - private static final LruCache CACHE; - private static final Set MISSING = Collections.synchronizedSet(new HashSet()); - private static final ThreadPoolExecutor THUMBS; - - public interface Cb { - void done(Bitmap bitmap); - } - - public interface Wanted { - boolean still(); - } - - static { - int iMaxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); - CACHE = new LruCache((App.I == null || !App.I.lowRam) ? iMaxMemory / 8 : iMaxMemory / 16) { // from class: com.mulberry.player.Covers.1 - /* JADX INFO: Access modifiers changed from: protected */ - @Override // android.util.LruCache - public int sizeOf(String str, Bitmap bitmap) { - return bitmap.getByteCount() / 1024; - } - }; - THUMBS = new ThreadPoolExecutor(2, 2, 30L, TimeUnit.SECONDS, new LinkedBlockingDeque() { // from class: com.mulberry.player.Covers.2 - @Override // java.util.concurrent.LinkedBlockingDeque, java.util.Queue, java.util.concurrent.BlockingDeque, java.util.concurrent.BlockingQueue, java.util.Deque - public boolean offer(Runnable runnable) { - return offerFirst(runnable); - } - }, new ThreadFactory() { // from class: com.mulberry.player.Covers.3 - @Override // java.util.concurrent.ThreadFactory - public Thread newThread(final Runnable runnable) { - Thread thread = new Thread(new Runnable() { // from class: com.mulberry.player.Covers.3.1 - @Override // java.lang.Runnable - public void run() { - Process.setThreadPriority(10); - runnable.run(); - } - }, "mulberry-thumbs"); - thread.setDaemon(true); - return thread; - } - }); - } - - public static void loadThumb(final Song song, final int i, final Wanted wanted, final Cb cb) { - final String strKey = key(song, i); - Bitmap bitmap = CACHE.get(strKey); - if (bitmap == null) { - if (!MISSING.contains(strKey)) { - THUMBS.execute(new Runnable() { // from class: com.mulberry.player.Covers.4 - @Override // java.lang.Runnable - public void run() { - if (wanted.still()) { - Bitmap bm = (Bitmap) Covers.CACHE.get(strKey); - if (bm == null) { - try { - bm = Covers.loadBlocking(song, Covers.bucket(i), false); - } catch (Throwable th) { - } - if (bm != null) { - Covers.CACHE.put(strKey, bm); - } else { - Covers.MISSING.add(strKey); - } - } - final Bitmap bitmapLoadBlocking = bm; - App.ui(new Runnable() { // from class: com.mulberry.player.Covers.4.1 - @Override // java.lang.Runnable - public void run() { - if (wanted.still()) { - cb.done(bitmapLoadBlocking); - } - } - }); - } - } - }); - return; - } else { - cb.done(null); - return; - } - } - cb.done(bitmap); - } - - public static Bitmap cached(Song song, int i) { - if (song == null) { - return null; - } - return CACHE.get(key(song, i)); - } - - private static String key(Song song, int i) { - return (song.albumId >= 0 ? "a" + song.albumId : song.key()) + "@" + bucket(i); - } - - /* JADX INFO: Access modifiers changed from: private */ - public static int bucket(int i) { - if (i <= 160) { - return 160; - } - return i <= 400 ? 400 : 800; - } - - public static void load(final Song song, final int i, final boolean z, final Cb cb) { - if (song != null) { - final String strKey = key(song, i); - Bitmap bitmap = CACHE.get(strKey); - if (bitmap == null) { - if (!MISSING.contains(strKey) || z) { - App.IO.execute(new Runnable() { // from class: com.mulberry.player.Covers.5 - @Override // java.lang.Runnable - public void run() { - Bitmap bm = null; - try { - bm = Covers.loadBlocking(song, Covers.bucket(i), z); - } catch (Throwable th) { - } - if (bm != null) { - Covers.CACHE.put(strKey, bm); - } else { - Covers.MISSING.add(strKey); - } - final Bitmap bitmapLoadBlocking = bm; - App.ui(new Runnable() { // from class: com.mulberry.player.Covers.5.1 - @Override // java.lang.Runnable - public void run() { - cb.done(bitmapLoadBlocking); - } - }); - } - }); - return; - } else { - cb.done(null); - return; - } - } - cb.done(bitmap); - return; - } - cb.done(null); - } - - public static Bitmap loadBlocking(Song song, int i, boolean z) { - byte[] bArrFetchOnline; - File parentFile; - ContentResolver contentResolver = App.I.getContentResolver(); - File fileOverrideFile = overrideFile(song); - Bitmap bitmapDecodeFile = fileOverrideFile.exists() ? decodeFile(fileOverrideFile, i) : null; - File fileOnlineFile = onlineFile(song); - if (bitmapDecodeFile == null && fileOnlineFile.exists()) { - bitmapDecodeFile = decodeFile(fileOnlineFile, i); - } - if (bitmapDecodeFile == null && song.id >= 0 && Build.VERSION.SDK_INT >= 29) { - try { - bitmapDecodeFile = contentResolver.loadThumbnail(ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, song.id), new Size(i, i), null); - } catch (Exception e) { - } - if (bitmapDecodeFile == null && song.albumId >= 0) { - try { - bitmapDecodeFile = contentResolver.loadThumbnail(ContentUris.withAppendedId(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, song.albumId), new Size(i, i), null); - } catch (Exception e2) { - } - } - } - if (bitmapDecodeFile == null && song.albumId >= 0 && Build.VERSION.SDK_INT < 29) { - try { - InputStream inputStreamOpenInputStream = contentResolver.openInputStream(Library.albumArtUri(song.albumId)); - if (inputStreamOpenInputStream != null) { - bitmapDecodeFile = decodeStream(Net.readAll(inputStreamOpenInputStream), i); - } - } catch (Exception e3) { - } - } - if (bitmapDecodeFile == null && !song.isStream()) { - MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever(); - try { - mediaMetadataRetriever.setDataSource(App.I, song.toUri()); - byte[] embeddedPicture = mediaMetadataRetriever.getEmbeddedPicture(); - if (embeddedPicture != null) { - bitmapDecodeFile = decodeStream(embeddedPicture, i); - } - try { - mediaMetadataRetriever.release(); - } catch (Exception e4) { - } - } catch (Exception e5) { - try { - mediaMetadataRetriever.release(); - } catch (Exception e6) { - } - } catch (Throwable th) { - try { - mediaMetadataRetriever.release(); - } catch (Exception e7) { - } - throw th; - } - } - if (bitmapDecodeFile == null && song.path.length() > 0 && (parentFile = new File(song.path).getParentFile()) != null) { - for (String str : new String[]{"cover.jpg", "folder.jpg", "front.jpg", "cover.png", "folder.png", "AlbumArt.jpg"}) { - File file = new File(parentFile, str); - if (file.canRead() && (bitmapDecodeFile = decodeFile(file, i)) != null) { - break; - } - } - } - if (bitmapDecodeFile == null && z && App.I.prefs.getBool(Prefs.ONLINE_COVERS, true) && (bArrFetchOnline = fetchOnline(song)) != null && bArrFetchOnline.length > 1000) { - try { - FileOutputStream fileOutputStream = new FileOutputStream(fileOnlineFile); - fileOutputStream.write(bArrFetchOnline); - fileOutputStream.close(); - } catch (Exception e8) { - } - return decodeStream(bArrFetchOnline, i); - } - return bitmapDecodeFile; - } - - static File overrideFile(Song song) { - File file = new File(App.I.getFilesDir(), "art"); - file.mkdirs(); - return new File(file, Integer.toHexString(song.key().hashCode()) + "_" + Integer.toHexString(song.path.hashCode()) + ".img"); - } - - public static void setOverride(Song song, byte[] bArr) { - try { - File fileOverrideFile = overrideFile(song); - if (bArr == null) { - fileOverrideFile.delete(); - onlineFile(song).delete(); - } else { - FileOutputStream fileOutputStream = new FileOutputStream(fileOverrideFile); - fileOutputStream.write(bArr); - fileOutputStream.close(); - } - } catch (Exception e) { - } - forget(song); - } - - public static void forget(Song song) { - for (int i : new int[]{160, 400, 800}) { - String strKey = key(song, i); - CACHE.remove(strKey); - synchronized (MISSING) { - MISSING.remove(strKey); - } - } - } - - private static File onlineFile(Song song) { - File file = new File(App.I.getCacheDir(), "covers"); - file.mkdirs(); - return new File(file, Integer.toHexString(((song.albumArtist.length() > 0 ? song.albumArtist : song.artist) + "|" + (song.album.length() > 0 ? song.album : song.title)).toLowerCase().hashCode()) + ".jpg"); - } - - static Bitmap decodeFile(File file, int i) { - try { - return decodeStream(Net.readAll(new FileInputStream(file)), i); - } catch (Exception e) { - return null; - } - } - - static Bitmap decodeStream(byte[] bArr, int i) { - int i2 = 1; - BitmapFactory.Options options = new BitmapFactory.Options(); - options.inJustDecodeBounds = true; - BitmapFactory.decodeByteArray(bArr, 0, bArr.length, options); - while (options.outWidth / (i2 * 2) >= i && options.outHeight / (i2 * 2) >= i) { - i2 *= 2; - } - BitmapFactory.Options options2 = new BitmapFactory.Options(); - options2.inSampleSize = i2; - options2.inPreferredConfig = Bitmap.Config.ARGB_8888; - return BitmapFactory.decodeByteArray(bArr, 0, bArr.length, options2); - } - - private static String norm(String str) { - return str == null ? FrameBodyCOMM.DEFAULT : str.toLowerCase().replaceAll("[^a-z0-9]", FrameBodyCOMM.DEFAULT); - } - - // Rewritten by hand: the decompiler could not rebuild this method. - static byte[] fetchOnline(Song song) { - String strOptString = null; - String strReplaceAll; - String strDisplayArtist = song.albumArtist.length() > 0 ? song.albumArtist : song.displayArtist(); - String str = song.album; - if (strDisplayArtist.length() == 0 && str.length() == 0) { - return null; - } - try { - JSONArray jSONArrayOptJSONArray = new JSONObject(Net.get("https://itunes.apple.com/search?entity=" + (str.length() > 0 ? "album" : "song") + "&limit=6&term=" + Net.enc(strDisplayArtist + " " + (str.length() > 0 ? str : song.title)), null)).optJSONArray("results"); - for (int i = 0; jSONArrayOptJSONArray != null && i < jSONArrayOptJSONArray.length(); i++) { - JSONObject jSONObject = jSONArrayOptJSONArray.getJSONObject(i); - if (norm(strDisplayArtist).length() > 0 && !norm(jSONObject.optString("artistName")).contains(norm(strDisplayArtist)) && !norm(strDisplayArtist).contains(norm(jSONObject.optString("artistName")))) { - continue; - } - strOptString = jSONObject.optString("artworkUrl100").replace("100x100bb", "800x800bb"); - break; - } - } catch (Exception e4) { - strOptString = null; - } - if (strOptString == null) { - try { - JSONArray jSONArrayOptJSONArray2 = new JSONObject(Net.get("https://api.deezer.com/search/album?q=" + Net.enc(strDisplayArtist + " " + str), null)).optJSONArray(Mp4DataBox.IDENTIFIER); - for (int i2 = 0; jSONArrayOptJSONArray2 != null && i2 < jSONArrayOptJSONArray2.length(); i2++) { - JSONObject jSONObject2 = jSONArrayOptJSONArray2.getJSONObject(i2); - if (norm(jSONObject2.optJSONObject("artist") != null ? jSONObject2.optJSONObject("artist").optString(Mp4NameBox.IDENTIFIER) : FrameBodyCOMM.DEFAULT).contains(norm(strDisplayArtist))) { - strOptString = jSONObject2.optString("cover_xl"); - break; - } - } - } catch (Exception e) { - } - } - if (strOptString == null && str.length() > 0) { - try { - HashMap map = new HashMap(); - map.put("method", "album.getinfo"); - map.put("api_key", LastFm.KEY); - map.put("artist", strDisplayArtist); - map.put("album", str); - map.put("format", "json"); - map.put("autocorrect", "1"); - JSONObject jSONObject3 = new JSONObject(Net.get("https://ws.audioscrobbler.com/2.0/?" + Net.query(map), null)); - JSONArray jSONArrayOptJSONArray3 = jSONObject3.optJSONObject("album") != null ? jSONObject3.getJSONObject("album").optJSONArray("image") : null; - if (jSONArrayOptJSONArray3 == null || jSONArrayOptJSONArray3.length() <= 0) { - strReplaceAll = strOptString; - } else { - String strOptString2 = jSONArrayOptJSONArray3.getJSONObject(jSONArrayOptJSONArray3.length() - 1).optString("#text"); - if (strOptString2.length() > 0) { - strReplaceAll = strOptString2.replaceAll("/\\d+x\\d+/", "/"); - } else { - strReplaceAll = strOptString; - } - } - strOptString = strReplaceAll; - } catch (Exception e2) { - } - } - if (strOptString == null || strOptString.length() == 0) { - return null; - } - try { - return Net.getBytes(strOptString, null); - } catch (Exception e3) { - return null; - } - } - - public static Uri contentUri(Song song) { - return song.toUri(); - } -} diff --git a/android/src/com/mulberry/player/Draw.java b/android/src/com/mulberry/player/Draw.java deleted file mode 100644 index ae47cb8..0000000 --- a/android/src/com/mulberry/player/Draw.java +++ /dev/null @@ -1,161 +0,0 @@ -package com.mulberry.player; - -import android.graphics.Bitmap; -import android.graphics.BitmapShader; -import android.graphics.Canvas; -import android.graphics.Matrix; -import android.graphics.Paint; -import android.graphics.Path; -import android.graphics.Shader; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; - -/* JADX INFO: loaded from: classes.dex */ -public final class Draw { - public static final int LOBES = 9; - - private Draw() { - } - - public static Path cookie(Path path, float f, float f2, float f3, float f4, float f5) { - if (path == null) { - path = new Path(); - } else { - path.reset(); - } - for (int i = 0; i < 120; i++) { - double d = (6.283185307179586d * ((double) i)) / ((double) Shapes.N); - double dCos = ((double) f3) * (((double) (1.0f - f4)) + (((double) f4) * Math.cos(9.0d * (d - ((double) f5))))); - float fCos = (float) (((double) f) + (Math.cos(d) * dCos)); - float fSin = (float) ((Math.sin(d) * dCos) + ((double) f2)); - if (i == 0) { - path.moveTo(fCos, fSin); - } else { - path.lineTo(fCos, fSin); - } - } - path.close(); - return path; - } - - public static void cookieCover(Canvas canvas, Path path, Bitmap bitmap, float f, float f2, float f3, Paint paint, int i, Matrix matrix) { - cookieCover(canvas, path, bitmap, null, f, f2, f3, paint, i, matrix); - } - - public static void cookieCover(Canvas canvas, Path path, Bitmap bitmap, BitmapShader bitmapShader, float f, float f2, float f3, Paint paint, int i, Matrix matrix) { - if (bitmap != null && !bitmap.isRecycled()) { - if (bitmapShader == null) { - bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); - } - if (matrix == null) { - matrix = new Matrix(); - } - matrix.reset(); - float fMin = Math.min(bitmap.getWidth(), bitmap.getHeight()); - float f4 = (2.0f * f3) / fMin; - matrix.setScale(f4, f4); - matrix.postTranslate((f - f3) - (((bitmap.getWidth() - fMin) / 2.0f) * f4), (f2 - f3) - (((bitmap.getHeight() - fMin) / 2.0f) * f4)); - bitmapShader.setLocalMatrix(matrix); - paint.setShader(bitmapShader); - paint.setColor(-1); - canvas.drawPath(path, paint); - paint.setShader(null); - return; - } - paint.setShader(null); - paint.setColor(i); - canvas.drawPath(path, paint); - } - - public static void bars(Canvas canvas, float f, float f2, float f3, float f4, float f5, float f6, float[] fArr, int i, int i2, float f7, Paint paint) { - float f8; - paint.setStyle(Paint.Style.STROKE); - paint.setStrokeCap(Paint.Cap.ROUND); - paint.setStrokeWidth(f7); - paint.setShader(null); - float f9 = f3 * 0.06f; - int i3 = 0; - while (i3 < i) { - double d = (6.283185307179586d * ((double) i3)) / ((double) i); - double d2 = ((double) f5) + d; - double dCos = ((double) f3) * ((Math.cos(d * 9.0d) * ((double) f4)) + ((double) (1.0f - f4))); - if (fArr != null) { - int i4 = i / 2; - f8 = fArr[Math.min(fArr.length - 1, ((i3 < i4 ? i3 : (i - 1) - i3) * fArr.length) / Math.max(1, i4))]; - } else { - f8 = 0.18f; - } - paint.setColor(Palette.alpha(i2, (Math.min(3, (int) (4.5f * f8)) * 0.19f) + 0.42f)); - double d3 = dCos + ((double) f9); - double d4 = 2.5d + d3 + ((double) (f8 * f6)); - float fCos = (float) Math.cos(d2); - float fSin = (float) Math.sin(d2); - canvas.drawLine((((float) d3) * fCos) + f, (((float) d3) * fSin) + f2, f + (fCos * ((float) d4)), f2 + (((float) d4) * fSin), paint); - i3++; - } - paint.setStyle(Paint.Style.FILL); - } - - public static void wavy(Canvas canvas, float f, float f2, float f3, float f4, float f5, float f6, float f7, float f8, float f9, int i, int i2, Paint paint, Path path, boolean z, float f10) { - float fMax = f + ((f2 - f) * Math.max(0.0f, Math.min(1.0f, f4))); - float f11 = f7 * 1.5f; - paint.setStyle(Paint.Style.STROKE); - paint.setStrokeCap(Paint.Cap.ROUND); - paint.setStrokeJoin(Paint.Join.ROUND); - paint.setStrokeWidth(f7); - paint.setShader(null); - if (fMax + f11 < f2) { - paint.setColor(i2); - canvas.drawLine(fMax + f11, f3, f2, f3, paint); - paint.setStyle(Paint.Style.FILL); - paint.setColor(i); - canvas.drawCircle(f2 - (f7 / 2.0f), f3, f7 / 2.0f, paint); - paint.setStyle(Paint.Style.STROKE); - } - if (fMax - f11 > f) { - float f12 = f9 * f5; - float f13 = fMax - f11; - float f14 = f8 * 0.42f; - if (path == null) { - path = new Path(); - } else { - path.reset(); - } - path.moveTo(f, f3); - float fMax2 = Math.max(1.0f, f7 / 2.5f); - float f15 = f; - while (f15 < f13) { - float fMin = Math.min(f15 + fMax2, f13); - float fMin2 = Math.min(1.0f, Math.min((fMin - f) / f14, (f13 - fMin) / f14)); - if (fMin2 < 0.0f) { - fMin2 = 0.0f; - } - Path path2 = path; - path2.lineTo(fMin, ((3.0f - (fMin2 * 2.0f)) * fMin2 * fMin2 * f12 * ((float) Math.sin((((double) (((fMin - f) / f8) * 2.0f)) * 3.141592653589793d) - ((double) f6)))) + f3); - f15 = fMin; - } - paint.setColor(i); - canvas.drawPath(path, paint); - } - if (z) { - paint.setStyle(Paint.Style.FILL); - paint.setColor(i); - float f16 = 1.25f * f7; - canvas.drawRoundRect(fMax - (f16 / 2.0f), f3 - (f10 / 2.0f), (f16 / 2.0f) + fMax, (f10 / 2.0f) + f3, f16 / 2.0f, f16 / 2.0f, paint); - } - paint.setStyle(Paint.Style.FILL); - } - - public static String time(long j) { - if (j < 0) { - j = 0; - } - long j2 = j / 1000; - long j3 = j2 / 3600; - long j4 = (j2 / 60) % 60; - long j5 = j2 % 60; - if (j3 > 0) { - return j3 + ":" + (j4 < 10 ? "0" : FrameBodyCOMM.DEFAULT) + j4 + ":" + (j5 < 10 ? "0" : FrameBodyCOMM.DEFAULT) + j5; - } - return j4 + ":" + (j5 < 10 ? "0" : FrameBodyCOMM.DEFAULT) + j5; - } -} diff --git a/android/src/com/mulberry/player/LastFm.java b/android/src/com/mulberry/player/LastFm.java deleted file mode 100644 index 0ad12c1..0000000 --- a/android/src/com/mulberry/player/LastFm.java +++ /dev/null @@ -1,420 +0,0 @@ -package com.mulberry.player; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.security.MessageDigest; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; -import org.jaudiotagger.tag.mp4.atom.Mp4NameBox; -import org.json.JSONArray; -import org.json.JSONObject; - -/* JADX INFO: loaded from: classes.dex */ -public final class LastFm { - static final String API = "https://ws.audioscrobbler.com/2.0/"; - public static final String KEY = "654be90d519a1688bb90661f8f493c0a"; - static final String SECRET = "df1f1a14348a083d9aef80820b274931"; - - public interface Cb { - void done(String str); - } - - /** Last.fm API error with its code (0 = network/HTTP problem). */ - public static final class LfmError extends Exception { - public final int code; - - LfmError(int code, String msg) { - super(msg); - this.code = code; - } - } - - /** Session no longer valid (auth failed, invalid session key, unauthorized token). */ - static boolean authError(int code) { - return code == 4 || code == 9 || code == 14; - } - - /** Worth retrying later (service offline, temporary error, rate limit, network). */ - static boolean retryError(int code) { - return code == 0 || code == 11 || code == 16 || code == 29; - } - - /** Either scrobbler is on. */ - public static boolean anyOn() { - return enabled() || ListenBrainz.enabled(); - } - - public static boolean loggedIn() { - return App.I.prefs.getStr(Prefs.LFM_SESSION, FrameBodyCOMM.DEFAULT).length() > 0; - } - - public static boolean enabled() { - return loggedIn() && App.I.prefs.getBool(Prefs.LFM_ENABLED, true); - } - - static String md5(String str) throws Exception { - byte[] bArrDigest = MessageDigest.getInstance("MD5").digest(str.getBytes("UTF-8")); - StringBuilder sb = new StringBuilder(); - for (byte b : bArrDigest) { - sb.append(String.format("%02x", Integer.valueOf(b & 255))); - } - return sb.toString(); - } - - static JSONObject call(String str, Map map, boolean z) throws Exception { - TreeMap treeMap = new TreeMap(map); - treeMap.put("method", str); - treeMap.put("api_key", KEY); - if (z) { - treeMap.put("sk", App.I.prefs.getStr(Prefs.LFM_SESSION, FrameBodyCOMM.DEFAULT)); - } - StringBuilder sb = new StringBuilder(); - for (Map.Entry entry : (java.util.Set) (java.util.Set) treeMap.entrySet()) { - sb.append((String) entry.getKey()).append((String) entry.getValue()); - } - treeMap.put("api_sig", md5(((Object) sb) + SECRET)); - treeMap.put("format", "json"); - String text; - try { - text = Net.post(API, Net.query(treeMap)); - } catch (Exception e) { - throw new LfmError(0, "Last.fm: " + e.getMessage()); - } - JSONObject jSONObject; - try { - jSONObject = new JSONObject(text); - } catch (Exception e) { - throw new LfmError(0, "Last.fm: bad reply"); - } - if (jSONObject.has("error")) { - int code = jSONObject.optInt("error"); - if (z && authError(code)) { - sessionExpired(); - } - throw new LfmError(code, jSONObject.optString("message", "Last.fm error " + code)); - } - return jSONObject; - } - - public static void login(final String str, final String str2, final Cb cb) { - App.IO.execute(new Runnable() { // from class: com.mulberry.player.LastFm.1 - @Override // java.lang.Runnable - public void run() { - String msg = null; - try { - TreeMap treeMap = new TreeMap(); - treeMap.put("username", str); - treeMap.put("password", str2); - JSONObject jSONObject = LastFm.call("auth.getMobileSession", treeMap, false).getJSONObject("session"); - App.I.prefs.setStr(Prefs.LFM_SESSION, jSONObject.getString("key")); - App.I.prefs.setStr(Prefs.LFM_USER, jSONObject.optString(Mp4NameBox.IDENTIFIER, str)); - App.I.prefs.setBool(Prefs.LFM_ENABLED, true); - } catch (Exception e) { - msg = e.getMessage(); - } - final String message = msg; - App.ui(new Runnable() { // from class: com.mulberry.player.LastFm.1.1 - @Override // java.lang.Runnable - public void run() { - cb.done(message); - } - }); - } - }); - } - - public static void logout() { - App.I.prefs.setStr(Prefs.LFM_SESSION, FrameBodyCOMM.DEFAULT); - App.I.prefs.setStr(Prefs.LFM_USER, FrameBodyCOMM.DEFAULT); - purge("lastfm"); - } - - /** Last.fm dropped our session: forget it but keep the queue for the next sign-in. */ - static void sessionExpired() { - App.I.prefs.setStr(Prefs.LFM_SESSION, FrameBodyCOMM.DEFAULT); - App.ui(new Runnable() { - @Override - public void run() { - MainActivity.toast("Last.fm signed Mulberry out. Sign in again in Settings; scrobbles are kept."); - } - }); - } - - static TreeMap trackParams(Song song, String str) { - TreeMap treeMap = new TreeMap<>(); - treeMap.put("artist" + str, song.displayArtist()); - treeMap.put("track" + str, song.displayTitle()); - if (song.album.length() > 0) { - treeMap.put("album" + str, song.album); - } - if (song.albumArtist.length() > 0 && !song.albumArtist.equals(song.artist)) { - treeMap.put("albumArtist" + str, song.albumArtist); - } - if (song.duration > 0) { - treeMap.put("duration" + str, String.valueOf(song.duration / 1000)); - } - if (song.track > 0) { - treeMap.put("trackNumber" + str, String.valueOf(song.track)); - } - String mbid = ListenBrainz.fileInfo(song).optString("recording_mbid", ""); - if (mbid.length() > 0) { - treeMap.put("mbid" + str, mbid); - } - if (str.length() > 0) { - treeMap.put("chosenByUser" + str, song.isStream() ? "0" : "1"); - } - return treeMap; - } - - public static void nowPlaying(final Song song) { - ListenBrainz.nowPlaying(song); - if (enabled() && song != null && song.displayArtist().length() != 0) { - App.IO.execute(new Runnable() { // from class: com.mulberry.player.LastFm.2 - @Override // java.lang.Runnable - public void run() { - try { - LastFm.call("track.updateNowPlaying", LastFm.trackParams(song, FrameBodyCOMM.DEFAULT), true); - } catch (Exception e) { - } - } - }); - } - } - - static File queueFile() { - return new File(App.I.getFilesDir(), "scrobbles.json"); - } - - static synchronized JSONArray readQueue() { - JSONArray jSONArray; - try { - jSONArray = new JSONArray(new String(Net.readAll(new FileInputStream(queueFile())), "UTF-8")); - } catch (Exception e) { - jSONArray = new JSONArray(); - } - return jSONArray; - } - - static synchronized void writeQueue(JSONArray jSONArray) { - try { - FileOutputStream fileOutputStream = new FileOutputStream(queueFile()); - fileOutputStream.write(jSONArray.toString().getBytes("UTF-8")); - fileOutputStream.close(); - } catch (Exception e) { - } - } - - public static void scrobble(final Song song, final long j) { - if (anyOn() && song.displayArtist().length() != 0) { - App.IO.execute(new Runnable() { - @Override - public void run() { - LastFm.queueScrobble(song, j); - } - }); - } - } - - static void queueScrobble(Song song, long j) { - try { - synchronized (LastFm.class) { - JSONArray queue = readQueue(); - for (String svc : new String[]{"lastfm", "listenbrainz"}) { - if ("lastfm".equals(svc) ? enabled() : ListenBrainz.enabled()) { - JSONObject json = song.toJson(); - json.put("ts", j); - json.put("svc", svc); - queue.put(json); - } - } - writeQueue(queue); - } - } catch (Exception e) { - } - flush(); - } - - static String svcOf(JSONObject o) { - return o.optString("svc", "lastfm"); - } - - /** Drop the queue of a service the user signed out of. */ - public static void purge(String svc) { - synchronized (LastFm.class) { - JSONArray q = readQueue(); - JSONArray keep = new JSONArray(); - for (int i = 0; i < q.length(); i++) { - JSONObject o = q.optJSONObject(i); - if (o != null && !svc.equals(svcOf(o))) { - keep.put(o); - } - } - writeQueue(keep); - } - } - - /** Remove sent (or rejected) entries, matched by service + timestamp + uri. */ - static void removeDone(List done) { - if (done.isEmpty()) { - return; - } - java.util.Set keys = new java.util.HashSet<>(); - for (JSONObject o : done) { - keys.add(svcOf(o) + "|" + o.optLong("ts") + "|" + o.optString("uri")); - } - synchronized (LastFm.class) { - JSONArray q = readQueue(); - JSONArray keep = new JSONArray(); - for (int i = 0; i < q.length(); i++) { - JSONObject o = q.optJSONObject(i); - if (o != null && !keys.contains(svcOf(o) + "|" + o.optLong("ts") + "|" + o.optString("uri"))) { - keep.put(o); - } - } - writeQueue(keep); - } - } - - /** Retry queued scrobbles this often while playing, so a failed send waits at most this long. */ - static final long RETRY_MS = 120000L; - private static long lastRetry = 0L; - - /** Called from the playback tick: flush now and then while something is queued. */ - public static void maybeRetry() { - long now = android.os.SystemClock.elapsedRealtime(); - if (now - lastRetry < RETRY_MS) { - return; - } - lastRetry = now; - flush(); - } - - /** Send queued scrobbles. Each service goes on its own, so one failing never blocks the other. */ - public static void flush() { - if (!anyOn()) { - return; - } - App.IO.execute(new Runnable() { - @Override - public void run() { - JSONArray queue; - synchronized (LastFm.class) { - queue = LastFm.readQueue(); - } - List lfm = new ArrayList<>(), lb = new ArrayList<>(), done = new ArrayList<>(); - long now = System.currentTimeMillis() / 1000; - for (int i = 0; i < queue.length(); i++) { - JSONObject o = queue.optJSONObject(i); - if (o == null) { - continue; - } - if ("listenbrainz".equals(svcOf(o))) { - lb.add(o); - } else if (now - o.optLong("ts", now) > 14 * 86400) { - done.add(o); // Last.fm refuses scrobbles older than 14 days - } else { - lfm.add(o); - } - } - if (enabled()) { - for (int s = 0; s < lfm.size(); s += 50) { - List chunk = lfm.subList(s, Math.min(s + 50, lfm.size())); - TreeMap params = new TreeMap<>(); - for (int i = 0; i < chunk.size(); i++) { - params.putAll(trackParams(Song.fromJson(chunk.get(i)), "[" + i + "]")); - params.put("timestamp[" + i + "]", String.valueOf(chunk.get(i).optLong("ts"))); - } - try { - call("track.scrobble", params, true); - done.addAll(chunk); - } catch (LfmError e) { - if (authError(e.code) || retryError(e.code)) { - break; - } - done.addAll(chunk); // Last.fm rejected the data itself; retrying would loop forever - } catch (Exception e) { - break; - } - } - } - if (ListenBrainz.enabled()) { - outer: - for (int s = 0; s < lb.size(); s += 100) { - List chunk = lb.subList(s, Math.min(s + 100, lb.size())); - JSONArray payload = new JSONArray(); - try { - for (JSONObject o : chunk) { - payload.put(ListenBrainz.payload(Song.fromJson(o), o.optLong("ts"))); - } - } catch (Exception e) { - break; - } - try { - ListenBrainz.submit(payload.length() > 1 ? "import" : "single", payload); - done.addAll(chunk); - } catch (ListenBrainz.HttpError e) { - if (e.status != 400) { - break; - } - // One bad listen spoils a batch: send them one by one and drop the bad ones. - for (int i = 0; i < chunk.size(); i++) { - try { - ListenBrainz.submit("single", new JSONArray().put(payload.opt(i))); - done.add(chunk.get(i)); - } catch (ListenBrainz.HttpError e2) { - if (e2.status != 400) { - break outer; - } - done.add(chunk.get(i)); - } - } - } - } - } - removeDone(done); - } - }); - } - - public static int pending() { - return readQueue().length(); - } - - public static int pending(String svc) { - JSONArray q = readQueue(); - int n = 0; - for (int i = 0; i < q.length(); i++) { - JSONObject o = q.optJSONObject(i); - if (o != null && svc.equals(svcOf(o))) { - n++; - } - } - return n; - } - - public static void love(final Song song, final boolean z) { - ListenBrainz.love(song, z); - if (enabled()) { - App.IO.execute(new Runnable() { - @Override - public void run() { - TreeMap treeMap = new TreeMap(); - treeMap.put("artist", song.displayArtist()); - treeMap.put("track", song.displayTitle()); - try { - LastFm.call(z ? "track.love" : "track.unlove", treeMap, true); - } catch (Exception e) { - } - } - }); - } - } - - static List unused() { - return new ArrayList(); - } -} diff --git a/android/src/com/mulberry/player/Library.java b/android/src/com/mulberry/player/Library.java deleted file mode 100644 index 9f577de..0000000 --- a/android/src/com/mulberry/player/Library.java +++ /dev/null @@ -1,390 +0,0 @@ -package com.mulberry.player; - -import android.content.ContentResolver; -import android.content.Context; -import android.database.ContentObserver; -import android.database.Cursor; -import android.net.Uri; -import android.os.Build; -import android.provider.MediaStore; -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; - -/* JADX INFO: loaded from: classes.dex */ -public class Library { - private final Context ctx; - private boolean observing; - private Runnable pendingRefresh; - public volatile List songs = new ArrayList(); - public volatile List albums = new ArrayList(); - public volatile List artists = new ArrayList(); - public volatile List folders = new ArrayList(); - public volatile boolean loaded = false; - private final Map byId = new HashMap(); - private final Map byPath = new HashMap(); - private final CopyOnWriteArrayList listeners = new CopyOnWriteArrayList<>(); - - public static final class Group { - public String key; - public String subtitle; - public String title; - public long albumId = -1; - public final List songs = new ArrayList(); - } - - public interface Listener { - void onLibraryChanged(); - } - - public Library(Context context) { - this.ctx = context.getApplicationContext(); - } - - public void addListener(Listener listener) { - this.listeners.add(listener); - } - - public void removeListener(Listener listener) { - this.listeners.remove(listener); - } - - public void startObserving() { - if (!this.observing) { - this.observing = true; - this.ctx.getContentResolver().registerContentObserver(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true, new ContentObserver(App.MAIN) { // from class: com.mulberry.player.Library.1 - @Override // android.database.ContentObserver - public void onChange(boolean z) { - if (Library.this.pendingRefresh != null) { - App.MAIN.removeCallbacks(Library.this.pendingRefresh); - } - Library.this.pendingRefresh = new Runnable() { // from class: com.mulberry.player.Library.1.1 - @Override // java.lang.Runnable - public void run() { - Library.this.refresh(); - } - }; - App.MAIN.postDelayed(Library.this.pendingRefresh, 2500L); - } - }); - } - } - - public void refresh() { - App.IO.execute(new Runnable() { // from class: com.mulberry.player.Library.2 - @Override // java.lang.Runnable - public void run() { - try { - Library.this.build(Library.this.query()); - App.ui(new Runnable() { // from class: com.mulberry.player.Library.2.1 - @Override // java.lang.Runnable - public void run() { - Library.this.loaded = true; - Iterator it = Library.this.listeners.iterator(); - while (it.hasNext()) { - ((Listener) it.next()).onLibraryChanged(); - } - } - }); - } catch (Throwable th) { - } - } - }); - } - - /* JADX INFO: Access modifiers changed from: private */ - /* JADX WARN: Code duplicated, block: B:31:0x0195 */ - /* JADX WARN: Code duplicated, block: B:42:0x01ae */ - /* JADX WARN: Code duplicated, block: B:57:? A[SYNTHETIC] */ - public List query() throws Throwable { - Throwable th; - Cursor cursorQuery; - ArrayList arrayList = new ArrayList(); - ContentResolver contentResolver = this.ctx.getContentResolver(); - String[] strArr = {String.valueOf(((long) App.I.prefs.getInt(Prefs.MIN_DURATION, 20)) * 1000)}; - String[] strArr2 = {"_id", "title", "artist", "album", "album_id", "duration", "track", "year", "date_added", "mime_type", "_data"}; - String[] strArr3 = new String[strArr2.length + 1]; - System.arraycopy(strArr2, 0, strArr3, 0, strArr2.length); - strArr3[strArr2.length] = "album_artist"; - Cursor cursor = null; - try { - try { - cursorQuery = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, strArr3, "duration >= ?", strArr, null); - } catch (Exception e) { - cursorQuery = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, strArr2, "duration >= ?", strArr, null); - } - if (cursorQuery == null) { - if (cursorQuery != null) { - cursorQuery.close(); - } - return arrayList; - } - try { - int columnIndex = cursorQuery.getColumnIndex("_id"); - int columnIndex2 = cursorQuery.getColumnIndex("title"); - int columnIndex3 = cursorQuery.getColumnIndex("artist"); - int columnIndex4 = cursorQuery.getColumnIndex("album"); - int columnIndex5 = cursorQuery.getColumnIndex("album_id"); - int columnIndex6 = cursorQuery.getColumnIndex("duration"); - int columnIndex7 = cursorQuery.getColumnIndex("track"); - int columnIndex8 = cursorQuery.getColumnIndex("year"); - int columnIndex9 = cursorQuery.getColumnIndex("date_added"); - int columnIndex10 = cursorQuery.getColumnIndex("mime_type"); - int columnIndex11 = cursorQuery.getColumnIndex("_data"); - int columnIndex12 = cursorQuery.getColumnIndex("album_artist"); - while (cursorQuery.moveToNext()) { - Song songFromStore = Song.fromStore(cursorQuery.getLong(columnIndex)); - songFromStore.title = str(cursorQuery, columnIndex2); - songFromStore.artist = str(cursorQuery, columnIndex3); - if ("".equals(songFromStore.artist)) { - songFromStore.artist = FrameBodyCOMM.DEFAULT; - } - songFromStore.album = str(cursorQuery, columnIndex4); - songFromStore.albumId = cursorQuery.getLong(columnIndex5); - songFromStore.duration = cursorQuery.getLong(columnIndex6); - songFromStore.track = cursorQuery.getInt(columnIndex7) % 1000; - songFromStore.year = cursorQuery.getInt(columnIndex8); - songFromStore.dateAdded = cursorQuery.getLong(columnIndex9); - songFromStore.mime = str(cursorQuery, columnIndex10); - songFromStore.path = columnIndex11 >= 0 ? str(cursorQuery, columnIndex11) : FrameBodyCOMM.DEFAULT; - songFromStore.albumArtist = columnIndex12 >= 0 ? str(cursorQuery, columnIndex12) : FrameBodyCOMM.DEFAULT; - int iLastIndexOf = songFromStore.path.lastIndexOf(47); - songFromStore.folder = iLastIndexOf > 0 ? songFromStore.path.substring(0, iLastIndexOf) : FrameBodyCOMM.DEFAULT; - arrayList.add(songFromStore); - } - if (cursorQuery != null) { - cursorQuery.close(); - } - } catch (SecurityException e2) { - if (cursorQuery != null) { - cursorQuery.close(); - } - } catch (Throwable th2) { - th = th2; - cursor = cursorQuery; - if (cursor != null) { - throw th; - } - cursor.close(); - throw th; - } - return arrayList; - } catch (SecurityException e3) { - cursorQuery = null; - if (cursorQuery != null) { - cursorQuery.close(); - } - return arrayList; - } catch (Throwable th3) { - th = th3; - if (cursor != null) { - throw th; - } - cursor.close(); - throw th; - } - } - - private static String str(Cursor cursor, int i) { - String string; - return (i >= 0 && (string = cursor.getString(i)) != null) ? string : FrameBodyCOMM.DEFAULT; - } - - /* JADX INFO: Access modifiers changed from: private */ - public synchronized void build(List list) { - String str; - Collections.sort(list, new Comparator() { // from class: com.mulberry.player.Library.3 - @Override // java.util.Comparator - public int compare(Song song, Song song2) { - return song.displayTitle().compareToIgnoreCase(song2.displayTitle()); - } - }); - LinkedHashMap linkedHashMap = new LinkedHashMap(); - LinkedHashMap linkedHashMap2 = new LinkedHashMap(); - LinkedHashMap linkedHashMap3 = new LinkedHashMap(); - this.byId.clear(); - this.byPath.clear(); - for (Song song : list) { - this.byId.put(Long.valueOf(song.id), song); - if (song.path.length() > 0) { - this.byPath.put(song.path, song); - } - String str2 = song.albumId + FrameBodyCOMM.DEFAULT; - Group group = (Group) linkedHashMap.get(str2); - if (group == null) { - group = new Group(); - group.key = str2; - group.title = song.album.length() > 0 ? song.album : "Unknown album"; - group.albumId = song.albumId; - group.subtitle = song.albumArtist.length() > 0 ? song.albumArtist : song.displayArtist(); - linkedHashMap.put(str2, group); - } - group.songs.add(song); - String strDisplayArtist = song.albumArtist.length() > 0 ? song.albumArtist : song.displayArtist(); - String str3 = strDisplayArtist.length() == 0 ? "Unknown artist" : strDisplayArtist; - Group group2 = (Group) linkedHashMap2.get(str3.toLowerCase(Locale.ROOT)); - if (group2 == null) { - group2 = new Group(); - group2.key = str3; - group2.title = str3; - linkedHashMap2.put(str3.toLowerCase(Locale.ROOT), group2); - } - group2.songs.add(song); - if (group2.albumId < 0) { - group2.albumId = song.albumId; - } - Group group3 = (Group) linkedHashMap3.get(song.folder); - if (group3 == null) { - group3 = new Group(); - group3.key = song.folder; - group3.title = song.folder.length() > 0 ? new File(song.folder).getName() : "Other"; - group3.subtitle = song.folder; - group3.albumId = song.albumId; - linkedHashMap3.put(song.folder, group3); - } - group3.songs.add(song); - } - Comparator comparator = new Comparator() { // from class: com.mulberry.player.Library.4 - @Override // java.util.Comparator - public int compare(Song song2, Song song3) { - return song2.track != song3.track ? song2.track - song3.track : song2.displayTitle().compareToIgnoreCase(song3.displayTitle()); - } - }; - Iterator it = linkedHashMap.values().iterator(); - while (it.hasNext()) { - Collections.sort(((Group) it.next()).songs, comparator); - } - Iterator it2 = linkedHashMap3.values().iterator(); - while (it2.hasNext()) { - Collections.sort(((Group) it2.next()).songs, new Comparator() { // from class: com.mulberry.player.Library.5 - @Override // java.util.Comparator - public int compare(Song song2, Song song3) { - return song2.path.compareToIgnoreCase(song3.path); - } - }); - } - for (Group group4 : (java.util.Collection) linkedHashMap2.values()) { - Collections.sort(group4.songs, new Comparator() { // from class: com.mulberry.player.Library.6 - @Override // java.util.Comparator - public int compare(Song song2, Song song3) { - int iCompareToIgnoreCase = song2.album.compareToIgnoreCase(song3.album); - return iCompareToIgnoreCase != 0 ? iCompareToIgnoreCase : song2.track - song3.track; - } - }); - int i = 0; - String str4 = null; - for (Song song2 : group4.songs) { - if (song2.album.equals(str4)) { - str = str4; - } else { - str = song2.album; - i++; - } - str4 = str; - } - group4.subtitle = i + (i == 1 ? " album · " : " albums · ") + group4.songs.size() + " songs"; - } - Comparator comparator2 = new Comparator() { // from class: com.mulberry.player.Library.7 - @Override // java.util.Comparator - public int compare(Group group5, Group group6) { - return group5.title.compareToIgnoreCase(group6.title); - } - }; - ArrayList arrayList = new ArrayList(linkedHashMap.values()); - ArrayList arrayList2 = new ArrayList(linkedHashMap2.values()); - ArrayList arrayList3 = new ArrayList(linkedHashMap3.values()); - Collections.sort(arrayList, comparator2); - Collections.sort(arrayList2, comparator2); - Collections.sort(arrayList3, comparator2); - this.songs = list; - this.albums = arrayList; - this.artists = arrayList2; - this.folders = arrayList3; - } - - public synchronized Song byId(long j) { - return this.byId.get(Long.valueOf(j)); - } - - public synchronized Song byPath(String str) { - return this.byPath.get(str); - } - - /* JADX WARN: Code duplicated, block: B:7:0x000b */ - public synchronized Song matchPath(String str) { - Song next; - if (str == null) { - next = null; - } else if (str.length() == 0) { - next = null; - } else { - next = this.byPath.get(str); - if (next == null) { - String[] strArrSplit = str.replace('\\', '/').split("/"); - if (strArrSplit.length == 0) { - next = null; - } else { - String lowerCase = strArrSplit[strArrSplit.length - 1].toLowerCase(Locale.ROOT); - String lowerCase2 = strArrSplit.length > 1 ? strArrSplit[strArrSplit.length - 2].toLowerCase(Locale.ROOT) : FrameBodyCOMM.DEFAULT; - int i = 0; - Iterator it = this.songs.iterator(); - Song song = null; - while (it.hasNext()) { - next = it.next(); - String lowerCase3 = next.path.toLowerCase(Locale.ROOT); - if (!lowerCase3.endsWith("/" + lowerCase)) { - next = song; - } else if (lowerCase2.length() <= 0 || !lowerCase3.endsWith("/" + lowerCase2 + "/" + lowerCase)) { - i++; - } - song = next; - } - if (i != 1) { - song = null; - } - next = song; - } - } - } - return next; - } - - public List search(String str) { - ArrayList arrayList = new ArrayList(); - String[] strArrSplit = str.toLowerCase(Locale.ROOT).trim().split("\\s+"); - for (Song song : this.songs) { - String lowerCase = (song.title + " " + song.artist + " " + song.album + " " + song.albumArtist).toLowerCase(Locale.ROOT); - boolean z = true; - for (String str2 : strArrSplit) { - if (!lowerCase.contains(str2)) { - z = false; - break; - } - } - if (z) { - arrayList.add(song); - } - if (arrayList.size() > 500) { - break; - } - } - return arrayList; - } - - public static Uri albumArtUri(long j) { - return Uri.parse("content://media/external/audio/albumart/" + j); - } - - public static boolean hasModernThumbs() { - return Build.VERSION.SDK_INT >= 29; - } -} diff --git a/android/src/com/mulberry/player/ListenBrainz.java b/android/src/com/mulberry/player/ListenBrainz.java deleted file mode 100644 index bfaedeb..0000000 --- a/android/src/com/mulberry/player/ListenBrainz.java +++ /dev/null @@ -1,317 +0,0 @@ -package com.mulberry.player; - -import java.io.File; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.RandomAccessFile; -import java.net.HttpURLConnection; -import java.net.URL; -import org.jaudiotagger.audio.AudioFileIO; -import org.jaudiotagger.tag.FieldKey; -import org.jaudiotagger.tag.Tag; -import org.json.JSONArray; -import org.json.JSONObject; - -/** ListenBrainz listens, "now playing" and loves, plus the MusicBrainz ids both scrobblers send (desktop scrobble.rs). */ -public final class ListenBrainz { - static final String API = "https://api.listenbrainz.org/1/"; - - /** HTTP failure with its status code (0 = no connection). */ - public static final class HttpError extends Exception { - public final int status; - - HttpError(int status, String msg) { - super(msg); - this.status = status; - } - } - - public static boolean connected() { - return App.I.prefs.getStr(Prefs.LB_TOKEN, "").length() > 0; - } - - public static boolean enabled() { - return connected() && App.I.prefs.getBool(Prefs.LB_ENABLED, true); - } - - static JSONObject http(String method, String path, String token, JSONObject body) throws HttpError { - HttpURLConnection c = null; - try { - c = (HttpURLConnection) new URL(API + path).openConnection(); - c.setConnectTimeout(10000); - c.setReadTimeout(20000); - c.setRequestMethod(method); - c.setRequestProperty("User-Agent", Net.UA); - c.setRequestProperty("Authorization", "Token " + token); - if (body != null) { - c.setDoOutput(true); - c.setRequestProperty("Content-Type", "application/json; charset=utf-8"); - OutputStream o = c.getOutputStream(); - o.write(body.toString().getBytes("UTF-8")); - o.close(); - } - int st = c.getResponseCode(); - InputStream in = st >= 400 ? c.getErrorStream() : c.getInputStream(); - String text = in == null ? "" : new String(Net.readAll(in), "UTF-8"); - JSONObject res; - try { - res = new JSONObject(text); - } catch (Exception e) { - res = new JSONObject(); - } - if (st >= 400) { - throw new HttpError(st, "ListenBrainz: " + res.optString("error", "HTTP " + st)); - } - return res; - } catch (HttpError e) { - throw e; - } catch (Exception e) { - throw new HttpError(0, "ListenBrainz: " + e.getMessage()); - } finally { - if (c != null) { - c.disconnect(); - } - } - } - - /** Checks a token; gives the user name. */ - public static String validate(String token) throws Exception { - JSONObject r = http("GET", "validate-token", token.trim(), null); - if (!r.optBoolean("valid", false)) { - throw new Exception(r.optString("message", "Token not valid")); - } - return r.optString("user_name", ""); - } - - public static void connect(final String token, final LastFm.Cb cb) { - App.IO.execute(new Runnable() { - @Override - public void run() { - String err = null; - try { - String name = validate(token); - App.I.prefs.setStr(Prefs.LB_TOKEN, token.trim()); - App.I.prefs.setStr(Prefs.LB_USER, name); - App.I.prefs.setBool(Prefs.LB_ENABLED, true); - } catch (Exception e) { - err = e.getMessage(); - } - final String msg = err; - App.ui(new Runnable() { - @Override - public void run() { - cb.done(msg); - } - }); - if (msg == null) { - LastFm.flush(); - } - } - }); - } - - public static void disconnect() { - App.I.prefs.setStr(Prefs.LB_TOKEN, ""); - App.I.prefs.setStr(Prefs.LB_USER, ""); - App.I.prefs.setBool(Prefs.LB_ENABLED, false); - LastFm.purge("listenbrainz"); - } - - // ---------------------------------------------------------------- ids from the file's tags - - static String clean(String s) { - return s == null ? "" : s.trim(); - } - - static void putIds(JSONObject out, String name, String raw, boolean many) throws Exception { - JSONArray arr = new JSONArray(); - for (String p : clean(raw).split("[/;,\\u0000]")) { - p = p.trim(); - if (p.length() == 36) { - arr.put(p); - } - } - if (arr.length() > 0) { - out.put(name, many ? arr : arr.get(0)); - } - } - - /** MusicBrainz ids, ISRC, disc and genre from a local file, named like ListenBrainz additional_info. */ - public static JSONObject fileInfo(Song s) { - JSONObject out = new JSONObject(); - try { - if (s.isStream() || s.path == null || s.path.length() == 0) { - return out; - } - File f = new File(s.path); - if (!f.canRead()) { - return out; - } - String rec, rel, rg, rtrack, art, relart, work, isrc, disc, genre; - String ext = TagCore.extOf(f); - if (TagCore.isOpus(f, ext)) { - java.util.Map v = new java.util.HashMap<>(); - RandomAccessFile raf = new RandomAccessFile(f, "r"); - try { - for (String item : OggOpus.parse(OggOpus.layout(raf).tags).items) { - int i = item.indexOf('='); - if (i > 0) { - String k = item.substring(0, i).toUpperCase(); - String old = v.get(k); - v.put(k, old == null ? item.substring(i + 1) : old + "/" + item.substring(i + 1)); - } - } - } finally { - raf.close(); - } - rec = v.get("MUSICBRAINZ_TRACKID"); - rel = v.get("MUSICBRAINZ_ALBUMID"); - rg = v.get("MUSICBRAINZ_RELEASEGROUPID"); - rtrack = v.get("MUSICBRAINZ_RELEASETRACKID"); - art = v.get("MUSICBRAINZ_ARTISTID"); - relart = v.get("MUSICBRAINZ_ALBUMARTISTID"); - work = v.get("MUSICBRAINZ_WORKID"); - isrc = v.get("ISRC"); - disc = v.get("DISCNUMBER"); - genre = v.get("GENRE"); - } else { - Tag t = AudioFileIO.read(f).getTag(); - if (t == null) { - return out; - } - rec = TagCore.first(t, FieldKey.MUSICBRAINZ_TRACK_ID); - rel = TagCore.first(t, FieldKey.MUSICBRAINZ_RELEASEID); - rg = TagCore.first(t, FieldKey.MUSICBRAINZ_RELEASE_GROUP_ID); - rtrack = null; - art = TagCore.first(t, FieldKey.MUSICBRAINZ_ARTISTID); - relart = TagCore.first(t, FieldKey.MUSICBRAINZ_RELEASEARTISTID); - work = TagCore.first(t, FieldKey.MUSICBRAINZ_WORK_ID); - isrc = TagCore.first(t, FieldKey.ISRC); - disc = TagCore.first(t, FieldKey.DISC_NO); - genre = TagCore.first(t, FieldKey.GENRE); - } - putIds(out, "recording_mbid", rec, false); - putIds(out, "release_mbid", rel, false); - putIds(out, "release_group_mbid", rg, false); - putIds(out, "track_mbid", rtrack, false); - putIds(out, "artist_mbids", art, true); - putIds(out, "release_artist_mbids", relart, true); - putIds(out, "work_mbids", work, true); - if (clean(isrc).length() > 0) { - out.put("isrc", clean(isrc)); - } - String d = clean(disc).split("/")[0]; - if (d.matches("\\d+") && Integer.parseInt(d) > 0) { - out.put("discnumber", Integer.parseInt(d)); - } - JSONArray tags = new JSONArray(); - for (String g : clean(genre).split("[;/,]")) { - if (g.trim().length() > 0) { - tags.put(g.trim()); - } - } - if (tags.length() > 0) { - out.put("tags", tags); - } - } catch (Throwable e) { - } - return out; - } - - static String version() { - try { - return App.I.getPackageManager().getPackageInfo(App.I.getPackageName(), 0).versionName; - } catch (Exception e) { - return ""; - } - } - - /** One listen: https://listenbrainz.readthedocs.io/en/latest/users/json.html */ - public static JSONObject payload(Song s, long ts) throws Exception { - JSONObject info = fileInfo(s); - String v = version(); - info.put("media_player", "Mulberry Android"); - info.put("media_player_version", v); - info.put("submission_client", "Mulberry Android"); - info.put("submission_client_version", v); - if (s.duration > 0) { - info.put("duration_ms", s.duration); - } - if (s.track > 0) { - info.put("tracknumber", s.track); - } - if (s.albumArtist.length() > 0) { - info.put("release_artist_name", s.albumArtist); - } - if (s.isStream()) { - info.put("origin_url", s.uri); - String host = s.uri.replaceFirst("^[a-z]+://", "").split("[/:?]")[0].replaceFirst("^www\\.", ""); - if (host.length() > 0) { - info.put("music_service", host); - } - } - JSONObject meta = new JSONObject(); - meta.put("artist_name", s.displayArtist()); - meta.put("track_name", s.displayTitle()); - if (s.album.length() > 0 && !s.isStream()) { - meta.put("release_name", s.album); - } - meta.put("additional_info", info); - JSONObject p = new JSONObject(); - p.put("track_metadata", meta); - if (ts > 0) { - p.put("listened_at", ts); - } - return p; - } - - public static void submit(String type, JSONArray payload) throws HttpError { - try { - JSONObject body = new JSONObject(); - body.put("listen_type", type); - body.put("payload", payload); - http("POST", "submit-listens", App.I.prefs.getStr(Prefs.LB_TOKEN, ""), body); - } catch (HttpError e) { - throw e; - } catch (Exception e) { - throw new HttpError(0, e.getMessage()); - } - } - - public static void nowPlaying(final Song song) { - if (!enabled() || song == null || song.displayArtist().length() == 0) { - return; - } - App.IO.execute(new Runnable() { - @Override - public void run() { - try { - submit("playing_now", new JSONArray().put(payload(song, 0))); - } catch (Exception e) { - } - } - }); - } - - public static void love(final Song song, final boolean on) { - if (!enabled()) { - return; - } - App.IO.execute(new Runnable() { - @Override - public void run() { - String mbid = fileInfo(song).optString("recording_mbid", ""); - if (mbid.length() == 0) { - return; - } - try { - JSONObject b = new JSONObject(); - b.put("recording_mbid", mbid); - b.put("score", on ? 1 : 0); - http("POST", "feedback/recording-feedback", App.I.prefs.getStr(Prefs.LB_TOKEN, ""), b); - } catch (Exception e) { - } - } - }); - } -} diff --git a/android/src/com/mulberry/player/Lists.java b/android/src/com/mulberry/player/Lists.java deleted file mode 100644 index f4cbc0e..0000000 --- a/android/src/com/mulberry/player/Lists.java +++ /dev/null @@ -1,396 +0,0 @@ -package com.mulberry.player; - -import android.app.Dialog; -import android.content.Context; -import android.content.res.ColorStateList; -import android.graphics.Bitmap; -import android.graphics.drawable.ColorDrawable; -import android.graphics.drawable.GradientDrawable; -import android.view.View; -import android.view.ViewGroup; -import android.view.Window; -import android.widget.BaseAdapter; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.ScrollView; -import android.widget.TextView; -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.List; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; - -/* JADX INFO: loaded from: classes.dex */ -public final class Lists { - - public interface GroupClick { - void click(Library.Group group); - - void longClick(Library.Group group); - } - - public interface SongClick { - void click(List list, int i); - - void longClick(List list, int i, View view); - } - - private Lists() { - } - - static ImageView coverView(Context context, int i, float f) { - ImageView imageView = new ImageView(context); - imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); - imageView.setLayoutParams(new LinearLayout.LayoutParams(Ui.dp(context, i), Ui.dp(context, i))); - imageView.setBackground(Ui.round(Ui.c(10), Ui.dpf(context, f))); - imageView.setClipToOutline(true); - return imageView; - } - - static void bindCover(final ImageView imageView, final Song song, int i) { - imageView.setTag(song); - Bitmap bitmapCached = Covers.cached(song, i); - if (bitmapCached == null) { - placeholder(imageView); - final WeakReference weakReference = new WeakReference(imageView); - Covers.loadThumb(song, i, new Covers.Wanted() { // from class: com.mulberry.player.Lists.1 - @Override // com.mulberry.player.Covers.Wanted - public boolean still() { - ImageView imageView2 = (ImageView) weakReference.get(); - return imageView2 != null && imageView2.getTag() == song; - } - }, new Covers.Cb() { // from class: com.mulberry.player.Lists.2 - @Override // com.mulberry.player.Covers.Cb - public void done(Bitmap bitmap) { - if (imageView.getTag() == song && bitmap != null) { - imageView.setPadding(0, 0, 0, 0); - imageView.setImageTintList(null); - imageView.setImageBitmap(bitmap); - if (!App.lowPower()) { - imageView.setAlpha(0.0f); - imageView.animate().alpha(1.0f).setDuration(180L).start(); - } - } - } - }); - } else { - imageView.setImageBitmap(bitmapCached); - imageView.setPadding(0, 0, 0, 0); - } - } - - static void placeholder(ImageView imageView) { - int i = imageView.getLayoutParams() != null ? imageView.getLayoutParams().width / 4 : 12; - imageView.setPadding(i, i, i, i); - imageView.setImageResource(R.drawable.ic_music_note); - imageView.setImageTintList(ColorStateList.valueOf(Ui.c(12))); - imageView.setBackground(Ui.round(Ui.c(10), Ui.dpf(imageView.getContext(), 12.0f))); - } - - public static class SongAdapter extends BaseAdapter { - final SongClick click; - final Context ctx; - List items = new ArrayList(); - public boolean numbers; - public Song playing; - - public SongAdapter(Context context, SongClick songClick) { - this.ctx = context; - this.click = songClick; - } - - public void set(List list) { - if (list == null) { - list = new ArrayList<>(); - } - this.items = list; - notifyDataSetChanged(); - } - - @Override // android.widget.Adapter - public int getCount() { - return this.items.size(); - } - - @Override // android.widget.Adapter - public Object getItem(int i) { - return this.items.get(i); - } - - @Override // android.widget.Adapter - public long getItemId(int i) { - return i; - } - - static final class H { - ImageView cover; - TextView dur; - ImageView more; - TextView num; - TextView sub; - TextView title; - - H() { - } - } - - @Override // android.widget.Adapter - public View getView(final int i, View view, ViewGroup viewGroup) { - H h; - View view2; - if (view == null) { - LinearLayout linearLayoutRow = Ui.row(this.ctx); - int iDp = Ui.dp(this.ctx, 8.0f); - linearLayoutRow.setPadding(Ui.dp(this.ctx, 12.0f), iDp, Ui.dp(this.ctx, 4.0f), iDp); - Ui.clickable(linearLayoutRow, 18.0f); - H h2 = new H(); - h2.num = Ui.single(this.ctx, FrameBodyCOMM.DEFAULT, 13.0f, 12, true); - h2.num.setGravity(17); - h2.num.setLayoutParams(new LinearLayout.LayoutParams(Ui.dp(this.ctx, 28.0f), -2)); - linearLayoutRow.addView(h2.num); - h2.cover = Lists.coverView(this.ctx, 48, 12.0f); - linearLayoutRow.addView(h2.cover); - LinearLayout linearLayoutCol = Ui.col(this.ctx); - linearLayoutCol.setPadding(Ui.dp(this.ctx, 14.0f), 0, Ui.dp(this.ctx, 8.0f), 0); - h2.title = Ui.single(this.ctx, FrameBodyCOMM.DEFAULT, 15.5f, 11, true); - h2.sub = Ui.single(this.ctx, FrameBodyCOMM.DEFAULT, 13.0f, 12, false); - linearLayoutCol.addView(h2.title); - linearLayoutCol.addView(h2.sub); - linearLayoutRow.addView(linearLayoutCol, Ui.lpw(-2, 1.0f)); - h2.dur = Ui.single(this.ctx, FrameBodyCOMM.DEFAULT, 12.0f, 12, false); - linearLayoutRow.addView(h2.dur); - h2.more = Ui.iconButton(this.ctx, R.drawable.ic_more_vert, 12, 40, null); - linearLayoutRow.addView(h2.more); - linearLayoutRow.setTag(h2); - h = h2; - view2 = linearLayoutRow; - } else { - h = (H) view.getTag(); - view2 = view; - } - Song song = this.items.get(i); - boolean z = this.playing != null && this.playing.key().equals(song.key()); - h.title.setText(song.displayTitle()); - h.title.setTextColor(z ? Ui.c(0) : Ui.c(11)); - String strDisplayArtist = song.displayArtist(); - if (!this.numbers && song.album.length() > 0) { - strDisplayArtist = strDisplayArtist.length() > 0 ? strDisplayArtist + " · " + song.album : song.album; - } - h.sub.setText(strDisplayArtist); - h.dur.setText(song.duration > 0 ? Draw.time(song.duration) : FrameBodyCOMM.DEFAULT); - h.num.setVisibility(this.numbers ? 0 : 8); - h.cover.setVisibility(this.numbers ? 8 : 0); - if (this.numbers) { - h.num.setText(song.track > 0 ? String.valueOf(song.track) : "–"); - } else { - Lists.bindCover(h.cover, song, 160); - } - final List list = this.items; - view2.setOnClickListener(new View.OnClickListener() { // from class: com.mulberry.player.Lists.SongAdapter.1 - @Override // android.view.View.OnClickListener - public void onClick(View view3) { - SongAdapter.this.click.click(list, i); - } - }); - view2.setOnLongClickListener(new View.OnLongClickListener() { // from class: com.mulberry.player.Lists.SongAdapter.2 - @Override // android.view.View.OnLongClickListener - public boolean onLongClick(View view3) { - SongAdapter.this.click.longClick(list, i, view3); - return true; - } - }); - h.more.setOnClickListener(new View.OnClickListener() { // from class: com.mulberry.player.Lists.SongAdapter.3 - @Override // android.view.View.OnClickListener - public void onClick(View view3) { - SongAdapter.this.click.longClick(list, i, view3); - } - }); - return view2; - } - } - - public static class GroupAdapter extends BaseAdapter { - final GroupClick click; - final Context ctx; - List items = new ArrayList(); - public int icon = R.drawable.ic_album; - - public GroupAdapter(Context context, GroupClick groupClick) { - this.ctx = context; - this.click = groupClick; - } - - public void set(List list) { - if (list == null) { - list = new ArrayList<>(); - } - this.items = list; - notifyDataSetChanged(); - } - - @Override // android.widget.Adapter - public int getCount() { - return this.items.size(); - } - - @Override // android.widget.Adapter - public Object getItem(int i) { - return this.items.get(i); - } - - @Override // android.widget.Adapter - public long getItemId(int i) { - return i; - } - - static final class H { - ImageView cover; - TextView sub; - TextView title; - - H() { - } - } - - @Override // android.widget.Adapter - public View getView(int i, View view, ViewGroup viewGroup) { - H h; - View view2; - if (view == null) { - LinearLayout linearLayoutRow = Ui.row(this.ctx); - int iDp = Ui.dp(this.ctx, 8.0f); - linearLayoutRow.setPadding(Ui.dp(this.ctx, 12.0f), iDp, Ui.dp(this.ctx, 12.0f), iDp); - Ui.clickable(linearLayoutRow, 18.0f); - h = new H(); - h.cover = Lists.coverView(this.ctx, 56, this.icon == R.drawable.ic_artist ? 28.0f : 14.0f); - linearLayoutRow.addView(h.cover); - LinearLayout linearLayoutCol = Ui.col(this.ctx); - linearLayoutCol.setPadding(Ui.dp(this.ctx, 14.0f), 0, 0, 0); - h.title = Ui.single(this.ctx, FrameBodyCOMM.DEFAULT, 16.0f, 11, true); - h.sub = Ui.single(this.ctx, FrameBodyCOMM.DEFAULT, 13.0f, 12, false); - linearLayoutCol.addView(h.title); - linearLayoutCol.addView(h.sub); - linearLayoutRow.addView(linearLayoutCol, Ui.lpw(-2, 1.0f)); - linearLayoutRow.setTag(h); - view2 = linearLayoutRow; - } else { - h = (H) view.getTag(); - view2 = view; - } - final Library.Group group = this.items.get(i); - h.title.setText(group.title); - h.sub.setText(group.subtitle); - if (this.icon == R.drawable.ic_folder) { - h.cover.setTag(null); - h.cover.setImageResource(R.drawable.ic_folder); - int iDp2 = Ui.dp(this.ctx, 14.0f); - h.cover.setPadding(iDp2, iDp2, iDp2, iDp2); - h.cover.setImageTintList(ColorStateList.valueOf(Ui.c(5))); - h.cover.setBackground(Ui.round(Ui.c(4), Ui.dpf(this.ctx, 14.0f))); - } else if (!group.songs.isEmpty()) { - h.cover.setBackground(Ui.round(Ui.c(10), Ui.dpf(this.ctx, this.icon != R.drawable.ic_artist ? 14.0f : 28.0f))); - Lists.bindCover(h.cover, group.songs.get(0), 160); - } - view2.setOnClickListener(new View.OnClickListener() { // from class: com.mulberry.player.Lists.GroupAdapter.1 - @Override // android.view.View.OnClickListener - public void onClick(View view3) { - GroupAdapter.this.click.click(group); - } - }); - view2.setOnLongClickListener(new View.OnLongClickListener() { // from class: com.mulberry.player.Lists.GroupAdapter.2 - @Override // android.view.View.OnLongClickListener - public boolean onLongClick(View view3) { - GroupAdapter.this.click.longClick(group); - return true; - } - }); - return view2; - } - } - - public static ListView list(Context context) { - ListView listView = new ListView(context); - listView.setDivider(null); - listView.setSelector(new ColorDrawable(0)); - listView.setClipToPadding(false); - listView.setFastScrollEnabled(true); - listView.setVerticalScrollBarEnabled(false); - listView.setOverScrollMode(1); - listView.setCacheColorHint(0); - return listView; - } - - public static final class Item { - final Runnable action; - final int icon; - final String label; - - public Item(int i, String str, Runnable runnable) { - this.icon = i; - this.label = str; - this.action = runnable; - } - } - - public static Dialog sheet(Context context, String str, String str2, List list) { - final Dialog dialog = new Dialog(context); - dialog.requestWindowFeature(1); - LinearLayout linearLayoutCol = Ui.col(context); - linearLayoutCol.setPadding(Ui.dp(context, 8.0f), Ui.dp(context, 10.0f), Ui.dp(context, 8.0f), Ui.dp(context, 18.0f)); - GradientBg(linearLayoutCol, context); - View view = new View(context); - view.setBackground(Ui.round(Ui.c(14), Ui.dpf(context, 2.0f))); - LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Ui.dp(context, 36.0f), Ui.dp(context, 4.0f)); - layoutParams.gravity = 1; - layoutParams.bottomMargin = Ui.dp(context, 10.0f); - linearLayoutCol.addView(view, layoutParams); - if (str != null) { - TextView textViewSingle = Ui.single(context, str, 17.0f, 11, true); - textViewSingle.setPadding(Ui.dp(context, 16.0f), 0, Ui.dp(context, 16.0f), 0); - linearLayoutCol.addView(textViewSingle); - } - if (str2 != null && str2.length() > 0) { - TextView textViewSingle2 = Ui.single(context, str2, 13.0f, 12, false); - textViewSingle2.setPadding(Ui.dp(context, 16.0f), Ui.dp(context, 2.0f), Ui.dp(context, 16.0f), Ui.dp(context, 8.0f)); - linearLayoutCol.addView(textViewSingle2); - } - for (final Item item : list) { - LinearLayout linearLayoutRow = Ui.row(context); - linearLayoutRow.setPadding(Ui.dp(context, 16.0f), Ui.dp(context, 13.0f), Ui.dp(context, 16.0f), Ui.dp(context, 13.0f)); - Ui.clickable(linearLayoutRow, 16.0f); - linearLayoutRow.addView(Ui.icon(context, item.icon, 12, 22)); - TextView textViewSingle3 = Ui.single(context, item.label, 15.0f, 11, false); - textViewSingle3.setPadding(Ui.dp(context, 18.0f), 0, 0, 0); - linearLayoutRow.addView(textViewSingle3); - linearLayoutRow.setOnClickListener(new View.OnClickListener() { // from class: com.mulberry.player.Lists.3 - @Override // android.view.View.OnClickListener - public void onClick(View view2) { - dialog.dismiss(); - item.action.run(); - } - }); - linearLayoutCol.addView(linearLayoutRow); - } - ScrollView scrollView = new ScrollView(context); - scrollView.addView(linearLayoutCol); - dialog.setContentView(scrollView); - Window window = dialog.getWindow(); - if (window != null) { - window.setBackgroundDrawable(new ColorDrawable(0)); - window.setGravity(80); - window.setLayout(-1, -2); - window.setWindowAnimations(android.R.style.Animation_InputMethod); - window.setDimAmount(0.35f); - } - dialog.show(); - return dialog; - } - - static void GradientBg(View view, Context context) { - GradientDrawable gradientDrawable = new GradientDrawable(); - gradientDrawable.setColor(Ui.c(8)); - float fDpf = Ui.dpf(context, 28.0f); - gradientDrawable.setCornerRadii(new float[]{fDpf, fDpf, fDpf, fDpf, 0.0f, 0.0f, 0.0f, 0.0f}); - view.setBackground(gradientDrawable); - } -} diff --git a/android/src/com/mulberry/player/Lyrics.java b/android/src/com/mulberry/player/Lyrics.java deleted file mode 100644 index eb346b9..0000000 --- a/android/src/com/mulberry/player/Lyrics.java +++ /dev/null @@ -1,456 +0,0 @@ -package com.mulberry.player; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; -import org.jaudiotagger.tag.mp4.atom.Mp4NameBox; -import org.json.JSONArray; -import org.json.JSONObject; - -/* JADX INFO: loaded from: classes.dex */ -public final class Lyrics { - private static final Pattern TS = Pattern.compile("\\[(\\d+):(\\d+(?:[.:]\\d+)?)\\]"); - private static final Pattern CREDIT = Pattern.compile("^\\s*\\[[^\\]]*\\]\\s*(作词|作曲|编曲|制作人|监制|混音|母带|词|曲|Lyricist|Lyrics by|Composer|Composed by|Arranger|Producer|Written by)\\s*[::].*", 2); - private static final Map NE_HEADERS = new HashMap(); - - public interface Cb { - void done(Result result); - } - - public static final class Result { - public boolean synced; - public List lines = new ArrayList(); - public String source = FrameBodyCOMM.DEFAULT; - public String message = FrameBodyCOMM.DEFAULT; - } - - public static final class Line { - public final long ms; - public final String text; - - Line(long j, String str) { - this.ms = j; - this.text = str; - } - } - - static { - NE_HEADERS.put("Referer", "https://music.163.com/"); - NE_HEADERS.put("User-Agent", "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 Chrome/124.0 Mobile Safari/537.36"); - } - - public static Result parse(String str, boolean z) { - ArrayList arrayList; - ArrayList arrayList2; - Result result = new Result(); - if (str == null) { - return result; - } - Matcher matcher = Pattern.compile("\\[offset:\\s*([-+]?\\d+)\\]", 2).matcher(str); - long j = matcher.find() ? Long.parseLong(matcher.group(1)) : 0L; - ArrayList arrayList3 = new ArrayList(); - boolean z2 = false; - String[] strArrSplit = str.split("\\r?\\n"); - int length = strArrSplit.length; - int i = 0; - while (i < length) { - String str2 = strArrSplit[i]; - Matcher matcher2 = TS.matcher(str2); - ArrayList arrayList4 = new ArrayList(); - while (matcher2.find()) { - arrayList4.add(Long.valueOf(((long) ((Double.parseDouble(matcher2.group(2).replace(':', '.')) * 1000.0d) + (((long) Integer.parseInt(matcher2.group(1))) * 60000))) - j)); - } - String strTrim = TS.matcher(str2).replaceAll(FrameBodyCOMM.DEFAULT).replaceAll("<\\d+:\\d+(?:\\.\\d+)?>", FrameBodyCOMM.DEFAULT).trim(); - if (!arrayList4.isEmpty()) { - z2 = true; - Iterator it = arrayList4.iterator(); - while (it.hasNext()) { - arrayList3.add(new Line(Math.max(0L, ((Long) it.next()).longValue()), strTrim)); - } - } else if (!str2.trim().matches("^\\[[a-zA-Z]+:.*\\]$")) { - arrayList3.add(new Line(-1L, str2.trim())); - } - i++; - z2 = z2; - } - if (z2) { - ArrayList arrayList5 = new ArrayList(); - for (Line line : arrayList3) { - if (line.ms >= 0) { - arrayList5.add(line); - } - } - Collections.sort(arrayList5, new Comparator() { // from class: com.mulberry.player.Lyrics.1 - @Override // java.util.Comparator - public int compare(Line line2, Line line3) { - return Long.compare(line2.ms, line3.ms); - } - }); - arrayList = arrayList5; - } else { - arrayList = arrayList3; - } - if (z && z2) { - arrayList2 = new ArrayList(); - Iterator it2 = arrayList.iterator(); - while (it2.hasNext()) { - arrayList2.add(new Line(-1L, ((Line) it2.next()).text)); - } - z2 = false; - } else { - arrayList2 = arrayList; - } - while (!arrayList2.isEmpty() && ((Line) arrayList2.get(0)).text.length() == 0 && !z2) { - arrayList2.remove(0); - } - result.lines = arrayList2; - result.synced = z2; - return result; - } - - static boolean isSynced(String str) { - return str != null && TS.matcher(str).find(); - } - - static String clean(String str) { - return str == null ? FrameBodyCOMM.DEFAULT : str.replaceAll("(?i)\\s*[(\\[](feat\\.?|ft\\.?|with|remaster(ed)?|\\d{4} remaster|live|explicit|bonus)[^)\\]]*[)\\]]", FrameBodyCOMM.DEFAULT).trim(); - } - - static String norm(String str) { - return str == null ? FrameBodyCOMM.DEFAULT : str.toLowerCase().replaceAll("[^\\p{L}\\p{N}]", FrameBodyCOMM.DEFAULT); - } - - static String lrclib(Song song) throws Exception { - JSONObject jSONObject; - String str = "artist_name=" + Net.enc(song.displayArtist()) + "&track_name=" + Net.enc(clean(song.displayTitle())); - String str2 = Net.get("https://lrclib.net/api/get?" + (str + (song.album.length() > 0 ? "&album_name=" + Net.enc(song.album) : FrameBodyCOMM.DEFAULT) + (song.duration > 0 ? "&duration=" + Math.round(song.duration / 1000.0d) : FrameBodyCOMM.DEFAULT)), null); - if (str2.startsWith("{")) { - JSONObject jSONObject2 = new JSONObject(str2); - if (jSONObject2.optBoolean("instrumental")) { - return "[instrumental]"; - } - String strOptString = jSONObject2.optString("syncedLyrics", FrameBodyCOMM.DEFAULT); - if (strOptString.length() == 0 || "null".equals(strOptString)) { - strOptString = jSONObject2.optString("plainLyrics", FrameBodyCOMM.DEFAULT); - } - if (strOptString.length() > 0 && !"null".equals(strOptString)) { - return strOptString; - } - } - String str3 = Net.get("https://lrclib.net/api/search?" + str, null); - if (!str3.startsWith("[")) { - return FrameBodyCOMM.DEFAULT; - } - JSONArray jSONArray = new JSONArray(str3); - JSONObject jSONObject3 = null; - int i = 0; - while (true) { - int i2 = i; - if (i2 >= jSONArray.length()) { - jSONObject = jSONObject3; - break; - } - jSONObject = jSONArray.getJSONObject(i2); - if (song.duration <= 0 || jSONObject.optDouble("duration", 0.0d) <= 0.0d || Math.abs(jSONObject.optDouble("duration") - (song.duration / 1000.0d)) <= 6.0d) { - String strOptString2 = jSONObject.optString("syncedLyrics", FrameBodyCOMM.DEFAULT); - if (strOptString2.length() > 0 && !"null".equals(strOptString2)) { - break; - } - if (jSONObject3 == null) { - jSONObject3 = jSONObject; - } - } - i = i2 + 1; - } - if (jSONObject == null) { - return FrameBodyCOMM.DEFAULT; - } - String strOptString3 = jSONObject.optString("syncedLyrics", FrameBodyCOMM.DEFAULT); - return (strOptString3.length() <= 0 || "null".equals(strOptString3)) ? jSONObject.optString("plainLyrics", FrameBodyCOMM.DEFAULT) : strOptString3; - } - - static String netease(Song song) throws Exception { - JSONObject jSONObjectOptJSONObject = new JSONObject(Net.get("https://music.163.com/api/cloudsearch/pc?type=1&offset=0&limit=10&s=" + Net.enc((clean(song.displayTitle()) + " " + song.displayArtist()).trim()), NE_HEADERS)).optJSONObject("result"); - JSONArray jSONArrayOptJSONArray = jSONObjectOptJSONObject != null ? jSONObjectOptJSONObject.optJSONArray("songs") : null; - if (jSONArrayOptJSONArray == null) { - return FrameBodyCOMM.DEFAULT; - } - JSONObject jSONObject = null; - double d = -1.0E9d; - int i = 0; - while (i < jSONArrayOptJSONArray.length()) { - JSONObject jSONObject2 = jSONArrayOptJSONArray.getJSONObject(i); - double dMin = 0.0d; - StringBuilder sb = new StringBuilder(); - JSONArray jSONArrayOptJSONArray2 = jSONObject2.optJSONArray("ar"); - for (int i2 = 0; jSONArrayOptJSONArray2 != null && i2 < jSONArrayOptJSONArray2.length(); i2++) { - sb.append(jSONArrayOptJSONArray2.getJSONObject(i2).optString(Mp4NameBox.IDENTIFIER)).append(' '); - } - String strNorm = norm(sb.toString()); - String strNorm2 = norm(song.displayArtist()); - if (strNorm2.length() > 0 && (strNorm.contains(strNorm2) || strNorm2.contains(strNorm))) { - dMin = 0.0d + 50.0d; - } - if (norm(clean(song.displayTitle())).equals(norm(clean(jSONObject2.optString(Mp4NameBox.IDENTIFIER))))) { - dMin += 30.0d; - } - long jOptLong = jSONObject2.optLong("dt"); - if (song.duration > 0 && jOptLong > 0) { - dMin -= Math.min(40.0d, (Math.abs(jOptLong - song.duration) / 1000.0d) * 4.0d); - } - if (dMin <= d) { - dMin = d; - jSONObject2 = jSONObject; - } - i++; - d = dMin; - jSONObject = jSONObject2; - } - if (jSONObject == null || d < 0.0d) { - return FrameBodyCOMM.DEFAULT; - } - JSONObject jSONObjectOptJSONObject2 = new JSONObject(Net.get("https://music.163.com/api/song/lyric?lv=1&kv=1&tv=-1&id=" + jSONObject.optLong("id"), NE_HEADERS)).optJSONObject("lrc"); - String strOptString = jSONObjectOptJSONObject2 != null ? jSONObjectOptJSONObject2.optString("lyric", FrameBodyCOMM.DEFAULT) : FrameBodyCOMM.DEFAULT; - StringBuilder sb2 = new StringBuilder(); - String[] strArrSplit = strOptString.split("\n"); - for (String str : strArrSplit) { - if (!CREDIT.matcher(str).matches()) { - sb2.append(str).append('\n'); - } - } - return sb2.toString().trim(); - } - - static String local(Song song) { - if (song.path.length() == 0) { - return FrameBodyCOMM.DEFAULT; - } - int iLastIndexOf = song.path.lastIndexOf(46); - String strSubstring = iLastIndexOf > 0 ? song.path.substring(0, iLastIndexOf) : song.path; - for (String str : new String[]{".lrc", ".LRC", ".txt"}) { - File file = new File(strSubstring + str); - if (file.canRead()) { - try { - return new String(Net.readAll(new FileInputStream(file)), "UTF-8"); - } catch (Exception e) { - } - } - } - File file2 = new File(song.path); - String strSubstring2 = song.path.substring(song.path.lastIndexOf(46) + 1); - if (file2.canRead() && file2.length() < 83886080 && TagCore.canWrite(strSubstring2)) { - try { - return TagCore.read(file2).lyrics; - } catch (Throwable th) { - } - } - return FrameBodyCOMM.DEFAULT; - } - - static File cacheFile(Song song, String str) { - File file = new File(App.I.getCacheDir(), "lyrics"); - file.mkdirs(); - return new File(file, Integer.toHexString((song.displayArtist() + "|" + song.displayTitle() + "|" + song.album + "|" + str).toLowerCase().hashCode()) + ".lrc"); - } - - static String readCache(Song song, String str) { - File fileCacheFile = cacheFile(song, str); - if (!fileCacheFile.exists()) { - return null; - } - try { - return new String(Net.readAll(new FileInputStream(fileCacheFile)), "UTF-8"); - } catch (Exception e) { - return null; - } - } - - static void writeCache(Song song, String str, String str2) { - try { - FileOutputStream fileOutputStream = new FileOutputStream(cacheFile(song, str)); - if (str2 == null) { - str2 = FrameBodyCOMM.DEFAULT; - } - fileOutputStream.write(str2.getBytes("UTF-8")); - fileOutputStream.close(); - } catch (Exception e) { - } - } - - public static void clearCache(Song song, String str) { - cacheFile(song, str).delete(); - } - - public static void load(final Song song, final boolean z, final Cb cb) { - App.IO.execute(new Runnable() { // from class: com.mulberry.player.Lyrics.2 - @Override // java.lang.Runnable - public void run() { - Result resultV; - try { - resultV = Lyrics.loadBlocking(song, z); - } catch (Throwable th) { - resultV = new Result(); - resultV.message = "Couldn't load lyrics"; - } - final Result result = resultV; - App.ui(new Runnable() { // from class: com.mulberry.player.Lyrics.2.1 - @Override // java.lang.Runnable - public void run() { - cb.done(result); - } - }); - } - }); - } - - // Rewritten by hand: the decompiler could not rebuild this method. - public static Result loadBlocking(Song song, boolean z) { - Prefs prefs = App.I.prefs; - String src = prefs.getStr(Prefs.LYRICS_SOURCE, "auto"); - boolean plain = prefs.getBool(Prefs.LYRICS_PLAIN, false); - boolean online = prefs.getBool(Prefs.ONLINE_LYRICS, true); - Result result2 = new Result(); - if (song == null) { - return result2; - } - String text = ""; - String source = ""; - try { - if ("local".equals(src)) { - text = local(song); - source = "Local .lrc"; - if (text.length() == 0) { - result2.message = "No .lrc file or embedded lyrics for this song.\nGive Mulberry “All files access” in Settings, or pick another source."; - } - } else if ("lrclib".equals(src) || "netease".equals(src)) { - source = "lrclib".equals(src) ? "LRCLIB" : "NetEase"; - try { - String cache = z ? null : readCache(song, src); - if (cache == null) { - if (!online) { - cache = ""; - } else { - cache = "lrclib".equals(src) ? lrclib(song) : netease(song); - writeCache(song, src, cache); - } - } - text = cache; - if (text.length() == 0) { - result2.message = source + " has no lyrics for this song."; - } - } catch (Exception e) { - text = ""; - result2.message = "Couldn't reach the lyrics service"; - } - } else { - String name; - String body; - String cache2 = z ? null : readCache(song, "auto"); - if (cache2 != null) { - int nl = cache2.indexOf(10); - name = nl > 0 ? cache2.substring(0, nl) : ""; - body = nl > 0 ? cache2.substring(nl + 1) : ""; - } else if (!online) { - name = ""; - body = ""; - } else { - boolean ok; - String lrc; - String lrcName; - try { - lrc = lrclib(song); - lrcName = "LRCLIB"; - ok = true; - } catch (Exception e2) { - lrc = ""; - lrcName = ""; - ok = false; - } - if (!isSynced(lrc) && !"[instrumental]".equals(lrc)) { - try { - String ne = netease(song); - if (isSynced(ne) || lrc.length() == 0) { - lrcName = "NetEase"; - lrc = ne; - } - ok = true; - } catch (Exception e4) { - } - } - if (ok) { - writeCache(song, "auto", lrcName + "\n" + lrc); - } - name = lrcName; - body = lrc; - } - String[][] cands = {new String[]{body, name}, new String[]{local(song), "Local .lrc"}}; - for (String[] c : cands) { - if (isSynced(c[0]) || "[instrumental]".equals(c[0])) { - text = c[0]; - source = c[1]; - break; - } - } - if (text.length() == 0) { - for (String[] c : cands) { - if (c[0].trim().length() > 0) { - text = c[0]; - source = c[1]; - break; - } - } - } - if (text.length() == 0) { - result2.message = online ? "No lyrics found" : "Online lyrics are off (Settings)"; - } - } - } catch (Exception e6) { - } - if ("[instrumental]".equals(text.trim())) { - result2.message = "♪ Instrumental ♪"; - return result2; - } - Result result; - try { - result = parse(text, plain); - } catch (Throwable th) { - result = new Result(); - } - result.source = source; - result.message = result2.message; - if (!result.lines.isEmpty() || result.message.length() != 0) { - return result; - } - result.message = "No lyrics found"; - return result; - } - - public static int lineAt(List list, long j) { - int i; - int i2 = 0; - int size = list.size() - 1; - int i3 = -1; - while (i2 <= size) { - int i4 = (i2 + size) >>> 1; - if (list.get(i4).ms <= 150 + j) { - i = i4; - i2 = i4 + 1; - } else { - i = i3; - size = i4 - 1; - } - i3 = i; - } - return i3; - } -} diff --git a/android/src/com/mulberry/player/LyricsView.java b/android/src/com/mulberry/player/LyricsView.java deleted file mode 100644 index 4581d28..0000000 --- a/android/src/com/mulberry/player/LyricsView.java +++ /dev/null @@ -1,292 +0,0 @@ -package com.mulberry.player; - -import android.content.Context; -import android.graphics.Canvas; -import android.graphics.Typeface; -import android.text.Layout; -import android.text.StaticLayout; -import android.text.TextPaint; -import android.view.GestureDetector; -import android.view.MotionEvent; -import android.view.View; -import android.widget.OverScroller; -import java.util.ArrayList; -import java.util.List; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; - -/* JADX INFO: loaded from: classes.dex */ -public class LyricsView extends View implements Ticker.Client { - private float[] act; - private boolean attached; - public boolean compact; - private int current; - private final GestureDetector gd; - private int layoutW; - private final List layouts; - private List lines; - private long manualUntil; - private String message; - private final TextPaint msgPaint; - private float offset; - private OnSeek onSeek; - private boolean playing; - private final OverScroller scroller; - private long settleUntil; - private String source; - private MusicService svc; - private boolean synced; - private float target; - private boolean ticking; - private float[] tops; - private final TextPaint tp; - - public interface OnSeek { - void seekTo(long j); - } - - public LyricsView(Context context) { - super(context); - this.tp = new TextPaint(1); - this.msgPaint = new TextPaint(1); - this.lines = new ArrayList(); - this.message = FrameBodyCOMM.DEFAULT; - this.source = FrameBodyCOMM.DEFAULT; - this.layouts = new ArrayList(); - this.tops = new float[0]; - this.act = new float[0]; - this.layoutW = -1; - this.current = -1; - this.scroller = new OverScroller(context); - this.tp.setTypeface(Typeface.create("sans-serif", 1)); - this.msgPaint.setTextSize(Ui.dpf(context, 15.0f)); - this.gd = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { // from class: com.mulberry.player.LyricsView.1 - @Override // android.view.GestureDetector.SimpleOnGestureListener, android.view.GestureDetector.OnGestureListener - public boolean onDown(MotionEvent motionEvent) { - LyricsView.this.scroller.forceFinished(true); - return true; - } - - @Override // android.view.GestureDetector.SimpleOnGestureListener, android.view.GestureDetector.OnGestureListener - public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent2, float f, float f2) { - LyricsView.this.manualUntil = System.currentTimeMillis() + 3500; - LyricsView.this.offset = LyricsView.this.clamp(LyricsView.this.offset + f2); - LyricsView.this.target = LyricsView.this.offset; - LyricsView.this.getParent().requestDisallowInterceptTouchEvent(true); - LyricsView.this.invalidate(); - return true; - } - - @Override // android.view.GestureDetector.SimpleOnGestureListener, android.view.GestureDetector.OnGestureListener - public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent2, float f, float f2) { - LyricsView.this.manualUntil = System.currentTimeMillis() + 3500; - LyricsView.this.scroller.fling(0, (int) LyricsView.this.offset, 0, (int) (-f2), 0, 0, 0, (int) LyricsView.this.maxOffset()); - LyricsView.this.ensureTick(); - return true; - } - - @Override // android.view.GestureDetector.SimpleOnGestureListener, android.view.GestureDetector.OnGestureListener - public boolean onSingleTapUp(MotionEvent motionEvent) { - if (!LyricsView.this.synced || LyricsView.this.onSeek == null) { - return false; - } - float y = motionEvent.getY() + LyricsView.this.offset; - for (int i = 0; i < LyricsView.this.tops.length; i++) { - float height = i + 1 < LyricsView.this.tops.length ? LyricsView.this.tops[i + 1] : ((StaticLayout) LyricsView.this.layouts.get(i)).getHeight() + LyricsView.this.tops[i]; - if (y >= LyricsView.this.tops[i] && y < height) { - LyricsView.this.manualUntil = 0L; - LyricsView.this.onSeek.seekTo(((Lyrics.Line) LyricsView.this.lines.get(i)).ms); - return true; - } - } - return false; - } - }); - } - - public void setService(MusicService musicService) { - this.svc = musicService; - } - - public void setOnSeek(OnSeek onSeek) { - this.onSeek = onSeek; - } - - public void setResult(Lyrics.Result result) { - this.lines = result == null ? new ArrayList<>() : result.lines; - this.synced = result != null && result.synced; - this.message = result == null ? "Loading lyrics…" : result.message; - this.source = result == null ? FrameBodyCOMM.DEFAULT : result.source; - this.current = -1; - this.layoutW = -1; - this.target = 0.0f; - this.offset = 0.0f; - this.manualUntil = 0L; - requestLayout(); - invalidate(); - kick(); - } - - public String source() { - return this.source; - } - - public void setPlaying(boolean z) { - this.playing = z; - kick(); - } - - void kick() { - this.settleUntil = System.currentTimeMillis() + 1500; - ensureTick(); - } - - void ensureTick() { - boolean z = this.attached && isShown() && getWindowVisibility() == 0 && !this.lines.isEmpty() && ((this.synced && this.playing) || System.currentTimeMillis() < this.settleUntil || !this.scroller.isFinished()); - if (!z || this.ticking) { - if (z || !this.ticking) { - return; - } - Ticker.remove(this); - this.ticking = false; - return; - } - Ticker.add(this); - this.ticking = true; - } - - @Override // android.view.View - protected void onAttachedToWindow() { - super.onAttachedToWindow(); - this.attached = true; - ensureTick(); - } - - @Override // android.view.View - protected void onDetachedFromWindow() { - super.onDetachedFromWindow(); - this.attached = false; - ensureTick(); - } - - @Override // android.view.View - protected void onVisibilityChanged(View view, int i) { - super.onVisibilityChanged(view, i); - kick(); - } - - @Override // android.view.View - protected void onWindowVisibilityChanged(int i) { - super.onWindowVisibilityChanged(i); - kick(); - } - - @Override // android.view.View - public boolean onTouchEvent(MotionEvent motionEvent) { - if (this.lines.isEmpty()) { - return false; - } - kick(); - return this.gd.onTouchEvent(motionEvent) || super.onTouchEvent(motionEvent); - } - - void build() { - int width = (getWidth() - getPaddingLeft()) - getPaddingRight(); - if (width > 0 && width != this.layoutW) { - this.layoutW = width; - this.layouts.clear(); - this.tp.setTextSize(Ui.dpf(getContext(), this.compact ? 18.0f : 23.0f)); - float fDpf = Ui.dpf(getContext(), this.compact ? 10.0f : 14.0f); - this.tops = new float[this.lines.size()]; - this.act = new float[this.lines.size()]; - int i = 0; - float height = 0.0f; - while (i < this.lines.size()) { - StaticLayout staticLayout = new StaticLayout(this.lines.get(i).text.length() == 0 ? "♪" : this.lines.get(i).text, this.tp, (int) (width / 1.06f), Layout.Alignment.ALIGN_NORMAL, 1.08f, 0.0f, false); - this.layouts.add(staticLayout); - this.tops[i] = height; - i++; - height += staticLayout.getHeight() + fDpf; - } - } - } - - float contentHeight() { - if (this.tops.length == 0) { - return 0.0f; - } - return this.layouts.get(this.layouts.size() - 1).getHeight() + this.tops[this.tops.length - 1]; - } - - float maxOffset() { - return Math.max(0.0f, contentHeight() - (getHeight() * 0.5f)); - } - - float clamp(float f) { - return Math.max((-getHeight()) * 0.3f, Math.min(maxOffset(), f)); - } - - @Override // com.mulberry.player.Ticker.Client - public void frame(float f, long j) { - build(); - if (this.scroller.computeScrollOffset()) { - this.offset = clamp(this.scroller.getCurrY()); - this.target = this.offset; - } - if (this.synced && this.svc != null) { - int iLineAt = Lyrics.lineAt(this.lines, this.svc.positionFast() + 250); - if (iLineAt != this.current) { - this.settleUntil = System.currentTimeMillis() + 1200; - } - if (iLineAt != this.current) { - this.current = iLineAt; - } - if (System.currentTimeMillis() > this.manualUntil && this.current >= 0 && this.current < this.tops.length) { - this.target = clamp(((this.layouts.get(this.current).getHeight() / 2.0f) + this.tops[this.current]) - (getHeight() * 0.36f)); - } - } - this.offset += (this.target - this.offset) * Math.min(1.0f, 7.0f * f); - int i = 0; - while (i < this.act.length) { - float f2 = (!this.synced || i == this.current) ? 1.0f : 0.0f; - float[] fArr = this.act; - fArr[i] = ((f2 - this.act[i]) * Math.min(1.0f, 8.0f * f)) + fArr[i]; - i++; - } - invalidate(); - if ((!this.synced || !this.playing) && System.currentTimeMillis() >= this.settleUntil && this.scroller.isFinished()) { - ensureTick(); - } - } - - @Override // android.view.View - protected void onDraw(Canvas canvas) { - int i = 0; - Palette palette = App.I.palette; - if (this.lines.isEmpty()) { - this.msgPaint.setColor(palette.onSurfaceVariant); - StaticLayout staticLayout = new StaticLayout(this.message.length() == 0 ? "No lyrics" : this.message, this.msgPaint, Math.max(1, (getWidth() - getPaddingLeft()) - getPaddingRight()), Layout.Alignment.ALIGN_CENTER, 1.1f, 0.0f, false); - canvas.save(); - canvas.translate(getPaddingLeft(), Math.max(0.0f, (getHeight() - staticLayout.getHeight()) / 2.0f)); - staticLayout.draw(canvas); - canvas.restore(); - return; - } - build(); - float f = -this.offset; - while (i < this.layouts.size()) { - float f2 = f + this.tops[i]; - StaticLayout staticLayout2 = this.layouts.get(i); - if (staticLayout2.getHeight() + f2 >= 0.0f && f2 <= getHeight()) { - float f3 = i < this.act.length ? this.act[i] : 1.0f; - this.tp.setColor(Palette.alpha(this.synced ? Palette.mixC(palette.onSurfaceVariant, palette.primary, f3) : palette.onSurface, this.synced ? 0.42f + (0.58f * f3) : 0.95f)); - float f4 = (this.synced ? f3 * 0.06f : 0.0f) + 1.0f; - canvas.save(); - canvas.translate(getPaddingLeft(), f2); - canvas.scale(f4, f4, 0.0f, staticLayout2.getHeight() / 2.0f); - staticLayout2.draw(canvas); - canvas.restore(); - } - i++; - } - } -} diff --git a/android/src/com/mulberry/player/MainActivity.java b/android/src/com/mulberry/player/MainActivity.java deleted file mode 100644 index 075e74d..0000000 --- a/android/src/com/mulberry/player/MainActivity.java +++ /dev/null @@ -1,2196 +0,0 @@ -package com.mulberry.player; - -import android.app.Activity; -import android.app.Dialog; -import android.content.ComponentName; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.ServiceConnection; -import android.content.res.ColorStateList; -import android.content.res.Configuration; -import android.graphics.Typeface; -import android.graphics.drawable.ColorDrawable; -import android.graphics.drawable.Drawable; -import android.graphics.drawable.GradientDrawable; -import android.media.MediaMetadataRetriever; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.os.IBinder; -import android.os.PowerManager; -import android.text.Editable; -import android.text.TextWatcher; -import android.view.GestureDetector; -import android.view.MotionEvent; -import android.view.View; -import android.view.Window; -import android.view.WindowInsets; -import android.view.animation.PathInterpolator; -import android.widget.CheckBox; -import android.widget.EditText; -import android.widget.FrameLayout; -import android.widget.HorizontalScrollView; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ListAdapter; -import android.widget.ListView; -import android.widget.RadioButton; -import android.widget.RadioGroup; -import android.widget.ScrollView; -import android.widget.TextView; -import android.widget.Toast; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; - -/* JADX INFO: loaded from: classes.dex */ -public class MainActivity extends Activity implements MusicService.Listener, Library.Listener, Playlists.Listener { - static MainActivity CURRENT = null; - static final int REQ_EXPORT_ALL = 12; - static final int REQ_EXPORT_ONE = 11; - static final int REQ_IMPORT = 10; - static final int REQ_PERMS = 1; - static final int REQ_TAGS = 20; - BassShapeView bassShape; - View bottomBar; - TextView emptyMsg; - Playlists.PL exportPl; - Lists.GroupAdapter groupAdapter; - int insetBottom; - int insetTop; - ListView libList; - int libTab; - View libraryPage; - int listBottom; - LinearLayout mini; - TextView miniArtist; - CookieView miniCookie; - PlayButton miniPlay; - WavySeekBar miniSeek; - TextView miniTitle; - LinearLayout nav; - FrameLayout pages; - Runnable pendingPlay; - LinearLayout plBox; - NowPlaying player; - View playlistsPage; - FrameLayout root; - EditText search; - SettingsPage settingsPage; - Lists.SongAdapter songAdapter; - MusicService svc; - LinearLayout tabs; - final List stack = new ArrayList(); - int page = 0; - String sortMode = "title"; - String exportFmt = "m3u8"; - boolean exportReplace = true; - final List navItems = new ArrayList(); - final ServiceConnection conn = new ServiceConnection() { // from class: com.mulberry.player.MainActivity.1 - @Override // android.content.ServiceConnection - public void onServiceConnected(ComponentName componentName, IBinder iBinder) { - MainActivity.this.svc = ((MusicService.LocalBinder) iBinder).service(); - MainActivity.this.svc.addListener(MainActivity.this); - MainActivity.this.player.bindService(MainActivity.this.svc); - MainActivity.this.miniCookie.setService(MainActivity.this.svc); - MainActivity.this.bassShape.setService(MainActivity.this.svc); - MainActivity.this.onTrackChanged(); - MainActivity.this.onQueueChanged(); - if (MainActivity.this.pendingPlay != null) { - Runnable runnable = MainActivity.this.pendingPlay; - MainActivity.this.pendingPlay = null; - runnable.run(); - } - } - - @Override // android.content.ServiceConnection - public void onServiceDisconnected(ComponentName componentName) { - MainActivity.this.svc = null; - } - }; - final Runnable uiTick = new Runnable() { // from class: com.mulberry.player.MainActivity.2 - @Override // java.lang.Runnable - public void run() { - if (MainActivity.this.svc != null) { - if (MainActivity.this.player.open) { - MainActivity.this.player.tick(); - } - if (MainActivity.this.mini.getVisibility() == 0) { - MainActivity.this.miniSeek.set(MainActivity.this.svc.position(), MainActivity.this.svc.duration()); - } - } - App.MAIN.postDelayed(this, 500L); - } - }; - final Runnable searchTask = new Runnable() { // from class: com.mulberry.player.MainActivity.21 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.fillLibrary(); - } - }; - final Lists.SongClick songClick = new Lists.SongClick() { // from class: com.mulberry.player.MainActivity.29 - @Override // com.mulberry.player.Lists.SongClick - public void click(List list, final int i) { - final ArrayList arrayList = new ArrayList(list); - MainActivity.this.withService(new Runnable() { // from class: com.mulberry.player.MainActivity.29.1 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.playList(arrayList, i); - } - }); - } - - @Override // com.mulberry.player.Lists.SongClick - public void longClick(List list, int i, View view) { - MainActivity.this.songMenu(list.get(i), null, -1); - } - }; - final Lists.GroupClick groupClick = new Lists.GroupClick() { // from class: com.mulberry.player.MainActivity.30 - @Override // com.mulberry.player.Lists.GroupClick - public void click(Library.Group group) { - MainActivity.this.openGroup(group.title, group.subtitle, group.songs, MainActivity.this.libTab == 1, null); - } - - @Override // com.mulberry.player.Lists.GroupClick - public void longClick(Library.Group group) { - MainActivity.this.groupMenu(group.title, group.songs); - } - }; - - interface TextCb { - void ok(String str); - } - - @Override // android.app.Activity - protected void onCreate(Bundle bundle) { - int i; - super.onCreate(bundle); - CURRENT = this; - Window window = getWindow(); - window.setStatusBarColor(0); - window.setNavigationBarColor(0); - View decorView = window.getDecorView(); - if (App.I.palette.dark) { - i = 0; - } else { - i = (Build.VERSION.SDK_INT >= 26 ? 16 : 0) | 8192 /* SYSTEM_UI_FLAG_LIGHT_STATUS_BAR */; - } - decorView.setSystemUiVisibility(i | 1792); - this.libTab = App.I.prefs.getInt(Prefs.LIB_TAB, 0); - build(); - App.I.library.addListener(this); - Playlists.addListener(this); - bindService(new Intent(this, (Class) MusicService.class), this.conn, 1); - if (App.I.library.loaded) { - fillLibrary(); - } - if (hasAudioPermission()) { - startLibrary(); - } else { - requestPerms(); - } - handleIntent(getIntent()); - } - - @Override // android.app.Activity - protected void onNewIntent(Intent intent) { - super.onNewIntent(intent); - setIntent(intent); - handleIntent(intent); - } - - @Override // android.app.Activity - protected void onResume() { - super.onResume(); - App.MAIN.removeCallbacks(this.uiTick); - App.MAIN.post(this.uiTick); - if (this.settingsPage == null || this.page != 2 || !this.stack.isEmpty()) { - return; - } - this.settingsPage.refresh(); - } - - @Override // android.app.Activity - protected void onPause() { - super.onPause(); - App.MAIN.removeCallbacks(this.uiTick); - } - - @Override // android.app.Activity - protected void onDestroy() { - App.I.library.removeListener(this); - Playlists.removeListener(this); - if (this.svc != null) { - this.svc.removeListener(this); - } - try { - unbindService(this.conn); - } catch (Exception e) { - } - if (CURRENT == this) { - CURRENT = null; - } - super.onDestroy(); - } - - @Override // android.app.Activity, android.content.ComponentCallbacks - public void onConfigurationChanged(Configuration configuration) { - super.onConfigurationChanged(configuration); - Palette palette = App.I.palette; - Integer numDominant = null; - if (this.svc != null && this.svc.art() != null && "album".equals(App.I.prefs.getStr(Prefs.COLOR_SOURCE, "system"))) { - numDominant = Palette.dominant(this.svc.art()); - } - App.I.palette = Palette.build(this, numDominant); - if (palette.dark == App.I.palette.dark) { - Ui.recolor(); - } else { - recreate(); - } - } - - void withService(Runnable runnable) { - MusicService.ensureStarted(this); - if (this.svc == null) { - this.pendingPlay = runnable; - } else { - runnable.run(); - } - } - - public static void toast(final String str) { - App.ui(new Runnable() { // from class: com.mulberry.player.MainActivity.3 - @Override // java.lang.Runnable - public void run() { - Toast.makeText(App.I, str, 0).show(); - } - }); - } - - boolean hasAudioPermission() { - return checkSelfPermission(Build.VERSION.SDK_INT >= 33 ? "android.permission.READ_MEDIA_AUDIO" : "android.permission.READ_EXTERNAL_STORAGE") == 0; - } - - void requestPerms() { - ArrayList arrayList = new ArrayList(); - if (Build.VERSION.SDK_INT >= 33) { - arrayList.add("android.permission.READ_MEDIA_AUDIO"); - arrayList.add("android.permission.POST_NOTIFICATIONS"); - } else { - arrayList.add("android.permission.READ_EXTERNAL_STORAGE"); - if (Build.VERSION.SDK_INT <= 28) { - arrayList.add("android.permission.WRITE_EXTERNAL_STORAGE"); - } - } - requestPermissions((String[]) arrayList.toArray(new String[0]), 1); - } - - @Override // android.app.Activity - public void onRequestPermissionsResult(int i, String[] strArr, int[] iArr) { - if (i == 1) { - if (hasAudioPermission()) { - startLibrary(); - maybeAskBattery(); - } else { - this.emptyMsg.setText("Mulberry needs access to your music.\nTap here to allow it."); - this.emptyMsg.setVisibility(0); - } - } - } - - void startLibrary() { - App.I.library.startObserving(); - App.I.library.refresh(); - this.emptyMsg.setText("Scanning your music…"); - } - - void maybeAskBattery() { - if (!App.I.prefs.getBool("asked_battery", false)) { - App.I.prefs.setBool("asked_battery", true); - PowerManager powerManager = (PowerManager) getSystemService("power"); - if (powerManager != null && !powerManager.isIgnoringBatteryOptimizations(getPackageName())) { - Ui.show(Ui.dialog(this).setTitle("Keep playing in the background?").setMessage("Some phones stop music apps in the background to save battery. Allow Mulberry to run unrestricted so playback, the notification and widgets keep working.").setPositiveButton("Allow", new DialogInterface.OnClickListener() { // from class: com.mulberry.player.MainActivity.4 - @Override // android.content.DialogInterface.OnClickListener - public void onClick(DialogInterface dialogInterface, int i) { - MainActivity.this.requestBatteryExemption(); - } - }).setNegativeButton("Not now", (DialogInterface.OnClickListener) null)); - } - } - } - - void requestBatteryExemption() { - try { - startActivity(new Intent("android.settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS", Uri.parse("package:" + getPackageName()))); - } catch (Exception e) { - try { - startActivity(new Intent("android.settings.IGNORE_BATTERY_OPTIMIZATION_SETTINGS")); - } catch (Exception e2) { - } - } - } - - void requestAllFiles() { - if (Build.VERSION.SDK_INT >= 30) { - try { - startActivity(new Intent("android.settings.MANAGE_APP_ALL_FILES_ACCESS_PERMISSION", Uri.parse("package:" + getPackageName()))); - return; - } catch (Exception e) { - try { - startActivity(new Intent("android.settings.MANAGE_ALL_FILES_ACCESS_PERMISSION")); - return; - } catch (Exception e2) { - return; - } - } - } - requestPerms(); - } - - void build() { - this.root = new FrameLayout(this); - Ui.plain(this.root, 6); - this.pages = new FrameLayout(this); - this.root.addView(this.pages, new FrameLayout.LayoutParams(-1, -1)); - this.libraryPage = buildLibrary(); - this.playlistsPage = buildPlaylists(); - this.settingsPage = new SettingsPage(this); - this.pages.addView(this.libraryPage); - this.pages.addView(this.playlistsPage); - this.pages.addView(this.settingsPage); - LinearLayout linearLayoutCol = Ui.col(this); - this.mini = buildMini(); - linearLayoutCol.addView(this.mini); - this.nav = buildNav(); - linearLayoutCol.addView(this.nav); - this.root.addView(linearLayoutCol, Ui.flp(-1, -2, 80)); - this.bottomBar = linearLayoutCol; - linearLayoutCol.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { // from class: com.mulberry.player.MainActivity.5 - @Override // android.view.View.OnLayoutChangeListener - public void onLayoutChange(View view, int i, int i2, int i3, int i4, int i5, int i6, int i7, int i8) { - if (i2 != i6 || i4 != i8) { - int i9 = i4 - i2; - MainActivity.this.setListBottom(Ui.dp(MainActivity.this, 12.0f) + i9); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) MainActivity.this.bassShape.getLayoutParams(); - layoutParams.bottomMargin = i9 + Ui.dp(MainActivity.this, 8.0f); - layoutParams.leftMargin = Ui.dp(MainActivity.this, 14.0f); - MainActivity.this.bassShape.setLayoutParams(layoutParams); - } - } - }); - this.bassShape = new BassShapeView(this); - this.bassShape.setOnClickListener(new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.6 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - MainActivity.this.openPlayer(); - } - }); - this.root.addView(this.bassShape, Ui.flp(Ui.dp(this, 64.0f), Ui.dp(this, 64.0f), 8388691)); - this.player = new NowPlaying(this); - this.player.setVisibility(8); - this.root.addView(this.player, new FrameLayout.LayoutParams(-1, -1)); - this.root.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() { // from class: com.mulberry.player.MainActivity.7 - @Override // android.view.View.OnApplyWindowInsetsListener - public WindowInsets onApplyWindowInsets(View view, WindowInsets windowInsets) { - MainActivity.this.insetTop = windowInsets.getSystemWindowInsetTop(); - MainActivity.this.insetBottom = windowInsets.getSystemWindowInsetBottom(); - MainActivity.this.applyInsets(); - return windowInsets.consumeSystemWindowInsets(); - } - }); - setContentView(this.root); - showPage(0, false); - updateBassShape(); - } - - void applyInsets() { - this.nav.setPadding(0, Ui.dp(this, 8.0f), 0, Ui.dp(this, 8.0f) + this.insetBottom); - this.player.setPadding(0, this.insetTop, 0, this.insetBottom); - for (int i = 0; i < this.pages.getChildCount(); i++) { - this.pages.getChildAt(i).setPadding(0, this.insetTop, 0, 0); - } - Iterator it = this.stack.iterator(); - while (it.hasNext()) { - it.next().setPadding(0, this.insetTop, 0, 0); - } - } - - void setListBottom(int i) { - this.listBottom = i; - if (this.libList != null) { - this.libList.setPadding(this.libList.getPaddingLeft(), this.libList.getPaddingTop(), this.libList.getPaddingRight(), i); - } - if (this.plBox != null) { - this.plBox.setPadding(this.plBox.getPaddingLeft(), this.plBox.getPaddingTop(), this.plBox.getPaddingRight(), i); - } - this.settingsPage.setBottomPad(i); - Iterator it = this.stack.iterator(); - while (it.hasNext()) { - ListView listView = (ListView) it.next().findViewWithTag("list"); - if (listView != null) { - listView.setPadding(0, listView.getPaddingTop(), 0, i); - } - } - } - - void updateBassShape() { - this.bassShape.setVisibility(App.I.prefs.getBool(Prefs.BASS_SHAPE, false) && Spectrum.enabled() ? 0 : 8); - } - - LinearLayout buildNav() { - LinearLayout linearLayoutRow = Ui.row(this); - Ui.plain(linearLayoutRow, 8); - String[] strArr = {"Library", "Playlists", "Settings"}; - int[] iArr = {R.drawable.ic_library_music, R.drawable.ic_queue_music, R.drawable.ic_settings}; - for (int i0 = 0; i0 < 3; i0++) { - final int i = i0; - LinearLayout linearLayoutCol = Ui.col(this); - linearLayoutCol.setGravity(17); - FrameLayout frameLayout = new FrameLayout(this); - frameLayout.addView(Ui.icon(this, iArr[i], 12, 24), Ui.flp(Ui.dp(this, 24.0f), Ui.dp(this, 24.0f), 17)); - linearLayoutCol.addView(frameLayout, new LinearLayout.LayoutParams(Ui.dp(this, 64.0f), Ui.dp(this, 32.0f))); - TextView textViewSingle = Ui.single(this, strArr[i], 12.0f, 12, true); - textViewSingle.setPadding(0, Ui.dp(this, 4.0f), 0, 0); - textViewSingle.setGravity(17); - linearLayoutCol.addView(textViewSingle, new LinearLayout.LayoutParams(-2, -2)); - linearLayoutCol.setOnClickListener(new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.8 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - MainActivity.this.showPage(i, true); - } - }); - linearLayoutRow.addView(linearLayoutCol, Ui.lpw(-2, 1.0f)); - this.navItems.add(linearLayoutCol); - } - return linearLayoutRow; - } - - void styleNav() { - int i = 0; - while (i < this.navItems.size()) { - LinearLayout linearLayout = (LinearLayout) this.navItems.get(i); - FrameLayout frameLayout = (FrameLayout) linearLayout.getChildAt(0); - ImageView imageView = (ImageView) frameLayout.getChildAt(0); - TextView textView = (TextView) linearLayout.getChildAt(1); - boolean z = i == this.page; - frameLayout.setBackground(z ? Ui.round(Ui.c(4), Ui.dpf(this, 16.0f)) : null); - imageView.setImageTintList(ColorStateList.valueOf(Ui.c(z ? 5 : 12))); - textView.setTextColor(Ui.c(z ? 11 : 12)); - if (z && !App.lowPower()) { - frameLayout.setScaleX(0.6f); - frameLayout.animate().scaleX(1.0f).setDuration(260L).setInterpolator(new PathInterpolator(0.2f, 0.0f, 0.0f, 1.0f)).start(); - } - i++; - } - } - - void showPage(int i, boolean z) { - while (!this.stack.isEmpty()) { - popDetail(false); - } - this.page = i; - View[] viewArr = {this.libraryPage, this.playlistsPage, this.settingsPage}; - for (int i2 = 0; i2 < viewArr.length; i2++) { - View view = viewArr[i2]; - if (i2 == i) { - view.setVisibility(0); - if (z && !App.lowPower()) { - view.setAlpha(0.0f); - view.setTranslationY(Ui.dp(this, 16.0f)); - view.animate().alpha(1.0f).translationY(0.0f).setDuration(220L).setInterpolator(new PathInterpolator(0.2f, 0.0f, 0.0f, 1.0f)).start(); - } - } else { - view.setVisibility(8); - } - } - if (i == 1) { - rebuildPlaylists(); - } - if (i == 2) { - this.settingsPage.refresh(); - } - styleNav(); - } - - LinearLayout buildMini() { - final LinearLayout linearLayoutCol = Ui.col(this); - linearLayoutCol.setPadding(Ui.dp(this, 8.0f), Ui.dp(this, 8.0f), Ui.dp(this, 10.0f), Ui.dp(this, 2.0f)); - Ui.themed(linearLayoutCol, new Ui.Paint() { // from class: com.mulberry.player.MainActivity.9 - @Override // com.mulberry.player.Ui.Paint - public void apply() { - GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, new int[]{Palette.mixC(Ui.c(9), Ui.c(2), 0.45f), Ui.c(9)}); - gradientDrawable.setCornerRadius(Ui.dpf(MainActivity.this, 30.0f)); - linearLayoutCol.setBackground(Ui.ripple(gradientDrawable, Ui.c(11), Ui.round(-1, Ui.dpf(MainActivity.this, 30.0f)))); - linearLayoutCol.setElevation(Ui.dpf(MainActivity.this, 6.0f)); - } - }); - LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(-1, -2); - int iDp = Ui.dp(this, 10.0f); - layoutParams.rightMargin = iDp; - layoutParams.leftMargin = iDp; - layoutParams.bottomMargin = Ui.dp(this, 8.0f); - linearLayoutCol.setLayoutParams(layoutParams); - LinearLayout linearLayoutRow = Ui.row(this); - this.miniCookie = new CookieView(this); - this.miniCookie.small = true; - linearLayoutRow.addView(this.miniCookie, new LinearLayout.LayoutParams(Ui.dp(this, 70.0f), Ui.dp(this, 70.0f))); - LinearLayout linearLayoutCol2 = Ui.col(this); - linearLayoutCol2.setPadding(Ui.dp(this, 10.0f), 0, Ui.dp(this, 6.0f), 0); - this.miniTitle = Ui.single(this, FrameBodyCOMM.DEFAULT, 16.5f, 11, true); - this.miniTitle.setTypeface(Typeface.create("sans-serif", 1)); - this.miniArtist = Ui.single(this, FrameBodyCOMM.DEFAULT, 13.5f, 0, true); - linearLayoutCol2.addView(this.miniTitle); - linearLayoutCol2.addView(this.miniArtist); - linearLayoutRow.addView(linearLayoutCol2, Ui.lpw(-2, 1.0f)); - this.miniPlay = new PlayButton(this); - this.miniPlay.setOnClickListener(new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.10 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - MainActivity.this.togglePlay(); - } - }); - linearLayoutRow.addView(this.miniPlay, new LinearLayout.LayoutParams(Ui.dp(this, 66.0f), Ui.dp(this, 50.0f))); - linearLayoutRow.addView(Ui.iconButton(this, R.drawable.ic_skip_next_fill, 11, 46, new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.11 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - if (MainActivity.this.svc != null) { - MainActivity.this.svc.next(); - } - } - })); - linearLayoutCol.addView(linearLayoutRow); - this.miniSeek = new WavySeekBar(this); - this.miniSeek.heightDp = 26; - this.miniSeek.setOnSeek(new WavySeekBar.OnSeek() { // from class: com.mulberry.player.MainActivity.12 - @Override // com.mulberry.player.WavySeekBar.OnSeek - public void seek(float f) { - if (MainActivity.this.svc != null) { - MainActivity.this.svc.seek((long) (MainActivity.this.svc.duration() * f)); - } - } - - @Override // com.mulberry.player.WavySeekBar.OnSeek - public void dragging(float f) { - } - }); - linearLayoutCol.addView(this.miniSeek, Ui.lp(-1, -2)); - final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() { // from class: com.mulberry.player.MainActivity.13 - @Override // android.view.GestureDetector.SimpleOnGestureListener, android.view.GestureDetector.OnGestureListener - public boolean onDown(MotionEvent motionEvent) { - return true; - } - - @Override // android.view.GestureDetector.SimpleOnGestureListener, android.view.GestureDetector.OnGestureListener - public boolean onSingleTapUp(MotionEvent motionEvent) { - MainActivity.this.openPlayer(); - return true; - } - - @Override // android.view.GestureDetector.SimpleOnGestureListener, android.view.GestureDetector.OnGestureListener - public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent2, float f, float f2) { - if (motionEvent == null || MainActivity.this.svc == null) { - return false; - } - float x = motionEvent2.getX() - motionEvent.getX(); - float y = motionEvent2.getY() - motionEvent.getY(); - if (Math.abs(x) <= Math.abs(y) || Math.abs(x) <= Ui.dp(MainActivity.this, 60.0f)) { - if (y >= (-Ui.dp(MainActivity.this, 40.0f))) { - return false; - } - MainActivity.this.openPlayer(); - return true; - } - if (x < 0.0f) { - MainActivity.this.svc.next(); - } else { - MainActivity.this.svc.prev(); - } - if (!App.lowPower()) { - MainActivity.this.mini.setTranslationX(x < 0.0f ? -Ui.dp(MainActivity.this, 40.0f) : Ui.dp(MainActivity.this, 40.0f)); - MainActivity.this.mini.setAlpha(0.4f); - MainActivity.this.mini.animate().translationX(0.0f).alpha(1.0f).setDuration(260L).setInterpolator(new PathInterpolator(0.2f, 0.0f, 0.0f, 1.0f)).start(); - } - return true; - } - }); - linearLayoutRow.setOnTouchListener(new View.OnTouchListener() { // from class: com.mulberry.player.MainActivity.14 - @Override // android.view.View.OnTouchListener - public boolean onTouch(View view, MotionEvent motionEvent) { - return gestureDetector.onTouchEvent(motionEvent); - } - }); - linearLayoutCol.setVisibility(8); - return linearLayoutCol; - } - - View buildLibrary() { - LinearLayout linearLayoutCol = Ui.col(this); - LinearLayout linearLayoutRow = Ui.row(this); - linearLayoutRow.setPadding(Ui.dp(this, 20.0f), Ui.dp(this, 14.0f), Ui.dp(this, 10.0f), Ui.dp(this, 6.0f)); - linearLayoutRow.addView(Ui.title(this, "Library"), Ui.lpw(-2, 1.0f)); - linearLayoutRow.addView(Ui.iconButton(this, R.drawable.ic_sort, 12, 44, new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.15 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - MainActivity.this.sortMenu(); - } - })); - linearLayoutRow.addView(Ui.pill(this, R.drawable.ic_shuffle, "Shuffle", true, new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.16 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - final ArrayList arrayList = new ArrayList(App.I.library.songs); - if (!arrayList.isEmpty()) { - MainActivity.this.withService(new Runnable() { // from class: com.mulberry.player.MainActivity.16.1 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.playShuffled(arrayList); - } - }); - } - } - })); - linearLayoutCol.addView(linearLayoutRow); - LinearLayout linearLayoutRow2 = Ui.row(this); - linearLayoutRow2.setPadding(Ui.dp(this, 16.0f), 0, Ui.dp(this, 16.0f), Ui.dp(this, 8.0f)); - this.search = Ui.field(this, "Search songs, artists, albums", FrameBodyCOMM.DEFAULT); - this.search.setSingleLine(true); - this.search.setCompoundDrawablePadding(Ui.dp(this, 10.0f)); - this.search.setCompoundDrawablesRelativeWithIntrinsicBounds(tinted(R.drawable.ic_search, 12, 20), (Drawable) null, (Drawable) null, (Drawable) null); - Ui.themed(this.search, new Ui.Paint() { // from class: com.mulberry.player.MainActivity.17 - @Override // com.mulberry.player.Ui.Paint - public void apply() { - MainActivity.this.search.setBackground(Ui.round(Ui.c(9), Ui.dpf(MainActivity.this, 28.0f))); - } - }); - this.search.addTextChangedListener(new TextWatcher() { // from class: com.mulberry.player.MainActivity.18 - @Override // android.text.TextWatcher - public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { - } - - @Override // android.text.TextWatcher - public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { - } - - @Override // android.text.TextWatcher - public void afterTextChanged(Editable editable) { - App.MAIN.removeCallbacks(MainActivity.this.searchTask); - App.MAIN.postDelayed(MainActivity.this.searchTask, 180L); - } - }); - linearLayoutRow2.addView(this.search, Ui.lpw(-2, 1.0f)); - linearLayoutCol.addView(linearLayoutRow2); - HorizontalScrollView horizontalScrollView = new HorizontalScrollView(this); - horizontalScrollView.setHorizontalScrollBarEnabled(false); - this.tabs = Ui.row(this); - this.tabs.setPadding(Ui.dp(this, 14.0f), 0, Ui.dp(this, 14.0f), Ui.dp(this, 6.0f)); - String[] strArr = {"Songs", "Albums", "Artists", "Folders"}; - for (int i0 = 0; i0 < strArr.length; i0++) { - final int i = i0; - TextView textViewSingle = Ui.single(this, strArr[i], 14.0f, 11, true); - textViewSingle.setPadding(Ui.dp(this, 16.0f), Ui.dp(this, 8.0f), Ui.dp(this, 16.0f), Ui.dp(this, 8.0f)); - LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(-2, -2); - layoutParams.rightMargin = Ui.dp(this, 8.0f); - textViewSingle.setOnClickListener(new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.19 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - MainActivity.this.libTab = i; - App.I.prefs.setInt(Prefs.LIB_TAB, i); - MainActivity.this.styleTabs(); - MainActivity.this.fillLibrary(); - MainActivity.this.libList.setSelection(0); - } - }); - this.tabs.addView(textViewSingle, layoutParams); - } - horizontalScrollView.addView(this.tabs); - linearLayoutCol.addView(horizontalScrollView); - FrameLayout frameLayout = new FrameLayout(this); - this.libList = Lists.list(this); - this.libList.setPadding(Ui.dp(this, 6.0f), 0, Ui.dp(this, 6.0f), Ui.dp(this, 140.0f)); - this.songAdapter = new Lists.SongAdapter(this, this.songClick); - this.groupAdapter = new Lists.GroupAdapter(this, this.groupClick); - frameLayout.addView(this.libList, new FrameLayout.LayoutParams(-1, -1)); - this.emptyMsg = Ui.text(this, "Scanning your music…", 15.0f, 12, false); - this.emptyMsg.setGravity(17); - this.emptyMsg.setPadding(Ui.dp(this, 32.0f), 0, Ui.dp(this, 32.0f), Ui.dp(this, 120.0f)); - this.emptyMsg.setOnClickListener(new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.20 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - if (MainActivity.this.hasAudioPermission()) { - return; - } - MainActivity.this.openAppSettingsOrAsk(); - } - }); - frameLayout.addView(this.emptyMsg, new FrameLayout.LayoutParams(-1, -1)); - linearLayoutCol.addView(frameLayout, Ui.lp(-1, 0)); - ((LinearLayout.LayoutParams) frameLayout.getLayoutParams()).weight = 1.0f; - styleTabs(); - return linearLayoutCol; - } - - void openAppSettingsOrAsk() { - if (shouldShowRequestPermissionRationale(Build.VERSION.SDK_INT >= 33 ? "android.permission.READ_MEDIA_AUDIO" : "android.permission.READ_EXTERNAL_STORAGE") || !App.I.prefs.getBool("asked_perm", false)) { - App.I.prefs.setBool("asked_perm", true); - requestPerms(); - } else { - startActivity(new Intent("android.settings.APPLICATION_DETAILS_SETTINGS", Uri.parse("package:" + getPackageName()))); - } - } - - Drawable tinted(int i, int i2, int i3) { - Drawable drawableMutate = getDrawable(i).mutate(); - drawableMutate.setTint(Ui.c(i2)); - drawableMutate.setBounds(0, 0, Ui.dp(this, i3), Ui.dp(this, i3)); - return drawableMutate; - } - - void styleTabs() { - int i = 0; - while (i < this.tabs.getChildCount()) { - TextView textView = (TextView) this.tabs.getChildAt(i); - boolean z = i == this.libTab; - textView.setBackground(z ? Ui.round(Ui.c(4), Ui.dpf(this, 18.0f)) : strokeChip()); - textView.setTextColor(Ui.c(z ? 5 : 12)); - i++; - } - } - - Drawable strokeChip() { - GradientDrawable gradientDrawableRound = Ui.round(0, Ui.dpf(this, 18.0f)); - gradientDrawableRound.setStroke(Ui.dp(this, 1.0f), Ui.c(14)); - return gradientDrawableRound; - } - - void fillLibrary() { - int i; - List list; - String str; - Library library = App.I.library; - String strTrim = this.search.getText().toString().trim(); - if (strTrim.length() > 0) { - this.libList.setAdapter((ListAdapter) this.songAdapter); - this.songAdapter.numbers = false; - this.songAdapter.set(library.search(strTrim)); - this.emptyMsg.setVisibility(this.songAdapter.getCount() != 0 ? 8 : 0); - this.emptyMsg.setText("Nothing matches “" + strTrim + "”"); - return; - } - if (this.libTab == 0) { - ArrayList arrayList = new ArrayList(library.songs); - sortSongs(arrayList); - this.songAdapter.numbers = false; - if (this.libList.getAdapter() != this.songAdapter) { - this.libList.setAdapter((ListAdapter) this.songAdapter); - } - this.songAdapter.set(arrayList); - } else { - Lists.GroupAdapter groupAdapter = this.groupAdapter; - if (this.libTab == 1) { - i = R.drawable.ic_album; - } else { - i = this.libTab == 2 ? R.drawable.ic_artist : R.drawable.ic_folder; - } - groupAdapter.icon = i; - this.libList.setAdapter((ListAdapter) this.groupAdapter); - Lists.GroupAdapter groupAdapter2 = this.groupAdapter; - if (this.libTab == 1) { - list = library.albums; - } else { - list = this.libTab == 2 ? library.artists : library.folders; - } - groupAdapter2.set(list); - } - boolean zIsEmpty = library.songs.isEmpty(); - this.emptyMsg.setVisibility(zIsEmpty ? 0 : 8); - if (zIsEmpty) { - TextView textView = this.emptyMsg; - if (hasAudioPermission()) { - str = library.loaded ? "No music found.\nCopy songs to your phone (Music or Download folder) and they'll show up here." : "Scanning your music…"; - } else { - str = "Mulberry needs access to your music.\nTap here to allow it."; - } - textView.setText(str); - } - } - - void sortSongs(List list) { - Comparator comparator; - if ("artist".equals(this.sortMode)) { - comparator = new Comparator() { // from class: com.mulberry.player.MainActivity.22 - @Override // java.util.Comparator - public int compare(Song song, Song song2) { - int iCompareToIgnoreCase = song.displayArtist().compareToIgnoreCase(song2.displayArtist()); - if (iCompareToIgnoreCase == 0) { - int iCompareToIgnoreCase2 = song.album.compareToIgnoreCase(song2.album); - return iCompareToIgnoreCase2 == 0 ? song.track - song2.track : iCompareToIgnoreCase2; - } - return iCompareToIgnoreCase; - } - }; - } else if ("added".equals(this.sortMode)) { - comparator = new Comparator() { // from class: com.mulberry.player.MainActivity.23 - @Override // java.util.Comparator - public int compare(Song song, Song song2) { - return Long.compare(song2.dateAdded, song.dateAdded); - } - }; - } else if ("year".equals(this.sortMode)) { - comparator = new Comparator() { // from class: com.mulberry.player.MainActivity.24 - @Override // java.util.Comparator - public int compare(Song song, Song song2) { - return song2.year - song.year; - } - }; - } else { - comparator = "duration".equals(this.sortMode) ? new Comparator() { // from class: com.mulberry.player.MainActivity.25 - @Override // java.util.Comparator - public int compare(Song song, Song song2) { - return Long.compare(song2.duration, song.duration); - } - } : new Comparator() { // from class: com.mulberry.player.MainActivity.26 - @Override // java.util.Comparator - public int compare(Song song, Song song2) { - return song.displayTitle().compareToIgnoreCase(song2.displayTitle()); - } - }; - } - Collections.sort(list, comparator); - } - - void sortMenu() { - ArrayList arrayList = new ArrayList(); - for (final String[] strArr : new String[][]{new String[]{"title", "Title"}, new String[]{"artist", "Artist"}, new String[]{"added", "Recently added"}, new String[]{"year", "Year"}, new String[]{"duration", "Length"}}) { - arrayList.add(new Lists.Item(strArr[0].equals(this.sortMode) ? R.drawable.ic_check : R.drawable.ic_sort, strArr[1], new Runnable() { // from class: com.mulberry.player.MainActivity.27 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.sortMode = strArr[0]; - MainActivity.this.libTab = 0; - MainActivity.this.styleTabs(); - MainActivity.this.fillLibrary(); - } - })); - } - arrayList.add(new Lists.Item(R.drawable.ic_refresh, "Rescan library", new Runnable() { // from class: com.mulberry.player.MainActivity.28 - @Override // java.lang.Runnable - public void run() { - App.I.library.refresh(); - MainActivity.toast("Rescanning…"); - } - })); - Lists.sheet(this, "Sort songs by", null, arrayList); - } - - @Override // com.mulberry.player.Library.Listener - public void onLibraryChanged() { - fillLibrary(); - if (this.page == 1) { - rebuildPlaylists(); - } - if (this.svc == null || !this.svc.queue().isEmpty()) { - return; - } - onTrackChanged(); - } - - void songMenu(final Song song, final Playlists.PL pl, final int i) { - ArrayList arrayList = new ArrayList(); - final List listSingletonList = Collections.singletonList(song); - arrayList.add(new Lists.Item(R.drawable.ic_queue_play_next, "Play next", new Runnable() { // from class: com.mulberry.player.MainActivity.31 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.withService(new Runnable() { // from class: com.mulberry.player.MainActivity.31.1 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.playNext(listSingletonList); - MainActivity.toast("Plays next"); - } - }); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_queue_music, "Add to queue", new Runnable() { // from class: com.mulberry.player.MainActivity.32 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.withService(new Runnable() { // from class: com.mulberry.player.MainActivity.32.1 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.enqueue(listSingletonList); - MainActivity.toast("Added to queue"); - } - }); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_playlist_add, "Add to playlist…", new Runnable() { // from class: com.mulberry.player.MainActivity.33 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.addToPlaylist(listSingletonList); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_edit, "Edit tags…", new Runnable() { // from class: com.mulberry.player.MainActivity.34 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.editTags(listSingletonList); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_cloud_download, "Fetch tags (MusicBrainz)", new Runnable() { // from class: com.mulberry.player.MainActivity.35 - @Override // java.lang.Runnable - public void run() { - TagEditorActivity.open(MainActivity.this, listSingletonList, 1); - } - })); - final boolean zFav = PlayStats.fav(song); - arrayList.add(new Lists.Item(zFav ? R.drawable.ic_favorite_fill : R.drawable.ic_favorite, zFav ? "Remove from favourites" : "Add to favourites", new Runnable() { // from class: com.mulberry.player.MainActivity.36 - @Override // java.lang.Runnable - public void run() { - PlayStats.setFav(song, !zFav); - if (MainActivity.this.svc != null) { - MainActivity.this.svc.refreshUi(); - } - } - })); - if (song.album.length() > 0) { - arrayList.add(new Lists.Item(R.drawable.ic_album, "Go to album", new Runnable() { // from class: com.mulberry.player.MainActivity.37 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.goToAlbum(song); - } - })); - } - if (song.displayArtist().length() > 0) { - arrayList.add(new Lists.Item(R.drawable.ic_artist, "Go to artist", new Runnable() { // from class: com.mulberry.player.MainActivity.38 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.goToArtist(song); - } - })); - } - if (pl != null) { - arrayList.add(new Lists.Item(R.drawable.ic_expand_more, "Move down", new Runnable() { // from class: com.mulberry.player.MainActivity.39 - @Override // java.lang.Runnable - public void run() { - Playlists.move(pl, i, i + 1); - MainActivity.this.refreshTopDetail(); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_drag_indicator, "Move up", new Runnable() { // from class: com.mulberry.player.MainActivity.40 - @Override // java.lang.Runnable - public void run() { - Playlists.move(pl, i, i - 1); - MainActivity.this.refreshTopDetail(); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_delete, "Remove from playlist", new Runnable() { // from class: com.mulberry.player.MainActivity.41 - @Override // java.lang.Runnable - public void run() { - Playlists.removeAt(pl, i); - MainActivity.this.refreshTopDetail(); - } - })); - } - arrayList.add(new Lists.Item(R.drawable.ic_link, "Share", new Runnable() { // from class: com.mulberry.player.MainActivity.42 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.share(song); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_info, "Details", new Runnable() { // from class: com.mulberry.player.MainActivity.43 - @Override // java.lang.Runnable - public void run() { - TagEditorActivity.open(MainActivity.this, listSingletonList, 0); - } - })); - Lists.sheet(this, song.displayTitle(), song.displayArtist(), arrayList); - } - - void groupMenu(String str, List list) { - ArrayList arrayList = new ArrayList(); - final ArrayList arrayList2 = new ArrayList(list); - arrayList.add(new Lists.Item(R.drawable.ic_play_arrow_fill, "Play", new Runnable() { // from class: com.mulberry.player.MainActivity.44 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.withService(new Runnable() { // from class: com.mulberry.player.MainActivity.44.1 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.playList(arrayList2, 0); - } - }); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_shuffle, "Shuffle", new Runnable() { // from class: com.mulberry.player.MainActivity.45 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.withService(new Runnable() { // from class: com.mulberry.player.MainActivity.45.1 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.playShuffled(arrayList2); - } - }); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_queue_play_next, "Play next", new Runnable() { // from class: com.mulberry.player.MainActivity.46 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.withService(new Runnable() { // from class: com.mulberry.player.MainActivity.46.1 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.playNext(arrayList2); - } - }); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_queue_music, "Add to queue", new Runnable() { // from class: com.mulberry.player.MainActivity.47 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.withService(new Runnable() { // from class: com.mulberry.player.MainActivity.47.1 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.enqueue(arrayList2); - } - }); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_playlist_add, "Add to playlist…", new Runnable() { // from class: com.mulberry.player.MainActivity.48 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.addToPlaylist(arrayList2); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_edit, "Edit tags (" + arrayList2.size() + " songs)…", new Runnable() { // from class: com.mulberry.player.MainActivity.49 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.editTags(arrayList2); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_cloud_download, "Fetch tags for all (MusicBrainz)", new Runnable() { // from class: com.mulberry.player.MainActivity.50 - @Override // java.lang.Runnable - public void run() { - TagEditorActivity.open(MainActivity.this, arrayList2, 3); - } - })); - Lists.sheet(this, str, arrayList2.size() + " songs", arrayList); - } - - void editTags(List list) { - ArrayList arrayList = new ArrayList(); - for (Song song : list) { - if (Tagger.canTag(this, song)) { - arrayList.add(song); - } - } - if (arrayList.isEmpty()) { - toast("These files can't be tagged (supported: MP3, M4A, AAC, FLAC, OGG, Opus, WMA, WAV, AIFF)"); - return; - } - if (arrayList.size() < list.size()) { - toast((list.size() - arrayList.size()) + " file(s) skipped — format can't be tagged"); - } - TagEditorActivity.open(this, arrayList, 0); - } - - void share(Song song) { - try { - Intent intent = new Intent("android.intent.action.SEND"); - intent.setType((song.mime == null || song.mime.length() <= 0) ? "audio/*" : song.mime); - intent.putExtra("android.intent.extra.STREAM", song.toUri()); - intent.putExtra("android.intent.extra.TEXT", song.displayArtist() + " – " + song.displayTitle()); - intent.addFlags(1); - startActivity(Intent.createChooser(intent, "Share")); - } catch (Exception e) { - toast("Can't share this file"); - } - } - - void goToAlbum(Song song) { - for (Library.Group group : App.I.library.albums) { - Iterator it = group.songs.iterator(); - while (it.hasNext()) { - if (it.next().key().equals(song.key())) { - closePlayer(); - openGroup(group.title, group.subtitle, group.songs, true, null); - return; - } - } - } - } - - void goToArtist(Song song) { - for (Library.Group group : App.I.library.artists) { - Iterator it = group.songs.iterator(); - while (it.hasNext()) { - if (it.next().key().equals(song.key())) { - closePlayer(); - openGroup(group.title, group.subtitle, group.songs, false, null); - return; - } - } - } - } - - void addToPlaylist(final List list) { - List listAll = Playlists.all(); - ArrayList arrayList = new ArrayList(); - arrayList.add(new Lists.Item(R.drawable.ic_add, "New playlist…", new Runnable() { // from class: com.mulberry.player.MainActivity.51 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.askText("New playlist", "Name", FrameBodyCOMM.DEFAULT, new TextCb() { // from class: com.mulberry.player.MainActivity.51.1 - @Override // com.mulberry.player.MainActivity.TextCb - public void ok(String str) { - Playlists.create(str, list); - MainActivity.toast("Created “" + str + "”"); - } - }); - } - })); - for (final Playlists.PL pl : listAll) { - arrayList.add(new Lists.Item(R.drawable.ic_queue_music, pl.name, new Runnable() { // from class: com.mulberry.player.MainActivity.52 - @Override // java.lang.Runnable - public void run() { - Playlists.add(pl, list); - MainActivity.toast("Added to “" + pl.name + "”"); - } - })); - } - Lists.sheet(this, "Add to playlist", list.size() + (list.size() == 1 ? " song" : " songs"), arrayList); - } - - void askText(String str, String str2, String str3, final TextCb textCb) { - final EditText editTextField = Ui.field(this, str2, str3); - editTextField.setSingleLine(true); - FrameLayout frameLayout = new FrameLayout(this); - frameLayout.setPadding(Ui.dp(this, 22.0f), Ui.dp(this, 8.0f), Ui.dp(this, 22.0f), 0); - frameLayout.addView(editTextField); - Ui.show(Ui.dialog(this).setTitle(str).setView(frameLayout).setPositiveButton("OK", new DialogInterface.OnClickListener() { // from class: com.mulberry.player.MainActivity.53 - @Override // android.content.DialogInterface.OnClickListener - public void onClick(DialogInterface dialogInterface, int i) { - String strTrim = editTextField.getText().toString().trim(); - if (strTrim.length() > 0) { - textCb.ok(strTrim); - } - } - }).setNegativeButton("Cancel", (DialogInterface.OnClickListener) null)); - } - - void openGroup(String str, String str2, final List list, boolean z, final Playlists.PL pl) { - long j; - LinearLayout linearLayoutCol = Ui.col(this); - Ui.plain(linearLayoutCol, 6); - linearLayoutCol.setClickable(true); - linearLayoutCol.setPadding(0, this.insetTop, 0, 0); - LinearLayout linearLayoutRow = Ui.row(this); - linearLayoutRow.setPadding(Ui.dp(this, 6.0f), Ui.dp(this, 6.0f), Ui.dp(this, 10.0f), 0); - linearLayoutRow.addView(Ui.iconButton(this, R.drawable.ic_arrow_back, 11, 44, new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.54 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - MainActivity.this.popDetail(true); - } - })); - linearLayoutRow.addView(new View(this), Ui.lpw(1, 1.0f)); - linearLayoutRow.addView(Ui.iconButton(this, R.drawable.ic_more_vert, 11, 44, new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.55 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - if (pl == null) { - MainActivity.this.groupMenu(MainActivity.this.currentTitle(), list); - } else { - MainActivity.this.playlistMenu(pl); - } - } - })); - linearLayoutCol.addView(linearLayoutRow); - LinearLayout linearLayoutRow2 = Ui.row(this); - linearLayoutRow2.setPadding(Ui.dp(this, 20.0f), Ui.dp(this, 4.0f), Ui.dp(this, 20.0f), Ui.dp(this, 12.0f)); - if (!list.isEmpty()) { - ImageView imageViewCoverView = Lists.coverView(this, 112, 28.0f); - Lists.bindCover(imageViewCoverView, list.get(0), 400); - linearLayoutRow2.addView(imageViewCoverView); - } - LinearLayout linearLayoutCol2 = Ui.col(this); - linearLayoutCol2.setPadding(Ui.dp(this, 16.0f), 0, 0, 0); - TextView textViewText = Ui.text(this, str, 24.0f, 11, true); - textViewText.setMaxLines(3); - textViewText.setTag("title"); - linearLayoutCol2.addView(textViewText); - if (str2 == null) { - str2 = list.size() + " songs"; - } - linearLayoutCol2.addView(Ui.single(this, str2, 14.0f, 12, false)); - long j2 = 0; - Iterator it = list.iterator(); - while (true) { - j = j2; - if (!it.hasNext()) { - break; - } else { - j2 = it.next().duration + j; - } - } - linearLayoutCol2.addView(Ui.single(this, Draw.time(j), 13.0f, 12, false)); - linearLayoutRow2.addView(linearLayoutCol2, Ui.lpw(-2, 1.0f)); - linearLayoutCol.addView(linearLayoutRow2); - LinearLayout linearLayoutRow3 = Ui.row(this); - linearLayoutRow3.setPadding(Ui.dp(this, 20.0f), 0, Ui.dp(this, 20.0f), Ui.dp(this, 8.0f)); - linearLayoutRow3.addView(Ui.pill(this, R.drawable.ic_play_arrow_fill, "Play", true, new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.56 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - final ArrayList arrayList = new ArrayList(list); - if (!arrayList.isEmpty()) { - MainActivity.this.withService(new Runnable() { // from class: com.mulberry.player.MainActivity.56.1 - @Override // java.lang.Runnable - public void run() { - if (MainActivity.this.svc.shuffle()) { - MainActivity.this.svc.setShuffle(false); - } - MainActivity.this.svc.playList(arrayList, 0); - } - }); - } - } - })); - linearLayoutRow3.addView(Ui.space(this, 10)); - linearLayoutRow3.addView(Ui.pill(this, R.drawable.ic_shuffle, "Shuffle", false, new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.57 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - final ArrayList arrayList = new ArrayList(list); - if (!arrayList.isEmpty()) { - MainActivity.this.withService(new Runnable() { // from class: com.mulberry.player.MainActivity.57.1 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.playShuffled(arrayList); - } - }); - } - } - })); - linearLayoutCol.addView(linearLayoutRow3); - ListView list2 = Lists.list(this); - list2.setTag("list"); - list2.setPadding(Ui.dp(this, 6.0f), 0, Ui.dp(this, 6.0f), this.listBottom); - Lists.SongAdapter songAdapter = new Lists.SongAdapter(this, new Lists.SongClick() { // from class: com.mulberry.player.MainActivity.58 - @Override // com.mulberry.player.Lists.SongClick - public void click(List list3, final int i) { - final ArrayList arrayList = new ArrayList(list3); - MainActivity.this.withService(new Runnable() { // from class: com.mulberry.player.MainActivity.58.1 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.playList(arrayList, i); - } - }); - } - - @Override // com.mulberry.player.Lists.SongClick - public void longClick(List list3, int i, View view) { - MainActivity.this.songMenu(list3.get(i), pl, i); - } - }); - songAdapter.numbers = z; - songAdapter.playing = this.svc == null ? null : this.svc.current(); - songAdapter.set(new ArrayList(pl != null ? pl.songs : list)); - list2.setAdapter((ListAdapter) songAdapter); - linearLayoutCol.addView(list2, Ui.lp(-1, 0)); - ((LinearLayout.LayoutParams) list2.getLayoutParams()).weight = 1.0f; - linearLayoutCol.setTag(R.id.detail_adapter, songAdapter); - if (pl != null) { - linearLayoutCol.setTag(R.id.detail_pl, pl); - } - pushDetail(linearLayoutCol); - } - - String currentTitle() { - TextView textView; - return (this.stack.isEmpty() || (textView = (TextView) this.stack.get(this.stack.size() + (-1)).findViewWithTag("title")) == null) ? FrameBodyCOMM.DEFAULT : textView.getText().toString(); - } - - void refreshTopDetail() { - for (View view : this.stack) { - Object tag = view.getTag(R.id.detail_adapter); - if (tag instanceof Lists.SongAdapter) { - Lists.SongAdapter songAdapter = (Lists.SongAdapter) tag; - songAdapter.playing = this.svc == null ? null : this.svc.current(); - Object tag2 = view.getTag(R.id.detail_pl); - if (tag2 instanceof Playlists.PL) { - songAdapter.set(new ArrayList(((Playlists.PL) tag2).songs)); - } else { - songAdapter.notifyDataSetChanged(); - } - } - } - } - - void pushDetail(View view) { - this.pages.addView(view, new FrameLayout.LayoutParams(-1, -1)); - this.stack.add(view); - if (!App.lowPower()) { - view.setTranslationX(Ui.dp(this, 60.0f)); - view.setAlpha(0.0f); - view.animate().translationX(0.0f).alpha(1.0f).setDuration(240L).setInterpolator(new PathInterpolator(0.2f, 0.0f, 0.0f, 1.0f)).start(); - } - } - - void popDetail(boolean z) { - if (!this.stack.isEmpty()) { - final View viewRemove = this.stack.remove(this.stack.size() - 1); - if (z && !App.lowPower()) { - viewRemove.animate().translationX(Ui.dp(this, 60.0f)).alpha(0.0f).setDuration(180L).withEndAction(new Runnable() { // from class: com.mulberry.player.MainActivity.59 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.pages.removeView(viewRemove); - } - }).start(); - } else { - this.pages.removeView(viewRemove); - } - } - } - - @Override // android.app.Activity - public void onBackPressed() { - if (!this.player.open) { - if (this.stack.isEmpty()) { - if (this.search.getText().length() <= 0 || this.page != 0) { - if (this.page == 0) { - moveTaskToBack(true); - return; - } else { - showPage(0, true); - return; - } - } - this.search.setText(FrameBodyCOMM.DEFAULT); - return; - } - popDetail(true); - return; - } - closePlayer(); - } - - View buildPlaylists() { - ScrollView scrollView = new ScrollView(this); - scrollView.setClipToPadding(false); - this.plBox = Ui.col(this); - this.plBox.setPadding(Ui.dp(this, 12.0f), 0, Ui.dp(this, 12.0f), Ui.dp(this, 140.0f)); - scrollView.addView(this.plBox); - return scrollView; - } - - @Override // com.mulberry.player.Playlists.Listener - public void onPlaylistsChanged() { - if (this.page == 1) { - rebuildPlaylists(); - } - refreshTopDetail(); - } - - void rebuildPlaylists() { - this.plBox.removeAllViews(); - LinearLayout linearLayoutRow = Ui.row(this); - linearLayoutRow.setPadding(Ui.dp(this, 8.0f), Ui.dp(this, 14.0f), 0, Ui.dp(this, 10.0f)); - linearLayoutRow.addView(Ui.title(this, "Playlists"), Ui.lpw(-2, 1.0f)); - this.plBox.addView(linearLayoutRow); - HorizontalScrollView horizontalScrollView = new HorizontalScrollView(this); - horizontalScrollView.setHorizontalScrollBarEnabled(false); - LinearLayout linearLayoutRow2 = Ui.row(this); - linearLayoutRow2.setPadding(Ui.dp(this, 6.0f), 0, Ui.dp(this, 6.0f), Ui.dp(this, 12.0f)); - linearLayoutRow2.addView(Ui.pill(this, R.drawable.ic_add, "New", true, new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.60 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - MainActivity.this.askText("New playlist", "Name", FrameBodyCOMM.DEFAULT, new TextCb() { // from class: com.mulberry.player.MainActivity.60.1 - @Override // com.mulberry.player.MainActivity.TextCb - public void ok(String str) { - Playlists.create(str, null); - } - }); - } - })); - linearLayoutRow2.addView(Ui.space(this, 8)); - linearLayoutRow2.addView(Ui.pill(this, R.drawable.ic_download, "Import", false, new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.61 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - MainActivity.this.importPlaylist(); - } - })); - linearLayoutRow2.addView(Ui.space(this, 8)); - linearLayoutRow2.addView(Ui.pill(this, R.drawable.ic_upload, "Export all", false, new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.62 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - MainActivity.this.exportAllDialog(); - } - })); - linearLayoutRow2.addView(Ui.space(this, 8)); - linearLayoutRow2.addView(Ui.pill(this, R.drawable.ic_save, "Save queue", false, new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.63 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - if (MainActivity.this.svc != null && !MainActivity.this.svc.queue().isEmpty()) { - MainActivity.this.askText("Save queue as playlist", "Name", "Queue", new TextCb() { // from class: com.mulberry.player.MainActivity.63.1 - @Override // com.mulberry.player.MainActivity.TextCb - public void ok(String str) { - Playlists.create(str, new ArrayList(MainActivity.this.svc.queue())); - } - }); - } else { - MainActivity.toast("The queue is empty"); - } - } - })); - horizontalScrollView.addView(linearLayoutRow2); - this.plBox.addView(horizontalScrollView); - this.plBox.addView(section("Smart playlists")); - List list = App.I.library.songs; - smart(R.drawable.ic_favorite_fill, "Favourites", PlayStats.favourites(list)); - smart(R.drawable.ic_trending_up, "Most played", PlayStats.mostPlayed(list, 100)); - smart(R.drawable.ic_history, "Recently played", PlayStats.recentlyPlayed(list, 100)); - smart(R.drawable.ic_auto_awesome, "Recently added", PlayStats.recentlyAdded(list, 100)); - smart(R.drawable.ic_visibility, "Never played", PlayStats.neverPlayed(list)); - List listAll = Playlists.all(); - this.plBox.addView(section(listAll.isEmpty() ? "Your playlists — none yet" : "Your playlists")); - for (final Playlists.PL pl : listAll) { - LinearLayout linearLayoutPlRow = plRow(R.drawable.ic_queue_music, pl.name, pl.songs.size() + " songs", false); - linearLayoutPlRow.setOnClickListener(new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.64 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - MainActivity.this.openGroup(pl.name, pl.songs.size() + " songs", pl.songs, false, pl); - } - }); - linearLayoutPlRow.setOnLongClickListener(new View.OnLongClickListener() { // from class: com.mulberry.player.MainActivity.65 - @Override // android.view.View.OnLongClickListener - public boolean onLongClick(View view) { - MainActivity.this.playlistMenu(pl); - return true; - } - }); - this.plBox.addView(linearLayoutPlRow); - } - this.plBox.setPadding(this.plBox.getPaddingLeft(), this.plBox.getPaddingTop(), this.plBox.getPaddingRight(), this.listBottom); - } - - TextView section(String str) { - TextView textViewSingle = Ui.single(this, str, 14.0f, 0, true); - textViewSingle.setPadding(Ui.dp(this, 10.0f), Ui.dp(this, 14.0f), 0, Ui.dp(this, 6.0f)); - return textViewSingle; - } - - void smart(int i, final String str, final List list) { - LinearLayout linearLayoutPlRow = plRow(i, str, list.size() + " songs", true); - linearLayoutPlRow.setOnClickListener(new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.66 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - MainActivity.this.openGroup(str, list.size() + " songs", list, false, null); - } - }); - linearLayoutPlRow.setOnLongClickListener(new View.OnLongClickListener() { // from class: com.mulberry.player.MainActivity.67 - @Override // android.view.View.OnLongClickListener - public boolean onLongClick(View view) { - MainActivity.this.groupMenu(str, list); - return true; - } - }); - this.plBox.addView(linearLayoutPlRow); - } - - LinearLayout plRow(int i, String str, String str2, boolean z) { - LinearLayout linearLayoutRow = Ui.row(this); - linearLayoutRow.setPadding(Ui.dp(this, 8.0f), Ui.dp(this, 8.0f), Ui.dp(this, 8.0f), Ui.dp(this, 8.0f)); - Ui.clickable(linearLayoutRow, 18.0f); - ImageView imageViewIcon = Ui.icon(this, i, z ? 11 : 5, 52); - int iDp = Ui.dp(this, 14.0f); - imageViewIcon.setPadding(iDp, iDp, iDp, iDp); - imageViewIcon.setBackground(Ui.round(Ui.c(z ? 16 : 4), Ui.dpf(this, 16.0f))); - linearLayoutRow.addView(imageViewIcon); - LinearLayout linearLayoutCol = Ui.col(this); - linearLayoutCol.setPadding(Ui.dp(this, 14.0f), 0, 0, 0); - linearLayoutCol.addView(Ui.single(this, str, 16.0f, 11, true)); - linearLayoutCol.addView(Ui.single(this, str2, 13.0f, 12, false)); - linearLayoutRow.addView(linearLayoutCol, Ui.lpw(-2, 1.0f)); - return linearLayoutRow; - } - - void playlistMenu(final Playlists.PL pl) { - ArrayList arrayList = new ArrayList(); - arrayList.add(new Lists.Item(R.drawable.ic_play_arrow_fill, "Play", new Runnable() { // from class: com.mulberry.player.MainActivity.68 - @Override // java.lang.Runnable - public void run() { - final ArrayList arrayList2 = new ArrayList(pl.songs); - if (!arrayList2.isEmpty()) { - MainActivity.this.withService(new Runnable() { // from class: com.mulberry.player.MainActivity.68.1 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.playList(arrayList2, 0); - } - }); - } - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_queue_music, "Add to queue", new Runnable() { // from class: com.mulberry.player.MainActivity.69 - @Override // java.lang.Runnable - public void run() { - final ArrayList arrayList2 = new ArrayList(pl.songs); - if (!arrayList2.isEmpty()) { - MainActivity.this.withService(new Runnable() { // from class: com.mulberry.player.MainActivity.69.1 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.enqueue(arrayList2); - } - }); - } - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_edit, "Rename", new Runnable() { // from class: com.mulberry.player.MainActivity.70 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.askText("Rename playlist", "Name", pl.name, new TextCb() { // from class: com.mulberry.player.MainActivity.70.1 - @Override // com.mulberry.player.MainActivity.TextCb - public void ok(String str) { - Playlists.rename(pl, str); - } - }); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_upload, "Export…", new Runnable() { // from class: com.mulberry.player.MainActivity.71 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.exportOne(pl); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_label, "Edit tags of all songs…", new Runnable() { // from class: com.mulberry.player.MainActivity.72 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.editTags(new ArrayList(pl.songs)); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_delete, "Delete playlist", new Runnable() { // from class: com.mulberry.player.MainActivity.73 - @Override // java.lang.Runnable - public void run() { - Ui.show(Ui.dialog(MainActivity.this).setTitle("Delete “" + pl.name + "”?").setMessage("The songs themselves are not deleted.").setPositiveButton("Delete", new DialogInterface.OnClickListener() { // from class: com.mulberry.player.MainActivity.73.1 - @Override // android.content.DialogInterface.OnClickListener - public void onClick(DialogInterface dialogInterface, int i) { - Playlists.delete(pl); - MainActivity.this.popDetail(true); - } - }).setNegativeButton("Cancel", (DialogInterface.OnClickListener) null)); - } - })); - Lists.sheet(this, pl.name, pl.songs.size() + " songs", arrayList); - } - - void importPlaylist() { - Intent intent = new Intent("android.intent.action.OPEN_DOCUMENT"); - intent.addCategory("android.intent.category.OPENABLE"); - intent.setType("*/*"); - intent.putExtra("android.intent.extra.MIME_TYPES", new String[]{"audio/x-mpegurl", "audio/mpegurl", "application/vnd.apple.mpegurl", "audio/x-scpls", "application/octet-stream", "text/plain"}); - intent.putExtra("android.intent.extra.ALLOW_MULTIPLE", true); - try { - startActivityForResult(intent, 10); - } catch (Exception e) { - toast("No file picker available"); - } - } - - void doImport(final Uri uri) { - App.IO.execute(new Runnable() { // from class: com.mulberry.player.MainActivity.74 - @Override // java.lang.Runnable - public void run() { - try { - final Playlists.Parsed parsedImportUri = Playlists.importUri(MainActivity.this, uri); - App.ui(new Runnable() { // from class: com.mulberry.player.MainActivity.74.1 - @Override // java.lang.Runnable - public void run() { - if (!parsedImportUri.songs.isEmpty()) { - Playlists.create(parsedImportUri.name, parsedImportUri.songs); - MainActivity.toast("Imported “" + parsedImportUri.name + "”: " + parsedImportUri.songs.size() + " songs" + (parsedImportUri.missing > 0 ? ", " + parsedImportUri.missing + " not found" : FrameBodyCOMM.DEFAULT)); - } else { - MainActivity.toast("No songs from “" + parsedImportUri.name + "” were found on this phone"); - } - } - }); - } catch (Exception e) { - MainActivity.toast("Import failed: " + e.getMessage()); - } - } - }); - } - - void exportOne(final Playlists.PL pl) { - final String[] strArr = {"m3u8", "m3u", "pls"}; - Ui.show(Ui.dialog(this).setTitle("Export “" + pl.name + "” as").setItems(new String[]{"M3U8 (UTF-8, recommended)", "M3U", "PLS"}, new DialogInterface.OnClickListener() { // from class: com.mulberry.player.MainActivity.75 - @Override // android.content.DialogInterface.OnClickListener - public void onClick(DialogInterface dialogInterface, int i) { - MainActivity.this.exportPl = pl; - MainActivity.this.exportFmt = strArr[i]; - Intent intent = new Intent("android.intent.action.CREATE_DOCUMENT"); - intent.addCategory("android.intent.category.OPENABLE"); - intent.setType("pls".equals(MainActivity.this.exportFmt) ? "audio/x-scpls" : "audio/x-mpegurl"); - intent.putExtra("android.intent.extra.TITLE", Playlists.safeName(pl.name) + "." + MainActivity.this.exportFmt); - try { - MainActivity.this.startActivityForResult(intent, 11); - } catch (Exception e) { - MainActivity.toast("No file picker available"); - } - } - })); - } - - void exportAllDialog() { - if (!Playlists.all().isEmpty()) { - LinearLayout linearLayoutCol = Ui.col(this); - linearLayoutCol.setPadding(Ui.dp(this, 24.0f), Ui.dp(this, 8.0f), Ui.dp(this, 24.0f), 0); - linearLayoutCol.addView(Ui.text(this, "File type", 14.0f, 12, true)); - final RadioGroup radioGroup = new RadioGroup(this); - String[] strArr = {"M3U8 (UTF-8, recommended)", "M3U", "PLS"}; - final String[] strArr2 = {"m3u8", "m3u", "pls"}; - for (int i = 0; i < 3; i++) { - RadioButton radioButton = new RadioButton(this); - radioButton.setText(strArr[i]); - radioButton.setId(i + 1000); - radioButton.setTextColor(Ui.c(11)); - radioButton.setButtonTintList(ColorStateList.valueOf(Ui.c(0))); - radioGroup.addView(radioButton); - } - radioGroup.check(1000); - linearLayoutCol.addView(radioGroup); - final CheckBox checkBox = new CheckBox(this); - checkBox.setText("Replace files that already exist"); - checkBox.setChecked(true); - checkBox.setTextColor(Ui.c(11)); - checkBox.setButtonTintList(ColorStateList.valueOf(Ui.c(0))); - linearLayoutCol.addView(checkBox); - linearLayoutCol.addView(Ui.text(this, "Songs are written with full paths, so the lists open in Mulberry on other phones and PCs too.", 13.0f, 12, false)); - Ui.show(Ui.dialog(this).setTitle("Export all playlists").setView(linearLayoutCol).setPositiveButton("Choose folder", new DialogInterface.OnClickListener() { // from class: com.mulberry.player.MainActivity.76 - @Override // android.content.DialogInterface.OnClickListener - public void onClick(DialogInterface dialogInterface, int i2) { - MainActivity.this.exportFmt = strArr2[Math.max(0, radioGroup.getCheckedRadioButtonId() - 1000)]; - MainActivity.this.exportReplace = checkBox.isChecked(); - try { - MainActivity.this.startActivityForResult(new Intent("android.intent.action.OPEN_DOCUMENT_TREE"), 12); - } catch (Exception e) { - MainActivity.toast("No folder picker available"); - } - } - }).setNegativeButton("Cancel", (DialogInterface.OnClickListener) null)); - return; - } - toast("No playlists to export"); - } - - @Override // android.app.Activity - protected void onActivityResult(int i, int i2, final Intent intent) { - super.onActivityResult(i, i2, intent); - if (i2 == -1 && intent != null) { - if (i == 10) { - if (intent.getClipData() != null) { - for (int i3 = 0; i3 < intent.getClipData().getItemCount(); i3++) { - doImport(intent.getClipData().getItemAt(i3).getUri()); - } - return; - } - if (intent.getData() != null) { - doImport(intent.getData()); - return; - } - return; - } - if (i == 11 && this.exportPl != null && intent.getData() != null) { - final Playlists.PL pl = this.exportPl; - App.IO.execute(new Runnable() { // from class: com.mulberry.player.MainActivity.77 - @Override // java.lang.Runnable - public void run() { - try { - Playlists.writeTo(MainActivity.this, intent.getData(), pl, MainActivity.this.exportFmt); - MainActivity.toast("Exported “" + pl.name + "”"); - } catch (Exception e) { - MainActivity.toast("Export failed: " + e.getMessage()); - } - } - }); - } else if (i == 12 && intent.getData() != null) { - final Uri data = intent.getData(); - try { - getContentResolver().takePersistableUriPermission(data, 3); - } catch (Exception e) { - } - App.IO.execute(new Runnable() { // from class: com.mulberry.player.MainActivity.78 - @Override // java.lang.Runnable - public void run() { - try { - int iExportAll = Playlists.exportAll(MainActivity.this, data, MainActivity.this.exportFmt, MainActivity.this.exportReplace); - MainActivity.toast("Exported " + iExportAll + " playlist" + (iExportAll == 1 ? FrameBodyCOMM.DEFAULT : "s")); - } catch (Exception e2) { - MainActivity.toast("Export failed: " + e2.getMessage()); - } - } - }); - } - } - } - - void openPlayer() { - if (this.svc != null && this.svc.current() != null) { - this.player.updateTrack(); - this.player.animateOpen(true); - this.mini.setVisibility(4); - } - } - - void closePlayer() { - if (this.player.open) { - this.player.animateOpen(false); - this.mini.setVisibility((this.svc == null || this.svc.current() == null) ? 8 : 0); - } - } - - void togglePlay() { - withService(new Runnable() { // from class: com.mulberry.player.MainActivity.79 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.toggle(); - } - }); - } - - void toggleFav() { - if (this.svc != null && this.svc.current() != null) { - Song songCurrent = this.svc.current(); - boolean z = !PlayStats.fav(songCurrent); - PlayStats.setFav(songCurrent, z); - if (z && LastFm.anyOn()) { - LastFm.love(songCurrent, true); - } - this.svc.refreshUi(); - this.player.updateTrack(); - } - } - - void playerMenu() { - if (this.svc != null && this.svc.current() != null) { - final Song songCurrent = this.svc.current(); - ArrayList arrayList = new ArrayList(); - arrayList.add(new Lists.Item(R.drawable.ic_playlist_add, "Add to playlist…", new Runnable() { // from class: com.mulberry.player.MainActivity.80 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.addToPlaylist(Collections.singletonList(songCurrent)); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_edit, "Edit tags…", new Runnable() { // from class: com.mulberry.player.MainActivity.81 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.editTags(Collections.singletonList(songCurrent)); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_album, "Go to album", new Runnable() { // from class: com.mulberry.player.MainActivity.82 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.goToAlbum(songCurrent); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_artist, "Go to artist", new Runnable() { // from class: com.mulberry.player.MainActivity.83 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.goToArtist(songCurrent); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_history, "Sleep timer", new Runnable() { // from class: com.mulberry.player.MainActivity.84 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.sleepTimer(); - } - })); - if (LastFm.anyOn()) { - arrayList.add(new Lists.Item(R.drawable.ic_favorite, LastFm.enabled() ? "Love on Last.fm" : "Love on ListenBrainz", new Runnable() { // from class: com.mulberry.player.MainActivity.85 - @Override // java.lang.Runnable - public void run() { - LastFm.love(songCurrent, true); - MainActivity.toast("Loved"); - } - })); - } - arrayList.add(new Lists.Item(R.drawable.ic_link, "Share", new Runnable() { // from class: com.mulberry.player.MainActivity.86 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.share(songCurrent); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_stop_fill, "Stop & close", new Runnable() { // from class: com.mulberry.player.MainActivity.87 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.closePlayer(); - MainActivity.this.svc.stopAndQuit(); - } - })); - Lists.sheet(this, songCurrent.displayTitle(), songCurrent.displayArtist(), arrayList); - } - } - - void lyricsMenu() { - int i = R.drawable.ic_check; - String str = App.I.prefs.getStr(Prefs.LYRICS_SOURCE, "auto"); - final boolean bool = App.I.prefs.getBool(Prefs.LYRICS_PLAIN, false); - ArrayList arrayList = new ArrayList(); - for (final String[] strArr : new String[][]{new String[]{"auto", "Auto (synced first, local last)"}, new String[]{"lrclib", "LRCLIB"}, new String[]{"netease", "NetEase"}, new String[]{"local", "Local .lrc / embedded"}}) { - arrayList.add(new Lists.Item(strArr[0].equals(str) ? R.drawable.ic_check : R.drawable.ic_lyrics, strArr[1], new Runnable() { // from class: com.mulberry.player.MainActivity.88 - @Override // java.lang.Runnable - public void run() { - App.I.prefs.setStr(Prefs.LYRICS_SOURCE, strArr[0]); - if (MainActivity.this.svc != null) { - MainActivity.this.svc.reloadLyrics(false); - } - } - })); - } - if (!bool) { - i = R.drawable.ic_text_snippet; - } - arrayList.add(new Lists.Item(i, "Plain text (no timing)", new Runnable() { // from class: com.mulberry.player.MainActivity.89 - @Override // java.lang.Runnable - public void run() { - App.I.prefs.setBool(Prefs.LYRICS_PLAIN, !bool); - if (MainActivity.this.svc != null) { - MainActivity.this.svc.reloadLyrics(false); - } - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_refresh, "Search again", new Runnable() { // from class: com.mulberry.player.MainActivity.90 - @Override // java.lang.Runnable - public void run() { - if (MainActivity.this.svc != null) { - MainActivity.this.svc.reloadLyrics(true); - } - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_edit, "Edit / save lyrics…", new Runnable() { // from class: com.mulberry.player.MainActivity.91 - @Override // java.lang.Runnable - public void run() { - if (MainActivity.this.svc != null && MainActivity.this.svc.current() != null) { - TagEditorActivity.open(MainActivity.this, Collections.singletonList(MainActivity.this.svc.current()), 2); - } - } - })); - Lists.sheet(this, "Lyrics source", null, arrayList); - } - - void sleepTimer() { - if (this.svc != null) { - long jSleepRemaining = this.svc.sleepRemaining(); - String str = jSleepRemaining > 0 ? "Stops in " + Draw.time(jSleepRemaining) : jSleepRemaining < 0 ? "Stops after this song" : "Off"; - ArrayList arrayList = new ArrayList(); - for (final int i : new int[]{10, 15, 30, 45, 60, 90}) { - arrayList.add(new Lists.Item(R.drawable.ic_history, i + " minutes", new Runnable() { // from class: com.mulberry.player.MainActivity.92 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.sleepIn(i); - MainActivity.toast("Sleep timer: " + i + " min"); - } - })); - } - arrayList.add(new Lists.Item(R.drawable.ic_music_note, "End of this song", new Runnable() { // from class: com.mulberry.player.MainActivity.93 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.sleepAtEndOfTrack(); - MainActivity.toast("Stops after this song"); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_close, "Turn off", new Runnable() { // from class: com.mulberry.player.MainActivity.94 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.sleepIn(0); - MainActivity.toast("Sleep timer off"); - } - })); - Lists.sheet(this, "Sleep timer", str, arrayList); - } - } - - void showQueue() { - if (this.svc != null) { - final Dialog dialog = new Dialog(this); - dialog.requestWindowFeature(1); - LinearLayout linearLayoutCol = Ui.col(this); - Lists.GradientBg(linearLayoutCol, this); - linearLayoutCol.setPadding(Ui.dp(this, 6.0f), Ui.dp(this, 14.0f), Ui.dp(this, 6.0f), Ui.dp(this, 10.0f)); - LinearLayout linearLayoutRow = Ui.row(this); - linearLayoutRow.setPadding(Ui.dp(this, 14.0f), 0, Ui.dp(this, 6.0f), Ui.dp(this, 6.0f)); - linearLayoutRow.addView(Ui.single(this, "Up next · " + this.svc.queue().size() + " songs", 17.0f, 11, true), Ui.lpw(-2, 1.0f)); - linearLayoutRow.addView(Ui.iconButton(this, R.drawable.ic_save, 12, 40, new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.95 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - dialog.dismiss(); - MainActivity.this.askText("Save queue as playlist", "Name", "Queue", new TextCb() { // from class: com.mulberry.player.MainActivity.95.1 - @Override // com.mulberry.player.MainActivity.TextCb - public void ok(String str) { - Playlists.create(str, new ArrayList(MainActivity.this.svc.queue())); - MainActivity.toast("Saved"); - } - }); - } - })); - linearLayoutRow.addView(Ui.iconButton(this, R.drawable.ic_clear_all, 12, 40, new View.OnClickListener() { // from class: com.mulberry.player.MainActivity.96 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - dialog.dismiss(); - MainActivity.this.closePlayer(); - MainActivity.this.svc.clearQueue(); - } - })); - linearLayoutCol.addView(linearLayoutRow); - ListView list = Lists.list(this); - Lists.SongAdapter[] songAdapterArr = new Lists.SongAdapter[1]; - songAdapterArr[0] = new Lists.SongAdapter(this, new AnonymousClass97(songAdapterArr)); - songAdapterArr[0].playing = this.svc.current(); - songAdapterArr[0].set(new ArrayList(this.svc.queue())); - list.setAdapter((ListAdapter) songAdapterArr[0]); - linearLayoutCol.addView(list, new LinearLayout.LayoutParams(-1, (int) (getResources().getDisplayMetrics().heightPixels * 0.62f))); - list.setSelection(Math.max(0, this.svc.index() - 1)); - dialog.setContentView(linearLayoutCol); - Window window = dialog.getWindow(); - if (window != null) { - window.setBackgroundDrawable(new ColorDrawable(0)); - window.setGravity(80); - window.setLayout(-1, -2); - window.setWindowAnimations(android.R.style.Animation_InputMethod); - } - dialog.show(); - } - } - - /* JADX INFO: renamed from: com.mulberry.player.MainActivity$97, reason: invalid class name */ - class AnonymousClass97 implements Lists.SongClick { - final /* synthetic */ Lists.SongAdapter[] val$holder; - - AnonymousClass97(Lists.SongAdapter[] songAdapterArr) { - this.val$holder = songAdapterArr; - } - - @Override // com.mulberry.player.Lists.SongClick - public void click(List list, int i) { - MainActivity.this.svc.jump(i); - this.val$holder[0].playing = MainActivity.this.svc.current(); - this.val$holder[0].notifyDataSetChanged(); - } - - @Override // com.mulberry.player.Lists.SongClick - public void longClick(List list, final int i, View view) { - final Song song = list.get(i); - ArrayList arrayList = new ArrayList(); - arrayList.add(new Lists.Item(R.drawable.ic_play_arrow_fill, "Play now", new Runnable() { // from class: com.mulberry.player.MainActivity.97.1 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.jump(i); - AnonymousClass97.this.refresh(); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_drag_indicator, "Move up", new Runnable() { // from class: com.mulberry.player.MainActivity.97.2 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.move(i, i - 1); - AnonymousClass97.this.refresh(); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_expand_more, "Move down", new Runnable() { // from class: com.mulberry.player.MainActivity.97.3 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.move(i, i + 1); - AnonymousClass97.this.refresh(); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_queue_play_next, "Play after current", new Runnable() { // from class: com.mulberry.player.MainActivity.97.4 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.move(i, (i > MainActivity.this.svc.index() ? 1 : 0) + MainActivity.this.svc.index()); - AnonymousClass97.this.refresh(); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_delete, "Remove from queue", new Runnable() { // from class: com.mulberry.player.MainActivity.97.5 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.removeAt(i); - AnonymousClass97.this.refresh(); - } - })); - arrayList.add(new Lists.Item(R.drawable.ic_edit, "Edit tags…", new Runnable() { // from class: com.mulberry.player.MainActivity.97.6 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.editTags(Collections.singletonList(song)); - } - })); - Lists.sheet(MainActivity.this, song.displayTitle(), song.displayArtist(), arrayList); - } - - void refresh() { - this.val$holder[0].playing = MainActivity.this.svc.current(); - this.val$holder[0].set(new ArrayList(MainActivity.this.svc.queue())); - } - } - - @Override // com.mulberry.player.MusicService.Listener - public void onTrackChanged() { - if (this.svc != null) { - Song songCurrent = this.svc.current(); - boolean z = songCurrent != null; - if (!this.player.open) { - this.mini.setVisibility(z ? 0 : 8); - } - applyInsets(); - if (z) { - this.miniTitle.setText(songCurrent.displayTitle()); - this.miniArtist.setText(songCurrent.displayArtist()); - this.miniCookie.setCover(this.svc.art()); - this.miniSeek.set(this.svc.position(), this.svc.duration()); - } - this.songAdapter.playing = songCurrent; - this.songAdapter.notifyDataSetChanged(); - refreshTopDetail(); - if ("album".equals(App.I.prefs.getStr(Prefs.COLOR_SOURCE, "system"))) { - Ui.recolor(); - } - if (this.player.open) { - this.player.updateTrack(); - } - if (this.player.open && !z) { - closePlayer(); - } - onStateChanged(); - } - } - - @Override // com.mulberry.player.MusicService.Listener - public void onStateChanged() { - if (this.svc != null) { - this.miniPlay.setPlaying(this.svc.isPlaying() || this.svc.isLoading()); - this.miniCookie.setPlaying(this.svc.isPlaying()); - this.miniSeek.setPlaying(this.svc.isPlaying()); - this.bassShape.setPlaying(this.svc.isPlaying()); - if (this.player.open) { - this.player.updateState(); - } - } - } - - @Override // com.mulberry.player.MusicService.Listener - public void onQueueChanged() { - refreshTopDetail(); - } - - @Override // com.mulberry.player.MusicService.Listener - public void onLyrics() { - if (this.player.open) { - this.player.updateLyrics(); - } - } - - void handleIntent(Intent intent) { - if (intent != null) { - if (intent.getBooleanExtra("open_player", false)) { - intent.removeExtra("open_player"); - App.MAIN.postDelayed(new Runnable() { // from class: com.mulberry.player.MainActivity.98 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.openPlayer(); - } - }, 300L); - return; - } - if ("android.intent.action.VIEW".equals(intent.getAction()) && intent.getData() != null) { - final Uri data = intent.getData(); - String type = intent.getType() == null ? FrameBodyCOMM.DEFAULT : intent.getType(); - String lowerCase = Playlists.displayName(this, data).toLowerCase(Locale.ROOT); - intent.setAction(null); - if (type.contains("mpegurl") || type.contains("scpls") || lowerCase.endsWith(".m3u") || lowerCase.endsWith(".m3u8") || lowerCase.endsWith(".pls")) { - doImport(data); - showPage(1, false); - return; - } - final Song song = new Song(); - song.uri = data.toString(); - song.title = Playlists.displayName(this, data); - int iLastIndexOf = song.title.lastIndexOf(46); - if (iLastIndexOf > 0) { - song.title = song.title.substring(0, iLastIndexOf); - } - song.mime = type; - if ("file".equals(data.getScheme())) { - song.path = data.getPath(); - Song songByPath = App.I.library.byPath(song.path); - if (songByPath != null) { - playOpened(songByPath); - return; - } - } - App.IO.execute(new Runnable() { // from class: com.mulberry.player.MainActivity.99 - @Override // java.lang.Runnable - public void run() { - MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever(); - try { - mediaMetadataRetriever.setDataSource(MainActivity.this, data); - String strExtractMetadata = mediaMetadataRetriever.extractMetadata(7); - String strExtractMetadata2 = mediaMetadataRetriever.extractMetadata(2); - String strExtractMetadata3 = mediaMetadataRetriever.extractMetadata(1); - String strExtractMetadata4 = mediaMetadataRetriever.extractMetadata(9); - if (strExtractMetadata != null && strExtractMetadata.length() > 0) { - song.title = strExtractMetadata; - } - if (strExtractMetadata2 != null) { - song.artist = strExtractMetadata2; - } - if (strExtractMetadata3 != null) { - song.album = strExtractMetadata3; - } - if (strExtractMetadata4 != null) { - song.duration = Long.parseLong(strExtractMetadata4); - } - try { - mediaMetadataRetriever.release(); - } catch (Exception e) { - } - } catch (Exception e2) { - try { - mediaMetadataRetriever.release(); - } catch (Exception e3) { - } - } catch (Throwable th) { - try { - mediaMetadataRetriever.release(); - } catch (Exception e4) { - } - throw th; - } - App.ui(new Runnable() { // from class: com.mulberry.player.MainActivity.99.1 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.playOpened(song); - } - }); - } - }); - } - } - } - - void playOpened(final Song song) { - withService(new Runnable() { // from class: com.mulberry.player.MainActivity.100 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.svc.playList(Collections.singletonList(song), 0); - App.MAIN.postDelayed(new Runnable() { // from class: com.mulberry.player.MainActivity.100.1 - @Override // java.lang.Runnable - public void run() { - MainActivity.this.openPlayer(); - } - }, 400L); - } - }); - } - - static void tagsEdited() { - MusicService musicService = MusicService.INSTANCE; - if (musicService != null) { - musicService.songEdited(); - } - App.I.library.refresh(); - MainActivity mainActivity = CURRENT; - if (mainActivity != null) { - mainActivity.songAdapter.notifyDataSetChanged(); - mainActivity.groupAdapter.notifyDataSetChanged(); - mainActivity.refreshTopDetail(); - } - } -} diff --git a/android/src/com/mulberry/player/MediaButtonReceiver.java b/android/src/com/mulberry/player/MediaButtonReceiver.java deleted file mode 100644 index dbea6a8..0000000 --- a/android/src/com/mulberry/player/MediaButtonReceiver.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.mulberry.player; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.os.Build; -import android.view.KeyEvent; - -/* JADX INFO: loaded from: classes.dex */ -public class MediaButtonReceiver extends BroadcastReceiver { - @Override // android.content.BroadcastReceiver - public void onReceive(Context context, Intent intent) { - KeyEvent keyEvent; - String str; - if ("android.intent.action.MEDIA_BUTTON".equals(intent.getAction()) && (keyEvent = (KeyEvent) intent.getParcelableExtra("android.intent.extra.KEY_EVENT")) != null && keyEvent.getAction() == 0) { - switch (keyEvent.getKeyCode()) { - case 79: - case 85: - str = MusicService.ACT_TOGGLE; - break; - case 86: - case 127: - str = MusicService.ACT_PAUSE; - break; - case 87: - str = MusicService.ACT_NEXT; - break; - case 88: - str = MusicService.ACT_PREV; - break; - case 126: - str = MusicService.ACT_PLAY; - break; - default: - return; - } - MusicService musicService = MusicService.INSTANCE; - if (musicService == null) { - Intent action = new Intent(context, (Class) MusicService.class).setAction(str); - try { - if (Build.VERSION.SDK_INT >= 26) { - context.startForegroundService(action.putExtra(MusicService.EXTRA_FG, true)); - } else { - context.startService(action); - } - return; - } catch (Exception e) { - return; - } - } - musicService.handleAction(str); - } - } -} diff --git a/android/src/com/mulberry/player/MusicBrainz.java b/android/src/com/mulberry/player/MusicBrainz.java deleted file mode 100644 index e627078..0000000 --- a/android/src/com/mulberry/player/MusicBrainz.java +++ /dev/null @@ -1,325 +0,0 @@ -package com.mulberry.player; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; -import org.jaudiotagger.tag.mp4.atom.Mp4DataBox; -import org.jaudiotagger.tag.mp4.atom.Mp4NameBox; -import org.json.JSONArray; -import org.json.JSONObject; - -/* JADX INFO: loaded from: classes.dex */ -public final class MusicBrainz { - private static long last; - - public static final class Cand { - public int disc; - public long lengthMs; - public int score; - public int track; - public int year; - public String title = FrameBodyCOMM.DEFAULT; - public String artist = FrameBodyCOMM.DEFAULT; - public String album = FrameBodyCOMM.DEFAULT; - public String albumArtist = FrameBodyCOMM.DEFAULT; - public String mbTrack = FrameBodyCOMM.DEFAULT; - public String mbAlbum = FrameBodyCOMM.DEFAULT; - public String status = FrameBodyCOMM.DEFAULT; - } - - public static final class CoverCand { - public String label; - public String source; - public String thumb; - public String url; - } - - private MusicBrainz() { - } - - static JSONObject mb(String str, Map map) throws Exception { - synchronized (MusicBrainz.class) { - long jCurrentTimeMillis = 1050 - (System.currentTimeMillis() - last); - if (jCurrentTimeMillis > 0) { - Thread.sleep(jCurrentTimeMillis); - } - last = System.currentTimeMillis(); - } - LinkedHashMap linkedHashMap = new LinkedHashMap(map); - linkedHashMap.put("fmt", "json"); - return new JSONObject(Net.get("https://musicbrainz.org/ws/2/" + str + "?" + Net.query(linkedHashMap), null)); - } - - public static String clean(String str) { - return str == null ? FrameBodyCOMM.DEFAULT : str.replaceAll("(?i)\\s*[\\(\\[](feat\\.?|ft\\.?|with|remaster(ed)?|\\d{4} remaster|live|explicit|bonus)[^\\)\\]]*[\\)\\]]", FrameBodyCOMM.DEFAULT).trim(); - } - - public static String q(String str) { - return str.replaceAll("([+\\-&|!(){}\\[\\]^\"~*?:\\\\/])", "\\\\$1"); - } - - static String credit(JSONArray jSONArray) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; jSONArray != null && i < jSONArray.length(); i++) { - JSONObject jSONObjectOptJSONObject = jSONArray.optJSONObject(i); - if (jSONObjectOptJSONObject != null) { - sb.append(jSONObjectOptJSONObject.optString(Mp4NameBox.IDENTIFIER)).append(jSONObjectOptJSONObject.optString("joinphrase")); - } - } - return sb.toString(); - } - - public static List search(String str, String str2, String str3, long j, int i) throws Exception { - JSONArray jSONArrayOptJSONArray; - ArrayList arrayList = new ArrayList(); - if (str.length() > 0) { - arrayList.add("recording:\"" + q(clean(str)) + "\""); - } - if (str2.length() > 0) { - arrayList.add("artist:\"" + q(str2) + "\""); - } - String str4 = str3.length() > 0 ? "release:\"" + q(clean(str3)) + "\"" : null; - ArrayList arrayList2 = new ArrayList(); - if (arrayList.isEmpty() && str4 == null) { - return arrayList2; - } - String strJoin = join(arrayList); - HashMap map = new HashMap(); - map.put("limit", String.valueOf(i)); - map.put("query", str4 != null ? strJoin.length() > 0 ? strJoin + " AND (" + str4 + ")" : str4 : strJoin); - JSONArray jSONArrayOptJSONArray2 = mb("recording", map).optJSONArray("recordings"); - if ((jSONArrayOptJSONArray2 == null || jSONArrayOptJSONArray2.length() == 0) && str4 != null && strJoin.length() > 0) { - map.put("query", strJoin); - jSONArrayOptJSONArray = mb("recording", map).optJSONArray("recordings"); - } else { - jSONArrayOptJSONArray = jSONArrayOptJSONArray2; - } - for (int i2 = 0; jSONArrayOptJSONArray != null && i2 < jSONArrayOptJSONArray.length(); i2++) { - JSONObject jSONObject = jSONArrayOptJSONArray.getJSONObject(i2); - JSONArray jSONArrayOptJSONArray3 = jSONObject.optJSONArray("artist-credit"); - String strCredit = credit(jSONArrayOptJSONArray3); - String strOptString = (jSONArrayOptJSONArray3 == null || jSONArrayOptJSONArray3.length() <= 0) ? strCredit : jSONArrayOptJSONArray3.getJSONObject(0).optString(Mp4NameBox.IDENTIFIER, strCredit); - JSONArray jSONArrayOptJSONArray4 = jSONObject.optJSONArray("releases"); - int iMin = jSONArrayOptJSONArray4 == null ? 0 : Math.min(4, jSONArrayOptJSONArray4.length()); - for (int i3 = 0; i3 < Math.max(1, iMin); i3++) { - JSONObject jSONObject2 = iMin == 0 ? new JSONObject() : jSONArrayOptJSONArray4.getJSONObject(i3); - JSONArray jSONArrayOptJSONArray5 = jSONObject2.optJSONArray("media"); - JSONObject jSONObject3 = (jSONArrayOptJSONArray5 == null || jSONArrayOptJSONArray5.length() <= 0) ? new JSONObject() : jSONArrayOptJSONArray5.getJSONObject(0); - JSONArray jSONArrayOptJSONArray6 = jSONObject3.optJSONArray("track"); - JSONObject jSONObject4 = (jSONArrayOptJSONArray6 == null || jSONArrayOptJSONArray6.length() <= 0) ? new JSONObject() : jSONArrayOptJSONArray6.getJSONObject(0); - Cand cand = new Cand(); - cand.title = jSONObject.optString("title"); - cand.artist = strCredit; - cand.album = jSONObject2.optString("title"); - String strCredit2 = credit(jSONObject2.optJSONArray("artist-credit")); - if (strCredit2.length() <= 0) { - strCredit2 = strOptString; - } - cand.albumArtist = strCredit2; - cand.year = toInt(jSONObject2.optString("date").length() >= 4 ? jSONObject2.optString("date").substring(0, 4) : "0"); - cand.track = toInt(jSONObject4.optString("number", "0").replaceAll("\\D", FrameBodyCOMM.DEFAULT)); - cand.disc = jSONObject3.optInt("position", 0); - cand.lengthMs = jSONObject.optLong("length", 0L); - cand.mbTrack = jSONObject.optString("id"); - cand.mbAlbum = jSONObject2.optString("id"); - cand.score = jSONObject.optInt("score", 0); - cand.status = jSONObject2.optString("status"); - if (j > 0 && cand.lengthMs > 0) { - cand.score -= (int) Math.min(40.0d, (Math.abs(cand.lengthMs - j) / 1000.0d) * 2.0d); - } - if ("Official".equals(cand.status)) { - cand.score += 5; - } - arrayList2.add(cand); - } - } - Collections.sort(arrayList2, new Comparator() { // from class: com.mulberry.player.MusicBrainz.1 - @Override // java.util.Comparator - public int compare(Cand cand2, Cand cand3) { - return cand3.score - cand2.score; - } - }); - return arrayList2; - } - - public static String genre(String str) { - try { - HashMap map = new HashMap(); - map.put("inc", "genres+release-groups"); - JSONArray jSONArrayOptJSONArray = mb("release/" + str, map).optJSONArray("genres"); - if (jSONArrayOptJSONArray == null || jSONArrayOptJSONArray.length() == 0) { - return FrameBodyCOMM.DEFAULT; - } - JSONObject jSONObject = null; - for (int i = 0; i < jSONArrayOptJSONArray.length(); i++) { - JSONObject jSONObject2 = jSONArrayOptJSONArray.getJSONObject(i); - if (jSONObject == null || jSONObject2.optInt("count") > jSONObject.optInt("count")) { - jSONObject = jSONObject2; - } - } - return title(jSONObject.optString(Mp4NameBox.IDENTIFIER)); - } catch (Exception e) { - return FrameBodyCOMM.DEFAULT; - } - } - - static String title(String str) { - StringBuilder sb = new StringBuilder(); - boolean z = true; - for (char c : str.toCharArray()) { - sb.append(z ? Character.toUpperCase(c) : c); - z = !Character.isLetterOrDigit(c); - } - return sb.toString(); - } - - static int toInt(String str) { - if (str == null) { - return 0; - } - try { - if (str.length() == 0) { - return 0; - } - return Integer.parseInt(str); - } catch (Exception e) { - return 0; - } - } - - static String join(List list) { - StringBuilder sb = new StringBuilder(); - for (String str : list) { - if (sb.length() > 0) { - sb.append(" AND "); - } - sb.append(str); - } - return sb.toString(); - } - - public static List covers(final String str, final String str2, final String str3) { - ArrayList arrayList; - final List listSynchronizedList = Collections.synchronizedList(new ArrayList()); - final String strTrim = (str + " " + (str2.length() > 0 ? str2 : str3)).trim(); - Thread[] threadArr = {new Thread(new Runnable() { // from class: com.mulberry.player.MusicBrainz.2 - @Override // java.lang.Runnable - public void run() { - try { - HashMap map = new HashMap(); - map.put("term", strTrim); - map.put("entity", str2.length() > 0 ? "album" : "song"); - map.put("limit", "8"); - JSONArray jSONArrayOptJSONArray = new JSONObject(Net.get("https://itunes.apple.com/search?" + Net.query(map), null)).optJSONArray("results"); - for (int i = 0; jSONArrayOptJSONArray != null && i < jSONArrayOptJSONArray.length(); i++) { - JSONObject jSONObject = jSONArrayOptJSONArray.getJSONObject(i); - String strOptString = jSONObject.optString("artworkUrl100"); - if (strOptString.length() != 0) { - CoverCand coverCand = new CoverCand(); - coverCand.url = strOptString.replace("100x100bb", "1200x1200bb"); - coverCand.thumb = strOptString.replace("100x100bb", "300x300bb"); - coverCand.source = "iTunes"; - coverCand.label = jSONObject.optString("artistName") + " – " + jSONObject.optString("collectionName"); - listSynchronizedList.add(coverCand); - } - } - } catch (Exception e) { - } - } - }), new Thread(new Runnable() { // from class: com.mulberry.player.MusicBrainz.3 - @Override // java.lang.Runnable - public void run() { - try { - JSONArray jSONArrayOptJSONArray = new JSONObject(Net.get("https://api.deezer.com/search/album?q=" + Net.enc("artist:\"" + str + "\" album:\"" + (str2.length() > 0 ? str2 : str3) + "\""), null)).optJSONArray(Mp4DataBox.IDENTIFIER); - if (jSONArrayOptJSONArray == null || jSONArrayOptJSONArray.length() == 0) { - jSONArrayOptJSONArray = new JSONObject(Net.get("https://api.deezer.com/search/album?q=" + Net.enc(strTrim), null)).optJSONArray(Mp4DataBox.IDENTIFIER); - } - for (int i = 0; jSONArrayOptJSONArray != null && i < Math.min(8, jSONArrayOptJSONArray.length()); i++) { - JSONObject jSONObject = jSONArrayOptJSONArray.getJSONObject(i); - if (jSONObject.optString("cover_xl").length() != 0) { - CoverCand coverCand = new CoverCand(); - coverCand.url = jSONObject.optString("cover_xl"); - coverCand.thumb = jSONObject.optString("cover_medium", coverCand.url); - coverCand.source = "Deezer"; - JSONObject jSONObjectOptJSONObject = jSONObject.optJSONObject("artist"); - coverCand.label = (jSONObjectOptJSONObject != null ? jSONObjectOptJSONObject.optString(Mp4NameBox.IDENTIFIER) : FrameBodyCOMM.DEFAULT) + " – " + jSONObject.optString("title"); - listSynchronizedList.add(coverCand); - } - } - } catch (Exception e) { - } - } - }), new Thread(new Runnable() { // from class: com.mulberry.player.MusicBrainz.4 - @Override // java.lang.Runnable - public void run() { - if (str2.length() != 0) { - try { - HashMap map = new HashMap(); - map.put("query", "release:\"" + MusicBrainz.q(str2) + "\" AND artist:\"" + MusicBrainz.q(str) + "\""); - map.put("limit", "5"); - JSONArray jSONArrayOptJSONArray = MusicBrainz.mb("release", map).optJSONArray("releases"); - for (int i = 0; jSONArrayOptJSONArray != null && i < Math.min(5, jSONArrayOptJSONArray.length()); i++) { - JSONObject jSONObject = jSONArrayOptJSONArray.getJSONObject(i); - String strOptString = jSONObject.optString("id"); - CoverCand coverCand = new CoverCand(); - coverCand.url = "https://coverartarchive.org/release/" + strOptString + "/front"; - coverCand.thumb = "https://coverartarchive.org/release/" + strOptString + "/front-250"; - coverCand.source = "Cover Art Archive"; - String strOptString2 = jSONObject.optString("date"); - coverCand.label = jSONObject.optString("title") + (strOptString2.length() >= 4 ? " (" + strOptString2.substring(0, 4) + ")" : FrameBodyCOMM.DEFAULT); - listSynchronizedList.add(coverCand); - } - } catch (Exception e) { - } - } - } - }), new Thread(new Runnable() { // from class: com.mulberry.player.MusicBrainz.5 - @Override // java.lang.Runnable - public void run() { - if (str2.length() != 0) { - try { - HashMap map = new HashMap(); - map.put("method", "album.getinfo"); - map.put("api_key", LastFm.KEY); - map.put("artist", str); - map.put("album", str2); - map.put("format", "json"); - map.put("autocorrect", "1"); - JSONObject jSONObjectOptJSONObject = new JSONObject(Net.get("https://ws.audioscrobbler.com/2.0/?" + Net.query(map), null)).optJSONObject("album"); - JSONArray jSONArrayOptJSONArray = jSONObjectOptJSONObject != null ? jSONObjectOptJSONObject.optJSONArray("image") : null; - if (jSONArrayOptJSONArray != null && jSONArrayOptJSONArray.length() != 0) { - String strOptString = jSONArrayOptJSONArray.getJSONObject(jSONArrayOptJSONArray.length() - 1).optString("#text"); - if (strOptString.length() != 0) { - CoverCand coverCand = new CoverCand(); - coverCand.url = strOptString.replaceAll("/\\d+x\\d+/", "/"); - coverCand.thumb = strOptString; - coverCand.source = "Last.fm"; - coverCand.label = str2; - listSynchronizedList.add(coverCand); - } - } - } catch (Exception e) { - } - } - } - })}; - for (Thread thread : threadArr) { - thread.start(); - } - for (Thread thread2 : threadArr) { - try { - thread2.join(20000L); - } catch (InterruptedException e) { - } - } - synchronized (listSynchronizedList) { - arrayList = new ArrayList(listSynchronizedList); - } - return arrayList; - } -} diff --git a/android/src/com/mulberry/player/MusicService.java b/android/src/com/mulberry/player/MusicService.java deleted file mode 100644 index bf9a71f..0000000 --- a/android/src/com/mulberry/player/MusicService.java +++ /dev/null @@ -1,1957 +0,0 @@ -package com.mulberry.player; - -import android.app.Notification; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.BroadcastReceiver; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.graphics.Bitmap; -import android.graphics.drawable.Icon; -import android.media.AudioAttributes; -import android.media.AudioFocusRequest; -import android.media.AudioManager; -import android.media.MediaDescription; -import android.media.MediaMetadata; -import android.media.MediaPlayer; -import android.media.browse.MediaBrowser; -import android.media.session.MediaSession; -import android.media.session.PlaybackState; -import android.os.Binder; -import android.os.Build; -import android.os.Bundle; -import android.os.IBinder; -import android.os.PowerManager; -import android.os.SystemClock; -import android.service.media.MediaBrowserService; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Random; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArrayList; -import org.jaudiotagger.audio.flac.FlacTagCreator; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; -import org.json.JSONArray; -import org.json.JSONObject; - -/* JADX INFO: loaded from: classes.dex */ -public class MusicService extends MediaBrowserService implements AudioManager.OnAudioFocusChangeListener { - public static final String ACT_FAV = "com.mulberry.player.FAV"; - public static final String ACT_NEXT = "com.mulberry.player.NEXT"; - public static final String ACT_PAUSE = "com.mulberry.player.PAUSE"; - public static final String ACT_PLAY = "com.mulberry.player.PLAY"; - public static final String ACT_PREV = "com.mulberry.player.PREV"; - public static final String ACT_REFRESH = "com.mulberry.player.REFRESH"; - public static final String ACT_REPEAT = "com.mulberry.player.REPEAT"; - public static final String ACT_SHUFFLE = "com.mulberry.player.SHUFFLE"; - public static final String ACT_STOP = "com.mulberry.player.STOP"; - public static final String ACT_TOGGLE = "com.mulberry.player.TOGGLE"; - public static final String EXTRA_FG = "fg"; - public static MusicService INSTANCE = null; - static final int NOTIF_ID = 7; - private AudioManager am; - private Bitmap art; - private int artToken; - private boolean countedPlay; - private MediaPlayer cur; - private boolean curPrepared; - private int errorStreak; - private int fadeToken; - private MediaPlayer fadingOut; - private boolean focusLossTransient; - private AudioFocusRequest focusReq; - private boolean foreground; - private boolean held; - private boolean heldPlaying; - private long heldPos; - private long lastSavedPos; - private long lastTick; - private long listenedMs; - public Lyrics.Result lyrics; - private boolean noisyRegistered; - private boolean notifShown; - private MediaPlayer nxt; - private boolean nxtLinked; - private boolean nxtPrepared; - private boolean playWhenLibrary; - private boolean playWhenReady; - private PowerManager pm; - volatile long pubPos; - private int repeat; - private long sampleAt; - private boolean samplePlaying; - private long samplePos; - private int saveCounter; - private boolean scrobbled; - private boolean selfStarted; - private MediaSession session; - private boolean shuffle; - private long sleepAt; - private boolean sleepEndOfTrack; - public final Spectrum spectrum; - private long startedSec; - private int xfMs; - private long xfStart; - private final LocalBinder binder = new LocalBinder(); - private final CopyOnWriteArrayList listeners = new CopyOnWriteArrayList<>(); - private int nxtIndex = -1; - private List queue = new ArrayList(); - private List original = new ArrayList(); - private int index = -1; - private long pendingSeek = -1; - private float duckVol = 1.0f; - private int widgetLine = -2; - private final Library.Listener libListener = new Library.Listener() { // from class: com.mulberry.player.MusicService.2 - @Override // com.mulberry.player.Library.Listener - public void onLibraryChanged() { - if (MusicService.this.playWhenLibrary && MusicService.this.queue.isEmpty() && !App.I.library.songs.isEmpty()) { - MusicService.this.playWhenLibrary = false; - MusicService.this.playShuffled(new ArrayList(App.I.library.songs)); - } - } - }; - private final MediaPlayer.OnErrorListener errors = new MediaPlayer.OnErrorListener() { // from class: com.mulberry.player.MusicService.4 - @Override // android.media.MediaPlayer.OnErrorListener - public boolean onError(MediaPlayer mediaPlayer, int i, int i2) { - MusicService.this.handleError(mediaPlayer); - return true; - } - }; - private final MediaPlayer.OnCompletionListener completion = new MediaPlayer.OnCompletionListener() { // from class: com.mulberry.player.MusicService.7 - @Override // android.media.MediaPlayer.OnCompletionListener - public void onCompletion(MediaPlayer mediaPlayer) { - if (mediaPlayer == MusicService.this.cur) { - Song songCurrent = MusicService.this.current(); - if (songCurrent != null) { - ScrobbleBridge.send(MusicService.this, songCurrent, 3); - } - MusicService.this.finishListen(true); - if (MusicService.this.sleepEndOfTrack) { - MusicService.this.sleepEndOfTrack = false; - MusicService.this.sleepAt = 0L; - int iNextIndex = MusicService.this.nextIndex(false); - if (iNextIndex >= 0) { - MusicService.this.load(iNextIndex, false, 0L); - return; - } else { - MusicService.this.stopPlayback(); - return; - } - } - if (MusicService.this.nxt == null || !MusicService.this.nxtPrepared || !MusicService.this.nxtLinked || MusicService.this.nxtIndex < 0) { - int iNextIndex2 = MusicService.this.nextIndex(false); - if (iNextIndex2 < 0) { - MusicService.this.releasePlayers(); - MusicService.this.playWhenReady = false; - MusicService.this.index = 0; - if (!MusicService.this.queue.isEmpty()) { - MusicService.this.load(0, false, 0L); - } - MusicService.this.abandonFocus(); - MusicService.this.stopFg(false); - MusicService.this.notifyState(); - return; - } - MusicService.this.load(iNextIndex2, true, 0L); - return; - } - MediaPlayer mediaPlayer2 = MusicService.this.cur; - MusicService.this.cur = MusicService.this.nxt; - MusicService.this.curPrepared = true; - MusicService.this.index = MusicService.this.nxtIndex; - MusicService.this.nxt = null; - MusicService.this.nxtPrepared = false; - MusicService.this.nxtLinked = false; - MusicService.this.nxtIndex = -1; - try { - mediaPlayer2.release(); - } catch (Exception e) { - } - MusicService.this.cur.setOnCompletionListener(MusicService.this.completion); - MusicService.this.cur.setOnErrorListener(MusicService.this.errors); - try { - MusicService.this.cur.setLooping(MusicService.this.repeat == 2); - } catch (Exception e2) { - } - Song songCurrent2 = MusicService.this.current(); - if (songCurrent2 != null && songCurrent2.duration <= 0) { - songCurrent2.duration = Math.max(0, MusicService.this.cur.getDuration()); - } - if (MusicService.this.spectrum != null && songCurrent2 != null) { - MusicService.this.spectrum.start(songCurrent2, songCurrent2.duration); - } - MusicService.this.beginListen(songCurrent2); - MusicService.this.onStarted(); - MusicService.this.notifyTrack(); - MusicService.this.loadArtAndLyrics(songCurrent2); - MusicService.this.prepareNext(); - MusicService.this.saveQueueLater(); - } - } - }; - private float gain = 1.0f; - private float xfIn = 1.0f; - private float xfOut = 0.0f; - private final Runnable xfWatch = new Runnable() { // from class: com.mulberry.player.MusicService.10 - @Override // java.lang.Runnable - public void run() { - int iCrossfadeMs = MusicService.this.crossfadeMs(); - if (iCrossfadeMs > 0 && MusicService.this.isPlaying()) { - if (MusicService.this.fadingOut == null && MusicService.this.repeat != 2 && !MusicService.this.sleepEndOfTrack && MusicService.this.nxt != null && MusicService.this.nxtPrepared && MusicService.this.nxtIndex >= 0) { - long jDuration = MusicService.this.duration(); - long jPosition = MusicService.this.position(); - if (jDuration > ((long) iCrossfadeMs) * 2 && jDuration - jPosition <= iCrossfadeMs) { - MusicService.this.beginCrossfade((int) Math.max(500L, jDuration - jPosition)); - } - } - App.MAIN.postDelayed(this, 100L); - } - } - }; - private final Runnable xfRamp = new Runnable() { // from class: com.mulberry.player.MusicService.13 - @Override // java.lang.Runnable - public void run() { - if (MusicService.this.fadingOut != null) { - float fMin = Math.min(1.0f, (SystemClock.elapsedRealtime() - MusicService.this.xfStart) / Math.max(1, MusicService.this.xfMs)); - MusicService.this.xfIn = (float) Math.sin((((double) fMin) * 3.141592653589793d) / 2.0d); - MusicService.this.xfOut = (float) Math.cos((((double) fMin) * 3.141592653589793d) / 2.0d); - MusicService.this.applyVolume(); - if (fMin >= 1.0f) { - MusicService.this.endCrossfade(); - MusicService.this.prepareNext(); - } else { - App.MAIN.postDelayed(this, 40L); - } - } - } - }; - private final Runnable sleepTask = new Runnable() { // from class: com.mulberry.player.MusicService.15 - @Override // java.lang.Runnable - public void run() { - MusicService.this.sleepAt = 0L; - MusicService.this.fadeOutAndPause(); - } - }; - private final Runnable ticker = new Runnable() { // from class: com.mulberry.player.MusicService.17 - @Override // java.lang.Runnable - public void run() { - if (MusicService.this.isPlaying()) { - MusicService.this.pubPos = MusicService.this.position(); - MusicService.this.tickListen(); - if (MusicService.this.pm == null || MusicService.this.pm.isInteractive()) { - Widgets.tick(MusicService.this); - } - if (MusicService.access$4804(MusicService.this) % 10 == 0) { - MusicService.this.savePosition(); - } - App.MAIN.postDelayed(this, 1000L); - } - } - }; - private final BroadcastReceiver noisy = new BroadcastReceiver() { // from class: com.mulberry.player.MusicService.18 - @Override // android.content.BroadcastReceiver - public void onReceive(Context context, Intent intent) { - if (!"android.media.AUDIO_BECOMING_NOISY".equals(intent.getAction()) || !App.I.prefs.getBool(Prefs.PAUSE_ON_DETACH, true)) { - return; - } - MusicService.this.pause(); - } - }; - private final Runnable saveLater = new Runnable() { // from class: com.mulberry.player.MusicService.22 - @Override // java.lang.Runnable - public void run() { - MusicService.this.saveQueue(); - } - }; - - public interface Listener { - void onLyrics(); - - void onQueueChanged(); - - void onStateChanged(); - - void onTrackChanged(); - } - - static /* synthetic */ int access$4804(MusicService musicService) { - int i = musicService.saveCounter + 1; - musicService.saveCounter = i; - return i; - } - - public class LocalBinder extends Binder { - public LocalBinder() { - } - - public MusicService service() { - return MusicService.this; - } - } - - public MusicService() { - this.spectrum = App.I == null ? null : new Spectrum(App.I); - } - - @Override // android.service.media.MediaBrowserService, android.app.Service - public void onCreate() { - super.onCreate(); - INSTANCE = this; - this.am = (AudioManager) getSystemService("audio"); - this.pm = (PowerManager) getSystemService("power"); - this.shuffle = App.I.prefs.getBool(Prefs.SHUFFLE, false); - this.repeat = App.I.prefs.getInt(Prefs.REPEAT, 0); - if (this.spectrum != null) { - this.spectrum.setClock(new Spectrum.Clock() { // from class: com.mulberry.player.MusicService.1 - @Override // com.mulberry.player.Spectrum.Clock - public long positionMs() { - return MusicService.this.pubPos; - } - }); - } - this.session = new MediaSession(this, "Mulberry"); - this.session.setFlags(3); - this.session.setCallback(new SessionCb()); - this.session.setSessionActivity(PendingIntent.getActivity(this, 1, new Intent(this, (Class) MainActivity.class).addFlags(536870912), 201326592)); - this.session.setMediaButtonReceiver(PendingIntent.getBroadcast(this, 2, new Intent("android.intent.action.MEDIA_BUTTON").setClass(this, MediaButtonReceiver.class), 67108864)); - setSessionToken(this.session.getSessionToken()); - restoreQueue(); - updateSession(); - App.I.library.addListener(this.libListener); - if (!App.I.library.loaded) { - App.I.library.refresh(); - } - } - - @Override // android.service.media.MediaBrowserService, android.app.Service - public IBinder onBind(Intent intent) { - return "android.media.browse.MediaBrowserService".equals(intent.getAction()) ? super.onBind(intent) : this.binder; - } - - @Override // android.app.Service - public int onStartCommand(Intent intent, int i, int i2) { - if (intent != null && intent.getBooleanExtra(EXTRA_FG, false)) { - goForeground(true); - } - if (intent != null && intent.getAction() != null) { - handleAction(intent.getAction()); - } else if (intent != null && "android.intent.action.MEDIA_BUTTON".equals(intent.getAction())) { - toggle(); - } - if (intent != null && intent.getBooleanExtra(EXTRA_FG, false) && !isPlaying() && !this.playWhenReady && !this.playWhenLibrary) { - stopFg(false); - return 2; - } - return 2; - } - - void handleAction(String str) { - if (!ACT_TOGGLE.equals(str)) { - if (!ACT_PLAY.equals(str)) { - if (!ACT_PAUSE.equals(str)) { - if (!ACT_NEXT.equals(str)) { - if (!ACT_PREV.equals(str)) { - if (!ACT_SHUFFLE.equals(str)) { - if (!ACT_REPEAT.equals(str)) { - if (ACT_FAV.equals(str)) { - Song songCurrent = current(); - if (songCurrent != null) { - PlayStats.setFav(songCurrent, PlayStats.fav(songCurrent) ? false : true); - refreshUi(); - return; - } - return; - } - if (!ACT_STOP.equals(str)) { - if (ACT_REFRESH.equals(str)) { - refreshUi(); - return; - } - return; - } - stopAndQuit(); - return; - } - cycleRepeat(); - return; - } - setShuffle(this.shuffle ? false : true); - return; - } - prev(); - return; - } - next(); - return; - } - pause(); - return; - } - play(); - return; - } - toggle(); - } - - @Override // android.app.Service - public void onTaskRemoved(Intent intent) { - if (!isPlaying()) { - stopAndQuit(); - } - } - - @Override // android.app.Service - public void onDestroy() { - NotificationManager notificationManager; - saveQueue(); - PlayStats.save(); - App.MAIN.removeCallbacks(this.ticker); - App.MAIN.removeCallbacks(this.sleepTask); - releasePlayers(); - if (this.spectrum != null) { - this.spectrum.stop(); - } - abandonFocus(); - unregisterNoisy(); - App.I.library.removeListener(this.libListener); - this.session.setActive(false); - this.session.release(); - INSTANCE = null; - if (!this.foreground && (notificationManager = (NotificationManager) getSystemService("notification")) != null) { - notificationManager.cancel(7); - } - Widgets.updateAll(this); - super.onDestroy(); - } - - public void addListener(Listener listener) { - this.listeners.add(listener); - } - - public void removeListener(Listener listener) { - this.listeners.remove(listener); - } - - public List queue() { - return Collections.unmodifiableList(this.queue); - } - - public int index() { - return this.index; - } - - public Song current() { - if (this.index < 0 || this.index >= this.queue.size()) { - return null; - } - return this.queue.get(this.index); - } - - public boolean shuffle() { - return this.shuffle; - } - - public int repeat() { - return this.repeat; - } - - public void playList(List list, int i) { - if (list != null && !list.isEmpty()) { - this.original = new ArrayList(list); - this.queue = new ArrayList(list); - this.index = Math.max(0, Math.min(i, list.size() - 1)); - if (this.shuffle) { - shuffleKeepingCurrent(); - } - this.errorStreak = 0; - notifyQueue(); - load(this.index, true, 0L); - } - } - - public void playShuffled(List list) { - if (list != null && !list.isEmpty()) { - if (!this.shuffle) { - this.shuffle = true; - App.I.prefs.setBool(Prefs.SHUFFLE, true); - } - playList(list, new Random().nextInt(list.size())); - } - } - - public void playNext(List list) { - if (!list.isEmpty()) { - if (!this.queue.isEmpty()) { - this.queue.addAll(this.index + 1, list); - int iIndexOf = this.original.indexOf(current()); - this.original.addAll(iIndexOf < 0 ? this.original.size() : iIndexOf + 1, list); - afterQueueEdit(); - return; - } - playList(list, 0); - } - } - - public void enqueue(List list) { - if (!list.isEmpty()) { - if (!this.queue.isEmpty()) { - this.queue.addAll(list); - this.original.addAll(list); - afterQueueEdit(); - return; - } - playList(list, 0); - } - } - - public void removeAt(int i) { - if (i >= 0 && i < this.queue.size()) { - this.original.remove(this.queue.remove(i)); - if (i < this.index) { - this.index--; - } else if (i == this.index) { - if (!this.queue.isEmpty()) { - boolean z = isPlaying() || this.playWhenReady; - if (this.index >= this.queue.size()) { - this.index = 0; - if (this.repeat != 1) { - z = false; - } - } - load(this.index, z, 0L); - } else { - stopPlayback(); - this.index = -1; - notifyQueue(); - notifyTrack(); - return; - } - } - afterQueueEdit(); - } - } - - public void move(int i, int i2) { - if (i >= 0 && i < this.queue.size() && i2 >= 0 && i2 < this.queue.size() && i != i2) { - this.queue.add(i2, this.queue.remove(i)); - if (this.index == i) { - this.index = i2; - } else if (i < this.index && i2 >= this.index) { - this.index--; - } else if (i > this.index && i2 <= this.index) { - this.index++; - } - if (!this.shuffle) { - this.original = new ArrayList(this.queue); - } - afterQueueEdit(); - } - } - - public void clearQueue() { - stopPlayback(); - this.queue = new ArrayList(); - this.original = new ArrayList(); - this.index = -1; - notifyQueue(); - notifyTrack(); - saveQueue(); - } - - public void jump(int i) { - if (i >= 0 && i < this.queue.size()) { - this.index = i; - this.errorStreak = 0; - load(i, true, 0L); - } - } - - private void afterQueueEdit() { - prepareNext(); - notifyQueue(); - saveQueueLater(); - updateSessionQueue(); - } - - public void setShuffle(boolean z) { - if (z != this.shuffle) { - this.shuffle = z; - App.I.prefs.setBool(Prefs.SHUFFLE, z); - Song songCurrent = current(); - if (z) { - shuffleKeepingCurrent(); - } else { - this.queue = new ArrayList(this.original); - this.index = songCurrent != null ? Math.max(0, this.queue.indexOf(songCurrent)) : 0; - } - afterQueueEdit(); - refreshUi(); - } - } - - private void shuffleKeepingCurrent() { - Song songCurrent = current(); - ArrayList arrayList = new ArrayList(this.queue); - if (songCurrent != null) { - arrayList.remove(this.index); - } - Collections.shuffle(arrayList); - this.queue = new ArrayList(); - if (songCurrent != null) { - this.queue.add(songCurrent); - } - this.queue.addAll(arrayList); - if (songCurrent == null) { - } - this.index = 0; - } - - public void cycleRepeat() { - this.repeat = (this.repeat + 1) % 3; - App.I.prefs.setInt(Prefs.REPEAT, this.repeat); - if (this.cur != null) { - try { - this.cur.setLooping(this.repeat == 2); - } catch (Exception e) { - } - } - prepareNext(); - refreshUi(); - } - - private MediaPlayer newPlayer() { - MediaPlayer mediaPlayer = new MediaPlayer(); - mediaPlayer.setAudioAttributes(new AudioAttributes.Builder().setUsage(1).setContentType(2).build()); - mediaPlayer.setWakeMode(getApplicationContext(), 1); - return mediaPlayer; - } - - /* JADX INFO: Access modifiers changed from: private */ - public void releasePlayers() { - endCrossfade(); - this.fadeToken++; - this.gain = 1.0f; - if (this.cur != null) { - try { - this.cur.release(); - } catch (Exception e) { - } - this.cur = null; - } - releaseNext(); - this.curPrepared = false; - } - - private void releaseNext() { - if (this.nxt != null) { - if (this.cur != null && this.nxtLinked) { - try { - this.cur.setNextMediaPlayer(null); - } catch (Exception e) { - } - } - try { - this.nxt.release(); - } catch (Exception e2) { - } - this.nxt = null; - } - this.nxtPrepared = false; - this.nxtLinked = false; - this.nxtIndex = -1; - } - - /* JADX INFO: Access modifiers changed from: private */ - public void stopPlayback() { - finishListen(false); - releasePlayers(); - this.playWhenReady = false; - if (this.spectrum != null) { - this.spectrum.stop(); - } - abandonFocus(); - unregisterNoisy(); - stopFg(false); - notifyState(); - } - - /* JADX INFO: Access modifiers changed from: private */ - public void load(int i, boolean z, long j) { - if (i >= 0 && i < this.queue.size()) { - finishListen(false); - releasePlayers(); - this.index = i; - this.playWhenReady = z; - this.pendingSeek = j; - final Song song = this.queue.get(i); - MediaPlayer mediaPlayerNewPlayer = newPlayer(); - this.cur = mediaPlayerNewPlayer; - this.curPrepared = false; - mediaPlayerNewPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { // from class: com.mulberry.player.MusicService.3 - @Override // android.media.MediaPlayer.OnPreparedListener - public void onPrepared(MediaPlayer mediaPlayer) { - if (mediaPlayer == MusicService.this.cur) { - MusicService.this.curPrepared = true; - MusicService.this.errorStreak = 0; - if (song.duration <= 0) { - song.duration = Math.max(0, mediaPlayer.getDuration()); - } - mediaPlayer.setLooping(MusicService.this.repeat == 2); - if (MusicService.this.pendingSeek > 0) { - try { - mediaPlayer.seekTo((int) MusicService.this.pendingSeek); - } catch (Exception e) { - } - } - MusicService.this.pendingSeek = -1L; - if (MusicService.this.spectrum != null) { - MusicService.this.spectrum.start(song, Math.max(song.duration, mediaPlayer.getDuration())); - } - if (MusicService.this.playWhenReady) { - MusicService.this.startPlayback(); - } else { - MusicService.this.notifyState(); - } - MusicService.this.prepareNext(); - } - } - }); - mediaPlayerNewPlayer.setOnCompletionListener(this.completion); - mediaPlayerNewPlayer.setOnErrorListener(this.errors); - try { - mediaPlayerNewPlayer.setDataSource(getApplicationContext(), song.toUri()); - mediaPlayerNewPlayer.prepareAsync(); - } catch (Exception e) { - handleError(mediaPlayerNewPlayer); - } - beginListen(song); - notifyTrack(); - loadArtAndLyrics(song); - saveQueueLater(); - } - } - - /* JADX INFO: Access modifiers changed from: private */ - public void handleError(final MediaPlayer mediaPlayer) { - if (mediaPlayer != this.nxt) { - if (mediaPlayer == this.cur) { - this.errorStreak++; - Song songCurrent = current(); - App.ui(new Runnable() { // from class: com.mulberry.player.MusicService.5 - @Override // java.lang.Runnable - public void run() { - Iterator it = MusicService.this.listeners.iterator(); - while (it.hasNext()) { - ((Listener) it.next()).onStateChanged(); - } - } - }); - if (songCurrent != null) { - MainActivity.toast("Can't play “" + songCurrent.displayTitle() + "” — skipping"); - } - if (this.errorStreak >= Math.min(8, Math.max(1, this.queue.size()))) { - this.errorStreak = 0; - stopPlayback(); - return; - } else { - final boolean z = this.playWhenReady || isPlaying(); - App.MAIN.postDelayed(new Runnable() { // from class: com.mulberry.player.MusicService.6 - @Override // java.lang.Runnable - public void run() { - if (MusicService.this.cur == mediaPlayer) { - int iNextIndex = MusicService.this.nextIndex(true); - if (iNextIndex < 0) { - MusicService.this.stopPlayback(); - } else { - MusicService.this.load(iNextIndex, z, 0L); - } - } - } - }, 300L); - return; - } - } - return; - } - releaseNext(); - } - - /* JADX INFO: Access modifiers changed from: private */ - public int nextIndex(boolean z) { - if (this.queue.isEmpty()) { - return -1; - } - if (this.index + 1 < this.queue.size()) { - return this.index + 1; - } - return (this.repeat == 1 || (z && this.repeat != 0)) ? 0 : -1; - } - - /* JADX INFO: Access modifiers changed from: private */ - public void prepareNext() { - int iNextIndex; - releaseNext(); - if (this.cur != null && this.curPrepared && this.repeat != 2 && !this.sleepEndOfTrack) { - if (((crossfadeMs() > 0) || App.I.prefs.getBool(Prefs.GAPLESS, true)) && (iNextIndex = nextIndex(false)) >= 0 && iNextIndex != this.index) { - Song song = this.queue.get(iNextIndex); - if (!song.isStream()) { - MediaPlayer mediaPlayerNewPlayer = newPlayer(); - this.nxt = mediaPlayerNewPlayer; - this.nxtIndex = iNextIndex; - mediaPlayerNewPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { // from class: com.mulberry.player.MusicService.8 - @Override // android.media.MediaPlayer.OnPreparedListener - public void onPrepared(MediaPlayer mediaPlayer) { - if (mediaPlayer == MusicService.this.nxt && MusicService.this.cur != null) { - MusicService.this.nxtPrepared = true; - if (MusicService.this.crossfadeMs() <= 0) { - try { - MusicService.this.cur.setNextMediaPlayer(mediaPlayer); - MusicService.this.nxtLinked = true; - } catch (Exception e) { - MusicService.this.nxtLinked = false; - } - } - } - } - }); - mediaPlayerNewPlayer.setOnErrorListener(this.errors); - try { - mediaPlayerNewPlayer.setDataSource(getApplicationContext(), song.toUri()); - mediaPlayerNewPlayer.prepareAsync(); - } catch (Exception e) { - releaseNext(); - } - } - } - } - } - - public boolean isPlaying() { - try { - return this.playWhenReady && this.cur != null && this.curPrepared && this.cur.isPlaying(); - } catch (Exception e) { - return false; - } - } - - public boolean isLoading() { - return (this.cur == null || this.curPrepared || !this.playWhenReady) ? false : true; - } - - public long position() { - try { - if (this.cur != null && this.curPrepared) { - return this.cur.getCurrentPosition(); - } - } catch (Exception e) { - } - if (this.pendingSeek > 0) { - return this.pendingSeek; - } - return 0L; - } - - public long positionFast() { - long jElapsedRealtime = SystemClock.elapsedRealtime(); - if (jElapsedRealtime - this.sampleAt <= 250 && this.sampleAt != 0) { - if (!this.samplePlaying) { - return this.samplePos; - } - return (jElapsedRealtime - this.sampleAt) + this.samplePos; - } - this.samplePos = position(); - this.samplePlaying = isPlaying(); - this.sampleAt = jElapsedRealtime; - this.pubPos = this.samplePos; - return this.samplePos; - } - - public long duration() { - int duration; - Song songCurrent = current(); - try { - if (this.cur != null && this.curPrepared && (duration = this.cur.getDuration()) > 0) { - return duration; - } - } catch (Exception e) { - } - if (songCurrent == null) { - return 0L; - } - return songCurrent.duration; - } - - public void toggle() { - if (isPlaying() || isLoading()) { - pause(); - } else { - play(); - } - } - - public void play() { - if (this.queue.isEmpty()) { - List list = App.I.library.songs; - if (list.isEmpty()) { - this.playWhenLibrary = true; - if (App.I.library.loaded) { - MainActivity.toast("No music found on this phone"); - return; - } else { - App.I.library.refresh(); - return; - } - } - playShuffled(new ArrayList(list)); - return; - } - if (this.cur != null) { - this.playWhenReady = true; - if (this.curPrepared) { - startPlayback(); - return; - } else { - notifyState(); - return; - } - } - load(Math.max(0, this.index), true, this.lastSavedPos); - this.lastSavedPos = 0L; - } - - /* JADX INFO: Access modifiers changed from: private */ - public void startPlayback() { - if (requestFocus()) { - boolean z = App.I.prefs.getBool(Prefs.FADE_PAUSE, true) && !App.lowPower(); - this.fadeToken++; - try { - this.gain = z ? 0.0f : 1.0f; - applyVolume(); - this.cur.start(); - if (z) { - ramp(0.0f, 1.0f, 350, null); - } - onStarted(); - return; - } catch (Exception e) { - handleError(this.cur); - return; - } - } - this.playWhenReady = false; - notifyState(); - } - - public void playbackSettingsChanged() { - prepareNext(); - App.MAIN.removeCallbacks(this.xfWatch); - if (crossfadeMs() <= 0 || !isPlaying()) { - return; - } - App.MAIN.post(this.xfWatch); - } - - int crossfadeMs() { - return Math.max(0, Math.min(12, App.I.prefs.getInt(Prefs.CROSSFADE, 0))) * 1000; - } - - /* JADX INFO: Access modifiers changed from: private */ - public void applyVolume() { - float f = this.duckVol * this.gain * this.xfIn; - if (this.cur != null) { - try { - this.cur.setVolume(f, f); - } catch (Exception e) { - } - } - if (this.fadingOut != null) { - float f2 = this.duckVol * this.xfOut; - try { - this.fadingOut.setVolume(f2, f2); - } catch (Exception e2) { - } - } - } - - private void ramp(final float f, final float f2, final int i, final Runnable runnable) { - final int i2 = this.fadeToken + 1; - this.fadeToken = i2; - final long jElapsedRealtime = SystemClock.elapsedRealtime(); - App.MAIN.post(new Runnable() { // from class: com.mulberry.player.MusicService.9 - @Override // java.lang.Runnable - public void run() { - if (i2 == MusicService.this.fadeToken) { - float fMin = Math.min(1.0f, (SystemClock.elapsedRealtime() - jElapsedRealtime) / i); - MusicService.this.gain = f + ((f2 - f) * fMin); - MusicService.this.applyVolume(); - if (fMin >= 1.0f) { - if (runnable != null) { - runnable.run(); - return; - } - return; - } - App.MAIN.postDelayed(this, 25L); - } - } - }); - } - - /* JADX INFO: Access modifiers changed from: private */ - public void beginCrossfade(int i) { - Song songCurrent = current(); - if (songCurrent != null) { - ScrobbleBridge.send(this, songCurrent, 3); - } - finishListen(true); - MediaPlayer mediaPlayer = this.cur; - this.fadingOut = mediaPlayer; - mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { // from class: com.mulberry.player.MusicService.11 - @Override // android.media.MediaPlayer.OnCompletionListener - public void onCompletion(MediaPlayer mediaPlayer2) { - if (mediaPlayer2 == MusicService.this.fadingOut) { - MusicService.this.endCrossfade(); - } - } - }); - mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { // from class: com.mulberry.player.MusicService.12 - @Override // android.media.MediaPlayer.OnErrorListener - public boolean onError(MediaPlayer mediaPlayer2, int i2, int i3) { - if (mediaPlayer2 != MusicService.this.fadingOut) { - return true; - } - MusicService.this.endCrossfade(); - return true; - } - }); - this.cur = this.nxt; - this.curPrepared = true; - this.index = this.nxtIndex; - this.nxt = null; - this.nxtPrepared = false; - this.nxtLinked = false; - this.nxtIndex = -1; - this.cur.setOnCompletionListener(this.completion); - this.cur.setOnErrorListener(this.errors); - try { - this.cur.setLooping(this.repeat == 2); - } catch (Exception e) { - } - this.xfIn = 0.0f; - this.xfOut = 1.0f; - this.gain = 1.0f; - applyVolume(); - try { - this.cur.start(); - this.xfStart = SystemClock.elapsedRealtime(); - this.xfMs = i; - App.MAIN.post(this.xfRamp); - Song songCurrent2 = current(); - if (songCurrent2 != null && songCurrent2.duration <= 0) { - songCurrent2.duration = Math.max(0, this.cur.getDuration()); - } - if (this.spectrum != null && songCurrent2 != null) { - this.spectrum.start(songCurrent2, songCurrent2.duration); - } - beginListen(songCurrent2); - onStarted(); - notifyTrack(); - loadArtAndLyrics(songCurrent2); - saveQueueLater(); - } catch (Exception e2) { - endCrossfade(); - handleError(this.cur); - } - } - - /* JADX INFO: Access modifiers changed from: private */ - public void endCrossfade() { - App.MAIN.removeCallbacks(this.xfRamp); - if (this.fadingOut != null) { - try { - this.fadingOut.release(); - } catch (Exception e) { - } - this.fadingOut = null; - } - this.xfIn = 1.0f; - this.xfOut = 0.0f; - applyVolume(); - } - - /* JADX INFO: Access modifiers changed from: private */ - public void onStarted() { - this.playWhenReady = true; - if (!this.selfStarted) { - try { - startService(new Intent(this, (Class) MusicService.class)); - this.selfStarted = true; - } catch (Exception e) { - } - } - this.lastTick = SystemClock.elapsedRealtime(); - registerNoisy(); - goForeground(false); - App.MAIN.removeCallbacks(this.ticker); - App.MAIN.post(this.ticker); - App.MAIN.removeCallbacks(this.xfWatch); - if (crossfadeMs() > 0) { - App.MAIN.postDelayed(this.xfWatch, 200L); - } - Song songCurrent = current(); - if (songCurrent != null) { - ScrobbleBridge.send(this, songCurrent, this.listenedMs <= 0 ? 0 : 1); - } - notifyState(); - } - - public void pause() { - pause(false); - } - - void pause(boolean z) { - this.playWhenReady = false; - endCrossfade(); - final MediaPlayer mediaPlayer = this.cur; - if (!z && App.I.prefs.getBool(Prefs.FADE_PAUSE, true) && !App.lowPower() && isPlaying()) { - ramp(this.gain, 0.0f, 220, new Runnable() { // from class: com.mulberry.player.MusicService.14 - @Override // java.lang.Runnable - public void run() { - try { - if (mediaPlayer != MusicService.this.cur || MusicService.this.playWhenReady || !mediaPlayer.isPlaying()) { - return; - } - mediaPlayer.pause(); - } catch (Exception e) { - } - } - }); - } else { - this.fadeToken++; - try { - if (this.cur != null && this.curPrepared && this.cur.isPlaying()) { - this.cur.pause(); - } - } catch (Exception e) { - } - } - tickListen(); - Song songCurrent = current(); - if (songCurrent != null) { - ScrobbleBridge.send(this, songCurrent, 2); - } - unregisterNoisy(); - if (z) { - updateNotification(); - } else { - stopFg(false); - } - savePosition(); - notifyState(); - } - - public void next() { - int iNextIndex = nextIndex(true); - if (iNextIndex < 0) { - iNextIndex = 0; - } - if (!this.queue.isEmpty()) { - this.errorStreak = 0; - load(iNextIndex, true, 0L); - } - } - - public void prev() { - if (this.queue.isEmpty()) { - return; - } - if (position() <= 4000) { - int size = this.index - 1; - if (size < 0) { - size = this.repeat == 1 ? this.queue.size() - 1 : 0; - } - this.errorStreak = 0; - load(size, true, 0L); - return; - } - seek(0L); - } - - public void seek(long j) { - if (this.cur != null && this.curPrepared) { - try { - this.cur.seekTo((int) Math.max(0L, j)); - } catch (Exception e) { - } - } else { - this.pendingSeek = j; - } - if (this.spectrum != null) { - this.spectrum.seek(j); - } - this.sampleAt = 0L; - this.pubPos = j; - this.lastTick = SystemClock.elapsedRealtime(); - this.widgetLine = -2; - notifyState(); - } - - public void stopAndQuit() { - stopPlayback(); - saveQueue(); - NotificationManager notificationManager = (NotificationManager) getSystemService("notification"); - if (notificationManager != null) { - notificationManager.cancel(7); - } - this.notifShown = false; - stopSelf(); - } - - public void sleepIn(int i) { - App.MAIN.removeCallbacks(this.sleepTask); - boolean z = this.sleepEndOfTrack; - this.sleepEndOfTrack = false; - if (z) { - prepareNext(); - } - if (i > 0) { - this.sleepAt = SystemClock.elapsedRealtime() + (((long) i) * 60000); - App.MAIN.postDelayed(this.sleepTask, ((long) i) * 60000); - } else { - this.sleepAt = 0L; - } - } - - public void sleepAtEndOfTrack() { - App.MAIN.removeCallbacks(this.sleepTask); - this.sleepAt = 0L; - this.sleepEndOfTrack = true; - releaseNext(); - } - - public long sleepRemaining() { - if (this.sleepAt == 0) { - return this.sleepEndOfTrack ? -1 : 0; - } - return Math.max(0L, this.sleepAt - SystemClock.elapsedRealtime()); - } - - /* JADX INFO: Access modifiers changed from: private */ - public void fadeOutAndPause() { - if (isPlaying()) { - ramp(this.gain, 0.0f, FlacTagCreator.DEFAULT_PADDING, new Runnable() { // from class: com.mulberry.player.MusicService.16 - @Override // java.lang.Runnable - public void run() { - MusicService.this.pause(); - } - }); - } - } - - /* JADX INFO: Access modifiers changed from: private */ - public void beginListen(Song song) { - this.listenedMs = 0L; - this.scrobbled = false; - this.countedPlay = false; - this.startedSec = System.currentTimeMillis() / 1000; - this.lastTick = SystemClock.elapsedRealtime(); - if (song == null || !LastFm.anyOn()) { - return; - } - LastFm.nowPlaying(song); - } - - /* JADX INFO: Access modifiers changed from: private */ - public void tickListen() { - long jElapsedRealtime = SystemClock.elapsedRealtime(); - if (isPlaying()) { - this.listenedMs += Math.min(5000L, jElapsedRealtime - this.lastTick); - } - this.lastTick = jElapsedRealtime; - Song songCurrent = current(); - if (songCurrent != null) { - long jDuration = duration(); - if (!this.countedPlay && jDuration > 0 && this.listenedMs >= Math.min(jDuration / 2, 240000L)) { - this.countedPlay = true; - PlayStats.played(songCurrent); - } - if (!this.scrobbled && jDuration >= 30000 && this.listenedMs >= Math.min(jDuration / 2, 240000L)) { - this.scrobbled = true; - LastFm.scrobble(songCurrent, this.startedSec); - } - } - if (isPlaying()) { - LastFm.maybeRetry(); - } - } - - /* JADX INFO: Access modifiers changed from: private */ - public void finishListen(boolean z) { - tickListen(); - this.listenedMs = 0L; - } - - boolean lyricLineChanged() { - Lyrics.Result result = this.lyrics; - int iLineAt = (result == null || !result.synced || result.lines.isEmpty()) ? -1 : Lyrics.lineAt(result.lines, position() + 250); - if (iLineAt == this.widgetLine) { - return false; - } - this.widgetLine = iLineAt; - return true; - } - - private boolean requestFocus() { - int iRequestAudioFocus; - if (this.am == null) { - return true; - } - if (Build.VERSION.SDK_INT >= 26) { - if (this.focusReq == null) { - this.focusReq = new AudioFocusRequest.Builder(1).setAudioAttributes(new AudioAttributes.Builder().setUsage(1).setContentType(2).build()).setOnAudioFocusChangeListener(this).setWillPauseWhenDucked(false).build(); - } - iRequestAudioFocus = this.am.requestAudioFocus(this.focusReq); - } else { - iRequestAudioFocus = this.am.requestAudioFocus(this, 3, 1); - } - return iRequestAudioFocus == 1; - } - - /* JADX INFO: Access modifiers changed from: private */ - public void abandonFocus() { - if (this.am != null) { - if (Build.VERSION.SDK_INT < 26) { - this.am.abandonAudioFocus(this); - } else if (this.focusReq != null) { - this.am.abandonAudioFocusRequest(this.focusReq); - } - } - } - - @Override // android.media.AudioManager.OnAudioFocusChangeListener - public void onAudioFocusChange(int i) { - switch (i) { - case -3: - this.duckVol = 0.3f; - applyVolume(); - break; - case Ui.WRAP /* -2 */: - if (isPlaying()) { - this.focusLossTransient = true; - pause(true); - } - break; - case Ui.MATCH /* -1 */: - boolean z = this.focusLossTransient; - this.focusLossTransient = false; - pause(); - if (z) { - stopFg(false); - } - break; - case 1: - this.duckVol = 1.0f; - applyVolume(); - if (this.focusLossTransient) { - this.focusLossTransient = false; - play(); - } - break; - } - } - - private void registerNoisy() { - if (!this.noisyRegistered) { - registerReceiver(this.noisy, new IntentFilter("android.media.AUDIO_BECOMING_NOISY")); - this.noisyRegistered = true; - } - } - - private void unregisterNoisy() { - if (this.noisyRegistered) { - try { - unregisterReceiver(this.noisy); - } catch (Exception e) { - } - this.noisyRegistered = false; - } - } - - public Bitmap art() { - return this.art; - } - - /* JADX INFO: Access modifiers changed from: private */ - public void loadArtAndLyrics(Song song) { - final int i = this.artToken + 1; - this.artToken = i; - this.art = null; - this.lyrics = null; - this.widgetLine = -2; - if (song != null) { - Covers.load(song, App.I.lowRam ? 400 : 800, true, new Covers.Cb() { // from class: com.mulberry.player.MusicService.19 - @Override // com.mulberry.player.Covers.Cb - public void done(Bitmap bitmap) { - if (i == MusicService.this.artToken) { - MusicService.this.art = bitmap; - if ("album".equals(App.I.prefs.getStr(Prefs.COLOR_SOURCE, "system"))) { - App.I.palette = Palette.build(MusicService.this, bitmap == null ? null : Palette.dominant(bitmap)); - } - MusicService.this.updateSession(); - MusicService.this.updateNotification(); - Widgets.updateAll(MusicService.this); - Iterator it = MusicService.this.listeners.iterator(); - while (it.hasNext()) { - ((Listener) it.next()).onTrackChanged(); - } - } - } - }); - Lyrics.load(song, false, new Lyrics.Cb() { // from class: com.mulberry.player.MusicService.20 - @Override // com.mulberry.player.Lyrics.Cb - public void done(Lyrics.Result result) { - if (i == MusicService.this.artToken) { - MusicService.this.lyrics = result; - MusicService.this.widgetLine = -2; - Widgets.updateAll(MusicService.this); - Iterator it = MusicService.this.listeners.iterator(); - while (it.hasNext()) { - ((Listener) it.next()).onLyrics(); - } - } - } - }); - } - } - - public void reloadLyrics(boolean z) { - Song songCurrent = current(); - if (songCurrent != null) { - final int i = this.artToken; - this.lyrics = null; - Iterator it = this.listeners.iterator(); - while (it.hasNext()) { - it.next().onLyrics(); - } - Lyrics.load(songCurrent, z, new Lyrics.Cb() { // from class: com.mulberry.player.MusicService.21 - @Override // com.mulberry.player.Lyrics.Cb - public void done(Lyrics.Result result) { - if (i == MusicService.this.artToken) { - MusicService.this.lyrics = result; - MusicService.this.widgetLine = -2; - Widgets.updateAll(MusicService.this); - Iterator it2 = MusicService.this.listeners.iterator(); - while (it2.hasNext()) { - ((Listener) it2.next()).onLyrics(); - } - } - } - }); - } - } - - public void holdForEdit(Set set) { - Song songCurrent = current(); - if (this.nxtIndex >= 0 && this.nxtIndex < this.queue.size() && set.contains(this.queue.get(this.nxtIndex).key())) { - releaseNext(); - } - if (songCurrent != null && set.contains(songCurrent.key()) && this.cur != null) { - this.held = true; - this.heldPlaying = isPlaying() || this.playWhenReady; - this.heldPos = position(); - tickListen(); - releasePlayers(); - if (this.spectrum != null) { - this.spectrum.stop(); - } - notifyState(); - } - } - - public void resumeAfterEdit() { - if (this.held) { - this.held = false; - if (this.index >= 0 && this.index < this.queue.size()) { - long j = this.listenedMs; - boolean z = this.scrobbled; - boolean z2 = this.countedPlay; - long j2 = this.startedSec; - load(this.index, this.heldPlaying, this.heldPos); - this.listenedMs = j; - this.scrobbled = z; - this.countedPlay = z2; - this.startedSec = j2; - return; - } - return; - } - prepareNext(); - } - - public void songEdited() { - Song songCurrent = current(); - if (songCurrent != null) { - loadArtAndLyrics(songCurrent); - } - refreshUi(); - notifyQueue(); - } - - /* JADX INFO: Access modifiers changed from: private */ - public void notifyTrack() { - updateSession(); - updateNotification(); - Widgets.updateAll(this); - Iterator it = this.listeners.iterator(); - while (it.hasNext()) { - it.next().onTrackChanged(); - } - } - - /* JADX INFO: Access modifiers changed from: private */ - public void notifyState() { - updateSession(); - updateNotification(); - Widgets.updateAll(this); - Iterator it = this.listeners.iterator(); - while (it.hasNext()) { - it.next().onStateChanged(); - } - } - - private void notifyQueue() { - updateSessionQueue(); - Iterator it = this.listeners.iterator(); - while (it.hasNext()) { - it.next().onQueueChanged(); - } - } - - public void refreshUi() { - updateSession(); - updateNotification(); - Widgets.updateAll(this); - Iterator it = this.listeners.iterator(); - while (it.hasNext()) { - it.next().onStateChanged(); - } - } - - /* JADX INFO: Access modifiers changed from: private */ - public void updateSession() { - int i; - Song songCurrent = current(); - MediaMetadata.Builder builder = new MediaMetadata.Builder(); - if (songCurrent != null) { - builder.putString("android.media.metadata.TITLE", songCurrent.displayTitle()); - builder.putString("android.media.metadata.ARTIST", songCurrent.displayArtist()); - builder.putString("android.media.metadata.ALBUM", songCurrent.album); - builder.putString("android.media.metadata.ALBUM_ARTIST", songCurrent.albumArtist.length() > 0 ? songCurrent.albumArtist : songCurrent.displayArtist()); - builder.putString("android.media.metadata.MEDIA_ID", songCurrent.key()); - builder.putLong("android.media.metadata.DURATION", duration()); - if (songCurrent.track > 0) { - builder.putLong("android.media.metadata.TRACK_NUMBER", songCurrent.track); - } - if (songCurrent.year > 0) { - builder.putLong("android.media.metadata.YEAR", songCurrent.year); - } - builder.putLong("android.media.metadata.NUM_TRACKS", this.queue.size()); - if (this.art != null) { - builder.putBitmap("android.media.metadata.ALBUM_ART", this.art); - } - } - this.session.setMetadata(builder.build()); - if (isPlaying()) { - i = 3; - } else if (isLoading()) { - i = 6; - } else { - i = songCurrent == null ? 0 : 2; - } - PlaybackState.Builder activeQueueItemId = new PlaybackState.Builder().setActions(5943L).setState(i, position(), isPlaying() ? 1.0f : 0.0f, SystemClock.elapsedRealtime()).setActiveQueueItemId(this.index); - if (this.shuffle) { - } - activeQueueItemId.addCustomAction(new PlaybackState.CustomAction.Builder(ACT_SHUFFLE, "Shuffle", R.drawable.ic_shuffle).build()); - activeQueueItemId.addCustomAction(new PlaybackState.CustomAction.Builder(ACT_REPEAT, "Repeat", this.repeat == 2 ? R.drawable.ic_repeat_one : R.drawable.ic_repeat).build()); - this.session.setPlaybackState(activeQueueItemId.build()); - if (songCurrent == null || this.session.isActive()) { - return; - } - this.session.setActive(true); - } - - private void updateSessionQueue() { - ArrayList arrayList = new ArrayList(); - int iMax = Math.max(0, this.index - 20); - int iMin = Math.min(this.queue.size(), iMax + 100); - for (int i = iMax; i < iMin; i++) { - Song song = this.queue.get(i); - arrayList.add(new MediaSession.QueueItem(new MediaDescription.Builder().setMediaId(song.key()).setTitle(song.displayTitle()).setSubtitle(song.displayArtist()).build(), i)); - } - this.session.setQueue(arrayList); - this.session.setQueueTitle("Queue"); - } - - private PendingIntent svcIntent(String str, int i) { - Intent action = new Intent(this, (Class) MusicService.class).setAction(str); - if (Build.VERSION.SDK_INT < 26 || ACT_STOP.equals(str)) { - return PendingIntent.getService(this, i, action, 201326592); - } - action.putExtra(EXTRA_FG, true); - return PendingIntent.getForegroundService(this, i, action, 201326592); - } - - public PendingIntent actionIntent(String str, int i) { - return svcIntent(str, i); - } - - Notification buildNotification() { - Song songCurrent = current(); - Notification.Builder builder = Build.VERSION.SDK_INT >= 26 ? new Notification.Builder(this, App.CHANNEL) : new Notification.Builder(this); - boolean z = isPlaying() || isLoading(); - builder.setSmallIcon(R.drawable.ic_music_note).setContentTitle(songCurrent == null ? "Mulberry" : songCurrent.displayTitle()).setContentText(songCurrent == null ? FrameBodyCOMM.DEFAULT : songCurrent.displayArtist()).setSubText(songCurrent == null ? null : songCurrent.album).setLargeIcon(this.art).setVisibility(1).setShowWhen(false).setOnlyAlertOnce(true).setOngoing(z).setColor(App.I.palette.primary).setContentIntent(this.session.getController().getSessionActivity()).setDeleteIntent(PendingIntent.getService(this, 20, new Intent(this, (Class) MusicService.class).setAction(ACT_STOP), 67108864)); - builder.addAction(new Notification.Action.Builder(Icon.createWithResource(this, PlayStats.fav(songCurrent == null ? new Song() : songCurrent) ? R.drawable.ic_favorite_fill : R.drawable.ic_favorite), "Favourite", svcIntent(ACT_FAV, 15)).build()); - builder.addAction(new Notification.Action.Builder(Icon.createWithResource(this, R.drawable.ic_skip_previous_fill), "Previous", svcIntent(ACT_PREV, 11)).build()); - builder.addAction(new Notification.Action.Builder(Icon.createWithResource(this, z ? R.drawable.ic_pause_fill : R.drawable.ic_play_arrow_fill), z ? "Pause" : "Play", svcIntent(ACT_TOGGLE, 12)).build()); - builder.addAction(new Notification.Action.Builder(Icon.createWithResource(this, R.drawable.ic_skip_next_fill), "Next", svcIntent(ACT_NEXT, 13)).build()); - builder.addAction(new Notification.Action.Builder(Icon.createWithResource(this, R.drawable.ic_close), "Close", PendingIntent.getService(this, 14, new Intent(this, (Class) MusicService.class).setAction(ACT_STOP), 67108864)).build()); - builder.setStyle(new Notification.MediaStyle().setMediaSession(this.session.getSessionToken()).setShowActionsInCompactView(1, 2, 3)); - if (Build.VERSION.SDK_INT >= 31) { - builder.setForegroundServiceBehavior(1); - } - return builder.build(); - } - - /* JADX INFO: Access modifiers changed from: private */ - public void updateNotification() { - NotificationManager notificationManager; - if (current() != null) { - if ((this.notifShown || this.foreground || this.playWhenReady) && (notificationManager = (NotificationManager) getSystemService("notification")) != null) { - try { - notificationManager.notify(7, buildNotification()); - } catch (Exception e) { - } - } - } - } - - private void goForeground(boolean z) { - if (!this.foreground || z) { - try { - Notification notificationBuildNotification = buildNotification(); - if (Build.VERSION.SDK_INT >= 29) { - startForeground(7, notificationBuildNotification, 2); - } else { - startForeground(7, notificationBuildNotification); - } - this.foreground = true; - this.notifShown = true; - return; - } catch (Exception e) { - updateNotification(); - return; - } - } - updateNotification(); - } - - /* JADX INFO: Access modifiers changed from: private */ - public void stopFg(boolean z) { - if (this.foreground) { - if (Build.VERSION.SDK_INT >= 24) { - stopForeground(z ? 1 : 2); - } else { - stopForeground(z); - } - this.foreground = false; - } - if (current() == null) { - NotificationManager notificationManager = (NotificationManager) getSystemService("notification"); - if (notificationManager != null) { - notificationManager.cancel(7); - return; - } - return; - } - if (!z) { - updateNotification(); - } - } - - /* JADX INFO: Access modifiers changed from: private */ - public File queueFile() { - return new File(getFilesDir(), "queue.json"); - } - - /* JADX INFO: Access modifiers changed from: private */ - public void saveQueueLater() { - App.MAIN.removeCallbacks(this.saveLater); - App.MAIN.postDelayed(this.saveLater, 2000L); - } - - void savePosition() { - App.I.prefs.raw().edit().putInt("q_index", this.index).putLong("q_pos", position()).apply(); - } - - void saveQueue() { - savePosition(); - final ArrayList arrayList = new ArrayList(this.queue); - final ArrayList arrayList2 = new ArrayList(this.original); - final int i = this.index; - final long jPosition = position(); - App.IO.execute(new Runnable() { // from class: com.mulberry.player.MusicService.23 - @Override // java.lang.Runnable - public void run() { - try { - JSONObject jSONObject = new JSONObject(); - JSONArray jSONArray = new JSONArray(); - Iterator it = arrayList.iterator(); - while (it.hasNext()) { - jSONArray.put(((Song) it.next()).toJson()); - } - jSONObject.put("q", jSONArray); - if (MusicService.this.shuffle) { - IdentityHashMap identityHashMap = new IdentityHashMap(); - for (int i2 = 0; i2 < arrayList.size(); i2++) { - if (!identityHashMap.containsKey(arrayList.get(i2))) { - identityHashMap.put((Song) arrayList.get(i2), Integer.valueOf(i2)); - } - } - JSONArray jSONArray2 = new JSONArray(); - Iterator it2 = arrayList2.iterator(); - while (it2.hasNext()) { - Integer num = (Integer) identityHashMap.get((Song) it2.next()); - jSONArray2.put(num == null ? -1 : num.intValue()); - } - jSONObject.put("o", jSONArray2); - } - jSONObject.put("i", i); - jSONObject.put("pos", jPosition); - synchronized (MusicService.class) { - try { - File file = new File(MusicService.this.queueFile().getPath() + ".tmp"); - FileOutputStream fileOutputStream = new FileOutputStream(file); - fileOutputStream.write(jSONObject.toString().getBytes("UTF-8")); - fileOutputStream.close(); - file.renameTo(MusicService.this.queueFile()); - } catch (Throwable th) { - throw th; - } - } - } catch (Exception e) { - } - } - }); - } - - private void restoreQueue() { - try { - File fileQueueFile = queueFile(); - if (fileQueueFile.exists()) { - FileInputStream fileInputStream = new FileInputStream(fileQueueFile); - JSONObject jSONObject = new JSONObject(new String(Net.readAll(fileInputStream), "UTF-8")); - fileInputStream.close(); - JSONArray jSONArray = jSONObject.getJSONArray("q"); - ArrayList arrayList = new ArrayList(); - for (int i = 0; i < jSONArray.length(); i++) { - arrayList.add(Playlists.relink(Song.fromJson(jSONArray.getJSONObject(i)))); - } - ArrayList arrayList2 = new ArrayList(arrayList); - JSONArray jSONArrayOptJSONArray = jSONObject.optJSONArray("o"); - if (jSONArrayOptJSONArray != null && jSONArrayOptJSONArray.length() == arrayList.size()) { - ArrayList arrayList3 = new ArrayList(); - for (int i2 = 0; i2 < jSONArrayOptJSONArray.length(); i2++) { - int i3 = jSONArrayOptJSONArray.getInt(i2); - if (i3 >= 0 && i3 < arrayList.size()) { - arrayList3.add((Song) arrayList.get(i3)); - } - } - arrayList2 = arrayList3.size() != arrayList.size() ? new ArrayList(arrayList) : arrayList3; - } - this.queue = arrayList; - this.original = arrayList2; - int iMin = App.I.prefs.getInt("q_index", -1); - if (iMin < 0 || iMin >= arrayList.size()) { - iMin = Math.min(jSONObject.optInt("i", 0), arrayList.size() - 1); - } - this.index = iMin; - long jOptLong = App.I.prefs.getLong("q_pos", -1L); - if (!App.I.prefs.getBool(Prefs.RESUME, true)) { - jOptLong = 0; - } else if (jOptLong < 0) { - jOptLong = jSONObject.optLong("pos", 0L); - } - this.lastSavedPos = jOptLong; - if (this.index >= 0) { - loadArtAndLyrics(current()); - updateSessionQueue(); - } - } - } catch (Exception e) { - } - } - - public long resumePosition() { - return this.cur == null ? this.lastSavedPos : position(); - } - - private class SessionCb extends MediaSession.Callback { - private SessionCb() { - } - - @Override // android.media.session.MediaSession.Callback - public void onPlay() { - MusicService.this.play(); - } - - @Override // android.media.session.MediaSession.Callback - public void onPause() { - MusicService.this.pause(); - } - - @Override // android.media.session.MediaSession.Callback - public void onSkipToNext() { - MusicService.this.next(); - } - - @Override // android.media.session.MediaSession.Callback - public void onSkipToPrevious() { - MusicService.this.prev(); - } - - @Override // android.media.session.MediaSession.Callback - public void onStop() { - MusicService.this.pause(); - } - - @Override // android.media.session.MediaSession.Callback - public void onSeekTo(long j) { - MusicService.this.seek(j); - } - - @Override // android.media.session.MediaSession.Callback - public void onSkipToQueueItem(long j) { - MusicService.this.jump((int) j); - } - - @Override // android.media.session.MediaSession.Callback - public void onCustomAction(String str, Bundle bundle) { - MusicService.this.handleAction(str); - } - - @Override // android.media.session.MediaSession.Callback - public void onPlayFromMediaId(String str, Bundle bundle) { - MusicService.this.playMediaId(str); - } - - @Override // android.media.session.MediaSession.Callback - public void onPlayFromSearch(String str, Bundle bundle) { - List listSearch = (str == null || str.length() == 0) ? App.I.library.songs : App.I.library.search(str); - if (!listSearch.isEmpty()) { - MusicService.this.playList(listSearch, 0); - } - } - } - - @Override // android.service.media.MediaBrowserService - public MediaBrowserService.BrowserRoot onGetRoot(String str, int i, Bundle bundle) { - return new MediaBrowserService.BrowserRoot("root", null); - } - - @Override // android.service.media.MediaBrowserService - public void onLoadChildren(String str, MediaBrowserService.Result> result) { - ArrayList arrayList = new ArrayList(); - Library library = App.I.library; - if ("root".equals(str)) { - arrayList.add(browsable("shuffle_all", "Shuffle all", library.songs.size() + " songs", true)); - arrayList.add(browsable("albums", "Albums", null, false)); - arrayList.add(browsable("artists", "Artists", null, false)); - arrayList.add(browsable("playlists", "Playlists", null, false)); - } else if ("albums".equals(str) || "artists".equals(str)) { - List list = "albums".equals(str) ? library.albums : library.artists; - for (int i = 0; i < list.size() && i < 500; i++) { - arrayList.add(browsable(str + "/" + i, list.get(i).title, list.get(i).subtitle, false)); - } - } else if ("playlists".equals(str)) { - List listAll = Playlists.all(); - for (int i2 = 0; i2 < listAll.size(); i2++) { - arrayList.add(browsable("pl/" + i2, listAll.get(i2).name, listAll.get(i2).songs.size() + " songs", false)); - } - } else { - List listSongsFor = songsFor(str); - for (int i3 = 0; i3 < listSongsFor.size() && i3 < 500; i3++) { - Song song = listSongsFor.get(i3); - arrayList.add(new MediaBrowser.MediaItem(new MediaDescription.Builder().setMediaId(str + "#" + i3).setTitle(song.displayTitle()).setSubtitle(song.displayArtist()).build(), 2)); - } - } - result.sendResult(arrayList); - } - - private MediaBrowser.MediaItem browsable(String str, String str2, String str3, boolean z) { - return new MediaBrowser.MediaItem(new MediaDescription.Builder().setMediaId(str).setTitle(str2).setSubtitle(str3).build(), z ? 2 : 1); - } - - // Rewritten by hand from the bytecode: the decompiler could not rebuild this method. - private List songsFor(String str) { - Library library = App.I.library; - try { - if (str.startsWith("albums/")) { - return library.albums.get(Integer.parseInt(str.substring(7))).songs; - } - if (str.startsWith("artists/")) { - return library.artists.get(Integer.parseInt(str.substring(8))).songs; - } - if (str.startsWith("pl/")) { - return ((Playlists.PL) Playlists.all().get(Integer.parseInt(str.substring(3)))).songs; - } - } catch (Exception e) { - } - return new ArrayList<>(); - } - - /* JADX INFO: Access modifiers changed from: private */ - public void playMediaId(String str) { - if (str != null) { - if (!"shuffle_all".equals(str)) { - int iLastIndexOf = str.lastIndexOf(35); - if (iLastIndexOf > 0) { - try { - playList(songsFor(str.substring(0, iLastIndexOf)), Integer.parseInt(str.substring(iLastIndexOf + 1))); - return; - } catch (Exception e) { - return; - } - } - playList(songsFor(str), 0); - return; - } - playShuffled(App.I.library.songs); - } - } - - public static void ensureStarted(Context context) { - Intent intent = new Intent(context, (Class) MusicService.class); - try { - context.startService(intent); - } catch (Exception e) { - if (Build.VERSION.SDK_INT >= 26) { - try { - context.startForegroundService(intent.putExtra(EXTRA_FG, true)); - } catch (Exception e2) { - } - } - } - } - - public static ComponentName component(Context context) { - return new ComponentName(context, (Class) MusicService.class); - } -} diff --git a/android/src/com/mulberry/player/Net.java b/android/src/com/mulberry/player/Net.java deleted file mode 100644 index 273c23e..0000000 --- a/android/src/com/mulberry/player/Net.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.mulberry.player; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLEncoder; -import java.util.Map; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; - -/* JADX INFO: loaded from: classes.dex */ -public final class Net { - public static final String UA = "Mulberry-Android/1.0 ( https://github.com/BeamStarTech/Mulberry )"; - - public static String enc(String str) { - if (str == null) { - str = FrameBodyCOMM.DEFAULT; - } - try { - return URLEncoder.encode(str, "UTF-8"); - } catch (Exception e) { - return FrameBodyCOMM.DEFAULT; - } - } - - public static String query(Map map) { - StringBuilder sb = new StringBuilder(); - for (Map.Entry entry : map.entrySet()) { - if (sb.length() > 0) { - sb.append('&'); - } - sb.append(enc(entry.getKey())).append('=').append(enc(entry.getValue())); - } - return sb.toString(); - } - - public static byte[] getBytes(String str, Map map) throws IOException { - HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(str).openConnection(); - httpURLConnection.setConnectTimeout(10000); - httpURLConnection.setReadTimeout(15000); - httpURLConnection.setInstanceFollowRedirects(true); - httpURLConnection.setRequestProperty("User-Agent", UA); - if (map != null) { - for (Map.Entry entry : map.entrySet()) { - httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue()); - } - } - try { - int responseCode = httpURLConnection.getResponseCode(); - InputStream errorStream = responseCode >= 400 ? httpURLConnection.getErrorStream() : httpURLConnection.getInputStream(); - byte[] all = errorStream == null ? new byte[0] : readAll(errorStream); - if (responseCode >= 400 && responseCode != 403 && responseCode != 404) { - throw new IOException("HTTP " + responseCode); - } - if (responseCode == 404) { - byte[] bArr = new byte[0]; - httpURLConnection.disconnect(); - return bArr; - } - httpURLConnection.disconnect(); - return all; - } catch (Throwable th) { - httpURLConnection.disconnect(); - throw th; - } - } - - public static String get(String str, Map map) throws IOException { - return new String(getBytes(str, map), "UTF-8"); - } - - public static String post(String str, String str2) throws IOException { - HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(str).openConnection(); - httpURLConnection.setConnectTimeout(10000); - httpURLConnection.setReadTimeout(15000); - httpURLConnection.setDoOutput(true); - httpURLConnection.setRequestMethod("POST"); - httpURLConnection.setRequestProperty("User-Agent", UA); - httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); - try { - OutputStream outputStream = httpURLConnection.getOutputStream(); - outputStream.write(str2.getBytes("UTF-8")); - outputStream.close(); - InputStream errorStream = httpURLConnection.getResponseCode() >= 400 ? httpURLConnection.getErrorStream() : httpURLConnection.getInputStream(); - return errorStream == null ? FrameBodyCOMM.DEFAULT : new String(readAll(errorStream), "UTF-8"); - } finally { - httpURLConnection.disconnect(); - } - } - - public static byte[] readAll(InputStream inputStream) throws IOException { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - byte[] bArr = new byte[16384]; - while (true) { - try { - int i = inputStream.read(bArr); - if (i <= 0) { - inputStream.close(); - return byteArrayOutputStream.toByteArray(); - } - byteArrayOutputStream.write(bArr, 0, i); - } catch (Throwable th) { - inputStream.close(); - throw th; - } - } - } -} diff --git a/android/src/com/mulberry/player/NowPlaying.java b/android/src/com/mulberry/player/NowPlaying.java deleted file mode 100644 index 6967783..0000000 --- a/android/src/com/mulberry/player/NowPlaying.java +++ /dev/null @@ -1,443 +0,0 @@ -package com.mulberry.player; - -import android.content.res.ColorStateList; -import android.graphics.Typeface; -import android.graphics.drawable.GradientDrawable; -import android.text.TextUtils; -import android.view.GestureDetector; -import android.view.MotionEvent; -import android.view.View; -import android.view.animation.DecelerateInterpolator; -import android.view.animation.PathInterpolator; -import android.widget.FrameLayout; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; -import java.util.Collections; -import org.jaudiotagger.tag.datatype.DataTypes; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; - -/* JADX INFO: loaded from: classes.dex */ -public class NowPlaying extends FrameLayout { - final MainActivity act; - final TextView album; - final TextView artist; - final CookieView cookie; - final TextView dur; - final ImageView fav; - final ImageView lyrBtn; - final TextView lyrSource; - final LyricsView lyrics; - final LinearLayout lyricsCard; - boolean open; - final PlayButton play; - final TextView pos; - final ImageView repeat; - final WavySeekBar seek; - boolean showLyrics; - final ImageView shuffle; - final TextView sourcePill; - final FrameLayout stage; - private final GestureDetector swipe; - final TextView title; - - public NowPlaying(MainActivity mainActivity) { - super(mainActivity); - this.act = mainActivity; - setClickable(true); - Ui.themed(this, new Ui.Paint() { // from class: com.mulberry.player.NowPlaying.1 - @Override // com.mulberry.player.Ui.Paint - public void apply() { - NowPlaying.this.setBackground(new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{Palette.mixC(Ui.c(6), Ui.c(2), 0.35f), Ui.c(6), Ui.c(7)})); - } - }); - LinearLayout linearLayoutCol = Ui.col(mainActivity); - linearLayoutCol.setPadding(Ui.dp(mainActivity, 20.0f), 0, Ui.dp(mainActivity, 20.0f), Ui.dp(mainActivity, 16.0f)); - addView(linearLayoutCol, new FrameLayout.LayoutParams(-1, -1)); - LinearLayout linearLayoutRow = Ui.row(mainActivity); - linearLayoutRow.setPadding(0, Ui.dp(mainActivity, 6.0f), 0, Ui.dp(mainActivity, 6.0f)); - linearLayoutRow.addView(Ui.iconButton(mainActivity, R.drawable.ic_expand_more, 11, 44, new View.OnClickListener() { // from class: com.mulberry.player.NowPlaying.2 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - NowPlaying.this.act.closePlayer(); - } - })); - LinearLayout linearLayoutCol2 = Ui.col(mainActivity); - linearLayoutCol2.setGravity(17); - TextView textViewSingle = Ui.single(mainActivity, "NOW PLAYING", 11.0f, 12, true); - textViewSingle.setLetterSpacing(0.12f); - linearLayoutCol2.addView(textViewSingle); - this.sourcePill = Ui.single(mainActivity, "Mulberry", 12.0f, 3, true); - this.sourcePill.setPadding(Ui.dp(mainActivity, 10.0f), Ui.dp(mainActivity, 2.0f), Ui.dp(mainActivity, 10.0f), Ui.dp(mainActivity, 3.0f)); - Ui.themed(this.sourcePill, new Ui.Paint() { // from class: com.mulberry.player.NowPlaying.3 - @Override // com.mulberry.player.Ui.Paint - public void apply() { - NowPlaying.this.sourcePill.setBackground(Ui.round(Ui.c(2), Ui.dpf(NowPlaying.this.act, 12.0f))); - } - }); - LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(-2, -2); - layoutParams.topMargin = Ui.dp(mainActivity, 3.0f); - linearLayoutCol2.addView(this.sourcePill, layoutParams); - linearLayoutRow.addView(linearLayoutCol2, Ui.lpw(-2, 1.0f)); - linearLayoutRow.addView(Ui.iconButton(mainActivity, R.drawable.ic_more_vert, 11, 44, new View.OnClickListener() { // from class: com.mulberry.player.NowPlaying.4 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - NowPlaying.this.act.playerMenu(); - } - })); - linearLayoutCol.addView(linearLayoutRow); - this.stage = new FrameLayout(mainActivity); - this.cookie = new CookieView(mainActivity); - this.cookie.setOnClickListener(new View.OnClickListener() { // from class: com.mulberry.player.NowPlaying.5 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - NowPlaying.this.toggleLyrics(); - } - }); - this.stage.addView(this.cookie, new FrameLayout.LayoutParams(-1, -1, 17)); - this.lyricsCard = Ui.col(mainActivity); - this.lyricsCard.setPadding(Ui.dp(mainActivity, 18.0f), Ui.dp(mainActivity, 14.0f), Ui.dp(mainActivity, 12.0f), Ui.dp(mainActivity, 8.0f)); - Ui.themed(this.lyricsCard, new Ui.Paint() { // from class: com.mulberry.player.NowPlaying.6 - @Override // com.mulberry.player.Ui.Paint - public void apply() { - NowPlaying.this.lyricsCard.setBackground(Ui.round(Ui.c(8), Ui.dpf(NowPlaying.this.act, 28.0f))); - } - }); - LinearLayout linearLayoutRow2 = Ui.row(mainActivity); - linearLayoutRow2.addView(Ui.icon(mainActivity, R.drawable.ic_lyrics, 11, 20)); - TextView textViewSingle2 = Ui.single(mainActivity, DataTypes.OBJ_LYRICS, 16.0f, 11, true); - textViewSingle2.setPadding(Ui.dp(mainActivity, 8.0f), 0, 0, 0); - linearLayoutRow2.addView(textViewSingle2, Ui.lpw(-2, 1.0f)); - this.lyrSource = Ui.single(mainActivity, FrameBodyCOMM.DEFAULT, 12.0f, 12, false); - linearLayoutRow2.addView(this.lyrSource); - linearLayoutRow2.addView(Ui.iconButton(mainActivity, R.drawable.ic_tune, 12, 38, new View.OnClickListener() { // from class: com.mulberry.player.NowPlaying.7 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - NowPlaying.this.act.lyricsMenu(); - } - })); - this.lyricsCard.addView(linearLayoutRow2); - this.lyrics = new LyricsView(mainActivity); - this.lyrics.setPadding(Ui.dp(mainActivity, 4.0f), 0, Ui.dp(mainActivity, 4.0f), 0); - this.lyrics.setOnSeek(new LyricsView.OnSeek() { // from class: com.mulberry.player.NowPlaying.8 - @Override // com.mulberry.player.LyricsView.OnSeek - public void seekTo(long j) { - if (NowPlaying.this.act.svc != null) { - NowPlaying.this.act.svc.seek(j); - } - } - }); - this.lyricsCard.addView(this.lyrics, Ui.lp(-1, 0)); - ((LinearLayout.LayoutParams) this.lyrics.getLayoutParams()).weight = 1.0f; - this.lyricsCard.setVisibility(8); - this.stage.addView(this.lyricsCard, new FrameLayout.LayoutParams(-1, -1)); - LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(-1, 0, 1.0f); - layoutParams2.topMargin = Ui.dp(mainActivity, 8.0f); - layoutParams2.bottomMargin = Ui.dp(mainActivity, 12.0f); - linearLayoutCol.addView(this.stage, layoutParams2); - LinearLayout linearLayoutRow3 = Ui.row(mainActivity); - LinearLayout linearLayoutCol3 = Ui.col(mainActivity); - this.title = Ui.single(mainActivity, FrameBodyCOMM.DEFAULT, 23.0f, 11, true); - this.title.setTypeface(Typeface.create("sans-serif", 1)); - this.title.setSelected(true); - this.title.setEllipsize(TextUtils.TruncateAt.MARQUEE); - this.title.setMarqueeRepeatLimit(-1); - this.artist = Ui.single(mainActivity, FrameBodyCOMM.DEFAULT, 16.0f, 11, true); - this.album = Ui.single(mainActivity, FrameBodyCOMM.DEFAULT, 15.0f, 0, true); - linearLayoutCol3.addView(this.title); - linearLayoutCol3.addView(this.artist); - linearLayoutCol3.addView(this.album); - linearLayoutRow3.addView(linearLayoutCol3, Ui.lpw(-2, 1.0f)); - this.fav = Ui.iconButton(mainActivity, R.drawable.ic_favorite, 12, 46, new View.OnClickListener() { // from class: com.mulberry.player.NowPlaying.9 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - NowPlaying.this.act.toggleFav(); - } - }); - linearLayoutRow3.addView(this.fav); - linearLayoutCol.addView(linearLayoutRow3); - this.seek = new WavySeekBar(mainActivity); - this.seek.setOnSeek(new WavySeekBar.OnSeek() { // from class: com.mulberry.player.NowPlaying.10 - @Override // com.mulberry.player.WavySeekBar.OnSeek - public void seek(float f) { - if (NowPlaying.this.act.svc != null) { - NowPlaying.this.act.svc.seek((long) (NowPlaying.this.act.svc.duration() * f)); - } - } - - @Override // com.mulberry.player.WavySeekBar.OnSeek - public void dragging(float f) { - if (NowPlaying.this.act.svc != null) { - NowPlaying.this.pos.setText(Draw.time((long) (NowPlaying.this.act.svc.duration() * f))); - } - } - }); - LinearLayout.LayoutParams layoutParamsLp = Ui.lp(-1, -2); - layoutParamsLp.topMargin = Ui.dp(mainActivity, 10.0f); - linearLayoutCol.addView(this.seek, layoutParamsLp); - LinearLayout linearLayoutRow4 = Ui.row(mainActivity); - linearLayoutRow4.setPadding(Ui.dp(mainActivity, 10.0f), 0, Ui.dp(mainActivity, 10.0f), 0); - this.pos = Ui.single(mainActivity, "0:00", 12.0f, 12, false); - this.dur = Ui.single(mainActivity, "0:00", 12.0f, 12, false); - linearLayoutRow4.addView(this.pos, Ui.lpw(-2, 1.0f)); - linearLayoutRow4.addView(this.dur); - linearLayoutCol.addView(linearLayoutRow4); - LinearLayout linearLayoutRow5 = Ui.row(mainActivity); - linearLayoutRow5.setGravity(17); - linearLayoutRow5.setPadding(0, Ui.dp(mainActivity, 10.0f), 0, Ui.dp(mainActivity, 6.0f)); - this.shuffle = tonalCircle(R.drawable.ic_shuffle, new View.OnClickListener() { // from class: com.mulberry.player.NowPlaying.11 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - if (NowPlaying.this.act.svc != null) { - NowPlaying.this.act.svc.setShuffle(!NowPlaying.this.act.svc.shuffle()); - } - } - }); - linearLayoutRow5.addView(this.shuffle); - linearLayoutRow5.addView(tonalCircle(R.drawable.ic_skip_previous_fill, new View.OnClickListener() { // from class: com.mulberry.player.NowPlaying.12 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - if (NowPlaying.this.act.svc != null) { - NowPlaying.this.act.svc.prev(); - } - } - })); - this.play = new PlayButton(mainActivity); - this.play.setOnClickListener(new View.OnClickListener() { // from class: com.mulberry.player.NowPlaying.13 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - NowPlaying.this.act.togglePlay(); - } - }); - LinearLayout.LayoutParams layoutParams3 = new LinearLayout.LayoutParams(Ui.dp(mainActivity, 104.0f), Ui.dp(mainActivity, 68.0f)); - int iDp = Ui.dp(mainActivity, 8.0f); - layoutParams3.rightMargin = iDp; - layoutParams3.leftMargin = iDp; - linearLayoutRow5.addView(this.play, layoutParams3); - linearLayoutRow5.addView(tonalCircle(R.drawable.ic_skip_next_fill, new View.OnClickListener() { // from class: com.mulberry.player.NowPlaying.14 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - if (NowPlaying.this.act.svc != null) { - NowPlaying.this.act.svc.next(); - } - } - })); - this.repeat = tonalCircle(R.drawable.ic_repeat, new View.OnClickListener() { // from class: com.mulberry.player.NowPlaying.15 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - if (NowPlaying.this.act.svc != null) { - NowPlaying.this.act.svc.cycleRepeat(); - } - } - }); - linearLayoutRow5.addView(this.repeat); - linearLayoutCol.addView(linearLayoutRow5); - LinearLayout linearLayoutRow6 = Ui.row(mainActivity); - linearLayoutRow6.setGravity(17); - this.lyrBtn = Ui.iconButton(mainActivity, R.drawable.ic_lyrics, 12, 46, new View.OnClickListener() { // from class: com.mulberry.player.NowPlaying.16 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - NowPlaying.this.toggleLyrics(); - } - }); - linearLayoutRow6.addView(this.lyrBtn); - linearLayoutRow6.addView(Ui.space(mainActivity, 28)); - linearLayoutRow6.addView(Ui.iconButton(mainActivity, R.drawable.ic_queue_music, 12, 46, new View.OnClickListener() { // from class: com.mulberry.player.NowPlaying.17 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - NowPlaying.this.act.showQueue(); - } - })); - linearLayoutRow6.addView(Ui.space(mainActivity, 28)); - linearLayoutRow6.addView(Ui.iconButton(mainActivity, R.drawable.ic_history, 12, 46, new View.OnClickListener() { // from class: com.mulberry.player.NowPlaying.18 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - NowPlaying.this.act.sleepTimer(); - } - })); - linearLayoutRow6.addView(Ui.space(mainActivity, 28)); - linearLayoutRow6.addView(Ui.iconButton(mainActivity, R.drawable.ic_edit, 12, 46, new View.OnClickListener() { // from class: com.mulberry.player.NowPlaying.19 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - Song songCurrent = NowPlaying.this.act.svc == null ? null : NowPlaying.this.act.svc.current(); - if (songCurrent != null) { - NowPlaying.this.act.editTags(Collections.singletonList(songCurrent)); - } - } - })); - linearLayoutCol.addView(linearLayoutRow6); - this.swipe = new GestureDetector(mainActivity, new GestureDetector.SimpleOnGestureListener() { // from class: com.mulberry.player.NowPlaying.20 - @Override // android.view.GestureDetector.SimpleOnGestureListener, android.view.GestureDetector.OnGestureListener - public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent2, float f, float f2) { - if (motionEvent == null || motionEvent2.getY() - motionEvent.getY() <= Ui.dp(NowPlaying.this.act, 90.0f) || Math.abs(f2) <= Math.abs(f)) { - return false; - } - NowPlaying.this.act.closePlayer(); - return true; - } - }); - applyOrientation(); - } - - ImageView tonalCircle(int i, View.OnClickListener onClickListener) { - final ImageView imageViewIcon = Ui.icon(this.act, i, 5, 52); - int iDp = Ui.dp(this.act, 14.0f); - imageViewIcon.setPadding(iDp, iDp, iDp, iDp); - Ui.themed(imageViewIcon, new Ui.Paint() { // from class: com.mulberry.player.NowPlaying.21 - @Override // com.mulberry.player.Ui.Paint - public void apply() { - imageViewIcon.setBackground(Ui.ripple(Ui.round(Ui.c(4), Ui.dpf(NowPlaying.this.act, 26.0f)), Ui.c(11), Ui.round(-1, Ui.dpf(NowPlaying.this.act, 26.0f)))); - } - }); - imageViewIcon.setClickable(true); - imageViewIcon.setOnClickListener(onClickListener); - LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) imageViewIcon.getLayoutParams(); - int iDp2 = Ui.dp(this.act, 4.0f); - layoutParams.rightMargin = iDp2; - layoutParams.leftMargin = iDp2; - return imageViewIcon; - } - - @Override // android.view.ViewGroup - public boolean onInterceptTouchEvent(MotionEvent motionEvent) { - this.swipe.onTouchEvent(motionEvent); - return false; - } - - @Override // android.view.View - public boolean onTouchEvent(MotionEvent motionEvent) { - this.swipe.onTouchEvent(motionEvent); - return true; - } - - void applyOrientation() { - if (getResources().getConfiguration().orientation == 2) { - this.showLyrics = false; - } - } - - void toggleLyrics() { - this.showLyrics = !this.showLyrics; - View view = this.showLyrics ? this.lyricsCard : this.cookie; - final View view2 = this.showLyrics ? this.cookie : this.lyricsCard; - this.lyrBtn.setImageTintList(ColorStateList.valueOf(Ui.c(this.showLyrics ? 0 : 12))); - if (!App.lowPower()) { - view.setAlpha(0.0f); - view.setScaleX(0.94f); - view.setScaleY(0.94f); - view.setVisibility(0); - view.animate().alpha(1.0f).scaleX(1.0f).scaleY(1.0f).setDuration(260L).setInterpolator(new PathInterpolator(0.2f, 0.0f, 0.0f, 1.0f)).start(); - view2.animate().alpha(0.0f).scaleX(0.94f).scaleY(0.94f).setDuration(180L).withEndAction(new Runnable() { // from class: com.mulberry.player.NowPlaying.22 - @Override // java.lang.Runnable - public void run() { - view2.setVisibility(8); - view2.setAlpha(1.0f); - view2.setScaleX(1.0f); - view2.setScaleY(1.0f); - } - }).start(); - return; - } - view2.setVisibility(8); - view.setVisibility(0); - } - - void bindService(MusicService musicService) { - this.cookie.setService(musicService); - this.lyrics.setService(musicService); - } - - void updateTrack() { - MusicService musicService = this.act.svc; - Song songCurrent = musicService == null ? null : musicService.current(); - this.title.setText(songCurrent == null ? "Nothing playing" : songCurrent.displayTitle()); - this.artist.setText(songCurrent == null ? FrameBodyCOMM.DEFAULT : songCurrent.displayArtist()); - this.album.setText(songCurrent == null ? FrameBodyCOMM.DEFAULT : songCurrent.album); - this.cookie.setCover(musicService != null ? musicService.art() : null); - this.fav.setImageResource((songCurrent == null || !PlayStats.fav(songCurrent)) ? R.drawable.ic_favorite : R.drawable.ic_favorite_fill); - this.fav.setImageTintList(ColorStateList.valueOf(Ui.c((songCurrent == null || !PlayStats.fav(songCurrent)) ? 12 : 0))); - updateLyrics(); - updateState(); - } - - void updateLyrics() { - String str; - MusicService musicService = this.act.svc; - Lyrics.Result result = musicService == null ? null : musicService.lyrics; - if (musicService != null && musicService.current() == null) { - result = new Lyrics.Result(); - } - this.lyrics.setResult(result); - TextView textView = this.lyrSource; - if (result == null) { - str = FrameBodyCOMM.DEFAULT; - } else { - str = result.source + ((result == null || !result.synced) ? FrameBodyCOMM.DEFAULT : " · synced"); - } - textView.setText(str); - } - - void updateState() { - MusicService musicService = this.act.svc; - this.play.setPlaying(musicService != null && (musicService.isPlaying() || musicService.isLoading())); - this.cookie.setPlaying(musicService != null && musicService.isPlaying()); - this.seek.setPlaying(musicService != null && musicService.isPlaying()); - this.lyrics.setPlaying(musicService != null && musicService.isPlaying()); - long jPosition = musicService == null ? 0L : musicService.position(); - long jDuration = musicService != null ? musicService.duration() : 0L; - this.seek.set(jPosition, jDuration); - this.pos.setText(Draw.time(jPosition)); - this.dur.setText(Draw.time(jDuration)); - boolean z = musicService != null && musicService.shuffle(); - int iRepeat = musicService == null ? 0 : musicService.repeat(); - tint(this.shuffle, z); - tint(this.repeat, iRepeat != 0); - this.repeat.setImageResource(iRepeat == 2 ? R.drawable.ic_repeat_one : R.drawable.ic_repeat); - } - - void tint(ImageView imageView, boolean z) { - imageView.setBackground(Ui.ripple(Ui.round(Ui.c(z ? 0 : 4), Ui.dpf(this.act, z ? 16.0f : 26.0f)), Ui.c(11), Ui.round(-1, Ui.dpf(this.act, 26.0f)))); - imageView.setImageTintList(ColorStateList.valueOf(Ui.c(z ? 1 : 5))); - } - - void tick() { - MusicService musicService = this.act.svc; - if (musicService != null) { - long jPosition = musicService.position(); - long jDuration = musicService.duration(); - this.seek.set(jPosition, jDuration); - this.pos.setText(Draw.time(jPosition)); - this.dur.setText(Draw.time(jDuration)); - } - } - - void animateOpen(boolean z) { - this.open = z; - if (z) { - setVisibility(0); - if (!App.lowPower()) { - setTranslationY(getHeight() > 0 ? getHeight() : Ui.dp(this.act, 800.0f)); - setAlpha(0.6f); - animate().translationY(0.0f).alpha(1.0f).setDuration(340L).setInterpolator(new PathInterpolator(0.05f, 0.7f, 0.1f, 1.0f)).start(); - return; - } else { - setTranslationY(0.0f); - setAlpha(1.0f); - return; - } - } - if (!App.lowPower()) { - animate().translationY(getHeight()).alpha(0.6f).setDuration(240L).setInterpolator(new DecelerateInterpolator()).withEndAction(new Runnable() { // from class: com.mulberry.player.NowPlaying.23 - @Override // java.lang.Runnable - public void run() { - if (NowPlaying.this.open) { - return; - } - NowPlaying.this.setVisibility(8); - } - }).start(); - } else { - setVisibility(8); - } - } -} diff --git a/android/src/com/mulberry/player/OggOpus.java b/android/src/com/mulberry/player/OggOpus.java deleted file mode 100644 index 6c9bb71..0000000 --- a/android/src/com/mulberry/player/OggOpus.java +++ /dev/null @@ -1,582 +0,0 @@ -package com.mulberry.player; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.RandomAccessFile; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import org.jaudiotagger.audio.asf.data.ContentDescription; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; -import org.jaudiotagger.tag.id3.framebody.FrameBodyTXXX; -import org.jaudiotagger.tag.id3.valuepair.TextEncoding; - -/* JADX INFO: loaded from: classes.dex */ -public final class OggOpus { - private static final int[] CRC = new int[256]; - static final String[][] KEYS; - - private OggOpus() { - } - - static { - for (int i = 0; i < 256; i++) { - int i2 = i << 24; - for (int i3 = 0; i3 < 8; i3++) { - i2 = (Integer.MIN_VALUE & i2) != 0 ? (i2 << 1) ^ 79764919 : i2 << 1; - } - CRC[i] = i2; - } - KEYS = new String[][]{new String[]{"title", ContentDescription.KEY_TITLE}, new String[]{"artist", "ARTIST"}, new String[]{"album", "ALBUM"}, new String[]{"albumartist", "ALBUMARTIST"}, new String[]{"genre", "GENRE"}, new String[]{"composer", "COMPOSER"}, new String[]{"year", "DATE"}, new String[]{"comment", "COMMENT"}, new String[]{"mb_trackid", "MUSICBRAINZ_TRACKID"}, new String[]{"mb_albumid", "MUSICBRAINZ_ALBUMID"}}; - } - - static int crc(byte[] bArr, int i, int i2) { - int i3 = 0; - for (int i4 = i; i4 < i + i2; i4++) { - i3 = CRC[((i3 >>> 24) ^ bArr[i4]) & 255] ^ (i3 << 8); - } - return i3; - } - - static final class Page { - long granule; - int headerLen; - int headerType; - int[] lacing; - long offset; - byte[] raw; - int seq; - int serial; - - Page() { - } - - int dataLen() { - int[] iArr = this.lacing; - int length = iArr.length; - int i = 0; - int i2 = 0; - while (i < length) { - int i3 = iArr[i] + i2; - i++; - i2 = i3; - } - return i2; - } - } - - static Page readPage(RandomAccessFile randomAccessFile) throws IOException { - long filePointer = randomAccessFile.getFilePointer(); - byte[] bArr = new byte[27]; - if (randomAccessFile.read(bArr) < 27) { - return null; - } - if (bArr[0] != 79 || bArr[1] != 103 || bArr[2] != 103 || bArr[3] != 83) { - throw new IOException("not an Ogg file (bad page at " + filePointer + ")"); - } - int i = bArr[26] & 255; - byte[] bArr2 = new byte[i]; - randomAccessFile.readFully(bArr2); - Page page = new Page(); - page.offset = filePointer; - page.headerType = bArr[5] & 255; - page.granule = le64(bArr, 6); - page.serial = le32(bArr, 14); - page.seq = le32(bArr, 18); - page.lacing = new int[i]; - int i2 = 0; - for (int i3 = 0; i3 < i; i3++) { - page.lacing[i3] = bArr2[i3] & 255; - i2 += page.lacing[i3]; - } - page.headerLen = i + 27; - page.raw = new byte[page.headerLen + i2]; - System.arraycopy(bArr, 0, page.raw, 0, 27); - System.arraycopy(bArr2, 0, page.raw, 27, i); - randomAccessFile.readFully(page.raw, page.headerLen, i2); - return page; - } - - static int le32(byte[] bArr, int i) { - return (bArr[i] & 255) | ((bArr[i + 1] & 255) << 8) | ((bArr[i + 2] & 255) << 16) | ((bArr[i + 3] & 255) << 24); - } - - static long le64(byte[] bArr, int i) { - return (((long) le32(bArr, i)) & 4294967295L) | (((long) le32(bArr, i + 4)) << 32); - } - - static void put32(byte[] bArr, int i, int i2) { - bArr[i] = (byte) i2; - bArr[i + 1] = (byte) (i2 >> 8); - bArr[i + 2] = (byte) (i2 >> 16); - bArr[i + 3] = (byte) (i2 >> 24); - } - - static void put64(byte[] bArr, int i, long j) { - put32(bArr, i, (int) j); - put32(bArr, i + 4, (int) (j >>> 32)); - } - - static void reseal(byte[] bArr, int i) { - put32(bArr, 18, i); - put32(bArr, 22, 0); - put32(bArr, 22, crc(bArr, 0, bArr.length)); - } - - static final class Layout { - long audioOffset; - byte[] head; - int lastHeaderSeq; - int serial; - int tagPages; - byte[] tags; - - Layout() { - } - } - - static Layout layout(RandomAccessFile randomAccessFile) throws IOException { - randomAccessFile.seek(0L); - Layout layout = new Layout(); - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - int i = 0; - int i2 = 0; - while (true) { - Page page = readPage(randomAccessFile); - if (page == null) { - throw new IOException("truncated Ogg header"); - } - if (i2 == 0 && byteArrayOutputStream.size() == 0) { - layout.serial = page.serial; - } - if (page.serial == layout.serial) { - if (i2 == 1) { - i++; - } - int i3 = page.headerLen; - for (int i4 : page.lacing) { - byteArrayOutputStream.write(page.raw, i3, i4); - i3 += i4; - if (i4 < 255) { - if (i2 == 0) { - layout.head = byteArrayOutputStream.toByteArray(); - } else if (i2 == 1) { - layout.tags = byteArrayOutputStream.toByteArray(); - } - byteArrayOutputStream.reset(); - i2++; - if (i2 == 1) { - i = 0; - } - } - } - if (i2 >= 2) { - if (i3 != page.raw.length) { - throw new IOException("unexpected data after OpusTags"); - } - layout.tagPages = Math.max(1, i); - layout.lastHeaderSeq = page.seq; - layout.audioOffset = randomAccessFile.getFilePointer(); - if (layout.head == null || layout.head.length < 19 || !new String(layout.head, 0, 8, TextEncoding.CHARSET_ISO_8859_1).equals("OpusHead")) { - throw new IOException("not an Opus file"); - } - if (layout.tags == null || layout.tags.length < 16 || !new String(layout.tags, 0, 8, TextEncoding.CHARSET_ISO_8859_1).equals("OpusTags")) { - throw new IOException("missing OpusTags"); - } - return layout; - } - if (byteArrayOutputStream.size() > 33554432) { - throw new IOException("header too large"); - } - } - } - } - - public static boolean isOpus(File file) { - try { - RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); - try { - byte[] bArr = new byte[36]; - if (randomAccessFile.read(bArr) < 36) { - return false; - } - return bArr[0] == 79 && bArr[1] == 103 && bArr[2] == 103 && bArr[3] == 83 && new String(bArr, 28, 8, TextEncoding.CHARSET_ISO_8859_1).equals("OpusHead"); - } finally { - randomAccessFile.close(); - } - } catch (Exception e) { - return false; - } - } - - static final class Comments { - String vendor = "Mulberry"; - final List items = new ArrayList(); - byte[] trailer = new byte[0]; - - Comments() { - } - - String get(String str) { - String str2 = str.toUpperCase(Locale.ROOT) + "="; - for (String str3 : this.items) { - if (str3.length() >= str2.length() && str3.substring(0, str2.length()).toUpperCase(Locale.ROOT).equals(str2)) { - return str3.substring(str2.length()); - } - } - return FrameBodyCOMM.DEFAULT; - } - - void remove(String str) { - String str2 = str.toUpperCase(Locale.ROOT) + "="; - for (int size = this.items.size() - 1; size >= 0; size--) { - String str3 = this.items.get(size); - if (str3.length() >= str2.length() && str3.substring(0, str2.length()).toUpperCase(Locale.ROOT).equals(str2)) { - this.items.remove(size); - } - } - } - - void set(String str, String str2) { - remove(str); - if (str2 == null || str2.length() <= 0) { - return; - } - this.items.add(str + "=" + str2); - } - } - - static Comments parse(byte[] bArr) throws IOException { - Comments comments = new Comments(); - int iLe32 = le32(bArr, 8); - if (iLe32 < 0 || iLe32 + 12 > bArr.length) { - throw new IOException("bad OpusTags"); - } - comments.vendor = new String(bArr, 12, iLe32, "UTF-8"); - int i = iLe32 + 12; - int iLe33 = le32(bArr, i); - int i2 = i + 4; - for (int i3 = 0; i3 < iLe33; i3++) { - int iLe34 = le32(bArr, i2); - int i4 = i2 + 4; - if (iLe34 < 0 || i4 + iLe34 > bArr.length) { - throw new IOException("bad OpusTags comment"); - } - comments.items.add(new String(bArr, i4, iLe34, "UTF-8")); - i2 = i4 + iLe34; - } - if (i2 < bArr.length && (bArr[i2] & 1) == 1) { - comments.trailer = new byte[bArr.length - i2]; - System.arraycopy(bArr, i2, comments.trailer, 0, comments.trailer.length); - } - return comments; - } - - static byte[] build(Comments comments) throws IOException { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - byteArrayOutputStream.write("OpusTags".getBytes(TextEncoding.CHARSET_ISO_8859_1)); - byte[] bytes = comments.vendor.getBytes("UTF-8"); - writeLe32(byteArrayOutputStream, bytes.length); - byteArrayOutputStream.write(bytes); - writeLe32(byteArrayOutputStream, comments.items.size()); - Iterator it = comments.items.iterator(); - while (it.hasNext()) { - byte[] bytes2 = it.next().getBytes("UTF-8"); - writeLe32(byteArrayOutputStream, bytes2.length); - byteArrayOutputStream.write(bytes2); - } - byteArrayOutputStream.write(comments.trailer); - return byteArrayOutputStream.toByteArray(); - } - - static void writeLe32(OutputStream outputStream, int i) throws IOException { - outputStream.write(i); - outputStream.write(i >> 8); - outputStream.write(i >> 16); - outputStream.write(i >> 24); - } - - static String vkey(String str) { - for (String[] strArr : KEYS) { - if (strArr[0].equals(str)) { - return strArr[1]; - } - } - return null; - } - - static byte[] picture(byte[] bArr, String str, int i, int i2) throws IOException { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - byte[] bytes = str.getBytes(TextEncoding.CHARSET_ISO_8859_1); - be32(byteArrayOutputStream, 3); - be32(byteArrayOutputStream, bytes.length); - byteArrayOutputStream.write(bytes); - be32(byteArrayOutputStream, 0); - be32(byteArrayOutputStream, i); - be32(byteArrayOutputStream, i2); - be32(byteArrayOutputStream, 24); - be32(byteArrayOutputStream, 0); - be32(byteArrayOutputStream, bArr.length); - byteArrayOutputStream.write(bArr); - return byteArrayOutputStream.toByteArray(); - } - - static void be32(OutputStream outputStream, int i) throws IOException { - outputStream.write(i >> 24); - outputStream.write(i >> 16); - outputStream.write(i >> 8); - outputStream.write(i); - } - - static int be32(byte[] bArr, int i) { - return ((bArr[i] & 255) << 24) | ((bArr[i + 1] & 255) << 16) | ((bArr[i + 2] & 255) << 8) | (bArr[i + 3] & 255); - } - - static Object[] unpicture(byte[] bArr) { - try { - int iBe32 = be32(bArr, 4); - String str = new String(bArr, 8, iBe32, TextEncoding.CHARSET_ISO_8859_1); - int i = iBe32 + 8; - int iBe33 = i + be32(bArr, i) + 4 + 16; - int iBe34 = be32(bArr, iBe33); - int i2 = iBe33 + 4; - if (iBe34 <= 0 || i2 + iBe34 > bArr.length) { - return null; - } - byte[] bArr2 = new byte[iBe34]; - System.arraycopy(bArr, i2, bArr2, 0, iBe34); - return new Object[]{bArr2, str}; - } catch (Exception e) { - return null; - } - } - - public static TagCore.Info read(File file) throws Exception { - Object[] objArrUnpicture; - String strNum; - RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); - try { - Layout layout = layout(randomAccessFile); - Comments comments = parse(layout.tags); - TagCore.Info info = new TagCore.Info(); - for (String[] strArr : TagCore.FIELDS) { - if ("track".equals(strArr[0])) { - strNum = num(comments.get("TRACKNUMBER"), comments.get("TRACKTOTAL").length() > 0 ? comments.get("TRACKTOTAL") : comments.get("TOTALTRACKS")); - } else if ("disc".equals(strArr[0])) { - strNum = num(comments.get("DISCNUMBER"), comments.get("DISCTOTAL").length() > 0 ? comments.get("DISCTOTAL") : comments.get("TOTALDISCS")); - } else { - strNum = comments.get(vkey(strArr[0])); - if ("comment".equals(strArr[0]) && strNum.length() == 0) { - strNum = comments.get(ContentDescription.KEY_DESCRIPTION); - } - if ("albumartist".equals(strArr[0]) && strNum.length() == 0) { - strNum = comments.get(FrameBodyTXXX.ALBUM_ARTIST); - } - } - info.fields.put(strArr[0], strNum.trim()); - } - info.lyrics = comments.get("LYRICS").length() > 0 ? comments.get("LYRICS") : comments.get("UNSYNCEDLYRICS"); - String str = comments.get("METADATA_BLOCK_PICTURE"); - if (str.length() > 0 && (objArrUnpicture = unpicture(TagCore.B64.decode(str))) != null) { - info.cover = (byte[]) objArrUnpicture[0]; - info.coverMime = (String) objArrUnpicture[1]; - } - info.format = "Opus"; - info.channels = String.valueOf(layout.head[9] & 255); - int iLe32 = le32(layout.head, 12); - if (iLe32 <= 0) { - iLe32 = 48000; - } - info.sampleRate = iLe32; - int i = (layout.head[10] & 255) | ((layout.head[11] & 255) << 8); - long jLastGranule = lastGranule(randomAccessFile, layout.serial); - if (jLastGranule > i) { - info.lengthSec = (int) ((jLastGranule - ((long) i)) / 48000); - } - if (info.lengthSec > 0) { - info.bitrate = String.valueOf(((file.length() * 8) / 1000) / ((long) info.lengthSec)); - } - return info; - } finally { - randomAccessFile.close(); - } - } - - static String num(String str, String str2) { - String strTrim = str.trim(); - String strTrim2 = str2.trim(); - if (strTrim.length() == 0) { - return FrameBodyCOMM.DEFAULT; - } - return (strTrim2.length() <= 0 || "0".equals(strTrim2) || strTrim.contains("/")) ? strTrim : strTrim + "/" + strTrim2; - } - - static long lastGranule(RandomAccessFile randomAccessFile, int i) throws IOException { - long length = randomAccessFile.length(); - int iMin = (int) Math.min(length, 65836L); - byte[] bArr = new byte[iMin]; - randomAccessFile.seek(length - ((long) iMin)); - randomAccessFile.readFully(bArr); - for (int i2 = iMin - 27; i2 >= 0; i2--) { - if (bArr[i2] == 79 && bArr[i2 + 1] == 103 && bArr[i2 + 2] == 103 && bArr[i2 + 3] == 83 && le32(bArr, i2 + 14) == i) { - long jLe64 = le64(bArr, i2 + 6); - if (jLe64 != -1) { - return jLe64; - } - } - } - return -1L; - } - - public static void write(File file, Map map, byte[] bArr, String str, int i, int i2, boolean z, String str2) throws Exception { - String strTrim; - RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); - File file2 = new File(file.getPath() + ".mbtmp"); - try { - try { - Layout layout = layout(randomAccessFile); - Comments comments = parse(layout.tags); - comments.vendor = comments.vendor.length() == 0 ? "Mulberry" : comments.vendor; - for (Map.Entry entry : map.entrySet()) { - String strTrim2 = entry.getValue() == null ? FrameBodyCOMM.DEFAULT : entry.getValue().trim(); - String key = entry.getKey(); - if ("track".equals(key) || "disc".equals(key)) { - String str3 = "track".equals(key) ? "TRACKNUMBER" : "DISCNUMBER"; - String str4 = "track".equals(key) ? "TRACKTOTAL" : "DISCTOTAL"; - String strTrim3 = FrameBodyCOMM.DEFAULT; - int iIndexOf = strTrim2.indexOf(47); - if (iIndexOf >= 0) { - strTrim = strTrim2.substring(0, iIndexOf).trim(); - strTrim3 = strTrim2.substring(iIndexOf + 1).trim(); - } else { - strTrim = strTrim2; - } - String strReplaceAll = strTrim.replaceAll("[^0-9]", FrameBodyCOMM.DEFAULT); - String strReplaceAll2 = strTrim3.replaceAll("[^0-9]", FrameBodyCOMM.DEFAULT); - comments.set(str3, (strReplaceAll.length() == 0 || "0".equals(strReplaceAll)) ? FrameBodyCOMM.DEFAULT : String.valueOf(Integer.parseInt(strReplaceAll))); - if (iIndexOf >= 0 || strReplaceAll.length() == 0) { - comments.set(str4, (strReplaceAll2.length() == 0 || "0".equals(strReplaceAll2)) ? FrameBodyCOMM.DEFAULT : String.valueOf(Integer.parseInt(strReplaceAll2))); - comments.remove("TRACKNUMBER".equals(str3) ? "TOTALTRACKS" : "TOTALDISCS"); - } - } else { - String strVkey = vkey(key); - if (strVkey != null) { - comments.set(strVkey, strTrim2); - if ("comment".equals(key)) { - comments.remove(ContentDescription.KEY_DESCRIPTION); - } - } - } - } - if (str2 != null) { - comments.set("LYRICS", str2); - comments.remove("UNSYNCEDLYRICS"); - } - if (z || bArr != null) { - comments.remove("METADATA_BLOCK_PICTURE"); - comments.remove("COVERART"); - comments.remove("COVERARTMIME"); - } - if (bArr != null) { - comments.items.add("METADATA_BLOCK_PICTURE=" + TagCore.B64.encode(picture(bArr, str, i, i2))); - } - byte[] bArrBuild = build(comments); - FileOutputStream fileOutputStream = new FileOutputStream(file2); - try { - randomAccessFile.seek(0L); - Page page = readPage(randomAccessFile); - fileOutputStream.write(page.raw); - int i3 = page.seq + 1; - int length = (bArrBuild.length / 255) + 1; - boolean z2 = false; - int i4 = 0; - int i5 = 0; - int i6 = i3; - while (i4 < length) { - int iMin = Math.min(255, length - i4); - boolean z3 = i4 + iMin == length; - int i7 = 0; - byte[] bArr2 = new byte[iMin]; - for (int i8 = 0; i8 < iMin; i8++) { - int length2 = i4 + i8 < length + (-1) ? 255 : bArrBuild.length - ((length - 1) * 255); - bArr2[i8] = (byte) length2; - i7 += length2; - } - byte[] bArr3 = new byte[iMin + 27 + i7]; - bArr3[0] = 79; - bArr3[1] = 103; - bArr3[2] = 103; - bArr3[3] = 83; - bArr3[4] = 0; - bArr3[5] = (byte) (z2 ? 1 : 0); - put64(bArr3, 6, z3 ? 0L : -1L); - put32(bArr3, 14, layout.serial); - bArr3[26] = (byte) iMin; - System.arraycopy(bArr2, 0, bArr3, 27, iMin); - System.arraycopy(bArrBuild, i5, bArr3, iMin + 27, i7); - reseal(bArr3, i6); - fileOutputStream.write(bArr3); - z2 = true; - i4 += iMin; - i5 = i7 + i5; - i6++; - } - int i9 = (i6 - 1) - layout.lastHeaderSeq; - randomAccessFile.seek(layout.audioOffset); - if (i9 != 0) { - while (true) { - Page page2 = readPage(randomAccessFile); - if (page2 == null) { - break; - } - if (page2.serial == layout.serial) { - reseal(page2.raw, page2.seq + i9); - } - fileOutputStream.write(page2.raw); - } - } else { - byte[] bArr4 = new byte[262144]; - while (true) { - int i10 = randomAccessFile.read(bArr4); - if (i10 <= 0) { - break; - } else { - fileOutputStream.write(bArr4, 0, i10); - } - } - } - randomAccessFile.close(); - if (!file.delete() || !file2.renameTo(file)) { - FileInputStream fileInputStream = new FileInputStream(file2); - FileOutputStream fileOutputStream2 = new FileOutputStream(file); - byte[] bArr5 = new byte[262144]; - while (true) { - int i11 = fileInputStream.read(bArr5); - if (i11 <= 0) { - fileInputStream.close(); - fileOutputStream2.close(); - file2.delete(); - return; - } - fileOutputStream2.write(bArr5, 0, i11); - } - } - } finally { - fileOutputStream.close(); - } - } catch (Exception e) { - file2.delete(); - throw e; - } - } catch (Throwable th) { - randomAccessFile.close(); - throw th; - } - } -} diff --git a/android/src/com/mulberry/player/Palette.java b/android/src/com/mulberry/player/Palette.java deleted file mode 100644 index eb6072b..0000000 --- a/android/src/com/mulberry/player/Palette.java +++ /dev/null @@ -1,298 +0,0 @@ -package com.mulberry.player; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.Color; -import android.os.Build; - -/* JADX INFO: loaded from: classes.dex */ -public final class Palette { - public boolean dark; - public int error; - public int onPrimary; - public int onPrimaryContainer; - public int onSecondaryContainer; - public int onSurface; - public int onSurfaceVariant; - public int outline; - public int outlineVariant; - public int primary; - public int primaryContainer; - public int secondary; - public int secondaryContainer; - public int seed; - public int surface; - public int surfaceContainer; - public int surfaceHigh; - public int surfaceHighest; - public int surfaceLow; - public int tertiary; - public int tertiaryContainer; - - public static Palette build(Context context, Integer num) { - Palette paletteFromSystem; - boolean z = true; - Prefs prefs = App.I.prefs; - String str = prefs.getStr(Prefs.THEME_MODE, "system"); - if (!"dark".equals(str) && ("light".equals(str) || (context.getResources().getConfiguration().uiMode & 48) != 32)) { - z = false; - } - String str2 = prefs.getStr(Prefs.COLOR_SOURCE, "system"); - if ("album".equals(str2) && num != null) { - return fromSeed(num.intValue(), z); - } - if ("custom".equals(str2)) { - return fromSeed(prefs.getInt(Prefs.CUSTOM_COLOR, -6651951), z); - } - return (Build.VERSION.SDK_INT < 31 || (paletteFromSystem = fromSystem(context, z)) == null) ? fromSeed(-6651951, z) : paletteFromSystem; - } - - private static int sys(Context context, String str) { - int identifier = context.getResources().getIdentifier(str, "color", "android"); - if (identifier == 0) { - throw new IllegalStateException(str); - } - return context.getColor(identifier); - } - - static Palette fromSystem(Context context, boolean z) { - try { - Palette palette = new Palette(); - palette.dark = z; - if (z) { - palette.primary = sys(context, "system_accent1_200"); - palette.onPrimary = sys(context, "system_accent1_800"); - palette.primaryContainer = sys(context, "system_accent1_700"); - palette.onPrimaryContainer = sys(context, "system_accent1_100"); - palette.secondary = sys(context, "system_accent2_200"); - palette.secondaryContainer = sys(context, "system_accent2_700"); - palette.onSecondaryContainer = sys(context, "system_accent2_100"); - palette.tertiary = sys(context, "system_accent3_200"); - palette.tertiaryContainer = sys(context, "system_accent3_700"); - palette.surface = sys(context, "system_neutral1_900"); - palette.surfaceLow = mixC(sys(context, "system_neutral1_900"), sys(context, "system_neutral1_800"), 0.4f); - palette.surfaceContainer = mixC(sys(context, "system_neutral1_900"), sys(context, "system_neutral1_800"), 0.75f); - palette.surfaceHigh = sys(context, "system_neutral1_800"); - palette.surfaceHighest = mixC(sys(context, "system_neutral1_800"), sys(context, "system_neutral1_700"), 0.5f); - palette.onSurface = sys(context, "system_neutral1_100"); - palette.onSurfaceVariant = sys(context, "system_neutral2_200"); - palette.outline = sys(context, "system_neutral2_400"); - palette.outlineVariant = sys(context, "system_neutral2_700"); - palette.error = -870219; - } else { - palette.primary = sys(context, "system_accent1_600"); - palette.onPrimary = sys(context, "system_accent1_0"); - palette.primaryContainer = sys(context, "system_accent1_100"); - palette.onPrimaryContainer = sys(context, "system_accent1_900"); - palette.secondary = sys(context, "system_accent2_600"); - palette.secondaryContainer = sys(context, "system_accent2_100"); - palette.onSecondaryContainer = sys(context, "system_accent2_900"); - palette.tertiary = sys(context, "system_accent3_600"); - palette.tertiaryContainer = sys(context, "system_accent3_100"); - palette.surface = sys(context, "system_neutral1_10"); - palette.surfaceLow = sys(context, "system_neutral1_50"); - palette.surfaceContainer = mixC(sys(context, "system_neutral1_50"), sys(context, "system_neutral1_100"), 0.5f); - palette.surfaceHigh = sys(context, "system_neutral1_100"); - palette.surfaceHighest = mixC(sys(context, "system_neutral1_100"), sys(context, "system_neutral1_200"), 0.5f); - palette.onSurface = sys(context, "system_neutral1_900"); - palette.onSurfaceVariant = sys(context, "system_neutral2_700"); - palette.outline = sys(context, "system_neutral2_500"); - palette.outlineVariant = sys(context, "system_neutral2_200"); - palette.error = -5036514; - } - palette.seed = palette.primary; - return palette; - } catch (Exception e) { - return null; - } - } - - public static Palette fromSeed(int i, boolean z) { - double[] dArrRgbToOklch = rgbToOklch(i); - double d = dArrRgbToOklch[2]; - Tonal tonal = new Tonal(d, Math.min(Math.max(dArrRgbToOklch[1], 0.085d), 0.15d)); - Tonal tonal2 = new Tonal(d, 0.04d); - Tonal tonal3 = new Tonal((60.0d + d) % 360.0d, 0.075d); - Tonal tonal4 = new Tonal(d, 0.014d); - Tonal tonal5 = new Tonal(d, 0.025d); - Palette palette = new Palette(); - palette.dark = z; - palette.seed = i; - if (z) { - palette.primary = tonal.t(80.0d); - palette.onPrimary = tonal.t(20.0d); - palette.primaryContainer = tonal.t(30.0d); - palette.onPrimaryContainer = tonal.t(90.0d); - palette.secondary = tonal2.t(80.0d); - palette.secondaryContainer = tonal2.t(30.0d); - palette.onSecondaryContainer = tonal2.t(90.0d); - palette.tertiary = tonal3.t(80.0d); - palette.tertiaryContainer = tonal3.t(30.0d); - palette.surface = tonal4.t(6.0d); - palette.surfaceLow = tonal4.t(10.0d); - palette.surfaceContainer = tonal4.t(12.0d); - palette.surfaceHigh = tonal4.t(17.0d); - palette.surfaceHighest = tonal4.t(22.0d); - palette.onSurface = tonal4.t(90.0d); - palette.onSurfaceVariant = tonal5.t(80.0d); - palette.outline = tonal5.t(60.0d); - palette.outlineVariant = tonal5.t(30.0d); - palette.error = -870219; - } else { - palette.primary = tonal.t(40.0d); - palette.onPrimary = tonal.t(100.0d); - palette.primaryContainer = tonal.t(90.0d); - palette.onPrimaryContainer = tonal.t(10.0d); - palette.secondary = tonal2.t(40.0d); - palette.secondaryContainer = tonal2.t(90.0d); - palette.onSecondaryContainer = tonal2.t(10.0d); - palette.tertiary = tonal3.t(40.0d); - palette.tertiaryContainer = tonal3.t(90.0d); - palette.surface = tonal4.t(98.0d); - palette.surfaceLow = tonal4.t(96.0d); - palette.surfaceContainer = tonal4.t(94.0d); - palette.surfaceHigh = tonal4.t(92.0d); - palette.surfaceHighest = tonal4.t(90.0d); - palette.onSurface = tonal4.t(10.0d); - palette.onSurfaceVariant = tonal5.t(30.0d); - palette.outline = tonal5.t(50.0d); - palette.outlineVariant = tonal5.t(80.0d); - palette.error = -5036514; - } - return palette; - } - - public static int alpha(int i, float f) { - return (Math.round(Math.max(0.0f, Math.min(1.0f, f)) * 255.0f) << 24) | (16777215 & i); - } - - public static int mixC(int i, int i2, float f) { - int iRed = Color.red(i); - int iGreen = Color.green(i); - int iBlue = Color.blue(i); - int iAlpha = Color.alpha(i); - return Color.argb(Math.round(((Color.alpha(i2) - iAlpha) * f) + iAlpha), Math.round(((Color.red(i2) - iRed) * f) + iRed), Math.round(((Color.green(i2) - iGreen) * f) + iGreen), Math.round(((Color.blue(i2) - iBlue) * f) + iBlue)); - } - - public static Integer dominant(Bitmap bitmap) { - if (bitmap == null) { - return null; - } - Bitmap bitmapCreateScaledBitmap = Bitmap.createScaledBitmap(bitmap, 32, 32, true); - double[] dArr = new double[24]; - double[] dArr2 = new double[24]; - double[] dArr3 = new double[24]; - double[] dArr4 = new double[24]; - int i = 0; - while (true) { - int i2 = i; - if (i2 >= 32) { - break; - } - for (int i3 = 0; i3 < 32; i3++) { - double[] dArrRgbToOklch = rgbToOklch(bitmapCreateScaledBitmap.getPixel(i3, i2)); - if (dArrRgbToOklch[1] >= 0.03d && dArrRgbToOklch[0] >= 0.2d && dArrRgbToOklch[0] <= 0.95d) { - int i4 = ((int) (dArrRgbToOklch[2] / 15.0d)) % 24; - double d = dArrRgbToOklch[1] * dArrRgbToOklch[1]; - dArr[i4] = dArr[i4] + d; - dArr2[i4] = dArr2[i4] + (Math.cos(Math.toRadians(dArrRgbToOklch[2])) * d); - dArr3[i4] = dArr3[i4] + (Math.sin(Math.toRadians(dArrRgbToOklch[2])) * d); - dArr4[i4] = (d * dArrRgbToOklch[1]) + dArr4[i4]; - } - } - i = i2 + 1; - } - if (bitmapCreateScaledBitmap != bitmap) { - bitmapCreateScaledBitmap.recycle(); - } - int i5 = -1; - int i6 = 0; - while (i6 < 24) { - int i7 = (dArr[i6] <= 0.0d || (i5 >= 0 && dArr[i6] <= dArr[i5])) ? i5 : i6; - i6++; - i5 = i7; - } - if (i5 < 0) { - return null; - } - return Integer.valueOf(oklchToRgb(0.65d, Math.max(dArr4[i5] / dArr[i5], 0.1d), (Math.toDegrees(Math.atan2(dArr3[i5], dArr2[i5])) + 360.0d) % 360.0d)); - } - - static final class Tonal { - final double c; - final double h; - - Tonal(double d, double d2) { - this.h = d; - this.c = d2; - } - - int t(double d) { - return Palette.oklchToRgb(Palette.toneToL(d), this.c, this.h); - } - } - - static double toneToL(double d) { - return d <= 8.0d ? Math.cbrt(d / 903.2963d) : (16.0d + d) / 116.0d; - } - - static double lin(double d) { - return d <= 0.04045d ? d / 12.92d : Math.pow((0.055d + d) / 1.055d, 2.4d); - } - - static double delin(double d) { - return d <= 0.0031308d ? 12.92d * d : (1.055d * Math.pow(d, 0.4166666666666667d)) - 0.055d; - } - - public static double[] rgbToOklch(int i) { - double dLin = lin(((double) Color.red(i)) / 255.0d); - double dLin2 = lin(((double) Color.green(i)) / 255.0d); - double dLin3 = lin(((double) Color.blue(i)) / 255.0d); - double dCbrt = Math.cbrt((0.4122214708d * dLin) + (0.5363325363d * dLin2) + (0.0514459929d * dLin3)); - double dCbrt2 = Math.cbrt((0.2119034982d * dLin) + (0.6806995451d * dLin2) + (0.1073969566d * dLin3)); - double dCbrt3 = Math.cbrt((dLin * 0.0883024619d) + (dLin2 * 0.2817188376d) + (0.6299787005d * dLin3)); - double d = ((0.2104542553d * dCbrt) + (0.793617785d * dCbrt2)) - (0.0040720468d * dCbrt3); - double d2 = ((1.9779984951d * dCbrt) - (2.428592205d * dCbrt2)) + (0.4505937099d * dCbrt3); - double d3 = ((dCbrt * 0.0259040371d) + (dCbrt2 * 0.7827717662d)) - (dCbrt3 * 0.808675766d); - return new double[]{d, Math.hypot(d2, d3), (Math.toDegrees(Math.atan2(d3, d2)) + 360.0d) % 360.0d}; - } - - static double[] toLin(double d, double d2, double d3) { - double dCos = Math.cos(Math.toRadians(d3)) * d2; - double dSin = Math.sin(Math.toRadians(d3)) * d2; - double dPow = Math.pow((0.3963377774d * dCos) + d + (0.2158037573d * dSin), 3.0d); - double dPow2 = Math.pow((d - (0.1055613458d * dCos)) - (0.0638541728d * dSin), 3.0d); - double dPow3 = Math.pow((d - (dCos * 0.0894841775d)) - (dSin * 1.291485548d), 3.0d); - return new double[]{((4.0767416621d * dPow) - (3.3077115913d * dPow2)) + (0.2309699292d * dPow3), (((-1.2684380046d) * dPow) + (2.6097574011d * dPow2)) - (0.3413193965d * dPow3), (dPow3 * 1.707614701d) + ((dPow * (-0.0041960863d)) - (dPow2 * 0.7034186147d))}; - } - - static boolean inGamut(double[] dArr) { - return dArr[0] >= -1.0E-4d && dArr[0] <= 1.0001d && dArr[1] >= -1.0E-4d && dArr[1] <= 1.0001d && dArr[2] >= -1.0E-4d && dArr[2] <= 1.0001d; - } - - public static int oklchToRgb(double d, double d2, double d3) { - double d4; - double d5; - double[] lin = toLin(d, d2, d3); - if (!inGamut(lin)) { - double d6 = 0.0d; - int i = 0; - double d7 = d2; - while (i < 18) { - double d8 = (d6 + d7) / 2.0d; - if (inGamut(toLin(d, d8, d3))) { - d4 = d7; - d5 = d8; - } else { - d4 = d8; - d5 = d6; - } - i++; - d7 = d4; - d6 = d5; - } - lin = toLin(d, d6, d3); - } - return Color.rgb(Math.max(0, Math.min(255, (int) Math.round(delin(Math.max(0.0d, Math.min(1.0d, lin[0]))) * 255.0d))), Math.max(0, Math.min(255, (int) Math.round(delin(Math.max(0.0d, Math.min(1.0d, lin[1]))) * 255.0d))), Math.max(0, Math.min(255, (int) Math.round(delin(Math.max(0.0d, Math.min(1.0d, lin[2]))) * 255.0d)))); - } -} diff --git a/android/src/com/mulberry/player/PlayButton.java b/android/src/com/mulberry/player/PlayButton.java deleted file mode 100644 index fe83d09..0000000 --- a/android/src/com/mulberry/player/PlayButton.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.mulberry.player; - -import android.content.Context; -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.RectF; -import android.graphics.drawable.Drawable; -import android.view.MotionEvent; -import android.view.View; - -/* JADX INFO: loaded from: classes.dex */ -public class PlayButton extends View implements Ticker.Client { - private float iconT; - private float morph; - private final Paint p; - private final Drawable pause; - private final Drawable play; - private boolean playing; - private float press; - private boolean pressed; - private final RectF r; - private boolean ticking; - public boolean tonal; - - public PlayButton(Context context) { - super(context); - this.p = new Paint(1); - this.r = new RectF(); - this.play = context.getDrawable(R.drawable.ic_play_arrow_fill).mutate(); - this.pause = context.getDrawable(R.drawable.ic_pause_fill).mutate(); - setClickable(true); - setContentDescription("Play or pause"); - } - - public void setPlaying(boolean z) { - if (z != this.playing) { - this.playing = z; - if (!App.lowPower() && isShown()) { - start(); - return; - } - this.morph = z ? 1.0f : 0.0f; - this.iconT = this.morph; - invalidate(); - } - } - - void start() { - if (this.ticking) { - return; - } - this.ticking = true; - Ticker.add(this); - } - - @Override // com.mulberry.player.Ticker.Client - public void frame(float f, long j) { - float f2 = this.playing ? 1.0f : 0.0f; - float f3 = this.pressed ? 1.0f : 0.0f; - this.morph += (f2 - this.morph) * Math.min(1.0f, 10.0f * f); - this.iconT += (f2 - this.iconT) * Math.min(1.0f, 14.0f * f); - this.press = (Math.min(1.0f, 18.0f * f) * (f3 - this.press)) + this.press; - invalidate(); - if (Math.abs(f2 - this.morph) < 0.002f && Math.abs(f2 - this.iconT) < 0.002f && Math.abs(f3 - this.press) < 0.002f) { - this.morph = f2; - this.iconT = f2; - this.press = f3; - Ticker.remove(this); - this.ticking = false; - } - } - - @Override // android.view.View - protected void onDetachedFromWindow() { - super.onDetachedFromWindow(); - if (this.ticking) { - Ticker.remove(this); - this.ticking = false; - } - } - - @Override // android.view.View - public boolean onTouchEvent(MotionEvent motionEvent) { - int actionMasked = motionEvent.getActionMasked(); - if (actionMasked == 0) { - this.pressed = true; - start(); - } else if (actionMasked == 1 || actionMasked == 3) { - this.pressed = false; - start(); - } - return super.onTouchEvent(motionEvent); - } - - @Override // android.view.View - protected void onDraw(Canvas canvas) { - Palette palette = App.I.palette; - float width = getWidth(); - float height = getHeight(); - float f = 1.0f - (0.08f * this.press); - float f2 = width * f * (1.0f - (0.12f * this.morph)); - float f3 = height * f; - this.r.set((width - f2) / 2.0f, (height - f3) / 2.0f, (f2 + width) / 2.0f, (height + f3) / 2.0f); - float f4 = f3 / 2.0f; - float f5 = (((f3 * 0.3f) - f4) * this.morph) + f4; - this.p.setColor(this.tonal ? palette.secondaryContainer : palette.primary); - canvas.drawRoundRect(this.r, f5, f5, this.p); - int i = this.tonal ? palette.onSecondaryContainer : palette.onPrimary; - int i2 = (int) (0.52f * f3); - int i3 = (int) ((width / 2.0f) - (i2 / 2.0f)); - int i4 = (int) ((height / 2.0f) - (i2 / 2.0f)); - canvas.save(); - canvas.rotate(((-90.0f) * (1.0f - Math.abs((this.iconT * 2.0f) - 1.0f)) * 0.0f) + 0.0f, width / 2.0f, height / 2.0f); - this.pause.setTint(i); - this.play.setTint(i); - this.pause.setAlpha((int) (255.0f * this.iconT)); - this.play.setAlpha((int) (255.0f * (1.0f - this.iconT))); - float f6 = (this.iconT * 0.3f) + 0.7f; - float f7 = ((1.0f - this.iconT) * 0.3f) + 0.7f; - canvas.save(); - canvas.scale(f7, f7, width / 2.0f, height / 2.0f); - this.play.setBounds(i3, i4, i3 + i2, i4 + i2); - this.play.draw(canvas); - canvas.restore(); - canvas.save(); - canvas.scale(f6, f6, width / 2.0f, height / 2.0f); - this.pause.setBounds(i3, i4, i3 + i2, i2 + i4); - this.pause.draw(canvas); - canvas.restore(); - canvas.restore(); - } -} diff --git a/android/src/com/mulberry/player/PlayStats.java b/android/src/com/mulberry/player/PlayStats.java deleted file mode 100644 index 1c58480..0000000 --- a/android/src/com/mulberry/player/PlayStats.java +++ /dev/null @@ -1,230 +0,0 @@ -package com.mulberry.player; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.json.JSONArray; -import org.json.JSONObject; - -/* JADX INFO: loaded from: classes.dex */ -public final class PlayStats { - private static boolean dirty; - private static boolean loaded; - private static final Map COUNTS = new HashMap(); - private static final Map LAST = new HashMap(); - private static final Set FAVS = new HashSet(); - private static final Runnable SAVE = new Runnable() { // from class: com.mulberry.player.PlayStats.1 - @Override // java.lang.Runnable - public void run() { - App.IO.execute(new Runnable() { // from class: com.mulberry.player.PlayStats.1.1 - @Override // java.lang.Runnable - public void run() { - PlayStats.save(); - } - }); - } - }; - - private PlayStats() { - } - - static File file() { - return new File(App.I.getFilesDir(), "stats.json"); - } - - static synchronized void ensure() { - synchronized (PlayStats.class) { - if (!loaded) { - loaded = true; - try { - File file = file(); - if (file.exists()) { - FileInputStream fileInputStream = new FileInputStream(file); - JSONObject jSONObject = new JSONObject(new String(Net.readAll(fileInputStream), "UTF-8")); - fileInputStream.close(); - JSONObject jSONObjectOptJSONObject = jSONObject.optJSONObject("c"); - if (jSONObjectOptJSONObject != null) { - JSONArray jSONArrayNames = jSONObjectOptJSONObject.names(); - for (int i = 0; jSONArrayNames != null && i < jSONArrayNames.length(); i++) { - String string = jSONArrayNames.getString(i); - COUNTS.put(string, new int[]{jSONObjectOptJSONObject.optInt(string)}); - } - } - JSONObject jSONObjectOptJSONObject2 = jSONObject.optJSONObject("l"); - if (jSONObjectOptJSONObject2 != null) { - JSONArray jSONArrayNames2 = jSONObjectOptJSONObject2.names(); - for (int i2 = 0; jSONArrayNames2 != null && i2 < jSONArrayNames2.length(); i2++) { - String string2 = jSONArrayNames2.getString(i2); - LAST.put(string2, Long.valueOf(jSONObjectOptJSONObject2.optLong(string2))); - } - } - JSONArray jSONArrayOptJSONArray = jSONObject.optJSONArray("f"); - for (int i3 = 0; jSONArrayOptJSONArray != null && i3 < jSONArrayOptJSONArray.length(); i3++) { - FAVS.add(jSONArrayOptJSONArray.getString(i3)); - } - } - } catch (Exception e) { - } - } - } - } - - public static synchronized void played(Song song) { - ensure(); - String strKey = song.key(); - int[] iArr = COUNTS.get(strKey); - if (iArr == null) { - COUNTS.put(strKey, new int[]{1}); - } else { - iArr[0] = iArr[0] + 1; - } - LAST.put(strKey, Long.valueOf(System.currentTimeMillis())); - dirty = true; - saveLater(); - } - - public static synchronized int count(Song song) { - int[] iArr; - ensure(); - iArr = COUNTS.get(song.key()); - return iArr == null ? 0 : iArr[0]; - } - - public static synchronized boolean fav(Song song) { - ensure(); - return FAVS.contains(song.key()); - } - - public static synchronized void setFav(Song song, boolean z) { - ensure(); - if (z) { - FAVS.add(song.key()); - } else { - FAVS.remove(song.key()); - } - dirty = true; - saveLater(); - } - - private static void saveLater() { - App.MAIN.removeCallbacks(SAVE); - App.MAIN.postDelayed(SAVE, 3000L); - } - - public static synchronized void save() { - if (dirty) { - try { - JSONObject jSONObject = new JSONObject(); - JSONObject jSONObject2 = new JSONObject(); - for (Map.Entry entry : COUNTS.entrySet()) { - jSONObject2.put(entry.getKey(), entry.getValue()[0]); - } - JSONObject jSONObject3 = new JSONObject(); - for (Map.Entry entry2 : LAST.entrySet()) { - jSONObject3.put(entry2.getKey(), entry2.getValue()); - } - JSONArray jSONArray = new JSONArray(); - Iterator it = FAVS.iterator(); - while (it.hasNext()) { - jSONArray.put(it.next()); - } - jSONObject.put("c", jSONObject2); - jSONObject.put("l", jSONObject3); - jSONObject.put("f", jSONArray); - File file = new File(file().getPath() + ".tmp"); - FileOutputStream fileOutputStream = new FileOutputStream(file); - fileOutputStream.write(jSONObject.toString().getBytes("UTF-8")); - fileOutputStream.close(); - file.renameTo(file()); - dirty = false; - } catch (Exception e) { - } - } - } - - public static List mostPlayed(List list, int i) { - ensure(); - ArrayList arrayList = new ArrayList(); - synchronized (PlayStats.class) { - for (Song song : list) { - if (COUNTS.containsKey(song.key())) { - arrayList.add(song); - } - } - } - Collections.sort(arrayList, new Comparator() { // from class: com.mulberry.player.PlayStats.2 - @Override // java.util.Comparator - public int compare(Song song2, Song song3) { - return PlayStats.count(song3) - PlayStats.count(song2); - } - }); - return arrayList.size() > i ? new ArrayList(arrayList.subList(0, i)) : arrayList; - } - - public static List recentlyPlayed(List list, int i) { - final HashMap map; - ensure(); - synchronized (PlayStats.class) { - map = new HashMap(LAST); - } - ArrayList arrayList = new ArrayList(); - for (Song song : list) { - if (map.containsKey(song.key())) { - arrayList.add(song); - } - } - Collections.sort(arrayList, new Comparator() { // from class: com.mulberry.player.PlayStats.3 - @Override // java.util.Comparator - public int compare(Song song2, Song song3) { - return Long.compare(((Long) map.get(song3.key())).longValue(), ((Long) map.get(song2.key())).longValue()); - } - }); - return arrayList.size() > i ? new ArrayList(arrayList.subList(0, i)) : arrayList; - } - - public static List recentlyAdded(List list, int i) { - ArrayList arrayList = new ArrayList(list); - Collections.sort(arrayList, new Comparator() { // from class: com.mulberry.player.PlayStats.4 - @Override // java.util.Comparator - public int compare(Song song, Song song2) { - return Long.compare(song2.dateAdded, song.dateAdded); - } - }); - return arrayList.size() > i ? new ArrayList(arrayList.subList(0, i)) : arrayList; - } - - public static List favourites(List list) { - ensure(); - ArrayList arrayList = new ArrayList(); - synchronized (PlayStats.class) { - for (Song song : list) { - if (FAVS.contains(song.key())) { - arrayList.add(song); - } - } - } - return arrayList; - } - - public static List neverPlayed(List list) { - ensure(); - ArrayList arrayList = new ArrayList(); - synchronized (PlayStats.class) { - for (Song song : list) { - if (!COUNTS.containsKey(song.key())) { - arrayList.add(song); - } - } - } - return arrayList; - } -} diff --git a/android/src/com/mulberry/player/Playlists.java b/android/src/com/mulberry/player/Playlists.java deleted file mode 100644 index 8386dbf..0000000 --- a/android/src/com/mulberry/player/Playlists.java +++ /dev/null @@ -1,534 +0,0 @@ -package com.mulberry.player; - -import android.content.ContentResolver; -import android.content.Context; -import android.database.Cursor; -import android.net.Uri; -import android.provider.DocumentsContract; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.concurrent.CopyOnWriteArrayList; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; -import org.jaudiotagger.tag.id3.valuepair.TextEncoding; -import org.jaudiotagger.tag.mp4.atom.Mp4NameBox; -import org.json.JSONArray; -import org.json.JSONObject; - -/* JADX INFO: loaded from: classes.dex */ -public final class Playlists { - private static final List ALL = new ArrayList(); - private static final CopyOnWriteArrayList LISTENERS = new CopyOnWriteArrayList<>(); - private static final Object SAVE_LOCK = new Object(); - private static boolean loaded; - - public interface Listener { - void onPlaylistsChanged(); - } - - public static final class Parsed { - public int missing; - public String name = "Imported"; - public final List songs = new ArrayList(); - } - - public static final class PL { - public String name; - public final List songs = new ArrayList(); - - PL(String str) { - this.name = str; - } - } - - private Playlists() { - } - - public static void addListener(Listener listener) { - LISTENERS.add(listener); - } - - public static void removeListener(Listener listener) { - LISTENERS.remove(listener); - } - - static File file() { - return new File(App.I.getFilesDir(), "playlists.json"); - } - - public static synchronized List all() { - ensure(); - return new ArrayList(ALL); - } - - public static synchronized PL get(String str) { - PL next; - ensure(); - Iterator it = ALL.iterator(); - while (it.hasNext()) { - next = it.next(); - if (next.name.equals(str)) { - } - } - next = null; - return next; - } - - static synchronized void ensure() { - if (!loaded) { - loaded = true; - try { - File file = file(); - if (file.exists()) { - FileInputStream fileInputStream = new FileInputStream(file); - JSONArray jSONArray = new JSONArray(new String(Net.readAll(fileInputStream), "UTF-8")); - fileInputStream.close(); - for (int i = 0; i < jSONArray.length(); i++) { - JSONObject jSONObject = jSONArray.getJSONObject(i); - PL pl = new PL(jSONObject.optString(Mp4NameBox.IDENTIFIER, "Playlist")); - JSONArray jSONArrayOptJSONArray = jSONObject.optJSONArray("songs"); - for (int i2 = 0; jSONArrayOptJSONArray != null && i2 < jSONArrayOptJSONArray.length(); i2++) { - pl.songs.add(relink(Song.fromJson(jSONArrayOptJSONArray.getJSONObject(i2)))); - } - ALL.add(pl); - } - } - } catch (Exception e) { - } - } - } - - static Song relink(Song song) { - Song songById; - Library library = App.I.library; - if (library != null && !song.isStream()) { - Song songByPath = song.path.length() > 0 ? library.byPath(song.path) : null; - if (songByPath == null && song.id >= 0 && (songById = library.byId(song.id)) != null && (song.path.length() == 0 || songById.path.equals(song.path))) { - songByPath = songById; - } - return songByPath != null ? songByPath : song; - } - return song; - } - - public static synchronized void save() { - try { - JSONArray jSONArray = new JSONArray(); - for (PL pl : ALL) { - JSONObject jSONObject = new JSONObject(); - jSONObject.put(Mp4NameBox.IDENTIFIER, pl.name); - JSONArray jSONArray2 = new JSONArray(); - Iterator it = pl.songs.iterator(); - while (it.hasNext()) { - jSONArray2.put(it.next().toJson()); - } - jSONObject.put("songs", jSONArray2); - jSONArray.put(jSONObject); - } - final String string = jSONArray.toString(); - App.IO.execute(new Runnable() { // from class: com.mulberry.player.Playlists.1 - @Override // java.lang.Runnable - public void run() { - synchronized (Playlists.SAVE_LOCK) { - try { - File file = new File(Playlists.file().getPath() + ".tmp"); - FileOutputStream fileOutputStream = new FileOutputStream(file); - fileOutputStream.write(string.getBytes("UTF-8")); - fileOutputStream.close(); - file.renameTo(Playlists.file()); - } catch (Exception e) { - } - } - } - }); - App.ui(new Runnable() { // from class: com.mulberry.player.Playlists.2 - @Override // java.lang.Runnable - public void run() { - Iterator it2 = Playlists.LISTENERS.iterator(); - while (it2.hasNext()) { - ((Listener) it2.next()).onPlaylistsChanged(); - } - } - }); - } catch (Exception e) { - } - } - - public static synchronized String uniqueName(String str) { - String str2; - ensure(); - String strTrim = (str == null || str.trim().length() == 0) ? "Playlist" : str.trim(); - int i = 2; - str2 = strTrim; - while (get(str2) != null) { - str2 = strTrim + " (" + i + ")"; - i++; - } - return str2; - } - - public static synchronized PL create(String str, List list) { - PL pl; - ensure(); - pl = new PL(uniqueName(str)); - if (list != null) { - pl.songs.addAll(list); - } - ALL.add(pl); - save(); - return pl; - } - - public static synchronized PL put(String str, List list) { - PL pl; - ensure(); - pl = get(str); - if (pl == null) { - pl = new PL(str); - ALL.add(pl); - } - pl.songs.clear(); - pl.songs.addAll(list); - save(); - return pl; - } - - public static synchronized void delete(PL pl) { - ALL.remove(pl); - save(); - } - - public static synchronized void rename(PL pl, String str) { - if (str != null) { - if (str.trim().length() != 0 && !str.equals(pl.name)) { - pl.name = uniqueName(str); - save(); - } - } - } - - public static synchronized void add(PL pl, List list) { - pl.songs.addAll(list); - save(); - } - - public static synchronized void removeAt(PL pl, int i) { - if (i >= 0) { - if (i < pl.songs.size()) { - pl.songs.remove(i); - save(); - } - } - } - - public static synchronized void move(PL pl, int i, int i2) { - if (i >= 0) { - if (i < pl.songs.size() && i2 >= 0 && i2 < pl.songs.size()) { - pl.songs.add(i2, pl.songs.remove(i)); - save(); - } - } - } - - /* JADX WARN: Code duplicated, block: B:70:0x0182 */ - public static Parsed parse(String str, String str2, String str3) { - String strTrim; - long jMax; - Parsed parsed = new Parsed(); - if (str2 != null) { - int iLastIndexOf = str2.lastIndexOf(46); - parsed.name = iLastIndexOf > 0 ? str2.substring(0, iLastIndexOf) : str2; - } - if (str.length() > 0 && str.charAt(0) == 65279) { - str = str.substring(1); - } - String[] strArrSplit = str.split("\r\n|\r|\n"); - boolean z = (str2 != null && str2.toLowerCase(Locale.ROOT).endsWith(".pls")) || str.trim().startsWith("[playlist]"); - String str4 = null; - long j = 0; - ArrayList arrayList = new ArrayList(); - int length = strArrSplit.length; - int i = 0; - while (i < length) { - String strTrim2 = strArrSplit[i].trim(); - if (strTrim2.length() == 0) { - jMax = j; - strTrim = str4; - } else if (z) { - int iIndexOf = strTrim2.indexOf(61); - if (iIndexOf < 0) { - jMax = j; - strTrim = str4; - } else { - String lowerCase = strTrim2.substring(0, iIndexOf).trim().toLowerCase(Locale.ROOT); - String strTrim3 = strTrim2.substring(iIndexOf + 1).trim(); - if (lowerCase.startsWith("file")) { - add(parsed, strTrim3, null, 0L, str3); - jMax = j; - strTrim = str4; - } else if (lowerCase.startsWith("title")) { - arrayList.add(new String[]{lowerCase.substring(5), strTrim3}); - jMax = j; - strTrim = str4; - } else { - jMax = j; - strTrim = str4; - } - } - } else if (strTrim2.startsWith("#EXTINF:")) { - String strSubstring = strTrim2.substring(8); - int iIndexOf2 = strSubstring.indexOf(44); - if (iIndexOf2 >= 0) { - try { - jMax = Math.max(0L, Long.parseLong(strSubstring.substring(0, iIndexOf2).trim().split(" ")[0])) * 1000; - } catch (Exception e) { - jMax = 0; - } - strTrim = strSubstring.substring(iIndexOf2 + 1).trim(); - } else { - jMax = j; - strTrim = str4; - } - } else if (strTrim2.startsWith("#PLAYLIST:")) { - parsed.name = strTrim2.substring(10).trim(); - jMax = j; - strTrim = str4; - } else if (strTrim2.startsWith("#")) { - jMax = j; - strTrim = str4; - } else { - add(parsed, strTrim2, str4, j, str3); - strTrim = null; - jMax = 0; - } - i++; - j = jMax; - str4 = strTrim; - } - for (String[] strArr : arrayList) { - try { - int i2 = Integer.parseInt(strArr[0]) - 1; - if (i2 >= 0 && i2 < parsed.songs.size() && parsed.songs.get(i2).title.length() == 0) { - parsed.songs.get(i2).title = strArr[1]; - } - } catch (Exception e2) { - } - } - return parsed; - } - - static void add(Parsed parsed, String str, String str2, long j, String str3) { - if (str.startsWith("http://") || str.startsWith("https://")) { - Song song = new Song(); - song.uri = str; - song.title = str2 != null ? splitTitle(str2)[1] : FrameBodyCOMM.DEFAULT; - song.artist = str2 != null ? splitTitle(str2)[0] : FrameBodyCOMM.DEFAULT; - song.duration = j; - parsed.songs.add(song); - return; - } - if (str.startsWith("file://")) { - str = Uri.decode(str.substring(7)); - } - String strReplace = str.replace('\\', '/'); - String strNormalize = (strReplace.startsWith("/") || strReplace.matches("^[A-Za-z]:/.*") || str3 == null) ? strReplace : normalize(str3 + "/" + strReplace); - Library library = App.I.library; - Song songByPath = library == null ? null : library.byPath(strNormalize); - if (songByPath == null && library != null) { - songByPath = library.matchPath(strNormalize); - } - Song songMatchPath = (songByPath != null || library == null || strNormalize.equals(strReplace)) ? songByPath : library.matchPath(strReplace); - if (songMatchPath == null) { - File file = new File(strNormalize); - if (strNormalize.startsWith("/") && file.exists()) { - Song song2 = new Song(); - song2.uri = Uri.fromFile(file).toString(); - song2.path = strNormalize; - String[] strArrSplitTitle = str2 != null ? splitTitle(str2) : new String[]{FrameBodyCOMM.DEFAULT, FrameBodyCOMM.DEFAULT}; - song2.artist = strArrSplitTitle[0]; - song2.title = strArrSplitTitle[1]; - song2.duration = j; - parsed.songs.add(song2); - return; - } - parsed.missing++; - return; - } - parsed.songs.add(songMatchPath); - } - - static String[] splitTitle(String str) { - int iIndexOf = str.indexOf(" - "); - return iIndexOf > 0 ? new String[]{str.substring(0, iIndexOf).trim(), str.substring(iIndexOf + 3).trim()} : new String[]{FrameBodyCOMM.DEFAULT, str}; - } - - public static String normalize(String str) { - String[] strArrSplit = str.split("/"); - ArrayList arrayList = new ArrayList(); - for (String str2 : strArrSplit) { - if (str2.length() != 0 && !str2.equals(".")) { - if (!str2.equals("..")) { - arrayList.add(str2); - } else if (!arrayList.isEmpty()) { - arrayList.remove(arrayList.size() - 1); - } - } - } - StringBuilder sb = new StringBuilder(); - Iterator it = arrayList.iterator(); - while (it.hasNext()) { - sb.append('/').append((String) it.next()); - } - return sb.length() == 0 ? "/" : sb.toString(); - } - - public static String displayName(Context context, Uri uri) { - String strSubstring = null; - try { - Cursor cursorQuery = context.getContentResolver().query(uri, new String[]{"_display_name"}, null, null, null); - if (cursorQuery != null) { - try { - strSubstring = cursorQuery.moveToFirst() ? cursorQuery.getString(0) : null; - } finally { - cursorQuery.close(); - } - } - } catch (Exception e2) { - } - if (strSubstring == null) { - strSubstring = uri.getLastPathSegment(); - } - if (strSubstring != null && strSubstring.contains("/")) { - strSubstring = strSubstring.substring(strSubstring.lastIndexOf(47) + 1); - } - return strSubstring == null ? "Imported.m3u8" : strSubstring; - } - - static String guessDir(Uri uri) { - try { - if ("file".equals(uri.getScheme())) { - return new File(uri.getPath()).getParent(); - } - String documentId = DocumentsContract.getDocumentId(uri); - int iIndexOf = documentId.indexOf(58); - if (iIndexOf > 0) { - String strSubstring = documentId.substring(0, iIndexOf); - String strSubstring2 = documentId.substring(iIndexOf + 1); - return strSubstring2.startsWith("/") ? new File(strSubstring2).getParent() : new File(("primary".equals(strSubstring) ? "/storage/emulated/0" : "/storage/" + strSubstring) + "/" + strSubstring2).getParent(); - } - return null; - } catch (Exception e) { - return null; - } - } - - public static Parsed importUri(Context context, Uri uri) throws Exception { - InputStream inputStreamOpenInputStream = context.getContentResolver().openInputStream(uri); - if (inputStreamOpenInputStream == null) { - throw new Exception("could not open file"); - } - byte[] all = Net.readAll(inputStreamOpenInputStream); - inputStreamOpenInputStream.close(); - String strDisplayName = displayName(context, uri); - return parse(decode(all, strDisplayName), strDisplayName, guessDir(uri)); - } - - static String decode(byte[] bArr, String str) throws Exception { - String str2 = new String(bArr, "UTF-8"); - return (str.toLowerCase(Locale.ROOT).endsWith(".m3u") && str2.contains("�")) ? new String(bArr, TextEncoding.CHARSET_ISO_8859_1) : str2; - } - - public static String render(PL pl, String str) { - StringBuilder sb = new StringBuilder(); - if ("pls".equals(str)) { - sb.append("[playlist]\n"); - int i = 0; - for (Song song : pl.songs) { - i++; - sb.append("File").append(i).append('=').append(entry(song)).append('\n'); - sb.append("Title").append(i).append('=').append(label(song)).append('\n'); - sb.append("Length").append(i).append('=').append(song.duration > 0 ? song.duration / 1000 : -1L).append('\n'); - } - sb.append("NumberOfEntries=").append(i).append("\nVersion=2\n"); - return sb.toString(); - } - sb.append("#EXTM3U\n#PLAYLIST:").append(pl.name).append('\n'); - for (Song song2 : pl.songs) { - sb.append("#EXTINF:").append(song2.duration > 0 ? song2.duration / 1000 : -1L).append(',').append(label(song2)).append('\n'); - sb.append(entry(song2)).append('\n'); - } - return sb.toString(); - } - - static String label(Song song) { - String strDisplayArtist = song.displayArtist(); - return strDisplayArtist.length() > 0 ? strDisplayArtist + " - " + song.displayTitle() : song.displayTitle(); - } - - static String entry(Song song) { - if (song.isStream()) { - return song.uri; - } - return (song.path == null || song.path.length() <= 0) ? song.uri : song.path; - } - - public static byte[] bytes(PL pl, String str) throws Exception { - String strRender = render(pl, str); - return "m3u".equals(str) ? strRender.getBytes(TextEncoding.CHARSET_ISO_8859_1) : strRender.getBytes("UTF-8"); - } - - public static void writeTo(Context context, Uri uri, PL pl, String str) throws Exception { - OutputStream outputStreamOpenOutputStream = context.getContentResolver().openOutputStream(uri, "wt"); - if (outputStreamOpenOutputStream == null) { - throw new Exception("could not write file"); - } - outputStreamOpenOutputStream.write(bytes(pl, str)); - outputStreamOpenOutputStream.close(); - } - - public static String safeName(String str) { - String strTrim = str.replaceAll("[\\\\/:*?\"<>|]", "_").trim(); - return strTrim.length() == 0 ? "Playlist" : strTrim; - } - - public static int exportAll(Context context, Uri uri, String str, boolean z) throws Exception { - Uri uriBuildDocumentUriUsingTree; - ContentResolver contentResolver = context.getContentResolver(); - Uri uriBuildDocumentUriUsingTree2 = DocumentsContract.buildDocumentUriUsingTree(uri, DocumentsContract.getTreeDocumentId(uri)); - Uri uriBuildChildDocumentsUriUsingTree = DocumentsContract.buildChildDocumentsUriUsingTree(uri, DocumentsContract.getTreeDocumentId(uri)); - HashMap map = new HashMap(); - Cursor cursorQuery = contentResolver.query(uriBuildChildDocumentsUriUsingTree, new String[]{"document_id", "_display_name"}, null, null, null); - if (cursorQuery != null) { - while (cursorQuery.moveToNext()) { - map.put(cursorQuery.getString(1), cursorQuery.getString(0)); - } - cursorQuery.close(); - } - String str2 = "pls".equals(str) ? "audio/x-scpls" : "audio/x-mpegurl"; - int i = 0; - for (PL pl : all()) { - String str3 = safeName(pl.name) + "." + str; - if (map.containsKey(str3)) { - if (z) { - uriBuildDocumentUriUsingTree = DocumentsContract.buildDocumentUriUsingTree(uri, (String) map.get(str3)); - writeTo(context, uriBuildDocumentUriUsingTree, pl, str); - i++; - } - } else { - uriBuildDocumentUriUsingTree = DocumentsContract.createDocument(contentResolver, uriBuildDocumentUriUsingTree2, str2, str3); - if (uriBuildDocumentUriUsingTree != null) { - writeTo(context, uriBuildDocumentUriUsingTree, pl, str); - i++; - } - } - } - return i; - } -} diff --git a/android/src/com/mulberry/player/Prefs.java b/android/src/com/mulberry/player/Prefs.java deleted file mode 100644 index 917423d..0000000 --- a/android/src/com/mulberry/player/Prefs.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.mulberry.player; - -import android.content.Context; -import android.content.SharedPreferences; - -/* JADX INFO: loaded from: classes.dex */ -public class Prefs { - public static final String BASS_SHAPE = "bass_shape"; - public static final String COLOR_SOURCE = "color_source"; - public static final String CROSSFADE = "crossfade"; - public static final String CUSTOM_COLOR = "custom_color"; - public static final String FADE_PAUSE = "fade_pause"; - public static final String GAPLESS = "gapless"; - public static final String LFM_ENABLED = "lfm_enabled"; - public static final String LFM_SESSION = "lfm_session"; - public static final String LFM_USER = "lfm_user"; - public static final String LB_ENABLED = "lb_enabled"; - public static final String LB_TOKEN = "lb_token"; - public static final String LB_USER = "lb_user"; - public static final String LIB_TAB = "lib_tab"; - public static final String LOW_POWER = "low_power"; - public static final String LYRICS_PLAIN = "lyrics_plain"; - public static final String LYRICS_SOURCE = "lyrics_source"; - public static final String MIN_DURATION = "min_duration"; - public static final String ONLINE_COVERS = "online_covers"; - public static final String ONLINE_LYRICS = "online_lyrics"; - public static final String PAUSE_ON_DETACH = "pause_detach"; - public static final String REPEAT = "repeat"; - public static final String RESUME = "resume"; - public static final String RESUME_ON_CONNECT = "resume_connect"; - public static final String SCROBBLER_APPS = "scrobbler_apps"; - public static final String SHUFFLE = "shuffle"; - public static final String THEME_MODE = "theme_mode"; - public static final String VISUALIZER = "visualizer"; - public static final String WIDGET_ANIM = "widget_anim"; - private final SharedPreferences sp; - - public Prefs(Context context) { - this.sp = context.getSharedPreferences("mulberry", 0); - } - - public boolean contains(String str) { - return this.sp.contains(str); - } - - public boolean getBool(String str, boolean z) { - return this.sp.getBoolean(str, z); - } - - public void setBool(String str, boolean z) { - this.sp.edit().putBoolean(str, z).apply(); - } - - public int getInt(String str, int i) { - return this.sp.getInt(str, i); - } - - public void setInt(String str, int i) { - this.sp.edit().putInt(str, i).apply(); - } - - public long getLong(String str, long j) { - return this.sp.getLong(str, j); - } - - public void setLong(String str, long j) { - this.sp.edit().putLong(str, j).apply(); - } - - public String getStr(String str, String str2) { - return this.sp.getString(str, str2); - } - - public void setStr(String str, String str2) { - this.sp.edit().putString(str, str2).apply(); - } - - public SharedPreferences raw() { - return this.sp; - } -} diff --git a/android/src/com/mulberry/player/ScrobbleBridge.java b/android/src/com/mulberry/player/ScrobbleBridge.java deleted file mode 100644 index fc62400..0000000 --- a/android/src/com/mulberry/player/ScrobbleBridge.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.mulberry.player; - -import android.content.Context; -import android.content.Intent; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; - -/* JADX INFO: loaded from: classes.dex */ -public final class ScrobbleBridge { - public static final int COMPLETE = 3; - public static final int PAUSE = 2; - public static final int RESUME = 1; - public static final String SD_ACTION = "net.jjc1138.android.scrobbler.action.MUSIC_STATUS"; - public static final String SD_PKG = "net.jjc1138.android.scrobbler"; - public static final String SLS_ACTION = "com.adam.aslfms.notify.playstatechanged"; - public static final String SLS_PKG = "com.adam.aslfms"; - public static final int START = 0; - - private ScrobbleBridge() { - } - - public static boolean enabled() { - return App.I.prefs.getBool(Prefs.SCROBBLER_APPS, true); - } - - public static void send(Context context, Song song, int i) { - boolean z = true; - if (song == null || !enabled()) { - return; - } - if (!song.isStream() || song.displayArtist().length() != 0) { - try { - Intent intent = new Intent(SLS_ACTION); - intent.setPackage(SLS_PKG); - intent.putExtra("state", i); - intent.putExtra("app-name", "Mulberry"); - intent.putExtra("app-package", context.getPackageName()); - intent.putExtra("artist", song.displayArtist()); - intent.putExtra("album", song.album == null ? FrameBodyCOMM.DEFAULT : song.album); - intent.putExtra("track", song.displayTitle()); - intent.putExtra("duration", (int) Math.max(1L, song.duration / 1000)); - if (song.track > 0) { - intent.putExtra("track-number", song.track % 1000); - } - context.sendBroadcast(intent); - } catch (Throwable th) { - } - try { - Intent intent2 = new Intent(SD_ACTION); - intent2.setPackage(SD_PKG); - if (i != 0 && i != 1) { - z = false; - } - intent2.putExtra("playing", z); - intent2.putExtra("artist", song.displayArtist()); - intent2.putExtra("track", song.displayTitle()); - intent2.putExtra("album", song.album == null ? FrameBodyCOMM.DEFAULT : song.album); - intent2.putExtra("secs", (int) Math.max(1L, song.duration / 1000)); - context.sendBroadcast(intent2); - } catch (Throwable th2) { - } - } - } - - public static boolean installed(Context context, String str) { - try { - context.getPackageManager().getPackageInfo(str, 0); - return true; - } catch (Throwable th) { - return false; - } - } - - public static String detected(Context context) { - StringBuilder sb = new StringBuilder(); - if (installed(context, "com.arn.scrobble")) { - sb.append("Pano Scrobbler"); - } - if (installed(context, SLS_PKG)) { - sb.append(sb.length() > 0 ? ", " : FrameBodyCOMM.DEFAULT).append("Simple Last.fm Scrobbler"); - } - if (installed(context, SD_PKG)) { - sb.append(sb.length() > 0 ? ", " : FrameBodyCOMM.DEFAULT).append("Scrobble Droid"); - } - return sb.length() == 0 ? "none found" : sb.toString(); - } -} diff --git a/android/src/com/mulberry/player/SettingsPage.java b/android/src/com/mulberry/player/SettingsPage.java deleted file mode 100644 index 0151499..0000000 --- a/android/src/com/mulberry/player/SettingsPage.java +++ /dev/null @@ -1,609 +0,0 @@ -package com.mulberry.player; - -import android.app.AlertDialog; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.res.ColorStateList; -import android.net.Uri; -import android.os.Build; -import android.os.Environment; -import android.os.PowerManager; -import android.view.View; -import android.widget.EditText; -import android.widget.LinearLayout; -import android.widget.ScrollView; -import android.widget.Switch; -import android.widget.TextView; -import java.io.File; -import java.util.Locale; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; - -/* JADX INFO: loaded from: classes.dex */ -public class SettingsPage extends ScrollView { - final MainActivity a; - final LinearLayout box; - final Prefs p; - - public SettingsPage(MainActivity mainActivity) { - super(mainActivity); - this.p = App.I.prefs; - this.a = mainActivity; - setClipToPadding(false); - this.box = Ui.col(mainActivity); - this.box.setPadding(Ui.dp(mainActivity, 12.0f), 0, Ui.dp(mainActivity, 12.0f), Ui.dp(mainActivity, 140.0f)); - addView(this.box); - refresh(); - } - - void setBottomPad(int i) { - this.box.setPadding(this.box.getPaddingLeft(), this.box.getPaddingTop(), this.box.getPaddingRight(), i); - } - - void refresh() { - String str; - boolean zIsExternalStorageManager; - final int scrollY = getScrollY(); - this.box.removeAllViews(); - TextView textViewTitle = Ui.title(this.a, "Settings"); - textViewTitle.setPadding(Ui.dp(this.a, 8.0f), Ui.dp(this.a, 14.0f), 0, Ui.dp(this.a, 6.0f)); - this.box.addView(textViewTitle); - section("Appearance"); - LinearLayout linearLayoutCard = card(); - String str2 = this.p.getStr(Prefs.COLOR_SOURCE, "system"); - String[][] strArr = new String[3][]; - String[] strArr2 = new String[2]; - strArr2[0] = "system"; - strArr2[1] = Build.VERSION.SDK_INT >= 31 ? "Wallpaper (Material You)" : "Default"; - strArr[0] = strArr2; - strArr[1] = new String[]{"album", "From album art"}; - strArr[2] = new String[]{"custom", "Custom colour"}; - choice(linearLayoutCard, R.drawable.ic_palette, "Colours", label(str2, strArr), new Runnable() { // from class: com.mulberry.player.SettingsPage.1 - @Override // java.lang.Runnable - public void run() { - SettingsPage.this.pickColorSource(); - } - }); - if ("custom".equals(str2)) { - choice(linearLayoutCard, R.drawable.ic_tune, "Custom colour", "Tap to change", new Runnable() { // from class: com.mulberry.player.SettingsPage.2 - @Override // java.lang.Runnable - public void run() { - SettingsPage.this.pickCustomColor(); - } - }); - } - choice(linearLayoutCard, R.drawable.ic_visibility, "Theme", label(this.p.getStr(Prefs.THEME_MODE, "system"), new String[][]{new String[]{"system", "Follow system"}, new String[]{"dark", "Dark"}, new String[]{"light", "Light"}}), new Runnable() { // from class: com.mulberry.player.SettingsPage.3 - @Override // java.lang.Runnable - public void run() { - SettingsPage.this.pick("Theme", new String[][]{new String[]{"system", "Follow system"}, new String[]{"dark", "Dark"}, new String[]{"light", "Light"}}, Prefs.THEME_MODE, new Runnable() { // from class: com.mulberry.player.SettingsPage.3.1 - @Override // java.lang.Runnable - public void run() { - SettingsPage.this.repaint(); - } - }); - } - }); - toggle(linearLayoutCard, R.drawable.ic_graphic_eq, "Visualizer", "Spectrum bars around the cover (decoded ahead, no microphone needed)", Prefs.VISUALIZER, true, new Runnable() { // from class: com.mulberry.player.SettingsPage.4 - @Override // java.lang.Runnable - public void run() { - SettingsPage.this.a.updateBassShape(); - } - }); - toggle(linearLayoutCard, R.drawable.ic_auto_awesome, "Floating bass shape", "A shape at the bottom-left that morphs, spins and pulses with the beat", Prefs.BASS_SHAPE, false, new Runnable() { // from class: com.mulberry.player.SettingsPage.5 - @Override // java.lang.Runnable - public void run() { - SettingsPage.this.a.updateBassShape(); - } - }); - choice(linearLayoutCard, R.drawable.ic_auto_awesome, "Widget animation", label(this.p.getStr(Prefs.WIDGET_ANIM, "balanced"), new String[][]{new String[]{"smooth", "Smooth — 30 fps, a little more battery"}, new String[]{"balanced", "Balanced — 15 fps"}, new String[]{"saver", "Battery saver — 3 fps"}}), new Runnable() { // from class: com.mulberry.player.SettingsPage.6 - @Override // java.lang.Runnable - public void run() { - SettingsPage.this.pick("Widget animation", new String[][]{new String[]{"smooth", "Smooth — 30 fps, a little more battery"}, new String[]{"balanced", "Balanced — 15 fps"}, new String[]{"saver", "Battery saver — 3 fps"}}, Prefs.WIDGET_ANIM, null); - } - }); - toggle(linearLayoutCard, R.drawable.ic_trending_up, "Low-power mode", (App.I.lowRam ? "Turned on automatically for this phone. " : FrameBodyCOMM.DEFAULT) + "Fewer animations, no visualizer, 30 fps — for slow phones", Prefs.LOW_POWER, false, new Runnable() { // from class: com.mulberry.player.SettingsPage.7 - @Override // java.lang.Runnable - public void run() { - SettingsPage.this.a.updateBassShape(); - } - }); - section("Playback"); - LinearLayout linearLayoutCard2 = card(); - final int i = this.p.getInt(Prefs.CROSSFADE, 0); - if (i == 0) { - str = "Off"; - } else { - str = i + " second" + (i == 1 ? FrameBodyCOMM.DEFAULT : "s") + " — songs blend into each other"; - } - choice(linearLayoutCard2, R.drawable.ic_tune, "Crossfade", str, new Runnable() { // from class: com.mulberry.player.SettingsPage.8 - @Override // java.lang.Runnable - public void run() { - int i2 = 0; - final int[] iArr = {0, 1, 2, 3, 4, 5, 6, 8, 10, 12}; - String[] strArr3 = new String[iArr.length]; - int i3 = 0; - while (true) { - int i4 = i2; - if (i3 < iArr.length) { - strArr3[i3] = iArr[i3] == 0 ? "Off" : iArr[i3] + " seconds"; - i2 = iArr[i3] == i ? i3 : i4; - i3++; - } else { - Ui.show(Ui.dialog(SettingsPage.this.a).setTitle("Crossfade").setSingleChoiceItems(strArr3, i4, new DialogInterface.OnClickListener() { // from class: com.mulberry.player.SettingsPage.8.1 - @Override // android.content.DialogInterface.OnClickListener - public void onClick(DialogInterface dialogInterface, int i5) { - SettingsPage.this.p.setInt(Prefs.CROSSFADE, iArr[i5]); - dialogInterface.dismiss(); - if (SettingsPage.this.a.svc != null) { - SettingsPage.this.a.svc.playbackSettingsChanged(); - } - SettingsPage.this.refresh(); - } - })); - return; - } - } - } - }); - toggle(linearLayoutCard2, R.drawable.ic_graphic_eq, "Fade on play / pause", "A short, smooth volume fade instead of a hard stop", Prefs.FADE_PAUSE, true, null); - toggle(linearLayoutCard2, R.drawable.ic_queue_music, "Gapless playback", i > 0 ? "Crossfade is on, so it takes over between songs" : "Starts the next song with no silence in between", Prefs.GAPLESS, true, new Runnable() { // from class: com.mulberry.player.SettingsPage.9 - @Override // java.lang.Runnable - public void run() { - if (SettingsPage.this.a.svc != null) { - SettingsPage.this.a.svc.playbackSettingsChanged(); - } - } - }); - toggle(linearLayoutCard2, R.drawable.ic_history, "Remember position", "Resume the last song where you left off", Prefs.RESUME, true, null); - toggle(linearLayoutCard2, R.drawable.ic_stop_fill, "Pause when headphones disconnect", null, Prefs.PAUSE_ON_DETACH, true, null); - int i2 = this.p.getInt(Prefs.MIN_DURATION, 20); - choice(linearLayoutCard2, R.drawable.ic_music_note, "Hide short clips", i2 == 0 ? "Show everything" : "Shorter than " + i2 + " s", new Runnable() { // from class: com.mulberry.player.SettingsPage.10 - @Override // java.lang.Runnable - public void run() { - final int[] iArr = {0, 10, 20, 30, 60}; - Ui.show(Ui.dialog(SettingsPage.this.a).setTitle("Hide short clips").setItems(new String[]{"Show everything", "10 seconds", "20 seconds", "30 seconds", "1 minute"}, new DialogInterface.OnClickListener() { // from class: com.mulberry.player.SettingsPage.10.1 - @Override // android.content.DialogInterface.OnClickListener - public void onClick(DialogInterface dialogInterface, int i3) { - SettingsPage.this.p.setInt(Prefs.MIN_DURATION, iArr[i3]); - App.I.library.refresh(); - SettingsPage.this.refresh(); - } - })); - } - }); - section("Lyrics & covers"); - LinearLayout linearLayoutCard3 = card(); - choice(linearLayoutCard3, R.drawable.ic_lyrics, "Lyrics source", label(this.p.getStr(Prefs.LYRICS_SOURCE, "auto"), new String[][]{new String[]{"auto", "Auto — synced first, local last"}, new String[]{"lrclib", "LRCLIB"}, new String[]{"netease", "NetEase"}, new String[]{"local", "Local .lrc / embedded"}}), new Runnable() { // from class: com.mulberry.player.SettingsPage.11 - @Override // java.lang.Runnable - public void run() { - SettingsPage.this.pick("Lyrics source", new String[][]{new String[]{"auto", "Auto — synced first, local last"}, new String[]{"lrclib", "LRCLIB"}, new String[]{"netease", "NetEase"}, new String[]{"local", "Local .lrc / embedded"}}, Prefs.LYRICS_SOURCE, new Runnable() { // from class: com.mulberry.player.SettingsPage.11.1 - @Override // java.lang.Runnable - public void run() { - if (SettingsPage.this.a.svc != null) { - SettingsPage.this.a.svc.reloadLyrics(false); - } - } - }); - } - }); - toggle(linearLayoutCard3, R.drawable.ic_text_snippet, "Plain lyrics", "Show lyrics as text without timing", Prefs.LYRICS_PLAIN, false, null); - toggle(linearLayoutCard3, R.drawable.ic_cloud_download, "Fetch lyrics online", "LRCLIB and NetEase", Prefs.ONLINE_LYRICS, true, null); - toggle(linearLayoutCard3, R.drawable.ic_image, "Fetch missing covers", "iTunes, Deezer and Last.fm", Prefs.ONLINE_COVERS, true, null); - button(linearLayoutCard3, R.drawable.ic_delete, "Clear lyrics & cover cache", cacheSize(), new Runnable() { // from class: com.mulberry.player.SettingsPage.12 - @Override // java.lang.Runnable - public void run() { - SettingsPage.del(new File(SettingsPage.this.a.getCacheDir(), "lyrics")); - SettingsPage.del(new File(SettingsPage.this.a.getCacheDir(), "covers")); - MainActivity.toast("Cache cleared"); - SettingsPage.this.refresh(); - } - }); - section("Last.fm"); - LinearLayout linearLayoutCard4 = card(); - if (LastFm.loggedIn()) { - info(linearLayoutCard4, R.drawable.ic_person, "Signed in as " + this.p.getStr(Prefs.LFM_USER, FrameBodyCOMM.DEFAULT), LastFm.pending("lastfm") > 0 ? LastFm.pending("lastfm") + " scrobbles waiting to be sent" : "All scrobbles sent"); - toggle(linearLayoutCard4, R.drawable.ic_scrobble, "Scrobble", "Send “now playing” and scrobbles (after half the song or 4 minutes)", Prefs.LFM_ENABLED, true, null); - if (LastFm.pending("lastfm") > 0) { - button(linearLayoutCard4, R.drawable.ic_upload, "Send waiting scrobbles now", null, new Runnable() { // from class: com.mulberry.player.SettingsPage.13 - @Override // java.lang.Runnable - public void run() { - LastFm.flush(); - MainActivity.toast("Sending…"); - } - }); - } - button(linearLayoutCard4, R.drawable.ic_close, "Sign out", null, new Runnable() { // from class: com.mulberry.player.SettingsPage.14 - @Override // java.lang.Runnable - public void run() { - LastFm.logout(); - SettingsPage.this.refresh(); - } - }); - } else { - info(linearLayoutCard4, R.drawable.ic_scrobble, "Not signed in", "Sign in to scrobble directly from Mulberry"); - button(linearLayoutCard4, R.drawable.ic_person, "Sign in to Last.fm", null, new Runnable() { // from class: com.mulberry.player.SettingsPage.15 - @Override // java.lang.Runnable - public void run() { - SettingsPage.this.login(); - } - }); - } - toggle(linearLayoutCard4, R.drawable.ic_radio, "Tell scrobbler apps", "Pano Scrobbler reads the media session automatically; Simple Last.fm Scrobbler and Scrobble Droid get broadcasts. Found: " + ScrobbleBridge.detected(this.a), Prefs.SCROBBLER_APPS, true, null); - section("ListenBrainz"); - LinearLayout lbCard = card(); - if (ListenBrainz.connected()) { - int lbPending = LastFm.pending("listenbrainz"); - String lbUser = this.p.getStr(Prefs.LB_USER, FrameBodyCOMM.DEFAULT); - info(lbCard, R.drawable.ic_person, lbUser.length() > 0 ? "Connected as " + lbUser : "Connected", lbPending > 0 ? lbPending + " listens waiting to be sent" : "All listens sent"); - toggle(lbCard, R.drawable.ic_scrobble, "Submit listens", "Send “now playing” and listens with MusicBrainz ids, ISRC and more", Prefs.LB_ENABLED, true, null); - if (lbPending > 0) { - button(lbCard, R.drawable.ic_upload, "Send waiting listens now", null, new Runnable() { - @Override - public void run() { - LastFm.flush(); - MainActivity.toast("Sending…"); - } - }); - } - button(lbCard, R.drawable.ic_close, "Disconnect", null, new Runnable() { - @Override - public void run() { - ListenBrainz.disconnect(); - SettingsPage.this.refresh(); - } - }); - } else { - info(lbCard, R.drawable.ic_scrobble, "Not connected", "Paste your user token from listenbrainz.org/settings"); - button(lbCard, R.drawable.ic_person, "Connect ListenBrainz", null, new Runnable() { - @Override - public void run() { - SettingsPage.this.lbConnect(); - } - }); - } - section("Permissions & background"); - LinearLayout linearLayoutCard5 = card(); - button(linearLayoutCard5, R.drawable.ic_library_music, "Music access", this.a.hasAudioPermission() ? "Allowed" : "Not allowed — tap to allow", new Runnable() { // from class: com.mulberry.player.SettingsPage.16 - @Override // java.lang.Runnable - public void run() { - SettingsPage.this.a.openAppSettingsOrAsk(); - } - }); - if (Build.VERSION.SDK_INT >= 33) { - button(linearLayoutCard5, R.drawable.ic_info, "Notifications", this.a.checkSelfPermission("android.permission.POST_NOTIFICATIONS") == 0 ? "Allowed (player controls)" : "Off — tap to allow (needed for the player notification)", new Runnable() { // from class: com.mulberry.player.SettingsPage.17 - @Override // java.lang.Runnable - public void run() { - SettingsPage.this.a.requestPermissions(new String[]{"android.permission.POST_NOTIFICATIONS"}, 1); - } - }); - } - PowerManager powerManager = (PowerManager) this.a.getSystemService("power"); - button(linearLayoutCard5, R.drawable.ic_trending_up, "Background playback", powerManager != null && powerManager.isIgnoringBatteryOptimizations(this.a.getPackageName()) ? "Unrestricted — won't be stopped to save battery" : "Battery optimised — tap so long sessions aren't cut off", new Runnable() { // from class: com.mulberry.player.SettingsPage.18 - @Override // java.lang.Runnable - public void run() { - SettingsPage.this.a.requestBatteryExemption(); - } - }); - if (Build.VERSION.SDK_INT >= 30) { - zIsExternalStorageManager = Environment.isExternalStorageManager(); - } else { - zIsExternalStorageManager = this.a.checkSelfPermission("android.permission.READ_EXTERNAL_STORAGE") == 0; - } - button(linearLayoutCard5, R.drawable.ic_folder_open, "All files access", zIsExternalStorageManager ? "Allowed — .lrc files next to songs and tag saving work without prompts" : "Optional — for .lrc files next to songs and saving tags without asking each time", new Runnable() { // from class: com.mulberry.player.SettingsPage.19 - @Override // java.lang.Runnable - public void run() { - SettingsPage.this.a.requestAllFiles(); - } - }); - section("About"); - LinearLayout linearLayoutCard6 = card(); - String str3 = "1.0.0"; - try { - str3 = this.a.getPackageManager().getPackageInfo(this.a.getPackageName(), 0).versionName; - } catch (Exception e) { - } - info(linearLayoutCard6, R.drawable.ic_info, "Mulberry for Android " + str3, "Coded by Claude (Anthropic) · MIT licence"); - button(linearLayoutCard6, R.drawable.ic_link, "Mulberry for desktop", "github.com/BeamStarTech/Mulberry", new Runnable() { // from class: com.mulberry.player.SettingsPage.20 - @Override // java.lang.Runnable - public void run() { - try { - SettingsPage.this.a.startActivity(new Intent("android.intent.action.VIEW", Uri.parse("https://github.com/BeamStarTech/Mulberry"))); - } catch (Exception e2) { - } - } - }); - post(new Runnable() { // from class: com.mulberry.player.SettingsPage.21 - @Override // java.lang.Runnable - public void run() { - SettingsPage.this.scrollTo(0, scrollY); - } - }); - } - - void repaint() { - boolean z = App.I.palette.dark; - Integer numDominant = null; - if (this.a.svc != null && this.a.svc.art() != null && "album".equals(this.p.getStr(Prefs.COLOR_SOURCE, "system"))) { - numDominant = Palette.dominant(this.a.svc.art()); - } - App.I.palette = Palette.build(this.a, numDominant); - if (z == App.I.palette.dark) { - Ui.recolor(); - this.a.styleNav(); - this.a.styleTabs(); - refresh(); - Widgets.updateAll(this.a); - if (this.a.svc != null) { - this.a.svc.refreshUi(); - return; - } - return; - } - this.a.recreate(); - } - - void pickColorSource() { - String[][] strArr = new String[3][]; - String[] strArr2 = new String[2]; - strArr2[0] = "system"; - strArr2[1] = Build.VERSION.SDK_INT >= 31 ? "Wallpaper (Material You)" : "Default"; - strArr[0] = strArr2; - strArr[1] = new String[]{"album", "From album art"}; - strArr[2] = new String[]{"custom", "Custom colour"}; - pick("Colours", strArr, Prefs.COLOR_SOURCE, new Runnable() { // from class: com.mulberry.player.SettingsPage.22 - @Override // java.lang.Runnable - public void run() { - if (!"custom".equals(SettingsPage.this.p.getStr(Prefs.COLOR_SOURCE, FrameBodyCOMM.DEFAULT))) { - SettingsPage.this.repaint(); - } else { - SettingsPage.this.pickCustomColor(); - } - } - }); - } - - void pickCustomColor() { - int[] iArr = {-6651951, -3052130, -2070694, -1859269, -8408983, -12605546, -11563048, -9670695, -7508381, -8875876}; - LinearLayout linearLayoutCol = Ui.col(this.a); - linearLayoutCol.setPadding(Ui.dp(this.a, 20.0f), Ui.dp(this.a, 12.0f), Ui.dp(this.a, 20.0f), 0); - final AlertDialog[] alertDialogArr = new AlertDialog[1]; - LinearLayout linearLayoutRow = null; - for (int i = 0; i < iArr.length; i++) { - if (i % 5 == 0) { - linearLayoutRow = Ui.row(this.a); - linearLayoutRow.setGravity(17); - linearLayoutCol.addView(linearLayoutRow); - } - final int i2 = iArr[i]; - View view = new View(this.a); - view.setBackground(Ui.round(i2, Ui.dpf(this.a, 22.0f))); - LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Ui.dp(this.a, 44.0f), Ui.dp(this.a, 44.0f)); - layoutParams.setMargins(Ui.dp(this.a, 6.0f), Ui.dp(this.a, 6.0f), Ui.dp(this.a, 6.0f), Ui.dp(this.a, 6.0f)); - view.setOnClickListener(new View.OnClickListener() { // from class: com.mulberry.player.SettingsPage.23 - @Override // android.view.View.OnClickListener - public void onClick(View view2) { - SettingsPage.this.p.setInt(Prefs.CUSTOM_COLOR, i2); - SettingsPage.this.p.setStr(Prefs.COLOR_SOURCE, "custom"); - if (alertDialogArr[0] != null) { - alertDialogArr[0].dismiss(); - } - SettingsPage.this.repaint(); - } - }); - linearLayoutRow.addView(view, layoutParams); - } - alertDialogArr[0] = Ui.show(Ui.dialog(this.a).setTitle("Pick a colour").setView(linearLayoutCol).setNegativeButton("Cancel", (DialogInterface.OnClickListener) null)); - } - - void lbConnect() { - LinearLayout col = Ui.col(this.a); - col.setPadding(Ui.dp(this.a, 22.0f), Ui.dp(this.a, 8.0f), Ui.dp(this.a, 22.0f), 0); - final EditText field = Ui.field(this.a, "User token", FrameBodyCOMM.DEFAULT); - field.setSingleLine(true); - field.setInputType(129); - col.addView(field); - TextView hint = Ui.text(this.a, "Find it at listenbrainz.org/settings (“User token”).", 12.0f, 12, false); - hint.setPadding(0, Ui.dp(this.a, 10.0f), 0, 0); - col.addView(hint); - Ui.show(Ui.dialog(this.a).setTitle("Connect ListenBrainz").setView(col).setPositiveButton("Connect", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - MainActivity.toast("Checking token…"); - ListenBrainz.connect(field.getText().toString(), new LastFm.Cb() { - @Override - public void done(String str) { - MainActivity.toast(str == null ? "Connected to ListenBrainz" : "ListenBrainz: " + str); - SettingsPage.this.refresh(); - } - }); - } - }).setNeutralButton("Get token", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - try { - SettingsPage.this.a.startActivity(new Intent("android.intent.action.VIEW", Uri.parse("https://listenbrainz.org/settings/"))); - } catch (Exception e) { - } - } - }).setNegativeButton("Cancel", (DialogInterface.OnClickListener) null)); - } - - void login() { - LinearLayout linearLayoutCol = Ui.col(this.a); - linearLayoutCol.setPadding(Ui.dp(this.a, 22.0f), Ui.dp(this.a, 8.0f), Ui.dp(this.a, 22.0f), 0); - final EditText editTextField = Ui.field(this.a, "Username or email", FrameBodyCOMM.DEFAULT); - editTextField.setSingleLine(true); - final EditText editTextField2 = Ui.field(this.a, "Password", FrameBodyCOMM.DEFAULT); - editTextField2.setSingleLine(true); - editTextField2.setInputType(129); - linearLayoutCol.addView(editTextField); - linearLayoutCol.addView(new View(this.a), new LinearLayout.LayoutParams(1, Ui.dp(this.a, 10.0f))); - linearLayoutCol.addView(editTextField2); - TextView textViewText = Ui.text(this.a, "Your password is only sent to Last.fm to get a session key; Mulberry doesn't store it.", 12.0f, 12, false); - textViewText.setPadding(0, Ui.dp(this.a, 10.0f), 0, 0); - linearLayoutCol.addView(textViewText); - Ui.show(Ui.dialog(this.a).setTitle("Sign in to Last.fm").setView(linearLayoutCol).setPositiveButton("Sign in", new DialogInterface.OnClickListener() { // from class: com.mulberry.player.SettingsPage.25 - @Override // android.content.DialogInterface.OnClickListener - public void onClick(DialogInterface dialogInterface, int i) { - MainActivity.toast("Signing in…"); - LastFm.login(editTextField.getText().toString().trim(), editTextField2.getText().toString(), new LastFm.Cb() { // from class: com.mulberry.player.SettingsPage.25.1 - @Override // com.mulberry.player.LastFm.Cb - public void done(String str) { - if (str == null) { - MainActivity.toast("Signed in to Last.fm"); - LastFm.flush(); - } else { - MainActivity.toast("Last.fm: " + str); - } - SettingsPage.this.refresh(); - } - }); - } - }).setNeutralButton("Create account", new DialogInterface.OnClickListener() { // from class: com.mulberry.player.SettingsPage.24 - @Override // android.content.DialogInterface.OnClickListener - public void onClick(DialogInterface dialogInterface, int i) { - try { - SettingsPage.this.a.startActivity(new Intent("android.intent.action.VIEW", Uri.parse("https://www.last.fm/join"))); - } catch (Exception e) { - } - } - }).setNegativeButton("Cancel", (DialogInterface.OnClickListener) null)); - } - - void pick(String str, final String[][] strArr, final String str2, final Runnable runnable) { - String str3 = this.p.getStr(str2, strArr[0][0]); - String[] strArr2 = new String[strArr.length]; - int i = 0; - for (int i2 = 0; i2 < strArr.length; i2++) { - strArr2[i2] = strArr[i2][1]; - if (strArr[i2][0].equals(str3)) { - i = i2; - } - } - Ui.show(Ui.dialog(this.a).setTitle(str).setSingleChoiceItems(strArr2, i, new DialogInterface.OnClickListener() { // from class: com.mulberry.player.SettingsPage.26 - @Override // android.content.DialogInterface.OnClickListener - public void onClick(DialogInterface dialogInterface, int i3) { - SettingsPage.this.p.setStr(str2, strArr[i3][0]); - dialogInterface.dismiss(); - if (runnable != null) { - runnable.run(); - } - SettingsPage.this.refresh(); - } - })); - } - - static String label(String str, String[][] strArr) { - for (String[] strArr2 : strArr) { - if (strArr2[0].equals(str)) { - return strArr2[1]; - } - } - return strArr[0][1]; - } - - void section(String str) { - TextView textViewSingle = Ui.single(this.a, str, 14.0f, 0, true); - textViewSingle.setPadding(Ui.dp(this.a, 12.0f), Ui.dp(this.a, 18.0f), 0, Ui.dp(this.a, 8.0f)); - this.box.addView(textViewSingle); - } - - LinearLayout card() { - final LinearLayout linearLayoutCol = Ui.col(this.a); - linearLayoutCol.setPadding(0, Ui.dp(this.a, 4.0f), 0, Ui.dp(this.a, 4.0f)); - Ui.themed(linearLayoutCol, new Ui.Paint() { // from class: com.mulberry.player.SettingsPage.27 - @Override // com.mulberry.player.Ui.Paint - public void apply() { - linearLayoutCol.setBackground(Ui.round(Ui.c(8), Ui.dpf(SettingsPage.this.a, 24.0f))); - } - }); - this.box.addView(linearLayoutCol); - return linearLayoutCol; - } - - LinearLayout baseRow(LinearLayout linearLayout, int i, String str, String str2) { - LinearLayout linearLayoutRow = Ui.row(this.a); - linearLayoutRow.setPadding(Ui.dp(this.a, 16.0f), Ui.dp(this.a, 12.0f), Ui.dp(this.a, 14.0f), Ui.dp(this.a, 12.0f)); - linearLayoutRow.addView(Ui.icon(this.a, i, 12, 22)); - LinearLayout linearLayoutCol = Ui.col(this.a); - linearLayoutCol.setPadding(Ui.dp(this.a, 16.0f), 0, Ui.dp(this.a, 8.0f), 0); - linearLayoutCol.addView(Ui.text(this.a, str, 15.5f, 11, true)); - if (str2 != null && str2.length() > 0) { - linearLayoutCol.addView(Ui.text(this.a, str2, 13.0f, 12, false)); - } - linearLayoutRow.addView(linearLayoutCol, Ui.lpw(-2, 1.0f)); - linearLayout.addView(linearLayoutRow); - return linearLayoutRow; - } - - void info(LinearLayout linearLayout, int i, String str, String str2) { - baseRow(linearLayout, i, str, str2); - } - - void button(LinearLayout linearLayout, int i, String str, String str2, final Runnable runnable) { - LinearLayout linearLayoutBaseRow = baseRow(linearLayout, i, str, str2); - Ui.clickable(linearLayoutBaseRow, 20.0f); - linearLayoutBaseRow.setOnClickListener(new View.OnClickListener() { // from class: com.mulberry.player.SettingsPage.28 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - runnable.run(); - } - }); - } - - void choice(LinearLayout linearLayout, int i, String str, String str2, Runnable runnable) { - button(linearLayout, i, str, str2, runnable); - } - - void toggle(LinearLayout linearLayout, int i, String str, String str2, final String str3, boolean z, final Runnable runnable) { - LinearLayout linearLayoutBaseRow = baseRow(linearLayout, i, str, str2); - final Switch r1 = new Switch(this.a); - r1.setChecked(this.p.getBool(str3, z)); - int[][] iArr = {new int[]{android.R.attr.state_checked}, new int[0]}; - r1.setThumbTintList(new ColorStateList(iArr, new int[]{Ui.c(1), Ui.c(13)})); - r1.setTrackTintList(new ColorStateList(iArr, new int[]{Ui.c(0), Ui.c(10)})); - r1.setClickable(false); - linearLayoutBaseRow.addView(r1); - Ui.clickable(linearLayoutBaseRow, 20.0f); - linearLayoutBaseRow.setOnClickListener(new View.OnClickListener() { // from class: com.mulberry.player.SettingsPage.29 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - boolean z2 = !r1.isChecked(); - r1.setChecked(z2); - SettingsPage.this.p.setBool(str3, z2); - if (runnable != null) { - runnable.run(); - } - } - }); - } - - String cacheSize() { - long size = size(new File(this.a.getCacheDir(), "lyrics")) + size(new File(this.a.getCacheDir(), "covers")); - return size < 1048576 ? (size / 1024) + " KB" : String.format(Locale.ROOT, "%.1f MB", Double.valueOf(size / 1048576.0d)); - } - - static long size(File file) { - if (file.isFile()) { - return file.length(); - } - long size = 0; - File[] fileArrListFiles = file.listFiles(); - if (fileArrListFiles == null) { - return 0L; - } - for (File file2 : fileArrListFiles) { - size += size(file2); - } - return size; - } - - static void del(File file) { - File[] fileArrListFiles = file.listFiles(); - if (fileArrListFiles != null) { - for (File file2 : fileArrListFiles) { - del(file2); - } - } - file.delete(); - } -} diff --git a/android/src/com/mulberry/player/Shapes.java b/android/src/com/mulberry/player/Shapes.java deleted file mode 100644 index 5dac1c5..0000000 --- a/android/src/com/mulberry/player/Shapes.java +++ /dev/null @@ -1,398 +0,0 @@ -package com.mulberry.player; - -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Path; -import java.util.Random; - -/* JADX INFO: loaded from: classes.dex */ -public final class Shapes { - public static final float[][] ALL; - public static final int N = 120; - public static final String[] NAMES; - - static { - String[] strArr = {"circle", "cookie4", "cookie6", "cookie7", "cookie9", "cookie12", "clover4", "clover8", "sunny", "burst", "softburst", "star5", "star4", "triangle", "square", "pentagon", "hexagon", "gem", "pill", "flower", "puffy", "bean", "arch"}; - NAMES = strArr; - ALL = new float[strArr.length][]; - for (int i = 0; i < strArr.length; i++) { - float[] fArr = new float[N]; - for (int i2 = 0; i2 < 120; i2++) { - fArr[i2] = (float) radius(strArr[i], (6.283185307179586d * ((double) i2)) / 120.0d); - } - float fMax = 0.0f; - for (float f : fArr) { - fMax = Math.max(fMax, f); - } - for (int i3 = 0; i3 < 120; i3++) { - fArr[i3] = fArr[i3] / fMax; - } - ALL[i] = smooth(fArr, strArr[i].startsWith("burst") ? 0 : 1); - } - } - - private Shapes() { - } - - static double tri(double d) { - double d2 = (d / 6.283185307179586d) % 1.0d; - if (d2 < 0.0d) { - d2 += 1.0d; - } - return 1.0d - Math.abs((d2 * 2.0d) - 1.0d); - } - - static double poly(int i, double d, double d2) { - double d3 = 6.283185307179586d / ((double) i); - return ((Math.cos(3.141592653589793d / ((double) i)) / Math.cos((((d % d3) + d3) % d3) - (d3 / 2.0d))) * (1.0d - d2)) + (Math.cos(3.141592653589793d / ((double) i)) * d2 * 1.04d); - } - - /* JADX WARN: Failed to restore switch over string. Please report as a decompilation issue */ - static double radius(String str, double d) { - byte b = -1; - switch (str.hashCode()) { - case -2069233866: - if (str.equals("softburst")) { - b = 10; - } - break; - case -1360216880: - if (str.equals("circle")) { - b = 0; - } - break; - case -1271629221: - if (str.equals("flower")) { - b = 19; - } - break; - case -894674659: - if (str.equals("square")) { - b = 14; - } - break; - case -546895995: - if (str.equals("cookie12")) { - b = 5; - } - break; - case 102223: - if (str.equals("gem")) { - b = 17; - } - break; - case 3002454: - if (str.equals("arch")) { - b = 22; - } - break; - case 3019696: - if (str.equals("bean")) { - b = 21; - } - break; - case 3440953: - if (str.equals("pill")) { - b = 18; - } - break; - case 94103840: - if (str.equals("burst")) { - b = 9; - } - break; - case 107021204: - if (str.equals("puffy")) { - b = 20; - } - break; - case 109757474: - if (str.equals("star4")) { - b = 12; - } - break; - case 109757475: - if (str.equals("star5")) { - b = 11; - } - break; - case 109799703: - if (str.equals("sunny")) { - b = 8; - } - break; - case 329147776: - if (str.equals("pentagon")) { - b = 15; - } - break; - case 816461344: - if (str.equals("hexagon")) { - b = 16; - } - break; - case 866626327: - if (str.equals("clover4")) { - b = 6; - } - break; - case 866626331: - if (str.equals("clover8")) { - b = 7; - } - break; - case 952189520: - if (str.equals("cookie4")) { - b = 1; - } - break; - case 952189522: - if (str.equals("cookie6")) { - b = 2; - } - break; - case 952189523: - if (str.equals("cookie7")) { - b = 3; - } - break; - case 952189525: - if (str.equals("cookie9")) { - b = 4; - } - break; - case 1497762312: - if (str.equals("triangle")) { - b = 13; - } - break; - } - switch (b) { - case 0: - default: - return 1.0d; - case 1: - return 0.9d + (Math.cos(4.0d * d) * 0.1d); - case 2: - return 0.92d + (0.08d * Math.cos(6.0d * d)); - case 3: - return 0.925d + (0.075d * Math.cos(7.0d * d)); - case 4: - return 0.94d + (0.06d * Math.cos(9.0d * d)); - case 5: - return 0.955d + (0.045d * Math.cos(12.0d * d)); - case 6: - return 0.58d + (0.42d * Math.pow(Math.abs(Math.cos(2.0d * d)), 0.55d)); - case 7: - return 0.7d + (0.3d * Math.pow(Math.abs(Math.cos(4.0d * d)), 0.6d)); - case 8: - return 0.84d + (0.16d * Math.cos(8.0d * d)); - case 9: - return 0.72d + (0.28d * tri(12.0d * d)); - case 10: - return 0.8d + (0.2d * Math.pow(tri(10.0d * d), 1.6d)); - case 11: - return (Math.pow((1.0d + Math.cos(5.0d * d)) / 2.0d, 1.8d) * 0.5d) + 0.5d; - case 12: - return (Math.pow((1.0d + Math.cos(4.0d * (0.7853981633974483d + d))) / 2.0d, 2.2d) * 0.48d) + 0.52d; - case Ui.OUTLINE /* 13 */: - return poly(3, d - 1.5707963267948966d, 0.18d); - case 14: - return poly(4, d + 0.7853981633974483d, 0.16d); - case Ui.TERTIARY /* 15 */: - return poly(5, d - 1.5707963267948966d, 0.14d); - case 16: - return poly(6, d, 0.1d); - case Ui.ERROR /* 17 */: - return poly(4, d, 0.1d); - case 18: - return 1.0d / Math.sqrt(Math.pow(Math.sin(d) / 0.6d, 2.0d) + Math.pow(Math.cos(d) / 1.0d, 2.0d)); - case 19: - return 0.55d + (0.45d * Math.abs(Math.cos(3.0d * d))); - case 20: - return poly(4, d + 0.7853981633974483d, 0.3d) * (0.965d + (0.035d * Math.cos(16.0d * d))); - case 21: - return (((1.0d + Math.sin(d)) * 0.38d) / 2.0d) + 0.62d + (0.05d * Math.cos(2.0d * d)); - case 22: - if (Math.sin(d) > 0.0d) { - return poly(4, d + 0.7853981633974483d, 0.25d); - } - return 0.92d; - } - } - - static float[] smooth(float[] fArr, int i) { - int i2 = 0; - float[] fArr2 = (float[]) fArr.clone(); - while (i2 < i) { - float[] fArr3 = new float[N]; - for (int i3 = 0; i3 < 120; i3++) { - fArr3[i3] = ((fArr2[((i3 + N) - 1) % N] + (2.0f * fArr2[i3])) + fArr2[(i3 + 1) % N]) / 4.0f; - } - i2++; - fArr2 = fArr3; - } - return fArr2; - } - - public static Path path(Path path, float[] fArr, float f, float f2, float f3, float f4) { - if (path == null) { - path = new Path(); - } else { - path.reset(); - } - for (int i = 0; i <= 120; i++) { - int i2 = i % N; - double d = ((6.283185307179586d * ((double) i2)) / 120.0d) + ((double) f4); - float fCos = (float) (((double) f) + (((double) (fArr[i2] * f3)) * Math.cos(d))); - float fSin = (float) ((Math.sin(d) * ((double) (fArr[i2] * f3))) + ((double) f2)); - if (i == 0) { - path.moveTo(fCos, fSin); - } else { - path.lineTo(fCos, fSin); - } - } - path.close(); - return path; - } - - public static final class Animator { - static final int HIST = 24; - int beatsSinceMorph; - float clock; - float energy; - int from; - int histPos; - float innerRot; - float kick; - public boolean playing; - float prev; - float pulse; - float rot; - float sinceMorph; - final Random rnd = new Random(); - int to = 6; - int innerFrom = 3; - int innerTo = 11; - float t = 1.0f; - float tInner = 1.0f; - float morphSpeed = 6.0f; - float rotVel = 0.35f; - float avg = 0.2f; - float sinceBeat = 10.0f; - final float[] cur = new float[Shapes.N]; - final float[] inner = new float[Shapes.N]; - final float[] histV = new float[24]; - final float[] histT = new float[24]; - - int pick(int i, int i2) { - while (true) { - int iNextInt = this.rnd.nextInt(Shapes.ALL.length); - if (iNextInt != i && iNextInt != i2) { - return iNextInt; - } - } - } - - void jump(boolean z) { - this.from = this.to; - this.to = pick(this.to, this.from); - this.t = 0.0f; - this.morphSpeed = z ? 7.5f : 2.2f; - if (this.rnd.nextFloat() < 0.6f || !z) { - this.innerFrom = this.innerTo; - this.innerTo = pick(this.innerTo, this.to); - this.tInner = 0.0f; - } - if (z) { - this.rotVel = ((this.rnd.nextBoolean() ? 1 : -1) * (1.5f + (this.rnd.nextFloat() * 2.5f))) + this.rotVel; - } - this.sinceMorph = 0.0f; - } - - public void step(float f, float f2) { - this.sinceBeat += f; - this.sinceMorph += f; - if (this.playing) { - if (f2 >= 0.0f) { - this.energy += (f2 - this.energy) * Math.min(1.0f, 20.0f * f); - this.avg += (f2 - this.avg) * Math.min(1.0f, 0.7f * f); - float f3 = f2 - this.prev; - this.prev = f2; - this.clock += f; - float f4 = f2; - for (int i = 0; i < 24; i++) { - if (this.clock - this.histT[i] < 0.2f && this.histV[i] < f4) { - f4 = this.histV[i]; - } - } - this.histV[this.histPos] = f2; - this.histT[this.histPos] = this.clock; - this.histPos = (this.histPos + 1) % 24; - float f5 = f2 - f4; - if (f2 > 0.3f && f5 > 0.05f && f3 > 0.025f && this.sinceBeat > 0.28f) { - this.sinceBeat = 0.0f; - this.kick = Math.min(1.0f, (2.5f * f5) + 0.5f); - this.beatsSinceMorph++; - if (this.sinceMorph > 0.8f && (f5 > 0.2f || this.beatsSinceMorph >= 2)) { - this.beatsSinceMorph = 0; - jump(true); - } - } - } else if (this.sinceBeat > 1.8f) { - this.kick = 0.5f; - this.sinceBeat = 0.0f; - jump(true); - } - if (this.sinceMorph > 6.0f) { - jump(false); - } - } else { - this.energy += (0.0f - this.energy) * Math.min(1.0f, 4.0f * f); - if (this.sinceMorph > 8.0f) { - jump(false); - } - } - this.kick = Math.max(0.0f, this.kick - (3.4f * f)); - this.pulse = (((this.playing ? (0.15f + (this.energy * 0.45f)) + (this.kick * 0.55f) : 0.0f) - this.pulse) * Math.min(1.0f, 16.0f * f)) + this.pulse; - this.t = Math.min(1.0f, this.t + (this.morphSpeed * f)); - this.tInner = Math.min(1.0f, this.tInner + (this.morphSpeed * f * 0.8f)); - this.rotVel = (((this.playing ? 0.4f : 0.12f) - this.rotVel) * Math.min(1.0f, 2.5f * f)) + this.rotVel; - this.rot += this.rotVel * f; - this.innerRot -= (0.6f + (this.kick * 3.0f)) * f; - float fEase = ease(this.t); - float fEase2 = ease(this.tInner); - float[] fArr = Shapes.ALL[this.from]; - float[] fArr2 = Shapes.ALL[this.to]; - float[] fArr3 = Shapes.ALL[this.innerFrom]; - float[] fArr4 = Shapes.ALL[this.innerTo]; - for (int i2 = 0; i2 < 120; i2++) { - this.cur[i2] = fArr[i2] + ((fArr2[i2] - fArr[i2]) * fEase); - this.inner[i2] = fArr3[i2] + ((fArr4[i2] - fArr3[i2]) * fEase2); - } - } - - static float ease(float f) { - float f2 = f - 1.0f; - return (1.7f * f2 * f2) + ((1.7f + 1.0f) * f2 * f2 * f2) + 1.0f; - } - - public boolean settled() { - return !this.playing && this.pulse < 0.01f && this.t >= 1.0f && this.tInner >= 1.0f && this.kick <= 0.0f; - } - - public void draw(Canvas canvas, float f, float f2, float f3, int i, int i2, int i3, Paint paint, Path path) { - float f4 = f3 * (0.74f + (0.26f * this.pulse)); - paint.setStyle(Paint.Style.FILL); - paint.setColor(i); - canvas.drawPath(Shapes.path(path, this.cur, f, f2, f4, this.rot), paint); - paint.setStyle(Paint.Style.STROKE); - paint.setStrokeWidth(Math.max(2.0f, 0.035f * f3)); - paint.setColor(Palette.alpha(i3, 0.35f + (0.65f * this.kick))); - canvas.drawPath(path, paint); - paint.setStyle(Paint.Style.FILL); - paint.setColor(i2); - canvas.drawPath(Shapes.path(path, this.inner, f, f2, f4 * (0.36f + (0.12f * this.kick) + (0.06f * this.energy)), this.innerRot), paint); - } - } -} diff --git a/android/src/com/mulberry/player/Song.java b/android/src/com/mulberry/player/Song.java deleted file mode 100644 index 3a5d061..0000000 --- a/android/src/com/mulberry/player/Song.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.mulberry.player; - -import android.content.ContentUris; -import android.net.Uri; -import android.provider.MediaStore; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; -import org.json.JSONException; -import org.json.JSONObject; - -/* JADX INFO: loaded from: classes.dex */ -public final class Song { - public long dateAdded; - public long duration; - public int track; - public int year; - public long id = -1; - public String uri = FrameBodyCOMM.DEFAULT; - public String path = FrameBodyCOMM.DEFAULT; - public String title = FrameBodyCOMM.DEFAULT; - public String artist = FrameBodyCOMM.DEFAULT; - public String album = FrameBodyCOMM.DEFAULT; - public String albumArtist = FrameBodyCOMM.DEFAULT; - public long albumId = -1; - public String mime = FrameBodyCOMM.DEFAULT; - public String folder = FrameBodyCOMM.DEFAULT; - - public static Song fromStore(long j) { - Song song = new Song(); - song.id = j; - song.uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, j).toString(); - return song; - } - - public Uri toUri() { - return Uri.parse(this.uri); - } - - public boolean isStream() { - return this.uri.startsWith("http://") || this.uri.startsWith("https://"); - } - - public String displayTitle() { - if (this.title != null && this.title.length() > 0) { - return this.title; - } - if (this.path != null && this.path.length() > 0) { - String strSubstring = this.path.substring(this.path.lastIndexOf(47) + 1); - int iLastIndexOf = strSubstring.lastIndexOf(46); - return iLastIndexOf > 0 ? strSubstring.substring(0, iLastIndexOf) : strSubstring; - } - return this.uri; - } - - public String displayArtist() { - if (this.artist == null || this.artist.length() <= 0 || "".equals(this.artist)) { - return this.albumArtist != null ? this.albumArtist : FrameBodyCOMM.DEFAULT; - } - return this.artist; - } - - public String key() { - return this.id >= 0 ? "id:" + this.id : this.uri; - } - - public JSONObject toJson() { - JSONObject jSONObject = new JSONObject(); - try { - jSONObject.put("id", this.id); - jSONObject.put("uri", this.uri); - jSONObject.put("path", this.path); - jSONObject.put("title", this.title); - jSONObject.put("artist", this.artist); - jSONObject.put("album", this.album); - jSONObject.put("aa", this.albumArtist); - jSONObject.put("aid", this.albumId); - jSONObject.put("dur", this.duration); - jSONObject.put("tr", this.track); - jSONObject.put("yr", this.year); - } catch (JSONException e) { - } - return jSONObject; - } - - public static Song fromJson(JSONObject jSONObject) { - Song song = new Song(); - song.id = jSONObject.optLong("id", -1L); - song.uri = jSONObject.optString("uri"); - song.path = jSONObject.optString("path"); - song.title = jSONObject.optString("title"); - song.artist = jSONObject.optString("artist"); - song.album = jSONObject.optString("album"); - song.albumArtist = jSONObject.optString("aa"); - song.albumId = jSONObject.optLong("aid", -1L); - song.duration = jSONObject.optLong("dur"); - song.track = jSONObject.optInt("tr"); - song.year = jSONObject.optInt("yr"); - return song; - } -} diff --git a/android/src/com/mulberry/player/Spectrum.java b/android/src/com/mulberry/player/Spectrum.java deleted file mode 100644 index 1d68c36..0000000 --- a/android/src/com/mulberry/player/Spectrum.java +++ /dev/null @@ -1,420 +0,0 @@ -package com.mulberry.player; - -import android.content.Context; -import android.media.MediaCodec; -import android.media.MediaCrypto; -import android.media.MediaExtractor; -import android.media.MediaFormat; -import android.net.Uri; -import android.os.Build; -import android.view.Surface; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.Map; - -/* JADX INFO: loaded from: classes.dex */ -public final class Spectrum { - private static final long AHEAD_MS = 15000; - public static final int BANDS = 48; - public static final int FPS = 30; - private static final int N = 1024; - private volatile byte[] bassFrames; - private volatile Clock clock; - private final Context ctx; - private volatile byte[] frames; - private volatile int gen; - private volatile boolean[] have; - private int tableRate; - private volatile long seekReqMs = -1; - private final float[] cos = new float[512]; - private final float[] sin = new float[512]; - private final float[] win = new float[N]; - private final int[] rev = new int[N]; - private final int[] bandLo = new int[48]; - private final int[] bandHi = new int[48]; - - public interface Clock { - long positionMs(); - } - - public Spectrum(Context context) { - this.ctx = context.getApplicationContext(); - for (int i = 0; i < 512; i++) { - this.cos[i] = (float) Math.cos((((double) i) * (-6.283185307179586d)) / 1024.0d); - this.sin[i] = (float) Math.sin((((double) i) * (-6.283185307179586d)) / 1024.0d); - } - for (int i2 = 0; i2 < N; i2++) { - this.win[i2] = (float) (0.5d - (Math.cos((6.283185307179586d * ((double) i2)) / 1023.0d) * 0.5d)); - } - int iNumberOfTrailingZeros = Integer.numberOfTrailingZeros(N); - for (int i3 = 0; i3 < N; i3++) { - this.rev[i3] = Integer.reverse(i3) >>> (32 - iNumberOfTrailingZeros); - } - } - - public static boolean enabled() { - return !App.lowPowerFlag && App.visualizerFlag; - } - - public void setClock(Clock clock) { - this.clock = clock; - } - - public void stop() { - this.gen++; - this.frames = null; - this.have = null; - this.bassFrames = null; - } - - public void start(final Song song, long j) { - int i; - final int i2 = this.gen + 1; - this.gen = i2; - this.frames = null; - this.have = null; - this.seekReqMs = -1L; - if (song != null && !song.isStream() && enabled() && j > 0 && (i = ((int) ((30 * j) / 1000)) + 30) <= 162000) { - this.frames = new byte[i * 48]; - this.bassFrames = new byte[i]; - this.have = new boolean[i]; - App.HEAVY.execute(new Runnable() { // from class: com.mulberry.player.Spectrum.1 - @Override // java.lang.Runnable - public void run() { - try { - Spectrum.this.decode(song.toUri(), i2); - } catch (Throwable th) { - } - } - }); - } - } - - public void seek(long j) { - int i; - boolean[] zArr = this.have; - if (zArr != null && (i = (int) ((30 * j) / 1000)) >= 0 && i < zArr.length && !zArr[i]) { - this.seekReqMs = j; - } - } - - public boolean levels(long j, float[] fArr) { - int i; - byte[] bArr = this.frames; - boolean[] zArr = this.have; - if (bArr == null || zArr == null || (i = (int) ((30 * j) / 1000)) < 0 || i >= zArr.length || !zArr[i]) { - return false; - } - int i2 = i * 48; - for (int i3 = 0; i3 < 48 && i3 < fArr.length; i3++) { - fArr[i3] = (bArr[i2 + i3] & 255) / 255.0f; - } - return true; - } - - public float bass(long j) { - int i; - byte[] bArr = this.bassFrames; - boolean[] zArr = this.have; - if (bArr == null || zArr == null || (i = (int) ((30 * j) / 1000)) < 0 || i >= zArr.length || i >= bArr.length || !zArr[i]) { - return -1.0f; - } - return (bArr[i] & 255) / 255.0f; - } - - private void buildBands(int i) { - if (i != this.tableRate) { - this.tableRate = i; - double dMin = Math.min(16000.0d, (((double) i) / 2.0d) - 1.0d); - for (int i2 = 0; i2 < 48; i2++) { - double dPow = Math.pow(dMin / 40.0d, ((double) i2) / 48.0d) * 40.0d; - double dPow2 = Math.pow(dMin / 40.0d, ((double) (i2 + 1)) / 48.0d) * 40.0d; - int iFloor = (int) Math.floor((dPow * 1024.0d) / ((double) i)); - int iCeil = (int) Math.ceil((1024.0d * dPow2) / ((double) i)); - int iMax = Math.max(1, Math.min(511, iFloor)); - int iMax2 = Math.max(iMax + 1, Math.min(512, iCeil)); - this.bandLo[i2] = iMax; - this.bandHi[i2] = iMax2; - } - } - } - - /* JADX INFO: Access modifiers changed from: private */ - public void decode(Uri uri, int i) throws Exception { - Throwable th; - boolean z; - long j; - long j2; - int i2; - int i3; - int iDequeueInputBuffer; - byte[] bArr = this.frames; - byte[] bArr2 = this.bassFrames; - boolean[] zArr = this.have; - if (bArr == null || zArr == null || bArr2 == null) { - return; - } - MediaExtractor mediaExtractor = new MediaExtractor(); - MediaCodec mediaCodec = null; - try { - mediaExtractor.setDataSource(this.ctx, uri, (Map) null); - MediaFormat mediaFormat = null; - int i4 = 0; - while (true) { - if (i4 >= mediaExtractor.getTrackCount()) { - i4 = -1; - break; - } - MediaFormat trackFormat = mediaExtractor.getTrackFormat(i4); - String string = trackFormat.getString("mime"); - if (string != null && string.startsWith("audio/")) { - mediaFormat = trackFormat; - break; - } - i4++; - } - if (i4 < 0) { - if (0 != 0) { - try { - mediaCodec.stop(); - mediaCodec.release(); - } catch (Exception e) { - } - } - mediaExtractor.release(); - return; - } - mediaExtractor.selectTrack(i4); - MediaCodec mediaCodecCreateDecoderByType = MediaCodec.createDecoderByType(mediaFormat.getString("mime")); - try { - mediaCodecCreateDecoderByType.configure(mediaFormat, (Surface) null, (MediaCrypto) null, 0); - mediaCodecCreateDecoderByType.start(); - int integer = mediaFormat.containsKey("sample-rate") ? mediaFormat.getInteger("sample-rate") : 44100; - int integer2 = mediaFormat.containsKey("channel-count") ? mediaFormat.getInteger("channel-count") : 2; - boolean z2 = false; - buildBands(integer); - float[] fArr = new float[N]; - int i5 = 0; - int i6 = 0; - long j3 = 0; - long j4 = 0; - float[] fArr2 = new float[N]; - float[] fArr3 = new float[N]; - MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); - boolean z3 = false; - while (this.gen == i) { - long j5 = this.seekReqMs; - if (j5 >= 0) { - this.seekReqMs = -1L; - mediaExtractor.seekTo(1000 * j5, 0); - mediaCodecCreateDecoderByType.flush(); - z3 = false; - i6 = 0; - j3 = -1; - j4 = j5 * 1000; - } - Clock clock = this.clock; - if (clock == null || j4 / 1000 <= clock.positionMs() + AHEAD_MS) { - if (z3 || (iDequeueInputBuffer = mediaCodecCreateDecoderByType.dequeueInputBuffer(10000L)) < 0) { - z = z3; - } else { - ByteBuffer inputBuffer = mediaCodecCreateDecoderByType.getInputBuffer(iDequeueInputBuffer); - int sampleData = inputBuffer == null ? -1 : mediaExtractor.readSampleData(inputBuffer, 0); - if (sampleData < 0) { - mediaCodecCreateDecoderByType.queueInputBuffer(iDequeueInputBuffer, 0, 0, 0L, 4); - z = true; - } else { - mediaCodecCreateDecoderByType.queueInputBuffer(iDequeueInputBuffer, 0, sampleData, mediaExtractor.getSampleTime(), 0); - mediaExtractor.advance(); - z = z3; - } - } - int iDequeueOutputBuffer = mediaCodecCreateDecoderByType.dequeueOutputBuffer(bufferInfo, 10000L); - if (iDequeueOutputBuffer == -2) { - MediaFormat outputFormat = mediaCodecCreateDecoderByType.getOutputFormat(); - int integer3 = outputFormat.containsKey("sample-rate") ? outputFormat.getInteger("sample-rate") : integer; - int iMax = outputFormat.containsKey("channel-count") ? Math.max(1, outputFormat.getInteger("channel-count")) : integer2; - boolean z4 = (Build.VERSION.SDK_INT < 24 || !outputFormat.containsKey("pcm-encoding")) ? z2 : outputFormat.getInteger("pcm-encoding") == 4; - buildBands(integer3); - z3 = z; - z2 = z4; - integer2 = iMax; - integer = integer3; - } else if (iDequeueOutputBuffer < 0) { - z3 = z; - } else { - ByteBuffer outputBuffer = mediaCodecCreateDecoderByType.getOutputBuffer(iDequeueOutputBuffer); - if (outputBuffer == null || bufferInfo.size <= 0) { - j = j4; - j2 = j3; - i2 = i6; - } else { - outputBuffer.position(bufferInfo.offset); - outputBuffer.limit(bufferInfo.offset + bufferInfo.size); - outputBuffer.order(ByteOrder.nativeOrder()); - if (j3 < 0 || Math.abs(bufferInfo.presentationTimeUs - j4) > 500000) { - j4 = bufferInfo.presentationTimeUs; - j2 = ((((30 * j4) / 1000000) + 1) * 1000000) / 30; - i3 = 0; - } else { - j2 = j3; - i3 = i6; - } - long jMax = 1000000 / ((long) Math.max(1, integer)); - int i7 = bufferInfo.size / ((z2 ? 4 : 2) * integer2); - int i8 = 0; - int i9 = i5; - while (i8 < i7) { - float f = 0.0f; - for (int i10 = 0; i10 < integer2; i10++) { - f += z2 ? outputBuffer.getFloat() : outputBuffer.getShort() / 32768.0f; - } - fArr[i9] = f / integer2; - int i11 = (i9 + 1) & 1023; - int i12 = i3 < N ? i3 + 1 : i3; - long j6 = j4 + jMax; - if (j6 >= j2) { - int i13 = (int) ((30 * j2) / 1000000); - long j7 = 33333 + j2; - if (i12 == N) { - analyse(fArr, i11, fArr2, fArr3, i13, bArr, zArr, bArr2); - } - j2 = j7; - } - i8++; - j4 = j6; - i3 = i12; - i9 = i11; - } - j = j4; - i2 = i3; - i5 = i9; - } - mediaCodecCreateDecoderByType.releaseOutputBuffer(iDequeueOutputBuffer, false); - if ((bufferInfo.flags & 4) != 0) { - while (this.gen == i && this.seekReqMs < 0) { - Thread.sleep(300L); - } - } - z3 = z; - j4 = j; - j3 = j2; - i6 = i2; - } - } else { - Thread.sleep(250L); - } - } - if (mediaCodecCreateDecoderByType != null) { - try { - mediaCodecCreateDecoderByType.stop(); - mediaCodecCreateDecoderByType.release(); - } catch (Exception e2) { - } - } - mediaExtractor.release(); - return; - } catch (Throwable th2) { - th = th2; - mediaCodec = mediaCodecCreateDecoderByType; - } - } catch (Throwable th3) { - th = th3; - } - if (mediaCodec != null) { - try { - mediaCodec.stop(); - mediaCodec.release(); - } catch (Exception e3) { - } - } - mediaExtractor.release(); - if (th instanceof Exception) { - throw (Exception) th; - } - throw new Exception(th); - } - - private void analyse(float[] fArr, int i, float[] fArr2, float[] fArr3, int i2, byte[] bArr, boolean[] zArr, byte[] bArr2) { - if (i2 >= 0 && i2 < zArr.length) { - for (int i3 = 0; i3 < N; i3++) { - int i4 = this.rev[i3]; - fArr2[i4] = fArr[(i + i3) & 1023] * this.win[i3]; - fArr3[i4] = 0.0f; - } - int i5 = 2; - while (true) { - int i6 = i5; - if (i6 > N) { - break; - } - int i7 = i6 >> 1; - int i8 = N / i6; - int i9 = 0; - while (true) { - int i10 = i9; - if (i10 < N) { - for (int i11 = 0; i11 < i7; i11++) { - float f = this.cos[i11 * i8]; - float f2 = this.sin[i11 * i8]; - int i12 = i10 + i11; - int i13 = i12 + i7; - float f3 = (fArr2[i13] * f) - (fArr3[i13] * f2); - float f4 = (f * fArr3[i13]) + (f2 * fArr2[i13]); - fArr2[i13] = fArr2[i12] - f3; - fArr3[i13] = fArr3[i12] - f4; - fArr2[i12] = fArr2[i12] + f3; - fArr3[i12] = f4 + fArr3[i12]; - } - i9 = i10 + i6; - } else { - break; - } - } - i5 = i6 << 1; - } - int i14 = i2 * 48; - int i15 = 0; - while (true) { - int i16 = i15; - if (i16 >= 48) { - break; - } - float f5 = 0.0f; - for (int i17 = this.bandLo[i16]; i17 < this.bandHi[i16]; i17++) { - float f6 = (fArr2[i17] * fArr2[i17]) + (fArr3[i17] * fArr3[i17]); - if (f6 > f5) { - f5 = f6; - } - } - double dLog10 = (((Math.log10((((double) f5) / 65536.0d) + 1.0E-12d) * 10.0d) + 62.0d) / 56.0d) + (((double) i16) * 0.004d); - if (dLog10 < 0.0d) { - dLog10 = 0.0d; - } - if (dLog10 > 1.0d) { - dLog10 = 1.0d; - } - bArr[i14 + i16] = (byte) (dLog10 * 255.0d); - i15 = i16 + 1; - } - int iMax = Math.max(1, (int) Math.floor(35840.0d / ((double) Math.max(1, this.tableRate)))); - int iMax2 = Math.max(iMax, (int) Math.ceil(153600.0d / ((double) Math.max(1, this.tableRate)))); - double d = 0.0d; - while (iMax <= iMax2 && iMax < 512) { - d += (double) ((fArr2[iMax] * fArr2[iMax]) + (fArr3[iMax] * fArr3[iMax])); - iMax++; - } - double dLog11 = ((10.0d * Math.log10((d / 65536.0d) + 1.0E-12d)) + 36.0d) / 42.0d; - if (dLog11 < 0.0d) { - dLog11 = 0.0d; - } - if (dLog11 > 1.0d) { - dLog11 = 1.0d; - } - if (i2 < bArr2.length) { - bArr2[i2] = (byte) (dLog11 * 255.0d); - } - zArr[i2] = true; - } - } -} diff --git a/android/src/com/mulberry/player/TagCore.java b/android/src/com/mulberry/player/TagCore.java deleted file mode 100644 index 842c9d8..0000000 --- a/android/src/com/mulberry/player/TagCore.java +++ /dev/null @@ -1,363 +0,0 @@ -package com.mulberry.player; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.jaudiotagger.audio.AudioFile; -import org.jaudiotagger.audio.AudioFileIO; -import org.jaudiotagger.audio.AudioHeader; -import org.jaudiotagger.audio.flac.metadatablock.MetadataBlockDataPicture; -import org.jaudiotagger.tag.FieldKey; -import org.jaudiotagger.tag.Tag; -import org.jaudiotagger.tag.datatype.Artwork; -import org.jaudiotagger.tag.datatype.DataTypes; -import org.jaudiotagger.tag.flac.FlacTag; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; -import org.jaudiotagger.tag.id3.valuepair.ImageFormats; -import org.jaudiotagger.tag.vorbiscomment.VorbisCommentFieldKey; -import org.jaudiotagger.tag.vorbiscomment.VorbisCommentTag; - -/* JADX INFO: loaded from: classes.dex */ -public final class TagCore { - public static final String[][] FIELDS = {new String[]{"title", "Title"}, new String[]{"artist", "Artist"}, new String[]{"album", "Album"}, new String[]{"albumartist", "Album artist"}, new String[]{"genre", DataTypes.OBJ_GENRE}, new String[]{"composer", "Composer"}, new String[]{"year", "Year"}, new String[]{"track", "Track"}, new String[]{"disc", "Disc"}, new String[]{"comment", "Comment"}}; - public static final String[] WRITABLE = {"mp3", "m4a", "m4b", "m4p", "mp4", "flac", "ogg", "oga", "wma", "opus", "wav", "wave", "aif", "aiff", "aifc", "aac"}; - private static Logger quiet; - - public static final class Info { - public byte[] cover; - public int lengthSec; - public int sampleRate; - public final Map fields = new LinkedHashMap(); - public String lyrics = FrameBodyCOMM.DEFAULT; - public String coverMime = FrameBodyCOMM.DEFAULT; - public String format = FrameBodyCOMM.DEFAULT; - public String bitrate = FrameBodyCOMM.DEFAULT; - public String channels = FrameBodyCOMM.DEFAULT; - } - - static { - try { - quiet = Logger.getLogger("org.jaudiotagger"); - quiet.setLevel(Level.OFF); - } catch (Throwable th) { - } - } - - private TagCore() { - } - - public static boolean canWrite(String str) { - if (str == null) { - return false; - } - String lowerCase = str.toLowerCase(Locale.ROOT); - for (String str2 : WRITABLE) { - if (str2.equals(lowerCase)) { - return true; - } - } - return false; - } - - static FieldKey key(String str) { - if ("title".equals(str)) { - return FieldKey.TITLE; - } - if ("artist".equals(str)) { - return FieldKey.ARTIST; - } - if ("album".equals(str)) { - return FieldKey.ALBUM; - } - if ("albumartist".equals(str)) { - return FieldKey.ALBUM_ARTIST; - } - if ("genre".equals(str)) { - return FieldKey.GENRE; - } - if ("composer".equals(str)) { - return FieldKey.COMPOSER; - } - if ("year".equals(str)) { - return FieldKey.YEAR; - } - if ("track".equals(str)) { - return FieldKey.TRACK; - } - if ("disc".equals(str)) { - return FieldKey.DISC_NO; - } - if ("comment".equals(str)) { - return FieldKey.COMMENT; - } - if ("mb_trackid".equals(str)) { - return FieldKey.MUSICBRAINZ_TRACK_ID; - } - if ("mb_albumid".equals(str)) { - return FieldKey.MUSICBRAINZ_RELEASEID; - } - if ("lyrics".equals(str)) { - return FieldKey.LYRICS; - } - return null; - } - - static String first(Tag tag, FieldKey fieldKey) { - try { - String first = tag.getFirst(fieldKey); - return first == null ? FrameBodyCOMM.DEFAULT : first.trim(); - } catch (Throwable th) { - return FrameBodyCOMM.DEFAULT; - } - } - - static String extOf(File file) { - String name = file.getName(); - int iLastIndexOf = name.lastIndexOf(46); - return iLastIndexOf > 0 ? name.substring(iLastIndexOf + 1).toLowerCase(Locale.ROOT) : FrameBodyCOMM.DEFAULT; - } - - static boolean isChunk(String str) { - return "wav".equals(str) || "wave".equals(str) || "aif".equals(str) || "aiff".equals(str) || "aifc".equals(str) || "aac".equals(str); - } - - static boolean isOpus(File file, String str) { - return "opus".equals(str) || (("ogg".equals(str) || "oga".equals(str)) && OggOpus.isOpus(file)); - } - - public static Info read(File file) throws Exception { - String strExtOf = extOf(file); - if (isOpus(file, strExtOf)) { - return OggOpus.read(file); - } - if (isChunk(strExtOf)) { - return ChunkId3.read(file); - } - AudioFile audioFile = AudioFileIO.read(file); - Info info = new Info(); - fillInfo(audioFile.getTag(), info); - try { - AudioHeader audioHeader = audioFile.getAudioHeader(); - info.format = audioHeader.getFormat(); - info.bitrate = audioHeader.getBitRate(); - info.sampleRate = audioHeader.getSampleRateAsNumber(); - info.channels = audioHeader.getChannels(); - info.lengthSec = audioHeader.getTrackLength(); - return info; - } catch (Throwable th) { - return info; - } - } - - static void fillInfo(Tag tag, Info info) { - String strFirst; - for (String[] strArr : FIELDS) { - String strFirst2 = tag == null ? FrameBodyCOMM.DEFAULT : first(tag, key(strArr[0])); - if (("track".equals(strArr[0]) || "disc".equals(strArr[0])) && strFirst2.length() > 0) { - if (tag == null) { - strFirst = FrameBodyCOMM.DEFAULT; - } else { - strFirst = first(tag, "track".equals(strArr[0]) ? FieldKey.TRACK_TOTAL : FieldKey.DISC_TOTAL); - } - if (strFirst.length() > 0 && !"0".equals(strFirst) && !strFirst2.contains("/")) { - strFirst2 = strFirst2 + "/" + strFirst; - } - } - info.fields.put(strArr[0], strFirst2); - } - if (tag != null) { - info.lyrics = first(tag, FieldKey.LYRICS); - try { - Artwork firstArtwork = tag.getFirstArtwork(); - if (firstArtwork != null && firstArtwork.getBinaryData() != null && firstArtwork.getBinaryData().length > 0) { - info.cover = firstArtwork.getBinaryData(); - info.coverMime = firstArtwork.getMimeType() == null ? FrameBodyCOMM.DEFAULT : firstArtwork.getMimeType(); - } - } catch (Throwable th) { - } - } - } - - public static void write(File file, Map map, byte[] bArr, String str, int i, int i2, boolean z, String str2) throws Exception { - String strSniffMime; - String strExtOf = extOf(file); - if (bArr == null) { - strSniffMime = null; - } else { - strSniffMime = (str == null || str.length() == 0) ? sniffMime(bArr) : str; - } - if (!isOpus(file, strExtOf)) { - if (!isChunk(strExtOf)) { - AudioFile audioFile = AudioFileIO.read(file); - Tag tagOrCreateAndSetDefault = audioFile.getTagOrCreateAndSetDefault(); - if (tagOrCreateAndSetDefault == null) { - throw new Exception("this file can't hold tags"); - } - apply(tagOrCreateAndSetDefault, map, bArr, strSniffMime, i, i2, z, str2); - audioFile.commit(); - return; - } - ChunkId3.write(file, map, bArr, strSniffMime, z, str2); - return; - } - OggOpus.write(file, map, bArr, strSniffMime, i, i2, z, str2); - } - - static void apply(Tag tag, Map map, byte[] bArr, String str, int i, int i2, boolean z, String str2) throws Exception { - for (Map.Entry entry : map.entrySet()) { - String key = entry.getKey(); - String strTrim = entry.getValue() == null ? FrameBodyCOMM.DEFAULT : entry.getValue().trim(); - if ("track".equals(key) || "disc".equals(key)) { - setNumber(tag, key, strTrim); - } else { - FieldKey fieldKeyKey = key(key); - if (fieldKeyKey != null) { - set(tag, fieldKeyKey, strTrim); - } - } - } - if (str2 != null) { - set(tag, FieldKey.LYRICS, str2); - } - if (z || bArr != null) { - try { - tag.deleteArtworkField(); - } catch (Throwable th) { - } - if (tag instanceof FlacTag) { - try { - ((FlacTag) tag).getVorbisCommentTag().deleteArtworkField(); - } catch (Throwable th2) { - } - } - } - if (bArr != null) { - if (tag instanceof FlacTag) { - FlacTag flacTag = (FlacTag) tag; - flacTag.setField(flacTag.createArtworkField(bArr, 3, str, FrameBodyCOMM.DEFAULT, i, i2, 24, 0)); - } else { - if (tag instanceof VorbisCommentTag) { - VorbisCommentTag vorbisCommentTag = (VorbisCommentTag) tag; - vorbisCommentTag.setField(vorbisCommentTag.createField(VorbisCommentFieldKey.METADATA_BLOCK_PICTURE, B64.encode(new MetadataBlockDataPicture(bArr, 3, str, FrameBodyCOMM.DEFAULT, i, i2, 24, 0).getRawContent()))); - return; - } - Artwork artwork = new Artwork(); - artwork.setBinaryData(bArr); - artwork.setMimeType(str); - artwork.setPictureType(3); - artwork.setDescription(FrameBodyCOMM.DEFAULT); - tag.setField(artwork); - } - } - } - - static void set(Tag tag, FieldKey fieldKey, String str) throws Exception { - if (str.length() == 0) { - try { - tag.deleteField(fieldKey); - } catch (Throwable th) { - } - } else { - tag.setField(fieldKey, str); - } - } - - static void setNumber(Tag tag, String str, String str2) throws Exception { - FieldKey fieldKey = "track".equals(str) ? FieldKey.TRACK : FieldKey.DISC_NO; - FieldKey fieldKey2 = "track".equals(str) ? FieldKey.TRACK_TOTAL : FieldKey.DISC_TOTAL; - String strTrim = FrameBodyCOMM.DEFAULT; - int iIndexOf = str2.indexOf(47); - if (iIndexOf >= 0) { - String strTrim2 = str2.substring(0, iIndexOf).trim(); - strTrim = str2.substring(iIndexOf + 1).trim(); - str2 = strTrim2; - } - String strReplaceAll = str2.replaceAll("[^0-9]", FrameBodyCOMM.DEFAULT); - String strReplaceAll2 = strTrim.replaceAll("[^0-9]", FrameBodyCOMM.DEFAULT); - String strValueOf = strReplaceAll.length() > 0 ? String.valueOf(Integer.parseInt(strReplaceAll)) : strReplaceAll; - String strValueOf2 = strReplaceAll2.length() > 0 ? String.valueOf(Integer.parseInt(strReplaceAll2)) : strReplaceAll2; - if (strValueOf.length() == 0 || "0".equals(strValueOf)) { - try { - tag.deleteField(fieldKey); - } catch (Throwable th) { - } - try { - tag.deleteField(fieldKey2); - return; - } catch (Throwable th2) { - return; - } - } - tag.setField(fieldKey, strValueOf); - if (strValueOf2.length() <= 0 || "0".equals(strValueOf2)) { - if (iIndexOf >= 0) { - try { - tag.deleteField(fieldKey2); - return; - } catch (Throwable th3) { - return; - } - } - return; - } - tag.setField(fieldKey2, strValueOf2); - } - - public static String sniffMime(byte[] bArr) { - if (bArr.length > 8 && (bArr[0] & 255) == 137 && bArr[1] == 80 && bArr[2] == 78 && bArr[3] == 71) { - return ImageFormats.MIME_TYPE_PNG; - } - return (bArr.length > 12 && bArr[0] == 82 && bArr[1] == 73 && bArr[2] == 70 && bArr[3] == 70 && bArr[8] == 87) ? "image/webp" : ImageFormats.MIME_TYPE_JPEG; - } - - public static final class B64 { - private static final char[] A = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); - - public static byte[] decode(String str) { - int[] iArr = new int[128]; - Arrays.fill(iArr, -1); - for (int i = 0; i < A.length; i++) { - iArr[A[i]] = i; - } - iArr[45] = 62; - iArr[95] = 63; - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream((str.length() * 3) / 4); - int i2 = 0; - int i3 = 0; - for (int i4 = 0; i4 < str.length(); i4++) { - char cCharAt = str.charAt(i4); - if (cCharAt < 128 && iArr[cCharAt] >= 0) { - i3 = (i3 << 6) | iArr[cCharAt]; - i2 += 6; - if (i2 >= 8) { - i2 -= 8; - byteArrayOutputStream.write((i3 >> i2) & 255); - } - } - } - return byteArrayOutputStream.toByteArray(); - } - - public static String encode(byte[] bArr) { - StringBuilder sb = new StringBuilder(((bArr.length + 2) / 3) * 4); - for (int i = 0; i < bArr.length; i += 3) { - int i2 = (bArr[i] & 255) << 16; - if (i + 1 < bArr.length) { - i2 |= (bArr[i + 1] & 255) << 8; - } - if (i + 2 < bArr.length) { - i2 |= bArr[i + 2] & 255; - } - sb.append(A[(i2 >> 18) & 63]).append(A[(i2 >> 12) & 63]); - sb.append(i + 1 < bArr.length ? A[(i2 >> 6) & 63] : '='); - sb.append(i + 2 < bArr.length ? A[i2 & 63] : '='); - } - return sb.toString(); - } - } -} diff --git a/android/src/com/mulberry/player/TagEditorActivity.java b/android/src/com/mulberry/player/TagEditorActivity.java deleted file mode 100644 index a47b4c7..0000000 --- a/android/src/com/mulberry/player/TagEditorActivity.java +++ /dev/null @@ -1,1308 +0,0 @@ -package com.mulberry.player; - -import android.app.Activity; -import android.app.AlertDialog; -import android.app.PendingIntent; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.IntentSender; -import android.content.res.ColorStateList; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.drawable.ColorDrawable; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.view.View; -import android.view.ViewGroup; -import android.view.Window; -import android.view.WindowInsets; -import android.widget.AdapterView; -import android.widget.BaseAdapter; -import android.widget.CheckBox; -import android.widget.EditText; -import android.widget.FrameLayout; -import android.widget.GridView; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ListAdapter; -import android.widget.ListView; -import android.widget.ProgressBar; -import android.widget.ScrollView; -import android.widget.TextView; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import org.jaudiotagger.tag.datatype.DataTypes; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; - -/* JADX INFO: loaded from: classes.dex */ -public class TagEditorActivity extends Activity { - public static final int MODE_BATCH = 3; - public static final int MODE_EDIT = 0; - public static final int MODE_LYRICS = 2; - public static final int MODE_MB = 1; - static List PENDING = new ArrayList(); - static final int REQ_IMAGE = 1; - static final int REQ_LEGACY = 4; - static final int REQ_RECOVER = 3; - static final int REQ_WRITE = 2; - Runnable afterGrant; - volatile boolean cancelled; - ImageView coverView; - LinearLayout form; - TextView infoText; - int insetBottom; - int insetTop; - EditText lyricsEdit; - int mode; - byte[] newCover; - boolean removeCover; - View rootView; - CheckBox saveLrc; - List songs; - TextView status; - final Map edits = new LinkedHashMap(); - final Map orig = new HashMap(); - final Set multi = new LinkedHashSet(); - String origLyrics = FrameBodyCOMM.DEFAULT; - String mbTrack = FrameBodyCOMM.DEFAULT; - String mbAlbum = FrameBodyCOMM.DEFAULT; - final Map> plan = new LinkedHashMap(); - - public static void open(Context context, List list, int i) { - PENDING = new ArrayList(list); - context.startActivity(new Intent(context, (Class) TagEditorActivity.class).putExtra("mode", i)); - } - - @Override // android.app.Activity - protected void onCreate(Bundle bundle) { - super.onCreate(bundle); - this.songs = PENDING; - this.mode = getIntent().getIntExtra("mode", 0); - if (this.songs != null && !this.songs.isEmpty()) { - Window window = getWindow(); - window.setStatusBarColor(0); - window.setNavigationBarColor(0); - window.getDecorView().setSystemUiVisibility((App.I.palette.dark ? 0 : 8192 /* SYSTEM_UI_FLAG_LIGHT_STATUS_BAR */) | 1792); - if (this.mode != 3) { - buildEditor(); - return; - } else { - buildBatch(); - return; - } - } - finish(); - } - - @Override // android.app.Activity - protected void onDestroy() { - this.cancelled = true; - super.onDestroy(); - } - - LinearLayout frame(String str, String str2, String str3, View.OnClickListener onClickListener) { - FrameLayout frameLayout = new FrameLayout(this); - Ui.plain(frameLayout, 6); - final LinearLayout linearLayoutCol = Ui.col(this); - frameLayout.addView(linearLayoutCol, new FrameLayout.LayoutParams(-1, -1)); - LinearLayout linearLayoutRow = Ui.row(this); - linearLayoutRow.setPadding(Ui.dp(this, 6.0f), Ui.dp(this, 6.0f), Ui.dp(this, 12.0f), Ui.dp(this, 6.0f)); - linearLayoutRow.addView(Ui.iconButton(this, R.drawable.ic_close, 11, 44, new View.OnClickListener() { // from class: com.mulberry.player.TagEditorActivity.1 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - TagEditorActivity.this.finish(); - } - })); - LinearLayout linearLayoutCol2 = Ui.col(this); - linearLayoutCol2.setPadding(Ui.dp(this, 8.0f), 0, 0, 0); - linearLayoutCol2.addView(Ui.single(this, str, 20.0f, 11, true)); - linearLayoutCol2.addView(Ui.single(this, str2, 13.0f, 12, false)); - linearLayoutRow.addView(linearLayoutCol2, Ui.lpw(-2, 1.0f)); - if (str3 != null) { - linearLayoutRow.addView(Ui.pill(this, R.drawable.ic_save, str3, true, onClickListener)); - } - linearLayoutCol.addView(linearLayoutRow); - frameLayout.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() { // from class: com.mulberry.player.TagEditorActivity.2 - @Override // android.view.View.OnApplyWindowInsetsListener - public WindowInsets onApplyWindowInsets(View view, WindowInsets windowInsets) { - linearLayoutCol.setPadding(0, windowInsets.getSystemWindowInsetTop(), 0, windowInsets.getSystemWindowInsetBottom()); - return windowInsets.consumeSystemWindowInsets(); - } - }); - setContentView(frameLayout); - this.rootView = frameLayout; - return linearLayoutCol; - } - - void buildEditor() { - LinearLayout linearLayoutFrame = frame(this.mode == 2 ? "Edit lyrics" : "Edit tags", this.songs.size() == 1 ? this.songs.get(0).displayTitle() : this.songs.size() + " files", "Save", new View.OnClickListener() { // from class: com.mulberry.player.TagEditorActivity.3 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - TagEditorActivity.this.save(); - } - }); - final ScrollView scrollView = new ScrollView(this); - scrollView.setClipToPadding(false); - this.form = Ui.col(this); - this.form.setPadding(Ui.dp(this, 18.0f), Ui.dp(this, 4.0f), Ui.dp(this, 18.0f), Ui.dp(this, 40.0f)); - scrollView.addView(this.form); - linearLayoutFrame.addView(scrollView, Ui.lp(-1, 0)); - ((LinearLayout.LayoutParams) scrollView.getLayoutParams()).weight = 1.0f; - LinearLayout linearLayoutRow = Ui.row(this); - linearLayoutRow.setGravity(48); - this.coverView = Lists.coverView(this, 132, 28.0f); - linearLayoutRow.addView(this.coverView); - LinearLayout linearLayoutCol = Ui.col(this); - linearLayoutCol.setPadding(Ui.dp(this, 14.0f), 0, 0, 0); - linearLayoutCol.addView(smallBtn(R.drawable.ic_image, "Load image…", new View.OnClickListener() { // from class: com.mulberry.player.TagEditorActivity.4 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - TagEditorActivity.this.pickImage(); - } - })); - linearLayoutCol.addView(smallBtn(R.drawable.ic_search, "Search online…", new View.OnClickListener() { // from class: com.mulberry.player.TagEditorActivity.5 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - TagEditorActivity.this.searchCovers(); - } - })); - linearLayoutCol.addView(smallBtn(R.drawable.ic_delete, "Remove cover", new View.OnClickListener() { // from class: com.mulberry.player.TagEditorActivity.6 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - TagEditorActivity.this.newCover = null; - TagEditorActivity.this.removeCover = true; - TagEditorActivity.this.showCover(null); - } - })); - linearLayoutRow.addView(linearLayoutCol, Ui.lpw(-2, 1.0f)); - this.form.addView(linearLayoutRow); - LinearLayout linearLayoutRow2 = Ui.row(this); - linearLayoutRow2.setPadding(0, Ui.dp(this, 14.0f), 0, Ui.dp(this, 6.0f)); - linearLayoutRow2.addView(Ui.pill(this, R.drawable.ic_cloud_download, "Fetch from MusicBrainz", true, new View.OnClickListener() { // from class: com.mulberry.player.TagEditorActivity.7 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - TagEditorActivity.this.musicBrainz(); - } - })); - this.form.addView(linearLayoutRow2); - this.status = Ui.text(this, "Reading tags…", 13.0f, 12, false); - this.form.addView(this.status); - for (String[] strArr : TagCore.FIELDS) { - TextView textViewSingle = Ui.single(this, strArr[1], 13.0f, 0, true); - textViewSingle.setPadding(Ui.dp(this, 6.0f), Ui.dp(this, 12.0f), 0, Ui.dp(this, 4.0f)); - this.form.addView(textViewSingle); - EditText editTextField = Ui.field(this, FrameBodyCOMM.DEFAULT, FrameBodyCOMM.DEFAULT); - editTextField.setSingleLine(!"comment".equals(strArr[0])); - if ("year".equals(strArr[0])) { - editTextField.setInputType(2); - } - if ("track".equals(strArr[0]) || "disc".equals(strArr[0])) { - editTextField.setInputType(1); - editTextField.setHint("e.g. 3 or 3/12"); - } - editTextField.setEnabled(false); - this.edits.put(strArr[0], editTextField); - this.form.addView(editTextField); - } - if (this.songs.size() == 1) { - TextView textViewSingle2 = Ui.single(this, DataTypes.OBJ_LYRICS, 13.0f, 0, true); - textViewSingle2.setPadding(Ui.dp(this, 6.0f), Ui.dp(this, 16.0f), 0, Ui.dp(this, 4.0f)); - this.form.addView(textViewSingle2); - this.lyricsEdit = Ui.field(this, "Paste plain or synced (.lrc) lyrics", FrameBodyCOMM.DEFAULT); - this.lyricsEdit.setSingleLine(false); - this.lyricsEdit.setMinLines(6); - this.lyricsEdit.setGravity(48); - this.lyricsEdit.setInputType(131073); - this.lyricsEdit.setEnabled(false); - this.form.addView(this.lyricsEdit); - LinearLayout linearLayoutRow3 = Ui.row(this); - linearLayoutRow3.setPadding(0, Ui.dp(this, 8.0f), 0, 0); - linearLayoutRow3.addView(smallBtn(R.drawable.ic_lyrics, "Use found lyrics", new View.OnClickListener() { // from class: com.mulberry.player.TagEditorActivity.8 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - TagEditorActivity.this.useFoundLyrics(); - } - })); - this.form.addView(linearLayoutRow3); - this.saveLrc = new CheckBox(this); - this.saveLrc.setText("Also save as .lrc next to the song"); - this.saveLrc.setTextColor(Ui.c(11)); - this.saveLrc.setButtonTintList(ColorStateList.valueOf(Ui.c(0))); - this.form.addView(this.saveLrc); - this.infoText = Ui.text(this, FrameBodyCOMM.DEFAULT, 12.5f, 12, false); - this.infoText.setPadding(Ui.dp(this, 6.0f), Ui.dp(this, 16.0f), 0, 0); - this.infoText.setTextIsSelectable(true); - this.form.addView(this.infoText); - } - load(); - if (this.mode == 2 && this.lyricsEdit != null) { - scrollView.post(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.9 - @Override // java.lang.Runnable - public void run() { - scrollView.smoothScrollTo(0, TagEditorActivity.this.lyricsEdit.getTop() - Ui.dp(TagEditorActivity.this, 40.0f)); - } - }); - } - } - - View smallBtn(int i, String str, View.OnClickListener onClickListener) { - LinearLayout linearLayoutPill = Ui.pill(this, i, str, false, onClickListener); - LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(-2, -2); - layoutParams.bottomMargin = Ui.dp(this, 8.0f); - linearLayoutPill.setLayoutParams(layoutParams); - return linearLayoutPill; - } - - void showCover(Bitmap bitmap) { - if (bitmap != null) { - this.coverView.setPadding(0, 0, 0, 0); - this.coverView.setImageTintList(null); - this.coverView.setImageBitmap(bitmap); - return; - } - Lists.placeholder(this.coverView); - } - - void load() { - App.IO.execute(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.10 - @Override // java.lang.Runnable - public void run() { - final ArrayList arrayList = new ArrayList(); - final ArrayList arrayList2 = new ArrayList(); - for (int i = 0; i < TagEditorActivity.this.songs.size() && !TagEditorActivity.this.cancelled; i++) { - final int i2 = i + 1; - if (TagEditorActivity.this.songs.size() > 3) { - App.ui(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.10.1 - @Override // java.lang.Runnable - public void run() { - TagEditorActivity.this.status.setText("Reading tags " + i2 + "/" + TagEditorActivity.this.songs.size() + "…"); - } - }); - } - try { - arrayList.add(Tagger.read(TagEditorActivity.this, TagEditorActivity.this.songs.get(i))); - } catch (Throwable th) { - arrayList.add(null); - arrayList2.add(TagEditorActivity.this.songs.get(i).displayTitle() + ": " + th.getMessage()); - } - } - TagCore.Info info = arrayList.isEmpty() ? null : (TagCore.Info) arrayList.get(0); - Bitmap bitmapDecodeStreamV = (info == null || info.cover == null) ? null : Covers.decodeStream(info.cover, 400); - if (bitmapDecodeStreamV == null) { - bitmapDecodeStreamV = Covers.loadBlocking(TagEditorActivity.this.songs.get(0), 400, false); - } - final Bitmap bitmapDecodeStream = bitmapDecodeStreamV; - App.ui(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.10.2 - @Override // java.lang.Runnable - public void run() { - String str; - if (!TagEditorActivity.this.isFinishing() && !TagEditorActivity.this.isDestroyed()) { - TagEditorActivity.this.fill(arrayList); - TagEditorActivity.this.showCover(bitmapDecodeStream); - TextView textView = TagEditorActivity.this.status; - if (!arrayList2.isEmpty()) { - str = "Some files couldn't be read: " + ((String) arrayList2.get(0)); - } else if (TagEditorActivity.this.songs.size() > 1) { - str = "Editing " + TagEditorActivity.this.songs.size() + " files — fields that differ are empty; type to change them for all."; - } else { - str = FrameBodyCOMM.DEFAULT; - } - textView.setText(str); - if (TagEditorActivity.this.status.getText().length() == 0) { - TagEditorActivity.this.status.setVisibility(8); - } - if (TagEditorActivity.this.mode == 1) { - TagEditorActivity.this.musicBrainz(); - } - } - } - }); - } - }); - } - - void fill(List list) { - String str; - for (String[] strArr : TagCore.FIELDS) { - LinkedHashSet linkedHashSet = new LinkedHashSet(); - for (int i = 0; i < list.size(); i++) { - TagCore.Info info = list.get(i); - if (info == null) { - str = FrameBodyCOMM.DEFAULT; - } else { - str = info.fields.containsKey(strArr[0]) ? info.fields.get(strArr[0]) : FrameBodyCOMM.DEFAULT; - } - linkedHashSet.add(str); - } - EditText editText = this.edits.get(strArr[0]); - editText.setEnabled(true); - if (linkedHashSet.size() == 1) { - String str2 = (String) linkedHashSet.iterator().next(); - editText.setText(str2); - this.orig.put(strArr[0], str2); - } else { - editText.setText(FrameBodyCOMM.DEFAULT); - editText.setHint("(multiple values — leave empty to keep)"); - this.orig.put(strArr[0], FrameBodyCOMM.DEFAULT); - this.multi.add(strArr[0]); - } - } - if (this.songs.size() == 1 && list.get(0) != null) { - TagCore.Info info2 = list.get(0); - this.origLyrics = info2.lyrics == null ? FrameBodyCOMM.DEFAULT : info2.lyrics; - this.lyricsEdit.setText(this.origLyrics); - this.lyricsEdit.setEnabled(true); - Song song = this.songs.get(0); - String upperCase = Tagger.ext(this, song).toUpperCase(); - StringBuilder sb = new StringBuilder(); - if (upperCase.length() <= 0) { - upperCase = info2.format; - } - sb.append(upperCase); - if (info2.lengthSec > 0) { - sb.append(" · ").append(Draw.time(((long) info2.lengthSec) * 1000)); - } - if (info2.bitrate != null && info2.bitrate.length() > 0) { - sb.append(" · ").append(info2.bitrate.replace("~", FrameBodyCOMM.DEFAULT)).append(" kbps"); - } - if (info2.sampleRate > 0) { - sb.append(" · ").append(info2.sampleRate).append(" Hz"); - } - if (info2.channels != null && info2.channels.length() > 0) { - sb.append(" · ").append(info2.channels.toLowerCase().contains("stereo") ? "stereo" : info2.channels); - } - sb.append("\n").append(info2.format); - if (song.path.length() > 0) { - sb.append("\n").append(song.path); - } - this.infoText.setText(sb.toString()); - return; - } - if (this.songs.size() == 1) { - this.lyricsEdit.setEnabled(true); - } - } - - void useFoundLyrics() { - MusicService musicService = MusicService.INSTANCE; - Song song = this.songs.get(0); - if (musicService != null && musicService.current() != null && musicService.current().key().equals(song.key()) && musicService.lyrics != null && !musicService.lyrics.lines.isEmpty()) { - this.lyricsEdit.setText(toLrc(musicService.lyrics)); - } else { - MainActivity.toast("Searching lyrics…"); - Lyrics.load(song, false, new Lyrics.Cb() { // from class: com.mulberry.player.TagEditorActivity.11 - @Override // com.mulberry.player.Lyrics.Cb - public void done(Lyrics.Result result) { - if (result.lines.isEmpty()) { - MainActivity.toast(result.message.length() > 0 ? result.message : "No lyrics found"); - } else { - TagEditorActivity.this.lyricsEdit.setText(TagEditorActivity.toLrc(result)); - } - } - }); - } - } - - static String toLrc(Lyrics.Result result) { - StringBuilder sb = new StringBuilder(); - for (Lyrics.Line line : result.lines) { - if (result.synced) { - long j = line.ms; - sb.append(String.format(Locale.ROOT, "[%02d:%02d.%02d]", Long.valueOf(j / 60000), Long.valueOf((j / 1000) % 60), Long.valueOf((j / 10) % 100))); - } - sb.append(line.text).append('\n'); - } - return sb.toString().trim(); - } - - void pickImage() { - Intent intent = new Intent("android.intent.action.GET_CONTENT"); - intent.setType("image/*"); - intent.addCategory("android.intent.category.OPENABLE"); - try { - startActivityForResult(Intent.createChooser(intent, "Choose cover"), 1); - } catch (Exception e) { - MainActivity.toast("No image picker"); - } - } - - static byte[] normalizeImage(byte[] bArr) { - int i = 1; - try { - BitmapFactory.Options options = new BitmapFactory.Options(); - options.inJustDecodeBounds = true; - BitmapFactory.decodeByteArray(bArr, 0, bArr.length, options); - if (options.outWidth <= 0) { - return null; - } - String strSniffMime = TagCore.sniffMime(bArr); - if (bArr.length > 1500000 || Math.max(options.outWidth, options.outHeight) > 1600 || "image/webp".equals(strSniffMime)) { - while (Math.max(options.outWidth, options.outHeight) / (i * 2) >= 1200) { - i *= 2; - } - BitmapFactory.Options options2 = new BitmapFactory.Options(); - options2.inSampleSize = i; - Bitmap bitmapDecodeByteArray = BitmapFactory.decodeByteArray(bArr, 0, bArr.length, options2); - if (bitmapDecodeByteArray == null) { - return null; - } - int iMax = Math.max(bitmapDecodeByteArray.getWidth(), bitmapDecodeByteArray.getHeight()); - if (iMax > 1400) { - float f = 1400.0f / iMax; - bitmapDecodeByteArray = Bitmap.createScaledBitmap(bitmapDecodeByteArray, Math.round(bitmapDecodeByteArray.getWidth() * f), Math.round(f * bitmapDecodeByteArray.getHeight()), true); - } - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - bitmapDecodeByteArray.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream); - return byteArrayOutputStream.toByteArray(); - } - return bArr; - } catch (Throwable th) { - return null; - } - } - - void setNewCover(final byte[] bArr) { - App.IO.execute(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.12 - @Override // java.lang.Runnable - public void run() { - final byte[] bArrNormalizeImage = TagEditorActivity.normalizeImage(bArr); - final Bitmap bitmapDecodeStream = bArrNormalizeImage == null ? null : Covers.decodeStream(bArrNormalizeImage, 400); - App.ui(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.12.1 - @Override // java.lang.Runnable - public void run() { - if (!TagEditorActivity.this.isFinishing() && !TagEditorActivity.this.isDestroyed()) { - if (bArrNormalizeImage != null) { - TagEditorActivity.this.newCover = bArrNormalizeImage; - TagEditorActivity.this.removeCover = false; - TagEditorActivity.this.showCover(bitmapDecodeStream); - return; - } - MainActivity.toast("That image couldn't be read"); - } - } - }); - } - }); - } - - void searchCovers() { - String strText; - Song song = this.songs.get(0); - if (text("albumartist").length() > 0) { - strText = text("albumartist"); - } else { - strText = text("artist").length() > 0 ? text("artist") : song.displayArtist(); - } - String strText2 = text("album").length() > 0 ? text("album") : song.album; - String strText3 = text("title").length() > 0 ? text("title") : song.displayTitle(); - LinearLayout linearLayoutCol = Ui.col(this); - linearLayoutCol.setPadding(Ui.dp(this, 12.0f), Ui.dp(this, 4.0f), Ui.dp(this, 12.0f), 0); - TextView textViewText = Ui.text(this, "Searching iTunes, Deezer, Cover Art Archive and Last.fm…", 13.0f, 12, false); - textViewText.setPadding(Ui.dp(this, 8.0f), 0, 0, Ui.dp(this, 8.0f)); - linearLayoutCol.addView(textViewText); - GridView gridView = new GridView(this); - gridView.setNumColumns(3); - gridView.setVerticalSpacing(Ui.dp(this, 8.0f)); - gridView.setHorizontalSpacing(Ui.dp(this, 8.0f)); - gridView.setSelector(new ColorDrawable(0)); - linearLayoutCol.addView(gridView, new LinearLayout.LayoutParams(-1, (int) (getResources().getDisplayMetrics().heightPixels * 0.5f))); - App.IO.execute(new AnonymousClass13(strText, strText2, strText3, new AlertDialog[]{Ui.show(Ui.dialog(this).setTitle("Find a cover").setView(linearLayoutCol).setNegativeButton("Close", (DialogInterface.OnClickListener) null))}, textViewText, gridView)); - } - - /* JADX INFO: renamed from: com.mulberry.player.TagEditorActivity$13, reason: invalid class name */ - class AnonymousClass13 implements Runnable { - final /* synthetic */ AlertDialog[] val$dlg; - final /* synthetic */ String val$fa; - final /* synthetic */ String val$fal; - final /* synthetic */ String val$ft; - final /* synthetic */ GridView val$grid; - final /* synthetic */ TextView val$st; - - AnonymousClass13(String str, String str2, String str3, AlertDialog[] alertDialogArr, TextView textView, GridView gridView) { - this.val$fa = str; - this.val$fal = str2; - this.val$ft = str3; - this.val$dlg = alertDialogArr; - this.val$st = textView; - this.val$grid = gridView; - } - - /* JADX INFO: renamed from: com.mulberry.player.TagEditorActivity$13$1, reason: invalid class name */ - class AnonymousClass1 implements Runnable { - final /* synthetic */ List val$cands; - - AnonymousClass1(List list) { - this.val$cands = list; - } - - @Override // java.lang.Runnable - public void run() { - if (AnonymousClass13.this.val$dlg[0].isShowing()) { - AnonymousClass13.this.val$st.setText(this.val$cands.isEmpty() ? "No covers found — try editing the artist/album fields first." : this.val$cands.size() + " covers found · tap one"); - AnonymousClass13.this.val$grid.setAdapter((ListAdapter) TagEditorActivity.this.new CoverAdapter(this.val$cands)); - AnonymousClass13.this.val$grid.setOnItemClickListener(new C00031()); - } - } - - /* JADX INFO: renamed from: com.mulberry.player.TagEditorActivity$13$1$1, reason: invalid class name and collision with other inner class name */ - class C00031 implements AdapterView.OnItemClickListener { - C00031() { - } - - @Override // android.widget.AdapterView.OnItemClickListener - public void onItemClick(AdapterView adapterView, View view, int i, long j) { - final MusicBrainz.CoverCand coverCand = (MusicBrainz.CoverCand) AnonymousClass1.this.val$cands.get(i); - AnonymousClass13.this.val$st.setText("Downloading…"); - App.IO.execute(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.13.1.1.1 - @Override // java.lang.Runnable - public void run() { - byte[] bytesV = null; - try { - bytesV = Net.getBytes(coverCand.url, null); - } catch (Exception e) { - } - if (bytesV == null || bytesV.length < 1000) { - try { - bytesV = Net.getBytes(coverCand.thumb, null); - } catch (Exception e2) { - } - } - final byte[] bytes = bytesV; - App.ui(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.13.1.1.1.1 - @Override // java.lang.Runnable - public void run() { - if (bytes != null && bytes.length >= 1000) { - TagEditorActivity.this.setNewCover(bytes); - AnonymousClass13.this.val$dlg[0].dismiss(); - } else { - AnonymousClass13.this.val$st.setText("Download failed — try another"); - } - } - }); - } - }); - } - } - } - - @Override // java.lang.Runnable - public void run() { - App.ui(new AnonymousClass1(MusicBrainz.covers(this.val$fa, this.val$fal, this.val$ft))); - } - } - - class CoverAdapter extends BaseAdapter { - final List items; - - CoverAdapter(List list) { - this.items = list; - } - - @Override // android.widget.Adapter - public int getCount() { - return this.items.size(); - } - - @Override // android.widget.Adapter - public Object getItem(int i) { - return this.items.get(i); - } - - @Override // android.widget.Adapter - public long getItemId(int i) { - return i; - } - - @Override // android.widget.Adapter - public View getView(int i, View view, ViewGroup viewGroup) { - LinearLayout linearLayout; - if (view == null) { - LinearLayout linearLayoutCol = Ui.col(TagEditorActivity.this); - ImageView imageView = new ImageView(TagEditorActivity.this); - imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); - imageView.setBackground(Ui.round(Ui.c(10), Ui.dpf(TagEditorActivity.this, 14.0f))); - imageView.setClipToOutline(true); - linearLayoutCol.addView(imageView, new LinearLayout.LayoutParams(-1, Math.max(Ui.dp(TagEditorActivity.this, 80.0f), (viewGroup.getWidth() - Ui.dp(TagEditorActivity.this, 16.0f)) / 3))); - linearLayoutCol.addView(Ui.single(TagEditorActivity.this, FrameBodyCOMM.DEFAULT, 11.0f, 12, false)); - linearLayout = linearLayoutCol; - view = linearLayoutCol; - } else { - linearLayout = (LinearLayout) view; - } - final ImageView imageView2 = (ImageView) linearLayout.getChildAt(0); - final MusicBrainz.CoverCand coverCand = this.items.get(i); - ((TextView) linearLayout.getChildAt(1)).setText(coverCand.source); - imageView2.setTag(coverCand); - imageView2.setImageDrawable(null); - App.IO.execute(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.CoverAdapter.1 - @Override // java.lang.Runnable - public void run() { - Bitmap bitmapDecodeStreamV = null; - try { - bitmapDecodeStreamV = Covers.decodeStream(Net.getBytes(coverCand.thumb, null), 300); - } catch (Exception e) { - } - final Bitmap bitmapDecodeStream = bitmapDecodeStreamV; - App.ui(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.CoverAdapter.1.1 - @Override // java.lang.Runnable - public void run() { - if (imageView2.getTag() == coverCand) { - imageView2.setImageBitmap(bitmapDecodeStream); - } - } - }); - } - }); - return view; - } - } - - String text(String str) { - EditText editText = this.edits.get(str); - return editText == null ? FrameBodyCOMM.DEFAULT : editText.getText().toString().trim(); - } - - void musicBrainz() { - String strText; - Song song = this.songs.get(0); - LinearLayout linearLayoutCol = Ui.col(this); - linearLayoutCol.setPadding(Ui.dp(this, 16.0f), Ui.dp(this, 4.0f), Ui.dp(this, 16.0f), 0); - EditText editTextField = Ui.field(this, "Artist", text("artist").length() > 0 ? text("artist") : song.displayArtist()); - if (this.songs.size() == 1) { - strText = text("title").length() > 0 ? text("title") : song.displayTitle(); - } else { - strText = FrameBodyCOMM.DEFAULT; - } - EditText editTextField2 = Ui.field(this, "Title", strText); - EditText editTextField3 = Ui.field(this, "Album", text("album").length() > 0 ? text("album") : song.album); - for (EditText editText : new EditText[]{editTextField, editTextField2, editTextField3}) { - editText.setSingleLine(true); - LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(-1, -2); - layoutParams.bottomMargin = Ui.dp(this, 6.0f); - linearLayoutCol.addView(editText, layoutParams); - } - CheckBox checkBox = new CheckBox(this); - checkBox.setText("Also fetch genre"); - checkBox.setChecked(true); - checkBox.setTextColor(Ui.c(11)); - checkBox.setButtonTintList(ColorStateList.valueOf(Ui.c(0))); - linearLayoutCol.addView(checkBox); - TextView textViewText = Ui.text(this, FrameBodyCOMM.DEFAULT, 13.0f, 12, false); - linearLayoutCol.addView(textViewText); - ListView list = Lists.list(this); - linearLayoutCol.addView(list, new LinearLayout.LayoutParams(-1, (int) (getResources().getDisplayMetrics().heightPixels * 0.38f))); - AlertDialog alertDialogShow = Ui.show(Ui.dialog(this).setTitle("MusicBrainz").setView(linearLayoutCol).setPositiveButton("Search", (DialogInterface.OnClickListener) null).setNegativeButton("Close", (DialogInterface.OnClickListener) null)); - final AnonymousClass14 anonymousClass14 = new AnonymousClass14(textViewText, editTextField, editTextField2, editTextField3, song, alertDialogShow, list, checkBox); - alertDialogShow.getButton(-1).setOnClickListener(new View.OnClickListener() { // from class: com.mulberry.player.TagEditorActivity.15 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - anonymousClass14.run(); - } - }); - anonymousClass14.run(); - } - - /* JADX INFO: renamed from: com.mulberry.player.TagEditorActivity$14, reason: invalid class name */ - class AnonymousClass14 implements Runnable { - final /* synthetic */ AlertDialog val$d; - final /* synthetic */ CheckBox val$genre; - final /* synthetic */ ListView val$lv; - final /* synthetic */ EditText val$qa; - final /* synthetic */ EditText val$qal; - final /* synthetic */ EditText val$qt; - final /* synthetic */ Song val$s; - final /* synthetic */ TextView val$st; - - AnonymousClass14(TextView textView, EditText editText, EditText editText2, EditText editText3, Song song, AlertDialog alertDialog, ListView listView, CheckBox checkBox) { - this.val$st = textView; - this.val$qa = editText; - this.val$qt = editText2; - this.val$qal = editText3; - this.val$s = song; - this.val$d = alertDialog; - this.val$lv = listView; - this.val$genre = checkBox; - } - - @Override // java.lang.Runnable - public void run() { - this.val$st.setText("Searching MusicBrainz…"); - String strTrim = this.val$qa.getText().toString().trim(); - App.IO.execute(new AnonymousClass1(this.val$qt.getText().toString().trim(), strTrim, this.val$qal.getText().toString().trim())); - } - - /* JADX INFO: renamed from: com.mulberry.player.TagEditorActivity$14$1, reason: invalid class name */ - class AnonymousClass1 implements Runnable { - final /* synthetic */ String val$a; - final /* synthetic */ String val$al; - final /* synthetic */ String val$t; - - AnonymousClass1(String str, String str2, String str3) { - this.val$t = str; - this.val$a = str2; - this.val$al = str3; - } - - @Override // java.lang.Runnable - public void run() { - List arrayListV; - String messageV = null; - try { - arrayListV = MusicBrainz.search(this.val$t, this.val$a, this.val$al, TagEditorActivity.this.songs.size() == 1 ? AnonymousClass14.this.val$s.duration : 0L, 15); - } catch (Exception e) { - arrayListV = new ArrayList(); - messageV = e.getMessage(); - } - final String message = messageV; - final List arrayList = arrayListV; - App.ui(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.14.1.1 - @Override // java.lang.Runnable - public void run() { - String str; - if (AnonymousClass14.this.val$d.isShowing()) { - TextView textView = AnonymousClass14.this.val$st; - if (message != null) { - str = "Couldn't reach MusicBrainz: " + message; - } else { - str = arrayList.isEmpty() ? "No matches — try editing the search." : arrayList.size() + " results · tap one to use it"; - } - textView.setText(str); - AnonymousClass14.this.val$lv.setAdapter((ListAdapter) TagEditorActivity.this.new MbAdapter(arrayList)); - AnonymousClass14.this.val$lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { // from class: com.mulberry.player.TagEditorActivity.14.1.1.1 - @Override // android.widget.AdapterView.OnItemClickListener - public void onItemClick(AdapterView adapterView, View view, int i, long j) { - TagEditorActivity.this.applyCandidate((MusicBrainz.Cand) arrayList.get(i), AnonymousClass14.this.val$genre.isChecked()); - AnonymousClass14.this.val$d.dismiss(); - } - }); - } - } - }); - } - } - } - - class MbAdapter extends BaseAdapter { - final List items; - - MbAdapter(List list) { - this.items = list; - } - - @Override // android.widget.Adapter - public int getCount() { - return this.items.size(); - } - - @Override // android.widget.Adapter - public Object getItem(int i) { - return this.items.get(i); - } - - @Override // android.widget.Adapter - public long getItemId(int i) { - return i; - } - - @Override // android.widget.Adapter - public View getView(int i, View view, ViewGroup viewGroup) { - LinearLayout linearLayout; - if (view == null) { - LinearLayout linearLayoutCol = Ui.col(TagEditorActivity.this); - linearLayoutCol.setPadding(Ui.dp(TagEditorActivity.this, 8.0f), Ui.dp(TagEditorActivity.this, 10.0f), Ui.dp(TagEditorActivity.this, 8.0f), Ui.dp(TagEditorActivity.this, 10.0f)); - Ui.clickable(linearLayoutCol, 14.0f); - linearLayoutCol.addView(Ui.single(TagEditorActivity.this, FrameBodyCOMM.DEFAULT, 15.0f, 11, true)); - linearLayoutCol.addView(Ui.single(TagEditorActivity.this, FrameBodyCOMM.DEFAULT, 13.0f, 12, false)); - linearLayout = linearLayoutCol; - view = linearLayoutCol; - } else { - linearLayout = (LinearLayout) view; - } - MusicBrainz.Cand cand = this.items.get(i); - ((TextView) linearLayout.getChildAt(0)).setText(cand.title + " — " + cand.artist); - StringBuilder sb = new StringBuilder(cand.album); - if (cand.year > 0) { - sb.append(" (").append(cand.year).append(")"); - } - if (cand.track > 0) { - sb.append(" · track ").append(cand.track); - } - if (cand.disc > 1) { - sb.append(" · disc ").append(cand.disc); - } - if (cand.status.length() > 0) { - sb.append(" · ").append(cand.status); - } - sb.append(" · score ").append(cand.score); - ((TextView) linearLayout.getChildAt(1)).setText(sb.toString()); - linearLayout.setClickable(false); - return view; - } - } - - void applyCandidate(final MusicBrainz.Cand cand, boolean z) { - boolean z2 = this.songs.size() == 1; - set("artist", cand.artist); - set("album", cand.album); - set("albumartist", cand.albumArtist); - if (cand.year > 0) { - set("year", String.valueOf(cand.year)); - } - if (z2) { - set("title", cand.title); - if (cand.track > 0) { - set("track", String.valueOf(cand.track)); - } - if (cand.disc > 0) { - set("disc", String.valueOf(cand.disc)); - } - this.mbTrack = cand.mbTrack; - } - this.mbAlbum = cand.mbAlbum; - if (z && cand.mbAlbum.length() > 0) { - MainActivity.toast("Fetching genre…"); - App.IO.execute(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.16 - @Override // java.lang.Runnable - public void run() { - final String strGenre = MusicBrainz.genre(cand.mbAlbum); - App.ui(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.16.1 - @Override // java.lang.Runnable - public void run() { - if (strGenre.length() > 0) { - TagEditorActivity.this.set("genre", strGenre); - } - } - }); - } - }); - } - } - - void set(String str, String str2) { - if (str2 == null || str2.length() <= 0 || !this.edits.containsKey(str)) { - return; - } - this.edits.get(str).setText(str2); - } - - /* JADX WARN: Code duplicated, block: B:55:0x011b */ - void save() { - final String str; - LinkedHashMap linkedHashMap = new LinkedHashMap(); - for (Map.Entry entry : this.edits.entrySet()) { - String strTrim = entry.getValue().getText().toString().trim(); - String str2 = this.orig.containsKey(entry.getKey()) ? this.orig.get(entry.getKey()) : FrameBodyCOMM.DEFAULT; - if (this.multi.contains(entry.getKey())) { - if (strTrim.length() > 0) { - linkedHashMap.put(entry.getKey(), strTrim); - } - } else if (!strTrim.equals(str2)) { - linkedHashMap.put(entry.getKey(), strTrim); - } - } - if (this.mbTrack.length() > 0) { - linkedHashMap.put("mb_trackid", this.mbTrack); - } - if (this.mbAlbum.length() > 0) { - linkedHashMap.put("mb_albumid", this.mbAlbum); - } - if (this.lyricsEdit != null) { - String strTrim2 = this.lyricsEdit.getText().toString().trim(); - if (strTrim2.equals(this.origLyrics.trim())) { - str = null; - } else { - str = strTrim2; - } - } else { - str = null; - } - boolean z = this.saveLrc != null && this.saveLrc.isChecked() && this.lyricsEdit != null && this.lyricsEdit.getText().length() > 0; - if (!linkedHashMap.isEmpty() || this.newCover != null || this.removeCover || str != null || z) { - this.plan.clear(); - Iterator it = this.songs.iterator(); - while (it.hasNext()) { - this.plan.put(it.next(), linkedHashMap); - } - final String string = z ? this.lyricsEdit.getText().toString() : null; - withWriteAccess(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.17 - @Override // java.lang.Runnable - public void run() { - TagEditorActivity.this.write(TagEditorActivity.this.newCover, TagEditorActivity.this.removeCover, str, string); - } - }); - return; - } - finish(); - } - - void withWriteAccess(Runnable runnable) { - this.afterGrant = runnable; - ArrayList arrayList = new ArrayList(this.plan.keySet()); - if (Build.VERSION.SDK_INT >= 30) { - PendingIntent pendingIntentWriteRequest = Tagger.writeRequest(this, arrayList); - if (pendingIntentWriteRequest != null) { - try { - startIntentSenderForResult(pendingIntentWriteRequest.getIntentSender(), 2, null, 0, 0, 0); - return; - } catch (IntentSender.SendIntentException e) { - } - } - } else if (Build.VERSION.SDK_INT == 29) { - Iterator it = arrayList.iterator(); - while (it.hasNext()) { - IntentSender intentSenderRecoverable = Tagger.recoverable(this, (Song) it.next()); - if (intentSenderRecoverable != null) { - try { - startIntentSenderForResult(intentSenderRecoverable, 3, null, 0, 0, 0); - return; - } catch (Exception e2) { - } - } - } - } else if (checkSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE") != 0) { - requestPermissions(new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"}, 4); - return; - } - Runnable runnable2 = this.afterGrant; - this.afterGrant = null; - runnable2.run(); - } - - @Override // android.app.Activity - public void onRequestPermissionsResult(int i, String[] strArr, int[] iArr) { - if (i == 4) { - if (iArr.length > 0 && iArr[0] == 0 && this.afterGrant != null) { - Runnable runnable = this.afterGrant; - this.afterGrant = null; - runnable.run(); - return; - } - MainActivity.toast("Mulberry needs storage permission to save tags"); - } - } - - void write(final byte[] bArr, final boolean z, final String str, final String str2) { - final AlertDialog alertDialogProgress = progress("Saving tags…"); - final ArrayList arrayList = new ArrayList(this.plan.keySet()); - MusicService musicService = MusicService.INSTANCE; - if (musicService != null) { - HashSet hashSet = new HashSet(); - Iterator it = arrayList.iterator(); - while (it.hasNext()) { - hashSet.add(((Song) it.next()).key()); - } - musicService.holdForEdit(hashSet); - } - App.IO.execute(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.18 - @Override // java.lang.Runnable - public void run() { - int i; - final ArrayList arrayList2 = new ArrayList(); - int i2 = 0; - int i3V = 0; - while (i2 < arrayList.size()) { - Song song = (Song) arrayList.get(i2); - final int i4 = i2 + 1; - App.ui(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.18.1 - @Override // java.lang.Runnable - public void run() { - TagEditorActivity.this.setProgress(alertDialogProgress, "Saving " + i4 + "/" + arrayList.size() + "…"); - } - }); - try { - Map map = TagEditorActivity.this.plan.get(song); - TagEditorActivity tagEditorActivity = TagEditorActivity.this; - if (map == null) { - map = new HashMap<>(); - } - Tagger.write(tagEditorActivity, song, map, bArr, z, str); - i = i3V + 1; - } catch (Throwable th) { - arrayList2.add(song.displayTitle() + ": " + TagEditorActivity.friendly(th)); - i = i3V; - } - if (str2 != null) { - try { - Tagger.saveLrc(song, str2); - Lyrics.clearCache(song, "auto"); - } catch (Throwable th2) { - arrayList2.add(".lrc file: " + TagEditorActivity.friendly(th2) + " (needs All files access)"); - } - } - i2++; - i3V = i; - } - final int i3 = i3V; - App.ui(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.18.2 - @Override // java.lang.Runnable - public void run() { - try { - alertDialogProgress.dismiss(); - } catch (Exception e) { - } - MusicService musicService2 = MusicService.INSTANCE; - if (musicService2 != null) { - musicService2.resumeAfterEdit(); - } - MainActivity.tagsEdited(); - if (!TagEditorActivity.this.isFinishing() && !TagEditorActivity.this.isDestroyed()) { - if (arrayList2.isEmpty()) { - MainActivity.toast("Saved tags for " + i3 + " file" + (i3 == 1 ? FrameBodyCOMM.DEFAULT : "s")); - TagEditorActivity.this.finish(); - return; - } - StringBuilder sb = new StringBuilder(); - int i5 = 0; - while (true) { - int i6 = i5; - if (i6 >= arrayList2.size() || i6 >= 12) { - break; - } - sb.append((String) arrayList2.get(i6)).append("\n"); - i5 = i6 + 1; - } - Ui.show(Ui.dialog(TagEditorActivity.this).setTitle(i3 > 0 ? "Some files were not saved" : "Couldn't save").setMessage(sb.toString().trim()).setPositiveButton("OK", (DialogInterface.OnClickListener) null)); - } - } - }); - } - }); - } - - static String friendly(Throwable th) { - String message = th.getMessage(); - if (th instanceof SecurityException) { - return "no permission to change this file"; - } - return (message == null || message.length() == 0) ? th.getClass().getSimpleName() : message; - } - - AlertDialog progress(String str) { - LinearLayout linearLayoutRow = Ui.row(this); - linearLayoutRow.setPadding(Ui.dp(this, 24.0f), Ui.dp(this, 20.0f), Ui.dp(this, 24.0f), Ui.dp(this, 20.0f)); - ProgressBar progressBar = new ProgressBar(this); - progressBar.setIndeterminateTintList(ColorStateList.valueOf(Ui.c(0))); - linearLayoutRow.addView(progressBar, new LinearLayout.LayoutParams(Ui.dp(this, 36.0f), Ui.dp(this, 36.0f))); - TextView textViewText = Ui.text(this, str, 15.0f, 11, false); - textViewText.setTag("msg"); - textViewText.setPadding(Ui.dp(this, 16.0f), 0, 0, 0); - linearLayoutRow.addView(textViewText); - AlertDialog alertDialogCreate = Ui.dialog(this).setView(linearLayoutRow).setCancelable(false).create(); - Ui.styleDialog(alertDialogCreate); - alertDialogCreate.show(); - return alertDialogCreate; - } - - void setProgress(AlertDialog alertDialog, String str) { - View viewFindViewWithTag = alertDialog.getWindow() == null ? null : alertDialog.getWindow().getDecorView().findViewWithTag("msg"); - if (viewFindViewWithTag instanceof TextView) { - ((TextView) viewFindViewWithTag).setText(str); - } - } - - @Override // android.app.Activity - protected void onActivityResult(int i, int i2, Intent intent) { - super.onActivityResult(i, i2, intent); - if (i == 1 && i2 == -1 && intent != null && intent.getData() != null) { - final Uri data = intent.getData(); - App.IO.execute(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.19 - @Override // java.lang.Runnable - public void run() { - byte[] allV = null; - try { - InputStream inputStreamOpenInputStream = TagEditorActivity.this.getContentResolver().openInputStream(data); - if (inputStreamOpenInputStream != null) { - allV = Net.readAll(inputStreamOpenInputStream); - inputStreamOpenInputStream.close(); - } - } catch (Exception e) { - } - final byte[] all = allV; - App.ui(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.19.1 - @Override // java.lang.Runnable - public void run() { - if (all != null) { - TagEditorActivity.this.setNewCover(all); - } else { - MainActivity.toast("Couldn't open that image"); - } - } - }); - } - }); - return; - } - if (i == 2 || i == 3) { - if (i2 == -1 && this.afterGrant != null) { - if (i != 3) { - Runnable runnable = this.afterGrant; - this.afterGrant = null; - runnable.run(); - return; - } - withWriteAccess(this.afterGrant); - return; - } - this.afterGrant = null; - MainActivity.toast("Tags weren't saved — permission was not given"); - } - } - - void buildBatch() { - LinearLayout linearLayoutFrame = frame("Fetch tags", this.songs.size() + " songs · MusicBrainz", null, null); - LinearLayout linearLayoutCol = Ui.col(this); - linearLayoutCol.setPadding(Ui.dp(this, 18.0f), 0, Ui.dp(this, 18.0f), Ui.dp(this, 20.0f)); - TextView textViewText = Ui.text(this, "Looking up each song (MusicBrainz allows about one lookup per second)…", 14.0f, 12, false); - textViewText.setPadding(0, 0, 0, Ui.dp(this, 10.0f)); - linearLayoutCol.addView(textViewText); - ProgressBar progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal); - progressBar.setMax(this.songs.size()); - progressBar.setProgressTintList(ColorStateList.valueOf(Ui.c(0))); - linearLayoutCol.addView(progressBar); - ScrollView scrollView = new ScrollView(this); - scrollView.addView(linearLayoutCol); - linearLayoutFrame.addView(scrollView, Ui.lp(-1, 0)); - ((LinearLayout.LayoutParams) scrollView.getLayoutParams()).weight = 1.0f; - LinearLayout linearLayoutRow = Ui.row(this); - linearLayoutRow.setGravity(8388613); - linearLayoutRow.setPadding(Ui.dp(this, 18.0f), Ui.dp(this, 8.0f), Ui.dp(this, 18.0f), Ui.dp(this, 12.0f)); - linearLayoutRow.setVisibility(8); - linearLayoutFrame.addView(linearLayoutRow); - App.IO.execute(new AnonymousClass20(progressBar, linearLayoutCol, textViewText, linearLayoutRow)); - } - - /* JADX INFO: renamed from: com.mulberry.player.TagEditorActivity$20, reason: invalid class name */ - class AnonymousClass20 implements Runnable { - final /* synthetic */ ProgressBar val$bar; - final /* synthetic */ LinearLayout val$bottom; - final /* synthetic */ TextView val$head; - final /* synthetic */ LinearLayout val$list; - - AnonymousClass20(ProgressBar progressBar, LinearLayout linearLayout, TextView textView, LinearLayout linearLayout2) { - this.val$bar = progressBar; - this.val$list = linearLayout; - this.val$head = textView; - this.val$bottom = linearLayout2; - } - - @Override // java.lang.Runnable - public void run() { - int i = 0; - while (true) { - int i2 = i; - if (i2 >= TagEditorActivity.this.songs.size() || TagEditorActivity.this.cancelled) { - break; - } - final Song song = TagEditorActivity.this.songs.get(i2); - MusicBrainz.Cand candV; - try { - List listSearch = MusicBrainz.search(song.displayTitle(), song.displayArtist(), song.album, song.duration, 5); - candV = (listSearch.isEmpty() || listSearch.get(0).score < 80) ? null : listSearch.get(0); - } catch (Exception e) { - candV = null; - } - final MusicBrainz.Cand cand = candV; - final int i3 = i2 + 1; - if (cand != null) { - LinkedHashMap linkedHashMap = new LinkedHashMap(); - TagEditorActivity.put(linkedHashMap, "title", cand.title); - TagEditorActivity.put(linkedHashMap, "artist", cand.artist); - TagEditorActivity.put(linkedHashMap, "album", cand.album); - TagEditorActivity.put(linkedHashMap, "albumartist", cand.albumArtist); - if (cand.year > 0) { - linkedHashMap.put("year", String.valueOf(cand.year)); - } - if (cand.track > 0) { - linkedHashMap.put("track", String.valueOf(cand.track)); - } - if (cand.disc > 0) { - linkedHashMap.put("disc", String.valueOf(cand.disc)); - } - TagEditorActivity.put(linkedHashMap, "mb_trackid", cand.mbTrack); - TagEditorActivity.put(linkedHashMap, "mb_albumid", cand.mbAlbum); - synchronized (TagEditorActivity.this.plan) { - TagEditorActivity.this.plan.put(song, linkedHashMap); - } - } - App.ui(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.20.1 - @Override // java.lang.Runnable - public void run() { - String str; - AnonymousClass20.this.val$bar.setProgress(i3); - LinearLayout linearLayoutRow = Ui.row(TagEditorActivity.this); - linearLayoutRow.setPadding(0, Ui.dp(TagEditorActivity.this, 8.0f), 0, Ui.dp(TagEditorActivity.this, 8.0f)); - linearLayoutRow.addView(Ui.icon(TagEditorActivity.this, cand != null ? R.drawable.ic_check : R.drawable.ic_close, cand != null ? 0 : 17, 20)); - LinearLayout linearLayoutCol = Ui.col(TagEditorActivity.this); - linearLayoutCol.setPadding(Ui.dp(TagEditorActivity.this, 12.0f), 0, 0, 0); - linearLayoutCol.addView(Ui.single(TagEditorActivity.this, song.displayArtist() + " – " + song.displayTitle(), 14.0f, 11, true)); - TagEditorActivity tagEditorActivity = TagEditorActivity.this; - if (cand != null) { - str = "→ " + cand.artist + " – " + cand.title + " · " + cand.album + (cand.year > 0 ? " (" + cand.year + ")" : FrameBodyCOMM.DEFAULT); - } else { - str = "no confident match (kept as is)"; - } - linearLayoutCol.addView(Ui.single(tagEditorActivity, str, 12.5f, 12, false)); - linearLayoutRow.addView(linearLayoutCol, Ui.lpw(-2, 1.0f)); - AnonymousClass20.this.val$list.addView(linearLayoutRow); - } - }); - i = i2 + 1; - } - App.ui(new AnonymousClass2()); - } - - /* JADX INFO: renamed from: com.mulberry.player.TagEditorActivity$20$2, reason: invalid class name */ - class AnonymousClass2 implements Runnable { - AnonymousClass2() { - } - - @Override // java.lang.Runnable - public void run() { - if (!TagEditorActivity.this.isFinishing()) { - int size = TagEditorActivity.this.plan.size(); - AnonymousClass20.this.val$head.setText(size == 0 ? "No confident matches. Try editing the songs one by one (long-press › Edit tags › Fetch from MusicBrainz)." : "Found good matches for " + size + " of " + TagEditorActivity.this.songs.size() + " songs."); - AnonymousClass20.this.val$bottom.setVisibility(0); - AnonymousClass20.this.val$bottom.addView(Ui.pill(TagEditorActivity.this, 0, "Close", false, new View.OnClickListener() { // from class: com.mulberry.player.TagEditorActivity.20.2.1 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - TagEditorActivity.this.finish(); - } - })); - if (size > 0) { - AnonymousClass20.this.val$bottom.addView(Ui.space(TagEditorActivity.this, 10)); - AnonymousClass20.this.val$bottom.addView(Ui.pill(TagEditorActivity.this, R.drawable.ic_save, "Apply to " + size, true, new View.OnClickListener() { // from class: com.mulberry.player.TagEditorActivity.20.2.2 - @Override // android.view.View.OnClickListener - public void onClick(View view) { - TagEditorActivity.this.withWriteAccess(new Runnable() { // from class: com.mulberry.player.TagEditorActivity.20.2.2.1 - @Override // java.lang.Runnable - public void run() { - TagEditorActivity.this.write(null, false, null, null); - } - }); - } - })); - } - } - } - } - } - - static void put(Map map, String str, String str2) { - if (str2 == null || str2.length() <= 0) { - return; - } - map.put(str, str2); - } -} diff --git a/android/src/com/mulberry/player/Tagger.java b/android/src/com/mulberry/player/Tagger.java deleted file mode 100644 index 09e2d80..0000000 --- a/android/src/com/mulberry/player/Tagger.java +++ /dev/null @@ -1,331 +0,0 @@ -package com.mulberry.player; - -import android.app.PendingIntent; -import android.app.RecoverableSecurityException; -import android.content.ContentUris; -import android.content.Context; -import android.content.IntentSender; -import android.database.Cursor; -import android.graphics.BitmapFactory; -import android.media.MediaScannerConnection; -import android.net.Uri; -import android.os.Build; -import android.os.Environment; -import android.os.ParcelFileDescriptor; -import android.provider.MediaStore; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; - -/* JADX INFO: loaded from: classes.dex */ -public final class Tagger { - private Tagger() { - } - - public static String ext(Context context, Song song) { - String string; - int iLastIndexOf; - String str = song.path; - if (str == null || str.length() == 0) { - try { - Cursor cursorQuery = context.getContentResolver().query(song.toUri(), new String[]{"_display_name"}, null, null, null); - if (cursorQuery != null) { - string = cursorQuery.moveToFirst() ? cursorQuery.getString(0) : str; - try { - cursorQuery.close(); - } catch (Exception e) { - str = string; - } - } else { - string = str; - } - str = string; - } catch (Exception e2) { - } - } - if (str != null && (iLastIndexOf = str.lastIndexOf(46)) > 0 && iLastIndexOf > str.lastIndexOf(47)) { - return str.substring(iLastIndexOf + 1).toLowerCase(Locale.ROOT); - } - String str2 = song.mime == null ? FrameBodyCOMM.DEFAULT : song.mime; - if (str2.contains("opus")) { - return "opus"; - } - if (str2.contains("wav")) { - return "wav"; - } - if (str2.contains("aiff")) { - return "aiff"; - } - if (str2.contains("aac") && !str2.contains("mp4")) { - return "aac"; - } - if (str2.contains("mpeg")) { - return "mp3"; - } - if (str2.contains("mp4") || str2.contains("aac")) { - return "m4a"; - } - if (str2.contains("flac")) { - return "flac"; - } - if (str2.contains("ogg")) { - return "ogg"; - } - return (str2.contains("wma") || str2.contains("asf")) ? "wma" : FrameBodyCOMM.DEFAULT; - } - - public static boolean canTag(Context context, Song song) { - return !song.isStream() && TagCore.canWrite(ext(context, song)); - } - - static File workDir(Context context) { - File file = new File(context.getCacheDir(), "tagedit"); - file.mkdirs(); - return file; - } - - static File copyIn(Context context, Song song) throws Exception { - FileInputStream fileInputStream = null; - File file = new File(workDir(context), "t" + Math.abs(song.key().hashCode()) + "_" + System.nanoTime() + "." + ext(context, song)); - File file2 = song.path.length() > 0 ? new File(song.path) : null; - if (file2 != null && file2.canRead()) { - fileInputStream = new FileInputStream(file2); - } - InputStream inputStreamOpenInputStream = fileInputStream == null ? context.getContentResolver().openInputStream(song.toUri()) : fileInputStream; - if (inputStreamOpenInputStream == null) { - throw new Exception("can't open the file"); - } - FileOutputStream fileOutputStream = new FileOutputStream(file); - byte[] bArr = new byte[65536]; - while (true) { - try { - int i = inputStreamOpenInputStream.read(bArr); - if (i <= 0) { - inputStreamOpenInputStream.close(); - fileOutputStream.close(); - return file; - } - fileOutputStream.write(bArr, 0, i); - } catch (Throwable th) { - inputStreamOpenInputStream.close(); - fileOutputStream.close(); - throw th; - } - } - } - - public static TagCore.Info read(Context context, Song song) throws Exception { - File file = song.path.length() > 0 ? new File(song.path) : null; - if (file != null && file.canRead() && TagCore.canWrite(ext(context, song))) { - try { - return TagCore.read(file); - } catch (Throwable th) { - } - } - File fileCopyIn = copyIn(context, song); - try { - return TagCore.read(fileCopyIn); - } finally { - fileCopyIn.delete(); - } - } - - public static boolean allFiles() { - return Build.VERSION.SDK_INT >= 30 && Environment.isExternalStorageManager(); - } - - static Uri storeUri(Song song) { - return song.id >= 0 ? ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, song.id) : song.toUri(); - } - - public static PendingIntent writeRequest(Context context, List list) { - if (Build.VERSION.SDK_INT < 30 || allFiles()) { - return null; - } - ArrayList arrayList = new ArrayList(); - for (Song song : list) { - if (song.id >= 0) { - arrayList.add(storeUri(song)); - } - } - if (arrayList.isEmpty()) { - return null; - } - try { - return MediaStore.createWriteRequest(context.getContentResolver(), arrayList); - } catch (Exception e) { - return null; - } - } - - public static IntentSender recoverable(Context context, Song song) { - if (Build.VERSION.SDK_INT != 29) { - return null; - } - return Q.probe(context, storeUri(song)); - } - - static final class Q { - Q() { - } - - static IntentSender probe(Context context, Uri uri) { - try { - ParcelFileDescriptor parcelFileDescriptorOpenFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "rw"); - if (parcelFileDescriptorOpenFileDescriptor == null) { - return null; - } - parcelFileDescriptorOpenFileDescriptor.close(); - return null; - } catch (RecoverableSecurityException e) { - return e.getUserAction().getActionIntent().getIntentSender(); - } catch (Exception e2) { - return null; - } - } - } - - // Rewritten by hand: the decompiler could not rebuild this method. - public static void write(Context context, Song song, Map map, byte[] bArr, boolean z, String str) throws Exception { - if (!canTag(context, song)) { - throw new Exception("this file type (" + ext(context, song) + ") can't be tagged"); - } - File fileCopyIn = copyIn(context, song); - try { - int iMax = 0; - int iMax2 = 0; - if (bArr != null) { - BitmapFactory.Options options = new BitmapFactory.Options(); - options.inJustDecodeBounds = true; - BitmapFactory.decodeByteArray(bArr, 0, bArr.length, options); - iMax = Math.max(0, options.outWidth); - iMax2 = Math.max(0, options.outHeight); - } - TagCore.write(fileCopyIn, map, bArr, bArr == null ? null : TagCore.sniffMime(bArr), iMax, iMax2, z, str); - } catch (Throwable th) { - if (fileCopyIn != null) { - fileCopyIn.delete(); - } - if (th instanceof Exception) { - throw (Exception) th; - } - throw new Exception(th); - } - try { - copyBack(context, song, fileCopyIn); - } catch (Exception e) { - File fileKeepBackup = keepBackup(context, song, fileCopyIn); - throw new Exception(e.getMessage() + (fileKeepBackup != null ? " — a complete copy was kept at " + fileKeepBackup.getPath() : "")); - } - if (fileCopyIn != null) { - fileCopyIn.delete(); - } - if (song.path.length() > 0) { - MediaScannerConnection.scanFile(context, new String[]{song.path}, null, null); - } - if (bArr != null || z) { - Covers.setOverride(song, bArr); - } else { - Covers.forget(song); - } - for (Map.Entry entry : map.entrySet()) { - apply(song, entry.getKey(), entry.getValue()); - } - } - - static void apply(Song song, String str, String str2) { - String strTrim = str2 == null ? FrameBodyCOMM.DEFAULT : str2.trim(); - if (!"title".equals(str)) { - if (!"artist".equals(str)) { - if (!"album".equals(str)) { - if (!"albumartist".equals(str)) { - if (!"year".equals(str)) { - if ("track".equals(str)) { - if (strTrim.contains("/")) { - strTrim = strTrim.substring(0, strTrim.indexOf(47)); - } - song.track = MusicBrainz.toInt(strTrim.replaceAll("\\D", FrameBodyCOMM.DEFAULT)) + ((song.track / 1000) * 1000); - return; - } - return; - } - song.year = MusicBrainz.toInt(strTrim.length() >= 4 ? strTrim.substring(0, 4).replaceAll("\\D", FrameBodyCOMM.DEFAULT) : strTrim.replaceAll("\\D", FrameBodyCOMM.DEFAULT)); - return; - } - song.albumArtist = strTrim; - return; - } - song.album = strTrim; - return; - } - song.artist = strTrim; - return; - } - song.title = strTrim; - } - - static File keepBackup(Context context, Song song, File file) { - try { - File externalFilesDir = context.getExternalFilesDir("tag-backups"); - File file2 = externalFilesDir == null ? new File(context.getFilesDir(), "tag-backups") : externalFilesDir; - file2.mkdirs(); - File file3 = new File(file2, song.path.length() > 0 ? new File(song.path).getName() : "song." + ext(context, song)); - return file.renameTo(file3) ? file3 : file; - } catch (Exception e) { - return file; - } - } - - static void copyBack(Context context, Song song, File file) throws Exception { - FileOutputStream fileOutputStream; - File file2 = song.path.length() > 0 ? new File(song.path) : null; - if (file2 != null && file2.exists() && file2.canWrite()) { - try { - fileOutputStream = new FileOutputStream(file2); - } catch (Exception e) { - fileOutputStream = null; - } - } else { - fileOutputStream = null; - } - OutputStream outputStreamOpenOutputStream = fileOutputStream == null ? context.getContentResolver().openOutputStream(storeUri(song), "wt") : fileOutputStream; - if (outputStreamOpenOutputStream == null) { - throw new Exception("no write access"); - } - FileInputStream fileInputStream = new FileInputStream(file); - byte[] bArr = new byte[65536]; - while (true) { - try { - int i = fileInputStream.read(bArr); - if (i <= 0) { - outputStreamOpenOutputStream.flush(); - fileInputStream.close(); - outputStreamOpenOutputStream.close(); - return; - } - outputStreamOpenOutputStream.write(bArr, 0, i); - } catch (Throwable th) { - fileInputStream.close(); - outputStreamOpenOutputStream.close(); - throw th; - } - } - } - - public static void saveLrc(Song song, String str) throws Exception { - if (song.path.length() == 0) { - throw new Exception("unknown file location"); - } - int iLastIndexOf = song.path.lastIndexOf(46); - FileOutputStream fileOutputStream = new FileOutputStream(new File((iLastIndexOf > 0 ? song.path.substring(0, iLastIndexOf) : song.path) + ".lrc")); - fileOutputStream.write(str.getBytes("UTF-8")); - fileOutputStream.close(); - } -} diff --git a/android/src/com/mulberry/player/Ticker.java b/android/src/com/mulberry/player/Ticker.java deleted file mode 100644 index f06a7d8..0000000 --- a/android/src/com/mulberry/player/Ticker.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.mulberry.player; - -import android.view.Choreographer; -import java.util.Iterator; -import java.util.concurrent.CopyOnWriteArrayList; - -/* JADX INFO: loaded from: classes.dex */ -public final class Ticker implements Choreographer.FrameCallback { - private static final Ticker I = new Ticker(); - private final CopyOnWriteArrayList clients = new CopyOnWriteArrayList<>(); - private long last; - private long minFrameNs; - private boolean running; - - public interface Client { - void frame(float f, long j); - } - - public static void add(Client client) { - if (!I.clients.contains(client)) { - I.clients.add(client); - I.start(); - } - } - - public static void remove(Client client) { - I.clients.remove(client); - } - - private void start() { - if (!this.running) { - this.running = true; - this.last = 0L; - Choreographer.getInstance().postFrameCallback(this); - } - } - - @Override // android.view.Choreographer.FrameCallback - public void doFrame(long j) { - if (!this.clients.isEmpty()) { - this.minFrameNs = App.lowPower() ? 31000000L : 0L; - if (this.last != 0 && j - this.last < this.minFrameNs) { - Choreographer.getInstance().postFrameCallback(this); - return; - } - float fMin = this.last == 0 ? 0.016666668f : Math.min(0.1f, (j - this.last) / 1.0E9f); - this.last = j; - Iterator it = this.clients.iterator(); - while (it.hasNext()) { - try { - it.next().frame(fMin, j); - } catch (Exception e) { - } - } - Choreographer.getInstance().postFrameCallback(this); - return; - } - this.running = false; - } -} diff --git a/android/src/com/mulberry/player/Ui.java b/android/src/com/mulberry/player/Ui.java deleted file mode 100644 index d49270b..0000000 --- a/android/src/com/mulberry/player/Ui.java +++ /dev/null @@ -1,356 +0,0 @@ -package com.mulberry.player; - -import android.app.AlertDialog; -import android.content.Context; -import android.content.res.ColorStateList; -import android.graphics.Typeface; -import android.graphics.drawable.ColorDrawable; -import android.graphics.drawable.Drawable; -import android.graphics.drawable.GradientDrawable; -import android.graphics.drawable.RippleDrawable; -import android.text.TextUtils; -import android.view.View; -import android.widget.EditText; -import android.widget.FrameLayout; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.TextView; -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; - -/* JADX INFO: loaded from: classes.dex */ -public final class Ui { - public static final int ERROR = 17; - public static final int MATCH = -1; - public static final int ON_PRIMARY = 1; - public static final int ON_PRIMARY_C = 3; - public static final int ON_SECONDARY_C = 5; - public static final int ON_SURFACE = 11; - public static final int ON_SURFACE_VAR = 12; - public static final int OUTLINE = 13; - public static final int OUTLINE_VAR = 14; - private static final List> OWNERS = new ArrayList(); - public static final int PRIMARY = 0; - public static final int PRIMARY_C = 2; - public static final int SECONDARY = 18; - public static final int SECONDARY_C = 4; - public static final int SURFACE = 6; - public static final int SURFACE_C = 8; - public static final int SURFACE_HIGH = 9; - public static final int SURFACE_HIGHEST = 10; - public static final int SURFACE_LOW = 7; - public static final int TERTIARY = 15; - public static final int TERTIARY_C = 16; - public static final int WRAP = -2; - private static int sinceSweep; - - public interface Paint { - void apply(); - } - - public static int c(int i) { - Palette palette = App.I.palette; - switch (i) { - case 0: - return palette.primary; - case 1: - return palette.onPrimary; - case 2: - return palette.primaryContainer; - case 3: - return palette.onPrimaryContainer; - case 4: - return palette.secondaryContainer; - case 5: - return palette.onSecondaryContainer; - case 6: - return palette.surface; - case 7: - return palette.surfaceLow; - case 8: - return palette.surfaceContainer; - case 9: - return palette.surfaceHigh; - case 10: - return palette.surfaceHighest; - case 11: - return palette.onSurface; - case 12: - return palette.onSurfaceVariant; - case OUTLINE /* 13 */: - return palette.outline; - case 14: - return palette.outlineVariant; - case TERTIARY /* 15 */: - return palette.tertiary; - case 16: - return palette.tertiaryContainer; - case ERROR /* 17 */: - return palette.error; - case 18: - return palette.secondary; - default: - return palette.primary; - } - } - - public static V themed(V v, Paint paint) { - Object tag = v.getTag(R.id.ui_paint); - if (tag instanceof Paint[]) { - Paint[] paintArr = (Paint[]) tag; - Paint[] paintArr2 = new Paint[paintArr.length + 1]; - System.arraycopy(paintArr, 0, paintArr2, 0, paintArr.length); - paintArr2[paintArr.length] = paint; - v.setTag(R.id.ui_paint, paintArr2); - } else { - v.setTag(R.id.ui_paint, new Paint[]{paint}); - OWNERS.add(new WeakReference<>(v)); - int i = sinceSweep + 1; - sinceSweep = i; - if (i > 400) { - sweep(); - sinceSweep = 0; - } - } - paint.apply(); - return v; - } - - private static void sweep() { - Iterator> it = OWNERS.iterator(); - while (it.hasNext()) { - if (it.next().get() == null) { - it.remove(); - } - } - } - - public static void recolor() { - Iterator> it = OWNERS.iterator(); - while (it.hasNext()) { - View view = it.next().get(); - if (view == null) { - it.remove(); - } else { - Object tag = view.getTag(R.id.ui_paint); - if (tag instanceof Paint[]) { - for (Paint paint : (Paint[]) tag) { - paint.apply(); - } - } - view.invalidate(); - } - } - } - - public static int dp(Context context, float f) { - return Math.round(context.getResources().getDisplayMetrics().density * f); - } - - public static float dpf(Context context, float f) { - return context.getResources().getDisplayMetrics().density * f; - } - - public static GradientDrawable round(int i, float f) { - GradientDrawable gradientDrawable = new GradientDrawable(); - gradientDrawable.setColor(i); - gradientDrawable.setCornerRadius(f); - return gradientDrawable; - } - - public static Drawable ripple(Drawable drawable, int i, Drawable drawable2) { - return new RippleDrawable(ColorStateList.valueOf(Palette.alpha(i, 0.16f)), drawable, drawable2); - } - - public static void bg(final View view, final int i, final float f) { - themed(view, new Paint() { // from class: com.mulberry.player.Ui.1 - @Override // com.mulberry.player.Ui.Paint - public void apply() { - float fDpf = Ui.dpf(view.getContext(), f); - view.setBackground(Ui.ripple(Ui.round(Ui.c(i), fDpf), Ui.c(11), Ui.round(-1, fDpf))); - } - }); - } - - public static void plain(final View view, final int i) { - themed(view, new Paint() { // from class: com.mulberry.player.Ui.2 - @Override // com.mulberry.player.Ui.Paint - public void apply() { - view.setBackgroundColor(Ui.c(i)); - } - }); - } - - public static void clickable(final View view, final float f) { - themed(view, new Paint() { // from class: com.mulberry.player.Ui.3 - @Override // com.mulberry.player.Ui.Paint - public void apply() { - view.setBackground(Ui.ripple(null, Ui.c(11), Ui.round(-1, Ui.dpf(view.getContext(), f)))); - } - }); - view.setClickable(true); - view.setFocusable(true); - } - - public static TextView text(Context context, String str, float f, final int i, boolean z) { - final TextView textView = new TextView(context); - textView.setText(str); - textView.setTextSize(2, f); - if (z) { - textView.setTypeface(Typeface.create("sans-serif-medium", 0)); - } - themed(textView, new Paint() { // from class: com.mulberry.player.Ui.4 - @Override // com.mulberry.player.Ui.Paint - public void apply() { - textView.setTextColor(Ui.c(i)); - } - }); - return textView; - } - - public static TextView single(Context context, String str, float f, int i, boolean z) { - TextView textViewText = text(context, str, f, i, z); - textViewText.setSingleLine(true); - textViewText.setEllipsize(TextUtils.TruncateAt.END); - return textViewText; - } - - public static TextView title(Context context, String str) { - TextView textViewText = text(context, str, 28.0f, 11, false); - textViewText.setTypeface(Typeface.create("sans-serif", 1)); - return textViewText; - } - - public static ImageView icon(Context context, int i, final int i2, int i3) { - final ImageView imageView = new ImageView(context); - imageView.setImageResource(i); - imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); - themed(imageView, new Paint() { // from class: com.mulberry.player.Ui.5 - @Override // com.mulberry.player.Ui.Paint - public void apply() { - imageView.setImageTintList(ColorStateList.valueOf(Ui.c(i2))); - } - }); - imageView.setLayoutParams(new LinearLayout.LayoutParams(dp(context, i3), dp(context, i3))); - return imageView; - } - - public static ImageView iconButton(Context context, int i, int i2, int i3, View.OnClickListener onClickListener) { - ImageView imageViewIcon = icon(context, i, i2, i3); - int iDp = dp(context, i3 / 4.5f); - imageViewIcon.setPadding(iDp, iDp, iDp, iDp); - clickable(imageViewIcon, i3 / 2.0f); - imageViewIcon.setOnClickListener(onClickListener); - return imageViewIcon; - } - - public static LinearLayout pill(Context context, int i, String str, boolean z, View.OnClickListener onClickListener) { - LinearLayout linearLayout = new LinearLayout(context); - linearLayout.setOrientation(0); - linearLayout.setGravity(17); - int iDp = dp(context, 16.0f); - linearLayout.setPadding(iDp, dp(context, 10.0f), dp(context, 4.0f) + iDp, dp(context, 10.0f)); - int i2 = z ? 0 : 4; - int i3 = z ? 1 : 5; - bg(linearLayout, i2, 22.0f); - if (i != 0) { - ImageView imageViewIcon = icon(context, i, i3, 18); - ((LinearLayout.LayoutParams) imageViewIcon.getLayoutParams()).setMarginEnd(dp(context, 8.0f)); - linearLayout.addView(imageViewIcon); - } - linearLayout.addView(single(context, str, 14.0f, i3, true)); - linearLayout.setOnClickListener(onClickListener); - linearLayout.setClickable(true); - return linearLayout; - } - - public static EditText field(Context context, String str, String str2) { - final EditText editText = new EditText(context); - editText.setHint(str); - if (str2 == null) { - str2 = FrameBodyCOMM.DEFAULT; - } - editText.setText(str2); - editText.setTextSize(2, 15.0f); - int iDp = dp(context, 14.0f); - editText.setPadding(dp(context, 4.0f) + iDp, iDp, iDp, iDp); - themed(editText, new Paint() { // from class: com.mulberry.player.Ui.6 - @Override // com.mulberry.player.Ui.Paint - public void apply() { - editText.setTextColor(Ui.c(11)); - editText.setHintTextColor(Palette.alpha(Ui.c(12), 0.7f)); - editText.setBackground(Ui.round(Ui.c(9), Ui.dpf(editText.getContext(), 16.0f))); - editText.setHighlightColor(Palette.alpha(Ui.c(0), 0.35f)); - } - }); - return editText; - } - - public static LinearLayout row(Context context) { - LinearLayout linearLayout = new LinearLayout(context); - linearLayout.setOrientation(0); - linearLayout.setGravity(16); - return linearLayout; - } - - public static LinearLayout col(Context context) { - LinearLayout linearLayout = new LinearLayout(context); - linearLayout.setOrientation(1); - return linearLayout; - } - - public static LinearLayout.LayoutParams lp(int i, int i2) { - return new LinearLayout.LayoutParams(i, i2); - } - - public static LinearLayout.LayoutParams lpw(int i, float f) { - return new LinearLayout.LayoutParams(0, i, f); - } - - public static FrameLayout.LayoutParams flp(int i, int i2, int i3) { - return new FrameLayout.LayoutParams(i, i2, i3); - } - - public static View space(Context context, int i) { - View view = new View(context); - view.setLayoutParams(new LinearLayout.LayoutParams(dp(context, i), dp(context, i))); - return view; - } - - public static AlertDialog.Builder dialog(Context context) { - return new AlertDialog.Builder(context, App.I.palette.dark ? android.R.style.Theme_DeviceDefault_Dialog_Alert : android.R.style.Theme_DeviceDefault_Light_Dialog_Alert); - } - - public static void styleDialog(AlertDialog alertDialog) { - if (alertDialog.getWindow() != null) { - alertDialog.getWindow().setBackgroundDrawable(round(c(9), dpf(alertDialog.getContext(), 28.0f))); - } - } - - public static AlertDialog show(AlertDialog.Builder builder) { - AlertDialog alertDialogCreate = builder.create(); - styleDialog(alertDialogCreate); - alertDialogCreate.show(); - try { - int iC = c(0); - if (alertDialogCreate.getButton(-1) != null) { - alertDialogCreate.getButton(-1).setTextColor(iC); - } - if (alertDialogCreate.getButton(-2) != null) { - alertDialogCreate.getButton(-2).setTextColor(iC); - } - if (alertDialogCreate.getButton(-3) != null) { - alertDialogCreate.getButton(-3).setTextColor(iC); - } - } catch (Exception e) { - } - return alertDialogCreate; - } - - public static ColorDrawable none() { - return new ColorDrawable(0); - } -} diff --git a/android/src/com/mulberry/player/WavySeekBar.java b/android/src/com/mulberry/player/WavySeekBar.java deleted file mode 100644 index dfa5a29..0000000 --- a/android/src/com/mulberry/player/WavySeekBar.java +++ /dev/null @@ -1,179 +0,0 @@ -package com.mulberry.player; - -import android.content.Context; -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Path; -import android.view.MotionEvent; -import android.view.View; - -/* JADX INFO: loaded from: classes.dex */ -public class WavySeekBar extends View implements Ticker.Client { - private float amp; - private boolean attached; - private float drag; - private long durationMs; - public int heightDp; - private OnSeek listener; - private final Paint p; - private final Path path; - private float phase; - private boolean playing; - private float target; - private boolean ticking; - private float value; - - public interface OnSeek { - void dragging(float f); - - void seek(float f); - } - - public WavySeekBar(Context context) { - super(context); - this.p = new Paint(1); - this.path = new Path(); - this.target = -1.0f; - this.drag = -1.0f; - this.heightDp = 40; - } - - public void setOnSeek(OnSeek onSeek) { - this.listener = onSeek; - } - - public void set(long j, long j2) { - this.durationMs = j2; - float fMax = j2 > 0 ? Math.max(0.0f, Math.min(1.0f, j / j2)) : 0.0f; - if (this.drag < 0.0f) { - if (this.ticking && Math.abs(fMax - this.value) * Math.max(1L, j2) <= 900.0f) { - this.target = fMax; - return; - } - this.value = fMax; - this.target = -1.0f; - invalidate(); - } - } - - public void setPlaying(boolean z) { - this.playing = z; - ensureTick(); - } - - void ensureTick() { - boolean z = this.attached && isShown() && getWindowVisibility() == 0 && (this.playing || this.amp > 0.01f); - if (!z || this.ticking) { - if (z || !this.ticking) { - return; - } - Ticker.remove(this); - this.ticking = false; - return; - } - Ticker.add(this); - this.ticking = true; - } - - @Override // android.view.View - protected void onAttachedToWindow() { - super.onAttachedToWindow(); - this.attached = true; - ensureTick(); - } - - @Override // android.view.View - protected void onDetachedFromWindow() { - super.onDetachedFromWindow(); - this.attached = false; - ensureTick(); - } - - @Override // android.view.View - protected void onVisibilityChanged(View view, int i) { - super.onVisibilityChanged(view, i); - ensureTick(); - } - - @Override // android.view.View - protected void onWindowVisibilityChanged(int i) { - super.onWindowVisibilityChanged(i); - ensureTick(); - } - - @Override // com.mulberry.player.Ticker.Client - public void frame(float f, long j) { - this.amp = (((this.playing ? 1.0f : 0.0f) - this.amp) * Math.min(1.0f, 7.0f * f)) + this.amp; - this.phase = (float) (((double) (this.phase + (6.6f * f))) % 6.283185307179586d); - if (this.playing && this.durationMs > 0 && this.drag < 0.0f) { - this.value = Math.min(1.0f, this.value + ((1000.0f * f) / this.durationMs)); - if (this.target >= 0.0f) { - this.value += Math.min(1.0f, 3.0f * f) * (this.target - this.value); - if (Math.abs(this.target - this.value) < 1.0E-5f) { - this.target = -1.0f; - } - } - } - invalidate(); - if (this.playing || this.amp >= 0.01f) { - return; - } - this.amp = 0.0f; - ensureTick(); - } - - @Override // android.view.View - protected void onMeasure(int i, int i2) { - setMeasuredDimension(View.MeasureSpec.getSize(i), Ui.dp(getContext(), this.heightDp)); - } - - float frac(float f) { - float fDpf = Ui.dpf(getContext(), 10.0f); - return Math.max(0.0f, Math.min(1.0f, (f - fDpf) / Math.max(1.0f, getWidth() - (fDpf * 2.0f)))); - } - - @Override // android.view.View - public boolean onTouchEvent(MotionEvent motionEvent) { - switch (motionEvent.getActionMasked()) { - case 0: - getParent().requestDisallowInterceptTouchEvent(true); - this.drag = frac(motionEvent.getX()); - if (this.listener != null) { - this.listener.dragging(this.drag); - } - invalidate(); - return true; - case 1: - float fFrac = frac(motionEvent.getX()); - this.drag = -1.0f; - this.value = fFrac; - this.target = -1.0f; - if (this.listener != null) { - this.listener.seek(fFrac); - } - invalidate(); - return true; - case 2: - this.drag = frac(motionEvent.getX()); - if (this.listener != null) { - this.listener.dragging(this.drag); - } - invalidate(); - return true; - case 3: - this.drag = -1.0f; - invalidate(); - return true; - default: - return super.onTouchEvent(motionEvent); - } - } - - @Override // android.view.View - protected void onDraw(Canvas canvas) { - float fDpf = Ui.dpf(getContext(), 10.0f); - float height = getHeight() / 2.0f; - Palette palette = App.I.palette; - Draw.wavy(canvas, fDpf, getWidth() - fDpf, height, this.drag >= 0.0f ? this.drag : this.value, this.amp, this.phase, Ui.dpf(getContext(), 4.5f), Ui.dpf(getContext(), 36.0f), Ui.dpf(getContext(), 3.6f), palette.primary, palette.secondaryContainer, this.p, this.path, true, Math.min(getHeight() - 2, Ui.dpf(getContext(), this.drag >= 0.0f ? 26.0f : 20.0f))); - } -} diff --git a/android/src/com/mulberry/player/WidgetCompact.java b/android/src/com/mulberry/player/WidgetCompact.java deleted file mode 100644 index e8c849f..0000000 --- a/android/src/com/mulberry/player/WidgetCompact.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.mulberry.player; - -import android.appwidget.AppWidgetManager; -import android.appwidget.AppWidgetProvider; -import android.content.Context; -import android.os.Bundle; - -/* JADX INFO: loaded from: classes.dex */ -public class WidgetCompact extends AppWidgetProvider { - @Override // android.appwidget.AppWidgetProvider - public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] iArr) { - Widgets.updateAll(context); - } - - @Override // android.appwidget.AppWidgetProvider - public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int i, Bundle bundle) { - Widgets.updateAll(context); - } -} diff --git a/android/src/com/mulberry/player/WidgetLarge.java b/android/src/com/mulberry/player/WidgetLarge.java deleted file mode 100644 index 18c3ca9..0000000 --- a/android/src/com/mulberry/player/WidgetLarge.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.mulberry.player; - -import android.appwidget.AppWidgetManager; -import android.appwidget.AppWidgetProvider; -import android.content.Context; -import android.os.Bundle; - -/* JADX INFO: loaded from: classes.dex */ -public class WidgetLarge extends AppWidgetProvider { - @Override // android.appwidget.AppWidgetProvider - public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] iArr) { - Widgets.updateAll(context); - } - - @Override // android.appwidget.AppWidgetProvider - public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int i, Bundle bundle) { - Widgets.updateAll(context); - } -} diff --git a/android/src/com/mulberry/player/WidgetLyrics.java b/android/src/com/mulberry/player/WidgetLyrics.java deleted file mode 100644 index cdb0c03..0000000 --- a/android/src/com/mulberry/player/WidgetLyrics.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.mulberry.player; - -import android.appwidget.AppWidgetManager; -import android.appwidget.AppWidgetProvider; -import android.content.Context; -import android.os.Bundle; - -/* JADX INFO: loaded from: classes.dex */ -public class WidgetLyrics extends AppWidgetProvider { - @Override // android.appwidget.AppWidgetProvider - public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] iArr) { - Widgets.updateAll(context); - } - - @Override // android.appwidget.AppWidgetProvider - public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int i, Bundle bundle) { - Widgets.updateAll(context); - } -} diff --git a/android/src/com/mulberry/player/WidgetMedium.java b/android/src/com/mulberry/player/WidgetMedium.java deleted file mode 100644 index 81ee836..0000000 --- a/android/src/com/mulberry/player/WidgetMedium.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.mulberry.player; - -import android.appwidget.AppWidgetManager; -import android.appwidget.AppWidgetProvider; -import android.content.Context; -import android.os.Bundle; - -/* JADX INFO: loaded from: classes.dex */ -public class WidgetMedium extends AppWidgetProvider { - @Override // android.appwidget.AppWidgetProvider - public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] iArr) { - Widgets.updateAll(context); - } - - @Override // android.appwidget.AppWidgetProvider - public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int i, Bundle bundle) { - Widgets.updateAll(context); - } -} diff --git a/android/src/com/mulberry/player/WidgetShape.java b/android/src/com/mulberry/player/WidgetShape.java deleted file mode 100644 index e503441..0000000 --- a/android/src/com/mulberry/player/WidgetShape.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.mulberry.player; - -import android.appwidget.AppWidgetManager; -import android.appwidget.AppWidgetProvider; -import android.content.Context; -import android.os.Bundle; - -/* JADX INFO: loaded from: classes.dex */ -public class WidgetShape extends AppWidgetProvider { - @Override // android.appwidget.AppWidgetProvider - public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] iArr) { - Widgets.updateAll(context); - } - - @Override // android.appwidget.AppWidgetProvider - public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int i, Bundle bundle) { - Widgets.updateAll(context); - } -} diff --git a/android/src/com/mulberry/player/Widgets.java b/android/src/com/mulberry/player/Widgets.java deleted file mode 100644 index ac42ed3..0000000 --- a/android/src/com/mulberry/player/Widgets.java +++ /dev/null @@ -1,480 +0,0 @@ -package com.mulberry.player; - -import android.app.PendingIntent; -import android.appwidget.AppWidgetManager; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Matrix; -import android.graphics.Paint; -import android.graphics.Path; -import android.graphics.drawable.Drawable; -import android.os.Build; -import android.os.Bundle; -import android.os.PowerManager; -import android.os.SystemClock; -import android.widget.RemoteViews; -import java.util.HashMap; -import java.util.List; -import org.jaudiotagger.tag.datatype.DataTypes; -import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM; - -/* JADX INFO: loaded from: classes.dex */ -public final class Widgets { - private static final HashMap COVER_BMP = new HashMap<>(); - private static final HashMap COVER_KEY = new HashMap<>(); - private static final Shapes.Animator SHAPE = new Shapes.Animator(); - private static boolean anim; - private static long lastShape; - private static long lastWave; - private static float phase; - private static Bitmap shapeBmp; - private static long shapeLast; - private static Bitmap waveBmp; - - private Widgets() { - } - - static int[] ids(Context context, Class cls) { - try { - return AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, cls)); - } catch (Exception e) { - return new int[0]; - } - } - - static int[] size(AppWidgetManager appWidgetManager, int i, int i2, int i3) { - try { - Bundle appWidgetOptions = appWidgetManager.getAppWidgetOptions(i); - int i4 = appWidgetOptions.getInt("appWidgetMinWidth", 0); - int i5 = appWidgetOptions.getInt("appWidgetMaxHeight", 0); - int[] iArr = new int[2]; - if (i4 <= 0) { - i4 = i2; - } - iArr[0] = i4; - if (i5 <= 0) { - i5 = i3; - } - iArr[1] = i5; - return iArr; - } catch (Exception e) { - return new int[]{i2, i3}; - } - } - - public static void updateAll(Context context) { - try { - AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); - MusicService musicService = MusicService.INSTANCE; - for (int i : ids(context, WidgetLarge.class)) { - int[] size = size(appWidgetManager, i, 280, 300); - appWidgetManager.updateAppWidget(i, large(context, musicService, size[0], size[1])); - } - for (int i2 : ids(context, WidgetMedium.class)) { - int[] size2 = size(appWidgetManager, i2, 280, 190); - appWidgetManager.updateAppWidget(i2, medium(context, musicService, size2[0], size2[1])); - } - int[] iArrIds = ids(context, WidgetCompact.class); - if (iArrIds.length > 0) { - appWidgetManager.updateAppWidget(iArrIds, compact(context, musicService)); - } - for (int i3 : ids(context, WidgetLyrics.class)) { - appWidgetManager.updateAppWidget(i3, lyricsOnly(context, musicService, size(appWidgetManager, i3, 280, 180)[1])); - } - int[] iArrIds2 = ids(context, WidgetShape.class); - if (iArrIds2.length > 0) { - RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_shape); - remoteViews.setImageViewBitmap(R.id.w_shape, shapeFrame(context)); - remoteViews.setOnClickPendingIntent(R.id.w_root, openApp(context)); - appWidgetManager.updateAppWidget(iArrIds2, remoteViews); - SHAPE.playing = musicService != null && musicService.isPlaying(); - } - startAnim(context); - } catch (Exception e) { - } - } - - static void tick(MusicService musicService) { - startAnim(musicService); - } - - static PendingIntent action(Context context, String str, int i) { - Intent action = new Intent(context, (Class) MusicService.class).setAction(str); - if (Build.VERSION.SDK_INT < 26) { - return PendingIntent.getService(context, i + 100, action, 201326592); - } - action.putExtra(MusicService.EXTRA_FG, true); - return PendingIntent.getForegroundService(context, i + 100, action, 201326592); - } - - static PendingIntent openApp(Context context) { - return PendingIntent.getActivity(context, 99, new Intent(context, (Class) MainActivity.class).addFlags(805306368).putExtra("open_player", true), 201326592); - } - - static void info(RemoteViews remoteViews, MusicService musicService, boolean z) { - Song songCurrent = musicService == null ? null : musicService.current(); - remoteViews.setTextViewText(R.id.w_title, songCurrent == null ? "Mulberry" : songCurrent.displayTitle()); - remoteViews.setTextViewText(R.id.w_artist, songCurrent == null ? "Tap play to start" : songCurrent.displayArtist()); - if (z) { - remoteViews.setTextViewText(R.id.w_album, songCurrent == null ? FrameBodyCOMM.DEFAULT : songCurrent.album); - } - } - - static void controls(Context context, RemoteViews remoteViews, MusicService musicService, boolean z) { - remoteViews.setImageViewResource(R.id.w_play, musicService != null && (musicService.isPlaying() || musicService.isLoading()) ? R.drawable.ic_pause_fill : R.drawable.ic_play_arrow_fill); - remoteViews.setOnClickPendingIntent(R.id.w_play, action(context, MusicService.ACT_TOGGLE, 1)); - remoteViews.setOnClickPendingIntent(R.id.w_prev, action(context, MusicService.ACT_PREV, 2)); - remoteViews.setOnClickPendingIntent(R.id.w_next, action(context, MusicService.ACT_NEXT, 3)); - if (z) { - boolean zShuffle = musicService != null ? musicService.shuffle() : App.I.prefs.getBool(Prefs.SHUFFLE, false); - int iRepeat = musicService != null ? musicService.repeat() : App.I.prefs.getInt(Prefs.REPEAT, 0); - remoteViews.setInt(R.id.w_shuffle, "setImageAlpha", zShuffle ? 255 : 110); - remoteViews.setInt(R.id.w_repeat, "setImageAlpha", iRepeat != 0 ? 255 : 110); - remoteViews.setImageViewResource(R.id.w_repeat, iRepeat == 2 ? R.drawable.ic_repeat_one : R.drawable.ic_repeat); - remoteViews.setOnClickPendingIntent(R.id.w_shuffle, action(context, MusicService.ACT_SHUFFLE, 4)); - remoteViews.setOnClickPendingIntent(R.id.w_repeat, action(context, MusicService.ACT_REPEAT, 5)); - } - } - - static void sizeView(RemoteViews remoteViews, int i, int i2) { - if (Build.VERSION.SDK_INT >= 31) { - remoteViews.setViewLayoutWidth(i, i2, 1); - remoteViews.setViewLayoutHeight(i, i2, 1); - } - } - - static RemoteViews medium(Context context, MusicService musicService, int i, int i2) { - if (i2 < 110) { - return compact(context, musicService); - } - boolean z = i2 >= 250; - RemoteViews remoteViews = new RemoteViews(context.getPackageName(), z ? R.layout.widget_medium_tall : R.layout.widget_medium); - info(remoteViews, musicService, true); - Song songCurrent = musicService == null ? null : musicService.current(); - sizeView(remoteViews, R.id.w_cover, z ? 84 : Math.max(56, Math.min(132, (int) ((i2 - 110) * 0.95f)))); - if (z) { - remoteViews.setViewVisibility(R.id.w_lyr_prev, i2 >= 330 ? 0 : 8); - remoteViews.setViewVisibility(R.id.w_lyr_next, i2 >= 290 ? 0 : 8); - lyricLines(remoteViews, musicService, false); - remoteViews.setOnClickPendingIntent(R.id.w_lyrics_card, openApp(context)); - } - remoteViews.setImageViewBitmap(R.id.w_cover, cover(context, musicService, songCurrent, App.I.lowRam ? 240 : 320, true)); - boolean z2 = i >= 240; - remoteViews.setViewVisibility(R.id.w_shuffle, z2 ? 0 : 8); - remoteViews.setViewVisibility(R.id.w_repeat, z2 ? 0 : 8); - remoteViews.setViewVisibility(R.id.w_album, i2 >= 150 ? 0 : 8); - remoteViews.setViewVisibility(R.id.w_progress, i2 < 135 ? 8 : 0); - controls(context, remoteViews, musicService, true); - progress(context, remoteViews, musicService); - remoteViews.setOnClickPendingIntent(R.id.w_cover, openApp(context)); - remoteViews.setOnClickPendingIntent(R.id.w_root, openApp(context)); - return remoteViews; - } - - static RemoteViews large(Context context, MusicService musicService, int i, int i2) { - RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_large); - info(remoteViews, musicService, true); - remoteViews.setImageViewBitmap(R.id.w_cover, cover(context, musicService, musicService == null ? null : musicService.current(), App.I.lowRam ? 200 : 240, false)); - remoteViews.setViewVisibility(R.id.w_album, i2 >= 230 ? 0 : 8); - remoteViews.setViewVisibility(R.id.w_lyr_prev, i2 >= 270 ? 0 : 8); - remoteViews.setViewVisibility(R.id.w_lyr_next, i2 >= 215 ? 0 : 8); - boolean z = i >= 240; - remoteViews.setViewVisibility(R.id.w_shuffle, z ? 0 : 8); - remoteViews.setViewVisibility(R.id.w_repeat, z ? 0 : 8); - controls(context, remoteViews, musicService, true); - progress(context, remoteViews, musicService); - lyricLines(remoteViews, musicService, false); - remoteViews.setOnClickPendingIntent(R.id.w_cover, openApp(context)); - remoteViews.setOnClickPendingIntent(R.id.w_root, openApp(context)); - remoteViews.setOnClickPendingIntent(R.id.w_lyrics_card, openApp(context)); - return remoteViews; - } - - static RemoteViews compact(Context context, MusicService musicService) { - RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_compact); - info(remoteViews, musicService, false); - remoteViews.setImageViewBitmap(R.id.w_cover, cover(context, musicService, musicService == null ? null : musicService.current(), 150, false)); - controls(context, remoteViews, musicService, false); - remoteViews.setOnClickPendingIntent(R.id.w_box, openApp(context)); - return remoteViews; - } - - static RemoteViews lyricsOnly(Context context, MusicService musicService, int i) { - String str; - RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_lyrics); - Song songCurrent = musicService == null ? null : musicService.current(); - if (songCurrent == null) { - str = DataTypes.OBJ_LYRICS; - } else { - str = songCurrent.displayTitle() + (songCurrent.displayArtist().length() > 0 ? " · " + songCurrent.displayArtist() : FrameBodyCOMM.DEFAULT); - } - remoteViews.setTextViewText(R.id.w_title, str); - remoteViews.setViewVisibility(R.id.w_lyr_prev, i >= 150 ? 0 : 8); - remoteViews.setViewVisibility(R.id.w_lyr_next2, i < 190 ? 8 : 0); - lyricLines(remoteViews, musicService, true); - remoteViews.setOnClickPendingIntent(R.id.w_root, openApp(context)); - return remoteViews; - } - - static void progress(Context context, RemoteViews remoteViews, MusicService musicService) { - progress(context, remoteViews, musicService, musicService == null ? 0L : musicService.position()); - } - - static void progress(Context context, RemoteViews remoteViews, MusicService musicService, long j) { - long jDuration = musicService == null ? 0L : musicService.duration(); - boolean z = musicService != null && musicService.isPlaying(); - remoteViews.setTextViewText(R.id.w_pos, Draw.time(j)); - remoteViews.setTextViewText(R.id.w_dur, Draw.time(jDuration)); - remoteViews.setImageViewBitmap(R.id.w_wave, wave(context, jDuration > 0 ? j / jDuration : 0.0f, z)); - } - - static void lyricLines(RemoteViews remoteViews, MusicService musicService, boolean z) { - String str; - String str2; - Lyrics.Result result = musicService == null ? null : musicService.lyrics; - String str3 = FrameBodyCOMM.DEFAULT; - String str4 = FrameBodyCOMM.DEFAULT; - if (musicService == null || musicService.current() == null) { - str = FrameBodyCOMM.DEFAULT; - str2 = "♪"; - } else if (result == null) { - str = FrameBodyCOMM.DEFAULT; - str2 = "Loading lyrics…"; - } else if (result.lines.isEmpty()) { - String str5 = result.message.length() > 0 ? result.message : "No lyrics"; - str = FrameBodyCOMM.DEFAULT; - str2 = str5; - } else if (!result.synced) { - str2 = result.lines.get(0).text; - String str6 = result.lines.size() > 1 ? result.lines.get(1).text : FrameBodyCOMM.DEFAULT; - str = result.lines.size() > 2 ? result.lines.get(2).text : FrameBodyCOMM.DEFAULT; - str4 = str6; - } else { - List list = result.lines; - int iLineAt = Lyrics.lineAt(list, musicService.position() + 250); - if (iLineAt < 0) { - String str7 = list.get(0).text; - str = list.size() > 1 ? list.get(1).text : FrameBodyCOMM.DEFAULT; - str4 = str7; - str2 = "♪"; - } else { - str2 = list.get(iLineAt).text.length() == 0 ? "♪" : list.get(iLineAt).text; - String str8 = iLineAt > 0 ? list.get(iLineAt - 1).text : FrameBodyCOMM.DEFAULT; - String str9 = iLineAt + 1 < list.size() ? list.get(iLineAt + 1).text : FrameBodyCOMM.DEFAULT; - str = iLineAt + 2 < list.size() ? list.get(iLineAt + 2).text : FrameBodyCOMM.DEFAULT; - str4 = str9; - str3 = str8; - } - } - remoteViews.setTextViewText(R.id.w_lyr_prev, str3); - remoteViews.setTextViewText(R.id.w_lyr_cur, str2); - remoteViews.setTextViewText(R.id.w_lyr_next, str4); - if (z) { - remoteViews.setTextViewText(R.id.w_lyr_next2, str); - } - } - - static int color(Context context, int i) { - try { - return context.getColor(i); - } catch (Exception e) { - return -6651951; - } - } - - static synchronized Bitmap cover(Context context, MusicService musicService, Song song, int i, boolean z) { - Bitmap bitmap; - Bitmap bitmapArt = musicService == null ? null : musicService.art(); - int iColor = color(context, R.color.w_primary); - int iColor2 = color(context, R.color.w_tonal); - int i2 = (i * 2) + (z ? 1 : 0); - String str = (song == null ? "-" : song.key()) + "|" + (bitmapArt == null ? 0 : System.identityHashCode(bitmapArt)) + "|" + iColor; - bitmap = COVER_BMP.get(Integer.valueOf(i2)); - if (!str.equals(COVER_KEY.get(Integer.valueOf(i2))) || bitmap == null || bitmap.isRecycled()) { - Bitmap bitmapCreateBitmap = Bitmap.createBitmap(i, i, Bitmap.Config.ARGB_8888); - Canvas canvas = new Canvas(bitmapCreateBitmap); - Paint paint = new Paint(3); - float f = i / 2.0f; - float f2 = i / 2.0f; - float f3 = (i / 2.0f) - 2.0f; - float f4 = z ? 0.76f * f3 : 0.97f * f3; - if (z) { - Draw.bars(canvas, f, f2, f4, 0.06f, 0.0f, f3 - (1.1f * f4), null, 56, iColor, Math.max(2.5f, i / 75.0f), paint); - } - Draw.cookieCover(canvas, Draw.cookie(null, f, f2, f4, 0.06f, 0.0f), bitmapArt, f, f2, f4, paint, iColor2, new Matrix()); - if (bitmapArt == null) { - Drawable drawableMutate = context.getDrawable(R.drawable.ic_album).mutate(); - int i3 = (int) (f4 * 0.9f); - drawableMutate.setTint(color(context, R.color.w_on_tonal)); - drawableMutate.setBounds((int) (f - (i3 / 2.0f)), (int) (f2 - (i3 / 2.0f)), (int) (f + (i3 / 2.0f)), (int) (f2 + (i3 / 2.0f))); - drawableMutate.draw(canvas); - } - COVER_BMP.put(Integer.valueOf(i2), bitmapCreateBitmap); - COVER_KEY.put(Integer.valueOf(i2), str); - bitmap = bitmapCreateBitmap; - } - return bitmap; - } - - static synchronized Bitmap wave(Context context, float f, boolean z) { - if (waveBmp == null) { - waveBmp = Bitmap.createBitmap(420, 36, Bitmap.Config.ARGB_8888); - } - waveBmp.eraseColor(0); - Draw.wavy(new Canvas(waveBmp), 5.0f, 415, 36 / 2.0f, f, z ? 1.0f : 0.0f, phase, 5.5f, 38.0f, 6.0f, color(context, R.color.w_primary), color(context, R.color.w_tonal), new Paint(1), null, true, 24.0f); - return waveBmp; - } - - static synchronized Bitmap shapeFrame(Context context) { - int i = App.I.lowRam ? 160 : 200; - if (shapeBmp == null) { - shapeBmp = Bitmap.createBitmap(i, i, Bitmap.Config.ARGB_8888); - } - shapeBmp.eraseColor(0); - Canvas canvas = new Canvas(shapeBmp); - Paint paint = new Paint(1); - int iColor = color(context, R.color.w_primary); - SHAPE.draw(canvas, i / 2.0f, i / 2.0f, i * 0.42f, Palette.alpha(color(context, R.color.w_tonal), 0.96f), iColor, iColor, paint, new Path()); - return shapeBmp; - } - - static int[] rates() { - String str = App.lowPower() ? "saver" : App.I.prefs.getStr(Prefs.WIDGET_ANIM, "balanced"); - if ("smooth".equals(str)) { - return new int[]{33, 33}; - } - return "saver".equals(str) ? new int[]{333, 333} : new int[]{66, 66}; - } - - static void startAnim(final Context context) { - if (!anim) { - anim = true; - shapeLast = SystemClock.elapsedRealtime(); - App.MAIN.post(new Runnable() { // from class: com.mulberry.player.Widgets.1 - /* JADX WARN: Code duplicated, block: B:50:0x0102 */ - /* JADX WARN: Code duplicated, block: B:53:0x0139 A[Catch: Exception -> 0x01c1, TryCatch #0 {Exception -> 0x01c1, blocks: (B:37:0x008b, B:39:0x009b, B:41:0x00b6, B:43:0x00ba, B:44:0x00c6, B:46:0x00e8, B:48:0x00f8, B:51:0x0105, B:53:0x0139, B:54:0x013c, B:56:0x013f, B:79:0x01af, B:58:0x0144, B:60:0x014a, B:62:0x015d, B:63:0x0160, B:65:0x0163, B:66:0x0166, B:68:0x0169), top: B:83:0x008b }] */ - /* JADX WARN: Code duplicated, block: B:56:0x013f A[Catch: Exception -> 0x01c1, TryCatch #0 {Exception -> 0x01c1, blocks: (B:37:0x008b, B:39:0x009b, B:41:0x00b6, B:43:0x00ba, B:44:0x00c6, B:46:0x00e8, B:48:0x00f8, B:51:0x0105, B:53:0x0139, B:54:0x013c, B:56:0x013f, B:79:0x01af, B:58:0x0144, B:60:0x014a, B:62:0x015d, B:63:0x0160, B:65:0x0163, B:66:0x0166, B:68:0x0169), top: B:83:0x008b }] */ - /* JADX WARN: Code duplicated, block: B:62:0x015d A[Catch: Exception -> 0x01c1, TryCatch #0 {Exception -> 0x01c1, blocks: (B:37:0x008b, B:39:0x009b, B:41:0x00b6, B:43:0x00ba, B:44:0x00c6, B:46:0x00e8, B:48:0x00f8, B:51:0x0105, B:53:0x0139, B:54:0x013c, B:56:0x013f, B:79:0x01af, B:58:0x0144, B:60:0x014a, B:62:0x015d, B:63:0x0160, B:65:0x0163, B:66:0x0166, B:68:0x0169), top: B:83:0x008b }] */ - /* JADX WARN: Code duplicated, block: B:65:0x0163 A[Catch: Exception -> 0x01c1, TryCatch #0 {Exception -> 0x01c1, blocks: (B:37:0x008b, B:39:0x009b, B:41:0x00b6, B:43:0x00ba, B:44:0x00c6, B:46:0x00e8, B:48:0x00f8, B:51:0x0105, B:53:0x0139, B:54:0x013c, B:56:0x013f, B:79:0x01af, B:58:0x0144, B:60:0x014a, B:62:0x015d, B:63:0x0160, B:65:0x0163, B:66:0x0166, B:68:0x0169), top: B:83:0x008b }] */ - /* JADX WARN: Code duplicated, block: B:68:0x0169 A[Catch: Exception -> 0x01c1, TRY_LEAVE, TryCatch #0 {Exception -> 0x01c1, blocks: (B:37:0x008b, B:39:0x009b, B:41:0x00b6, B:43:0x00ba, B:44:0x00c6, B:46:0x00e8, B:48:0x00f8, B:51:0x0105, B:53:0x0139, B:54:0x013c, B:56:0x013f, B:79:0x01af, B:58:0x0144, B:60:0x014a, B:62:0x015d, B:63:0x0160, B:65:0x0163, B:66:0x0166, B:68:0x0169), top: B:83:0x008b }] */ - /* JADX WARN: Code duplicated, block: B:78:0x01ad */ - @Override // java.lang.Runnable - public void run() { - RemoteViews remoteViews; - float fMin; - RemoteViews remoteViews2; - Context applicationContext = context.getApplicationContext(); - AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(applicationContext); - int[] iArrIds = Widgets.ids(applicationContext, WidgetShape.class); - int[] iArrIds2 = Widgets.ids(applicationContext, WidgetMedium.class); - int[] iArrIds3 = Widgets.ids(applicationContext, WidgetLarge.class); - int[] iArrIds4 = Widgets.ids(applicationContext, WidgetLyrics.class); - MusicService musicService = MusicService.INSTANCE; - PowerManager powerManager = (PowerManager) applicationContext.getSystemService("power"); - boolean z = powerManager == null || powerManager.isInteractive(); - boolean z2 = musicService != null && musicService.isPlaying(); - int[] iArrRates = Widgets.rates(); - long jElapsedRealtime = SystemClock.elapsedRealtime(); - Widgets.SHAPE.playing = z2; - boolean z3 = iArrIds.length > 0 && (z2 || !Widgets.SHAPE.settled()); - boolean z4 = iArrIds2.length + iArrIds3.length > 0 && z2; - boolean z5 = (iArrIds2.length + iArrIds3.length) + iArrIds4.length > 0 && z2; - if (!z || (!z3 && !z4 && !z5)) { - boolean unused = Widgets.anim = false; - return; - } - if (z3) { - try { - if (jElapsedRealtime - Widgets.lastShape >= iArrRates[1]) { - float fMin2 = Math.min(0.5f, (jElapsedRealtime - Widgets.shapeLast) / 1000.0f); - long unused2 = Widgets.shapeLast = jElapsedRealtime; - long unused3 = Widgets.lastShape = jElapsedRealtime; - Widgets.SHAPE.step(fMin2, (!z2 || musicService.spectrum == null) ? -1.0f : musicService.spectrum.bass(musicService.positionFast())); - RemoteViews remoteViews3 = new RemoteViews(applicationContext.getPackageName(), R.layout.widget_shape); - remoteViews3.setImageViewBitmap(R.id.w_shape, Widgets.shapeFrame(applicationContext)); - appWidgetManager.partiallyUpdateAppWidget(iArrIds, remoteViews3); - } - if (z4 && jElapsedRealtime - Widgets.lastWave >= iArrRates[0]) { - if (Widgets.lastWave == 0) { - fMin = 0.3f; - } else { - fMin = Math.min(1.0f, (jElapsedRealtime - Widgets.lastWave) / 1000.0f); - } - long unused4 = Widgets.lastWave = jElapsedRealtime; - float unused5 = Widgets.phase = (float) (((double) ((fMin * 6.6f) + Widgets.phase)) % 6.283185307179586d); - remoteViews2 = new RemoteViews(applicationContext.getPackageName(), R.layout.widget_medium); - Widgets.progress(applicationContext, remoteViews2, musicService, musicService.positionFast()); - if (iArrIds2.length > 0) { - appWidgetManager.partiallyUpdateAppWidget(iArrIds2, remoteViews2); - } - if (iArrIds3.length > 0) { - appWidgetManager.partiallyUpdateAppWidget(iArrIds3, remoteViews2); - } - } - if (z5 && musicService.lyricLineChanged()) { - remoteViews = new RemoteViews(applicationContext.getPackageName(), R.layout.widget_large); - Widgets.lyricLines(remoteViews, musicService, false); - if (iArrIds3.length > 0) { - appWidgetManager.partiallyUpdateAppWidget(iArrIds3, remoteViews); - } - if (iArrIds2.length > 0) { - appWidgetManager.partiallyUpdateAppWidget(iArrIds2, remoteViews); - } - if (iArrIds4.length > 0) { - RemoteViews remoteViews4 = new RemoteViews(applicationContext.getPackageName(), R.layout.widget_lyrics); - Widgets.lyricLines(remoteViews4, musicService, true); - appWidgetManager.partiallyUpdateAppWidget(iArrIds4, remoteViews4); - } - } - } catch (Exception e) { - } - } else { - if (z4) { - if (Widgets.lastWave == 0) { - fMin = 0.3f; - } else { - fMin = Math.min(1.0f, (jElapsedRealtime - Widgets.lastWave) / 1000.0f); - } - long unused6 = Widgets.lastWave = jElapsedRealtime; - float unused7 = Widgets.phase = (float) (((double) ((fMin * 6.6f) + Widgets.phase)) % 6.283185307179586d); - remoteViews2 = new RemoteViews(applicationContext.getPackageName(), R.layout.widget_medium); - Widgets.progress(applicationContext, remoteViews2, musicService, musicService.positionFast()); - if (iArrIds2.length > 0) { - appWidgetManager.partiallyUpdateAppWidget(iArrIds2, remoteViews2); - } - if (iArrIds3.length > 0) { - appWidgetManager.partiallyUpdateAppWidget(iArrIds3, remoteViews2); - } - } - if (z5) { - remoteViews = new RemoteViews(applicationContext.getPackageName(), R.layout.widget_large); - Widgets.lyricLines(remoteViews, musicService, false); - if (iArrIds3.length > 0) { - appWidgetManager.partiallyUpdateAppWidget(iArrIds3, remoteViews); - } - if (iArrIds2.length > 0) { - appWidgetManager.partiallyUpdateAppWidget(iArrIds2, remoteViews); - } - if (iArrIds4.length > 0) { - RemoteViews remoteViews5 = new RemoteViews(applicationContext.getPackageName(), R.layout.widget_lyrics); - Widgets.lyricLines(remoteViews5, musicService, true); - appWidgetManager.partiallyUpdateAppWidget(iArrIds4, remoteViews5); - } - } - } - int iMin = z3 ? Math.min(1000, iArrRates[1]) : 1000; - if (z4) { - iMin = Math.min(iMin, iArrRates[0]); - } - if (z5) { - iMin = Math.min(iMin, Math.max(iArrRates[0], 100)); - } - App.MAIN.postDelayed(this, iMin); - } - }); - } - } -} diff --git a/docs/releases/2.0.4.md b/docs/releases/2.0.4.md index c7ef8c0..6839a35 100644 --- a/docs/releases/2.0.4.md +++ b/docs/releases/2.0.4.md @@ -6,5 +6,3 @@ with `install.sh` and `uninstall.sh` (`--system` for `/usr/local`, `--purge` to delete your data). - **Windows fixes:** links and "show in folder" open in the browser and Explorer (they did nothing before), and yt-dlp and ffmpeg no longer flash a console window. -- **Android is back:** `Mulberry-2.0.4-Android.apk` (Android 7 and up), rebuilt from source with the new icon. It is signed - with a new key, so uninstall the old Android 1.2.2 app first. diff --git a/docs/releases/2.0.5.md b/docs/releases/2.0.5.md deleted file mode 100644 index 5c30db4..0000000 --- a/docs/releases/2.0.5.md +++ /dev/null @@ -1,17 +0,0 @@ -# Mulberry 2.0.5 - -Scrobbling fixes on every platform (desktop, Android 2.0.5, iOS 1.0.7). - -- **Stuck scrobbles sent:** when Last.fm rejected the saved login, Mulberry stopped and never sent anything to - ListenBrainz either, so listens piled up. Now each service sends on its own. A dead Last.fm login signs you out - and keeps your scrobbles until you sign in again. Last.fm refuses scrobbles older than 14 days, so those are - dropped. Listens a service rejects are dropped too, instead of blocking the queue forever. -- **ListenBrainz done properly:** Connect checks your token and shows "Connected as …". Disconnect is there too, - and the token is hidden. Listens now include the MusicBrainz recording, release, release group, track, artist - and work ids, the ISRC, track and disc numbers, album artist, genres as tags, a Spotify link (if one is in the - comment), and the source for streams. Loving a track also sends feedback to ListenBrainz. -- **Correct MusicBrainz id:** the desktop app read the release-track id where it should read the recording id, and - sent it to Last.fm and ListenBrainz. Files with MusicBrainz tags are read again on the next library scan. -- **Last.fm:** desktop has **Log out**. On iOS, Sign out stays visible when scrobbling is switched off. - Settings show how many scrobbles are waiting for each service. -- **Android** now scrobbles to ListenBrainz (Settings › ListenBrainz › Connect). diff --git a/docs/releases/2.0.6.md b/docs/releases/2.0.6.md deleted file mode 100644 index fbceeb4..0000000 --- a/docs/releases/2.0.6.md +++ /dev/null @@ -1,19 +0,0 @@ -# Mulberry 2.0.6 - -Scrobbling fixes on every platform (desktop, Android 2.0.6, iOS 1.0.8). Replaces 2.0.5. - -- **Listens that never arrived:** a ListenBrainz or Last.fm send that failed was only tried again when the next - track ended or the app restarted. Waiting scrobbles are now retried every 2 minutes, on desktop, Android and iOS. -- **Nothing lost on quit:** the desktop app queues the track that is playing when you quit, and sends it on the - next start. On iOS a listen is sent as soon as it counts (half the track or 4 minutes), so closing the app - before the track ends no longer loses it. -- **Hidden window:** listening time keeps counting while the Mulberry window is hidden or on another workspace. -- **Scrobble log:** the desktop app writes what it queued, sent and why a send failed to `scrobble.log` in its - data folder (`~/.local/share/mulberry`). iOS writes the same to its log. -- **Last.fm while logged out:** Settings say nothing is sent until you log in, and how many scrobbles wait. - You can discard them. -- **Settings › Scrobbling:** each service has its own card with its own switch; buttons line up on the right. -- **iOS** builds include FFmpeg again (1.0.7 could be built without it). - -Note: ListenBrainz itself sometimes holds listens in a queue for an hour or more before they show on your page. -"Now playing" is not affected by that. diff --git a/ios/.gitignore b/ios/.gitignore index e442f1d..b89fd49 100644 --- a/ios/.gitignore +++ b/ios/.gitignore @@ -3,6 +3,6 @@ build/ *.deb .DS_Store # Built by Native/build-ffmpeg.sh -Native/ffmpeg +Native/ffmpeg/ # Decompiled Android app and screenshots used as the design reference (kept locally, not in git) reference/ diff --git a/ios/App/Audio/Player.swift b/ios/App/Audio/Player.swift index 7e6bdbb..1c32b8b 100644 --- a/ios/App/Audio/Player.swift +++ b/ios/App/Audio/Player.swift @@ -36,7 +36,6 @@ final class Player: ObservableObject { private var crossfading = false private var listenStart = Date() private var listened: Double = 0 - private var scrobbled = false // this play was already sent as a listen private var lastTick = Date() private var resumeAfterInterruption = false @@ -362,7 +361,6 @@ final class Player: ObservableObject { error = nil listenStart = Date() listened = 0 - scrobbled = false lastTick = Date() loadArtAndLyrics(s) let e = engine(for: s) @@ -410,7 +408,6 @@ final class Player: ObservableObject { duration = queue[i].duration listenStart = Date() listened = 0 - scrobbled = false loadArtAndLyrics(queue[i]) planNext(force: true) updateNowPlaying() @@ -466,7 +463,6 @@ final class Player: ObservableObject { duration = s.duration listenStart = Date() listened = 0 - scrobbled = false loadArtAndLyrics(s) updateNowPlaying() publishWidget() @@ -498,11 +494,6 @@ final class Player: ObservableObject { let now = Date() listened += now.timeIntervalSince(lastTick) lastTick = now - // Send the listen as soon as it counts, so it isn't lost if the app is closed before the track ends. - if !scrobbled, let s = current, Scrobbler.countsAsListen(s, listened: listened) { - scrobbled = true - Scrobbler.shared.finished(s, listened: listened, started: listenStart) - } (eng as? UniversalEngine)?.pollAdvance() planNext() if prefs.crossfade > 0, !crossfading, !stopAfterCurrent, !sleepAtTrackEnd, duration > Double(prefs.crossfade) * 2, @@ -520,8 +511,7 @@ final class Player: ObservableObject { private func finishListen() { guard let s = current, listened > 0 else { return } if listened >= min(30, max(1, duration * 0.5)) { PlayStats.shared.played(s) } - if !scrobbled { Scrobbler.shared.finished(s, listened: listened, started: listenStart) } - scrobbled = true + Scrobbler.shared.finished(s, listened: listened, started: listenStart) listened = 0 } diff --git a/ios/App/Model/Prefs.swift b/ios/App/Model/Prefs.swift index 8bf8a3f..008f5b2 100644 --- a/ios/App/Model/Prefs.swift +++ b/ios/App/Model/Prefs.swift @@ -27,8 +27,6 @@ final class Prefs: ObservableObject { @Published var lfmUser: String { didSet { d.set(lfmUser, forKey: "lfm_user") } } @Published var lfmSession: String { didSet { d.set(lfmSession, forKey: "lfm_session") } } @Published var lbToken: String { didSet { d.set(lbToken, forKey: "lb_token") } } - @Published var lbUser: String { didSet { d.set(lbUser, forKey: "lb_user") } } - @Published var lbEnabled: Bool { didSet { d.set(lbEnabled, forKey: "lb_enabled") } } @Published var shuffle: Bool { didSet { d.set(shuffle, forKey: "shuffle") } } @Published var repeatMode: Int { didSet { d.set(repeatMode, forKey: "repeat") } } // 0 off, 1 all, 2 one @Published var libTab: Int { didSet { d.set(libTab, forKey: "lib_tab") } } @@ -62,8 +60,6 @@ final class Prefs: ObservableObject { lfmUser = g("lfm_user", "") lfmSession = g("lfm_session", "") lbToken = g("lb_token", "") - lbUser = g("lb_user", "") - lbEnabled = g("lb_enabled", true) shuffle = g("shuffle", false) repeatMode = g("repeat", 0) libTab = g("lib_tab", 0) diff --git a/ios/App/Model/TagReader.swift b/ios/App/Model/TagReader.swift index ac85b7e..2bc747e 100644 --- a/ios/App/Model/TagReader.swift +++ b/ios/App/Model/TagReader.swift @@ -9,8 +9,6 @@ struct Tags { var cover: Data? var trackGain: Double? var albumGain: Double? - /// MusicBrainz ids and ISRC, keyed by ListenBrainz additional_info names; several values joined with "/". - var ids: [String: String] = [:] } enum TagReader { @@ -86,30 +84,7 @@ enum TagReader { case "LYRICS", "UNSYNCEDLYRICS", "UNSYNCED LYRICS": if t.lyrics.isEmpty { t.lyrics = v } case "REPLAYGAIN_TRACK_GAIN": t.trackGain = gain(v) case "REPLAYGAIN_ALBUM_GAIN": t.albumGain = gain(v) - default: - if let name = idNames[key.uppercased().replacingOccurrences(of: " ", with: "_")] { addId(name, v, &t) } - } - } - - /// Picard tag names (Vorbis / APE, and ID3 TXXX / MP4 freeform with spaces → "_") → ListenBrainz names. - static let idNames: [String: String] = [ - "MUSICBRAINZ_TRACKID": "recording_mbid", "MUSICBRAINZ_TRACK_ID": "recording_mbid", - "MUSICBRAINZ_ALBUMID": "release_mbid", "MUSICBRAINZ_ALBUM_ID": "release_mbid", - "MUSICBRAINZ_RELEASEGROUPID": "release_group_mbid", "MUSICBRAINZ_RELEASE_GROUP_ID": "release_group_mbid", - "MUSICBRAINZ_RELEASETRACKID": "track_mbid", "MUSICBRAINZ_RELEASE_TRACK_ID": "track_mbid", - "MUSICBRAINZ_ARTISTID": "artist_mbids", "MUSICBRAINZ_ARTIST_ID": "artist_mbids", - "MUSICBRAINZ_ALBUMARTISTID": "release_artist_mbids", "MUSICBRAINZ_ALBUM_ARTIST_ID": "release_artist_mbids", - "MUSICBRAINZ_WORKID": "work_mbids", "MUSICBRAINZ_WORK_ID": "work_mbids", - "ISRC": "isrc", - ] - - static func addId(_ name: String, _ v: String, _ t: inout Tags) { - let v = v.replacingOccurrences(of: "\0", with: "/").trimmingCharacters(in: .whitespacesAndNewlines) - guard !v.isEmpty else { return } - if let old = t.ids[name] { - if !old.split(separator: "/").contains(Substring(v)) { t.ids[name] = old + "/" + v } - } else { - t.ids[name] = v + default: break } } @@ -239,12 +214,6 @@ enum TagReader { case "TRCK", "TRK": if t.track == 0 { t.track = num(id3text(body)) } case "TPOS", "TPA": if t.disc == 0 { t.disc = num(id3text(body)) } case "TYER", "TYE", "TDRC", "TDOR": if t.year == 0 { t.year = num(String(id3text(body).prefix(4))) } - case "TSRC", "TRC": addId("isrc", id3text(body), &t) - case "UFID", "UFI": - let (owner, ident) = splitTerm(body, enc: 0) - if decode(owner, enc: 0) == "http://musicbrainz.org" { - addId("recording_mbid", String(decoding: ident, as: UTF8.self), &t) - } case "TXXX", "TXX": guard let enc = body.first else { return } let (k, v) = splitTerm(body.dropFirst(), enc: enc) diff --git a/ios/App/Services/Net.swift b/ios/App/Services/Net.swift index ba4101f..b6d2179 100644 --- a/ios/App/Services/Net.swift +++ b/ios/App/Services/Net.swift @@ -2,7 +2,7 @@ import Foundation /// Small blocking HTTP helpers for background work (Android Net.java). enum Net { - static let ua = "Mulberry/1.0 (iOS; +https://astar76.com/git/astar76/Mulberry)" + static let ua = "Mulberry/1.0 (iOS; +https://archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry)" private static let session: URLSession = { let c = URLSessionConfiguration.default @@ -40,26 +40,6 @@ enum Net { return try out.get() } - /// Request that hands back the status and body even for 4xx/5xx (Last.fm and ListenBrainz explain errors there). - static func status(_ url: String, headers: [String: String] = [:], method: String = "GET", body: Data? = nil, - contentType: String? = nil) throws -> (Int, [String: Any]) { - guard let u = URL(string: url) else { throw URLError(.badURL) } - var req = URLRequest(url: u) - req.httpMethod = method - req.httpBody = body - if let contentType { req.setValue(contentType, forHTTPHeaderField: "Content-Type") } - for (k, v) in headers { req.setValue(v, forHTTPHeaderField: k) } - let sem = DispatchSemaphore(value: 0) - var out: Result<(Int, Data), Error> = .failure(URLError(.unknown)) - session.dataTask(with: req) { d, r, e in - if let e { out = .failure(e) } else { out = .success(((r as? HTTPURLResponse)?.statusCode ?? 0, d ?? Data())) } - sem.signal() - }.resume() - sem.wait() - let (st, d) = try out.get() - return (st, (try? JSONSerialization.jsonObject(with: d)) as? [String: Any] ?? [:]) - } - static func get(_ url: String, headers: [String: String] = [:]) throws -> String { String(data: try data(url, headers: headers), encoding: .utf8) ?? "" } diff --git a/ios/App/Services/Scrobbler.swift b/ios/App/Services/Scrobbler.swift index 32a42c7..2aa5068 100644 --- a/ios/App/Services/Scrobbler.swift +++ b/ios/App/Services/Scrobbler.swift @@ -21,11 +21,6 @@ final class Scrobbler: NSObject, ObservableObject, ASWebAuthenticationPresentati var duration: Double var track: Int var ts: Int - // Added in 1.0.7 (optional so older queues still load). - var path: String? = nil - var disc: Int? = nil - var genre: String? = nil - var cue: Int? = nil } @Published private(set) var pending: [Entry] = [] @@ -41,15 +36,8 @@ final class Scrobbler: NSObject, ObservableObject, ASWebAuthenticationPresentati } private var prefs: Prefs { Prefs.shared } - var lfmLoggedIn: Bool { !prefs.lfmSession.isEmpty } - var lfmOn: Bool { prefs.lfmEnabled && lfmLoggedIn } - var lbConnected: Bool { !prefs.lbToken.isEmpty } - var lbOn: Bool { prefs.lbEnabled && lbConnected } - func pending(_ svc: String) -> Int { pending.filter { $0.svc == svc }.count } - - /// Last.fm errors meaning the session is dead / worth retrying later. - nonisolated static let authErrors: Set = [4, 9, 14] - nonisolated static let retryErrors: Set = [0, 11, 16, 29] + var lfmOn: Bool { prefs.lfmEnabled && !prefs.lfmSession.isEmpty } + var lbOn: Bool { !prefs.lbToken.isEmpty } nonisolated static func sign(_ params: [(String, String)]) -> [(String, String)] { let sorted = params.filter { $0.0 != "format" && $0.0 != "callback" }.sorted { $0.0 < $1.0 } @@ -62,20 +50,9 @@ final class Scrobbler: NSObject, ObservableObject, ASWebAuthenticationPresentati var p: [(String, String)] = [("method", method), ("api_key", key)] + params.filter { !$0.1.isEmpty } if let session { p.append(("sk", session)) } p = sign(p) + [("format", "json")] - let st: Int, o: [String: Any] - do { - (st, o) = post ? try Net.status(api, method: "POST", body: Data(Net.query(p).utf8), - contentType: "application/x-www-form-urlencoded; charset=utf-8") - : try Net.status(api + "?" + Net.query(p)) - } catch { - throw NSError(domain: "Last.fm", code: 0, userInfo: [NSLocalizedDescriptionKey: "Last.fm: " + error.localizedDescription]) - } - if o["error"] != nil { - let code = Int(o.num("error")) - if session != nil && authErrors.contains(code) { Task { @MainActor in Scrobbler.shared.sessionExpired() } } - throw NSError(domain: "Last.fm", code: code, userInfo: [NSLocalizedDescriptionKey: "Last.fm: " + o.str("message")]) - } - if st >= 400 { throw NSError(domain: "Last.fm", code: 0, userInfo: [NSLocalizedDescriptionKey: "Last.fm: HTTP \(st)"]) } + let res: Any = post ? try Net.postForm(api, p) : try Net.json(api + "?" + Net.query(p)) + guard let o = res as? [String: Any] else { throw URLError(.cannotParseResponse) } + if o["error"] != nil { throw NSError(domain: "Last.fm", code: 1, userInfo: [NSLocalizedDescriptionKey: "Last.fm: " + o.str("message")]) } return o } @@ -85,14 +62,12 @@ final class Scrobbler: NSObject, ObservableObject, ASWebAuthenticationPresentati if !e.albumArtist.isEmpty && e.albumArtist != e.artist { p.append(("albumArtist" + sfx, e.albumArtist)) } if e.duration > 0 { p.append(("duration" + sfx, String(Int(e.duration)))) } if e.track > 0 { p.append(("trackNumber" + sfx, String(e.track))) } - if let m = ids(e)["recording_mbid"]?.split(separator: "/").first { p.append(("mbid" + sfx, String(m))) } - if i != nil { p.append(("chosenByUser" + sfx, isStream(e) ? "0" : "1")) } return p } private func entry(_ s: Song, svc: String, ts: Int) -> Entry { Entry(svc: svc, artist: s.displayArtist, title: s.displayTitle, album: s.album, albumArtist: s.albumArtist, - duration: s.duration, track: s.track, ts: ts, path: s.path, disc: s.disc, genre: s.genre, cue: s.cueIndex) + duration: s.duration, track: s.track, ts: ts) } // MARK: Login (Last.fm web auth with a mulberry:// callback) @@ -119,7 +94,6 @@ final class Scrobbler: NSObject, ObservableObject, ASWebAuthenticationPresentati Prefs.shared.lfmUser = name Prefs.shared.lfmEnabled = true Scrobbler.shared.toast = "Signed in to Last.fm as \(name)" - Scrobbler.shared.flush() } } catch { await MainActor.run { Scrobbler.shared.toast = error.localizedDescription } @@ -136,55 +110,6 @@ final class Scrobbler: NSObject, ObservableObject, ASWebAuthenticationPresentati prefs.lfmSession = "" prefs.lfmUser = "" prefs.lfmEnabled = false - purge("lastfm") - } - - /// Last.fm dropped our session: forget it, keep the queue for the next sign-in. - func sessionExpired() { - guard !prefs.lfmSession.isEmpty else { return } - prefs.lfmSession = "" - toast = "Last.fm signed Mulberry out. Sign in again in Settings; scrobbles are kept." - } - - func purge(_ svc: String) { - pending.removeAll { $0.svc == svc } - save() - } - - // MARK: ListenBrainz account - - @Published var lbChecking = false - - func lbConnect(_ token: String) { - let token = token.trimmingCharacters(in: .whitespacesAndNewlines) - guard !token.isEmpty else { toast = "Paste your ListenBrainz user token first"; return } - lbChecking = true - Task.detached { - var msg: String - var name: String? - do { - let (_, r) = try Net.status("https://api.listenbrainz.org/1/validate-token", headers: ["Authorization": "Token \(token)"]) - if (r["valid"] as? Bool) == true { name = r.str("user_name"); msg = "Connected to ListenBrainz as \(name!)" } - else { msg = "ListenBrainz: " + (r.str("message").isEmpty ? "token not valid" : r.str("message")) } - } catch { msg = "ListenBrainz: " + error.localizedDescription } - await MainActor.run { [name, msg] in - let sc = Scrobbler.shared - sc.lbChecking = false - if let name { - sc.prefs.lbToken = token - sc.prefs.lbUser = name - sc.prefs.lbEnabled = true - sc.flush() - } - sc.toast = msg - } - } - } - - func lbDisconnect() { - prefs.lbToken = "" - prefs.lbUser = "" - purge("listenbrainz") } // MARK: Events from the player @@ -196,42 +121,26 @@ final class Scrobbler: NSObject, ObservableObject, ASWebAuthenticationPresentati let sk = prefs.lfmSession, lfm = lfmOn, lb = lbOn, token = prefs.lbToken Task.detached { if lfm { _ = try? Scrobbler.call("track.updateNowPlaying", Scrobbler.trackParams(e, nil), post: true, session: sk) } - if lb { Scrobbler.lbSubmit("playing_now", [Scrobbler.lbPayload(e, ts: nil)], token: token) } + if lb { _ = try? Scrobbler.lbSubmit("playing_now", [Scrobbler.lbPayload(e, ts: nil)], token: token) } } } - /// Retry queued scrobbles this often while playing (a failed send waits at most this long). - static let retrySeconds: TimeInterval = 120 - func progress(_ s: Song, listened: Double, duration: Double) { - if Date().timeIntervalSince(lastFlush) > Scrobbler.retrySeconds { lastFlush = Date(); flush() } - } - - /// Last.fm / ListenBrainz rule: half the track or 4 minutes; tracks under 30 s never count. - nonisolated static func countsAsListen(_ s: Song, listened: Double) -> Bool { - s.isStream ? listened >= 30 : s.duration >= 30 && listened >= min(s.duration / 2, 240) + if Date().timeIntervalSince(lastFlush) > 300 { lastFlush = Date(); flush() } } func finished(_ s: Song, listened: Double, started: Date) { - guard Scrobbler.countsAsListen(s, listened: listened), !s.displayArtist.isEmpty, !s.displayTitle.isEmpty else { return } + let dur = s.duration + let ok = s.isStream ? listened >= 30 : dur >= 30 && listened >= min(dur / 2, 240) + guard ok, !s.displayArtist.isEmpty, !s.displayTitle.isEmpty else { return } let ts = Int(started.timeIntervalSince1970) if lfmOn { pending.append(entry(s, svc: "lastfm", ts: ts)) } if lbOn { pending.append(entry(s, svc: "listenbrainz", ts: ts)) } - Log.i("scrobble queued (lastfm \(lfmOn), listenbrainz \(lbOn)): \(s.displayArtist) - \(s.displayTitle) at \(ts)") save() flush() } func love(_ s: Song, _ on: Bool) { - if lbOn { - let e = entry(s, svc: "", ts: 0), token = prefs.lbToken - Task.detached { - guard let mbid = Scrobbler.ids(e)["recording_mbid"]?.split(separator: "/").first else { return } - _ = try? Net.status("https://api.listenbrainz.org/1/feedback/recording-feedback", headers: ["Authorization": "Token \(token)"], - method: "POST", body: try? JSONSerialization.data(withJSONObject: ["recording_mbid": String(mbid), "score": on ? 1 : 0]), - contentType: "application/json") - } - } guard lfmOn else { return } let sk = prefs.lfmSession let a = s.displayArtist, t = s.displayTitle @@ -251,127 +160,56 @@ final class Scrobbler: NSObject, ObservableObject, ASWebAuthenticationPresentati private var flushing = false - /// Sends queued scrobbles. Each service goes on its own, so one failing never blocks the other. func flush() { guard !pending.isEmpty, !flushing else { return } flushing = true - let now = Int(Date().timeIntervalSince1970) - let lfmAll = pending.filter { $0.svc == "lastfm" } - let old = lfmAll.filter { now - $0.ts > 14 * 86400 } // Last.fm refuses scrobbles older than 14 days - let lfm = lfmAll.filter { now - $0.ts <= 14 * 86400 } - let lb = pending.filter { $0.svc == "listenbrainz" } + let lfm = Array(pending.filter { $0.svc == "lastfm" }.prefix(50)) + let lb = Array(pending.filter { $0.svc == "listenbrainz" }.prefix(100)) let sk = prefs.lfmSession, token = prefs.lbToken, lfmOn = lfmOn, lbOn = lbOn Task.detached { - var done: [Entry] = old - var sent = 0 + var done: [Entry] = [] var err: String? - if lfmOn { - for start in stride(from: 0, to: lfm.count, by: 50) { - let chunk = Array(lfm[start.. 1 ? "import" : "single", payload, token: token) - if st == 200 { done += chunk; sent += chunk.count; continue } - err = msg - guard st == 400 else { break } - // One bad listen spoils a batch: send them one by one and drop the bad ones. - for (e, p) in zip(chunk, payload) { - let (st1, msg1) = Scrobbler.lbSubmit("single", [p], token: token) - if st1 == 200 { done.append(e); sent += 1 } - else if st1 == 400 { done.append(e); err = msg1 } - else { err = msg1; break outer } - } - } + if !lb.isEmpty && lbOn { + do { + try Scrobbler.lbSubmit(lb.count > 1 ? "import" : "single", lb.map { Scrobbler.lbPayload($0, ts: $0.ts) }, token: token) + done += lb + } catch { err = error.localizedDescription } } - await MainActor.run { [done, sent, err] in + await MainActor.run { let sc = Scrobbler.shared sc.flushing = false sc.pending.removeAll { done.contains($0) } sc.save() - if sent > 0 { Log.i("scrobble sent \(sent)") } - if let err { Log.e("scrobble: \(err)") } - if sent == 0, let err { sc.toast = "Scrobbling deferred: \(err)" } + if let err { sc.toast = "Scrobbling deferred: \(err)" } } } } - /// MusicBrainz ids / ISRC read fresh from the local file (not for cue tracks, whose tags describe the whole file). - nonisolated static func ids(_ e: Entry) -> [String: String] { - guard let path = e.path, !isStream(e), (e.cue ?? 0) == 0 else { return [:] } - return TagReader.read(Library.root.appendingPathComponent(path)).ids - } - - nonisolated static func isStream(_ e: Entry) -> Bool { - (e.path ?? "").hasPrefix("http://") || (e.path ?? "").hasPrefix("https://") - } - // MARK: ListenBrainz - /// Full listen: https://listenbrainz.readthedocs.io/en/latest/users/json.html nonisolated static func lbPayload(_ e: Entry, ts: Int?) -> [String: Any] { - let stream = isStream(e) var meta: [String: Any] = ["artist_name": e.artist, "track_name": e.title] - if !e.album.isEmpty && !stream { meta["release_name"] = e.album } - let v = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "" - var info: [String: Any] = ["media_player": "Mulberry iOS", "media_player_version": v, - "submission_client": "Mulberry iOS", "submission_client_version": v] - for (k, val) in ids(e) { - let parts = val.split(separator: "/").map { String($0).trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } - if k.hasSuffix("_mbids") { - let uuids = parts.filter { $0.count == 36 } - if !uuids.isEmpty { info[k] = uuids } - } else if k == "isrc" { - if let p = parts.first { info[k] = p } - } else if let p = parts.first(where: { $0.count == 36 }) { - info[k] = p - } - } + if !e.album.isEmpty { meta["release_name"] = e.album } + var info: [String: Any] = ["media_player": "Mulberry", "submission_client": "Mulberry iOS"] if e.duration > 0 { info["duration_ms"] = Int(e.duration * 1000) } - if stream, let path = e.path { - info["origin_url"] = path - if let host = URL(string: path)?.host { info["music_service"] = host.hasPrefix("www.") ? String(host.dropFirst(4)) : host } - } else { - if e.track > 0 { info["tracknumber"] = e.track } - if let d = e.disc, d > 0 { info["discnumber"] = d } - if !e.albumArtist.isEmpty { info["release_artist_name"] = e.albumArtist } - let tags = (e.genre ?? "").split(whereSeparator: { ";/,".contains($0) }).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } - if !tags.isEmpty { info["tags"] = tags } - } + if e.track > 0 { info["tracknumber"] = e.track } meta["additional_info"] = info var p: [String: Any] = ["track_metadata": meta] if let ts { p["listened_at"] = ts } return p } - /// Gives (HTTP status, error message). Status 0 = no connection. - @discardableResult - nonisolated static func lbSubmit(_ type: String, _ payload: [[String: Any]], token: String) -> (Int, String) { - guard let body = try? JSONSerialization.data(withJSONObject: ["listen_type": type, "payload": payload]) else { return (400, "bad listen") } - do { - let (st, r) = try Net.status("https://api.listenbrainz.org/1/submit-listens", headers: ["Authorization": "Token \(token)"], - method: "POST", body: body, contentType: "application/json") - if st == 401 { return (401, "ListenBrainz token is not valid; connect again in Settings") } - return (st, st == 200 ? "" : "ListenBrainz: " + (r.str("error").isEmpty ? "HTTP \(st)" : r.str("error"))) - } catch { - return (0, "ListenBrainz: " + error.localizedDescription) - } + nonisolated static func lbSubmit(_ type: String, _ payload: [[String: Any]], token: String) throws { + _ = try Net.postJSON("https://api.listenbrainz.org/1/submit-listens", ["listen_type": type, "payload": payload], + headers: ["Authorization": "Token \(token)"]) } } diff --git a/ios/App/UI/NowPlayingView.swift b/ios/App/UI/NowPlayingView.swift index 3eb45fc..64f2e3e 100644 --- a/ios/App/UI/NowPlayingView.swift +++ b/ios/App/UI/NowPlayingView.swift @@ -231,8 +231,8 @@ struct NowPlayingView: View { items.append(.init("Details", "info.circle") { ui.details = s }) items.append(.init("Share", "square.and.arrow.up") { share([s.url]) }) } - if Scrobbler.shared.lfmOn || Scrobbler.shared.lbOn { - items.append(.init(Scrobbler.shared.lfmOn ? "Love on Last.fm" : "Love on ListenBrainz", "heart.circle") { Scrobbler.shared.love(s, true) }) + if Scrobbler.shared.lfmOn { + items.append(.init("Love on Last.fm", "heart.circle") { Scrobbler.shared.love(s, true) }) } ui.menu = MenuSheet(title: s.displayTitle, subtitle: s.subtitle, song: s, items: items) } diff --git a/ios/App/UI/SettingsView.swift b/ios/App/UI/SettingsView.swift index e8d13f4..9fd38b3 100644 --- a/ios/App/UI/SettingsView.swift +++ b/ios/App/UI/SettingsView.swift @@ -86,10 +86,10 @@ struct SettingsView: View { SectionLabel(text: "Last.fm") Card { - RowLabel(icon: "person.icloud", title: scrobbler.lfmLoggedIn ? "Signed in as \(prefs.lfmUser)" : "Not signed in", - sub: scrobbler.lfmLoggedIn ? (scrobbler.pending("lastfm") == 0 ? "All scrobbles sent" : "\(scrobbler.pending("lastfm")) scrobbles waiting to be sent") : (scrobbler.pending("lastfm") > 0 ? "Sign in again to send \(scrobbler.pending("lastfm")) waiting scrobbles" : "Sign in to scrobble directly from Mulberry")) - if scrobbler.lfmLoggedIn { - ToggleRow(icon: "dot.radiowaves.left.and.right", title: "Scrobble", sub: "“Now playing” and scrobbles after half the song or 4 minutes", on: $prefs.lfmEnabled) + RowLabel(icon: "person.icloud", title: scrobbler.lfmOn ? "Signed in as \(prefs.lfmUser)" : "Not signed in", + sub: scrobbler.lfmOn ? (scrobbler.pending.isEmpty ? "Scrobbling directly from Mulberry" : "\(scrobbler.pending.count) scrobbles waiting to be sent") : "Sign in to scrobble directly from Mulberry") + if scrobbler.lfmOn { + ToggleRow(icon: "dot.radiowaves.left.and.right", title: "Scrobble", sub: nil, on: $prefs.lfmEnabled) ButtonRow(icon: "rectangle.portrait.and.arrow.right", title: "Sign out", sub: nil) { scrobbler.logout() } } else { ButtonRow(icon: "person.badge.key", title: "Sign in to Last.fm", sub: nil) { scrobbler.login() } @@ -98,27 +98,16 @@ struct SettingsView: View { SectionLabel(text: "ListenBrainz") Card { - RowLabel(icon: "person.icloud", - title: scrobbler.lbChecking ? "Checking token…" : scrobbler.lbConnected ? (prefs.lbUser.isEmpty ? "Token saved" : "Connected as \(prefs.lbUser)") : "Not connected", - sub: scrobbler.lbConnected ? (scrobbler.pending("listenbrainz") == 0 ? "All listens sent" : "\(scrobbler.pending("listenbrainz")) listens waiting to be sent") : "Paste your user token from listenbrainz.org › Settings") - if scrobbler.lbConnected { - ToggleRow(icon: "dot.radiowaves.left.and.right", title: "Submit listens", sub: "With MusicBrainz ids, ISRC and more from your tags", on: $prefs.lbEnabled) - ButtonRow(icon: "key", title: "Change token", sub: nil) { lbToken = ""; askLB = true } - ButtonRow(icon: "rectangle.portrait.and.arrow.right", title: "Disconnect", sub: nil) { scrobbler.lbDisconnect() } - } else { - ButtonRow(icon: "key", title: "Connect ListenBrainz", sub: nil) { lbToken = ""; askLB = true } - ButtonRow(icon: "safari", title: "Get your token", sub: "listenbrainz.org/settings") { - if let u = URL(string: "https://listenbrainz.org/settings/") { UIApplication.shared.open(u) } - } - } + ButtonRow(icon: "key", title: prefs.lbToken.isEmpty ? "Add user token" : "Token saved", + sub: "Find it at listenbrainz.org › Settings") { lbToken = prefs.lbToken; askLB = true } } SectionLabel(text: "About") Card { RowLabel(icon: "info.circle", title: "Mulberry for iOS \(AppVersion.version)", sub: "Build \(AppVersion.build) · engine: \(Player.shared.engineName.isEmpty ? "—" : Player.shared.engineName) · Coded by Claude (Anthropic) · MIT licence") - ButtonRow(icon: "desktopcomputer", title: "Mulberry for desktop", sub: "astar76.com/git/astar76/Mulberry") { - if let u = URL(string: "https://astar76.com/git/astar76/Mulberry") { UIApplication.shared.open(u) } + ButtonRow(icon: "desktopcomputer", title: "Mulberry for desktop", sub: "archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry") { + if let u = URL(string: "https://archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry") { UIApplication.shared.open(u) } } } } @@ -129,8 +118,9 @@ struct SettingsView: View { .onAppear { cacheSize = Covers.cacheSize() } .sheet(isPresented: $showEQ) { EqualizerSheet().environmentObjects() } .alert("ListenBrainz token", isPresented: $askLB) { - SecureField("User token", text: $lbToken) - Button("Connect") { scrobbler.lbConnect(lbToken) } + TextField("User token", text: $lbToken) + Button("Save") { prefs.lbToken = lbToken.trimmingCharacters(in: .whitespaces) } + Button("Remove", role: .destructive) { prefs.lbToken = "" } Button("Cancel", role: .cancel) {} } .onChange(of: prefs.visualizer) { _ in } diff --git a/ios/VERSION b/ios/VERSION index b0f3d96..af0b7dd 100644 --- a/ios/VERSION +++ b/ios/VERSION @@ -1 +1 @@ -1.0.8 +1.0.6 diff --git a/ios/tools/deploy b/ios/tools/deploy index 62bdfdd..7b068fe 100755 --- a/ios/tools/deploy +++ b/ios/tools/deploy @@ -8,7 +8,7 @@ KEY=${IPHONE_KEY:-$HOME/.ssh/iphone_key} V=$(cat VERSION) IPA=build/Mulberry-$V-iOS.ipa ssh_=(ssh -i "$KEY" -o BatchMode=yes -o ConnectTimeout=10 "$IPHONE") -"${ssh_[@]}" 'mkdir -p /var/mobile/mulberry-build && find /var/mobile/mulberry-build -name "Mulberry-*" -delete' +"${ssh_[@]}" 'rm -f /var/mobile/mulberry-build/Mulberry-*.ipa /var/mobile/mulberry-build/Mulberry-*.deb' scp -q -i "$KEY" "$IPA" "build/Mulberry-$V-iOS-rootless.deb" "$IPHONE:/var/mobile/mulberry-build/" HELPER=/var/jb/Applications/TrollStoreLite.app/trollstorehelper if "${ssh_[@]}" "sudo -n $HELPER install /var/mobile/mulberry-build/$(basename "$IPA")" 2>/dev/null; then diff --git a/packaging/arch/.SRCINFO b/packaging/arch/.SRCINFO index 284e401..704189c 100644 --- a/packaging/arch/.SRCINFO +++ b/packaging/arch/.SRCINFO @@ -1,8 +1,8 @@ pkgbase = mulberry-bin pkgdesc = Material You music player - pkgver = 2.0.6 + pkgver = 2.0.4 pkgrel = 1 - url = https://astar76.com/git/astar76/Mulberry + url = https://archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry arch = x86_64 license = MIT depends = glibc>=2.35 @@ -29,7 +29,7 @@ pkgbase = mulberry-bin conflicts = mulberry options = !strip options = !debug - source = Mulberry-2.0.6-Linux-x86_64.tar.gz::https://astar76.com/git/astar76/Mulberry/releases/download/v2.0.6/Mulberry-2.0.6-Linux-x86_64.tar.gz - sha256sums = 429944f959f7f34865bb6f18a916eb24c3304c56085f2bec6185118c72f2124b + source = Mulberry-2.0.4-Linux-x86_64.tar.gz::https://archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry/releases/download/v2.0.4/Mulberry-2.0.4-Linux-x86_64.tar.gz + sha256sums = 87dab251e23593457ad3e3b2b8ca7903f79af385b805d276ec29e701785e5e5f pkgname = mulberry-bin diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILD index 251c5e3..e62f9c1 100644 --- a/packaging/arch/PKGBUILD +++ b/packaging/arch/PKGBUILD @@ -2,11 +2,11 @@ # Built by tools/package.sh from the release tar.gz (TARBALL=file://… for an offline build); it keeps pkgver, # sha256sums and the glibc floor current. pkgname=mulberry-bin -pkgver=2.0.6 +pkgver=2.0.4 pkgrel=1 pkgdesc='Material You music player' arch=('x86_64') -url='https://astar76.com/git/astar76/Mulberry' +url='https://archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry' license=('MIT') depends=('glibc>=2.35' 'gcc-libs' 'mpv' 'dbus' 'fontconfig' 'libglvnd' 'wayland' 'libxkbcommon' 'libxkbcommon-x11' 'libx11' 'libxcb' 'libxcursor' 'libxi' 'libxrender' 'hicolor-icon-theme') optdepends=( @@ -20,7 +20,7 @@ provides=('mulberry') conflicts=('mulberry') options=('!strip' '!debug') source=("Mulberry-$pkgver-Linux-x86_64.tar.gz::${TARBALL:-$url/releases/download/v$pkgver/Mulberry-$pkgver-Linux-x86_64.tar.gz}") -sha256sums=('429944f959f7f34865bb6f18a916eb24c3304c56085f2bec6185118c72f2124b') +sha256sums=('87dab251e23593457ad3e3b2b8ca7903f79af385b805d276ec29e701785e5e5f') package() { cd "$srcdir/mulberry-$pkgver" diff --git a/packaging/mulberry.iss b/packaging/mulberry.iss index 2fff17f..8e33c40 100644 --- a/packaging/mulberry.iss +++ b/packaging/mulberry.iss @@ -16,7 +16,7 @@ AppName=Mulberry AppVersion={#Version} AppVerName=Mulberry {#Version} AppPublisher=astar76 -AppPublisherURL=https://astar76.com/git/astar76/Mulberry +AppPublisherURL=https://archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry VersionInfoVersion={#Version} VersionInfoProductName=Mulberry VersionInfoDescription=Mulberry Setup diff --git a/packaging/nix/default.nix b/packaging/nix/default.nix index 286dc8d..63b1c8e 100644 --- a/packaging/nix/default.nix +++ b/packaging/nix/default.nix @@ -4,10 +4,10 @@ stdenv.mkDerivation rec { pname = "mulberry"; - version = "2.0.6"; + version = "2.0.4"; src = fetchurl { - url = "https://astar76.com/git/astar76/Mulberry/releases/download/v${version}/Mulberry-${version}-Linux-x86_64.tar.gz"; - hash = "sha256-QplE+Vn380hlu28YqRbrJMMwTFYIXyvsYYURjHLyEks="; + url = "https://archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry/releases/download/v${version}/Mulberry-${version}-Linux-x86_64.tar.gz"; + hash = "sha256-h9qyUeI1k0V60+OyuMp5A/ea84W4BdJ27CnnAXheXl8="; }; nativeBuildInputs = [ autoPatchelfHook makeWrapper ]; buildInputs = [ mpv-unwrapped stdenv.cc.cc.lib ]; @@ -24,7 +24,7 @@ stdenv.mkDerivation rec { meta = { description = "Material You music player"; - homepage = "https://astar76.com/git/astar76/Mulberry"; + homepage = "https://archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry"; license = lib.licenses.mit; platforms = [ "x86_64-linux" ]; mainProgram = "mulberry"; diff --git a/src/app.rs b/src/app.rs index 5ceb927..e38c304 100644 --- a/src/app.rs +++ b/src/app.rs @@ -283,7 +283,6 @@ impl App { Msg::CoverFull { token, bytes } => crate::ui::dialogs::on_cover_full(self, token, bytes), Msg::MbResults { token, items } => crate::ui::dialogs::on_mb_results(self, token, items), Msg::ConnectLastFm(r) => crate::ui::dialogs::on_lastfm_connected(self, r), - Msg::ConnectListenBrainz(r) => crate::ui::dialogs::on_listenbrainz_connected(self, r), } } } @@ -812,7 +811,6 @@ impl App { let _ = self.player.tick(&mut self.mgr, &self.lib); self.drain_notes(); self.mgr.save_if_due(&self.lib); - self.scrobbler.maybe_periodic(); self.maybe_notify(); self.publish_mpris(); if self.player.is_playing() && self.last_pos_save.elapsed() > Duration::from_secs(5) { @@ -856,8 +854,6 @@ impl App { self.lib.set_kv("resume_pos", &if self.player.song.is_some() { format!("{:.1}", self.player.pos()) } else { "0".into() }); self.mgr.save_all(&self.lib); self.lib.stop_scan(); - self.player.report_listen_on_quit(); - self.drain_notes(); self.player.shutdown(); self.ctx.send_viewport_cmd(egui::ViewportCommand::Close); // never hang on exit (mpv/D-Bus threads): leave for sure shortly after the window closes @@ -1083,7 +1079,6 @@ impl eframe::App for App { let _ = self.player.tick(&mut self.mgr, &self.lib); self.drain_notes(); self.mgr.save_if_due(&self.lib); - self.scrobbler.maybe_periodic(); if self.player.song.is_some() { let p = self.player.pos(); self.spectrum.set_position(p); @@ -1156,8 +1151,6 @@ impl App { self.lib.set_kv("resume_pos", &if self.player.song.is_some() { format!("{:.1}", self.player.pos()) } else { "0".into() }); self.mgr.save_all(&self.lib); self.lib.stop_scan(); - self.player.report_listen_on_quit(); - self.drain_notes(); self.player.shutdown(); } } diff --git a/src/bus.rs b/src/bus.rs index f12c455..978a425 100644 --- a/src/bus.rs +++ b/src/bus.rs @@ -33,8 +33,6 @@ pub enum Msg { /// Result of a background job the UI shows as a toast. Done { toast: String }, ConnectLastFm(Result<(String, String), String>), - /// (token, user name) after checking a ListenBrainz token. - ConnectListenBrainz(Result<(String, String), String>), } #[derive(Clone, Debug, Default)] diff --git a/src/config.rs b/src/config.rs index eac7a65..f99249b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -7,7 +7,7 @@ use std::sync::{LazyLock, RwLock}; pub const APP_NAME: &str = "Mulberry"; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); -pub const USER_AGENT: &str = concat!("Mulberry/", env!("CARGO_PKG_VERSION"), " ( https://astar76.com/git/astar76/Mulberry )"); +pub const USER_AGENT: &str = concat!("Mulberry/", env!("CARGO_PKG_VERSION"), " ( https://archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry )"); fn xdg(var: &str, default: &str) -> PathBuf { match std::env::var_os(var) { @@ -111,7 +111,6 @@ fn defaults() -> BTreeMap<&'static str, Value> { ("lastfm/user", json!("")), ("listenbrainz/enabled", json!(false)), ("listenbrainz/token", json!("")), - ("listenbrainz/user", json!("")), ("online/auto_lyrics", json!(true)), ("online/auto_covers", json!(true)), ("online/save_covers_to_folder", json!(false)), diff --git a/src/library.rs b/src/library.rs index cd270f1..65fabf6 100644 --- a/src/library.rs +++ b/src/library.rs @@ -143,11 +143,6 @@ impl Library { con.execute_batch(SCHEMA).expect("create schema"); let lib = Library { con: Mutex::new(con), scanning: Arc::new(AtomicBool::new(false)), abort: Arc::new(AtomicBool::new(false)) }; let empty = lib.con().query_row("SELECT 1 FROM radio LIMIT 1", [], |_| Ok(())).is_err(); - if lib.kv("mbid_recording_fix").is_none() { - // Older builds stored the release-track MBID as mb_trackid; re-read those files on the next scan. - let _ = lib.con().execute("UPDATE songs SET mtime=0 WHERE mb_trackid<>''", []); - lib.set_kv("mbid_recording_fix", "1"); - } if empty && lib.kv("radio_seeded").is_none() { let c = lib.con(); for (i, (name, url)) in DEFAULT_RADIO.iter().enumerate() { diff --git a/src/online.rs b/src/online.rs index ecb68b8..8fd0820 100644 --- a/src/online.rs +++ b/src/online.rs @@ -42,44 +42,19 @@ pub fn http_get_bytes(url: &str) -> Res> { resp.body_mut().with_config().limit(40 * 1024 * 1024).read_to_vec().map_err(|e| e.to_string()) } -/// Agent that hands back 4xx/5xx bodies instead of erroring (Last.fm and ListenBrainz put the reason there). -fn agent_raw() -> ureq::Agent { - ureq::Agent::config_builder() - .timeout_global(Some(Duration::from_secs(20))) - .user_agent(USER_AGENT) - .http_status_as_error(false) - .build() - .into() -} - -fn read_st(mut resp: ureq::http::Response) -> (u16, Value) { - let st = resp.status().as_u16(); - (st, resp.body_mut().read_json::().unwrap_or(Value::Null)) -} - -/// GET returning (status, json body); Err only for network failures. -pub fn http_get_json_st(url: &str, params: &[(&str, String)], headers: &[(&str, &str)]) -> Res<(u16, Value)> { - let mut req = agent_raw().get(url); - for (k, v) in params { - req = req.query(*k, v); - } - for (k, v) in headers { - req = req.header(*k, *v); - } - req.call().map(read_st).map_err(|e| e.to_string()) -} - -pub fn http_post_form_st(url: &str, form: &[(String, String)]) -> Res<(u16, Value)> { +pub fn http_post_form(url: &str, form: &[(String, String)]) -> Res { let items: Vec<(&str, &str)> = form.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect(); - agent_raw().post(url).send_form(items).map(read_st).map_err(|e| e.to_string()) + let mut resp = agent().post(url).send_form(items).map_err(|e| e.to_string())?; + resp.body_mut().read_json::().map_err(|e| e.to_string()) } -pub fn http_post_json_st(url: &str, body: &Value, headers: &[(&str, &str)]) -> Res<(u16, Value)> { - let mut req = agent_raw().post(url); +pub fn http_post_json(url: &str, body: &Value, headers: &[(&str, &str)]) -> Res { + let mut req = agent().post(url); for (k, v) in headers { req = req.header(*k, *v); } - req.send_json(body).map(read_st).map_err(|e| e.to_string()) + let mut resp = req.send_json(body).map_err(|e| e.to_string())?; + resp.body_mut().read_json::().map_err(|e| e.to_string()) } static MB_LAST: LazyLock> = LazyLock::new(|| Mutex::new(Instant::now() - Duration::from_secs(5))); diff --git a/src/player.rs b/src/player.rs index c3496b5..a2cb359 100644 --- a/src/player.rs +++ b/src/player.rs @@ -362,10 +362,6 @@ pub struct Player { next_engine_id: u8, } -/// Frames stall while the window is hidden (Wayland sends no frame callbacks), but the music keeps -/// playing, so long gaps between ticks still count as listening. Longer than this = the PC slept. -const MAX_TICK_GAP: f64 = 60.0; - fn now_ts() -> i64 { crate::library::now_secs() } @@ -800,16 +796,6 @@ impl Player { self.listen = 0.0; } - /// Report the playing track's listen before the app quits, so it is queued (and sent on the next start). - pub fn report_listen_on_quit(&mut self) { - if let Some(song) = &self.song { - if self.listen > 1.0 { - self.notes.push(Note::TrackFinished { song: song.clone(), listened: self.listen, start_ts: self.start_ts }); - } - } - self.listen = 0.0; - } - fn on_ended(&mut self, mgr: &mut Manager, lib: &Library) { if self.errors >= 5 { self.errors = 0; @@ -871,8 +857,6 @@ impl Player { self.xf_step(); } if self.state != "playing" { - // a pause must not count as listening when playback resumes - self.last_tick = None; return self.xf_t0.is_some(); } if now.duration_since(self.last_poll).as_millis() >= 40 { @@ -888,7 +872,7 @@ impl Player { } if let Some(t) = self.last_tick { let dt = now.duration_since(t).as_secs_f64(); - if dt > 0.0 && dt < MAX_TICK_GAP { + if dt > 0.0 && dt < 2.0 { self.listen += dt; } } diff --git a/src/scrobble.rs b/src/scrobble.rs index 83e98c8..7de7c5e 100644 --- a/src/scrobble.rs +++ b/src/scrobble.rs @@ -3,34 +3,15 @@ use crate::bus::{Bus, Msg}; use crate::config::{settings, PATHS}; use crate::library::{song_from_json, song_to_json}; -use crate::online::{http_get_json_st, http_post_form_st, http_post_json_st, lastfm_key}; +use crate::online::{http_get_json, http_post_form, http_post_json, lastfm_key}; use crate::song::Song; use serde_json::{json, Value}; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Instant; const LFM_API: &str = "https://ws.audioscrobbler.com/2.0/"; pub const CALLBACK_PORT: u16 = 47823; -/// Log of scrobble sends and errors (stdout/stderr go nowhere in the desktop app). -/// Rotated to scrobble.log.old past this size, so it never grows without bound. -const LOG_MAX_BYTES: u64 = 256 * 1024; - -pub fn log(line: &str) { - use std::io::Write; - let path = PATHS.data.join("scrobble.log"); - if std::fs::metadata(&path).map(|m| m.len() > LOG_MAX_BYTES).unwrap_or(false) { - let _ = std::fs::rename(&path, PATHS.data.join("scrobble.log.old")); - } - if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&path) { - let _ = writeln!(f, "{} {line}", chrono::Utc::now().format("%Y-%m-%d %H:%M:%SZ")); - } -} - -/// Retry queued scrobbles this often after a failed send (also catches anything a crash left behind). -const RETRY_SECS: u64 = 120; - pub fn has_key() -> bool { let (k, s) = lastfm_key(); !k.is_empty() && !s.is_empty() @@ -45,13 +26,7 @@ fn sign(params: &mut Vec<(String, String)>) { params.push(("api_sig".into(), sig)); } -/// Last.fm error codes that mean the saved session no longer works. -const LFM_AUTH_ERRORS: [i64; 3] = [4, 9, 14]; -/// Last.fm error codes worth retrying later (offline, temporary, rate limit). -const LFM_RETRY_ERRORS: [i64; 3] = [11, 16, 29]; - -/// Last.fm call; on failure gives (error code, message). Code 0 = network/HTTP problem. -pub fn lfm_raw(method: &str, params: Vec<(String, String)>, post: bool, auth: bool) -> Result { +pub fn lfm_call(method: &str, params: Vec<(String, String)>, post: bool, auth: bool) -> Result { let (key, _) = lastfm_key(); let mut p: Vec<(String, String)> = vec![("method".into(), method.into()), ("api_key".into(), key)]; p.extend(params.into_iter().filter(|(_, v)| !v.is_empty())); @@ -60,38 +35,18 @@ pub fn lfm_raw(method: &str, params: Vec<(String, String)>, post: bool, auth: bo } sign(&mut p); p.push(("format".into(), "json".into())); - let (st, res) = if post { - http_post_form_st(LFM_API, &p) + let res = if post { + http_post_form(LFM_API, &p)? } else { let q: Vec<(&str, String)> = p.iter().map(|(k, v)| (k.as_str(), v.clone())).collect(); - http_get_json_st(LFM_API, &q, &[]) - } - .map_err(|e| (0, format!("Last.fm: {e}")))?; - if let Some(code) = res.get("error").and_then(Value::as_i64) { - return Err((code, format!("Last.fm: {}", res["message"].as_str().unwrap_or("error")))); - } - if st >= 400 { - return Err((0, format!("Last.fm: HTTP {st}"))); + http_get_json(LFM_API, &q, &[])? + }; + if let Some(err) = res.get("error") { + return Err(format!("Last.fm: {}", res["message"].as_str().unwrap_or(&err.to_string()))); } Ok(res) } -pub fn lfm_call(method: &str, params: Vec<(String, String)>, post: bool, auth: bool) -> Result { - lfm_raw(method, params, post, auth).map_err(|(code, msg)| { - if auth && LFM_AUTH_ERRORS.contains(&code) { - lfm_session_expired() - } else { - msg - } - }) -} - -/// Forget a dead session so we stop hammering Last.fm; queued scrobbles wait for the next login. -fn lfm_session_expired() -> String { - settings().set("lastfm/session", ""); - "Last.fm logged Mulberry out. Log in again in Settings › Scrobbling; queued scrobbles are kept.".into() -} - pub fn begin_auth() -> Result { let res = lfm_call("auth.getToken", vec![], false, false)?; res["token"].as_str().map(String::from).ok_or_else(|| "no token".into()) @@ -140,111 +95,52 @@ pub fn start_login(bus: Bus) -> Result<(), String> { Ok(()) } -/// Artist and title, split from "Artist - Title" for radio streams. -fn artist_title(s: &Song) -> (String, String) { - if s.is_stream() && s.stream_title.contains(" - ") { - let (a, t) = s.stream_title.split_once(" - ").unwrap(); - return (a.trim().into(), t.trim().into()); - } - (s.display_artist(), s.display_title()) -} - -/// MusicBrainz ids / ISRC read fresh from a local file (not for cue sheet tracks, whose tags describe the whole file). -fn file_ids(s: &Song) -> serde_json::Map { - if s.is_local() && !s.is_cd() && s.end <= 0.0 { - crate::tags::scrobble_ids(&s.path()) - } else { - Default::default() - } -} - -fn recording_mbid(s: &Song, ids: &serde_json::Map) -> String { - ids.get("recording_mbid").and_then(Value::as_str).map(String::from).unwrap_or_else(|| s.mb_trackid.clone()) -} - fn track_params(s: &Song, idx: Option) -> Vec<(String, String)> { let sfx = idx.map(|i| format!("[{i}]")).unwrap_or_default(); - let (artist, title) = artist_title(s); + let (mut artist, mut title) = (s.display_artist(), s.display_title()); + if s.is_stream() && s.stream_title.contains(" - ") { + let (a, t) = s.stream_title.split_once(" - ").unwrap(); + artist = a.trim().into(); + title = t.trim().into(); + } let mut p = vec![(format!("artist{sfx}"), artist), (format!("track{sfx}"), title)]; if !s.album.is_empty() && !s.is_stream() { p.push((format!("album{sfx}"), s.album.clone())); } - if !s.albumartist.is_empty() && !s.is_stream() { + if !s.albumartist.is_empty() && s.albumartist != s.artist { p.push((format!("albumArtist{sfx}"), s.albumartist.clone())); } - if s.track > 0 && !s.is_stream() { + if s.track > 0 { p.push((format!("trackNumber{sfx}"), s.track.to_string())); } if s.duration() > 0.0 { p.push((format!("duration{sfx}"), (s.duration() as i64).to_string())); } - let mbid = recording_mbid(s, &file_ids(s)); - if !mbid.is_empty() { - p.push((format!("mbid{sfx}"), mbid)); - } - if idx.is_some() { - p.push((format!("chosenByUser{sfx}"), if s.is_stream() { "0" } else { "1" }.into())); + if !s.mb_trackid.is_empty() { + p.push((format!("mbid{sfx}"), s.mb_trackid.clone())); } p } -fn host_of(url: &str) -> String { - url.split("://").nth(1).unwrap_or("").split(['/', ':', '?']).next().unwrap_or("").trim_start_matches("www.").to_string() -} - -/// Full ListenBrainz listen: https://listenbrainz.readthedocs.io/en/latest/users/json.html fn lb_payload(s: &Song, ts: Option) -> Value { - let (artist, title) = artist_title(s); - let ids = file_ids(s); - let mut info = json!({ - "media_player": "Mulberry", - "media_player_version": crate::config::VERSION, - "submission_client": "Mulberry", - "submission_client_version": crate::config::VERSION, - }); - let a = info.as_object_mut().unwrap(); - for (k, v) in &ids { - a.insert(k.clone(), v.clone()); - } - let rec = recording_mbid(s, &ids); - if !rec.is_empty() { - a.insert("recording_mbid".into(), json!(rec)); - } - if !a.contains_key("release_mbid") && !s.mb_albumid.is_empty() { - a.insert("release_mbid".into(), json!(s.mb_albumid)); + let (mut artist, mut title) = (s.display_artist(), s.display_title()); + if s.is_stream() && s.stream_title.contains(" - ") { + let (a, t) = s.stream_title.split_once(" - ").unwrap(); + artist = a.trim().into(); + title = t.trim().into(); } + let mut info = json!({"media_player": "Mulberry", "submission_client": "Mulberry", "submission_client_version": crate::config::VERSION}); if s.duration() > 0.0 { - a.insert("duration_ms".into(), json!((s.duration() * 1000.0) as i64)); + info["duration_ms"] = json!((s.duration() * 1000.0) as i64); } - if s.is_stream() { - a.insert("origin_url".into(), json!(s.url)); - let host = host_of(&s.url); - if !host.is_empty() { - a.insert("music_service".into(), json!(host)); - } - } else { - if s.track > 0 { - a.insert("tracknumber".into(), json!(s.track)); - } - if s.disc > 0 { - a.insert("discnumber".into(), json!(s.disc)); - } - if !s.albumartist.is_empty() { - a.insert("release_artist_name".into(), json!(s.albumartist)); - } - let tags: Vec<&str> = s.genre.split([';', '/', ',']).map(str::trim).filter(|g| !g.is_empty()).collect(); - if !tags.is_empty() { - a.insert("tags".into(), json!(tags)); - } - if let Some(i) = s.comment.find("open.spotify.com/track/") { - let id: String = s.comment[i + 23..].chars().take_while(|c| c.is_ascii_alphanumeric()).collect(); - if !id.is_empty() { - a.insert("spotify_id".into(), json!(format!("https://open.spotify.com/track/{id}"))); - } - } + if !s.mb_trackid.is_empty() { + info["recording_mbid"] = json!(s.mb_trackid); + } + if !s.mb_albumid.is_empty() { + info["release_mbid"] = json!(s.mb_albumid); } let mut meta = json!({"artist_name": artist, "track_name": title, "additional_info": info}); - if !s.album.is_empty() && !s.is_stream() { + if !s.album.is_empty() { meta["release_name"] = json!(s.album); } let mut p = json!({"track_metadata": meta}); @@ -254,32 +150,9 @@ fn lb_payload(s: &Song, ts: Option) -> Value { p } -const LB_API: &str = "https://api.listenbrainz.org/1"; - -/// POST to ListenBrainz; Err gives (HTTP status, message). Status 0 = network problem. -fn lb_post(path: &str, body: &Value) -> Result { +fn lb_submit(kind: &str, payload: Vec) -> Result { let token = format!("Token {}", settings().get_str("listenbrainz/token")); - let (st, res) = http_post_json_st(&format!("{LB_API}/{path}"), body, &[("Authorization", &token)]).map_err(|e| (0, format!("ListenBrainz: {e}")))?; - if st >= 400 { - let msg = res["error"].as_str().map(String::from).unwrap_or_else(|| format!("HTTP {st}")); - return Err((st, format!("ListenBrainz: {msg}"))); - } - Ok(res) -} - -fn lb_submit(kind: &str, payload: Vec) -> Result { - lb_post("submit-listens", &json!({"listen_type": kind, "payload": payload})) -} - -/// Check a user token; gives the ListenBrainz user name. -pub fn lb_validate(token: &str) -> Result { - let auth = format!("Token {}", token.trim()); - let (_, res) = http_get_json_st(&format!("{LB_API}/validate-token"), &[], &[("Authorization", &auth)])?; - if res["valid"].as_bool() == Some(true) { - Ok(res["user_name"].as_str().unwrap_or("").to_string()) - } else { - Err(res["message"].as_str().unwrap_or("Token not valid").to_string()) - } + http_post_json("https://api.listenbrainz.org/1/submit-listens", &json!({"listen_type": kind, "payload": payload}), &[("Authorization", &token)]) } pub fn lfm_on() -> bool { @@ -295,14 +168,12 @@ pub struct Scrobbler { cache: Arc>>, announced: Option<(String, Instant)>, last_flush: Instant, - /// One flush at a time, so two threads never send the same queued listen. - busy: Arc, } impl Scrobbler { pub fn new(bus: Bus) -> Scrobbler { let cache: Vec = std::fs::read_to_string(PATHS.data.join("scrobble_cache.json")).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default(); - let s = Scrobbler { bus, cache: Arc::new(Mutex::new(cache)), announced: None, last_flush: Instant::now(), busy: Default::default() }; + let s = Scrobbler { bus, cache: Arc::new(Mutex::new(cache)), announced: None, last_flush: Instant::now() }; s.flush_later(10); s } @@ -315,18 +186,6 @@ impl Scrobbler { self.cache.lock().unwrap().len() } - /// Queued scrobbles for one service ("lastfm" / "listenbrainz"). - pub fn pending_for(&self, svc: &str) -> usize { - self.cache.lock().unwrap().iter().filter(|e| e["svc"] == svc).count() - } - - /// Drop the queue of a service the user disconnected. - pub fn purge(&self, svc: &str) { - let mut c = self.cache.lock().unwrap(); - c.retain(|e| e["svc"] != svc); - Self::save(&c); - } - /// Announce "now playing" (also when playback resumes after a long pause). pub fn track_started(&mut self, s: &Song) { self.announced = Some((s.key(), Instant::now())); @@ -338,15 +197,13 @@ impl Scrobbler { let (bus, song) = (bus.clone(), song.clone()); std::thread::spawn(move || { if let Err(e) = lfm_call("track.updateNowPlaying", track_params(&song, None), true, true) { - log(&format!("lastfm now playing failed: {e}")); bus.toast(e); } }); } if lb_on() { std::thread::spawn(move || { - if let Err((_, e)) = lb_submit("playing_now", vec![lb_payload(&song, None)]) { - log(&format!("listenbrainz now playing failed: {e}")); + if let Err(e) = lb_submit("playing_now", vec![lb_payload(&song, None)]) { bus.toast(e); } }); @@ -364,9 +221,9 @@ impl Scrobbler { } pub fn track_finished(&mut self, s: &Song, listened: f64, started: i64) { - let name = format!("{} - {}", s.display_artist(), s.display_title()); - if !counts_as_listen(s.is_stream(), s.duration(), listened) || s.display_artist().is_empty() || s.display_title().is_empty() { - log(&format!("not a listen ({listened:.0} of {:.0} s): {name}", s.duration())); + let dur = s.duration(); + let ok = if s.is_stream() { listened >= 30.0 } else { dur >= 30.0 && listened >= (dur / 2.0).min(240.0) }; + if !ok || s.display_artist().is_empty() || s.display_title().is_empty() { return; } let mut entry = json!({"song": song_to_json(s), "ts": started, "stream_title": s.stream_title}); @@ -382,12 +239,11 @@ impl Scrobbler { } Self::save(&c); } - log(&format!("queued (lastfm {}, listenbrainz {}): {name} at {started}", lfm_on(), lb_on())); self.flush(); } fn flush_later(&self, secs: u64) { - let s = Scrobbler { bus: self.bus.clone(), cache: self.cache.clone(), announced: None, last_flush: Instant::now(), busy: self.busy.clone() }; + let s = Scrobbler { bus: self.bus.clone(), cache: self.cache.clone(), announced: None, last_flush: Instant::now() }; std::thread::spawn(move || { std::thread::sleep(std::time::Duration::from_secs(secs)); s.flush(); @@ -395,25 +251,21 @@ impl Scrobbler { } pub fn maybe_periodic(&mut self) { - if self.last_flush.elapsed().as_secs() > RETRY_SECS { + if self.last_flush.elapsed().as_secs() > 300 { self.last_flush = Instant::now(); self.flush(); } } pub fn flush(&self) { - if self.cache.lock().unwrap().is_empty() || self.busy.swap(true, Ordering::SeqCst) { + if self.cache.lock().unwrap().is_empty() { return; } - let (cache, bus, busy) = (self.cache.clone(), self.bus.clone(), self.busy.clone()); - std::thread::spawn(move || { - let r = flush_work(&cache); - busy.store(false, Ordering::SeqCst); - match r { - Ok(n) if n > 0 => bus.toast(format!("Scrobbled {n} track(s)")), - Ok(_) => {} - Err(e) => bus.toast(format!("Scrobbling deferred: {e}")), - } + let (cache, bus) = (self.cache.clone(), self.bus.clone()); + std::thread::spawn(move || match flush_work(&cache) { + Ok(n) if n > 0 => bus.toast(format!("Scrobbled {n} track(s)")), + Ok(_) => {} + Err(e) => bus.toast(format!("Scrobbling deferred: {e}")), }); } @@ -429,172 +281,46 @@ impl Scrobbler { } }); } - if lb_on() { - let mbid = recording_mbid(s, &file_ids(s)); - if mbid.is_empty() { - if loved { - bus.toast("ListenBrainz needs a MusicBrainz recording id to love a track"); - } - return; - } + if lb_on() && !s.mb_trackid.is_empty() { + let mbid = s.mb_trackid.clone(); std::thread::spawn(move || { - match lb_post("feedback/recording-feedback", &json!({"recording_mbid": mbid, "score": if loved { 1 } else { 0 }})) { - Ok(_) => bus.toast(if loved { "Loved on ListenBrainz" } else { "Unloved on ListenBrainz" }), - Err((_, e)) => bus.toast(e), - } + let token = format!("Token {}", settings().get_str("listenbrainz/token")); + let _ = http_post_json("https://api.listenbrainz.org/1/feedback/recording-feedback", &json!({"recording_mbid": mbid, "score": if loved { 1 } else { 0 }}), &[("Authorization", &token)]); }); } } } -/// Send queued scrobbles. Each service goes on its own, so one failing never blocks the other. fn flush_work(cache: &Arc>>) -> Result { let pending: Vec = cache.lock().unwrap().clone(); let svc = |e: &Value, n: &str| e["svc"] == n; + let lfm: Vec<&Value> = pending.iter().filter(|e| svc(e, "lastfm")).take(50).collect(); + let lb: Vec<&Value> = pending.iter().filter(|e| svc(e, "listenbrainz")).take(100).collect(); + let mut sent = 0; + let mut done: Vec = vec![]; let song_of = |e: &Value| { let mut s = song_from_json(&e["song"]); s.stream_title = e["stream_title"].as_str().unwrap_or("").into(); s }; - let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0); - let mut sent = 0; - let mut done: Vec = vec![]; - let mut errors: Vec = vec![]; - - // Last.fm refuses scrobbles older than 14 days. - let (old, lfm): (Vec<&Value>, Vec<&Value>) = pending.iter().filter(|e| svc(e, "lastfm")).partition(|e| now - e["ts"].as_i64().unwrap_or(now) > 14 * 86400); - done.extend(old.into_iter().cloned()); if !lfm.is_empty() && lfm_on() { - for chunk in lfm.chunks(50) { - let mut params = vec![]; - for (i, e) in chunk.iter().enumerate() { - params.extend(track_params(&song_of(e), Some(i))); - params.push((format!("timestamp[{i}]"), e["ts"].to_string())); - } - match lfm_raw("track.scrobble", params, true, true) { - Ok(_) => { - log(&format!("lastfm sent {}: {}", chunk.len(), titles(chunk))); - sent += chunk.len(); - done.extend(chunk.iter().map(|e| (*e).clone())); - } - Err((code, _)) if LFM_AUTH_ERRORS.contains(&code) => { - errors.push(lfm_session_expired()); - break; - } - Err((code, msg)) if code == 0 || LFM_RETRY_ERRORS.contains(&code) => { - errors.push(msg); - break; - } - Err((_, msg)) => { - // Last.fm rejected the data itself; retrying would loop forever. - errors.push(format!("{msg} (dropped {} scrobble(s))", chunk.len())); - done.extend(chunk.iter().map(|e| (*e).clone())); - } - } + let mut params = vec![]; + for (i, e) in lfm.iter().enumerate() { + params.extend(track_params(&song_of(e), Some(i))); + params.push((format!("timestamp[{i}]"), e["ts"].to_string())); } + lfm_call("track.scrobble", params, true, true)?; + sent += lfm.len(); + done.extend(lfm.iter().map(|e| (*e).clone())); } - - let lb: Vec<&Value> = pending.iter().filter(|e| svc(e, "listenbrainz")).collect(); if !lb.is_empty() && lb_on() { - 'lb: for chunk in lb.chunks(100) { - let payload: Vec = chunk.iter().map(|e| lb_payload(&song_of(e), e["ts"].as_i64())).collect(); - match lb_submit(if payload.len() > 1 { "import" } else { "single" }, payload.clone()) { - Ok(_) => { - log(&format!("listenbrainz sent {}: {}", chunk.len(), titles(chunk))); - sent += chunk.len(); - done.extend(chunk.iter().map(|e| (*e).clone())); - } - Err((400, _)) => { - // One bad listen spoils a batch: send them one by one and drop the bad ones. - for (e, p) in chunk.iter().zip(payload) { - match lb_submit("single", vec![p]) { - Ok(_) => { - sent += 1; - done.push((*e).clone()); - } - Err((400, msg)) => { - errors.push(format!("{msg} (dropped 1 listen)")); - done.push((*e).clone()); - } - Err((_, msg)) => { - errors.push(msg); - break 'lb; - } - } - } - } - Err((401, _)) => { - errors.push("ListenBrainz token is not valid. Paste a new one in Settings › Scrobbling; queued listens are kept.".into()); - break; - } - Err((_, msg)) => { - errors.push(msg); - break; - } - } - } - } - - if !lfm.is_empty() && !lfm_on() { - log(&format!("lastfm: {} scrobble(s) wait for a login", lfm.len())); - } - if !lb.is_empty() && !lb_on() { - log(&format!("listenbrainz: {} listen(s) wait, ListenBrainz is off or has no token", lb.len())); - } - for e in &errors { - log(&format!("error: {e}")); + let payload: Vec = lb.iter().map(|e| lb_payload(&song_of(e), e["ts"].as_i64())).collect(); + lb_submit(if payload.len() > 1 { "import" } else { "single" }, payload)?; + sent += lb.len(); + done.extend(lb.iter().map(|e| (*e).clone())); } let mut c = cache.lock().unwrap(); c.retain(|e| !done.contains(e)); Scrobbler::save(&c); - if sent == 0 && !errors.is_empty() { - return Err(errors.join("\n")); - } Ok(sent) } - -/// Last.fm / ListenBrainz rule: half the track or 4 minutes, and tracks under 30 s never count. -fn counts_as_listen(stream: bool, dur: f64, listened: f64) -> bool { - if stream { - listened >= 30.0 - } else { - dur >= 30.0 && listened >= (dur / 2.0).min(240.0) - } -} - -fn titles(chunk: &[&Value]) -> String { - let t: Vec = chunk.iter().take(5).map(|e| format!("{} at {}", e["song"]["title"].as_str().unwrap_or("?"), e["ts"])).collect(); - t.join(", ") + if chunk.len() > 5 { ", …" } else { "" } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn listen_rule() { - assert!(counts_as_listen(false, 300.0, 150.0)); - assert!(!counts_as_listen(false, 300.0, 149.0)); - assert!(counts_as_listen(false, 900.0, 240.0)); // 4 minutes is enough for long tracks - assert!(!counts_as_listen(false, 25.0, 25.0)); // under 30 s never counts - assert!(counts_as_listen(true, 0.0, 30.0)); - } - - #[test] - fn lb_payload_has_ids_and_info() { - let mut s = Song::new("https://www.youtube.com/watch?v=x"); - s.stream_title = "Shinedown - Stranger Inside".into(); - let p = lb_payload(&s, Some(1_700_000_000)); - assert_eq!(p["track_metadata"]["artist_name"], "Shinedown"); - assert_eq!(p["track_metadata"]["additional_info"]["music_service"], "youtube.com"); - assert_eq!(p["listened_at"], 1_700_000_000); - // Real queued song, if this PC has one. - if let Ok(t) = std::fs::read_to_string(crate::config::PATHS.data.join("scrobble_cache.json")) { - let v: Vec = serde_json::from_str(&t).unwrap_or_default(); - if let Some(e) = v.last() { - println!("{}", serde_json::to_string_pretty(&lb_payload(&song_from_json(&e["song"]), e["ts"].as_i64())).unwrap()); - println!("{:?}", track_params(&song_from_json(&e["song"]), Some(0))); - } - } - } -} diff --git a/src/tags.rs b/src/tags.rs index 0a72656..20a4ae3 100644 --- a/src/tags.rs +++ b/src/tags.rs @@ -44,7 +44,7 @@ impl Field { Field::Track => "track", Field::Disc => "disc", Field::Comment => "comment", - Field::MbTrackId => "MusicBrainz recording id", + Field::MbTrackId => "MusicBrainz track id", Field::MbAlbumId => "MusicBrainz album id", } } @@ -169,7 +169,7 @@ pub fn read_song(path: &str) -> Option { s.disc = tag.disk().unwrap_or(0) as i64; s.rg_track = gain(tag.get_string(ItemKey::ReplayGainTrackGain)); s.rg_album = gain(tag.get_string(ItemKey::ReplayGainAlbumGain)); - s.mb_trackid = tag.get_string(ItemKey::MusicBrainzRecordingId).unwrap_or("").chars().take(64).collect(); + s.mb_trackid = tag.get_string(ItemKey::MusicBrainzTrackId).unwrap_or("").chars().take(64).collect(); s.mb_albumid = tag.get_string(ItemKey::MusicBrainzReleaseId).unwrap_or("").chars().take(64).collect(); if s.year == 0 { if let Some(y) = tag.get_string(ItemKey::RecordingDate) { @@ -300,41 +300,6 @@ pub fn jpeg_bytes(img: &image::DynamicImage, quality: u8) -> Vec { } // ------------------------------------------------------------------ lyrics -/// MusicBrainz ids and ISRC for scrobbling (ListenBrainz `additional_info` names). Read fresh from the file. -pub fn scrobble_ids(path: &str) -> serde_json::Map { - use serde_json::json; - let mut out = serde_json::Map::new(); - let Some(tagged) = lofty::read_from_path(path).ok() else { return out }; - let Some(tag) = tagged.primary_tag().or_else(|| tagged.first_tag()) else { return out }; - let many = |k: ItemKey| -> Vec { - let mut v: Vec = vec![]; - for s in tag.get_strings(k) { - for p in s.split(['/', ';', ',', '\0']) { - let p = p.trim(); - if p.len() == 36 && !v.iter().any(|x| x == p) { - v.push(p.to_string()); - } - } - } - v - }; - for (key, name) in [(ItemKey::MusicBrainzRecordingId, "recording_mbid"), (ItemKey::MusicBrainzReleaseId, "release_mbid"), (ItemKey::MusicBrainzReleaseGroupId, "release_group_mbid"), (ItemKey::MusicBrainzTrackId, "track_mbid")] { - if let Some(id) = many(key).into_iter().next() { - out.insert(name.into(), json!(id)); - } - } - for (key, name) in [(ItemKey::MusicBrainzArtistId, "artist_mbids"), (ItemKey::MusicBrainzReleaseArtistId, "release_artist_mbids"), (ItemKey::MusicBrainzWorkId, "work_mbids")] { - let v = many(key); - if !v.is_empty() { - out.insert(name.into(), json!(v)); - } - } - if let Some(isrc) = tag.get_string(ItemKey::Isrc).map(str::trim).filter(|s| !s.is_empty()) { - out.insert("isrc".into(), json!(isrc)); - } - out -} - pub fn read_embedded_lyrics(path: &str) -> String { let Ok(tagged) = lofty::read_from_path(path) else { return String::new() }; for tag in tagged.tags() { @@ -388,7 +353,7 @@ fn apply(tag: &mut Tag, field: Field, val: &str) { Field::Comment => if empty { tag.remove_comment() } else { tag.set_comment(val.into()) }, Field::AlbumArtist => item(tag, ItemKey::AlbumArtist, val, empty), Field::Composer => item(tag, ItemKey::Composer, val, empty), - Field::MbTrackId => item(tag, ItemKey::MusicBrainzRecordingId, val, empty), + Field::MbTrackId => item(tag, ItemKey::MusicBrainzTrackId, val, empty), Field::MbAlbumId => item(tag, ItemKey::MusicBrainzReleaseId, val, empty), Field::Year => { if empty { diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rs index 1310b4f..8b2fc3e 100644 --- a/src/ui/dialogs.rs +++ b/src/ui/dialogs.rs @@ -108,7 +108,7 @@ pub struct RipState { } pub struct SettingsState { - pub page: usize, + page: usize, folders: Vec, folder_sel: Option, scan_start: bool, @@ -148,8 +148,6 @@ pub struct SettingsState { rip_pat: String, lfm_waiting: bool, lfm_msg: String, - lb_checking: bool, - lb_msg: String, } pub enum Dialog { @@ -231,8 +229,6 @@ impl Dialog { rip_pat: s.get_str("cd/rip_pattern"), lfm_waiting: false, lfm_msg: String::new(), - lb_checking: false, - lb_msg: String::new(), })) } @@ -454,7 +450,6 @@ pub fn on_lastfm_connected(app: &mut App, r: Result<(String, String), String>) { settings().set("lastfm/user", name.clone()); settings().set("lastfm/enabled", true); app.toast(format!("Connected to Last.fm as {name}")); - app.scrobbler.flush(); if let Some(Dialog::Settings(s)) = app.dialog.as_mut() { s.lfm_waiting = false; s.lfm_on = true; @@ -471,28 +466,6 @@ pub fn on_lastfm_connected(app: &mut App, r: Result<(String, String), String>) { } } -pub fn on_listenbrainz_connected(app: &mut App, r: Result<(String, String), String>) { - let msg = match r { - Ok((token, name)) => { - settings().set("listenbrainz/token", token.clone()); - settings().set("listenbrainz/user", name.clone()); - settings().set("listenbrainz/enabled", true); - if let Some(Dialog::Settings(s)) = app.dialog.as_mut() { - s.lb_token = token; - s.lb_on = true; - } - app.scrobbler.flush(); - format!("Connected to ListenBrainz as {name}") - } - Err(e) => format!("ListenBrainz: {e}"), - }; - if let Some(Dialog::Settings(s)) = app.dialog.as_mut() { - s.lb_checking = false; - s.lb_msg = msg.clone(); - } - app.toast(msg); -} - pub fn on_picked(app: &mut App, purpose: &str, paths: Vec) { let Some(p) = paths.first().cloned() else { return }; match (purpose, app.dialog.as_mut()) { @@ -1445,32 +1418,9 @@ fn lyrics_editor(app: &mut App, ctx: &Context, text: &mut String, to_file: &mut // ---------------------------------------------------------------------- settings const PAGES: &[(&str, &str)] = &[("library_music", "Library"), ("play_arrow", "Playback"), ("palette", "Appearance"), ("scrobble", "Scrobbling"), ("cloud_download", "Metadata"), ("album", "CD")]; -/// Height of one settings line: a button is 36 tall, so labels beside it centre on the same line. -const LINE_H: f32 = 36.0; - -/// A settings line whose items share one centre line, starting at the page's left edge. -fn line(ui: &mut Ui, add: impl FnOnce(&mut Ui)) { - ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), LINE_H), egui::Layout::left_to_right(egui::Align::Center), |ui| { - ui.set_min_height(LINE_H); - add(ui); - }); -} - -/// A settings line with text on the left and controls on the right edge (add `right` items right to left). -fn split_line(ui: &mut Ui, left: impl FnOnce(&mut Ui), right: impl FnOnce(&mut Ui)) { - line(ui, |ui| { - left(ui); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), right); - }); -} - fn row(ui: &mut Ui, col: Color32, label: &str, add: impl FnOnce(&mut Ui)) { - line(ui, |ui| { - // left-aligned in a fixed column (add_sized would centre the text and indent it) - ui.allocate_ui_with_layout(egui::vec2(170.0, LINE_H), egui::Layout::left_to_right(egui::Align::Center), |ui| { - ui.set_min_width(170.0); - ui.label(RichText::new(label).color(col)); - }); + ui.horizontal(|ui| { + ui.add_sized([170.0, 28.0], egui::Label::new(RichText::new(label).color(col))); add(ui); }); } @@ -1527,10 +1477,6 @@ fn kv(items: &[(&str, &str)]) -> Vec<(String, String)> { fn settings_page(app: &mut App, ui: &mut Ui, s: &mut SettingsState) { let mut want_pick: Option<(&'static str, Pick)> = None; let mut login = false; - let mut lfm_logout = false; - let mut lfm_discard = false; - let mut lb_connect = false; - let mut lb_disconnect = false; { let g = &mut app.g; let theme = g.theme.clone(); @@ -1658,94 +1604,35 @@ fn settings_page(app: &mut App, ui: &mut Ui, s: &mut SettingsState) { }); } 3 => { - let small = |t: String| RichText::new(t).color(theme.on_surface_variant).size(12.5); - // ---- Last.fm: everything for it sits in its own card heading(ui, g, "Last.fm"); let user = settings().get_str("lastfm/user"); let logged = !settings().get_str("lastfm/session").is_empty(); - let lfm_queued = app.scrobbler.pending_for("lastfm"); - card(g).show(ui, |ui| { - ui.set_width(ui.available_width()); - split_line(ui, |ui| { - ui.label(RichText::new(if s.lfm_waiting { "Waiting for you to approve access in the browser…".to_string() } else if !s.lfm_msg.is_empty() { s.lfm_msg.clone() } else if logged { format!("Logged in as {user}") } else { "Not logged in".to_string() }).color(theme.on_surface)); - }, |ui| { - if logged && text_button(ui, g, None, "Log out", false).clicked() { - lfm_logout = true; - } - if text_button(ui, g, Some("link"), if logged { "Log in again" } else { "Log in with Last.fm" }, true).clicked() { - login = true; - } - }); - checkbox(ui, g, &mut s.lfm_on, "Scrobble to Last.fm and send “now playing”"); - if !logged && !s.lfm_waiting { - // nothing reaches Last.fm (and nothing new is queued) until you log in - let msg = if lfm_queued > 0 { format!("Nothing is sent while logged out. {lfm_queued} scrobble(s) wait for your next login.") } else { "Nothing is sent while logged out.".to_string() }; - split_line(ui, |ui| { - ui.label(small(msg)); - }, |ui| { - if lfm_queued > 0 && text_button(ui, g, None, "Discard", false).clicked() { - lfm_discard = true; - } - }); - } else if lfm_queued > 0 { - ui.label(small(format!("{lfm_queued} scrobble(s) waiting to be sent."))); - } - checkbox(ui, g, &mut s.lfm_own, "Use my own API key instead of Mulberry's (advanced)"); - if s.lfm_own { - row(ui, theme.on_surface_variant, "API key", |ui| { - text_field(ui, g, &mut s.lfm_key, 360.0); - }); - row(ui, theme.on_surface_variant, "Shared secret", |ui| { - text_field(ui, g, &mut s.lfm_secret, 360.0); - }); - ui.label(small("Get a free key at last.fm/api/account/create. Any app name works; leave the callback empty.".into())); + ui.horizontal(|ui| { + ui.label(RichText::new(if s.lfm_waiting { "Waiting for you to approve access in the browser…".to_string() } else if !s.lfm_msg.is_empty() { s.lfm_msg.clone() } else if logged { format!("Logged in as {user}") } else { "Not logged in".to_string() }).color(theme.on_surface_variant)); + if text_button(ui, g, Some("link"), if logged { "Log in again" } else { "Log in with Last.fm" }, true).clicked() { + login = true; } }); - // ---- ListenBrainz + checkbox(ui, g, &mut s.lfm_on, "Scrobble what I play and send “now playing”"); + checkbox(ui, g, &mut s.lfm_own, "Use my own API key instead of Mulberry's (advanced)"); + if s.lfm_own { + row(ui, theme.on_surface_variant, "API key", |ui| { + text_field(ui, g, &mut s.lfm_key, 360.0); + }); + row(ui, theme.on_surface_variant, "Shared secret", |ui| { + text_field(ui, g, &mut s.lfm_secret, 360.0); + }); + ui.label(RichText::new("Get a free key at last.fm/api/account/create — any app name works, leave the callback empty.").color(theme.on_surface_variant).size(12.5)); + } heading(ui, g, "ListenBrainz"); - let lb_user = settings().get_str("listenbrainz/user"); - let lb_saved = !settings().get_str("listenbrainz/token").is_empty(); - let lb_queued = app.scrobbler.pending_for("listenbrainz"); - card(g).show(ui, |ui| { - ui.set_width(ui.available_width()); - let status = if s.lb_checking { - "Checking your token…".to_string() - } else if !s.lb_msg.is_empty() { - s.lb_msg.clone() - } else if lb_saved && !lb_user.is_empty() { - format!("Connected as {lb_user}") - } else if lb_saved { - "Token saved (not checked yet)".to_string() - } else { - "Not connected".to_string() - }; - split_line(ui, |ui| { - ui.label(RichText::new(status).color(theme.on_surface)); - }, |ui| { - if lb_saved && text_button(ui, g, None, "Disconnect", false).clicked() { - lb_disconnect = true; - } - }); - split_line(ui, |ui| { - ui.label(RichText::new("User token").color(theme.on_surface_variant)); - }, |ui| { - if text_button(ui, g, Some("link"), if lb_saved { "Check" } else { "Connect" }, true).clicked() { - lb_connect = true; - } - secret_field(ui, g, &mut s.lb_token, 300.0); - }); - split_line(ui, |ui| { - ui.label(small("Copy your user token from listenbrainz.org/settings".into())); - }, |ui| { - if text_button(ui, g, None, "Open", false).clicked() { - crate::util::open_url("https://listenbrainz.org/settings/"); - } - }); - checkbox(ui, g, &mut s.lb_on, "Send listens and “now playing” to ListenBrainz"); - if lb_queued > 0 { - ui.label(small(format!("{lb_queued} listen(s) waiting to be sent."))); - } + checkbox(ui, g, &mut s.lb_on, "Submit listens to ListenBrainz"); + row(ui, theme.on_surface_variant, "User token", |ui| { + text_field(ui, g, &mut s.lb_token, 360.0); }); + let pend = app.scrobbler.pending(); + if pend > 0 { + ui.label(RichText::new(format!("{pend} scrobble(s) waiting to be sent.")).color(theme.on_surface_variant)); + } } 4 => { heading(ui, g, "Automatic fetching"); @@ -1788,41 +1675,6 @@ fn settings_page(app: &mut App, ui: &mut Ui, s: &mut SettingsState) { if let Some((purpose, kind)) = want_pick { pick(app, purpose, kind); } - if lfm_logout { - settings().set("lastfm/session", ""); - settings().set("lastfm/user", ""); - settings().set("lastfm/enabled", false); - s.lfm_on = false; - s.lfm_msg = "Logged out".into(); - app.scrobbler.purge("lastfm"); - } - if lfm_discard { - app.scrobbler.purge("lastfm"); - crate::scrobble::log("lastfm: queue discarded by the user"); - } - if lb_disconnect { - settings().set("listenbrainz/token", ""); - settings().set("listenbrainz/user", ""); - settings().set("listenbrainz/enabled", false); - s.lb_token.clear(); - s.lb_on = false; - s.lb_msg = "Disconnected".into(); - app.scrobbler.purge("listenbrainz"); - } - if lb_connect { - let token = s.lb_token.trim().to_string(); - if token.is_empty() { - s.lb_msg = "Paste your user token first".into(); - } else { - s.lb_checking = true; - s.lb_msg.clear(); - let bus = app.bus.clone(); - std::thread::spawn(move || { - let r = crate::scrobble::lb_validate(&token).map(|name| (token, name)); - bus.send(crate::bus::Msg::ConnectListenBrainz(r)); - }); - } - } if login { settings().set("lastfm/use_own_key", s.lfm_own); settings().set("lastfm/api_key", s.lfm_key.trim().to_string()); @@ -1868,10 +1720,6 @@ fn apply_settings(app: &mut App, s: &SettingsState) { st.set("lastfm/api_key", s.lfm_key.trim().to_string()); st.set("lastfm/api_secret", s.lfm_secret.trim().to_string()); st.set("listenbrainz/enabled", s.lb_on); - if st.get_str("listenbrainz/token") != s.lb_token.trim() { - // A new token was typed without pressing Connect: forget the old user name until it is checked. - st.set("listenbrainz/user", ""); - } st.set("listenbrainz/token", s.lb_token.trim().to_string()); st.set("online/auto_lyrics", s.auto_lyr); st.set("online/auto_covers", s.auto_cov); diff --git a/src/ui/widgets.rs b/src/ui/widgets.rs index db43f51..222b5a7 100644 --- a/src/ui/widgets.rs +++ b/src/ui/widgets.rs @@ -498,23 +498,6 @@ pub fn text_field(ui: &mut Ui, g: &Gfx, text: &mut String, width: f32) -> Respon .inner } -/// Like `text_field`, but hides the text (tokens, keys). -pub fn secret_field(ui: &mut Ui, g: &Gfx, text: &mut String, width: f32) -> Response { - let t = &g.theme; - egui::Frame::NONE - .fill(t.surface_container_highest) - .corner_radius(egui::CornerRadius { nw: 6, ne: 6, sw: 0, se: 0 }) - .inner_margin(egui::Margin::symmetric(8, 2)) - .show(ui, |ui| { - ui.visuals_mut().widgets.inactive.bg_fill = Color32::TRANSPARENT; - ui.visuals_mut().widgets.hovered.bg_fill = Color32::TRANSPARENT; - ui.visuals_mut().widgets.active.bg_fill = Color32::TRANSPARENT; - ui.visuals_mut().selection.bg_fill = t.primary; - ui.add(egui::TextEdit::singleline(text).password(true).frame(egui::Frame::NONE).desired_width(width - 16.0).margin(egui::Margin::symmetric(0, 6))) - }) - .inner -} - pub fn card(g: &Gfx) -> egui::Frame { egui::Frame::NONE.fill(g.theme.surface_container_low).corner_radius(cr(16.0)).inner_margin(egui::Margin::same(12)) } diff --git a/tests/shots.rs b/tests/shots.rs index f88320d..152e131 100644 --- a/tests/shots.rs +++ b/tests/shots.rs @@ -137,34 +137,3 @@ fn dialogs_tour() { h.state_mut().dialog = Some(mulberry::ui::dialogs::Dialog::lyrics_editor("[00:01.00]hello\n[00:05.00]world".into())); shot(&mut h, &out, "d_lyrics"); } - -/// Settings › Scrobbling with Last.fm logged out (queue waiting) and ListenBrainz connected. -#[test] -fn scrobble_settings() { - let out = setup_env(); - let st = mulberry::config::settings(); - st.set("lastfm/enabled", true); - st.set("lastfm/session", ""); - st.set("listenbrainz/enabled", true); - st.set("listenbrainz/token", "test-token"); - st.set("listenbrainz/user", "tester"); - let mut h = new_harness(); - settle(&mut h, 20); - h.state_mut().do_action("settings"); - settle(&mut h, 3); - if let Some(mulberry::ui::dialogs::Dialog::Settings(s)) = h.state_mut().dialog.as_mut() { - s.page = 3; - } - shot(&mut h, &out, "scrobble_settings"); - if let Some(mulberry::ui::dialogs::Dialog::Settings(s)) = h.state_mut().dialog.as_mut() { - s.page = 1; - } - shot(&mut h, &out, "playback_settings"); - // the startup flush (10 s) writes the scrobble log; queued Last.fm scrobbles wait while logged out - std::fs::write(mulberry::config::PATHS.data.join("scrobble_cache.json"), r#"[{"svc":"lastfm","ts":1796000000,"song":{"url":"/x.mp3","title":"T","artist":"A"}}]"#).unwrap(); - let _ = std::fs::remove_file(mulberry::config::PATHS.data.join("scrobble.log")); - let _ = mulberry::scrobble::Scrobbler::new(h.state().bus.clone()); - std::thread::sleep(std::time::Duration::from_secs(12)); - let log = std::fs::read_to_string(mulberry::config::PATHS.data.join("scrobble.log")).unwrap_or_default(); - assert!(log.contains("lastfm: 1 scrobble(s) wait for a login"), "scrobble.log: {log}"); -} diff --git a/tools/package.sh b/tools/package.sh index 20f934a..8805ac9 100755 --- a/tools/package.sh +++ b/tools/package.sh @@ -3,7 +3,7 @@ set -euo pipefail root=$(cd "$(dirname "$0")/.." && pwd) APP=mulberry NAME=Mulberry DESKTOP=mulberry.desktop -URL=https://astar76.com/git/astar76/Mulberry +URL=https://archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry ver=$(sed -n 's/^version = "\(.*\)"/\1/p' "$root/Cargo.toml" | head -n 1) BINS=(mulberry) LICENSE=MIT NIX_LICENSE=mit SUMMARY='Material You music player' @@ -125,7 +125,7 @@ cat > "$d/control/control" < +Maintainer: astar76 Installed-Size: $size Depends: libc6 (>= $glibc)${DEB_DEPENDS:+, $DEB_DEPENDS} ${DEB_RECOMMENDS:+Recommends: $DEB_RECOMMENDS