Skip to content

Commit

Permalink
Fixed #91
Browse files Browse the repository at this point in the history
  • Loading branch information
maxrave-dev committed Oct 28, 2023
1 parent 5729e04 commit f823b14
Show file tree
Hide file tree
Showing 16 changed files with 344 additions and 31 deletions.
2 changes: 2 additions & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,8 @@ dependencies {
val latestAboutLibsRelease = "10.9.1"
implementation ("com.mikepenz:aboutlibraries:${latestAboutLibsRelease}")

implementation("com.google.android.flexbox:flexbox:3.0.0")

}
hilt {
enableAggregatingTask = true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ class TrackChartAdapter( var trackList: ArrayList<ItemVideo>, val context: Conte
artistName = removeTrailingComma(artistName)
artistName = removeComma(artistName)
binding.tvArtistName.text = artistName
binding.ivArt.load(track.thumbnails.last().url)
binding.ivArt.load(track.thumbnails.lastOrNull()?.url)
}
}
private fun removeTrailingComma(sentence: String): String {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import com.maxrave.simpmusic.data.parser.search.parseSearchPlaylist
import com.maxrave.simpmusic.data.parser.search.parseSearchSong
import com.maxrave.simpmusic.data.parser.search.parseSearchVideo
import com.maxrave.simpmusic.extension.bestMatchingIndex
import com.maxrave.simpmusic.extension.removeDuplicateWords
import com.maxrave.simpmusic.extension.toListTrack
import com.maxrave.simpmusic.extension.toLyrics
import com.maxrave.simpmusic.extension.toTrack
Expand Down Expand Up @@ -1116,9 +1117,9 @@ class MainRepository @Inject constructor(private val localDataSource: LocalDataS
description = response.videoDetails?.description,
youtubeCaptionsUrl = response.captions?.playerCaptionsTracklistRenderer?.captionTracks?.get(0)?.baseUrl?.replace("&fmt=srv3", ""),
lengthSeconds = response.videoDetails?.lengthSeconds?.toInt(),
playbackTrackingVideostatsPlaybackUrl = response.playbackTracking?.videostatsPlaybackUrl?.baseUrl,
playbackTrackingAtrUrl = response.playbackTracking?.atrUrl?.baseUrl,
playbackTrackingVideostatsWatchtimeUrl = response.playbackTracking?.videostatsWatchtimeUrl?.baseUrl,
playbackTrackingVideostatsPlaybackUrl = response.playbackTracking?.videostatsPlaybackUrl?.baseUrl?.replace("https://s.youtube.com", "https://music.youtube.com"),
playbackTrackingAtrUrl = response.playbackTracking?.atrUrl?.baseUrl?.replace("https://s.youtube.com", "https://music.youtube.com"),
playbackTrackingVideostatsWatchtimeUrl = response.playbackTracking?.videostatsWatchtimeUrl?.baseUrl?.replace("https://s.youtube.com", "https://music.youtube.com"),
)
)
}
Expand Down
8 changes: 8 additions & 0 deletions app/src/main/java/com/maxrave/simpmusic/extension/AllExt.kt
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,14 @@ fun Track.toSongEntity(): SongEntity {
)
}

fun String?.removeDuplicateWords(): String {
if (this == null) return "null"
else {
val regex = Regex("\\b(\\w+)\\b\\s*(?=.*\\b\\1\\b)")
return this.replace(regex, "")
}
}

