Planning.kt 2.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package fr.forum_thalie.tsumugi.planning
  2. import android.content.Context
  3. import androidx.lifecycle.MutableLiveData
  4. import fr.forum_thalie.tsumugi.Async
  5. import org.json.JSONObject
  6. import java.io.IOException
  7. import java.net.URL
  8. class Planning {
  9. private val programmes: ArrayList<Programme> = ArrayList()
  10. private var regularProgramme: String? = null
  11. val currentProgramme: MutableLiveData<String> = MutableLiveData()
  12. private fun findCurrentProgramme(): String
  13. {
  14. programmes.forEach {
  15. if (it.isCurrent())
  16. return it.title
  17. }
  18. return regularProgramme ?: "none"
  19. }
  20. fun checkProgramme()
  21. {
  22. val newProgramme = findCurrentProgramme()
  23. if (currentProgramme.value != newProgramme)
  24. currentProgramme.value = newProgramme
  25. }
  26. fun parseUrl(url: String? = null, context: Context? = null)
  27. {
  28. val scrape : (Any?) -> String = {
  29. if (url.isNullOrEmpty() && context != null)
  30. {
  31. val json: String
  32. try {
  33. val inputStream = context.assets.open("planning_example.json")
  34. val size = inputStream.available()
  35. val buffer = ByteArray(size)
  36. inputStream.use { it.read(buffer) }
  37. json = String(buffer)
  38. json
  39. } catch (ioException: IOException) {
  40. ioException.printStackTrace()
  41. ""
  42. }
  43. }
  44. else
  45. URL(url).readText()
  46. }
  47. val post : (parameter: Any?) -> Unit = {
  48. val result = JSONObject(it as String)
  49. if (result.has("planning"))
  50. {
  51. val programList = result.getJSONArray("planning")
  52. for (i in 0 until programList.length())
  53. {
  54. val item = programList[i] as JSONObject
  55. val periodicity = item.getInt("periodicity")
  56. val hourBeginS = item.getString("hour_begin").split(":")
  57. val hourBegin = hourBeginS.first().toInt()*60 + hourBeginS.last().toInt()
  58. val hourEndS = item.getString("hour_end").split(":")
  59. val hourEnd = hourEndS.first().toInt()* 60 + hourEndS.last().toInt()
  60. val title = item.getString("title")
  61. programmes.add(Programme(title, periodicity, hourBegin, hourEnd))
  62. }
  63. }
  64. if (result.has("regular_programme"))
  65. regularProgramme = result.getString("regular_programme")
  66. }
  67. Async(scrape, post)
  68. }
  69. companion object {
  70. val instance by lazy {
  71. Planning()
  72. }
  73. }
  74. }