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. //[REMOVE LOG CALLS]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. //[REMOVE LOG CALLS]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. fetchLastRequest()
  114. isQueueUpdated.value = true
  115. isLpUpdated.value = true
  116. }
  117. isInitialized = true
  118. }
  119. Async(scrape, post)
  120. }
  121. fun fetchApi(isCompensatingLatency: Boolean = false) {
  122. val post: (parameter: Any?) -> Unit = {
  123. val result = JSONObject(it as String)
  124. if (!result.isNull("tracks"))
  125. {
  126. updateApi(result, isCompensatingLatency)
  127. }
  128. }
  129. Async(scrape, post)
  130. }
  131. private fun extractSong(songJSON: JSONObject) : Song {
  132. val song = Song()
  133. song.setTitleArtist(songJSON.getString("name"))
  134. song.startTime.value = getTimestamp(songJSON.getString("starts"))
  135. song.stopTime.value = getTimestamp(songJSON.getString("ends"))
  136. song.type.value = 0 // only used for R/a/dio
  137. return song
  138. }
  139. // ##################################################
  140. // ############## QUEUE / LP FUNCTIONS ##############
  141. // ##################################################
  142. fun updateQueue() {
  143. if (queue.isNotEmpty()) {
  144. queue.remove(queue.first())
  145. //[REMOVE LOG CALLS]Log.d((tag, queue.toString())
  146. fetchLastRequest()
  147. isQueueUpdated.value = true
  148. } else if (isInitialized) {
  149. fetchLastRequest()
  150. } else {
  151. //[REMOVE LOG CALLS]Log.d((tag, "queue is empty! fetching anyway !!")
  152. fetchLastRequest()
  153. }
  154. }
  155. fun updateLp() {
  156. // note : lp is empty at initialization. This check was needed when we used the R/a/dio API.
  157. //if (lp.isNotEmpty()){
  158. val n = Song()
  159. n.copy(currentSongBackup)
  160. if (n.title.value != noConnectionValue && n.title.value != streamDownValue)
  161. lp.add(0, n)
  162. currentSongBackup.copy(currentSong)
  163. isLpUpdated.value = true
  164. //[REMOVE LOG CALLS]Log.d(tag, playerStoreTag + lp.toString())
  165. //}
  166. }
  167. private fun fetchLastRequest()
  168. {
  169. val sleepScrape: (Any?) -> String = {
  170. /* 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.
  171. 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)
  172. 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.
  173. This way to fetch at the most probable time is a good compromise between fetch speed and fetch frequency
  174. We don't fetch too often, and we start to fetch at the most *probable* time.
  175. If there's no latencyCompensator measured yet, we only wait for 3 seconds.
  176. If the song is the same, it will be called again. 3 seconds is a good compromise between speed and frequency:
  177. 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.
  178. */
  179. val sleepTime: Long = if (latencyCompensator > 0) latencyCompensator + 2000 else 3000
  180. Thread.sleep(sleepTime) // we wait a bit (10s) for the API to get updated on R/a/dio side!
  181. URL(urlToScrape).readText()
  182. }
  183. lateinit var post: (parameter: Any?) -> Unit
  184. fun postFun(result: JSONObject)
  185. {
  186. if (result.has("tracks")) {
  187. val resMain = result.getJSONObject("tracks")
  188. /*
  189. if ((resMain.has("isafkstream") && !resMain.getBoolean("isafkstream")) &&
  190. queue.isNotEmpty())
  191. {
  192. queue.clear() //we're not requesting anything anymore.
  193. isQueueUpdated.value = true
  194. } else if (resMain.has("isafkstream") && resMain.getBoolean("isafkstream") &&
  195. queue.isEmpty())
  196. {
  197. initApi()
  198. } else
  199. */
  200. if (resMain.has("next") /*&& queue.isNotEmpty()*/) {
  201. val queueJSON =
  202. resMain.getJSONObject("next")
  203. val t = extractSong(queueJSON)
  204. if (queue.isNotEmpty() && (t == queue.last() || t == currentSong))
  205. {
  206. //[REMOVE LOG CALLS]Log.d((tag, playerStoreTag + "Song already in there: $t")
  207. Async(sleepScrape, post)
  208. } else {
  209. queue.add(queue.size, t)
  210. //[REMOVE LOG CALLS]Log.d(tag, playerStoreTag + "added last queue song: $t")
  211. isQueueUpdated.value = true
  212. }
  213. }
  214. }
  215. }
  216. post = {
  217. val result = JSONObject(it as String)
  218. /* The goal is to pass the result to a function that will process it (postFun).
  219. The magic trick is, under circumstances, the last queue song might not have been updated yet when we fetch it.
  220. So if this is detected ==> if (t == queue.last() )
  221. Then the function re-schedule an Async(sleepScrape, post).
  222. To do that, the "post" must be defined BEFORE the function, but the function must be defined BEFORE the "post" value.
  223. So I declare "post" as lateinit var, define the function, then define the "post" that calls the function. IT SHOULD WORK.
  224. */
  225. postFun(result)
  226. }
  227. Async(sleepScrape, post)
  228. }
  229. // ##################################################
  230. // ############## PICTURE FUNCTIONS #################
  231. // ##################################################
  232. fun initPicture(c: Context) {
  233. streamerPicture.value = BitmapFactory.decodeResource(c.resources,
  234. R.drawable.logo_roundsquare
  235. )
  236. }
  237. private val playerStoreTag = "====PlayerStore===="
  238. companion object {
  239. val instance by lazy {
  240. PlayerStore()
  241. }
  242. }
  243. }