fun SongEntity.toTrack(): Track {
val listArtist = mutableListOf<Artist>()
if (this.artistName != null ) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package com.maxrave.simpmusic.ui.fragment.home

import android.app.usage.StorageStatsManager
import android.content.Intent
import android.media.audiofx.AudioEffect
import android.net.Uri
import android.os.Bundle
import android.os.storage.StorageManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
Expand All @@ -12,14 +14,17 @@ import android.widget.EditText
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.ContextCompat.getSystemService
import androidx.core.os.LocaleListCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.media3.common.util.UnstableApi
import androidx.navigation.fragment.findNavController
import coil.annotation.ExperimentalCoilApi
import coil.imageLoader
import com.google.android.flexbox.FlexboxLayout
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.maxrave.simpmusic.R
import com.maxrave.simpmusic.common.LIMIT_CACHE_SIZE
Expand All @@ -37,13 +42,16 @@ import com.maxrave.simpmusic.viewModel.SharedViewModel
import com.mikepenz.aboutlibraries.LibsBuilder
import dagger.hilt.android.AndroidEntryPoint
import dev.chrisbanes.insetter.applyInsetter
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale


@UnstableApi
@AndroidEntryPoint
class SettingsFragment : Fragment() {
Expand Down Expand Up @@ -173,9 +181,11 @@ class SettingsFragment : Fragment() {
binding.tvQuality.text = it
}
viewModel.cacheSize.observe(viewLifecycleOwner) {
drawDataStat()
binding.tvPlayerCache.text = getString(R.string.cache_size, bytesToMB(it).toString())
}
viewModel.downloadedCacheSize.observe(viewLifecycleOwner) {
drawDataStat()
binding.tvDownloadedCache.text = getString(R.string.cache_size, bytesToMB(it).toString())
}
binding.tvThumbnailCache.text = getString(R.string.cache_size, if (diskCache?.size != null) {
Expand Down Expand Up @@ -335,6 +345,7 @@ class SettingsFragment : Fragment() {
.setPositiveButton(getString(R.string.clear)) { dialog, _ ->
viewModel.clearPlayerCache()
viewModel.cacheSize.observe(viewLifecycleOwner) {
drawDataStat()
binding.tvPlayerCache.text = getString(R.string.cache_size, bytesToMB(it).toString())
}
dialog.dismiss()
Expand Down Expand Up @@ -497,6 +508,7 @@ class SettingsFragment : Fragment() {
viewModel.clearDownloadedCache()
viewModel.downloadedCacheSize.observe(viewLifecycleOwner) {
binding.tvPlayerCache.text = getString(R.string.cache_size, bytesToMB(it).toString())
drawDataStat()
}
dialog.dismiss()
}
Expand Down Expand Up @@ -632,6 +644,50 @@ class SettingsFragment : Fragment() {
LibsBuilder()
.start(requireContext())
}


}
private fun browseFiles(dir: File): Long {
var dirSize: Long = 0
if (!dir.listFiles().isNullOrEmpty()) {
for (f in dir.listFiles()!!) {
dirSize += f.length()
Log.d("STORAGE_TAG", dir.absolutePath + "/" + f.name + " uses " + f.length() + " bytes")
if (f.isDirectory) {
dirSize += browseFiles(f)
}
}
}
Log.d("STORAGE_TAG", dir.absolutePath + " uses " + dirSize + " bytes")
return dirSize
}
private fun drawDataStat() {
val mStorageStatsManager = getSystemService(requireContext(), StorageStatsManager::class.java)
if (mStorageStatsManager != null) {
lifecycleScope.launch {
val totalByte = mStorageStatsManager.getTotalBytes(StorageManager.UUID_DEFAULT)
Log.w("Total", bytesToMB(totalByte).toString())
val freeSpace = mStorageStatsManager.getFreeBytes(StorageManager.UUID_DEFAULT)
Log.w("Free", bytesToMB(freeSpace).toString())
val usedSpace = totalByte - freeSpace
Log.w("Used", bytesToMB(usedSpace).toString())
val simpMusicSize = browseFiles(requireContext().filesDir)
Log.w("SimpMusic", bytesToMB(simpMusicSize).toString())
val otherApp = simpMusicSize.let { usedSpace.minus(it) }
Log.w("Other", bytesToMB(otherApp).toString())
val databaseSize = simpMusicSize - viewModel.playerCache.cacheSpace - viewModel.downloadCache.cacheSpace
Log.w("Database", databaseSize.toString())
Log.w("Player", viewModel.playerCache.cacheSpace.toString())
Log.w("Download", viewModel.downloadCache.cacheSpace.toString())
if (totalByte == freeSpace + otherApp + databaseSize + viewModel.playerCache.cacheSpace + viewModel.downloadCache.cacheSpace) {
(binding.flexBox.getChildAt(0).layoutParams as FlexboxLayout.LayoutParams).flexBasisPercent = otherApp.toFloat().div(totalByte.toFloat())
(binding.flexBox.getChildAt(1).layoutParams as FlexboxLayout.LayoutParams).flexBasisPercent = viewModel.downloadCache.cacheSpace.toFloat().div(totalByte.toFloat())
(binding.flexBox.getChildAt(2).layoutParams as FlexboxLayout.LayoutParams).flexBasisPercent = viewModel.playerCache.cacheSpace.toFloat().div(totalByte.toFloat())
(binding.flexBox.getChildAt(3).layoutParams as FlexboxLayout.LayoutParams).flexBasisPercent = databaseSize.toFloat().div(totalByte.toFloat())
(binding.flexBox.getChildAt(4).layoutParams as FlexboxLayout.LayoutParams).flexBasisPercent = freeSpace.toFloat().div(totalByte.toFloat())
}
}
}
}

private fun bytesToMB(bytes: Long): Long {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -602,6 +602,7 @@ class PlaylistFragment: Fragment() {
}
collapsingToolbarLayout.title = it?.title
tvTitle.text = it?.title
tvTitle.isSelected = true
tvPlaylistAuthor.text = it?.author?.name
if (it?.year != "") {
tvYearAndCategory.text = requireContext().getString(R.string.year_and_category, it?.year.toString(), "Playlist")
Expand Down Expand Up @@ -688,6 +689,7 @@ class PlaylistFragment: Fragment() {
}
collapsingToolbarLayout.title = it?.title
tvTitle.text = it?.title
tvTitle.isSelected = true
tvPlaylistAuthor.text = it?.author?.name
if (it?.year != "") {
tvYearAndCategory.text = requireContext().getString(R.string.year_and_category, it?.year.toString(), "Playlist")
Expand Down Expand Up @@ -748,6 +750,7 @@ class PlaylistFragment: Fragment() {
}
collapsingToolbarLayout.title = it?.title
tvTitle.text = it?.title
tvTitle.isSelected = true
tvPlaylistAuthor.text = it?.author?.name
if (it?.year != "") {
tvYearAndCategory.text = requireContext().getString(R.string.year_and_category, it?.year.toString(), "Playlist")
Expand Down Expand Up @@ -838,6 +841,7 @@ class PlaylistFragment: Fragment() {
}
collapsingToolbarLayout.title = playlistEntity.title
tvTitle.text = playlistEntity.title
tvTitle.isSelected = true
tvPlaylistAuthor.text = playlistEntity.author
tvYearAndCategory.text = requireContext().getString(R.string.year_and_category, playlistEntity.year.toString(), "Playlist")
tvTrackCountAndDuration.text = requireContext().getString(R.string.album_length, playlistEntity.trackCount.toString(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ class SettingsViewModel @Inject constructor(
private var mainRepository: MainRepository,
private var database: MusicDatabase,
private var databaseDao: DatabaseDao,
@PlayerCache private val playerCache: SimpleCache,
@DownloadCache private val downloadCache: SimpleCache,
@PlayerCache val playerCache: SimpleCache,
@DownloadCache val downloadCache: SimpleCache,
) : AndroidViewModel(application) {

@Inject
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1021,16 +1021,21 @@ class SharedViewModel @Inject constructor(private var dataStoreManager: DataStor
viewModelScope.launch {
if (dataStoreManager.lyricsProvider.first() == DataStoreManager.MUSIXMATCH) {
mainRepository.getSongById(videoId).first().let { song ->
val artist = if (song?.artistName?.firstOrNull() != null && song.artistName.firstOrNull()?.contains("Various Artists") == false) {
song.artistName.firstOrNull()
} else {
simpleMediaServiceHandler?.nowPlaying?.first()?.mediaMetadata?.artist ?: ""
}
song?.let {
if (song.downloadState == DownloadState.STATE_DOWNLOADED) {
getSavedLyrics(
song.toTrack().copy(
durationSeconds = duration
), "${song.title} ${song.artistName?.firstOrNull()}"
), "${song.title} $artist"
)
} else {
mainRepository.getLyricsData(
"${song.title} ${song.artistName?.firstOrNull()}",
"${song.title} $artist",
duration
).collect { response ->
_lyrics.value = response.second
Expand All @@ -1055,7 +1060,7 @@ class SharedViewModel @Inject constructor(private var dataStoreManager: DataStor
getSavedLyrics(
song.toTrack().copy(
durationSeconds = duration
), "${song.title} ${song.artistName?.firstOrNull()}"
), "${song.title} $artist"
)
}
}
Expand Down Expand Up @@ -1084,7 +1089,7 @@ class SharedViewModel @Inject constructor(private var dataStoreManager: DataStor
getSavedLyrics(
song.toTrack().copy(
durationSeconds = duration
), "${song.title} ${song.artistName?.firstOrNull()}"
), "${song.title} ${song.artistName?.firstOrNull() ?: simpleMediaServiceHandler?.nowPlaying?.first()?.mediaMetadata?.artist ?: ""}"
)
}
}
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/res/layout/fragment_artist.xml
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@
</com.google.android.material.card.MaterialCardView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="150sp">
android:layout_height="180sp">

</RelativeLayout>
</LinearLayout>
Expand Down
6 changes: 6 additions & 0 deletions app/src/main/res/layout/fragment_playlist.xml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,12 @@
android:id="@+id/tvTitle"
style="@style/album_name"
android:text="Playlist"
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:focusable="true"
android:focusableInTouchMode="true"
android:scrollHorizontally="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

Expand Down
Loading

0 comments on commit f823b14

Please sign in to comment.