NewsViewModel.kt 2.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package fr.riff_app.riff.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.riff_app.riff.R
  11. import fr.riff_app.riff.newsDateTimePattern
  12. import fr.riff_app.riff.tag
  13. import kotlinx.coroutines.CoroutineScope
  14. import kotlinx.coroutines.Dispatchers
  15. import kotlinx.coroutines.Job
  16. import kotlinx.coroutines.launch
  17. import java.text.SimpleDateFormat
  18. import java.util.*
  19. import kotlin.collections.ArrayList
  20. import kotlin.math.min
  21. class NewsViewModel : ViewModel() {
  22. var screenRatio: Int = 100
  23. lateinit var root: View
  24. var webView: WebView? = null
  25. var webViewNews: WebViewNews? = null
  26. var isPreLoadingNews = false
  27. val newsArray : ArrayList<News> = ArrayList()
  28. var isWebViewLoaded = false
  29. private val viewModelJob = Job()
  30. private val coroutineScope = CoroutineScope(Dispatchers.Main + viewModelJob)
  31. fun fetch(root: androidx.swiperefreshlayout.widget.SwipeRefreshLayout? = null, viewAdapter: RecyclerView.Adapter<*>? = null, c: Context, isPreloading: Boolean = false)
  32. {
  33. val urlToScrape = c.getString(R.string.rss_url)
  34. if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT)
  35. return // the RSS Parser does not support API20- because of no TLS v1.2
  36. val maxNumberOfArticles = 5
  37. coroutineScope.launch(Dispatchers.Main) {
  38. //[REMOVE LOG CALLS]Log.d(tag, "launching coroutine")
  39. val parser = Parser()
  40. try {
  41. val articleList = parser.getArticles(urlToScrape)
  42. newsArray.clear()
  43. for (i in 0 until min(articleList.size, maxNumberOfArticles)) {
  44. val item = articleList[i]
  45. //[REMOVE LOG CALLS]Log.d(tag, "i = $i / ${articleList.size}")
  46. val news = News()
  47. news.title = item.title ?: ""
  48. news.link = item.link ?: urlToScrape
  49. news.author = item.author ?: ""
  50. news.text = item.content ?: ""
  51. news.header = item.description ?: ""
  52. val formatter6 = SimpleDateFormat(newsDateTimePattern, Locale.ENGLISH)
  53. val dateString = item.pubDate.toString()
  54. //[REMOVE LOG CALLS]Log.d(tag, "$news --- $dateString")
  55. news.date = formatter6.parse(dateString) ?: Date(0)
  56. newsArray.add(news)
  57. }
  58. // The list contains all article's data. For example you can use it for your adapter.
  59. root?.isRefreshing = false
  60. isPreLoadingNews = isPreloading
  61. viewAdapter?.notifyDataSetChanged()
  62. }catch (e: Exception)
  63. {
  64. e.printStackTrace()
  65. }
  66. }
  67. }
  68. }