NewsViewModel.kt 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package fr.forum_thalie.tsumugi.ui.news
  2. import android.content.Context
  3. import android.os.Build
  4. import android.util.Log
  5. import android.view.View
  6. import android.webkit.WebView
  7. import androidx.lifecycle.ViewModel
  8. import androidx.recyclerview.widget.RecyclerView
  9. import com.prof.rssparser.Parser
  10. import fr.forum_thalie.tsumugi.Async
  11. import fr.forum_thalie.tsumugi.R
  12. import fr.forum_thalie.tsumugi.tag
  13. import kotlinx.coroutines.CoroutineScope
  14. import kotlinx.coroutines.Dispatchers
  15. import kotlinx.coroutines.Job
  16. import kotlinx.coroutines.launch
  17. import org.json.JSONArray
  18. import org.json.JSONObject
  19. import java.net.URL
  20. import java.text.SimpleDateFormat
  21. import java.util.*
  22. import kotlin.collections.ArrayList
  23. import kotlin.math.min
  24. class NewsViewModel : ViewModel() {
  25. lateinit var root: View
  26. var webView: WebView? = null
  27. var webViewNews: WebViewNews? = null
  28. val newsArray : ArrayList<News> = ArrayList()
  29. var isWebViewLoaded = false
  30. private val viewModelJob = Job()
  31. private val coroutineScope = CoroutineScope(Dispatchers.Main + viewModelJob)
  32. fun fetch(root: androidx.swiperefreshlayout.widget.SwipeRefreshLayout? = null, viewAdapter: RecyclerView.Adapter<*>? = null, c: Context)
  33. {
  34. val urlToScrape = c.getString(R.string.rss_url)
  35. if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT)
  36. return // the RSS Parser does not support API20- because of no TLS v1.2
  37. val maxNumberOfArticles = 5
  38. coroutineScope.launch(Dispatchers.Main) {
  39. Log.d(tag, "launching coroutine")
  40. val parser = Parser()
  41. val articleList = parser.getArticles(urlToScrape)
  42. newsArray.clear()
  43. for (i in 0 until min(articleList.size, maxNumberOfArticles))
  44. {
  45. val item = articleList[i]
  46. Log.d(tag, "i = $i / ${articleList.size}")
  47. val news = News()
  48. news.title = item.title ?: ""
  49. news.link = item.link ?: urlToScrape
  50. news.author = item.author ?: ""
  51. news.text = item.content ?: ""
  52. news.header = item.description ?: ""
  53. val formatter6 = SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH)
  54. val dateString = item.pubDate.toString()
  55. Log.d(tag, "$news --- ${dateString}")
  56. news.date = formatter6.parse(dateString) ?: Date(0)
  57. newsArray.add(news)
  58. }
  59. // The list contains all article's data. For example you can use it for your adapter.
  60. root?.isRefreshing = false
  61. viewAdapter?.notifyDataSetChanged()
  62. }
  63. }
  64. }