PlayerStore.kt 11KB

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