PlayerStore.kt 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. package fr.forum_thalie.tsumugi.playerstore
  2. import android.content.Context
  3. import android.graphics.Bitmap
  4. import android.graphics.BitmapFactory
  5. import android.support.v4.media.session.PlaybackStateCompat
  6. import android.util.Log
  7. import androidx.lifecycle.MutableLiveData
  8. import fr.forum_thalie.tsumugi.*
  9. import org.json.JSONObject
  10. import java.net.URL
  11. import java.text.ParseException
  12. import java.text.SimpleDateFormat
  13. import java.util.*
  14. import kotlin.collections.ArrayList
  15. class PlayerStore {
  16. private lateinit var urlToScrape: String
  17. val isPlaying: MutableLiveData<Boolean> = MutableLiveData()
  18. val isServiceStarted: MutableLiveData<Boolean> = MutableLiveData()
  19. val volume: MutableLiveData<Int> = MutableLiveData()
  20. val playbackState: MutableLiveData<Int> = MutableLiveData()
  21. val currentTime: MutableLiveData<Long> = MutableLiveData()
  22. val streamerPicture: MutableLiveData<Bitmap> = MutableLiveData()
  23. val streamerName: MutableLiveData<String> = MutableLiveData()
  24. val currentSong : Song = Song()
  25. val currentSongBackup: Song = Song()
  26. val lp : ArrayList<Song> = ArrayList()
  27. val queue : ArrayList<Song> = ArrayList()
  28. val isQueueUpdated: MutableLiveData<Boolean> = MutableLiveData()
  29. val isLpUpdated: MutableLiveData<Boolean> = MutableLiveData()
  30. val isMuted : MutableLiveData<Boolean> = MutableLiveData()
  31. val listenersCount: MutableLiveData<Int> = MutableLiveData()
  32. var latencyCompensator : Long = 0
  33. var isInitialized: Boolean = false
  34. var isStreamDown: Boolean = false
  35. init {
  36. playbackState.value = PlaybackStateCompat.STATE_STOPPED
  37. isPlaying.value = false
  38. isServiceStarted.value = false
  39. streamerName.value = ""
  40. volume.value = preferenceStore.getInt("volume", 100)
  41. currentTime.value = System.currentTimeMillis()
  42. isQueueUpdated.value = false
  43. isLpUpdated.value = false
  44. isMuted.value = false
  45. currentSong.title.value = noConnectionValue
  46. currentSongBackup.title.value = noConnectionValue
  47. listenersCount.value = 0
  48. }
  49. fun initUrl(c: Context)
  50. {
  51. urlToScrape = c.getString(R.string.API_URL)
  52. }
  53. private fun getTimestamp(s: String) : Long
  54. {
  55. val dateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault())
  56. try {
  57. val t: Date? = dateFormat.parse(s)
  58. return t!!.time
  59. } catch (e: ParseException) {
  60. e.printStackTrace()
  61. }
  62. return 0
  63. }
  64. // ##################################################
  65. // ################# API FUNCTIONS ##################
  66. // ##################################################
  67. private fun updateApi(res: JSONObject, isCompensatingLatency : Boolean = false) {
  68. // If we're not in PLAYING state, update title / artist metadata. If we're playing, the ICY will take care of that.
  69. val resMain = res.getJSONObject("tracks").getJSONObject("current")
  70. val s = extractSong(resMain)
  71. if (playbackState.value != PlaybackStateCompat.STATE_PLAYING || currentSong.title.value.isNullOrEmpty()
  72. || currentSong.title.value == noConnectionValue)
  73. currentSong.setTitleArtist("${s.artist.value} - ${s.title.value}")
  74. val starts = s.startTime.value
  75. val ends = s.stopTime.value
  76. if (currentSong.startTime.value != starts)
  77. currentSong.startTime.value = starts
  78. currentSong.stopTime.value = ends
  79. // I noticed that the server has a big (3 to 9 seconds !!) offset for current time.
  80. // we can measure it when the player is playing, to compensate it and have our progress bar perfectly timed
  81. // latencyCompensator is set to null when beginPlaying() (we can't measure it at the moment we start playing, since we're in the middle of a song),
  82. // at this moment, we set it to 0. Then, next time the updateApi is called when we're playing, we measure the latency and we set out latencyComparator.
  83. if(isCompensatingLatency)
  84. {
  85. latencyCompensator = getTimestamp(res.getJSONObject("station").getString("schedulerTime")) - (currentSong.startTime.value ?: getTimestamp(res.getJSONObject("station").getString("schedulerTime")))
  86. Log.d(tag, "latency compensator set to ${(latencyCompensator).toFloat()/1000} s")
  87. }
  88. currentTime.value = getTimestamp(res.getJSONObject("station").getString("schedulerTime")) - (latencyCompensator)
  89. /*
  90. val listeners = resMain.getInt("listeners")
  91. listenersCount.value = listeners
  92. Log.d(tag, playerStoreTag + "store updated")
  93. */
  94. }
  95. private val scrape : (Any?) -> String =
  96. {
  97. URL(urlToScrape).readText()
  98. }
  99. /* initApi is called :
  100. - at startup
  101. - when a streamer changes.
  102. the idea is to fetch the queue when a streamer changes (potentially Hanyuu), and at startup.
  103. The Last Played is only fetched if it's empty (so, only at startup), not when a streamer changes.
  104. */
  105. fun initApi()
  106. {
  107. val post : (parameter: Any?) -> Unit = {
  108. val result = JSONObject(it as String)
  109. if (result.has("tracks"))
  110. {
  111. updateApi(result)
  112. currentSongBackup.copy(currentSong)
  113. isQueueUpdated.value = true
  114. isLpUpdated.value = true
  115. }
  116. isInitialized = true
  117. }
  118. Async(scrape, post)
  119. }
  120. fun fetchApi(isCompensatingLatency: Boolean = false) {
  121. val post: (parameter: Any?) -> Unit = {
  122. val result = JSONObject(it as String)
  123. if (!result.isNull("tracks"))
  124. {
  125. updateApi(result, isCompensatingLatency)
  126. }
  127. }
  128. Async(scrape, post)
  129. }
  130. private fun extractSong(songJSON: JSONObject) : Song {
  131. val song = Song()
  132. song.setTitleArtist(songJSON.getString("name"))
  133. song.startTime.value = getTimestamp(songJSON.getString("starts"))
  134. song.stopTime.value = getTimestamp(songJSON.getString("ends"))
  135. song.type.value = 0 // only used for R/a/dio
  136. return song
  137. }
  138. // ##################################################
  139. // ############## QUEUE / LP FUNCTIONS ##############
  140. // ##################################################
  141. fun updateQueue() {
  142. if (queue.isNotEmpty()) {
  143. queue.remove(queue.first())
  144. Log.d(tag, queue.toString())
  145. fetchLastRequest()
  146. isQueueUpdated.value = true
  147. } else if (isInitialized) {
  148. fetchLastRequest()
  149. } else {
  150. Log.d(tag, "queue is empty! fetching anyway !!")
  151. fetchLastRequest()
  152. }
  153. }
  154. fun updateLp() {
  155. // note : lp is empty at initialization. This check was needed when we used the R/a/dio API.
  156. //if (lp.isNotEmpty()){
  157. val n = Song()
  158. n.copy(currentSongBackup)
  159. if (n.title.value != noConnectionValue && n.title.value != streamDownValue)
  160. lp.add(0, n)
  161. currentSongBackup.copy(currentSong)
  162. isLpUpdated.value = true
  163. //[REMOVE LOG CALLS]//[REMOVE LOG CALLS]Log.d(tag, playerStoreTag + lp.toString())
  164. //}
  165. }
  166. private fun fetchLastRequest()
  167. {
  168. val sleepScrape: (Any?) -> String = {
  169. /* we can maximize our chances to retrieve the last queued song by specifically waiting for the number of seconds we measure between ICY metadata and API change.
  170. we add 2 seconds just to get a higher probability that the API has correctly updated. (the latency compensator can have a jitter of 1 second usually)
  171. If, against all odds, the API hasn't updated yet, we will retry in the same amount of seconds. So we'll have the data anyway.
  172. This way to fetch at the most probable time is a good compromise between fetch speed and fetch frequency
  173. We don't fetch too often, and we start to fetch at the most *probable* time.
  174. If there's no latencyCompensator measured yet, we only wait for 3 seconds.
  175. If the song is the same, it will be called again. 3 seconds is a good compromise between speed and frequency:
  176. it might be called twice, rarely 3 times, and it's only the 2 first songs ; after these, the latencyCompensator is set to fetch at the most probable time.
  177. */
  178. val sleepTime: Long = if (latencyCompensator > 0) latencyCompensator + 2000 else 3000
  179. Thread.sleep(sleepTime) // we wait a bit (10s) for the API to get updated on R/a/dio side!
  180. URL(urlToScrape).readText()
  181. }
  182. lateinit var post: (parameter: Any?) -> Unit
  183. fun postFun(result: JSONObject)
  184. {
  185. if (result.has("tracks")) {
  186. val resMain = result.getJSONObject("tracks")
  187. /*
  188. if ((resMain.has("isafkstream") && !resMain.getBoolean("isafkstream")) &&
  189. queue.isNotEmpty())
  190. {
  191. queue.clear() //we're not requesting anything anymore.
  192. isQueueUpdated.value = true
  193. } else if (resMain.has("isafkstream") && resMain.getBoolean("isafkstream") &&
  194. queue.isEmpty())
  195. {
  196. initApi()
  197. } else
  198. */
  199. if (resMain.has("next") /*&& queue.isNotEmpty()*/) {
  200. val queueJSON =
  201. resMain.getJSONObject("next")
  202. val t = extractSong(queueJSON)
  203. if (queue.isNotEmpty() && t == queue.last())
  204. {
  205. Log.d(tag, playerStoreTag + "Song already in there: $t")
  206. Async(sleepScrape, post)
  207. } else {
  208. queue.add(queue.size, t)
  209. Log.d(tag, playerStoreTag + "added last queue song: $t")
  210. isQueueUpdated.value = true
  211. }
  212. }
  213. }
  214. }
  215. post = {
  216. val result = JSONObject(it as String)
  217. /* The goal is to pass the result to a function that will process it (postFun).
  218. The magic trick is, under circumstances, the last queue song might not have been updated yet when we fetch it.
  219. So if this is detected ==> if (t == queue.last() )
  220. Then the function re-schedule an Async(sleepScrape, post).
  221. To do that, the "post" must be defined BEFORE the function, but the function must be defined BEFORE the "post" value.
  222. So I declare "post" as lateinit var, define the function, then define the "post" that calls the function. IT SHOULD WORK.
  223. */
  224. postFun(result)
  225. }
  226. Async(sleepScrape, post)
  227. }
  228. // ##################################################
  229. // ############## PICTURE FUNCTIONS #################
  230. // ##################################################
  231. fun initPicture(c: Context) {
  232. streamerPicture.value = BitmapFactory.decodeResource(c.resources,
  233. R.drawable.logo_roundsquare
  234. )
  235. }
  236. private val playerStoreTag = "====PlayerStore===="
  237. companion object {
  238. val instance by lazy {
  239. PlayerStore()
  240. }
  241. }
  242. }