forked from libre-tube/LibreTube
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathChannelFragment.kt
More file actions
269 lines (233 loc) · 9.56 KB
/
Copy pathChannelFragment.kt
File metadata and controls
269 lines (233 loc) · 9.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package com.github.libretube.ui.fragments
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.github.libretube.R
import com.github.libretube.api.RetrofitInstance
import com.github.libretube.api.obj.ChannelTab
import com.github.libretube.api.obj.StreamItem
import com.github.libretube.constants.IntentData
import com.github.libretube.databinding.FragmentChannelBinding
import com.github.libretube.enums.ShareObjectType
import com.github.libretube.extensions.TAG
import com.github.libretube.extensions.formatShort
import com.github.libretube.extensions.toID
import com.github.libretube.helpers.ImageHelper
import com.github.libretube.helpers.NavigationHelper
import com.github.libretube.obj.ShareData
import com.github.libretube.ui.adapters.VideosAdapter
import com.github.libretube.ui.base.DynamicLayoutManagerFragment
import com.github.libretube.ui.dialogs.ShareDialog
import com.github.libretube.ui.extensions.setupSubscriptionButton
import com.github.libretube.ui.sheets.AddChannelToGroupSheet
import com.github.libretube.util.deArrow
import com.google.android.material.tabs.TabLayoutMediator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import retrofit2.HttpException
import java.io.IOException
class ChannelFragment : DynamicLayoutManagerFragment() {
private var _binding: FragmentChannelBinding? = null
private val binding get() = _binding!!
private val args by navArgs<ChannelFragmentArgs>()
private var channelId: String? = null
private var channelName: String? = null
private var channelAdapter: VideosAdapter? = null
private var isLoading = true
private lateinit var channelContentAdapter: ChannelContentAdapter
private var nextPages = Array<String?>(5) { null }
private var isAppBarFullyExpanded: Boolean = true
private val tabList = mutableListOf<ChannelTab>()
private val tabNamesMap = mapOf(
VIDEOS_TAB_KEY to R.string.videos,
"shorts" to R.string.yt_shorts,
"livestreams" to R.string.livestreams,
"playlists" to R.string.playlists,
"albums" to R.string.albums
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
channelName = args.channelName
?.replace("/c/", "")
?.replace("/user/", "")
channelId = args.channelId
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentChannelBinding.inflate(inflater, container, false)
return binding.root
}
override fun setLayoutManagers(gridItems: Int) {}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Check if the AppBarLayout is fully expanded
binding.channelAppBar.addOnOffsetChangedListener { _, verticalOffset ->
isAppBarFullyExpanded = verticalOffset == 0
}
binding.pager.reduceDragSensitivity()
// Determine if the child can scroll up
binding.channelRefresh.setOnChildScrollUpCallback { _, _ ->
!isAppBarFullyExpanded
}
binding.channelRefresh.setOnRefreshListener {
fetchChannel()
}
fetchChannel()
}
// adjust sensitivity due to the issue of viewpager2 with SwipeToRefresh https://issuetracker.google.com/issues/138314213
private fun ViewPager2.reduceDragSensitivity() {
val recyclerViewField = ViewPager2::class.java.getDeclaredField("mRecyclerView")
recyclerViewField.isAccessible = true
val recyclerView = recyclerViewField.get(this) as RecyclerView
val touchSlopField = RecyclerView::class.java.getDeclaredField("mTouchSlop")
touchSlopField.isAccessible = true
val touchSlop = touchSlopField.get(recyclerView) as Int
touchSlopField.set(recyclerView, touchSlop * 3)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun fetchChannel() = lifecycleScope.launch {
isLoading = true
_binding?.channelRefresh?.isRefreshing = true
val response = try {
withContext(Dispatchers.IO) {
if (channelId != null) {
RetrofitInstance.api.getChannel(channelId!!)
} else {
RetrofitInstance.api.getChannelByName(channelName!!)
}.apply {
relatedStreams = relatedStreams.deArrow()
}
}
} catch (e: IOException) {
Log.e(TAG(), "IOException, you might not have internet connection")
return@launch
} catch (e: HttpException) {
Log.e(TAG(), "HttpException, unexpected response")
return@launch
} finally {
_binding?.channelRefresh?.isRefreshing = false
isLoading = false
}
val binding = _binding ?: return@launch
// needed if the channel gets loaded by the ID
channelId = response.id
channelName = response.name
val shareData = ShareData(currentChannel = response.name)
val channelId = channelId ?: return@launch
binding.channelSubscribe.setupSubscriptionButton(
channelId,
channelName,
binding.notificationBell
)
binding.channelShare.setOnClickListener {
val bundle = bundleOf(
IntentData.id to channelId.toID(),
IntentData.shareObjectType to ShareObjectType.CHANNEL,
IntentData.shareData to shareData
)
val newShareDialog = ShareDialog()
newShareDialog.arguments = bundle
newShareDialog.show(childFragmentManager, ShareDialog::class.java.name)
}
binding.addToGroup.setOnClickListener {
AddChannelToGroupSheet().apply {
arguments = bundleOf(IntentData.channelId to channelId)
}.show(childFragmentManager)
}
nextPages[0] = response.nextpage
isLoading = false
binding.channelRefresh.isRefreshing = false
binding.channelCoordinator.isVisible = true
binding.channelName.text = response.name
if (response.verified) {
binding.channelName
.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_verified, 0)
}
binding.channelSubs.text = resources.getString(
R.string.subscribers,
response.subscriberCount.formatShort()
)
if (response.description.orEmpty().isBlank()) {
binding.channelDescription.isGone = true
} else {
binding.channelDescription.text = response.description.orEmpty().trim()
}
ImageHelper.loadImage(response.bannerUrl, binding.channelBanner)
ImageHelper.loadImage(response.avatarUrl, binding.channelImage, true)
binding.channelImage.setOnClickListener {
NavigationHelper.openImagePreview(
requireContext(),
response.avatarUrl ?: return@setOnClickListener
)
}
binding.channelBanner.setOnClickListener {
NavigationHelper.openImagePreview(
requireContext(),
response.bannerUrl ?: return@setOnClickListener
)
}
channelContentAdapter = ChannelContentAdapter(
tabList,
response.relatedStreams,
response.nextpage,
channelId,
this@ChannelFragment
)
binding.pager.adapter = channelContentAdapter
TabLayoutMediator(binding.tabParent, binding.pager) { tab, position ->
tab.text = tabList[position].name
}.attach()
channelAdapter = VideosAdapter(
response.relatedStreams.toMutableList(),
forceMode = VideosAdapter.Companion.LayoutMode.CHANNEL_ROW
)
tabList.clear()
val tabs = listOf(ChannelTab(VIDEOS_TAB_KEY, "")) + response.tabs
for (channelTab in tabs) {
val tabName = tabNamesMap[channelTab.name]?.let { getString(it) }
?: channelTab.name.replaceFirstChar(Char::titlecase)
tabList.add(ChannelTab(tabName, channelTab.data))
}
channelContentAdapter.notifyItemRangeChanged(0, tabList.size - 1)
}
companion object {
private const val VIDEOS_TAB_KEY = "videos"
}
}
class ChannelContentAdapter(
private val list: List<ChannelTab>,
private val videos: List<StreamItem>,
private val nextPage: String?,
private val channelId: String?,
fragment: Fragment
) : FragmentStateAdapter(fragment) {
override fun getItemCount() = list.size
override fun createFragment(position: Int) = ChannelContentFragment().apply {
arguments = bundleOf(
IntentData.tabData to Json.encodeToString(list[position]),
IntentData.videoList to Json.encodeToString(videos),
IntentData.channelId to channelId,
IntentData.nextPage to nextPage
)
}
}