/
Utils.kt
1555 lines (1400 loc) · 44.3 KB
/
Utils.kt
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.jerboa
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.ClipData
import android.content.ClipboardManager
import android.content.ContentValues
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.media.MediaScannerConnection
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.util.TypedValue
import android.webkit.MimeTypeMap.getFileExtensionFromUrl
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContract
import androidx.annotation.RequiresApi
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatDelegate
import androidx.browser.customtabs.CustomTabsIntent
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.material3.DrawerState
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Stable
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.core.os.LocaleListCompat
import androidx.core.util.PatternsCompat
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.navigation.NavController
import coil.annotation.ExperimentalCoilApi
import coil.imageLoader
import com.jerboa.api.API
import com.jerboa.api.ApiState
import com.jerboa.datatypes.BanFromCommunityData
import com.jerboa.datatypes.getDisplayName
import com.jerboa.db.APP_SETTINGS_DEFAULT
import com.jerboa.db.entity.AppSettings
import com.jerboa.ui.components.common.Route
import com.jerboa.ui.theme.SMALL_PADDING
import it.vercruysse.lemmyapi.v0x19.datatypes.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import okhttp3.Request
import org.ocpsoft.prettytime.PrettyTime
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.net.MalformedURLException
import java.net.URL
import java.text.DecimalFormat
import java.util.*
import kotlin.math.abs
import kotlin.math.pow
// / This should be done in a UI wrapper
fun toastException(
ctx: Context,
error: Exception,
) {
Log.e("toastException", "error", error)
Toast.makeText(ctx, error.message ?: "UNKNOWN EXCEPTION", Toast.LENGTH_SHORT).show()
}
fun loginFirstToast(ctx: Context) {
Toast.makeText(ctx, ctx.getString(R.string.utils_login_first), Toast.LENGTH_SHORT).show()
}
data class MissingCommentView(
val commentId: CommentId,
val path: String,
)
sealed class CommentNodeData(
val depth: Int,
// Must use a SnapshotStateList and not a MutableList here, otherwise changes in the tree children won't trigger a UI update
val children: SnapshotStateList<CommentNodeData> = mutableStateListOf(),
var parent: CommentNodeData? = null,
) {
abstract fun getId(): Long
abstract fun getPath(): String
}
class CommentNode(
val commentView: CommentView,
depth: Int,
children: SnapshotStateList<CommentNodeData> = mutableStateListOf(),
parent: CommentNodeData? = null,
) : CommentNodeData(depth, children, parent) {
override fun getId() = commentView.comment.id
override fun getPath() = commentView.comment.path
}
class MissingCommentNode(
val missingCommentView: MissingCommentView,
depth: Int,
children: SnapshotStateList<CommentNodeData> = mutableStateListOf(),
parent: CommentNodeData? = null,
) : CommentNodeData(depth, children, parent) {
override fun getId() = missingCommentView.commentId
override fun getPath() = missingCommentView.path
}
fun commentsToFlatNodes(comments: List<CommentView>): List<CommentNode> {
return comments.map { c -> CommentNode(c, depth = 0) }
}
/**
* This function takes a list of comments and builds a tree from it
*
* In commentView it should be giving a id of the root comment
* Else it would generate a chain of missingCommentNodes to the first comment
* Because the commentView doesn't start with the actual root comment
*/
fun buildCommentsTree(
comments: List<CommentView>,
// If it's in CommentView, then we need to know the root comment id
rootCommentId: CommentId?,
): List<CommentNodeData> {
val isCommentView = rootCommentId != null
val map = LinkedHashMap<Number, CommentNodeData>()
val firstComment = comments.firstOrNull()?.comment
val depthOffset =
if (isCommentView && firstComment != null) {
getCommentIdDepthFromPath(firstComment.path, rootCommentId!!)
} else {
0
}
comments.forEach { cv ->
val depth = getDepthFromComment(cv.comment).minus(depthOffset)
val node = CommentNode(cv, depth)
map[cv.comment.id] = node
}
val tree = mutableListOf<CommentNodeData>()
comments.forEach { cv ->
val child = map[cv.comment.id]
child?.let {
recCreateAndGenMissingCommentData(map, tree, cv.comment.path, it, rootCommentId)
}
}
return tree
}
/**
* This function is given a node and adds it to the parent's children
* If the parent doesn't exist it is missing, then it creates a placeholder node
* and passes it to this function again so that it can be added to the parent's children (recursively)
* TODO: Remove this once missing comments issue is fixed by Lemmy, see https://github.com/dessalines/jerboa/pull/1240
*/
fun recCreateAndGenMissingCommentData(
map: LinkedHashMap<Number, CommentNodeData>,
tree: MutableList<CommentNodeData>,
currCommentPath: String,
currCommentNodeData: CommentNodeData,
rootCommentId: CommentId?,
) {
val parentId = getCommentParentId(currCommentPath)
// if no parent then add it to the root of the three
if (parentId != null) {
val parent = map[parentId]
// If the parent doesn't exist, then we need to add a placeholder node
if (parent == null) {
// Do not generate a parent if its the root comment (commentView starting with this comment)
if (currCommentNodeData.getId() == rootCommentId) {
tree.add(currCommentNodeData)
return
}
val parentPath = getParentPath(currCommentPath)
val missingNode =
MissingCommentNode(
MissingCommentView(parentId, parentPath),
currCommentNodeData.depth - 1,
)
map[parentId] = missingNode
missingNode.children.add(currCommentNodeData)
currCommentNodeData.parent = missingNode
// The the missing parent needs to be correctly weaved into the tree
// It needs a parent, and it needs to be added to the parent's children
// The parent may also be missing, so we need to recursively call this function
recCreateAndGenMissingCommentData(map, tree, parentPath, missingNode, rootCommentId)
} else {
currCommentNodeData.parent = parent
parent.children.add(currCommentNodeData)
}
} else {
tree.add(currCommentNodeData)
}
}
fun LazyListState.isScrolledToEnd(): Boolean {
val totalItems = layoutInfo.totalItemsCount
val lastItemVisible = layoutInfo.visibleItemsInfo.lastOrNull()?.index
return if (totalItems > 0) {
lastItemVisible == totalItems - 1
} else {
false
}
}
/**
* Parses a "url" and returns a spec-compliant URL:
*
* - https://host/path - leave as-is
* - http://host/path - leave as-is
* - /c/community -> https://currentInstance/c/community
* - /c/community@instance -> https://instance/c/community
* - !community@instance -> https://instance/c/community
* - @user@instance -> https://instance/u/user
*
* @return A pair of a boolean and a string where the
* string represents the spec-compliant URL. The boolean
* represents true if the given string as argument was
* formatted in a lemmy specific format. Such as "/c/community"
*/
fun parseUrl(
baseUrl: String,
url: String,
): Pair<Boolean, String>? {
if (url.startsWith("https://") || url.startsWith("http://")) {
return Pair(false, url)
} else if (url.startsWith("/c/")) {
if (url.count { c -> c == '@' } == 1) {
val (community, host) = url.split("@", limit = 2)
return Pair(true, "https://$host$community")
}
return Pair(true, baseUrl + url)
} else if (url.startsWith("/u/")) {
if (url.count { c -> c == '@' } == 1) {
val (userPath, host) = url.split("@", limit = 2)
return Pair(true, "https://$host$userPath")
}
return Pair(true, baseUrl + url)
} else if (url.startsWith("!")) {
if (url.count { c -> c == '@' } == 1) {
val (community, host) = url.substring(1).split("@", limit = 2)
return Pair(true, "https://$host/c/$community")
}
return Pair(true, baseUrl + "/c/${url.substring(1)}")
} else if (url.startsWith("@")) {
if (url.count { c -> c == '@' } == 2) {
val (user, host) = url.substring(1).split("@", limit = 2)
return Pair(true, "https://$host/u/$user")
}
return Pair(true, baseUrl + "/u/${url.substring(1)}")
}
return null
}
fun looksLikeCommunityUrl(url: String): Pair<String, String>? {
val pattern = Regex("^https?://([^/]+)/c/([^/&?]+)")
val match = pattern.find(url)
if (match != null) {
val (host, community) = match.destructured
return Pair(host, community)
}
return null
}
fun looksLikeUserUrl(url: String): Pair<String, String>? {
val pattern = Regex("^https?://([^/]+)/u/([^/&?]+)")
val match = pattern.find(url)
if (match != null) {
val (host, user) = match.destructured
return Pair(host, user)
}
return null
}
// Current logic is that if the url matches a community url or user url then it confirms
// if the host is an actual lemmy instance unless it was originally formatted in a user/community format
suspend fun openLink(
url: String,
navController: NavController,
useCustomTab: Boolean,
usePrivateTab: Boolean,
) {
val baseUrl = API.getInstance().baseUrl
val (formatted, parsedUrl) = parseUrl(baseUrl, url) ?: return
val userUrl = looksLikeUserUrl(parsedUrl)
val communityUrl = looksLikeCommunityUrl(parsedUrl)
if (userUrl != null && (formatted || API.checkIfLemmyInstance(url))) {
val route =
Route.ProfileFromUrlArgs.makeRoute(instance = userUrl.first, name = userUrl.second)
navController.navigate(route)
} else if (communityUrl != null && (formatted || API.checkIfLemmyInstance(url))) {
val route =
Route.CommunityFromUrlArgs.makeRoute(
instance = communityUrl.first,
name = communityUrl.second,
)
navController.navigate(route)
} else {
openLinkRaw(url, navController, useCustomTab, usePrivateTab)
}
}
fun openLinkRaw(
url: String,
navController: NavController,
useCustomTab: Boolean,
usePrivateTab: Boolean,
) {
val extras =
Intent().apply {
if (usePrivateTab) {
// In non CustomTab mode this causes it to not open the link in Chrome
if (useCustomTab) {
putExtra("com.google.android.apps.chrome.EXTRA_OPEN_NEW_INCOGNITO_TAB", true)
}
putExtra("private_browsing_mode", true)
}
}
if (useCustomTab) {
val intent = CustomTabsIntent.Builder().build()
intent.intent.putExtras(extras)
intent.launchUrl(navController.context, Uri.parse(url))
} else {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
intent.putExtras(extras)
navController.context.startActivitySafe(intent)
}
}
var prettyTime = PrettyTime(Locale.getDefault())
var prettyTimeEnglish = PrettyTime(Locale.ENGLISH)
val invalidPrettyDateRegex = "^[0123456789 ]+$".toRegex()
fun formatDuration(
date: Date,
longTimeFormat: Boolean = false,
): String {
if (prettyTime.locale != Locale.getDefault()) {
prettyTime = PrettyTime(Locale.getDefault())
}
var prettyDate = prettyTime.formatDuration(date)
// A bug in PrettyTime means that some languages (pl, ru, uk, kk) will not include any time unit
if (prettyDate.matches(invalidPrettyDateRegex)) {
prettyDate = prettyTimeEnglish.formatDuration(date)
}
return if (longTimeFormat) {
prettyDate
} else {
prettyTimeShortener(prettyDate)
}
}
fun prettyTimeShortener(timeString: String): String {
return if (prettyTime.locale.language == "en") {
if (timeString.isEmpty()) {
"Now"
} else {
timeString
.replace(Regex("minutes?"), "m")
.replace(Regex("hours?"), "h")
.replace(Regex("days?"), "d")
.replace(Regex("weeks?"), "w")
.replace(Regex("months?"), "M")
.replace(Regex("years?"), "Y")
.filter { !it.isWhitespace() }
}
} else {
timeString
}
}
fun pictrsImageThumbnail(
src: String,
thumbnailSize: Int,
): String {
// sample url:
// http://localhost:8535/pictrs/image/file.png?thumbnail=256&format=jpg
val split = src.split("/pictrs/image/")
// If theres not multiple, then its not a pictrs image
if (split.size == 1) {
return src
}
val host = split[0]
var path = split[1]
// eliminate the query param portion of the path so we can replace it later
// without this, we'd end up with something like host/path?thumbnail=...?thumbnail=...
if ("?" in path) {
path = path.replaceAfter('?', "").dropLast(1)
}
return "$host/pictrs/image/$path?thumbnail=$thumbnailSize&format=webp"
}
fun isImage(url: String): Boolean {
return imageRegex.matches(url)
}
fun getPostType(url: String): PostType {
return if (isImage(url)) PostType.Image else PostType.Link
}
val imageRegex =
Regex(
pattern = "(http)?s?:?(//[^\"']*\\.(?:jpg|jpeg|gif|png|svg|webp))",
)
fun closeDrawer(
scope: CoroutineScope,
drawerState: DrawerState,
) {
scope.launch {
drawerState.close()
}
}
fun personNameShown(
person: Person,
federatedName: Boolean = false,
): String {
val name = person.getDisplayName()
return if (!federatedName) {
name
} else {
if (person.local) {
name
} else {
"$name@${hostName(person.actor_id)}"
}
}
}
/**
* Warning, do not use this for links and such, only for messages
*/
fun communityNameShown(community: Community): String {
return if (community.local) {
community.title
} else {
"${community.title}@${hostName(community.actor_id)}"
}
}
fun hostName(url: String): String? {
return try {
URL(url).host
} catch (e: MalformedURLException) {
null
}
}
enum class UnreadOrAll {
All,
Unread,
}
fun unreadOrAllFromBool(b: Boolean): UnreadOrAll {
return if (b) {
UnreadOrAll.Unread
} else {
UnreadOrAll.All
}
}
fun appendMarkdownImage(
text: String,
url: String,
): String {
return "$text\n\n![]($url)"
}
/**
* Border definition can be extended to provide border style or [androidx.compose.ui.graphics.Brush]
* One more way is make it sealed class and provide different implementations:
* SolidBorder, DashedBorder etc
*/
data class Border(val strokeWidth: Dp, val color: Color)
@Stable
fun Modifier.border(
start: Border? = null,
top: Border? = null,
end: Border? = null,
bottom: Border? = null,
) = drawBehind {
start?.let {
drawStartBorder(it, shareTop = top != null, shareBottom = bottom != null)
}
top?.let {
drawTopBorder(it, shareStart = start != null, shareEnd = end != null)
}
end?.let {
drawEndBorder(it, shareTop = top != null, shareBottom = bottom != null)
}
bottom?.let {
drawBottomBorder(border = it, shareStart = start != null, shareEnd = end != null)
}
}
private fun DrawScope.drawTopBorder(
border: Border,
shareStart: Boolean = true,
shareEnd: Boolean = true,
) {
val strokeWidthPx = border.strokeWidth.toPx()
if (strokeWidthPx == 0f) return
drawPath(
Path().apply {
moveTo(0f, 0f)
lineTo(if (shareStart) strokeWidthPx else 0f, strokeWidthPx)
val width = size.width
lineTo(if (shareEnd) width - strokeWidthPx else width, strokeWidthPx)
lineTo(width, 0f)
close()
},
color = border.color,
)
}
private fun DrawScope.drawBottomBorder(
border: Border,
shareStart: Boolean,
shareEnd: Boolean,
) {
val strokeWidthPx = border.strokeWidth.toPx()
if (strokeWidthPx == 0f) return
drawPath(
Path().apply {
val width = size.width
val height = size.height
moveTo(0f, height)
lineTo(if (shareStart) strokeWidthPx else 0f, height - strokeWidthPx)
lineTo(if (shareEnd) width - strokeWidthPx else width, height - strokeWidthPx)
lineTo(width, height)
close()
},
color = border.color,
)
}
private fun DrawScope.drawStartBorder(
border: Border,
shareTop: Boolean = true,
shareBottom: Boolean = true,
) {
val strokeWidthPx = border.strokeWidth.toPx()
if (strokeWidthPx == 0f) return
drawPath(
Path().apply {
moveTo(0f, 0f)
lineTo(strokeWidthPx, if (shareTop) strokeWidthPx else 0f)
val height = size.height
lineTo(strokeWidthPx, if (shareBottom) height - strokeWidthPx else height)
lineTo(0f, height)
close()
},
color = border.color,
)
}
private fun DrawScope.drawEndBorder(
border: Border,
shareTop: Boolean = true,
shareBottom: Boolean = true,
) {
val strokeWidthPx = border.strokeWidth.toPx()
if (strokeWidthPx == 0f) return
drawPath(
Path().apply {
val width = size.width
val height = size.height
moveTo(width, 0f)
lineTo(width - strokeWidthPx, if (shareTop) strokeWidthPx else 0f)
lineTo(width - strokeWidthPx, if (shareBottom) height - strokeWidthPx else height)
lineTo(width, height)
close()
},
color = border.color,
)
}
fun isPostCreator(commentView: CommentView): Boolean {
return commentView.creator.id == commentView.post.creator_id
}
data class InputField(
val label: String,
val hasError: Boolean,
)
fun validatePostName(
ctx: Context,
name: String,
): InputField {
return if (name.isEmpty()) {
InputField(
label = ctx.getString(R.string.title_required),
hasError = true,
)
} else if (name.length < 3) {
InputField(
label = ctx.getString(R.string.title_min_3_chars),
hasError = true,
)
} else if (name.length >= MAX_POST_TITLE_LENGTH) {
InputField(
label = ctx.getString(R.string.title_less_than_200_chars),
hasError = true,
)
} else {
InputField(
label = ctx.getString(R.string.title),
hasError = false,
)
}
}
fun validateUrl(
ctx: Context,
url: String,
): InputField {
return if (url.isNotEmpty() && !PatternsCompat.WEB_URL.matcher(url).matches()) {
InputField(
label = ctx.getString(R.string.url_invalid),
hasError = true,
)
} else {
InputField(
label = ctx.getString(R.string.url),
hasError = false,
)
}
}
fun siFormat(num: Long): String {
// Weird bug where if num is zero, it won't format
if (num == 0L) return "0"
var value = num.toDouble()
val suffix = " KMBT"
val formatter = DecimalFormat("#,###.#")
val power = StrictMath.log10(value).toInt()
value /= 10.0.pow((power / 3 * 3).toDouble())
var formattedNumber = formatter.format(value)
formattedNumber += suffix[power / 3]
return if (formattedNumber.length > 4) {
formattedNumber.replace(
"\\.[0-9]+".toRegex(),
"",
)
} else {
formattedNumber
}
}
fun imageInputStreamFromUri(
ctx: Context,
uri: Uri,
): InputStream {
return ctx.contentResolver.openInputStream(uri)!!
}
fun scrollToTop(
scope: CoroutineScope,
listState: LazyListState,
) {
scope.launch {
listState.animateScrollToItem(index = 0)
}
}
fun showSnackbar(
scope: CoroutineScope,
snackbarHostState: SnackbarHostState,
message: String,
actionLabel: String?,
withDismissAction: Boolean = false,
snackbarDuration: SnackbarDuration,
) {
scope.launch {
snackbarHostState.showSnackbar(
message,
actionLabel,
withDismissAction,
snackbarDuration,
)
}
}
// https://stackoverflow.com/questions/69234880/how-to-get-intent-data-in-a-composable
fun Context.findActivity(): Activity? =
when (this) {
is Activity -> this
is ContextWrapper -> baseContext.findActivity()
else -> null
}
enum class ThemeMode(
@StringRes val resId: Int,
) {
System(R.string.look_and_feel_theme_system),
SystemBlack(R.string.look_and_feel_theme_system_black),
Light(R.string.look_and_feel_theme_light),
Dark(R.string.look_and_feel_theme_dark),
Black(R.string.look_and_feel_theme_black),
}
enum class ThemeColor(
@StringRes val resId: Int,
) {
Dynamic(R.string.look_and_feel_theme_color_dynamic),
Beach(R.string.look_and_feel_theme_color_beach),
Blue(R.string.look_and_feel_theme_color_blue),
Crimson(R.string.look_and_feel_theme_color_crimson),
Green(R.string.look_and_feel_theme_color_green),
Grey(R.string.look_and_feel_theme_color_grey),
Pink(R.string.look_and_feel_theme_color_pink),
Purple(R.string.look_and_feel_theme_color_purple),
Woodland(R.string.look_and_feel_theme_color_woodland),
Dracula(R.string.look_and_feel_theme_color_dracula),
}
enum class PostViewMode(
@StringRes val resId: Int,
) {
/**
* The full size post view card. For image posts, this expands them to their full height. For
* link posts, the thumbnail is shown to the right of the title.
*/
Card(R.string.look_and_feel_post_view_card),
/**
* The same as regular card, except image posts only show a thumbnail image.
*/
SmallCard(R.string.look_and_feel_post_view_small_card),
/**
* A list view that has no action bar.
*/
List(R.string.look_and_feel_post_view_list),
}
/**
* For a given post, what sort of content Jerboa treats it as.
*/
enum class PostType {
/**
* A Link to an external website. Opens the browser.
*/
Link,
/**
* An Image. Opens the built-in image viewer.
*/
Image,
/**
* A Video. Should open the built-in video viewer.
* Also matches audio only
* (Not currently available).
*/
Video,
;
companion object {
fun fromURL(url: String): PostType {
return if (isImage(url)) {
Image
} else if (isVideo(url)) {
Video
} else {
Link
}
}
}
fun toMediaDir(): String {
return when (this) {
Image -> Environment.DIRECTORY_PICTURES
Video -> Environment.DIRECTORY_MOVIES
Link -> Environment.DIRECTORY_DOWNLOADS
}
}
}
fun isSameInstance(
url: String,
instance: String,
): Boolean {
return hostName(url) == instance
}
fun getCommentParentId(comment: Comment): CommentId? = getCommentParentId(comment.path)
fun getCommentParentId(commentPath: String): CommentId? {
val split = commentPath.split(".").toMutableList()
// remove the 0
split.removeFirst()
return if (split.size > 1) {
split[split.size - 2].toLong()
} else {
null
}
}
/**
* Returns the path of the parent
*
* Ex: 0.1.2.3 -> 0.1.2
*/
fun getParentPath(path: String) = path.substringBeforeLast(".")
fun getDepthFromComment(commentPath: String): Int {
return commentPath.split(".").size.minus(2)
}
fun getDepthFromComment(comment: Comment): Int = getDepthFromComment(comment.path)
fun getCommentIdDepthFromPath(
commentPath: String,
commentId: CommentId,
): Int {
val split = commentPath.split(".").toMutableList()
return split.indexOf(commentId.toString()).minus(1)
}
fun nsfwCheck(postView: PostView): Boolean {
return postView.post.nsfw || postView.community.nsfw
}
@RequiresApi(Build.VERSION_CODES.Q)
@Throws(IOException::class)
fun saveMediaQ(
ctx: Context,
inputStream: InputStream,
mimeType: String?,
displayName: String,
mediaType: PostType,
): Uri {
val values =
ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, displayName)
put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
put(MediaStore.MediaColumns.RELATIVE_PATH, mediaType.toMediaDir() + "/Jerboa")
}
val resolver = ctx.contentResolver
var uri: Uri? = null
try {
val insert =
when (mediaType) {
PostType.Image -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI
PostType.Video -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI
PostType.Link -> MediaStore.Downloads.EXTERNAL_CONTENT_URI
}
uri = resolver.insert(insert, values)
?: throw IOException("Failed to create new MediaStore record.")
resolver.openOutputStream(uri)?.use {
inputStream.copyTo(it)
} ?: throw IOException("Failed to open output stream.")
return uri
} catch (e: IOException) {
uri?.let { orphanUri ->
// Don't leave an orphan entry in the MediaStore
resolver.delete(orphanUri, null, null)
}
throw e
}
}
// saveMedia that works for Android 9 and below
fun saveMediaP(
context: Context,
inputStream: InputStream,
mimeType: String?,
displayName: String,
// Link is here more like other media (think of PDF, doc, txt)
mediaType: PostType,
) {
val dir = Environment.getExternalStoragePublicDirectory(mediaType.toMediaDir())
val mediaDir = File(dir, "Jerboa")
val dest = File(mediaDir, displayName)
mediaDir.mkdirs() // make if not exist
inputStream.use { input ->
dest.outputStream().use {
input.copyTo(it)
}
}
// Makes it show up in gallery
val mimeTypes = if (mimeType == null) null else arrayOf(mimeType)
MediaScannerConnection.scanFile(context, arrayOf(dest.absolutePath), mimeTypes, null)
}
/**
* Converts a scalable pixel (sp) to an actual pixel (px)
*/
fun convertSpToPx(
sp: TextUnit,
ctx: Context,
): Int {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP,
sp.value,
ctx.resources.displayMetrics,
).toInt()
}
fun findAndUpdatePrivateMessage(
messages: List<PrivateMessageView>,
updated: PrivateMessageView,
): List<PrivateMessageView> {
val foundIndex =
messages.indexOfFirst {
it.private_message.id == updated.private_message.id
}
return if (foundIndex != -1) {
val mutable = messages.toMutableList()
mutable[foundIndex] = updated
mutable.toList()
} else {
messages
}
}
fun findAndUpdateApplication(
applications: List<RegistrationApplicationView>,
updatedApplication: RegistrationApplicationView,
): List<RegistrationApplicationView> {
val foundIndex =
applications.indexOfFirst {
it.registration_application.id == updatedApplication.registration_application.id
}
return if (foundIndex != -1) {
val mutable = applications.toMutableList()
mutable[foundIndex] = updatedApplication
mutable.toList()
} else {
applications
}
}
fun findAndUpdatePostReport(
reports: List<PostReportView>,
updatedReport: PostReportView,
): List<PostReportView> {
val foundIndex =
reports.indexOfFirst {
it.post_report.id == updatedReport.post_report.id
}
return if (foundIndex != -1) {
val mutable = reports.toMutableList()
mutable[foundIndex] = updatedReport