content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.cmoney.kolfanci.ui.common import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.sp import com.cmoney.kolfanci.ui.theme.LocalColor import com.cmoney.kolfanci.ui.theme.White_767A7F import com.cmoney.kolfanci.ui.theme.White_DDDEDF @Composable fun GroupText( text: String, modifier: Modifier = Modifier, textColor: Color = LocalColor.current.text.default_100 ) { Text( text = text, style = TextStyle( fontSize = 16.sp, color = textColor, fontWeight = FontWeight.Bold ), maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = modifier ) } @Composable fun CategoryText( modifier: Modifier = Modifier, text: String) { Text( modifier = modifier, text = text, style = TextStyle( fontSize = 14.sp, color = LocalColor.current.text.default_50 ), maxLines = 1, overflow = TextOverflow.Ellipsis ) } @Composable fun ChannelText( modifier: Modifier = Modifier, text: String) { Text( modifier = modifier, text = text, style = TextStyle( fontSize = 16.sp, color = LocalColor.current.text.default_100 ), maxLines = 1, overflow = TextOverflow.Ellipsis ) } /** * 聊天室 po文時間 */ @Composable fun ChatTimeText(text: String) { Text( text = text, style = TextStyle( fontSize = 12.sp, color = White_767A7F ), maxLines = 1, overflow = TextOverflow.Ellipsis ) } /** * 聊天室 內文 */ @Composable fun ChatMessageText(text: String, modifier: Modifier = Modifier) { Text( text = text, style = TextStyle( fontSize = 17.sp, color = White_DDDEDF ), modifier = modifier ) } @Composable fun EmojiText(text: String, modifier: Modifier = Modifier) { Text( text = text, style = TextStyle( fontSize = 14.sp, color = LocalColor.current.text.default_80 ), modifier = modifier ) } /** * 聊天 回覆 content title */ @Composable fun ReplyTitleText(text: String, modifier: Modifier = Modifier) { Text( text = text, style = TextStyle( fontSize = 12.sp, color = LocalColor.current.text.default_100 ), modifier = modifier ) } /** * 聊天 回覆 content */ @Composable fun ReplyText(text: String, modifier: Modifier = Modifier) { Text( text = text, style = TextStyle( fontSize = 14.sp, color = LocalColor.current.text.default_100 ), modifier = modifier ) } /** * 聊天 回覆 title */ @Composable fun ReplyChatTitleText(text: String, modifier: Modifier = Modifier) { Text( text = text, color = LocalColor.current.text.default_100, fontSize = 12.sp, modifier = modifier, maxLines = 1, overflow = TextOverflow.Ellipsis ) } /** * 聊天 回覆 */ @Composable fun ReplyChatText(text: String, modifier: Modifier = Modifier) { Text( text = text, color = LocalColor.current.text.default_100, fontSize = 14.sp, modifier = modifier, maxLines = 1, overflow = TextOverflow.Ellipsis ) }
Fanci/app/src/main/java/com/cmoney/kolfanci/ui/common/Text.kt
730820402
package com.cmoney.kolfanci.ui.common import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Canvas import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathEffect import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.cmoney.kolfanci.R import com.cmoney.kolfanci.ui.theme.FanciTheme import com.cmoney.kolfanci.ui.theme.LocalColor @Composable fun TransparentButton(text: String, onClick: () -> Unit) { Button( modifier = Modifier .padding(25.dp) .fillMaxWidth() .height(50.dp), colors = ButtonDefaults.buttonColors(backgroundColor = Color.Transparent), elevation = ButtonDefaults.elevation(0.dp), border = BorderStroke(1.dp, LocalColor.current.text.default_50), onClick = { onClick.invoke() }) { Text( text = text, color = LocalColor.current.text.default_100, fontSize = 16.sp ) } } @Preview(showBackground = true) @Composable fun TransparentButtonPreview() { FanciTheme { TransparentButton(text = "Hello") {} } } @Composable fun BlueButton( modifier: Modifier = Modifier .padding(25.dp) .fillMaxWidth() .height(50.dp), text: String, onClick: () -> Unit ) { Button( modifier = modifier, colors = ButtonDefaults.buttonColors(backgroundColor = LocalColor.current.primary), onClick = { onClick.invoke() }) { Text( text = text, color = LocalColor.current.text.other, fontSize = 16.sp ) } } @Preview(showBackground = true) @Composable fun BlueButtonPreview() { FanciTheme { BlueButton(text = "Hello") {} } } @Composable fun GroupJoinButton( modifier: Modifier = Modifier, text: String, shape: RoundedCornerShape = RoundedCornerShape(4.dp), onClick: () -> Unit ) { androidx.compose.material3.Button( modifier = modifier .fillMaxWidth() .height(50.dp), colors = androidx.compose.material3.ButtonDefaults.buttonColors( containerColor = LocalColor.current.background, contentColor = LocalColor.current.background ), shape = shape, onClick = { onClick.invoke() } ) { Text( text = text, color = LocalColor.current.text.default_100, fontSize = 16.sp ) } } @Preview @Composable fun GroupJoinButtonPreview() { FanciTheme { GroupJoinButton(text = "Hello") {} } } @Composable fun GrayButton( text: String, shape: RoundedCornerShape = RoundedCornerShape(15), onClick: () -> Unit ) { Button( modifier = Modifier .fillMaxWidth() .height(50.dp), shape = shape, colors = ButtonDefaults.buttonColors(backgroundColor = LocalColor.current.env_80), onClick = { onClick.invoke() }) { Text( text = text, color = LocalColor.current.text.default_100, fontSize = 16.sp ) } } @Preview(showBackground = true) @Composable fun GrayButtonPreview() { FanciTheme { GrayButton(text = "Hello") {} } } @Composable fun BorderButton( modifier: Modifier = Modifier, text: String, shape: RoundedCornerShape = RoundedCornerShape(15), borderColor: Color, textColor: Color = borderColor, onClick: () -> Unit ) { androidx.compose.material3.Button( modifier = modifier, shape = shape, colors = androidx.compose.material3.ButtonDefaults.buttonColors( containerColor = Color.Transparent, contentColor = Color.Transparent ), border = BorderStroke(1.dp, borderColor), onClick = onClick ) { Text( text = text, color = textColor, fontSize = 14.sp ) } } @Preview(showBackground = true) @Composable fun BorderButtonPreview() { FanciTheme { BorderButton(text = "Hello BorderButtonPreview", borderColor = Color.Gray) {} } } /** * 虛線邊匡 - 中間加號 */ @Composable fun DashPlusButton( onClick: () -> Unit ) { val stroke = Stroke( width = 2f, pathEffect = PathEffect.dashPathEffect(floatArrayOf(20f, 10f), 0f) ) val borderColor = LocalColor.current.text.default_30 Box( modifier = Modifier .fillMaxWidth() .height(50.dp) .clickable { onClick.invoke() }, contentAlignment = Alignment.Center ) { Canvas( Modifier.fillMaxSize() ) { drawRoundRect( color = borderColor, style = stroke, cornerRadius = CornerRadius(8.dp.toPx()) ) } Image( painter = painterResource(id = R.drawable.plus_white), contentDescription = null ) } } @Preview(showBackground = true) @Composable fun DashPlusButtonPreview() { FanciTheme { DashPlusButton { } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/ui/common/Button.kt
257206337
package com.cmoney.kolfanci.ui.common import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.shape.CircleShape import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import coil.compose.AsyncImage import com.cmoney.kolfanci.R @Composable fun CircleImage( imageUrl: String, modifier: Modifier = Modifier ) { AsyncImage( model = imageUrl, modifier = modifier .aspectRatio(1f) .clip(CircleShape), contentScale = ContentScale.Crop, contentDescription = null, placeholder = painterResource(id = R.drawable.placeholder) ) }
Fanci/app/src/main/java/com/cmoney/kolfanci/ui/common/Image.kt
833149764
package com.cmoney.kolfanci.ui.common import android.text.method.LinkMovementMethod import android.text.util.Linkify import android.widget.TextView import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.viewinterop.AndroidView import androidx.core.text.util.LinkifyCompat import androidx.core.view.doOnLayout import com.socks.library.KLog /** * 帶連結 文字訊息 */ @Composable fun AutoLinkText( modifier: Modifier = Modifier, text: String, fontSize: TextUnit = TextUnit.Unspecified, color: Color = Color.Unspecified, onLongClick: (() -> Unit)? = null, ) { val context = LocalContext.current val customLinkifyTextView = remember { TextView(context) } AndroidView(modifier = modifier, factory = { customLinkifyTextView }) { textView -> textView.text = text textView.setTextColor(color.toArgb()) textView.textSize = fontSize.value LinkifyCompat.addLinks(textView, Linkify.WEB_URLS) // Linkify.addLinks( // textView, Patterns.PHONE, "tel:", // Linkify.sPhoneNumberMatchFilter, Linkify.sPhoneNumberTransformFilter // ) textView.movementMethod = LinkMovementMethod.getInstance() textView.setOnLongClickListener { onLongClick?.invoke() true } } } @Preview(showBackground = true) @Composable fun AutoLinkTextPreview() { AutoLinkText(text = "Hello") {} } @Composable fun AutoLinkPostText( modifier: Modifier = Modifier, text: String, fontSize: TextUnit = TextUnit.Unspecified, color: Color = Color.Unspecified, maxLine: Int = Int.MAX_VALUE, onClick: (() -> Unit)? = null, onLineCount: ((Int) -> Unit)? = null ) { val context = LocalContext.current val customLinkifyTextView = remember { TextView(context) } AndroidView(modifier = modifier, factory = { customLinkifyTextView }) { textView -> textView.text = text textView.setTextColor(color.toArgb()) textView.textSize = fontSize.value textView.maxLines = maxLine LinkifyCompat.addLinks(textView, Linkify.WEB_URLS) // Linkify.addLinks( // textView, Patterns.PHONE, "tel:", // Linkify.sPhoneNumberMatchFilter, Linkify.sPhoneNumberTransformFilter // ) textView.movementMethod = LinkMovementMethod.getInstance() textView.doOnLayout { val lineCount = (it as TextView).lineCount onLineCount?.invoke(lineCount) } textView.setOnClickListener { onClick?.invoke() } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/ui/common/AutoLinkText.kt
315884829
package com.cmoney.kolfanci.ui.common import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import com.cmoney.kolfanci.extension.toColor import com.cmoney.kolfanci.ui.theme.LocalColor /** * 16進位文字 對應 角色 顏色 */ @Composable fun HexStringMapRoleColor(hexString: String): Color { return if (hexString.isNotEmpty()) { val findColor = LocalColor.current.roleColor.colors.firstOrNull { it.name == hexString }?.hexColorCode?.toColor() findColor ?: LocalColor.current.primary } else { LocalColor.current.primary } }
Fanci/app/src/main/java/com/cmoney/kolfanci/ui/common/Color.kt
3786697811
package com.cmoney.kolfanci.ui.common import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.unit.dp import com.cmoney.kolfanci.ui.theme.LocalColor @Composable fun CircleDot() { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ) { Box( modifier = Modifier .size(3.8.dp) .clip(CircleShape) .background(LocalColor.current.primary) ) Box( modifier = Modifier .size(3.8.dp) .clip(CircleShape) .background(LocalColor.current.primary) ) Box( modifier = Modifier .size(3.8.dp) .clip(CircleShape) .background(LocalColor.current.primary) ) } }
Fanci/app/src/main/java/com/cmoney/kolfanci/ui/common/CircleDot.kt
3500807112
package com.cmoney.kolfanci.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
Fanci/app/src/main/java/com/cmoney/kolfanci/ui/theme/Shape.kt
392215174
package com.cmoney.kolfanci.ui.theme import androidx.compose.ui.graphics.Color val Black_14171C = Color(0xFF14171C) val Black_1B2129 = Color(0xFF1B2129) val Black_191E24 = Color(0xFF191E24) val Black_181C23 = Color(0xFF181C23) val Black_202327 = Color(0Xff202327) val Black_282A2D = Color(0xFF282A2D) val Black_99000000 = Color(0x99000000) val Black_2B313C = Color(0xFF2B313C) val Black_242424 = Color(0xFF242424) val Black_1AFFFFFF = Color(0x1AFFFFFF) val White_494D54 = Color(0Xff494D54) val White_BBBCBF = Color(0xFFBBBCBF) val White_767A7F = Color(0xFF767A7F) val White_DDDEDF = Color(0xFFDDDEDF) val White_262C34 = Color(0xFF262C34) val White_C7C7C7 = Color(0xFFC7C7C7) val Color_99FFFFFF = Color(0x99FFFFFF) //=========== Fanci =========== val Color_4F70E5 = Color(0xFF4F70E5) val Color_0DFFFFFF = Color(0x0DFFFFFF) val Color_3D4452 = Color(0xFF3D4452) val Color_303744 = Color(0xFF303744) val Color_2B313C = Color(0xFF2B313C) val Color_20262F = Color(0xFF20262F) val Color_E6FFFFFF = Color(0XE6FFFFFF) //=========== Coffee =========== val Color_84603F = Color(0xFF84603F) val Color_0D000000 = Color(0x0D000000) val Color_F5E7DA = Color(0xFFF5E7DA) val Color_FFF1E3 = Color(0xFFFFF1E3) val Color_FCE7D4 = Color(0xFFFCE7D4) val Color_A98F76 = Color(0xFFA98F76) val Color_CCFFFFFF = Color(0xCCFFFFFF) //=========== Light Component =========== val Color_33000000 = Color(0x33000000) val Color_4D292929 = Color(0x4D292929) //=========== Dark Component =========== val Color_33FFFFFF = Color(0x33FFFFFF) val Color_80FFFFFF = Color(0x80FFFFFF) val Color_4D2D2D2D = Color(0x4D2D2D2D) val Color_802D2D2D = Color(0x802D2D2D) val Color_CC2D2D2D = Color(0xCC2D2D2D) val Color_2D2D2D = Color(0xFF2D2D2D) val Color_37A2EF = Color(0xFF37A2EF) val Color_31B6A6 = Color(0xFF31B6A6) val Color_38B035 = Color(0xFF38B035) val Color_CA4848 = Color(0xFFCA4848) val Color_E18910 = Color(0xFFE18910) val Color_E24CA6 = Color(0xFFE24CA6) val Color_8559E1 = Color(0xFF8559E1) val Color_DDBA00 = Color(0xFFDDBA00) val Color_29787880 = Color(0x29787880)
Fanci/app/src/main/java/com/cmoney/kolfanci/ui/theme/Color.kt
2269890170
package com.cmoney.kolfanci.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.remember import androidx.compose.ui.graphics.Color import com.cmoney.kolfanci.R //========== Text ========== private val darkText = FanciTextColor( default_30 = Color_33FFFFFF, default_50 = Color_80FFFFFF, default_80 = Color_CCFFFFFF, default_100 = Color.White, other = Color.White ) private val lightText = FanciTextColor( default_30 = Color_4D2D2D2D, default_50 = Color_802D2D2D, default_80 = Color_CC2D2D2D, default_100 = Color_2D2D2D, other = Color.White ) //========== Component ========== private val lightComponent = FanciComponentColor( tabUnSelect = Color_33000000, tabSelected = Color.White, other = Color_4D292929 ) private val darkComponent = FanciComponentColor( tabUnSelect = Color_33FFFFFF, tabSelected = Color.White, other = Color_80FFFFFF ) //========== Input Text ========== private val inputText = FanciInputText( input_30 = Color_4D2D2D2D, input_50 = Color_802D2D2D, input_80 = Color_CC2D2D2D, input_100 = Color_2D2D2D ) private val specialColor = SpecialColor( blue = Color_37A2EF, blueGreen = Color_31B6A6, green = Color_38B035, hintRed = Color_CA4848, orange = Color_E18910, pink = Color_E24CA6, purple = Color_8559E1, red = Color.Red, yellow = Color_DDBA00 ) private val roleColor = RoleColor( listOf( com.cmoney.fanciapi.fanci.model.Color( hexColorCode = "FF37A2EF", displayName = "藍" ), com.cmoney.fanciapi.fanci.model.Color( hexColorCode = "FF31B6A6", displayName = "藍綠" ), com.cmoney.fanciapi.fanci.model.Color( hexColorCode = "FF38B035", displayName = "綠" ), com.cmoney.fanciapi.fanci.model.Color( hexColorCode = "FFE18910", displayName = "橘" ), com.cmoney.fanciapi.fanci.model.Color( hexColorCode = "FFE24CA6", displayName = "粉" ), com.cmoney.fanciapi.fanci.model.Color( hexColorCode = "FF8559E1", displayName = "紫" ), com.cmoney.fanciapi.fanci.model.Color( hexColorCode = "FFCA4848", displayName = "紅" ), com.cmoney.fanciapi.fanci.model.Color( hexColorCode = "FFDDBA00", displayName = "黃" ) ) ) val DefaultThemeColor = FanciColor( primary = Color_4F70E5, background = Color_0DFFFFFF, env_40 = Color_3D4452, env_60 = Color_303744, env_80 = Color_2B313C, env_100 = Color_20262F, inputFrame = Color_E6FFFFFF, component = darkComponent, text = darkText, inputText = inputText, specialColor = specialColor, roleColor = roleColor ) @Composable fun DefaultTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val image = DarkImages MainTheme(darkTheme, DefaultThemeColor, content, image) } val CoffeeThemeColor = FanciColor( primary = Color_84603F, background = Color_0D000000, env_40 = Color_F5E7DA, env_60 = Color_FFF1E3, env_80 = Color_FCE7D4, env_100 = Color_A98F76, inputFrame = Color_CCFFFFFF, component = lightComponent, text = lightText, inputText = inputText, specialColor = specialColor, roleColor = roleColor ) @Composable fun CoffeeTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { MainTheme(darkTheme, CoffeeThemeColor, content) } private val DarkImages = Images(lockupLogo = R.drawable.emoji_like) @Composable fun FanciTheme( darkTheme: Boolean = isSystemInDarkTheme(), fanciColor: FanciColor = LocalColor.current, content: @Composable () -> Unit ) { MainTheme(darkTheme, fanciColor, content) } @Composable private fun MainTheme( darkTheme: Boolean, fanciColor: FanciColor, content: @Composable () -> Unit, image: Images = LocalImages.current ) { val rememberColor = remember { // Explicitly creating a new object here so we don't mutate the initial [fanciColor] // provided, and overwrite the values set in it. fanciColor.copy() }.apply { updateColorFrom(other = fanciColor) } CompositionLocalProvider( LocalImages provides image, LocalColor provides rememberColor ) { MaterialTheme( colors = MaterialTheme.colors.copy( primary = fanciColor.env_100, background = fanciColor.env_100 ), content = content, typography = Typography, shapes = Shapes, ) } }
Fanci/app/src/main/java/com/cmoney/kolfanci/ui/theme/Theme.kt
2468192110
package com.cmoney.kolfanci.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ )
Fanci/app/src/main/java/com/cmoney/kolfanci/ui/theme/Type.kt
4143011270
package com.cmoney.kolfanci.ui.theme import androidx.annotation.DrawableRes import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.runtime.structuralEqualityPolicy import androidx.compose.ui.graphics.Color import com.cmoney.kolfanci.R import com.google.errorprone.annotations.Immutable private val LightImages = Images(lockupLogo = R.drawable.fanci) @Immutable data class Images(@DrawableRes val lockupLogo: Int) internal val LocalImages = staticCompositionLocalOf<Images> { LightImages } /** * Fanci 主題色 * * @property primary 主題色, 按鈕提示色 * @property background 打底色, List色、輸入匡等 * @property env_40 環境色 40, 其他配色 * @property env_60 環境色 60, 其他配色 * @property env_80 環境色 80, 物件背景色 * @property env_100 環境色 100, Nav/Tab色 * @property inputFrame 輸入框 * @property component 元件色 * @property text 文字色 * @property inputText 文字色-輸入框 * @property specialColor 特殊色 * @property roleColor 角色顏色 */ @Stable class FanciColor( primary: Color, background: Color, env_40: Color, env_60: Color, env_80: Color, env_100: Color, inputFrame: Color, component: FanciComponentColor, text: FanciTextColor, inputText: FanciInputText, specialColor: SpecialColor, roleColor: RoleColor ) { var primary by mutableStateOf(primary, structuralEqualityPolicy()) internal set var background by mutableStateOf(background, structuralEqualityPolicy()) internal set var env_40 by mutableStateOf(env_40, structuralEqualityPolicy()) internal set var env_60 by mutableStateOf(env_60, structuralEqualityPolicy()) internal set var env_80 by mutableStateOf(env_80, structuralEqualityPolicy()) internal set var env_100 by mutableStateOf(env_100, structuralEqualityPolicy()) internal set var inputFrame by mutableStateOf(inputFrame, structuralEqualityPolicy()) internal set var component by mutableStateOf(component, structuralEqualityPolicy()) internal set var text by mutableStateOf(text, structuralEqualityPolicy()) internal set var inputText by mutableStateOf(inputText, structuralEqualityPolicy()) internal set var specialColor by mutableStateOf(specialColor, structuralEqualityPolicy()) internal set var roleColor by mutableStateOf(roleColor, structuralEqualityPolicy()) internal set fun copy( primary: Color = this.primary, background: Color = this.background, env_40: Color = this.env_40, env_60: Color = this.env_60, env_80: Color = this.env_80, env_100: Color = this.env_100, inputFrame: Color = this.inputFrame, component: FanciComponentColor = this.component.copy(), text: FanciTextColor = this.text.copy(), inputText: FanciInputText = this.inputText.copy(), specialColor: SpecialColor = this.specialColor.copy(), roleColor: RoleColor = this.roleColor.copy() ): FanciColor { return FanciColor( primary = primary, background = background, env_40 = env_40, env_60 = env_60, env_80 = env_80, env_100 = env_100, inputFrame = inputFrame, component = component, text = text, inputText = inputText, specialColor = specialColor, roleColor = roleColor ) } override fun toString(): String { return "FanciColor(" + "primary=$primary, " + "background=$background, " + "env_40=$env_40, " + "env_60=$env_60, " + "env_80=$env_80, " + "env_100=$env_100, " + "inputFrame=$inputFrame, " + "component=$component, " + "text=$text, " + "inputText=$inputText, " + "specialColor=$specialColor, " + "roleColor=$roleColor" + ")" } } /** * 角色顏色 * * @property colors */ @Stable class RoleColor( colors: List<com.cmoney.fanciapi.fanci.model.Color> ) { var colors by mutableStateOf(colors, structuralEqualityPolicy()) internal set fun copy( colors: List<com.cmoney.fanciapi.fanci.model.Color> = this.colors.toList() ): RoleColor { return RoleColor( colors = colors ) } override fun toString(): String { return "RoleColor(" + "colors=$colors" + ")" } } /** * 特殊色 * * @property blue * @property blueGreen * @property green * @property hintRed * @property orange * @property pink * @property purple * @property red * @property yellow */ @Stable class SpecialColor( blue: Color, blueGreen: Color, green: Color, hintRed: Color, orange: Color, pink: Color, purple: Color, red: Color, yellow: Color ) { var blue by mutableStateOf(blue, structuralEqualityPolicy()) internal set var blueGreen by mutableStateOf(blueGreen, structuralEqualityPolicy()) internal set var green by mutableStateOf(green, structuralEqualityPolicy()) internal set var hintRed by mutableStateOf(hintRed, structuralEqualityPolicy()) internal set var orange by mutableStateOf(orange, structuralEqualityPolicy()) internal set var pink by mutableStateOf(pink, structuralEqualityPolicy()) internal set var purple by mutableStateOf(purple, structuralEqualityPolicy()) internal set var red by mutableStateOf(red, structuralEqualityPolicy()) internal set var yellow by mutableStateOf(yellow, structuralEqualityPolicy()) internal set fun copy( blue: Color = this.blue, blueGreen: Color = this.blueGreen, green: Color = this.green, hintRed: Color = this.hintRed, orange: Color = this.orange, pink: Color = this.pink, purple: Color = this.purple, red: Color = this.red, yellow: Color = this.yellow ): SpecialColor { return SpecialColor( blue = blue, blueGreen = blueGreen, green = green, hintRed = hintRed, orange = orange, pink = pink, purple = purple, red = red, yellow = yellow ) } override fun toString(): String { return "SpecialColor(" + "blue=$blue, " + "blueGreen=$blueGreen, " + "green=$green, " + "hintRed=$hintRed, " + "orange=$orange, " + "pink=$pink, " + "purple=$purple, " + "red=$red, " + "yellow=$yellow" + ")" } } /** * 文字色-輸入框 * * @property input_30 * @property input_50 * @property input_80 * @property input_100 */ @Stable class FanciInputText( input_30: Color, input_50: Color, input_80: Color, input_100: Color ) { var input_30 by mutableStateOf(input_30, structuralEqualityPolicy()) internal set var input_50 by mutableStateOf(input_50, structuralEqualityPolicy()) internal set var input_80 by mutableStateOf(input_80, structuralEqualityPolicy()) internal set var input_100 by mutableStateOf(input_100, structuralEqualityPolicy()) internal set fun copy( input_30: Color = this.input_30, input_50: Color = this.input_50, input_80: Color = this.input_80, input_100: Color = this.input_100 ): FanciInputText { return FanciInputText( input_30 = input_30, input_50 = input_50, input_80 = input_80, input_100 = input_100 ) } override fun toString(): String { return "FanciInputText(" + "input_30=$input_30, " + "input_50=$input_50, " + "input_80=$input_80, " + "input_100=$input_100" + ")" } } /** * 元件色 * * @property tabUnSelect * @property tabSelected * @property other */ @Stable class FanciComponentColor( tabUnSelect: Color, tabSelected: Color, other: Color ) { var tabUnSelect by mutableStateOf(tabUnSelect, structuralEqualityPolicy()) internal set var tabSelected by mutableStateOf(tabSelected, structuralEqualityPolicy()) internal set var other by mutableStateOf(other, structuralEqualityPolicy()) internal set fun copy( tabUnSelect: Color = this.tabUnSelect, tabSelected: Color = this.tabSelected, other: Color = this.other ): FanciComponentColor { return FanciComponentColor( tabUnSelect = tabUnSelect, tabSelected = tabSelected, other = other ) } override fun toString(): String { return "FanciComponentColor(" + "tabUnSelect=$tabUnSelect, " + "tabSelected=$tabSelected, " + "other=$other" + ")" } } /** * 文字色 * * @property default_30 * @property default_50 * @property default_80 * @property default_100 * @property other */ @Stable class FanciTextColor( default_30: Color, default_50: Color, default_80: Color, default_100: Color, other: Color ) { var default_30 by mutableStateOf(default_30, structuralEqualityPolicy()) internal set var default_50 by mutableStateOf(default_50, structuralEqualityPolicy()) internal set var default_80 by mutableStateOf(default_80, structuralEqualityPolicy()) internal set var default_100 by mutableStateOf(default_100, structuralEqualityPolicy()) internal set var other by mutableStateOf(other, structuralEqualityPolicy()) internal set fun copy( default_30: Color = this.default_30, default_50: Color = this.default_50, default_80: Color = this.default_80, default_100: Color = this.default_100, other: Color = this.other ): FanciTextColor { return FanciTextColor( default_30 = default_30, default_50 = default_50, default_80 = default_80, default_100 = default_100, other = other ) } override fun toString(): String { return "FanciTextColor(" + "default_30=$default_30, " + "default_50=$default_50, " + "default_80=$default_80, " + "default_100=$default_100, " + "other=$other" + ")" } } /** * Updates the internal values of the given [FanciColor] with values from the [other] [FanciColor]. This * allows efficiently updating a subset of [FanciColor], without recomposing every composable that * consumes values from [LocalColor]. * * Because [FanciColor] is very wide-reaching, and used by many expensive composables in the * hierarchy, providing a new value to [LocalColor] causes every composable consuming * [LocalColor] to recompose, which is prohibitively expensive in cases such as animating one * color in the theme. Instead, [FanciColor] is internally backed by [mutableStateOf], and this * function mutates the internal state of [this] to match values in [other]. This means that any * changes will mutate the internal state of [this], and only cause composables that are reading * the specific changed value to recompose. * * 備註:這是從 Material 的 Colors.kt 複製的註解 */ internal fun FanciColor.updateColorFrom(other: FanciColor) { primary = other.primary background = other.background env_40 = other.env_40 env_60 = other.env_60 env_80 = other.env_80 env_100 = other.env_100 inputFrame = other.inputFrame component.updateColorFrom(other.component) text.updateColorFrom(other.text) inputText.updateColorFrom(other.inputText) specialColor.updateColorFrom(other.specialColor) roleColor.updateColorFrom(other.roleColor) } private fun FanciComponentColor.updateColorFrom(other: FanciComponentColor) { tabUnSelect = other.tabSelected tabSelected = other.tabUnSelect this.other = other.other } private fun FanciTextColor.updateColorFrom(other: FanciTextColor) { default_30 = other.default_30 default_50 = other.default_50 default_80 = other.default_80 default_100 = other.default_100 this.other = other.other } private fun FanciInputText.updateColorFrom(other: FanciInputText) { input_30 = other.input_30 input_50 = other.input_50 input_80 = other.input_80 input_100 = other.input_100 } private fun SpecialColor.updateColorFrom(other: SpecialColor) { blue = other.blue blueGreen = other.blueGreen green = other.green hintRed = other.hintRed orange = other.orange pink = other.pink purple = other.purple red = other.red yellow = other.yellow } private fun RoleColor.updateColorFrom(other: RoleColor) { colors = other.colors } internal val LocalColor = staticCompositionLocalOf<FanciColor> { DefaultThemeColor }
Fanci/app/src/main/java/com/cmoney/kolfanci/ui/theme/Local.kt
2073043144
package com.cmoney.kolfanci.ui.main import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.cmoney.fanciapi.fanci.model.Group import com.cmoney.kolfanci.model.Constant import com.cmoney.kolfanci.model.notification.NotificationHelper import com.cmoney.kolfanci.model.notification.Payload import com.cmoney.kolfanci.model.notification.TargetType import com.cmoney.kolfanci.model.persistence.SettingsDataStore import com.cmoney.kolfanci.model.usecase.GroupUseCase import com.cmoney.kolfanci.model.usecase.UserUseCase import com.socks.library.KLog import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch class MainViewModel( private val userUseCase: UserUseCase, private val settingsDataStore: SettingsDataStore, private val notificationHelper: NotificationHelper, private val groupUseCase: GroupUseCase ) : ViewModel() { private val TAG = MainViewModel::class.java.simpleName //自動登入中 private val _loginLoading = MutableStateFlow(true) val loginLoading = _loginLoading.asStateFlow() private val _isOpenTutorial: MutableStateFlow<Boolean?> = MutableStateFlow(null) val isOpenTutorial = _isOpenTutorial.asStateFlow() private val _isLoginSuccess = MutableStateFlow(false) val isLoginSuccess = _isLoginSuccess.asStateFlow() //登入彈窗 private val _showLoginDialog: MutableStateFlow<Boolean> = MutableStateFlow(false) val showLoginDialog = _showLoginDialog.asStateFlow() init { viewModelScope.launch { _isOpenTutorial.value = settingsDataStore.isTutorial.first() } } /** * 登入成功之後,要向 Fanci後台註冊 */ private fun registerUser() { KLog.i(TAG, "registerUser") viewModelScope.launch { userUseCase.registerUser() userUseCase.fetchMyInfo().fold({ Constant.MyInfo = it }, { KLog.e(TAG, it) }) } } /** * 看過 tutorial */ fun tutorialOnOpen() { KLog.i(TAG, "tutorialOnOpen") viewModelScope.launch { settingsDataStore.onTutorialOpen() _isOpenTutorial.value = true } } /** * 自動登入作業完成 */ private fun loginProcessDone() { KLog.i(TAG, "loginProcessDone") _loginLoading.value = false } /** * 登入成功, 並註冊使用者資訊 */ fun loginSuccess() { KLog.i(TAG, "loginSuccess") registerUser() loginProcessDone() } /** * 登入失敗 */ fun loginFail(errorMessage: String) { KLog.i(TAG, "loginFail:$errorMessage") loginProcessDone() } fun showLoginDialog() { _showLoginDialog.value = true } fun dismissLoginDialog() { _showLoginDialog.value = false } }
Fanci/app/src/main/java/com/cmoney/kolfanci/ui/main/MainViewModel.kt
735040542
package com.cmoney.kolfanci.ui.main import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.MaterialTheme import androidx.compose.material.ModalBottomSheetValue import androidx.compose.material.Scaffold import androidx.compose.material.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.cmoney.fancylog.model.data.Clicked import com.cmoney.kolfanci.R import com.cmoney.kolfanci.model.analytics.AppUserLogger import com.cmoney.kolfanci.model.notification.Payload import com.cmoney.kolfanci.model.notification.TargetType import com.cmoney.kolfanci.model.viewmodel.GroupViewModel import com.cmoney.kolfanci.model.viewmodel.NotificationViewModel import com.cmoney.kolfanci.ui.NavGraphs import com.cmoney.kolfanci.ui.common.BlueButton import com.cmoney.kolfanci.ui.destinations.MainScreenDestination import com.cmoney.kolfanci.ui.screens.media.audio.AudioViewModel import com.cmoney.kolfanci.ui.screens.shared.audio.AudioMiniPlayIconScreen import com.cmoney.kolfanci.ui.screens.shared.bottomSheet.audio.AudioBottomPlayerScreen import com.cmoney.kolfanci.ui.screens.shared.dialog.DialogScreen import com.cmoney.kolfanci.ui.screens.shared.dialog.LoginDialogScreen import com.cmoney.kolfanci.ui.screens.tutorial.TutorialScreen import com.cmoney.kolfanci.ui.theme.DefaultThemeColor import com.cmoney.kolfanci.ui.theme.FanciTheme import com.cmoney.kolfanci.ui.theme.LocalColor import com.cmoney.xlogin.XLoginHelper import com.cmoney.xlogin.base.BaseWebLoginActivity import com.google.accompanist.systemuicontroller.rememberSystemUiController import com.ramcosta.composedestinations.DestinationsNavHost import com.socks.library.KLog import kotlinx.coroutines.launch import org.koin.androidx.compose.koinViewModel import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf class MainActivity : BaseWebLoginActivity() { private val TAG = MainActivity::class.java.simpleName private val globalViewModel by viewModel<MainViewModel>() private val globalGroupViewModel by viewModel<GroupViewModel>() private val notificationViewModel by viewModel<NotificationViewModel>() private var payLoad: Payload? = null companion object { const val FOREGROUND_NOTIFICATION_BUNDLE = "foreground_notification_bundle" const val REQUEST_CODE_ALLOW_NOTIFICATION_PERMISSION: Int = 1 fun start(context: Context, payload: Payload) { KLog.i("MainActivity", "start by Payload") val starter = Intent(context, MainActivity::class.java) .putExtra(FOREGROUND_NOTIFICATION_BUNDLE, payload) starter.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK context.startActivity(starter) } fun createIntent(context: Context, payload: Payload): Intent { return Intent(context, MainActivity::class.java) .putExtra(FOREGROUND_NOTIFICATION_BUNDLE, payload) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) checkPayload(intent) setContent { val loginLoading by globalViewModel.loginLoading.collectAsState() val isOpenTutorial by globalViewModel.isOpenTutorial.collectAsState() val targetType by notificationViewModel.targetType.collectAsState() //我的社團清單 val myGroupList by globalGroupViewModel.myGroupList.collectAsState() //登入彈窗 val showLoginDialog by globalViewModel.showLoginDialog.collectAsState() //解散社團 彈窗 val showDissolveDialog by notificationViewModel.showDissolveGroupDialog.collectAsState() //是否刷新我的社團 val isRefreshMyGroup by notificationViewModel.refreshGroup.collectAsState() LaunchedEffect(key1 = targetType, key2 = loginLoading, key3 = myGroupList) { targetType?.let { targetType -> if (!loginLoading) { if (XLoginHelper.isLogin) { when (targetType) { TargetType.MainPage -> {} is TargetType.InviteGroup -> { val groupId = targetType.groupId notificationViewModel.fetchInviteGroup(groupId) } is TargetType.ReceiveMessage -> { if (myGroupList.isNotEmpty()) { notificationViewModel.receiveNewMessage( receiveNewMessage = targetType, myGroupList = myGroupList ) } } is TargetType.ReceivePostMessage -> { if (myGroupList.isNotEmpty()) { notificationViewModel.receiveNewPost( receivePostMessage = targetType, myGroupList = myGroupList ) } } is TargetType.DissolveGroup -> { if (myGroupList.isNotEmpty()) { notificationViewModel.dissolveGroup( dissolveGroup = targetType ) } } is TargetType.GroupApprove -> { val groupId = targetType.groupId notificationViewModel.groupApprove(groupId) } is TargetType.OpenGroup -> { if (myGroupList.isNotEmpty()) { val groupId = targetType.groupId notificationViewModel.openGroup( groupId = groupId, myGroupList = myGroupList ) } } } if (myGroupList.isNotEmpty()) { notificationViewModel.clearPushDataState() } } //Not Login else { when (targetType) { is TargetType.InviteGroup -> { val groupId = targetType.groupId notificationViewModel.fetchInviteGroup(groupId) } else -> { globalViewModel.showLoginDialog() } } } } } } isOpenTutorial?.let { isCurrentOpenTutorial -> FanciTheme(fanciColor = DefaultThemeColor) { if (isCurrentOpenTutorial) { MainScreen() } else { //是否為 邀請啟動 if (isInvitePayload(payLoad)) { MainScreen() } else { TutorialScreen( modifier = Modifier.fillMaxWidth() ) { globalViewModel.tutorialOnOpen() } } } //刷新我的社團 if (isRefreshMyGroup) { globalGroupViewModel.fetchMyGroup(false) notificationViewModel.afterRefreshGroup() } //登入彈窗 if (showLoginDialog) { LoginDialogScreen( onDismiss = { globalViewModel.dismissLoginDialog() }, onLogin = { globalViewModel.dismissLoginDialog() startLogin() } ) } //解散社團 彈窗 showDissolveDialog?.let { groupId -> DialogScreen( title = stringResource(id = R.string.dissolve_group_title), subTitle = stringResource(id = R.string.dissolve_group_description), onDismiss = { notificationViewModel.dismissDissolveDialog() notificationViewModel.onCheckDissolveGroup( groupId, globalGroupViewModel.currentGroup.value ) }) { BlueButton( modifier = Modifier .fillMaxWidth() .height(50.dp), text = stringResource(id = R.string.confirm) ) { AppUserLogger.getInstance().log(Clicked.AlreadyDissolve) notificationViewModel.dismissDissolveDialog() notificationViewModel.onCheckDissolveGroup( groupId, globalGroupViewModel.currentGroup.value ) } } } } } } } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) checkPayload(intent) } /** * 檢查 推播 or dynamic link */ private fun checkPayload(intent: Intent?) { KLog.i(TAG, "checkPayload") intent?.let { payLoad = intent.getParcelableExtra<Payload>(FOREGROUND_NOTIFICATION_BUNDLE) KLog.d(TAG, "payLoad = $payLoad") payLoad?.let { notificationViewModel.setNotificationBundle(it) } this.intent = null } } /** * 是否為邀請連結啟動 */ private fun isInvitePayload(payload: Payload?): Boolean { return payload?.targetType == Payload.TYPE_1 } fun checkPayload(payload: Payload) { KLog.d(TAG, "payLoad = $payload") notificationViewModel.setNotificationBundle(payload) } @OptIn(ExperimentalMaterialApi::class) @Composable fun MainScreen( audioViewModel: AudioViewModel = koinViewModel( parameters = { parametersOf(Uri.EMPTY) } ) ) { StatusBarColorEffect() //===== Audio Controller Start ===== val isShowAudioMiniIcon by audioViewModel.isShowMiniIcon.collectAsState() val isOpenBottomAudioPlayer by audioViewModel.isShowBottomPlayer.collectAsState() val isAudioPlaying by audioViewModel.isPlaying.collectAsState() val coroutineScope = rememberCoroutineScope() //控制 audio BottomSheet val audioPlayerState = rememberModalBottomSheetState( if (isOpenBottomAudioPlayer) { ModalBottomSheetValue.Expanded } else { ModalBottomSheetValue.Hidden } ) //===== Audio Controller End ===== Scaffold( modifier = Modifier .fillMaxSize() .background(LocalColor.current.primary), ) { padding -> Box( modifier = Modifier .padding(padding) ) { val theme by globalGroupViewModel.theme.collectAsState() FanciTheme(fanciColor = theme) { DestinationsNavHost( navGraph = NavGraphs.root, startRoute = MainScreenDestination ) } //是否有音樂播放中 if (isShowAudioMiniIcon) { FanciTheme(fanciColor = theme) { AudioMiniPlayIconScreen( modifier = Modifier .align(Alignment.BottomEnd) .padding(bottom = 120.dp), isPlaying = isAudioPlaying, onClick = { coroutineScope.launch { audioPlayerState.show() } } ) //mini player AudioBottomPlayerScreen( state = audioPlayerState ) } } } } } @Composable fun StatusBarColorEffect() { val statusBarColor = MaterialTheme.colors.primary val systemUiController = rememberSystemUiController() LaunchedEffect(key1 = statusBarColor) { systemUiController.setStatusBarColor( color = statusBarColor, darkIcons = false ) } } //==================== auto login callback ==================== override fun autoLoginFailCallback() { KLog.e(TAG, "autoLoginFailCallback") globalViewModel.loginFail("autoLoginFailCallback") } override fun loginCancel() { KLog.i(TAG, "loginCancel") globalViewModel.loginFail("loginCancel") } override fun loginFailCallback(errorMessage: String) { KLog.e(TAG, "loginFailCallback:$errorMessage") globalViewModel.loginFail(errorMessage) } override fun loginSuccessCallback() { KLog.i(TAG, "loginSuccessCallback") globalViewModel.loginSuccess() globalGroupViewModel.fetchMyGroup() } }
Fanci/app/src/main/java/com/cmoney/kolfanci/ui/main/MainActivity.kt
1054661435
package com.cmoney.kolfanci.ui.main import android.os.Bundle import androidx.activity.ComponentActivity import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner import com.cmoney.fanciapi.fanci.model.ChatMessage import com.cmoney.fancylog.model.data.Clicked import com.cmoney.fancylog.model.data.From import com.cmoney.kolfanci.R import com.cmoney.kolfanci.extension.findActivity import com.cmoney.kolfanci.extension.globalGroupViewModel import com.cmoney.kolfanci.extension.showToast import com.cmoney.kolfanci.model.Constant import com.cmoney.kolfanci.model.analytics.AppUserLogger import com.cmoney.kolfanci.model.viewmodel.NotificationViewModel import com.cmoney.kolfanci.model.viewmodel.PushDataWrapper import com.cmoney.kolfanci.ui.common.BorderButton import com.cmoney.kolfanci.ui.destinations.ChannelScreenDestination import com.cmoney.kolfanci.ui.destinations.GroupApplyScreenDestination import com.cmoney.kolfanci.ui.destinations.GroupSettingScreenDestination import com.cmoney.kolfanci.ui.destinations.PostInfoScreenDestination import com.cmoney.kolfanci.ui.screens.channel.ResetRedDot import com.cmoney.kolfanci.ui.screens.chat.viewmodel.ChatRoomViewModel import com.cmoney.kolfanci.ui.screens.follow.FollowScreen import com.cmoney.kolfanci.ui.screens.follow.viewmodel.FollowViewModel import com.cmoney.kolfanci.ui.screens.notification.NoPermissionDialog import com.cmoney.kolfanci.ui.screens.shared.dialog.DialogScreen import com.cmoney.kolfanci.ui.theme.FanciTheme import com.cmoney.kolfanci.ui.theme.LocalColor import com.ramcosta.composedestinations.annotation.Destination import com.ramcosta.composedestinations.annotation.RootNavGraph import com.ramcosta.composedestinations.navigation.DestinationsNavigator import com.ramcosta.composedestinations.navigation.EmptyDestinationsNavigator import com.ramcosta.composedestinations.result.EmptyResultRecipient import com.ramcosta.composedestinations.result.NavResult import com.ramcosta.composedestinations.result.ResultRecipient import com.socks.library.KLog import org.koin.androidx.compose.koinViewModel @OptIn(ExperimentalMaterialApi::class) @RootNavGraph(start = true) @Destination @Composable fun MainScreen( navigator: DestinationsNavigator, leaveGroupResultRecipient: ResultRecipient<GroupSettingScreenDestination, String>, chatRoomViewModel: ChatRoomViewModel = koinViewModel(), followViewModel: FollowViewModel = koinViewModel(), resetRedDotResultRecipient: ResultRecipient<ChannelScreenDestination, ResetRedDot> ) { val TAG = "MainScreen" val context = LocalContext.current val notificationViewModel = koinViewModel<NotificationViewModel>( viewModelStoreOwner = LocalContext.current as? ComponentActivity ?: checkNotNull( LocalViewModelStoreOwner.current ) ) val globalGroupViewModel = globalGroupViewModel() val activity = LocalContext.current.findActivity() val isLoading by globalGroupViewModel.loading.collectAsState() //我的社團清單 val myGroupList by globalGroupViewModel.myGroupList.collectAsState() //目前選中社團 val currentGroup by globalGroupViewModel.currentGroup.collectAsState() //目前通知中心,未讀數量 val notificationUnReadCount by globalGroupViewModel.notificationUnreadCount.collectAsState() //邀請加入社團 val inviteGroup by notificationViewModel.inviteGroup.collectAsState() //禁止進入頻道彈窗 val channelAlertDialog = remember { mutableStateOf(false) } //目前不屬於此社團 val showNotJoinAlert by notificationViewModel.showNotJoinAlert.collectAsState() //前往申請加入審核畫面 val groupApprovePage by notificationViewModel.groupApprovePage.collectAsState() //打開指定社團 val openGroup by notificationViewModel.openGroup.collectAsState() //沒有權限 彈窗 val showNoPermissionTip by notificationViewModel.showNoPermissionTip.collectAsState() //前往指定 訊息/文章... val pushDataWrapper by notificationViewModel.jumpToChannelDest.collectAsState() LaunchedEffect(pushDataWrapper) { if (Constant.canReadMessage()) { pushDataWrapper?.let { pushDataWrapper -> when (pushDataWrapper) { //設定指定社團並前往指定訊息 is PushDataWrapper.ChannelMessage -> { val group = pushDataWrapper.group globalGroupViewModel.setCurrentGroup(group) navigator.navigate( ChannelScreenDestination( channel = pushDataWrapper.channel, jumpChatMessage = ChatMessage( id = pushDataWrapper.messageId ) ) ) } //設定指定社團並打開貼文 is PushDataWrapper.ChannelPost -> { val group = pushDataWrapper.group globalGroupViewModel.setCurrentGroup(group) navigator.navigate( PostInfoScreenDestination( channel = pushDataWrapper.channel, post = pushDataWrapper.bulletinboardMessage ) ) } } } } else { //禁止進入該頻道,show dialog channelAlertDialog.value = true } notificationViewModel.finishJumpToChannelDest() } // channel權限檢查 結束 val updatePermissionDone by chatRoomViewModel.updatePermissionDone.collectAsState() updatePermissionDone?.let { channel -> if (Constant.canReadMessage()) { //前往頻道 navigator.navigate( ChannelScreenDestination( channel = channel ) ) } else { //禁止進入該頻道,show dialog channelAlertDialog.value = true } notificationViewModel.finishJumpToChannelDest() chatRoomViewModel.afterUpdatePermissionDone() } //Reset redDot resetRedDotResultRecipient.onNavResult { navResult -> when (navResult) { NavResult.Canceled -> { } is NavResult.Value -> { val resetRedDot = navResult.value globalGroupViewModel.resetRedDot(resetRedDot) } } } FollowScreen( modifier = Modifier, group = currentGroup, inviteGroup = inviteGroup, navigator = navigator, myGroupList = myGroupList, notificationUnReadCount = notificationUnReadCount, onGroupItemClick = { globalGroupViewModel.setCurrentGroup(it) }, onRefreshMyGroupList = { isSilent -> globalGroupViewModel.fetchMyGroup(isSilent = isSilent) }, isLoading = isLoading, onDismissInvite = { notificationViewModel.openedInviteGroup() }, onChannelClick = { chatRoomViewModel.fetchChannelPermission(it) activity.intent?.replaceExtras(Bundle()) }, onChangeGroup = { globalGroupViewModel.setCurrentGroup(it) } ) leaveGroupResultRecipient.onNavResult { navResult -> when (navResult) { NavResult.Canceled -> { } is NavResult.Value -> { val leaveGroupId = navResult.value if (leaveGroupId.isNotBlank()) { context.showToast(context.getString(R.string.leaving_group)) globalGroupViewModel.leaveGroup(id = leaveGroupId) } } } } if (channelAlertDialog.value) { DialogScreen( title = "不具有此頻道的權限", subTitle = "這是個上了鎖的頻道,你目前沒有權限能夠進入喔!", onDismiss = { channelAlertDialog.value = false } ) { BorderButton( modifier = Modifier .fillMaxWidth() .height(50.dp), text = "返回", borderColor = LocalColor.current.text.default_50, textColor = LocalColor.current.text.default_100 ) { run { channelAlertDialog.value = false } } } } if (showNotJoinAlert) { DialogScreen( title = stringResource(id = R.string.not_belong_group), subTitle = stringResource(id = R.string.rejoin_group), onDismiss = { channelAlertDialog.value = false } ) { BorderButton( modifier = Modifier .fillMaxWidth() .height(50.dp), text = stringResource(id = R.string.back), borderColor = LocalColor.current.text.default_50, textColor = LocalColor.current.text.default_100 ) { notificationViewModel.dismissNotJoinAlert() } } } var hasShown by rememberSaveable { mutableStateOf(false) } LaunchedEffect(key1 = Unit) { // 刷新社團資訊 globalGroupViewModel.refreshGroupAndNotificationCount() // 檢查推播權限 if (hasShown) { followViewModel.checkNeedNotifyAllowNotificationPermission() } else { hasShown = true } } //打開社團 審核畫面 groupApprovePage?.let { group -> navigator.navigate( GroupApplyScreenDestination( group = group ) ) notificationViewModel.afterOpenApprovePage() } //打開指定社團 openGroup?.let { group -> globalGroupViewModel.setCurrentGroup(group) notificationViewModel.afterOpenGroup() } //沒有權限 彈窗 if (showNoPermissionTip) { NoPermissionDialog( onDismiss = { AppUserLogger.getInstance().log(Clicked.CannotUse, From.Notification) notificationViewModel.afterOpenApprovePage() }, onClick = { AppUserLogger.getInstance().log(Clicked.CannotUse, From.Notification) notificationViewModel.afterOpenApprovePage() } ) } } @Preview(showBackground = true) @Composable fun HomeScreenPreview() { FanciTheme { MainScreen( navigator = EmptyDestinationsNavigator, leaveGroupResultRecipient = EmptyResultRecipient(), resetRedDotResultRecipient = EmptyResultRecipient() ) } }
Fanci/app/src/main/java/com/cmoney/kolfanci/ui/main/MainScreen.kt
4210152277
package com.cmoney.kolfanci.ui import android.content.Context import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import com.cmoney.kolfanci.BuildConfig import com.cmoney.kolfanci.R import com.cmoney.kolfanci.extension.goAppStore import com.cmoney.kolfanci.extension.startActivity import com.cmoney.kolfanci.model.notification.NotificationHelper import com.cmoney.kolfanci.model.notification.Payload import com.cmoney.kolfanci.model.usecase.DynamicLinkUseCase import com.cmoney.kolfanci.ui.main.MainActivity import com.cmoney.remoteconfig_library.model.config.AppStatus import com.cmoney.xlogin.XLoginHelper import com.google.firebase.messaging.FirebaseMessaging import com.socks.library.KLog import kotlinx.coroutines.delay import kotlinx.coroutines.launch import org.koin.android.ext.android.inject class SplashActivity : AppCompatActivity() { private val TAG = SplashActivity::class.java.simpleName private val notificationHelper by inject<NotificationHelper>() private val dynamicLinksUseCase by inject<DynamicLinkUseCase>() private val viewModel by inject<SplashViewModel>() companion object { fun createIntent(context: Context, payload: Payload): Intent { return Intent(context, SplashActivity::class.java) .putExtra(EXTRA_PUSH_NOTIFICATION_PAYLOAD, payload) } private const val EXTRA_PUSH_NOTIFICATION_PAYLOAD = "push_notification_payload" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) initObserve() showDebugInfo() } private fun initObserve() { viewModel.appConfig.observe(this) { appConfig -> when (appConfig.appStatus) { is AppStatus.SuggestUpdate -> { AlertDialog.Builder(this) .setCancelable(false) .setTitle(getString(R.string.text_remote_config_update_title)) .setMessage(appConfig.appStatus.announcement) .setPositiveButton(getString(R.string.update_immediately)) { _, _ -> [email protected]() } .setNegativeButton(getString(R.string.later)) { _, _ -> startMainActivity() } .create() .show() } is AppStatus.NeedUpdate -> { AlertDialog.Builder(this) .setCancelable(false) .setTitle(getString(R.string.text_remote_config_update_title)) .setMessage(appConfig.appStatus.announcement) .setPositiveButton(getString(R.string.update_immediately)) { _, _ -> [email protected]() } .create() .show() } is AppStatus.CanUse -> { startMainActivity() } is AppStatus.IsInMaintain -> { AlertDialog.Builder(this) .setCancelable(false) .setTitle(getString(R.string.text_remote_config_under_maintain_title)) .setMessage(appConfig.appStatus.announcement) .setPositiveButton(getString(R.string.text_remote_config_under_maintain_confirm_button)) { _, _ -> finish() } .create() .show() } is AppStatus.IsUnderReview -> { AlertDialog.Builder(this) .setCancelable(false) .setTitle(getString(R.string.text_remote_config_under_review_title)) .setMessage(getString(R.string.text_remote_config_under_review_message)) .setPositiveButton(getString(R.string.confirm)) { _, _ -> startMainActivity() } .create() .show() } } } } private fun startMainActivity() { lifecycleScope.launch { delay(2000) val backgroundPayload = intent.getParcelableExtra<Payload>(EXTRA_PUSH_NOTIFICATION_PAYLOAD) ?: notificationHelper.getPayloadFromBackground(intent) if (backgroundPayload != null) { MainActivity.start(this@SplashActivity, backgroundPayload) finish() return@launch } dynamicLinksUseCase.getDynamicsLinksParam(intent)?.apply { MainActivity.start(this@SplashActivity, this) clearIntentExtra() } ?: kotlin.run { startActivity<MainActivity>() } finish() } } private fun clearIntentExtra() { intent.replaceExtras(Bundle()) intent.action = "" intent.data = null intent.flags = 0 } private fun showDebugInfo() { if (BuildConfig.DEBUG) { FirebaseMessaging.getInstance().token.addOnCompleteListener { val token = it.result KLog.i(TAG, "push token:$token") } KLog.i(TAG, "memberId:" + XLoginHelper.memberPk) } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/ui/SplashActivity.kt
428678050
package com.cmoney.kolfanci.repository import com.cmoney.kolfanci.model.notification.NotificationHistory import com.cmoney.kolfanci.repository.request.NotificationClick import com.cmoney.kolfanci.repository.request.NotificationSeen import retrofit2.Response import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.PUT import retrofit2.http.Url interface NotificationService { @GET("notification/History") suspend fun getNotificationHistory(): Response<NotificationHistory> @GET suspend fun getNextPageNotificationHistory( @Url url: String ): Response<NotificationHistory> @PUT("notification/History/clicked") suspend fun setNotificationHistoryClick( @Body notificationClick: NotificationClick ): Response<Unit> @GET("notification/History/unreadCount") suspend fun getNotificationUnreadCount(): Response<Long> @PUT("notification/History/seen") suspend fun setNotificationSeen( @Body notificationSeen: NotificationSeen ): Response<Unit> }
Fanci/app/src/main/java/com/cmoney/kolfanci/repository/NotificationService.kt
3662405879
package com.cmoney.kolfanci.repository import android.net.Uri import com.cmoney.kolfanci.model.notification.NotificationHistory import com.cmoney.kolfanci.repository.request.NotificationClick import com.cmoney.kolfanci.repository.response.FileUploadResponse import com.cmoney.kolfanci.repository.response.FileUploadStatusResponse interface Network { /** * 取得 推播歷史訊息 */ suspend fun getNotificationHistory(): Result<NotificationHistory> /** * 取得 下一頁 推播歷史訊息 */ suspend fun getNextPageNotificationHistory(nextPageUrl: String): Result<NotificationHistory> /** * 點擊 通知中心 item */ suspend fun setNotificationHistoryClick(notificationClick: NotificationClick): Result<Unit> /** * 取得 通知中心 未讀數量 */ suspend fun getNotificationUnreadCount(): Result<Long> /** * 通知中心 已讀 */ suspend fun setNotificationSeen(): Result<Unit> /** * 上傳檔案 step 1. */ suspend fun uploadFile(uri: Uri): Result<FileUploadResponse> /** * 上傳檔案 狀態檢查, 確認有上傳 完成 */ suspend fun checkUploadFileStatus(externalId: String, fileType: String): Result<FileUploadStatusResponse> /** * 取得 網址內容 */ suspend fun getContent(url: String): Result<String> }
Fanci/app/src/main/java/com/cmoney/kolfanci/repository/Network.kt
2627177160
package com.cmoney.kolfanci.repository.response data class FileUploadResponse( val externalId: String )
Fanci/app/src/main/java/com/cmoney/kolfanci/repository/response/FileUploadResponse.kt
320873017
package com.cmoney.kolfanci.repository.response data class FileUploadStatusResponse( val status: String )
Fanci/app/src/main/java/com/cmoney/kolfanci/repository/response/FileUploadStatusResponse.kt
178302951
package com.cmoney.kolfanci.repository import com.cmoney.kolfanci.repository.response.FileUploadResponse import com.cmoney.kolfanci.repository.response.FileUploadStatusResponse import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Multipart import retrofit2.http.POST import retrofit2.http.Part import retrofit2.http.Path import retrofit2.http.Url interface CentralFileService { // @Multipart // @POST("centralfileservice/files") // suspend fun uploadFile( // @Part("File") file: MultipartBody.Part, // @Part("type") type: RequestBody, // @Part("FileType") fileType: MultipartBody.Part // ): Response<FileUploadResponse> @Multipart @POST("files") suspend fun uploadFile( @Part file: MultipartBody.Part, @Part("FileType") fileType: RequestBody ): Response<FileUploadResponse> @GET("files/{fileType}/{externalId}/status") suspend fun checkUploadFileStatus( @Path("fileType") fileType: String, @Path("externalId") externalId: String ): Response<FileUploadStatusResponse> @GET suspend fun getContent( @Url url: String ): Response<String> }
Fanci/app/src/main/java/com/cmoney/kolfanci/repository/CentralFileService.kt
4023054759
package com.cmoney.kolfanci.repository.request data class NotificationSeen( val appId: Int = 176 )
Fanci/app/src/main/java/com/cmoney/kolfanci/repository/request/NotificationSeen.kt
2874118689
package com.cmoney.kolfanci.repository.request data class NotificationClick( val appId: Int = 176, val notificationIds: List<String> )
Fanci/app/src/main/java/com/cmoney/kolfanci/repository/request/NotificationClick.kt
1018709897
package com.cmoney.kolfanci.repository import android.app.Application import android.net.Uri import com.cmoney.kolfanci.extension.checkResponseBody import com.cmoney.kolfanci.extension.getMimeType import com.cmoney.kolfanci.extension.getUploadFileType import com.cmoney.kolfanci.extension.uriToFile import com.cmoney.kolfanci.model.notification.NotificationHistory import com.cmoney.kolfanci.repository.request.NotificationClick import com.cmoney.kolfanci.repository.request.NotificationSeen import com.cmoney.kolfanci.repository.response.FileUploadResponse import com.cmoney.kolfanci.repository.response.FileUploadStatusResponse import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import okhttp3.MediaType.Companion.toMediaType import okhttp3.MultipartBody import okhttp3.RequestBody.Companion.asRequestBody import okhttp3.RequestBody.Companion.toRequestBody class NetworkImpl( private val context: Application, private val notificationService: NotificationService, private val centralFileService: CentralFileService, private val dispatcher: CoroutineDispatcher = Dispatchers.IO ) : Network { override suspend fun getNotificationHistory(): Result<NotificationHistory> = withContext(dispatcher) { kotlin.runCatching { notificationService.getNotificationHistory().checkResponseBody() } } override suspend fun getNextPageNotificationHistory(nextPageUrl: String): Result<NotificationHistory> = withContext(dispatcher) { kotlin.runCatching { notificationService.getNextPageNotificationHistory(nextPageUrl).checkResponseBody() } } override suspend fun setNotificationHistoryClick(notificationClick: NotificationClick): Result<Unit> = withContext(dispatcher) { kotlin.runCatching { notificationService.setNotificationHistoryClick(notificationClick = notificationClick) .checkResponseBody() } } override suspend fun getNotificationUnreadCount(): Result<Long> = withContext(dispatcher) { kotlin.runCatching { notificationService.getNotificationUnreadCount().checkResponseBody() } } override suspend fun setNotificationSeen(): Result<Unit> = withContext(dispatcher) { kotlin.runCatching { notificationService.setNotificationSeen(NotificationSeen()).checkResponseBody() } } override suspend fun uploadFile(uri: Uri): Result<FileUploadResponse> = withContext(dispatcher) { kotlin.runCatching { val mimeType = uri.getMimeType(context) val file = uri.uriToFile(context) val requestBody = file.asRequestBody( contentType = mimeType?.toMediaType() ) val filePart = MultipartBody.Part.createFormData("File", file.name, requestBody) val fileType = uri.getUploadFileType(context) centralFileService.uploadFile( file = filePart, fileType = fileType.toRequestBody() ).checkResponseBody() } } override suspend fun checkUploadFileStatus( externalId: String, fileType: String ): Result<FileUploadStatusResponse> = withContext(dispatcher) { kotlin.runCatching { centralFileService.checkUploadFileStatus( fileType = fileType, externalId = externalId ).checkResponseBody() } } override suspend fun getContent(url: String): Result<String> = withContext(dispatcher) { kotlin.runCatching { centralFileService.getContent(url).checkResponseBody() } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/repository/NetworkImpl.kt
3814886072
package com.cmoney.kolfanci.repository.interceptor import android.os.Build import com.cmoney.kolfanci.BuildConfig import com.cmoney.xlogin.XLoginHelper import okhttp3.Headers import okhttp3.Interceptor import okhttp3.Response class AddBearerTokenInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val builder = chain.request().newBuilder() val host = chain.request().url.host val bearerToken = XLoginHelper.accessToken val headers = Headers.Builder() .addUnsafeNonAscii("Authorization", "Bearer $bearerToken") .addUnsafeNonAscii("os", "android") .addUnsafeNonAscii("os-version", Build.VERSION.SDK_INT.toString()) .addUnsafeNonAscii("app-version", BuildConfig.VERSION_NAME) builder.headers(headers.build()) return chain.proceed(builder.build()) } }
Fanci/app/src/main/java/com/cmoney/kolfanci/repository/interceptor/AddBearerTokenInterceptor.kt
2128197252
package com.cmoney.kolfanci import android.app.Application import com.cmoney.application_user_behavior.AnalyticsAgent import com.cmoney.application_user_behavior.di.analyticsModule import com.cmoney.backend2.base.model.manager.GlobalBackend2Manager import com.cmoney.backend2.base.model.setting.Platform import com.cmoney.backend2.di.backendServicesModule import com.cmoney.crypto.di.CryptoHelper import com.cmoney.data_logdatarecorder.recorder.LogDataRecorder import com.cmoney.kolfanci.di.appModule import com.cmoney.kolfanci.di.networkBaseModule import com.cmoney.kolfanci.di.useCaseModule import com.cmoney.kolfanci.di.viewModule import com.cmoney.loginlibrary.di.loginModule import com.cmoney.loginlibrary.di.loginServiceModule import com.cmoney.loginlibrary.di.loginSharedPreferencesModule import com.cmoney.loginlibrary.di.memberProfileCacheModule import com.cmoney.loginlibrary.di.visitBindRepositoryModule import com.cmoney.loginlibrary.di.visitBindViewModelModule import com.cmoney.member.application.di.CMoneyMemberServiceLocator import com.cmoney.remoteconfig_library.IRemoteConfig import com.google.firebase.FirebaseApp import org.koin.android.ext.android.get import org.koin.android.ext.android.getKoin import org.koin.android.ext.koin.androidContext import org.koin.core.context.loadKoinModules import org.koin.core.context.startKoin class MyApplication : Application() { companion object { lateinit var instance: MyApplication private set } override fun onCreate() { super.onCreate() instance = this CryptoHelper.registerAead() startKoin { androidContext(this@MyApplication) loadKoinModules( listOf( // 此為登入模組需要的網路或快取定義 memberProfileCacheModule, // 登入模組內的DI loginModule, // 華為/Google的定義 loginServiceModule, // 訪客使用的API定義 visitBindRepositoryModule, visitBindViewModelModule, // 登入提供的SharedPreference定義,需要位於 backendServicesModule 下 loginSharedPreferencesModule, // backend2 backendServicesModule, viewModule, useCaseModule, appModule, networkBaseModule, analyticsModule ) ) } FirebaseApp.initializeApp(this) // 設定Backend2 val remoteConfig = getKoin().get<IRemoteConfig>() val cmServer = remoteConfig.getApiConfig().serverUrl.ifBlank { BuildConfig.CM_SERVER_URL } val globalBackend2Manager = getKoin().get<GlobalBackend2Manager>().apply { setGlobalDomainUrl(cmServer) setPlatform(Platform.Android) setClientId(getString(R.string.app_client_id)) setAppId(resources.getInteger(R.integer.app_id)) } // 根據需求設定是否紀錄API LogDataRecorder.initialization(this) { isEnable = false appId = resources.getInteger(R.integer.app_id) platform = com.cmoney.domain_logdatarecorder.data.information.Platform.Android } CMoneyMemberServiceLocator.initialGoogle( context = this, identityWeb = get(), profileWeb = get(), commonWeb = get(), notificationWeb = get(), globalBackend2Manager = globalBackend2Manager ) AnalyticsAgent.initialization(context = this) { platform = com.cmoney.domain_user_behavior.data.information.Platform.Android appId = resources.getInteger(R.integer.app_id) } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/MyApplication.kt
866884123
package com.cmoney.kolfanci.di import android.content.ComponentName import com.cmoney.kolfanci.BuildConfig import com.cmoney.kolfanci.R import com.cmoney.kolfanci.model.notification.NotificationHelper import com.cmoney.kolfanci.model.persistence.SettingsDataStore import com.cmoney.kolfanci.model.persistence.dataStore import com.cmoney.kolfanci.service.media.MusicMediaService import com.cmoney.kolfanci.service.media.MusicServiceConnection import com.cmoney.kolfanci.service.media.RecorderAndPlayer import com.cmoney.kolfanci.service.media.RecorderAndPlayerImpl import com.cmoney.kolfanci.service.media.RecorderAndPlayerImpl2 import com.cmoney.remoteconfig_library.IRemoteConfig import com.cmoney.remoteconfig_library.RemoteConfigImpl import com.google.firebase.remoteconfig.FirebaseRemoteConfig import com.mixpanel.android.mpmetrics.MixpanelAPI import org.koin.android.ext.koin.androidApplication import org.koin.android.ext.koin.androidContext import org.koin.dsl.module val appModule = module { single { SettingsDataStore( androidContext().dataStore ) } single { NotificationHelper(androidApplication(), get(APP_GSON)) } single { MixpanelAPI.getInstance( androidContext(), if (BuildConfig.DEBUG) "fakeMixpanelToken" else androidContext().getString(R.string.mixpanel_token) ) } single<IRemoteConfig> { RemoteConfigImpl( context = androidApplication(), firebaseRemoteConfig = FirebaseRemoteConfig.getInstance() ) } single { MusicServiceConnection.getInstance( androidContext(), ComponentName(androidContext(), MusicMediaService::class.java) ) } single<RecorderAndPlayer> { RecorderAndPlayerImpl( context = androidApplication() ) } factory<RecorderAndPlayer> { RecorderAndPlayerImpl2( context = androidApplication(), musicServiceConnection = get() ) } }
Fanci/app/src/main/java/com/cmoney/kolfanci/di/AppModule.kt
3910005083
package com.cmoney.kolfanci.di import com.cmoney.kolfanci.model.viewmodel.AttachmentViewModel import com.cmoney.kolfanci.model.viewmodel.GroupViewModel import com.cmoney.kolfanci.model.viewmodel.NotificationViewModel import com.cmoney.kolfanci.model.viewmodel.UserViewModel import com.cmoney.kolfanci.ui.SplashViewModel import com.cmoney.kolfanci.ui.main.MainViewModel import com.cmoney.kolfanci.ui.screens.channel.ChannelViewModel import com.cmoney.kolfanci.ui.screens.chat.message.viewmodel.MessageViewModel import com.cmoney.kolfanci.ui.screens.chat.viewmodel.ChatRoomViewModel import com.cmoney.kolfanci.ui.screens.follow.viewmodel.FollowViewModel import com.cmoney.kolfanci.ui.screens.group.create.viewmodel.CreateGroupViewModel import com.cmoney.kolfanci.ui.screens.group.search.apply.viewmodel.ApplyForGroupViewModel import com.cmoney.kolfanci.ui.screens.group.search.viewmodel.DiscoverViewModel import com.cmoney.kolfanci.ui.screens.group.setting.apply.viewmodel.GroupApplyViewModel import com.cmoney.kolfanci.ui.screens.group.setting.ban.viewmodel.BanListViewModel import com.cmoney.kolfanci.ui.screens.group.setting.group.channel.viewmodel.ChannelSettingViewModel import com.cmoney.kolfanci.ui.screens.group.setting.group.groupsetting.avatar.GroupSettingImageViewModel import com.cmoney.kolfanci.ui.screens.group.setting.group.notification.NotificationSettingViewModel import com.cmoney.kolfanci.ui.screens.group.setting.group.openness.viewmodel.GroupOpennessViewModel import com.cmoney.kolfanci.ui.screens.group.setting.member.role.viewmodel.RoleManageViewModel import com.cmoney.kolfanci.ui.screens.group.setting.report.viewmodel.GroupReportViewModel import com.cmoney.kolfanci.ui.screens.group.setting.viewmodel.GroupSettingViewModel import com.cmoney.kolfanci.ui.screens.group.setting.vip.viewmodel.VipManagerViewModel import com.cmoney.kolfanci.ui.screens.media.audio.AudioViewModel import com.cmoney.kolfanci.ui.screens.media.audio.RecordingViewModel import com.cmoney.kolfanci.ui.screens.media.txt.TextPreviewViewModel import com.cmoney.kolfanci.ui.screens.my.MyScreenViewModel import com.cmoney.kolfanci.ui.screens.notification.NotificationCenterViewModel import com.cmoney.kolfanci.ui.screens.post.edit.viewmodel.EditPostViewModel import com.cmoney.kolfanci.ui.screens.post.info.viewmodel.PostInfoViewModel import com.cmoney.kolfanci.ui.screens.post.viewmodel.PostViewModel import com.cmoney.kolfanci.ui.screens.search.viewmodel.SearchViewModel import com.cmoney.kolfanci.ui.screens.shared.bottomSheet.mediaPicker.MediaPickerBottomSheetViewModel import com.cmoney.kolfanci.ui.screens.shared.member.viewmodel.MemberViewModel import com.cmoney.kolfanci.ui.screens.shared.member.viewmodel.RoleViewModel import com.cmoney.kolfanci.ui.screens.shared.vip.viewmodel.VipPlanViewModel import com.cmoney.kolfanci.ui.screens.vote.viewmodel.VoteViewModel import org.koin.android.ext.koin.androidApplication import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val viewModule = module { viewModel { SplashViewModel(get(), get()) } viewModel { MainViewModel(get(), get(), get(), get()) } viewModel { FollowViewModel( groupUseCase = get(), notificationUseCase = get(), dataStore = get(), groupApplyUseCase = get() ) } viewModel { ChatRoomViewModel(get(), get(), get(), get()) } viewModel { MessageViewModel( androidApplication(), get(), get(), get() ) } viewModel { DiscoverViewModel(get()) } viewModel { GroupSettingViewModel( groupUseCase = get(), themeUseCase = get(), groupApplyUseCase = get(), notificationUseCase = get() ) } viewModel { ChannelSettingViewModel(get(), get()) } viewModel { RoleManageViewModel(get(), get()) } viewModel { MemberViewModel( context = androidApplication(), get(), get(), get()) } viewModel { BanListViewModel(get()) } viewModel { GroupApplyViewModel(get()) } viewModel { params -> GroupOpennessViewModel( group = params.get(), get() ) } viewModel { CreateGroupViewModel(androidApplication(), get(), get(), get(), settingsDataStore = get()) } viewModel { ApplyForGroupViewModel(get(), get()) } viewModel { params -> GroupReportViewModel( get(), reportList = params.get(), group = params.get(), banUseCase = get(), chatRoomUseCase = get() ) } viewModel { GroupSettingImageViewModel() } viewModel { RoleViewModel(get(), get(), get()) } viewModel { UserViewModel(androidApplication()) } viewModel { params -> PostViewModel(get(), params.get(), chatRoomUseCase = get(), postPollUseCase = get()) } viewModel { params -> EditPostViewModel( androidApplication(), get(), get(), params.get(), get() ) } viewModel { ChannelViewModel( notificationUseCase = get() ) } viewModel { params -> PostInfoViewModel( androidApplication(), get(), get(), params.get(), params.get(), postPollUseCase = get() ) } viewModel { GroupViewModel( themeUseCase = get(), groupUseCase = get(), channelUseCase = get(), permissionUseCase = get(), orderUseCase = get(), groupApplyUseCase = get(), notificationUseCase = get() ) } viewModel { params -> VipManagerViewModel( group = params.get(), vipManagerUseCase = get() ) } viewModel { VipPlanViewModel( vipManagerUseCase = get() ) } viewModel { MyScreenViewModel(androidApplication(), get()) } viewModel { SearchViewModel(get()) } viewModel { NotificationCenterViewModel(get(), get()) } viewModel { NotificationSettingViewModel(androidApplication(), get()) } viewModel { NotificationViewModel(get(), get(), get(), get()) } viewModel { MediaPickerBottomSheetViewModel( context = androidApplication() ) } viewModel { params -> AudioViewModel( context = androidApplication(), musicServiceConnection = get(), uri = params.get() ) } viewModel { AttachmentViewModel( context = androidApplication(), attachmentUseCase = get(), uploadImageUseCase = get(), voteUseCase = get() ) } viewModel { TextPreviewViewModel( attachmentUseCase = get() ) } viewModel { VoteViewModel( context = androidApplication(), voteUseCase = get(), groupUseCase = get() ) } viewModel { RecordingViewModel(get()) } }
Fanci/app/src/main/java/com/cmoney/kolfanci/di/ViewModule.kt
1137814680
package com.cmoney.kolfanci.di import com.cmoney.kolfanci.model.usecase.AttachmentUseCase import com.cmoney.kolfanci.model.usecase.BanUseCase import com.cmoney.kolfanci.model.usecase.ChannelUseCase import com.cmoney.kolfanci.model.usecase.ChatRoomPollUseCase import com.cmoney.kolfanci.model.usecase.ChatRoomUseCase import com.cmoney.kolfanci.model.usecase.DynamicLinkUseCase import com.cmoney.kolfanci.model.usecase.GroupApplyUseCase import com.cmoney.kolfanci.model.usecase.GroupUseCase import com.cmoney.kolfanci.model.usecase.NotificationUseCase import com.cmoney.kolfanci.model.usecase.OrderUseCase import com.cmoney.kolfanci.model.usecase.PermissionUseCase import com.cmoney.kolfanci.model.usecase.PostPollUseCase import com.cmoney.kolfanci.model.usecase.PostUseCase import com.cmoney.kolfanci.model.usecase.RelationUseCase import com.cmoney.kolfanci.model.usecase.SearchUseCase import com.cmoney.kolfanci.model.usecase.ThemeUseCase import com.cmoney.kolfanci.model.usecase.UploadImageUseCase import com.cmoney.kolfanci.model.usecase.UserUseCase import com.cmoney.kolfanci.model.usecase.VipManagerUseCase import com.cmoney.kolfanci.model.usecase.VoteUseCase import org.koin.android.ext.koin.androidApplication import org.koin.dsl.module val useCaseModule = module { factory { ChatRoomUseCase( context = androidApplication(), chatRoomApi = get(), messageApi = get(), userReport = get() ) } factory { GroupUseCase( androidApplication(), get(), get(), get(), get(), get(), get(), get(), get() ) } factory { UserUseCase(get()) } factory { ChatRoomPollUseCase(get()) } factory { ThemeUseCase(get(), get()) } factory { ChannelUseCase(get(), get(), get(), get(), get()) } factory { BanUseCase(get()) } factory { GroupApplyUseCase(get(), get()) } factory { RelationUseCase(get()) } factory { PermissionUseCase(get(), get()) } factory { OrderUseCase(get()) } factory { PostUseCase( context = androidApplication(), get() ) } factory { DynamicLinkUseCase(androidApplication(), get()) } factory { VipManagerUseCase(get(), get(), get(), get()) } factory { SearchUseCase(get(), get()) } factory { UploadImageUseCase(androidApplication(), get()) } factory { NotificationUseCase( context = androidApplication(), network = get(), settingsDataStore = get(), chatRoomApi = get(), bulletinBoardApi = get(), pushNotificationApi = get() ) } factory { AttachmentUseCase( context = androidApplication(), network = get() ) } factory { VoteUseCase( votingApi = get() ) } factory { PostPollUseCase( bulletinBoardApi = get(), messageApi = get() ) } }
Fanci/app/src/main/java/com/cmoney/kolfanci/di/UseCaseModule.kt
487094425
package com.cmoney.kolfanci.di import android.app.Application import com.chuckerteam.chucker.api.ChuckerCollector import com.chuckerteam.chucker.api.ChuckerInterceptor import com.cmoney.fanciapi.fanci.api.BanApi import com.cmoney.fanciapi.fanci.api.BuffInformationApi import com.cmoney.fanciapi.fanci.api.BulletinBoardApi import com.cmoney.fanciapi.fanci.api.CategoryApi import com.cmoney.fanciapi.fanci.api.ChannelApi import com.cmoney.fanciapi.fanci.api.ChannelTabApi import com.cmoney.fanciapi.fanci.api.ChatRoomApi import com.cmoney.fanciapi.fanci.api.DefaultImageApi import com.cmoney.fanciapi.fanci.api.GroupApi import com.cmoney.fanciapi.fanci.api.GroupApplyApi import com.cmoney.fanciapi.fanci.api.GroupMemberApi import com.cmoney.fanciapi.fanci.api.GroupRequirementApi import com.cmoney.fanciapi.fanci.api.MessageApi import com.cmoney.fanciapi.fanci.api.OrderApi import com.cmoney.fanciapi.fanci.api.PermissionApi import com.cmoney.fanciapi.fanci.api.PushNotificationApi import com.cmoney.fanciapi.fanci.api.RelationApi import com.cmoney.fanciapi.fanci.api.RoleUserApi import com.cmoney.fanciapi.fanci.api.ThemeColorApi import com.cmoney.fanciapi.fanci.api.UserApi import com.cmoney.fanciapi.fanci.api.UserReportApi import com.cmoney.fanciapi.fanci.api.VipApi import com.cmoney.fanciapi.fanci.api.VotingApi import com.cmoney.fanciapi.infrastructure.ApiClient import com.cmoney.kolfanci.BuildConfig import com.cmoney.kolfanci.model.remoteconfig.BaseDomainKey import com.cmoney.kolfanci.repository.CentralFileService import com.cmoney.kolfanci.repository.Network import com.cmoney.kolfanci.repository.NetworkImpl import com.cmoney.kolfanci.repository.NotificationService import com.cmoney.kolfanci.repository.interceptor.AddBearerTokenInterceptor import com.cmoney.remoteconfig_library.extension.getKeyValue import com.google.firebase.remoteconfig.FirebaseRemoteConfig import com.google.gson.GsonBuilder import okhttp3.Cache import okhttp3.ConnectionSpec import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.koin.android.ext.koin.androidApplication import org.koin.core.qualifier.named import org.koin.dsl.module import java.util.concurrent.TimeUnit val APP_GSON = named("app_gson") val CM_COMMON_CLIENT = named("notification") val networkBaseModule = module { single(APP_GSON) { GsonBuilder() .serializeNulls() .setPrettyPrinting() .setLenient() .create() } single { ApiClient( baseUrl = getDomain(), okHttpClientBuilder = createOkHttpClient(androidApplication()).newBuilder(), ).apply { addAuthorization("Bearer", AddBearerTokenInterceptor()) } } single(CM_COMMON_CLIENT) { ApiClient( baseUrl = BuildConfig.CM_COMMON_URL, okHttpClientBuilder = createOkHttpClient(androidApplication()).newBuilder(), ).apply { addAuthorization("Bearer", AddBearerTokenInterceptor()) } } single { get<ApiClient>(CM_COMMON_CLIENT).createService(NotificationService::class.java) } single { get<ApiClient>(CM_COMMON_CLIENT).createService(CentralFileService::class.java) } single<Network> { NetworkImpl( context = androidApplication(), notificationService = get(), centralFileService = get() ) } single { get<ApiClient>().createService(GroupApi::class.java) } single { get<ApiClient>().createService(GroupMemberApi::class.java) } single { get<ApiClient>().createService(UserApi::class.java) } single { get<ApiClient>().createService(ChatRoomApi::class.java) } single { get<ApiClient>().createService(MessageApi::class.java) } single { get<ApiClient>().createService(DefaultImageApi::class.java) } single { get<ApiClient>().createService(ThemeColorApi::class.java) } single { get<ApiClient>().createService(CategoryApi::class.java) } single { get<ApiClient>().createService(ChannelApi::class.java) } single { get<ApiClient>().createService(PermissionApi::class.java) } single { get<ApiClient>().createService(RoleUserApi::class.java) } single { get<ApiClient>().createService(BanApi::class.java) } single { get<ApiClient>().createService(GroupApplyApi::class.java) } single { get<ApiClient>().createService(GroupRequirementApi::class.java) } single { get<ApiClient>().createService(RelationApi::class.java) } single { get<ApiClient>().createService(UserReportApi::class.java) } single { get<ApiClient>().createService(OrderApi::class.java) } single { get<ApiClient>().createService(BuffInformationApi::class.java) } single { get<ApiClient>().createService(ChannelTabApi::class.java) } single { get<ApiClient>().createService(BulletinBoardApi::class.java) } single { get<ApiClient>().createService(VipApi::class.java) } single { get<ApiClient>().createService(PushNotificationApi::class.java) } single { get<ApiClient>().createService(VotingApi::class.java) } } private fun getDomain(): String { val baseDomain = FirebaseRemoteConfig.getInstance().getKeyValue(BaseDomainKey).ifBlank { BuildConfig.FANCI_SERVER_URL } return baseDomain } private fun createOkHttpClient( context: Application, ): OkHttpClient { val cacheSize = 10 * 1024 * 1024L val cache = Cache(context.cacheDir, cacheSize) return OkHttpClient.Builder() .connectionSpecs(listOf(ConnectionSpec.COMPATIBLE_TLS, ConnectionSpec.CLEARTEXT)) .apply { if (BuildConfig.DEBUG) { val interceptor = HttpLoggingInterceptor() interceptor.level = HttpLoggingInterceptor.Level.BODY addInterceptor(interceptor) val chuckerInterceptor = ChuckerInterceptor.Builder(context) .collector(ChuckerCollector(context)) .maxContentLength(250000L) .redactHeaders(emptySet()) .alwaysReadResponseBody(false) .build() addInterceptor(chuckerInterceptor) } connectTimeout(30L, TimeUnit.SECONDS) callTimeout(30L, TimeUnit.SECONDS) readTimeout(30L, TimeUnit.SECONDS) writeTimeout(30L, TimeUnit.SECONDS) cache(cache) } .build() }
Fanci/app/src/main/java/com/cmoney/kolfanci/di/NetworkBaseModule.kt
2064860884
package com.cmoney.kolfanci.extension import androidx.activity.ComponentActivity import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner import com.cmoney.kolfanci.model.viewmodel.GroupViewModel import org.koin.androidx.compose.koinViewModel /** * 取得共用的 GroupViewModel * * @return ViewModelStoreOwner 為 Activity 的 GroupViewModel */ @Composable fun globalGroupViewModel(): GroupViewModel { val context = LocalContext.current return koinViewModel( viewModelStoreOwner = (context as? ComponentActivity) ?: checkNotNull(LocalViewModelStoreOwner.current) ) }
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/KoinExt.kt
2802800247
package com.cmoney.kolfanci.extension import com.cmoney.fanciapi.fanci.model.BulletinboardMessage import com.cmoney.fanciapi.fanci.model.ChatMessage import com.cmoney.fanciapi.fanci.model.User /** * 是否為自己的訊息 */ fun ChatMessage.isMyPostMessage(myInfo: User?): Boolean = author?.id == myInfo?.id fun ChatMessage.toBulletinboardMessage(): BulletinboardMessage = BulletinboardMessage( author = author, content = content, emojiCount = emojiCount, id = id, isDeleted = isDeleted, createUnixTime = createUnixTime, updateUnixTime = updateUnixTime, serialNumber = serialNumber, messageReaction = messageReaction, deleteStatus = deleteStatus, deleteFrom = deleteFrom, commentCount = commentCount, votings = votings ) /** * 取得 置頂訊息 顯示內容 */ fun ChatMessage.getPinMessage(): String { val content = this.content val text = content?.text.orEmpty() val mediaContent = mutableListOf<String>() content?.medias?.forEach { media -> val content = media.getDisplayType() mediaContent.add(content) } val mediaString = mediaContent.joinToString(separator = " ") return text + mediaString }
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/ChatMessageExt.kt
3822716378
package com.cmoney.kolfanci.extension import com.cmoney.fanciapi.fanci.model.IReplyVoting import com.cmoney.fanciapi.fanci.model.IVotingOptionStatistic import com.cmoney.fanciapi.fanci.model.Voting import com.cmoney.kolfanci.model.vote.VoteModel /** * 是否已經投過票 */ fun Voting.isVoted(): Boolean = this.userVote?.selectedOptions?.isEmpty() == false /** * 將 投票結果 轉換成 UI model */ fun List<IVotingOptionStatistic>.toPercentageList(): List<Pair<String, Float>> { val totalCount = this.sumOf { it.voteCount ?: 0 } return this.map { it.text.orEmpty() to (it.voteCount?.div(totalCount.toFloat()) ?: 0f) } } fun List<Voting>.toVoteModelList(): List<VoteModel> { return this.map { voting -> VoteModel( id = voting.id.toString(), question = voting.title.orEmpty(), choice = voting.votingOptionStatistics?.map { it.text.orEmpty() } ?: emptyList(), isSingleChoice = (voting.isMultipleChoice == false) ) } } fun List<VoteModel>.toVotingList(): List<Voting> { return this.map { voteModel -> Voting( id = voteModel.id, title = voteModel.question, votingOptionStatistics = voteModel.choice.map { choice -> IVotingOptionStatistic( text = choice ) }, isMultipleChoice = !voteModel.isSingleChoice ) } } /** * 轉為 回復用 model */ fun List<Voting>.toIReplyVotingList(): List<IReplyVoting> = this.map { IReplyVoting( id = it.id, title = it.title ) }
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/VotingExt.kt
1337774288
package com.cmoney.kolfanci.extension import android.os.Bundle import androidx.navigation.NavHostController /** * 返回指定的route並帶參數 */ fun NavHostController.goBackRouteWithParams( route: String, autoPop: Boolean = true, callback: (Bundle.() -> Unit)? = null, ) { getBackStackEntry(route).arguments?.let { callback?.invoke(it) } if (autoPop) { popBackStack() } } /** * 回到上個頁面並帶參數 */ fun NavHostController.goBackWithParams( autoPop: Boolean = true, callback: (Bundle.() -> Unit)? = null, ) { previousBackStackEntry?.arguments?.let { callback?.invoke(it) } if (autoPop) { popBackStack() } }
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/NavHostControllerExt.kt
1341844448
package com.cmoney.kolfanci.extension import java.util.Calendar import java.util.TimeZone fun Long.getDisplayFileSize(): String { val sizeInKB = this.toDouble() / 1024.0 val sizeInMB = sizeInKB / 1024.0 val sizeInGB = sizeInMB / 1024.0 return when { this < 1024 -> "$this bytes" sizeInKB < 1024 -> String.format("%.2f KB", sizeInKB) sizeInMB < 1024 -> String.format("%.2f MB", sizeInMB) else -> String.format("%.2f GB", sizeInGB) } } fun Long.formatDuration(): String { val milliseconds = this val hours = (milliseconds / 3600000).toInt() val minutes = ((milliseconds % 3600000) / 60000).toInt() val seconds = ((milliseconds % 60000) / 1000).toInt() return String.format("%02d:%02d:%02d", hours, minutes, seconds) } /** * 獲取當天的 0 點 0 分 0 秒 */ fun Long.startOfDayFromTimestamp(): Long { // 創建一個 Calendar 實例 val calendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Taipei")) // 使用提供的時間戳轉換成毫秒,並設置 Calendar 的時間 calendar.timeInMillis = this * 1000 // 將小時、分、秒和毫秒設置為 0,以獲得當天的 0 點 0 分 0 秒 calendar.set(Calendar.HOUR_OF_DAY, 0) calendar.set(Calendar.MINUTE, 0) calendar.set(Calendar.SECOND, 0) calendar.set(Calendar.MILLISECOND, 0) // 返回更新後的時間戳,並將毫秒轉換成秒 return calendar.timeInMillis / 1000 }
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/LongExt.kt
1976625355
package com.cmoney.kolfanci.extension import com.google.gson.Gson import com.google.gson.JsonParseException import com.google.gson.JsonSyntaxException import com.google.gson.reflect.TypeToken @Throws(JsonSyntaxException::class, JsonParseException::class) inline fun <reified T> Gson.fromJson(json: String) : T = this.fromJson<T>(json, T::class.java) @Throws(JsonSyntaxException::class, JsonParseException::class) inline fun <reified T> Gson.fromJsonTypeToken(json: String) : T = this.fromJson(json, object : TypeToken<T>(){}.type) @Throws(JsonSyntaxException::class, JsonParseException::class) inline fun <reified T> Gson.toJsonTypeToken(src: Any) : String = this.toJson(src, object : TypeToken<T>(){}.type)
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/GsonExt.kt
1515821189
package com.cmoney.kolfanci.extension import androidx.compose.foundation.lazy.LazyListState fun LazyListState.isScrolledToTop() = firstVisibleItemScrollOffset == 0
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/LazyListStateExt.kt
1326214233
package com.cmoney.kolfanci.extension import com.cmoney.fanciapi.fanci.model.GroupMember import com.cmoney.fanciapi.fanci.model.User /** * GroupUser as GroupMember * 有部分資訊無法提供 */ fun User.asGroupMember(): GroupMember = GroupMember( id = id, name = name, thumbNail = thumbNail, serialNumber = serialNumber // TODO 跟 server 溝通中, 要增加欄位才有辦法轉換 // isVip = this.isVip )
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/UserExt.kt
958583726
package com.cmoney.kolfanci.extension import com.cmoney.fanciapi.fanci.model.Emojis import com.cmoney.fanciapi.fanci.model.IEmojiCount fun Emojis.clickCount(emojiCount: Int, orgEmoji: IEmojiCount?): IEmojiCount? { return when (this) { Emojis.like -> orgEmoji?.copy(like = orgEmoji.like?.plus(emojiCount)?.coerceAtLeast(0)) Emojis.dislike -> orgEmoji?.copy( dislike = orgEmoji.dislike?.plus( emojiCount )?.coerceAtLeast(0) ) Emojis.laugh -> orgEmoji?.copy(laugh = orgEmoji.laugh?.plus(emojiCount)?.coerceAtLeast(0)) Emojis.money -> orgEmoji?.copy(money = orgEmoji.money?.plus(emojiCount)?.coerceAtLeast(0)) Emojis.shock -> orgEmoji?.copy(shock = orgEmoji.shock?.plus(emojiCount)?.coerceAtLeast(0)) Emojis.cry -> orgEmoji?.copy(cry = orgEmoji.cry?.plus(emojiCount)?.coerceAtLeast(0)) Emojis.think -> orgEmoji?.copy(think = orgEmoji.think?.plus(emojiCount)?.coerceAtLeast(0)) Emojis.angry -> orgEmoji?.copy(angry = orgEmoji.angry?.plus(emojiCount)?.coerceAtLeast(0)) } }
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/EmojisExt.kt
514113991
package com.cmoney.kolfanci.extension import com.cmoney.fanciapi.fanci.model.BulletinboardMessage import com.cmoney.fanciapi.fanci.model.User import com.cmoney.kolfanci.model.Constant import com.cmoney.kolfanci.utils.Utils fun BulletinboardMessage.displayPostTime(): String { this.createUnixTime?.apply { return Utils.timesMillisToDate(this.times(1000)) } return "" } fun BulletinboardMessage.isMyPost(): Boolean = author?.id == Constant.MyInfo?.id
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/BulletinboardMessageExt.kt
467167261
package com.cmoney.kolfanci.extension import androidx.compose.ui.graphics.Color import com.cmoney.kolfanci.model.attachment.AttachmentType fun String.toColor(): Color = Color(this.toLong(16)) /** * 轉換成app 在用的 attachment type */ fun String.toAttachmentType(): AttachmentType = when (this.lowercase()) { "voicemessage" -> AttachmentType.VoiceMessage "image" -> AttachmentType.Image "video" -> AttachmentType.Unknown "audio" -> AttachmentType.Audio "txt" -> AttachmentType.Txt "pdf" -> AttachmentType.Pdf else -> AttachmentType.Unknown }
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/StringExt.kt
2363044652
package com.cmoney.kolfanci.extension import com.cmoney.fanciapi.fanci.model.GroupMember fun GroupMember.isVip() = this.isGroupVip == true
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/GroupMemberExt.kt
3060019088
package com.cmoney.kolfanci.extension import android.content.Context import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem import com.cmoney.kolfanci.model.attachment.AttachmentType import com.cmoney.kolfanci.model.vote.VoteModel fun AttachmentInfoItem.getAttachmentType(context: Context): AttachmentType { var attachmentType = this.uri.getAttachmentType(context) val otherModel = this.other if (attachmentType is AttachmentType.Unknown) { otherModel?.let { if (otherModel is VoteModel) { attachmentType = AttachmentType.Choice } } } return attachmentType }
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/AttachmentInfoItemExt.kt
821415638
package com.cmoney.kolfanci.extension import com.google.gson.Gson import com.google.gson.JsonSyntaxException import retrofit2.HttpException import retrofit2.Response //fun <T : Any?> Response<T>.runCatching() = kotlin.runCatching { // this //} @Throws( HttpException::class, JsonSyntaxException::class ) inline fun <reified T : Response<T1>, reified T1> T.checkResponseBody(): T1 { return when { this.isSuccessful -> { if (this.code() == 204) { Unit as T1 } else { this.body() ?: throw EmptyBodyException() } } else -> { when (code()) { 403, 404, 409 -> { val errorBody = errorBody()?.string().orEmpty() if (errorBody.contains("\"message\"") && errorBody.contains("\"type\"")) { val error = Gson().fromJson( errorBody, GroupError::class.java ) throw GroupServerException(this, error) } throw HttpException(this) } } throw HttpException(this) } } } class GroupServerException(response: Response<*>, val groupError: GroupError) : HttpException(response) data class GroupError(val message: String, val type: Int) class EmptyBodyException : Exception("No response body from server")
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/ResponseExt.kt
1954019728
package com.cmoney.kolfanci.extension import android.app.Activity import android.app.ActivityManager import android.app.NotificationManager import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.ContextWrapper import android.content.Intent import android.content.Intent.FLAG_ACTIVITY_NEW_TASK import android.net.Uri import android.os.Environment import android.provider.Settings import android.widget.Toast import androidx.browser.customtabs.CustomTabsIntent import androidx.core.content.FileProvider import java.io.File fun Context.copyToClipboard(text: String) { val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText("", text) clipboard.setPrimaryClip(clip) } fun Context.share(shareMsg: String) { val intent = Intent(Intent.ACTION_SEND) intent.type = "text/分享給好友" intent.putExtra(Intent.EXTRA_TEXT, shareMsg) startActivity(Intent.createChooser(intent, "分享給好友")) } inline fun <reified T : Activity> Context.startActivity(block: Intent.() -> Unit = {}) { startActivity(Intent(this, T::class.java).apply(block)) } inline fun <reified T : Any> Context.intent(body: Intent.() -> Unit): Intent { val intent = Intent(this, T::class.java) intent.body() return intent } inline fun <reified T : Any> Context.intent(): Intent { return Intent(this, T::class.java) } fun Context.goAppStore() { try { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$packageName"))) } catch (e: android.content.ActivityNotFoundException) { startActivity( Intent( Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$packageName") ) ) } } fun Context.findActivity(): Activity { var context = this while (context is ContextWrapper) { if (context is Activity) return context context = context.baseContext } throw IllegalStateException("no activity") } fun Context.openUrl(url: String) { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(intent) } fun Context.showToast(msg: String) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() } fun Context.getCaptureUri(): Uri { val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES) // if (storageDir?.isDirectory == true) { // storageDir.listFiles()?.forEach { file -> // file.delete() // } // } val file = File(storageDir, System.currentTimeMillis().toString() + ".jpg") return FileProvider.getUriForFile( this, "${this.packageName}.provider", file ) } fun Context.openCustomTab(uri: Uri) { val customTabsIntent = CustomTabsIntent.Builder() .setShowTitle(true) .build() customTabsIntent.launchUrl(this, uri) } /** * 是否開啟通知 */ fun Context.isNotificationsEnabled(): Boolean { val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager ?: return false return notificationManager.areNotificationsEnabled() } /** * 打開系統 推播設定頁面 */ fun Context.openNotificationSetting() { Intent().apply { action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS val uri = Uri.fromParts("package", packageName, null) data = uri flags = FLAG_ACTIVITY_NEW_TASK startActivity(this) } } /** * 檢查該 activity 是否執行中 */ fun Context.isActivityRunning(className: String): Boolean { val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager return activityManager.appTasks .filter { it.taskInfo != null } .filter { it.taskInfo.baseActivity != null } .any { it.taskInfo.baseActivity?.className == className } }
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/ContextExt.kt
562721042
package com.cmoney.kolfanci.extension import android.content.res.Resources.getSystem val Int.dp: Int get() = (this / getSystem().displayMetrics.density).toInt() val Int.px: Int get() = (this * getSystem().displayMetrics.density).toInt()
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/IntExt.kt
2280558980
package com.cmoney.kolfanci.extension import com.cmoney.fanciapi.fanci.model.FanciRole import com.cmoney.kolfanci.ui.screens.group.setting.vip.model.VipPlanModel fun FanciRole.toVipPlanModel(): VipPlanModel { return VipPlanModel( id = this.id.orEmpty(), name = this.name.orEmpty(), memberCount = this.userCount?.toInt() ?: 0, description = "" ) }
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/FanciRoleExt.kt
1779817119
package com.cmoney.kolfanci.extension import android.net.Uri import com.cmoney.fanciapi.fanci.model.IMedia import com.cmoney.fanciapi.fanci.model.Media import com.cmoney.kolfanci.model.attachment.AttachmentType import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem /** * 取得 檔案名稱 */ fun Media.getFileName(): String { return when (this.type?.toAttachmentType()) { AttachmentType.VoiceMessage -> "錄音" AttachmentType.Audio -> audio?.fileName.orEmpty() AttachmentType.Image -> "" AttachmentType.Pdf -> pdf?.fileName.orEmpty() AttachmentType.Txt -> txt?.fileName.orEmpty() AttachmentType.Unknown -> "" else -> "" } } /** * 取得 檔案大小 */ fun Media.getFleSize(): Long { return when (this.type?.toAttachmentType()) { AttachmentType.VoiceMessage -> voiceMessage?.fileSize ?: 0L AttachmentType.Audio -> audio?.fileSize ?: 0L AttachmentType.Image -> 0 AttachmentType.Pdf -> pdf?.fileSize ?: 0L AttachmentType.Txt -> txt?.fileSize ?: 0L AttachmentType.Unknown -> 0 else -> 0 } } /** * 取得 音檔長度 */ fun Media.getDuration(): Long { return when (this.type?.toAttachmentType()) { AttachmentType.VoiceMessage -> voiceMessage?.duration ?: 0L AttachmentType.Audio -> audio?.duration ?: 0L AttachmentType.Image -> 0L AttachmentType.Pdf -> 0L AttachmentType.Txt -> 0L AttachmentType.Unknown -> 0L else -> 0L } } /** * 將 server 給的 List media 轉換成 map */ fun List<Media>.toAttachmentTypeMap() = this.map { (it.type?.toAttachmentType() ?: AttachmentType.Unknown) to it }.groupBy({ it.first }, { it.second }) /** * 將 server 給的 List media 轉換成 UploadFileItem map */ fun List<Media>.toUploadFileItemMap() = this.map { val attachmentType = (it.type?.toAttachmentType() ?: AttachmentType.Unknown) attachmentType to AttachmentInfoItem( uri = Uri.parse(it.resourceLink), status = AttachmentInfoItem.Status.Success, serverUrl = it.resourceLink.orEmpty(), filename = it.getFileName(), fileSize = it.getFleSize(), duration = it.getDuration(), attachmentType = attachmentType ) }.groupBy({ it.first }, { it.second }) fun Media.getDisplayType() = when (type?.toAttachmentType()) { AttachmentType.Audio -> "(音檔)" AttachmentType.Image -> "(圖片)" AttachmentType.Pdf -> "(檔案)" AttachmentType.Txt -> "(檔案)" AttachmentType.Unknown -> "(未知)" AttachmentType.Choice -> "(選擇題)" AttachmentType.VoiceMessage -> "(錄音)" null -> "" } fun IMedia.getDisplayType() = when (type?.toAttachmentType()) { AttachmentType.Audio -> "(音檔)" AttachmentType.Image -> "(圖片)" AttachmentType.Pdf -> "(檔案)" AttachmentType.Txt -> "(檔案)" AttachmentType.Unknown -> "(未知)" AttachmentType.Choice -> "(選擇題)" AttachmentType.VoiceMessage -> "(錄音)" null -> "" } fun List<Media>.toAttachmentInfoItem() = this.map { val attachmentType = (it.type?.toAttachmentType() ?: AttachmentType.Unknown) AttachmentInfoItem( uri = Uri.parse(it.resourceLink), status = AttachmentInfoItem.Status.Success, serverUrl = it.resourceLink.orEmpty(), filename = it.getFileName(), fileSize = it.getFleSize(), duration = it.getDuration(), attachmentType = attachmentType ) }
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/Media.kt
2298852889
package com.cmoney.kolfanci.extension import com.cmoney.fanciapi.fanci.model.BanPeriodOption fun BanPeriodOption.toDisplayDay(): String = when(this) { BanPeriodOption.oneDay -> "1日" BanPeriodOption.threeDay -> "3日" BanPeriodOption.oneWeek -> "7日" BanPeriodOption.oneMonth -> "30日" BanPeriodOption.forever -> "永久" }
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/BanPeriodOptionExt.kt
3654383407
package com.cmoney.kolfanci.extension import android.content.ContentResolver import android.content.Context import android.media.MediaMetadataRetriever import android.net.Uri import android.provider.MediaStore import android.provider.OpenableColumns import android.util.Log import android.webkit.MimeTypeMap import com.cmoney.kolfanci.model.Constant import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem import com.cmoney.kolfanci.model.attachment.AttachmentType import java.io.File import java.io.FileOutputStream import java.io.IOException import java.io.InputStream /** * 取得 顯示檔案大小 format */ fun Uri.getDisplayFileSize(context: Context): String { val fileSize = getFileSize(context) ?: 0 return fileSize.getDisplayFileSize() } fun Uri.getFileSize(context: Context): Long? { val cursor = context.contentResolver.query(this, null, null, null, null) val filePath = cursor?.use { if (it.moveToFirst()) { val sizeIndex = it.getColumnIndex(OpenableColumns.SIZE) it.getLong(sizeIndex) } else { null } } return filePath } fun Uri.uriToFile(context: Context): File { if (this.scheme.equals(ContentResolver.SCHEME_FILE)) { return File(this.path.orEmpty()) } else if (this.scheme.equals(ContentResolver.SCHEME_CONTENT)) { val contentResolver = context.contentResolver val displayName = getFileName(context).orEmpty() var inputStream: InputStream? = null var outputStream: FileOutputStream? = null try { inputStream = contentResolver.openInputStream(this) val cache = File(context.cacheDir.absolutePath, displayName) outputStream = FileOutputStream(cache) val buffer = ByteArray(4 * 1024) var read: Int while (inputStream!!.read(buffer).also { read = it } != -1) { outputStream.write(buffer, 0, read) } outputStream.flush() return cache } catch (e: Exception) { e.printStackTrace() } finally { try { inputStream?.close() outputStream?.close() } catch (e: IOException) { e.printStackTrace() } } } // val projection = arrayOf(MediaStore.Images.Media.DATA) // val cursorLoader = CursorLoader(context, this, projection, null, null, null) // val cursor: Cursor? = cursorLoader.loadInBackground() // // cursor?.use { // val columnIndex = it.getColumnIndexOrThrow(MediaStore.Images.Media.DATA) // it.moveToFirst() // val filePath = it.getString(columnIndex) // return File(filePath) // } throw IllegalArgumentException("Failed to convert URI to File") } /** * 取得 Uri file name * * @param context */ fun Uri.getFileName(context: Context): String? { var fileName: String? = null val scheme = this.scheme if (ContentResolver.SCHEME_CONTENT == scheme) { // If the URI scheme is content://, then query the content provider to get the file name. val projection = arrayOf(MediaStore.MediaColumns.DISPLAY_NAME) context.contentResolver.query(this, projection, null, null, null)?.use { cursor -> if (cursor.moveToFirst()) { val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME) fileName = cursor.getString(columnIndex) } } } else if (ContentResolver.SCHEME_FILE == scheme) { // If the URI scheme is file://, then extract the file name from the URI. fileName = this.lastPathSegment } return fileName } /** * 根據 Uri 區分檔案類型 */ fun Uri.getAttachmentType(context: Context): AttachmentType { val mimeType = getMimeType(context) ?: "" Log.i("LinLi", "mimeType: $mimeType") val lowMimeType = mimeType.lowercase() return if (lowMimeType.startsWith("image")) { AttachmentType.Image } else if (lowMimeType.startsWith("application")) { if (lowMimeType.contains("pdf")) { AttachmentType.Pdf } else { AttachmentType.Unknown } } else if (lowMimeType.startsWith("text")) { AttachmentType.Txt } else if (lowMimeType.startsWith("audio")) { val uriString = this.toString() val isRecordFile = Constant.absoluteCachePath.let { uriString.contains(it) } if (isRecordFile) { AttachmentType.VoiceMessage } else { AttachmentType.Audio } } else { AttachmentType.Unknown } } /** * 檔案 上傳時 要傳類型給後端知道 */ fun Uri.getUploadFileType(context: Context): String { val mimeType = getMimeType(context) val lowMimeType = mimeType?.lowercase() return if (lowMimeType != null) { if (lowMimeType.startsWith("audio")) { "audio" } else if (lowMimeType.startsWith("video")) { "video" } else { "document" } } else { "" } } /** * 取得檔案類型 */ fun Uri.getFileType(context: Context): String { val cr = context.contentResolver return cr.getType(this).orEmpty() // val mimeTypeMap = MimeTypeMap.getSingleton() // return mimeTypeMap.getExtensionFromMimeType(r.getType(uri)) } /** * 取得音檔類型 */ fun Uri.getMimeType(context: Context): String? { val type: String? val extension = MimeTypeMap.getFileExtensionFromUrl(this.toString()) type = if (!extension.isNullOrEmpty()) { MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) } else { getFileType(context) } return type } /** * 取得音檔長度 字串 * * @param context * @return 字串 -> 00:00:00 */ fun Uri.getAudioDisplayDuration(context: Context): String { try { val durationMillis = getAudioDuration(context) return durationMillis.formatDuration() } catch (e: Exception) { e.printStackTrace() } return "00:00:00" } /** * 取得音檔長度 */ fun Uri.getAudioDuration(context: Context): Long { val retriever = MediaMetadataRetriever() try { retriever.setDataSource(context, this) val durationStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION) return durationStr?.toLong() ?: 0L } catch (e: Exception) { e.printStackTrace() } finally { retriever.release() } return 0L } /** * 判斷 Uri 是否為網址 */ fun Uri.isURL(): Boolean = this.scheme?.startsWith("http") == true /** * 轉換成上傳物件 */ fun Uri.toUploadFileItem( context: Context, status: AttachmentInfoItem.Status = AttachmentInfoItem.Status.Undefined, serverUrl: String = "" ): AttachmentInfoItem = AttachmentInfoItem( uri = this, status = status, serverUrl = serverUrl, filename = this.getFileName(context).orEmpty(), fileSize = this.getFileSize(context) ?: 0L, duration = this.getAudioDuration(context), attachmentType = this.getAttachmentType(context) )
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/UriExt.kt
1260897702
package com.cmoney.kolfanci.extension import android.app.Activity import android.view.ViewGroup import androidx.activity.ComponentActivity import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.platform.ComposeView import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import com.cmoney.fanciapi.fanci.model.BulletinboardMessage import com.cmoney.fanciapi.fanci.model.ChatMessage import com.cmoney.kolfanci.ui.main.MainActivity import com.cmoney.kolfanci.ui.screens.post.dialog.PostInteract import com.cmoney.kolfanci.ui.screens.post.dialog.PostMoreActionType import com.cmoney.kolfanci.ui.screens.shared.bottomSheet.BottomSheetWrapper import com.cmoney.kolfanci.ui.screens.shared.bottomSheet.ColorPickerBottomSheet import com.cmoney.kolfanci.ui.screens.shared.bottomSheet.InteractBottomSheet import com.cmoney.kolfanci.ui.screens.shared.bottomSheet.MessageInteract import com.cmoney.kolfanci.ui.screens.shared.bottomSheet.PostMoreActionBottomSheet import com.cmoney.kolfanci.ui.theme.FanciTheme /** * Show 聊天室 互動彈窗 */ fun Activity.showInteractDialogBottomSheet( message: ChatMessage, onInteractClick: (MessageInteract) -> Unit ) { val viewGroup = this.findViewById(android.R.id.content) as ViewGroup if (this is MainActivity) { viewGroup.addView( ComposeView(viewGroup.context).apply { setContent { val theme by globalGroupViewModel().theme.collectAsState() FanciTheme(fanciColor = theme) { InteractBottomSheet(viewGroup, this, message, onInteractClick) } } } ) } } /** * 顏色 選擇器 * @param selectedColor 預設選擇顏色 */ fun Activity.showColorPickerDialogBottomSheet( selectedColor: com.cmoney.fanciapi.fanci.model.Color, onColorPicker: (com.cmoney.fanciapi.fanci.model.Color) -> Unit ) { val viewGroup = this.findViewById(android.R.id.content) as ViewGroup if (this is MainActivity) { viewGroup.addView( ComposeView(viewGroup.context).apply { setContent { val theme by globalGroupViewModel().theme.collectAsState() FanciTheme(fanciColor = theme) { ColorPickerBottomSheet(viewGroup, this, selectedColor, onColorPicker) } } } ) } } /** * 貼文 更多動作 */ fun Activity.showPostMoreActionDialogBottomSheet( postMessage: BulletinboardMessage, postMoreActionType: PostMoreActionType, onInteractClick: (PostInteract) -> Unit ) { val viewGroup = this.findViewById(android.R.id.content) as ViewGroup if (this is MainActivity) { viewGroup.addView( ComposeView(viewGroup.context).apply { setContent { val theme by globalGroupViewModel().theme.collectAsState() FanciTheme(fanciColor = theme) { PostMoreActionBottomSheet( parent = viewGroup, composeView = this, postMessage = postMessage, postMoreActionType = postMoreActionType, onInteractClick = onInteractClick ) } } } ) } } fun Activity.showAsBottomSheet( wrapWithBottomSheetUI: Boolean = false, content: @Composable (() -> Unit) -> Unit ) { val viewGroup = this.findViewById(android.R.id.content) as ViewGroup addContentToView(wrapWithBottomSheetUI, viewGroup, content) } fun Fragment.showAsBottomSheet( wrapWithBottomSheetUI: Boolean = false, content: @Composable (() -> Unit) -> Unit ) { val viewGroup = requireActivity().findViewById(android.R.id.content) as ViewGroup addContentToView(wrapWithBottomSheetUI, viewGroup, content) } private fun addContentToView( wrapWithBottomSheetUI: Boolean, viewGroup: ViewGroup, content: @Composable (() -> Unit) -> Unit ) { viewGroup.addView( ComposeView(viewGroup.context).apply { setContent { BottomSheetWrapper(wrapWithBottomSheetUI, viewGroup, this, content) } } ) } @Composable fun ComponentActivity.lifecycleEventListener(event: (Lifecycle.Event) -> Unit) { val eventHandler by rememberUpdatedState(newValue = event) val lifecycle = [email protected] DisposableEffect(lifecycle) { val observer = LifecycleEventObserver { _, event -> eventHandler(event) } lifecycle.addObserver(observer) onDispose { lifecycle.removeObserver(observer) } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/ActivityExt.kt
1799661715
package com.cmoney.kolfanci.extension import androidx.compose.foundation.lazy.LazyListState import androidx.compose.runtime.* @Composable fun LazyListState.OnBottomReached( loadMore: () -> Unit ) { // state object which tells us if we should load more val shouldLoadMore = remember { derivedStateOf { // get last visible item val lastVisibleItem = layoutInfo.visibleItemsInfo.lastOrNull() ?: // list is empty // return false here if loadMore should not be invoked if the list is empty return@derivedStateOf true // Check if last visible item is the last item in the list lastVisibleItem.index == layoutInfo.totalItemsCount - 1 } } // Convert the state into a cold flow and collect LaunchedEffect(shouldLoadMore) { snapshotFlow { shouldLoadMore.value } .collect { // if should load more, then invoke loadMore if (it) loadMore() } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/extension/LazyListState.kt
3816491188
package com.cmoney.kolfanci.utils import android.util.Patterns import androidx.annotation.DrawableRes import com.cmoney.fanciapi.fanci.model.Emojis import com.cmoney.fanciapi.fanci.model.IEmojiCount import com.cmoney.fanciapi.fanci.model.ReportReason import com.cmoney.kolfanci.R import java.text.SimpleDateFormat import java.util.Calendar import java.util.Date import java.util.Locale import java.util.regex.Matcher class Utils { companion object { /** * 根據顯示文案 回傳對應 ReportReason model * * @param reasonText 檢舉文案 * @return ReportReason model */ fun getReportReason(reasonText: String): ReportReason { return when (reasonText) { "濫發廣告訊息" -> ReportReason.spamAds "傳送色情訊息" -> ReportReason.adultContent "騷擾行為" -> ReportReason.harass "內容與主題無關" -> ReportReason.notRelated else -> { ReportReason.other } } } /** * 取得 檢舉文案 * @param reportReason ReportReason model * @return display text */ fun getReportReasonShowText(reportReason: ReportReason): String { return when (reportReason) { ReportReason.spamAds -> "濫發廣告訊息" ReportReason.adultContent -> "傳送色情訊息" ReportReason.harass -> "騷擾行為" ReportReason.notRelated -> "內容與主題無關" else -> "其他" } } /** * 根據 text 提出 url */ fun extractLinks(text: String): List<String> { val links = mutableListOf<String>() val matcher: Matcher = Patterns.WEB_URL.matcher(text) while (matcher.find()) { val url = matcher.group() links.add(url) } return links } /** * 將Emoji 圖檔 轉換對應Server Key * @param resourceId emoji 圖檔 */ fun emojiResourceToServerKey(@DrawableRes resourceId: Int): Emojis { return when (resourceId) { R.drawable.emoji_money -> { Emojis.money } R.drawable.emoji_shock -> { Emojis.shock } R.drawable.emoji_laugh -> { Emojis.laugh } R.drawable.emoji_angry -> { Emojis.angry } R.drawable.emoji_think -> { Emojis.think } R.drawable.emoji_cry -> { Emojis.cry } R.drawable.emoji_like -> { Emojis.like } else -> Emojis.like } } /** * 將Server 資料 map 對應圖檔 * @return resourceID, count */ fun emojiMapping(emojiCount: IEmojiCount): List<Pair<Int, Int>> { val result = mutableListOf<Pair<Int, Int>>() emojiCount.money?.let { result.add(Pair(R.drawable.emoji_money, it)) } emojiCount.shock?.let { result.add(Pair(R.drawable.emoji_shock, it)) } emojiCount.laugh?.let { result.add(Pair(R.drawable.emoji_laugh, it)) } emojiCount.angry?.let { result.add(Pair(R.drawable.emoji_angry, it)) } emojiCount.think?.let { result.add(Pair(R.drawable.emoji_think, it)) } emojiCount.cry?.let { result.add(Pair(R.drawable.emoji_cry, it)) } emojiCount.like?.let { result.add(Pair(R.drawable.emoji_like, it)) } return result } /** * Chat room message display send time. */ fun getDisplayTime(publishTime: Long): String { val sdf = SimpleDateFormat("a hh:mm E") return sdf.format(publishTime) } fun getTimeGroupByKey(publishTime: Long): String { val sdf = SimpleDateFormat("yyyy/MM/dd (E)") return sdf.format(publishTime) } fun getSearchDisplayTime(publishTime: Long): String { val sdf = SimpleDateFormat("yyyy.MM.dd") return sdf.format(publishTime) } fun timesMillisToDate(timestamp: Long): String { val calendar = Calendar.getInstance(Locale.TAIWAN).clone() as Calendar val timePassed = System.currentTimeMillis() - timestamp return when { timePassed / (1000 * 60 * 60 * 24) >= 2 -> { SimpleDateFormat("yyyy-MM-dd", Locale.TAIWAN).format(Date(timestamp)) } timePassed / (1000 * 60 * 60 * 24) >= 1 -> { "昨天" } timePassed / (1000 * 60 * 60) > 0 -> { StringBuilder().append(timePassed / (1000 * 60 * 60)).append("小時前") .toString() } timePassed / (1000 * 60) > 0 -> { StringBuilder().append(timePassed / (1000 * 60)).append("分鐘前").toString() } else -> { "剛剛" } } } fun timeMillisToMinutesSeconds(timestamp: Long): String { val minutes = timestamp / 1000 / 60 val seconds = (timestamp - (1000 * 60 * minutes)) / 1000 return String.format("%02d:%02d", minutes, seconds) } /** * 加密 邀請碼 * * @param input groupId * @param key xor key(default: 1357) * @param bits full bits count * * @return 加密過後字串 length = bits / 4 */ fun encryptInviteCode(input: Int, key: Int = 1357, bits: Int = 32): String { val binaryString = Integer.toBinaryString(input) val length = binaryString.length val finalString = if (length < bits) { "0".repeat(bits - length) + binaryString } else if (length > bits) { binaryString.substring(length - bits) } else { binaryString } val xorResult = performXOR(finalString, key) val decimal = xorResult.toInt(2) val output = Integer.toHexString(decimal) val outputLen = output.length val mustLen = bits / 4 return if (outputLen < mustLen) "0".repeat(mustLen - outputLen) + output else output } /** * 解密 邀請碼 * * @param input 加密字串 * @param key xor key(default: 1357) * @param bits full bits count * * @return groupId */ fun decryptInviteCode(input: String, key: Int = 1357, bits: Int = 32): Int? { try { val decimal = input.toInt(16) val binaryString = Integer.toBinaryString(decimal) val length = binaryString.length val finalString = if (length < bits) { "0".repeat(bits - length) + binaryString } else if (length > bits) { binaryString.substring(length - bits) } else { binaryString } val xorResult = performXOR(finalString, key) return xorResult.toInt(2) } catch (e: Exception) { e.printStackTrace() } return null } private fun performXOR(binaryString: String, xorKey: Int): String { val adjustedXORKey = Integer.toBinaryString(xorKey).padStart(binaryString.length, '0') val result = StringBuilder() for (i in binaryString.indices) { val bit1 = binaryString[i] val bit2 = adjustedXORKey[i] result.append(if (bit1 == bit2) '0' else '1') } return result.toString() } /** * 比較兩個Long時間是否在同一分鐘 */ fun areTimestampsInSameMinute(timestamp1: Long, timestamp2: Long): Boolean { val dateFormat = SimpleDateFormat("yyyyMMddHHmm", Locale.getDefault()) val dateStr1 = dateFormat.format(Date(timestamp1)) val dateStr2 = dateFormat.format(Date(timestamp2)) return dateStr1 == dateStr2 } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/utils/Utils.kt
3316250174
package com.cmoney.kolfanci.utils import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import android.net.Uri import android.os.Environment import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asAndroidBitmap import androidx.core.content.FileProvider import androidx.exifinterface.media.ExifInterface import com.socks.library.KLog import okhttp3.internal.closeQuietly import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.File import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException import java.io.InputStream import java.io.OutputStream object PhotoUtils { suspend fun createUploadImage(uri: Uri, context: Context): String? { var tempFile: File? = null var outputStream: OutputStream? = null var inputStream: InputStream? = null try { val storageDir: File? = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) tempFile = File(storageDir, "uploadedImage.jpg") outputStream = FileOutputStream(tempFile) inputStream = context.contentResolver?.openInputStream(uri) ?: return null val buffer = ByteArray(inputStream.available()) inputStream.read(buffer) outputStream.write(buffer) } catch (e: FileNotFoundException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } finally { inputStream?.closeQuietly() outputStream?.closeQuietly() tempFile?.deleteOnExit() } return compress(tempFile!!.path, context) } /** * 根據圖片路徑壓縮圖片,並返回壓縮後圖片路徑 * @param path * @return */ private suspend fun compress(path: String, context: Context): String? { // 壓縮照片 var bm = getImage(path) ?: return null val degree = readPictureDegree(path) // 讀取照片旋轉角度 if (degree > 0) { bm = rotateBitmap(bm, degree) // 旋轉照片 } val file: String val storageDir: File? = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) file = File(storageDir, "uploadedImage.jpg").absolutePath val f = File(file) if (!f.exists()) { f.mkdirs() } val picName = ("compressedImage.jpg") val resultFilePath = file + picName var out: OutputStream? = null try { out = FileOutputStream(resultFilePath) bm.compress(Bitmap.CompressFormat.JPEG, 90, out) out.flush() } catch (e: Exception) { e.printStackTrace() } finally { out?.closeQuietly() } return resultFilePath } /** * 第二:圖片按比例大小壓縮方法(根據路徑獲取圖片並壓縮): * @param srcPath * @return */ private suspend fun getImage(srcPath: String): Bitmap? { val newOpts = BitmapFactory.Options() // 開始讀入圖片,此時把options.inJustDecodeBounds設回true了 newOpts.inJustDecodeBounds = true val bitmap: Bitmap // 此時返回bm為空 newOpts.inJustDecodeBounds = false val w = newOpts.outWidth val h = newOpts.outHeight val hh = 800f // 這裡設置高度為800f val ww = 480f // 這裡設置高度為480f // 縮放比。由於是固定比例缩放,只用高或者寬其中一個數據進行計算即可 var be = 1 // be = 1表示不缩縮放 if (w > h && w > ww) { // 如果寬度大的話根據寬度固定大小缩放 be = (newOpts.outWidth / ww).toInt() } else if (w < h && h > hh) { // 如果高度高的話根據高度固定大小缩放 be = (newOpts.outHeight / hh).toInt() } if (be <= 0) be = 1 newOpts.inSampleSize = be // 設置縮放比例 // 重新讀入圖片,注意此時已經把options.inJustDecodeBounds設回false了 bitmap = BitmapFactory.decodeFile(srcPath, newOpts) return compressImage(bitmap) // 壓縮好比例大小後再進行質量壓縮 } /** * 質量壓縮 * @param image * @return */ private suspend fun compressImage(image: Bitmap): Bitmap? { val byteArrayOutputStream = ByteArrayOutputStream() image.compress( Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream ) // 質量壓縮方法,這裡100表示不壓縮,把壓縮後的數據存放到byteArrayOutputStream中 var options = 99 // 這個只能是0-100之間不包括0和100不然會報異常 while (byteArrayOutputStream.toByteArray().size / 1024 > 200 && options > 0) { // 循環判斷壓縮後圖片是否大於200kb,大於則繼續壓縮 byteArrayOutputStream.reset() // 重置byteArrayOutputStream及清空 image.compress( Bitmap.CompressFormat.JPEG, options, byteArrayOutputStream ) // 這裡壓縮options%,把壓縮後的數據存放到byteArrayOutputStream中 options -= 10 // 每次都减少10 } val isBm = ByteArrayInputStream(byteArrayOutputStream.toByteArray()) // 把壓縮後的數據byteArrayOutputStream存放到ByteArrayInputStream中 return BitmapFactory.decodeStream(isBm, null, null) } /** * 讀取照片的旋轉角度 * @param path * @return */ private suspend fun readPictureDegree(path: String): Float { var degree = 0 try { val exifInterface = ExifInterface(path) when (exifInterface.getAttributeInt( ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL )) { ExifInterface.ORIENTATION_ROTATE_90 -> { degree = 90 } ExifInterface.ORIENTATION_ROTATE_180 -> { degree = 180 } ExifInterface.ORIENTATION_ROTATE_270 -> { degree = 270 } } } catch (e: IOException) { e.printStackTrace() } return degree.toFloat() } /** * 旋轉照片 * @param bitmap * @param rotate * @return */ private suspend fun rotateBitmap(bitmap: Bitmap, rotate: Float): Bitmap { val w = bitmap.width val h = bitmap.height val matrix = Matrix() matrix.postRotate(rotate) return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true) } /** * 將ImageBitmap寫入IO * @param imageBitmap 圖片的ImageBitmap * @return 檔案的Uri,可能為空 */ fun saveBitmapAndGetUri(context: Context, imageBitmap: ImageBitmap): Uri? { val bitmap = imageBitmap.asAndroidBitmap() val directory = context.cacheDir val fileName = System.currentTimeMillis().toString() + ".png" val file = File(directory, fileName) return try { FileOutputStream(file).use { stream -> bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream) } FileProvider.getUriForFile(context, "${context.packageName}.provider", file) } catch (e: Exception) { KLog.e("saveBitmapAndGetUri: ${e.printStackTrace()}", e) null } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/utils/PhotoUtils.kt
558319491
package com.cmoney.kolfanci.utils import com.cmoney.fanciapi.fanci.model.DeleteStatus import com.cmoney.kolfanci.extension.startOfDayFromTimestamp import com.cmoney.kolfanci.model.ChatMessageWrapper class MessageUtils { companion object { /** * 檢查內容,是否有跨日期,並在跨日中間插入 time bar, * 或是 內容不滿分頁大小(訊息太少), 也插入 */ fun insertTimeBar(newMessage: List<ChatMessageWrapper>): List<ChatMessageWrapper> { if (newMessage.isEmpty()) { return newMessage } //依照日期 分群 val groupList = newMessage.groupBy { val createTime = it.message.createUnixTime?.times(1000) ?: 0L Utils.getTimeGroupByKey(createTime) } //大於2群, 找出跨日交界並插入time bar return if (groupList.size > 1) { val groupMessage = groupList.map { val newList = it.value.toMutableList() //此list的時間是由新到舊 newList.add(generateTimeBar(it.value.last())) //將當天最早的訊息資料作為參數 newList }.flatten().toMutableList() groupMessage } else { val newList = newMessage.toMutableList() val timeBarMessage = generateTimeBar(newMessage.last()) newList.add(timeBarMessage) return newList } } /** * 產生 Time bar item */ private fun generateTimeBar(chatMessageWrapper: ChatMessageWrapper): ChatMessageWrapper { return chatMessageWrapper.copy( message = chatMessageWrapper.message.copy( id = chatMessageWrapper.message.createUnixTime?.startOfDayFromTimestamp().toString(), createUnixTime = chatMessageWrapper.message.createUnixTime?.startOfDayFromTimestamp() ), messageType = ChatMessageWrapper.MessageType.TimeBar ) } /** * 定義 訊息類型 */ fun defineMessageType(chatMessageWrapper: ChatMessageWrapper): ChatMessageWrapper { val messageType = if (chatMessageWrapper.messageType == ChatMessageWrapper.MessageType.TimeBar) { ChatMessageWrapper.MessageType.TimeBar } else if (chatMessageWrapper.isBlocking) { ChatMessageWrapper.MessageType.Blocking } else if (chatMessageWrapper.isBlocker) { ChatMessageWrapper.MessageType.Blocker } else if (chatMessageWrapper.message.isDeleted == true && chatMessageWrapper.message.deleteStatus == DeleteStatus.deleted) { ChatMessageWrapper.MessageType.Delete } else if (chatMessageWrapper.message.isDeleted == true) { ChatMessageWrapper.MessageType.RecycleMessage } else { chatMessageWrapper.messageType } return chatMessageWrapper.copy( messageType = messageType ) } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/utils/MessageUtils.kt
3113367662
package com.cmoney.kolfanci.model.vote import android.os.Parcelable import kotlinx.parcelize.Parcelize /** * 投票 model * * @param id * @param question 問題 * @param choice 選項清單 * @param isSingleChoice 是否為單選題, 反之為多選 */ @Parcelize data class VoteModel( val id: String, val question: String, val choice: List<String>, val isSingleChoice: Boolean = true ): Parcelable
Fanci/app/src/main/java/com/cmoney/kolfanci/model/vote/VoteModel.kt
3166954996
package com.cmoney.kolfanci.model.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.cmoney.fanciapi.fanci.model.Group import com.cmoney.fanciapi.fanci.model.MessageServiceType import com.cmoney.kolfanci.extension.toBulletinboardMessage import com.cmoney.kolfanci.model.notification.NotificationHelper import com.cmoney.kolfanci.model.notification.Payload import com.cmoney.kolfanci.model.notification.TargetType import com.cmoney.kolfanci.model.usecase.ChatRoomUseCase import com.cmoney.kolfanci.model.usecase.GroupUseCase import com.cmoney.kolfanci.model.usecase.PermissionUseCase import com.cmoney.kolfanci.ui.screens.follow.model.GroupItem import com.socks.library.KLog import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch class NotificationViewModel( private val notificationHelper: NotificationHelper, private val groupUseCase: GroupUseCase, private val chatRoomUseCase: ChatRoomUseCase, private val permissionUseCase: PermissionUseCase ) : ViewModel() { private val TAG = NotificationViewModel::class.java.simpleName private val _inviteGroup: MutableStateFlow<Group?> = MutableStateFlow(null) val inviteGroup = _inviteGroup.asStateFlow() //收到 推播訊息 private val _targetType: MutableStateFlow<TargetType?> = MutableStateFlow(null) val targetType = _targetType.asStateFlow() //前往指定頻道, 指定貼文/指定訊息... private val _jumpToChannelDest = MutableStateFlow<PushDataWrapper?>(null) val jumpToChannelDest = _jumpToChannelDest.asStateFlow() //目前沒加入該社團, 彈窗 private val _showNotJoinAlert = MutableStateFlow(false) val showNotJoinAlert = _showNotJoinAlert.asStateFlow() //解散社團 彈窗 private val _showDissolveGroupDialog = MutableStateFlow<String?>(null) val showDissolveGroupDialog = _showDissolveGroupDialog.asStateFlow() //刷新 我的社團 private val _refreshGroup = MutableStateFlow(false) val refreshGroup = _refreshGroup.asStateFlow() //前往加入審核畫面 private val _groupApprovePage = MutableStateFlow<Group?>(null) val groupApprovePage = _groupApprovePage.asStateFlow() //打開指定社團 private val _openGroup = MutableStateFlow<Group?>(null) val openGroup = _openGroup.asStateFlow() //沒有權限 執行動作 private val _showNoPermissionTip = MutableStateFlow(false) val showNoPermissionTip = _showNoPermissionTip.asStateFlow() /** * 推播 or dynamic link 資料 */ fun setNotificationBundle(payLoad: Payload) { KLog.i(TAG, "setNotificationBundle payLoad:$payLoad") val targetType = notificationHelper.convertPayloadToTargetType(payLoad) ?: TargetType.MainPage KLog.i(TAG, "setNotificationBundle targetType:${targetType}") _targetType.value = targetType } /** * reset state */ fun clearPushDataState() { KLog.i(TAG, "clearPushDataState") _targetType.value = null } /** * 抓取邀請連結社團的資訊 */ fun fetchInviteGroup(groupId: String) { KLog.i(TAG, "fetchInviteGroup:$groupId") viewModelScope.launch { groupUseCase.getGroupById( groupId ).fold({ KLog.i(TAG, "fetchInviteGroup success:$it") _inviteGroup.value = it }, { it.printStackTrace() KLog.e(TAG, it) }) } } fun openedInviteGroup() { _inviteGroup.value = null } /** * 收到新訊息 推播 */ fun receiveNewMessage( receiveNewMessage: TargetType.ReceiveMessage?, myGroupList: List<GroupItem> ) { KLog.i(TAG, "receiveNewMessage:$receiveNewMessage") receiveNewMessage?.let { viewModelScope.launch { val groupId = receiveNewMessage.groupId val channelId = receiveNewMessage.channelId val messageId = receiveNewMessage.messageId myGroupList.firstOrNull { groupItem -> groupItem.groupModel.id == groupId }?.also { it.groupModel.categories?.flatMap { category -> category.channels.orEmpty() }?.firstOrNull { channel -> channel.id == channelId }?.also { channel -> //更新該頻道權限 permissionUseCase.updateChannelPermissionAndBuff(channelId = channel.id.orEmpty()) .onSuccess { _ -> _jumpToChannelDest.value = PushDataWrapper.ChannelMessage( group = it.groupModel, channel = channel, messageId = messageId ) } } } ?: kotlin.run { _showNotJoinAlert.value = true } } } } /** * 收到 新貼文 推播 * * 檢查是否已經加入該社團並打開該社團 * 取得指定文章資訊 */ fun receiveNewPost( receivePostMessage: TargetType.ReceivePostMessage?, myGroupList: List<GroupItem> ) { KLog.i(TAG, "receivePostMessage:$receivePostMessage") receivePostMessage?.let { viewModelScope.launch { val groupId = receivePostMessage.groupId val channelId = receivePostMessage.channelId val messageId = receivePostMessage.messageId myGroupList.firstOrNull { groupItem -> groupItem.groupModel.id == groupId }?.also { it.groupModel.categories?.flatMap { category -> category.channels.orEmpty() }?.firstOrNull { channel -> channel.id == channelId }?.also { channel -> //取得指定文章資訊 chatRoomUseCase.getSingleMessage( messageId = messageId, messageServiceType = MessageServiceType.bulletinboard ).onSuccess { chatMessage -> //更新該頻道權限 permissionUseCase.updateChannelPermissionAndBuff(channelId = channel.id.orEmpty()) .onSuccess { _ -> _jumpToChannelDest.value = PushDataWrapper.ChannelPost( group = it.groupModel, channel = channel, bulletinboardMessage = chatMessage.toBulletinboardMessage() ) } }.onFailure { err -> KLog.e(TAG, err) } } } ?: kotlin.run { _showNotJoinAlert.value = true } } } } /** * 解散 社團 */ fun dissolveGroup(dissolveGroup: TargetType.DissolveGroup) { KLog.i(TAG, "dissolveGroup:$dissolveGroup") _showDissolveGroupDialog.value = dissolveGroup.groupId } /** * 檢查 解散的社團跟目前選中的社團 是否一樣 * 如果一樣-> 就執行刷新動作 * 不一樣時-> 不動作 */ fun onCheckDissolveGroup(groupId: String, currentGroup: Group?) { KLog.i(TAG, "onCheckDissolveGroup:$groupId") if (currentGroup?.id == groupId) { _refreshGroup.value = true } } fun finishJumpToChannelDest() { _jumpToChannelDest.value = null } fun dismissNotJoinAlert() { _showNotJoinAlert.value = false } fun dismissDissolveDialog() { _showDissolveGroupDialog.value = null } fun afterRefreshGroup() { _refreshGroup.value = false } /** * 管理者, 前往申請加入審核頁面 */ fun groupApprove(groupId: String) { KLog.i(TAG, "groupApprove:$groupId") viewModelScope.launch { //檢查是否有權限進入 permissionUseCase.getPermissionByGroup(groupId = groupId) .onSuccess { //有權限審核 if (it.approveJoinApplies == true) { groupUseCase.getGroupById(groupId = groupId) .onSuccess { group -> _groupApprovePage.value = group } .onFailure { err -> KLog.e(TAG, err) } } //沒有該權限審核 else { _showNoPermissionTip.value = true } } .onFailure { err -> KLog.e(TAG, err) } } } fun afterOpenApprovePage() { _groupApprovePage.value = null _showNoPermissionTip.value = false } /** * 打開 指定社團 */ fun openGroup(groupId: String, myGroupList: List<GroupItem>) { KLog.i(TAG, "openGroup:$groupId") viewModelScope.launch { myGroupList.firstOrNull { groupItem -> groupItem.groupModel.id == groupId }?.also { _openGroup.value = it.groupModel } ?: kotlin.run { _showNotJoinAlert.value = true } } } fun afterOpenGroup() { _openGroup.value = null } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/viewmodel/NotificationViewModel.kt
2671189837
package com.cmoney.kolfanci.model.viewmodel import android.app.Application import android.net.Uri import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.asFlow import androidx.lifecycle.viewModelScope import com.cmoney.kolfanci.utils.PhotoUtils import com.cmoney.xlogin.XLoginHelper import com.socks.library.KLog import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File /** * 設定用戶資料 */ class UserViewModel( private val context: Application, ) : AndroidViewModel(context) { private val TAG = UserViewModel::class.java.simpleName private val _isLoading = MutableLiveData<Boolean>() val isLoading = _isLoading.asFlow() private val _isComplete = MutableLiveData<Boolean>() val isComplete = _isComplete.asFlow() private val _showEmptyNameDialog = MutableStateFlow(false) val showEmptyNameDialog = _showEmptyNameDialog.asStateFlow() /** * 更換暱稱 以及 大頭貼 */ fun changeNicknameAndAvatar(nickName: String, avatarUri: Uri?) { KLog.i(TAG, "changeNicknameAndAvatar") viewModelScope.launch { _isLoading.value = true //更換暱稱 val nickName = nickName.trim() if (nickName.isEmpty()) { _isLoading.value = false _showEmptyNameDialog.value = true return@launch } //不一樣才動作 if (nickName != XLoginHelper.nickName) { val isSuccess = XLoginHelper.changeNickNameRealTime(nickName).isSuccess KLog.i(TAG, "changeNickNameIsSuccess:$isSuccess") } //更換頭貼 avatarUri?.let { val file = withContext(Dispatchers.IO) { File( PhotoUtils.createUploadImage(avatarUri, context) ?: return@withContext null ) } ?: return@launch val isSuccess = XLoginHelper.changeAvatar(file).isSuccess KLog.i(TAG, "changeAvatarIsSuccess:$isSuccess") } _isComplete.value = true _isLoading.value = false } } fun dismissEmptyNameDialog() { _showEmptyNameDialog.value = false } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/viewmodel/UserViewModel.kt
1263771155
package com.cmoney.kolfanci.model.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.cmoney.fanciapi.fanci.model.ApplyStatus import com.cmoney.fanciapi.fanci.model.BulletinboardMessage import com.cmoney.fanciapi.fanci.model.Category import com.cmoney.fanciapi.fanci.model.Channel import com.cmoney.fanciapi.fanci.model.ChannelAuthType import com.cmoney.fanciapi.fanci.model.ChannelPrivacy import com.cmoney.fanciapi.fanci.model.ChannelTabType import com.cmoney.fanciapi.fanci.model.ColorTheme import com.cmoney.fanciapi.fanci.model.FanciRole import com.cmoney.fanciapi.fanci.model.Group import com.cmoney.fanciapi.fanci.model.GroupRequirementApply import com.cmoney.fanciapi.fanci.model.GroupRequirementApplyInfo import com.cmoney.kolfanci.model.Constant import com.cmoney.kolfanci.model.GroupJoinStatus import com.cmoney.kolfanci.model.usecase.ChannelUseCase import com.cmoney.kolfanci.model.usecase.GroupApplyUseCase import com.cmoney.kolfanci.model.usecase.GroupUseCase import com.cmoney.kolfanci.model.usecase.NotificationUseCase import com.cmoney.kolfanci.model.usecase.OrderUseCase import com.cmoney.kolfanci.model.usecase.PermissionUseCase import com.cmoney.kolfanci.model.usecase.ThemeUseCase import com.cmoney.kolfanci.ui.screens.channel.ResetRedDot import com.cmoney.kolfanci.ui.screens.follow.model.GroupItem import com.cmoney.kolfanci.ui.screens.group.setting.group.groupsetting.avatar.ImageChangeData import com.cmoney.kolfanci.ui.screens.group.setting.group.groupsetting.theme.model.GroupTheme import com.cmoney.kolfanci.ui.screens.shared.member.viewmodel.SelectedModel import com.cmoney.kolfanci.ui.theme.DefaultThemeColor import com.cmoney.xlogin.XLoginHelper import com.socks.library.KLog import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch sealed class ThemeSetting { object Default : ThemeSetting() object Coffee : ThemeSetting() } /** * 推播 跳轉頁面所需資料 */ sealed class PushDataWrapper { /** * 前往頻道聊天 */ data class ChannelMessage( val group: Group, val channel: Channel, val messageId: String ) : PushDataWrapper() /** * 前往頻道貼文 */ data class ChannelPost( val group: Group, val channel: Channel, val bulletinboardMessage: BulletinboardMessage ) : PushDataWrapper() } /** * 社團相關設定 */ class GroupViewModel( private val themeUseCase: ThemeUseCase, private val groupUseCase: GroupUseCase, private val channelUseCase: ChannelUseCase, private val permissionUseCase: PermissionUseCase, private val orderUseCase: OrderUseCase, private val groupApplyUseCase: GroupApplyUseCase, private val notificationUseCase: NotificationUseCase ) : ViewModel() { private val TAG = GroupViewModel::class.java.simpleName private val _loading = MutableStateFlow(false) val loading = _loading.asStateFlow() //目前選中的社團 private val _currentGroup: MutableStateFlow<Group?> = MutableStateFlow(null) val currentGroup = _currentGroup.asStateFlow() //我目前加入的社團 private val _myGroupList: MutableStateFlow<List<GroupItem>> = MutableStateFlow(emptyList()) val myGroupList = _myGroupList.asStateFlow() //主題設定檔 private val _theme = MutableStateFlow(DefaultThemeColor) val theme = _theme.asStateFlow() //加入社團狀態 private val _joinGroupStatus: MutableStateFlow<GroupJoinStatus> = MutableStateFlow(GroupJoinStatus.NotJoin) val joinGroupStatus = _joinGroupStatus.asStateFlow() //推播中心,未讀數量 private val _notificationUnreadCount: MutableStateFlow<Long> = MutableStateFlow(0L) val notificationUnreadCount = _notificationUnreadCount.asStateFlow() var haveNextPage: Boolean = false //拿取所有群組時 是否還有分頁 var nextWeight: Long? = null //下一分頁權重 /** * 有登入狀態, 取得 我的群組, 並設定該主題 * 未登入, 取得 server 社團清單 * * @param isSilent 是否在執行過程中避免影響目前畫面,true 表示會避免,false 表示會影響 */ fun fetchMyGroup(isSilent: Boolean = false) { KLog.i(TAG, "fetchMyGroup") if (XLoginHelper.isLogin) { viewModelScope.launch { val isNotSilent = !isSilent if (isNotSilent) { loading() } groupUseCase.groupToSelectGroupItem().fold({ if (it.isNotEmpty()) { var currentSelectedPos = _myGroupList.value.indexOfFirst { groupItem -> groupItem.isSelected } //not found selected group, reset to first if (currentSelectedPos < 0) { currentSelectedPos = 0 } //我的所有群組 _myGroupList.value = it.mapIndexed { index, groupItem -> if (index == currentSelectedPos) { groupItem.copy( isSelected = true ) } else { groupItem.copy( isSelected = false ) } } val selectedGroup = _myGroupList.value[currentSelectedPos].groupModel //設定目前的社團 _currentGroup.value = selectedGroup //抓取選中社團的主題 setAppTheme(selectedGroup) //抓取選中社團的權限 fetchGroupPermission(selectedGroup) } else { resetToDefault() } }, { KLog.e(TAG, it) }) fetchNotificationCenterCount() if (isNotSilent) { dismissLoading() } } } } /** * 將原本設定過的值, 都恢復至 default value */ private fun resetToDefault() { _currentGroup.value = null _myGroupList.value = emptyList() _theme.value = DefaultThemeColor } private fun loading() { KLog.i(TAG, "loading") _loading.value = true } private fun dismissLoading() { KLog.i(TAG, "dismissLoading") _loading.value = false } /** * 設定 目前所選的社團, 並設定Theme */ fun setCurrentGroup(group: Group) { KLog.i(TAG, "setCurrentGroup") if (group != _currentGroup.value && group.id != null) { KLog.i(TAG, "setCurrentGroup diff:$group") setAppTheme(group) fetchGroupPermission(group) _currentGroup.value = group setupMenuSelectedStatus(group) } } /** * 解散社團 * * @param id */ fun leaveGroup(id: String) { viewModelScope.launch { loading() val result = groupUseCase.leaveGroup(id = id) result.onSuccess { val myGroup = _myGroupList.value val newGroups = myGroup.filterNot { groupItem -> groupItem.groupModel.id == id }.mapIndexed { index, groupItem -> if (index == 0) { groupItem.copy(isSelected = true) } else { groupItem } } if (newGroups.isNotEmpty()) { val selectGroup = newGroups.first() _myGroupList.value = newGroups setCurrentGroup(group = selectGroup.groupModel) } else { // fetchAllGroupList() fetchMyGroup() } }.onFailure { t -> KLog.e(TAG, t) } dismissLoading() } } /** * 設定 側邊欄目前選擇狀態, 如果該 Group 不存在就新增 */ private fun setupMenuSelectedStatus(group: Group) { val groupList = _myGroupList.value.toMutableList() val isExists = groupList.any { it.groupModel.id == group.id } if (!isExists) { groupList.add( 0, GroupItem( groupModel = group, isSelected = true ) ) } _myGroupList.value = groupList.map { if (it.groupModel.id == group.id) { it.copy( isSelected = true ) } else { it.copy( isSelected = false ) } } } /** * 根據選擇的社團 設定 theme */ private fun setAppTheme(group: Group) { KLog.i(TAG, "setAppTheme.") viewModelScope.launch { group.colorSchemeGroupKey?.apply { themeUseCase.fetchThemeConfig(this).fold({ _theme.value = it.theme }, { KLog.e(TAG, it) }) } } } /** * 抓取在該社團的權限 */ private fun fetchGroupPermission(group: Group) { KLog.i(TAG, "fetchGroupPermission:$group") viewModelScope.launch { permissionUseCase.getPermissionByGroup(groupId = group.id.orEmpty()).fold( { KLog.i(TAG, it) Constant.MyGroupPermission = it }, { KLog.e(TAG, it) } ) } } /** * 更換 社團 簡介 * @param desc 簡介 */ fun changeGroupDesc(desc: String) { val group = _currentGroup.value ?: return viewModelScope.launch { groupUseCase.changeGroupDesc(desc, group).fold({ _currentGroup.value = group.copy(description = desc) }, { KLog.e(TAG, it) }) } } /** * 更換 社團名字 * @param name 更換的名字 */ fun changeGroupName(name: String) { KLog.i(TAG, "changeGroupNameL$name") val group = _currentGroup.value ?: return viewModelScope.launch { groupUseCase.changeGroupName(name, group).fold({ _currentGroup.value = group.copy(name = name) }, { KLog.e(TAG, it) }) } } /** * 更換社團 Logo */ fun changeGroupLogo(data: ImageChangeData) { KLog.i(TAG, "changeGroupLogo") val group = _currentGroup.value ?: return viewModelScope.launch { var uri: Any? = data.uri if (uri == null) { uri = data.url } uri?.let { groupUseCase.changeGroupLogo(uri, group).collect { _currentGroup.value = group.copy( logoImageUrl = it ) //refresh group list _myGroupList.value = _myGroupList.value.map { groupItem -> if (groupItem.groupModel.id == group.id) { groupItem.copy( groupModel = groupItem.groupModel.copy( logoImageUrl = it ) ) } else { groupItem } } } } } } /** * 更換社團 頭貼 */ fun changeGroupAvatar(data: ImageChangeData) { KLog.i(TAG, "changeGroupAvatar") val group = _currentGroup.value ?: return viewModelScope.launch { var uri: Any? = data.uri if (uri == null) { uri = data.url } uri?.let { groupUseCase.changeGroupAvatar(uri, group).collect { _currentGroup.value = group.copy( thumbnailImageUrl = it ) //refresh group list _myGroupList.value = _myGroupList.value.map { groupItem -> if (groupItem.groupModel.id == group.id) { groupItem.copy( groupModel = groupItem.groupModel.copy( thumbnailImageUrl = it ) ) } else { groupItem } } } } } } /** * 更換 社團 背景圖 */ fun changeGroupCover(data: ImageChangeData) { KLog.i(TAG, "changeGroupCover") val group = _currentGroup.value ?: return viewModelScope.launch { var uri: Any? = data.uri if (uri == null) { uri = data.url } uri?.let { groupUseCase.changeGroupBackground(uri, group).collect { _currentGroup.value = group.copy( coverImageUrl = it ) } } } } /** * Usr 選擇的 預設 大頭貼 */ fun onGroupAvatarSelect(url: String) { KLog.i(TAG, "onGroupAvatarSelect:$url") val group = _currentGroup.value ?: return viewModelScope.launch { _currentGroup.value = group.copy( thumbnailImageUrl = url ) } } /** * Usr 選擇的 預設 背景 */ fun onGroupCoverSelect(url: String) { KLog.i(TAG, "onGroupCoverSelect:$url") val group = _currentGroup.value ?: return viewModelScope.launch { _currentGroup.value = group.copy( coverImageUrl = url ) } } /** * 更換 主題 * @param groupTheme 要更換的主題 */ fun changeTheme(groupTheme: GroupTheme) { KLog.i(TAG, "changeTheme: $groupTheme") val group = _currentGroup.value ?: return viewModelScope.launch { if (group.id != null) { themeUseCase.changeGroupTheme(group, groupTheme) .onSuccess { ColorTheme.decode(groupTheme.id)?.let { colorTheme -> themeUseCase.fetchThemeConfig(colorTheme).fold({ localGroupTheme -> _theme.value = localGroupTheme.theme }, { t -> KLog.e(TAG, t) }) setSelectedTheme(group, colorTheme) } } .onFailure { KLog.e(TAG, it) } } } } /** * 設定 選中的 Theme */ private fun setSelectedTheme(group: Group, colorTheme: ColorTheme) { _currentGroup.value = group.copy( colorSchemeGroupKey = colorTheme ) } /** * 設定公開度 * * @param openness 公開度,true 公開,false 不公開 */ fun changeOpenness(openness: Boolean) { _currentGroup.update { group -> group?.copy( isNeedApproval = !openness ) } } /** * 新增 分類 * * @param name 分類名稱 */ fun addCategory(name: String) { val group = _currentGroup.value ?: return KLog.i(TAG, "addCategory: $group, $name") viewModelScope.launch { channelUseCase.addCategory(groupId = group.id.orEmpty(), name = name).fold({ val newCategoryList = group.categories.orEmpty().toMutableList() newCategoryList.add(it) _currentGroup.update { oldGroup -> oldGroup?.copy( categories = newCategoryList ) } }, { KLog.e(TAG, it) }) } } /** * 新增 頻道 * * @param categoryId 分類id, 在此分類下建立 * @param name 頻道名稱 */ fun addChannel( categoryId: String, name: String, isNeedApproval: Boolean, listPermissionSelected: Map<ChannelAuthType, SelectedModel>, orgChannelRoleList: List<FanciRole>, channelRole: List<FanciRole>? = null, isChatTabFirst: Boolean ) { val group = _currentGroup.value ?: return KLog.i(TAG, "addChannel: $categoryId, $name") viewModelScope.launch { val privacy = if (isNeedApproval) { ChannelPrivacy.private } else { ChannelPrivacy.public } val tabOrder = if (isChatTabFirst) { listOf(ChannelTabType.chatRoom, ChannelTabType.bulletinboard) } else { listOf(ChannelTabType.bulletinboard, ChannelTabType.chatRoom) } channelUseCase.addChannel( categoryId = categoryId, name = name, privacy = privacy, tabs = tabOrder ).fold({ channel -> //新增管理員 if (channelRole?.isNotEmpty() == true) { editChannelRole( channel = channel, orgChannelRoleList = orgChannelRoleList, channelRole = channelRole ) } //私密頻道處理 if (privacy == ChannelPrivacy.private) { setPrivateChannelWhiteList( channelId = channel.id.orEmpty(), listPermissionSelected = listPermissionSelected ) } // 設定類別到畫面上 addChannelToGroup(channel, group) }, { KLog.e(TAG, it) }) } } /** * 編輯 頻道 * * @param name 要更改的頻道名稱 */ fun editChannel( channel: Channel?, name: String, isNeedApproval: Boolean, listPermissionSelected: Map<ChannelAuthType, SelectedModel>, orgChannelRoleList: List<FanciRole>, channelRole: List<FanciRole>? = null, isChatTabFirst: Boolean ) { val group = _currentGroup.value ?: return KLog.i(TAG, "editChannel") viewModelScope.launch { channel?.let { channel -> // 私密頻道處理 if (isNeedApproval) { setPrivateChannelWhiteList( channelId = channel.id.orEmpty(), listPermissionSelected = listPermissionSelected ) } // 編輯管理員 editChannelRole( channel = channel, orgChannelRoleList = orgChannelRoleList, channelRole = channelRole ) // 編輯名稱 editChannelName( group = group, channel = channel, name = name, isNeedApproval = isNeedApproval ) //編輯tab 順序 editTabOrder( channel = channel, isChatTabFirst ) } } } /** * 編輯 頻道 tab 順序 */ private fun editTabOrder(channel: Channel, isChatTabFirst: Boolean) { KLog.i(TAG, "editTabOrder:$isChatTabFirst") val tabOrder = if (isChatTabFirst) { listOf(ChannelTabType.chatRoom, ChannelTabType.bulletinboard) } else { listOf(ChannelTabType.bulletinboard, ChannelTabType.chatRoom) } viewModelScope.launch { channelUseCase.setChannelTabOrder( channelId = channel.id.orEmpty(), tabs = tabOrder ) } } /** * 刪除 頻道 */ fun deleteChannel(channel: Channel) { val group = _currentGroup.value ?: return KLog.i(TAG, "deleteChannel:$channel") viewModelScope.launch { channelUseCase.deleteChannel(channel.id.orEmpty()).fold({ val newCategory = group.categories?.map { category -> category.copy( channels = category.channels?.filter { groupChannel -> groupChannel.id != channel.id } ) } _currentGroup.update { oldGroup -> oldGroup?.copy(categories = newCategory) } }, { KLog.e(TAG, it) }) } } /** * 編輯 頻道 管理員 */ private suspend fun editChannelRole( channel: Channel, orgChannelRoleList: List<FanciRole>, channelRole: List<FanciRole>? = null ) { KLog.i(TAG, "editChannelRole") //新增角色至channel val addRoleList = channelRole?.filter { !orgChannelRoleList.contains(it) }.orEmpty() if (addRoleList.isNotEmpty()) { val isSuccess = channelUseCase.addRoleToChannel( channelId = channel.id.orEmpty(), roleIds = addRoleList.map { it.id.orEmpty() }).getOrNull() KLog.i(TAG, "editChannelRole addRole: $isSuccess") } //要移除的角色 val removeRoleList = orgChannelRoleList.filter { !channelRole.orEmpty().contains(it) } if (removeRoleList.isNotEmpty()) { val isSuccess = channelUseCase.deleteRoleFromChannel(channelId = channel.id.orEmpty(), roleIds = removeRoleList.map { it.id.orEmpty() }).isSuccess KLog.i(TAG, "editChannelRole removeRole: $isSuccess") } } /** * 設定 私密頻道 白名單 */ private suspend fun setPrivateChannelWhiteList( channelId: String, listPermissionSelected: Map<ChannelAuthType, SelectedModel> ) { KLog.i(TAG, "setPrivateChannelWhiteList:$channelId") listPermissionSelected.forEach { (authType, selectedModel) -> channelUseCase.putPrivateChannelWhiteList( channelId = channelId, authType = authType, accessorList = selectedModel.toAccessorList() ) } } /** * 將新的 channel append 至 原本 group 做顯示 */ private fun addChannelToGroup(channel: Channel, group: Group) { channel.category?.let { channelCategory -> val newCategories = group.categories?.map { category -> if (category.id == channelCategory.id) { val newChannel = category.channels.orEmpty().toMutableList() newChannel.add(channel) category.copy( channels = newChannel ) } else { category } } _currentGroup.update { it?.copy( categories = newCategories ) } } } /** * 編輯 頻道 名稱 */ private fun editChannelName( group: Group, channel: Channel, name: String, isNeedApproval: Boolean ) { KLog.i(TAG, "editChanelName") viewModelScope.launch { channelUseCase.editChannelName( channelId = channel.id.orEmpty(), name = name, privacy = if (isNeedApproval) { ChannelPrivacy.private } else { ChannelPrivacy.public } ).fold({ val newCategory = group.categories?.map { category -> val newChannel = category.channels?.map { groupChannel -> if (channel.id == groupChannel.id) { channel.copy( name = name ) } else { groupChannel } } category.copy( channels = newChannel ) } _currentGroup.update { oldGroup -> oldGroup?.copy(categories = newCategory) } }, { KLog.e(TAG, it) }) } } /** * 編輯 類別名稱 */ fun editCategory(category: Category, name: String) { KLog.i(TAG, "editCategory") val group = _currentGroup.value ?: return viewModelScope.launch { channelUseCase.editCategoryName(categoryId = category.id.orEmpty(), name = name).fold({ val newCategory = group.categories?.map { groupCategory -> if (groupCategory.id == category.id) { groupCategory.copy(name = name) } else { groupCategory } } _currentGroup.update { oldGroup -> oldGroup?.copy( categories = newCategory ) } }, { KLog.e(TAG, it) }) } } /** * 刪除 分類, 並將該分類下的頻道分配至 預設 */ fun deleteCategory(category: Category) { KLog.i(TAG, "deleteCategory") val group = _currentGroup.value ?: return viewModelScope.launch { channelUseCase.deleteCategory(categoryId = category.id.orEmpty()).fold({ val targetChannels = category.channels ?: emptyList() // 刪除分類 val newCategories = group.categories?.filter { groupCategory -> groupCategory.id != category.id } // 將刪除分類下的頻道移至預設分類下 ?.map { groupCategory -> if (groupCategory.isDefault == true) { val currentChannels = groupCategory.channels?.toMutableList() ?: mutableListOf() currentChannels.addAll(targetChannels) groupCategory.copy( channels = currentChannels ) } else { groupCategory } } _currentGroup.update { oldGroup -> oldGroup?.copy(categories = newCategories) } }, { KLog.e(TAG, it) }) } } /** * 儲存 分類排序 */ fun updateCategories(categories: List<Category>) { val group = _currentGroup.value ?: return KLog.i(TAG, "updateCategories: $categories") viewModelScope.launch { orderUseCase.orderCategoryOrChannel( groupId = group.id.orEmpty(), category = categories ).fold({ _currentGroup.update { oldGroup -> oldGroup?.copy(categories = categories) } }, { KLog.e(TAG, it) }) } } /** * 取得 User 對於 準備加入該社團的狀態 * ex: 已經加入, 審核中, 未加入 */ fun getGroupJoinStatus(group: Group) { KLog.i(TAG, "getGroupStatus:$group") viewModelScope.launch { _myGroupList.value.any { myGroup -> myGroup.groupModel.id == group.id }.let { isJoined -> _joinGroupStatus.value = if (isJoined) { GroupJoinStatus.Joined } else { //私密社團 if (group.isNeedApproval == true) { if (XLoginHelper.isLogin) { val groupRequirementApplyInfo = groupApplyUseCase.fetchMyApply(groupId = group.id.orEmpty()) .getOrElse { //Default GroupRequirementApplyInfo( apply = GroupRequirementApply( status = ApplyStatus.confirmed ) ) } when (groupRequirementApplyInfo.apply?.status) { ApplyStatus.unConfirmed -> GroupJoinStatus.InReview ApplyStatus.confirmed -> GroupJoinStatus.Joined ApplyStatus.denied -> GroupJoinStatus.NotJoin null -> GroupJoinStatus.NotJoin } } else { GroupJoinStatus.NotJoin } } else { GroupJoinStatus.NotJoin } } } } } /** * 刷新 Group and Group List and notification unread count */ fun refreshGroupAndNotificationCount() { KLog.i(TAG, "refreshGroup") viewModelScope.launch { val groupId = _currentGroup.value?.id ?: return@launch groupUseCase.getGroupById(groupId = groupId) .onSuccess { group -> setCurrentGroup(group) } fetchMyGroup(isSilent = true) } } /** * 抓取 推播中心 未讀數量 */ private suspend fun fetchNotificationCenterCount() { KLog.i(TAG, "fetchNotificationCenterCount") notificationUseCase.getNotificationUnReadCount() .onSuccess { unreadCount -> KLog.i(TAG, "NotificationUnReadCount:$unreadCount") _notificationUnreadCount.value = unreadCount } } /** * 清空 指定紅點, 之後再去拿取最新Group資訊 */ fun resetRedDot(resetRedDot: ResetRedDot) { KLog.i(TAG, "resetRedDot:$resetRedDot") viewModelScope.launch { val channelId = resetRedDot.channelId if (resetRedDot.isResetChat) { notificationUseCase.clearChatUnReadCount(channelId = channelId) } if (resetRedDot.isResetPost) { notificationUseCase.clearPostUnReadCount(channelId = channelId) } refreshGroupAndNotificationCount() } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/viewmodel/GroupViewModel.kt
2566356
package com.cmoney.kolfanci.model.viewmodel import android.app.Application import android.net.Uri import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.cmoney.fanciapi.fanci.model.Media import com.cmoney.fanciapi.fanci.model.Voting import com.cmoney.kolfanci.extension.getAttachmentType import com.cmoney.kolfanci.extension.toUploadFileItem import com.cmoney.kolfanci.extension.toUploadFileItemMap import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem import com.cmoney.kolfanci.model.attachment.AttachmentType import com.cmoney.kolfanci.model.attachment.ReSendFile import com.cmoney.kolfanci.model.usecase.AttachmentUseCase import com.cmoney.kolfanci.model.usecase.UploadImageUseCase import com.cmoney.kolfanci.model.usecase.VoteUseCase import com.cmoney.kolfanci.model.vote.VoteModel import com.socks.library.KLog import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.toList import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class AttachmentViewModel( val context: Application, val attachmentUseCase: AttachmentUseCase, val uploadImageUseCase: UploadImageUseCase, val voteUseCase: VoteUseCase ) : AndroidViewModel(context) { private val TAG = AttachmentViewModel::class.java.simpleName //附加檔案 (依照加入順序) private val _attachmentList = MutableStateFlow<List<Pair<AttachmentType, AttachmentInfoItem>>>(emptyList()) val attachmentList = _attachmentList.asStateFlow() //附加檔案 (有分類聚合) - 來源 -> _attachmentList private val _attachment = MutableStateFlow<Map<AttachmentType, List<AttachmentInfoItem>>>(emptyMap()) val attachment = _attachment.asStateFlow() //是否全部檔案 上傳完成 private val _uploadComplete = MutableStateFlow<Pair<Boolean, Any?>>(false to null) val uploadComplete = _uploadComplete.asStateFlow() //有上傳失敗的檔案 private val _uploadFailed = MutableStateFlow(false) val uploadFailed = _uploadFailed.asStateFlow() //附加檔案,只有image類型 private val _isOnlyPhotoSelector = MutableStateFlow<Boolean>(false) val isOnlyPhotoSelector = _isOnlyPhotoSelector.asStateFlow() //資料是否初始化完成 private val _setInitDataSuccess = MutableStateFlow(false) val setInitDataSuccess = _setInitDataSuccess.asStateFlow() init { viewModelScope.launch { _attachmentList.collect { attachmentList -> _attachment.update { attachmentList.groupBy { it.first }.mapValues { entry -> entry.value.map { it.second } } } } } } /** * 附加檔案, 區分 類型 */ fun attachment(uris: List<Uri>) { val oldList = _attachmentList.value.toMutableList() oldList.addAll( uris.map { uri -> val attachmentType = uri.getAttachmentType(context) attachmentType to uri.toUploadFileItem(context = context) } ) _attachmentList.update { oldList } } /** * 附加檔案為錄音時,設定它的attachmentType */ fun setRecordingAttachmentType(uri: Uri?) { if (uri != null){ val oldList = _attachmentList.value.toMutableList() val attachmentType = AttachmentType.VoiceMessage val recordItem = uri.toUploadFileItem(context = context).copy( filename = "錄音" ) oldList.add( Pair(attachmentType,recordItem) ) _attachmentList.update { oldList } KLog.i(TAG,"_attachmentList: ${_attachmentList.value}" ) } } /** * 移除 附加 檔案 * @param attachmentInfoItem */ fun removeAttach(attachmentInfoItem: AttachmentInfoItem) { KLog.i(TAG, "removeAttach:$attachmentInfoItem") _attachmentList.update { _attachmentList.value.filter { it.second != attachmentInfoItem } } } /** * 執行上傳動作, 將未處理檔案改為 pending, 並執行上傳 * * @param channelId 頻道 id * @param other 檔案之外的東西, ex: text 內文 */ fun upload( channelId: String, other: Any? = null ) { KLog.i(TAG, "upload file:$channelId") viewModelScope.launch { statusToPending() val uploadList = _attachmentList.value //圖片處理 val imageFiles = uploadList.filter { it.first == AttachmentType.Image && it.second.status == AttachmentInfoItem.Status.Pending }.map { it.second.uri } val allImages = uploadImageUseCase.uploadImage2(imageFiles).toList() //todo ----- for test start ----- //為了測試 上傳失敗 // val testItem = allImages.first().copy( // status = UploadFileItem.Status.Failed("") // ) // allImages.toMutableList().apply { // this[0] = testItem // allImages = this // } //todo ----- for test end ----- //投票 val voteModelList = uploadList.filter { it.first == AttachmentType.Choice && it.second.status == AttachmentInfoItem.Status.Pending && it.second.other is VoteModel }.map { it.second.other as VoteModel } val voteFiles = voteUseCase.createVotes( channelId = channelId, voteModels = voteModelList ).toList().map { vote -> AttachmentInfoItem( status = AttachmentInfoItem.Status.Success, other = vote, attachmentType = AttachmentType.Choice ) } //其他 val otherFiles = uploadList.filter { it.first != AttachmentType.Image && it.first != AttachmentType.Choice && it.second.status == AttachmentInfoItem.Status.Pending }.map { it.second.uri } val allOtherFiles = attachmentUseCase.uploadFile(otherFiles).toList() updateAttachmentList( imageFiles = allImages, voteFiles = voteFiles, otherFiles = allOtherFiles, other = other ) } } /** * 更新 資料, 刷新附加檔案畫面 * 並檢查是否有失敗的 */ private fun updateAttachmentList( imageFiles: List<AttachmentInfoItem>, voteFiles: List<AttachmentInfoItem>, otherFiles: List<AttachmentInfoItem>, other: Any? = null ) { val allItems = imageFiles.reversed().distinctBy { it.uri } + voteFiles.reversed().distinctBy { it.other } + otherFiles.reversed().distinctBy { it.uri } val newList = _attachmentList.value.map { val key = it.first val oldItem = it.second val newStatusItem = allItems.firstOrNull { newItem -> if (newItem.attachmentType == AttachmentType.Choice) { (newItem.other as VoteModel).question == (oldItem.other as VoteModel).question } else { newItem.uri == oldItem.uri } } if (newStatusItem != null) { key to newStatusItem } else { key to oldItem } } _attachmentList.update { newList } val hasFailed = _attachmentList.value.any { pairItem -> val item = pairItem.second item.status is AttachmentInfoItem.Status.Failed } if (hasFailed) { _uploadFailed.value = true } else { _uploadComplete.value = (true to other) } } /** * 將檔案狀態 Undefine 改為 Pending */ private fun statusToPending() { KLog.i(TAG, "statusToPending") val newList = _attachmentList.value.map { val key = it.first val uploadItem = it.second val newUploadItem = uploadItem.copy( status = if (uploadItem.status == AttachmentInfoItem.Status.Undefined) { AttachmentInfoItem.Status.Pending } else { uploadItem.status } ) key to newUploadItem } _attachmentList.update { newList } } fun finishPost() { _uploadComplete.update { false to null } } fun clearUploadFailed() { _uploadFailed.update { false } } /** * 重新再次上傳,針對單一檔案處理 * * @param channelId 頻道 id * @param uploadFileItem 需要重新上傳的檔案 * @param other 檔案之外的東西, ex: text 內文 */ fun onResend( channelId: String, uploadFileItem: ReSendFile, other: Any? = null ) { KLog.i(TAG, "onResend:$uploadFileItem") viewModelScope.launch { val file = uploadFileItem.attachmentInfoItem.uri var allImages = emptyList<AttachmentInfoItem>() if (uploadFileItem.type == AttachmentType.Image) { allImages = uploadImageUseCase.uploadImage2(listOf(file)).toList() } var allVotes = emptyList<AttachmentInfoItem>() if (uploadFileItem.type == AttachmentType.Choice) { uploadFileItem.attachmentInfoItem.other?.let { other -> if (other is VoteModel) { allVotes = voteUseCase.createVotes( channelId = channelId, voteModels = listOf(other) ).toList().map { vote -> AttachmentInfoItem( status = AttachmentInfoItem.Status.Success, other = vote ) } } } } val allOtherFiles = attachmentUseCase.uploadFile(listOf(file)).toList() updateAttachmentList( imageFiles = allImages, voteFiles = allVotes, otherFiles = allOtherFiles, other = other ) } } fun clear() { KLog.i(TAG, "clear") _attachmentList.update { emptyList() } } /** * 將已經上傳的資料 加入清單 */ fun addAttachment(mediaList: List<Media>) { KLog.i(TAG, "addAttachment:" + mediaList.size) viewModelScope.launch { val attachmentMap = mediaList.toUploadFileItemMap() val attachmentList = attachmentMap.map { mapItem -> val key = mapItem.key val value = mapItem.value value.map { key to it } }.flatten() _attachmentList.update { attachmentList } } } /** * 取得 目前該 uri 所屬的類別 */ fun getAttachmentType(uri: Uri): AttachmentType? = _attachmentList.value.filter { it.second.uri == uri }.map { it.first }.firstOrNull() /** * 點擊 附加功能 */ fun onAttachClick() { KLog.i(TAG, "onAttachClick") _isOnlyPhotoSelector.update { false } } /** * 附加圖片 點擊更多圖片 */ fun onAttachImageAddClick() { KLog.i(TAG, "onImageAddClick") _isOnlyPhotoSelector.update { true } } /** * 新增/更新 選擇題 * 檢查 id 是否存在 就更新 否則 新增 */ fun addChoiceAttachment(voteModel: VoteModel) { KLog.i(TAG, "addChoiceAttachment") val oldList = _attachmentList.value.toMutableList() val filterList = oldList.filter { pairItem -> val otherModel = pairItem.second.other if (otherModel is VoteModel) { return@filter otherModel.id != voteModel.id } true }.toMutableList() filterList.add( AttachmentType.Choice to AttachmentInfoItem( other = voteModel, attachmentType = AttachmentType.Choice ) ) val distinctList = filterList.distinctBy { it -> val other = it.second.other if (other is VoteModel) { other.id } else { it } } _attachmentList.update { distinctList } } fun setDataInitFinish() { _setInitDataSuccess.update { true } } /** * 刪除多餘的投票 * * @param channelId 頻道 id * @param oldVoting 原本的投票 List */ fun deleteVotingCheck( channelId: String, oldVoting: List<Voting> ) { KLog.i(TAG, "deleteVotingCheck:$channelId") viewModelScope.launch { val newVoting = _attachmentList.value.filter { it.first == AttachmentType.Choice && (it.second.other is VoteModel) }.map { (it.second.other as VoteModel).id } val deleteItem = oldVoting.filter { !newVoting.contains(it.id.toString()) } voteUseCase.deleteVote( channelId = channelId, voteIds = deleteItem.map { it.id ?: "" } ).onSuccess { KLog.i(TAG, it) }.onFailure { KLog.e(TAG, it) } } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/viewmodel/AttachmentViewModel.kt
2656044139
package com.cmoney.kolfanci.model.notification import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class Payload ( val sn: Long?, val title: String, val message: String, val commonTargetType: Int, val commonParameter: String, val targetType: Int, val parameter: String, val analyticsId: Long?, val deeplink: String? ): Parcelable { companion object{ //type enum const val TYPE_1 = 1 //社團邀請 const val TYPE_2 = 2 //進入聊天區, 並跳往該訊息 const val TYPE_3 = 3 //打開貼文詳細頁面 const val TYPE_4 = 4 //社團解散 const val TYPE_5 = 5 //管理者, 前往申請加入審核頁面 const val TYPE_6 = 6 //打開指定社團 } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/notification/Payload.kt
3226017798
package com.cmoney.kolfanci.model.notification import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize sealed class TargetType : Parcelable { /** * 打開首頁 */ @Parcelize object MainPage : TargetType() /** * 邀請 加入社團 */ @Parcelize data class InviteGroup( @SerializedName("groupId", alternate = ["GroupId"]) val groupId: String = "" ) : TargetType() /** * 收到 社團訊息 */ @Parcelize data class ReceiveMessage( @SerializedName("groupId", alternate = ["GroupId"]) val groupId: String = "", @SerializedName("messageId", alternate = ["MessageId"]) val messageId: String = "", @SerializedName("channelId", alternate = ["ChannelId"]) val channelId: String = "", ) : TargetType() /** * 收到 社團貼文 */ @Parcelize data class ReceivePostMessage( @SerializedName("groupId", alternate = ["GroupId"]) val groupId: String = "", @SerializedName("channelId", alternate = ["ChannelId"]) val channelId: String = "", @SerializedName("messageId", alternate = ["MessageId"]) val messageId: String = "", ) : TargetType() /** * 解散 社團 */ @Parcelize data class DissolveGroup( @SerializedName("groupId", alternate = ["GroupId"]) val groupId: String = "" ) : TargetType() /** * 管理者, 前往申請加入審核頁面 */ @Parcelize data class GroupApprove( @SerializedName("groupId", alternate = ["GroupId"]) val groupId: String = "" ) : TargetType() /** * 打開指定社團 */ @Parcelize data class OpenGroup( @SerializedName("groupId", alternate = ["GroupId"]) val groupId: String = "" ) : TargetType() }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/notification/TargetType.kt
3307853549
package com.cmoney.kolfanci.model.notification import android.app.Application import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.content.Intent import android.media.RingtoneManager import android.net.Uri import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.text.isDigitsOnly import com.cmoney.kolfanci.R import com.cmoney.kolfanci.extension.fromJson import com.google.gson.Gson import com.google.gson.JsonParseException import com.google.gson.JsonSyntaxException import com.socks.library.KLog import org.json.JSONObject import java.net.URLDecoder class NotificationHelper( val context: Application, val gson: Gson ) { private val TAG = NotificationHelper::class.java.simpleName private val DEFAULT_CHANNEL_ID = context.getString(R.string.default_notification_channel_id) private val DEFAULT_CHANNEL_ID_MESSAGE = context.getString(R.string.default_notification_channel_message) private val manager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager init { createChannels() } private fun createChannels() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { var default = manager.getNotificationChannel(DEFAULT_CHANNEL_ID) if (default == null) { default = NotificationChannel( DEFAULT_CHANNEL_ID, DEFAULT_CHANNEL_ID_MESSAGE, NotificationManager.IMPORTANCE_DEFAULT ) manager.createNotificationChannel(default) } default.lockscreenVisibility = Notification.VISIBILITY_PUBLIC } } fun getPayloadFromForeground(customNotification: CustomNotification): Payload { val commonParameter = customNotification.commonParameter val commonTargetType = customNotification.commonTargetType val targetType = customNotification.targetType val title = customNotification.title val message = customNotification.message val sn = customNotification.sn val analyticsId = customNotification.analyticsId val parameter = customNotification.parameter val deeplink = customNotification.deeplink return Payload( sn = sn, title = title, message = message, commonTargetType = commonTargetType, commonParameter = commonParameter, targetType = targetType, parameter = parameter, analyticsId = analyticsId, deeplink = deeplink ) } fun getPayloadFromBackground(intent: Intent): Payload? { KLog.d("notification", "getPayloadFromBackground") val bundle = intent.extras ?: return null val customTargetType = bundle.get(CustomNotification.CUSTOM_TARGET_TYPE).toString().toIntOrNull() ?: return null val sn = bundle.getString(CustomNotification.SN)?.toLongOrNull() val title = bundle.getString(CustomNotification.TITLE).orEmpty() val message = bundle.getString(CustomNotification.MESSAGE).orEmpty() val targetType = if (customTargetType == -1) { bundle.getString(CustomNotification.TARGET_TYPE)?.toIntOrNull() ?: 0 } else { customTargetType } val parameter = bundle.getString(CustomNotification.PARAMETER).orEmpty() val commonTargetType = bundle.getString(CustomNotification.COMMON_TARGET_TYPE)?.toIntOrNull() ?: 0 val commonParameter = bundle.getString(CustomNotification.COMMON_PARAMETER).orEmpty() val analyticsId = bundle.getString(CustomNotification.ANALYTICS_ID)?.toLongOrNull() val deeplink = bundle.getString(CustomNotification.DEEPLINK).orEmpty() return Payload( sn = sn, title = title, message = message, commonTargetType = commonTargetType, commonParameter = commonParameter, targetType = targetType, parameter = parameter, analyticsId = analyticsId, deeplink = deeplink ) } fun getShareIntentPayload(uri: Uri): Payload { val decodeString = URLDecoder.decode(uri.toString(), "UTF-8") val decodeUrl = Uri.parse(decodeString) val customTargetType = decodeUrl.getQueryParameter("commonTargetType")?.toIntOrNull() ?: -1 var targetType = if (customTargetType == -1) { decodeUrl.getQueryParameter("targetType")?.toIntOrNull() ?: 0 } else { customTargetType } val groupId = decodeUrl.getQueryParameter("groupId").orEmpty() val deeplink = decodeUrl.getQueryParameter("deeplink").orEmpty() if (deeplink.isNotEmpty()) { targetType = 0 } return Payload( title = "", message = "", targetType = targetType, parameter = Gson().toJson(GroupModel(groupId)), analyticsId = null, commonParameter = "", commonTargetType = targetType, sn = null, deeplink = deeplink ) } private class GroupModel(val groupId: String) /** * payload.deeplink ex:"https://www.fanci.com.tw/landing?targetType=2&serialNumber=2455&groupId=27444&channelId=31913" */ fun convertPayloadToTargetType(payload: Payload): TargetType? { KLog.i(TAG, "convertPayloadToTargetType:" + payload.targetType) return when (payload.targetType) { 0 -> { if (payload.deeplink?.isNotEmpty() == true) { val uri = Uri.parse(payload.deeplink) val targetTypeLowCase = uri.getQueryParameter("targetType") val targetTypeHighCase = uri.getQueryParameter("TargetType") val targetTypeStr = targetTypeLowCase ?: targetTypeHighCase if (targetTypeStr?.isDigitsOnly() == false) { return null } val targetType = targetTypeStr?.toInt() ?: 0 if (targetType == 0) { return null } val jsonObject = JSONObject() val allKey = uri.queryParameterNames for (key in allKey) { val value = uri.getQueryParameter(key) jsonObject.put(key, value) } val parameter = jsonObject.toString() val payload = payload.copy( targetType = targetType, parameter = parameter ) return convertPayloadToTargetType(payload) } null } Payload.TYPE_1 -> { getParameter<TargetType.InviteGroup>(payload.parameter) } Payload.TYPE_2 -> { getParameter<TargetType.ReceiveMessage>(payload.parameter) } Payload.TYPE_3 -> { getParameter<TargetType.ReceivePostMessage>(payload.parameter) } Payload.TYPE_4 -> { getParameter<TargetType.DissolveGroup>(payload.parameter) } Payload.TYPE_5 -> { getParameter<TargetType.GroupApprove>(payload.parameter) } Payload.TYPE_6 -> { getParameter<TargetType.OpenGroup>(payload.parameter) } else -> getParameter<TargetType.InviteGroup>(payload.parameter) } } private inline fun <reified T> getParameter(originalMessage: String): T? { return try { gson.fromJson<T>(originalMessage) } catch (e: JsonSyntaxException) { null } catch (e: JsonParseException) { null } } fun getStyle0(title: String, body: String): NotificationCompat.Builder { return NotificationCompat.Builder(context, DEFAULT_CHANNEL_ID) .setSmallIcon(R.drawable.status_icon) // .setColor(ContextCompat.getColor(this, R.color.color_ddaf78)) .setCategory(NotificationCompat.CATEGORY_MESSAGE) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setAutoCancel(true) .setWhen(System.currentTimeMillis()) .setContentTitle(title) .setContentText(body) .setStyle( NotificationCompat.BigTextStyle() .setBigContentTitle(title) .bigText(body) ) } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/notification/NotificationHelper.kt
3088167229
package com.cmoney.kolfanci.model.notification import android.content.Intent import com.google.firebase.messaging.RemoteMessage /** * 將 推播訊息 以及 dynamic link 資料 轉為統一物件使用 * * @property title 標題 * @property message 訊息內容 * @property sound 音效 * @property targetType 目標類型 * @property commonTargetType 通用目標類型 * @property commonParameter 通用參數 * @property sn 推播序號 * @property analyticsId 統計用編號 * @property deeplink 跳轉連結 */ class CustomNotification { val title: String val message: String val sound: String val targetType: Int val parameter: String val commonTargetType: Int val commonParameter: String val sn: Long? val analyticsId: Long? val deeplink: String? constructor(intent: Intent?) { val customTargetType = intent?.extras?.get(CUSTOM_TARGET_TYPE) as? Int? ?: -1 message = intent?.getStringExtra(MESSAGE).orEmpty() title = intent?.getStringExtra(TITLE).orEmpty() sound = intent?.getStringExtra(SOUND).orEmpty() targetType = if (customTargetType == -1) { intent?.getStringExtra(TARGET_TYPE)?.toIntOrNull() ?: 0 } else { customTargetType } parameter = intent?.getStringExtra(PARAMETER).orEmpty() commonTargetType = intent?.getStringExtra(COMMON_TARGET_TYPE)?.toIntOrNull() ?: 0 commonParameter = intent?.getStringExtra(COMMON_PARAMETER).orEmpty() sn = intent?.getStringExtra(SN)?.toLongOrNull() analyticsId = intent?.getStringExtra(ANALYTICS_ID)?.toLongOrNull() deeplink = intent?.getStringExtra(DEEPLINK).orEmpty() } constructor(remoteMessage: RemoteMessage?) { val data = remoteMessage?.data val customTargetType = data?.get(CUSTOM_TARGET_TYPE)?.toIntOrNull() ?: -1 message = data?.get(MESSAGE).orEmpty() title = data?.get(TITLE).orEmpty() sound = data?.get(SOUND).orEmpty() targetType = if (customTargetType == -1) { data?.get(TARGET_TYPE)?.toIntOrNull() ?: 0 } else { customTargetType } parameter = data?.get(PARAMETER).orEmpty() commonTargetType = data?.get(COMMON_TARGET_TYPE)?.toIntOrNull() ?: 0 commonParameter = data?.get(COMMON_PARAMETER).orEmpty() sn = data?.get(SN)?.toLongOrNull() analyticsId = data?.get(ANALYTICS_ID)?.toLongOrNull() deeplink = data?.get(DEEPLINK).orEmpty() } companion object { const val SN = "sn" const val TITLE = "title" const val SOUND = "sound" const val MESSAGE = "msg" const val TARGET_TYPE = "targetType" const val PARAMETER = "parameter" const val COMMON_TARGET_TYPE = "commonTargetType" const val COMMON_PARAMETER = "commonParameter" const val ANALYTICS_ID = "analyticsId" const val CUSTOM_TARGET_TYPE = "targetType" const val DEEPLINK = "deeplink" } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/notification/CustomNotification.kt
2455133847
package com.cmoney.kolfanci.model.notification import com.cmoney.kolfanci.ui.screens.notification.NotificationCenterData import com.cmoney.kolfanci.utils.Utils import com.google.gson.annotations.SerializedName data class NotificationHistory( @SerializedName("items") val items: List<Item>? = listOf(), @SerializedName("paging") val paging: Paging? = Paging() ) { data class Item( @SerializedName("body") val body: String? = null, @SerializedName("createTime") val createTime: Int = 0, @SerializedName("hasClicked") val hasClicked: Boolean = false, @SerializedName("iconUrl") val iconUrl: String? = null, @SerializedName("imageUrl") val imageUrl: String? = null, @SerializedName("link") val link: String? = null, @SerializedName("notificationId") val notificationId: String? = null ) data class Paging( @SerializedName("next") val next: String? = null ) } fun NotificationHistory.Item.toNotificationCenterData(): NotificationCenterData { val splitStr = body?.split("<br>").orEmpty() val title = splitStr.firstOrNull().orEmpty() val description = if (splitStr.size > 1) { splitStr[1] } else { "" } return NotificationCenterData( notificationId = notificationId.orEmpty(), image = imageUrl.orEmpty(), title = title, description = description, deepLink = link.orEmpty(), isRead = hasClicked, displayTime = Utils.timesMillisToDate( createTime.toLong().times(1000) ) ) }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/notification/NotificationHistory.kt
430438182
package com.cmoney.kolfanci.model.attachment import android.content.Context import android.net.Uri import com.cmoney.fanciapi.fanci.model.AudioContent import com.cmoney.fanciapi.fanci.model.ImageContent import com.cmoney.fanciapi.fanci.model.Media import com.cmoney.fanciapi.fanci.model.PdfContent import com.cmoney.fanciapi.fanci.model.TxtContent import com.cmoney.fanciapi.fanci.model.VoiceMessageContent import com.cmoney.kolfanci.extension.getAudioDuration /** * 將附加檔案 List 轉為, 上傳用的 Media List */ fun List<Pair<AttachmentType, AttachmentInfoItem>>.toUploadMedia(context: Context): List<Media> { val medias = mutableListOf<Media>() //處理 附加檔案 this.forEach { item -> val attachmentType = item.first val attachmentInfo = item.second val file = attachmentInfo.uri val serverUrl = attachmentInfo.serverUrl val fileName = attachmentInfo.filename val fileSize = attachmentInfo.fileSize when (attachmentType) { AttachmentType.VoiceMessage -> Media( resourceLink = serverUrl, type = AttachmentType.VoiceMessage.name, voiceMessage = VoiceMessageContent( fileName = fileName, fileSize = fileSize, duration = file.getAudioDuration(context) ) ) AttachmentType.Audio -> Media( resourceLink = serverUrl, type = AttachmentType.Audio.name, audio = AudioContent( fileName = fileName, fileSize = fileSize, duration = file.getAudioDuration(context) ) ) AttachmentType.Image -> Media( resourceLink = serverUrl, type = AttachmentType.Image.name, image = ImageContent() ) AttachmentType.Pdf -> Media( resourceLink = serverUrl, type = AttachmentType.Pdf.name, pdf = PdfContent( fileName = fileName, fileSize = fileSize, ) ) AttachmentType.Txt -> Media( resourceLink = serverUrl, type = AttachmentType.Txt.name, txt = TxtContent( fileName = fileName, fileSize = fileSize, ) ) AttachmentType.Unknown -> { null } AttachmentType.Choice -> { null } }?.apply { medias.add(this) } } return medias } /** * 附加檔案 fanci 支援類型 */ sealed class AttachmentType { abstract val name: String object VoiceMessage : AttachmentType() { override val name: String get() = "VoiceMessage" } object Image : AttachmentType() { override val name: String get() = "Image" } object Audio : AttachmentType() { override val name: String get() = "Audio" } object Txt : AttachmentType() { override val name: String get() = "Txt" } object Pdf : AttachmentType() { override val name: String get() = "Pdf" } object Unknown : AttachmentType() { override val name: String get() = "" } /** * 選擇題 */ object Choice : AttachmentType() { override val name: String get() = "" } } /** * 檔案 上傳狀態 * * @param uri 上傳的檔案 * @param status 上傳狀態 * @param serverUrl 上傳成功後 拿到的 url * @param filename 檔案名稱 * @param fileSize 檔案大小 * @param duration 音檔長度 (option) * @param other 其他類型 model (option) (目前有的Model: VoteModel) * @param attachmentType 檔案類型 */ data class AttachmentInfoItem( val uri: Uri = Uri.EMPTY, val status: Status = Status.Undefined, val serverUrl: String = "", val filename: String = "", val fileSize: Long = 0, val duration: Long? = 0, val other: Any? = null, val attachmentType: AttachmentType = AttachmentType.Unknown ) { /** * 檔案上傳狀態 * @param description 說明 */ sealed class Status(description: String = "") { //還未確定要上傳 object Undefined : Status() //等待上傳中 object Pending : Status() //上傳成功 object Success : Status() //上傳中 object Uploading : Status() //上傳失敗 data class Failed(val reason: String) : Status(reason) } /** * 附加檔案 item, 是否可以點擊預覽 */ fun isAttachmentItemClickable(): Boolean = (status == Status.Undefined || status == Status.Success) } /** * 重新上傳檔案 info * * @param type 檔案類型 * @param attachmentInfoItem 附加檔案 * @param title dialog title * @param description dialog content */ data class ReSendFile( val type: AttachmentType, val attachmentInfoItem: AttachmentInfoItem, val title: String, val description: String )
Fanci/app/src/main/java/com/cmoney/kolfanci/model/attachment/Attachment.kt
1747223896
package com.cmoney.kolfanci.model.mock import com.cmoney.fanciapi.fanci.model.BulletinboardMessage import com.cmoney.fanciapi.fanci.model.Category import com.cmoney.fanciapi.fanci.model.Channel import com.cmoney.fanciapi.fanci.model.ChannelPrivacy import com.cmoney.fanciapi.fanci.model.ChannelTabType import com.cmoney.fanciapi.fanci.model.ChatMessage import com.cmoney.fanciapi.fanci.model.DeleteStatus import com.cmoney.fanciapi.fanci.model.FanciRole import com.cmoney.fanciapi.fanci.model.Group import com.cmoney.fanciapi.fanci.model.GroupMember import com.cmoney.fanciapi.fanci.model.IChannelTab import com.cmoney.fanciapi.fanci.model.IEmojiCount import com.cmoney.fanciapi.fanci.model.IReplyMessage import com.cmoney.fanciapi.fanci.model.IReplyVoting import com.cmoney.fanciapi.fanci.model.IUserVoteInfo import com.cmoney.fanciapi.fanci.model.IVotingOptionStatistic import com.cmoney.fanciapi.fanci.model.IVotingOptionStatisticWithVoter import com.cmoney.fanciapi.fanci.model.IVotingOptionStatistics import com.cmoney.fanciapi.fanci.model.IVotingOptionStatisticsWithVoter import com.cmoney.fanciapi.fanci.model.ImageContent import com.cmoney.fanciapi.fanci.model.Media import com.cmoney.fanciapi.fanci.model.MediaIChatContent import com.cmoney.fanciapi.fanci.model.MessageServiceType import com.cmoney.fanciapi.fanci.model.PushNotificationSetting import com.cmoney.fanciapi.fanci.model.PushNotificationSettingType import com.cmoney.fanciapi.fanci.model.Voting import com.cmoney.kolfanci.BuildConfig import com.cmoney.kolfanci.model.attachment.AttachmentType import com.cmoney.kolfanci.model.vote.VoteModel import com.cmoney.kolfanci.ui.screens.group.setting.group.notification.PushNotificationSettingWrap import com.cmoney.kolfanci.ui.screens.notification.NotificationCenterData import com.cmoney.kolfanci.ui.screens.post.viewmodel.PostViewModel import org.apache.commons.lang3.RandomStringUtils import kotlin.random.Random object MockData { val mockVote = VoteModel( id = System.currentTimeMillis().toString(), question = "What is indicated about advertising space on the Mooringtown Library notice board?", choice = listOf( "(A) complication", "(B) complicates", "(C) complicate", "(D) complicated" ), isSingleChoice = true ) val mockGroup: Group = Group( id = "", name = "愛莉莎莎Alisasa", description = "大家好,我是愛莉莎莎Alisasa!\n" + "\n" + "台灣人在韓國留學八個月 \n" + "已經在2018 一月\n" + "回到台灣當全職Youtuber囉!\n" + "\n" + "但是我還是每個月會去韓國\n" + "更新最新的韓國情報 (流行 美妝 美食等等) \n" + "提供給大家不同於一般觀光客\n" + "內行的認識韓國新角度\n" + "\n" + "另外也因為感情經驗豐富(?)\n" + "可以提供給大家一些女生的秘密想法~\n" + "\n" + "希望大家喜歡我的頻道^^\n" + "\n" + "\n" + "如果你喜歡我的影片,希望你可以幫我訂閱+分享\n" + "\n" + "任何合作邀約請洽Pressplay Email :\n" + "[email protected]\n" + "═════════════════════════════════════\n" + "\n" + "追蹤我 Follow Me \n" + "\n" + "★Facebook社團『愛莉莎莎敗家基地』: https://www.facebook.com/groups/924974291237889/\n" + "★Facebook粉絲專頁: https://www.facebook.com/alisasa11111/\n" + "★Instagram: goodalicia", coverImageUrl = "https://img.ltn.com.tw/Upload/health/page/800/2021/02/14/phpo5UnZT.png", thumbnailImageUrl = "https://picsum.photos/${ Random.nextInt( 100, 300 ) }/${Random.nextInt(100, 300)}", categories = listOf( Category( name = "一般分類", channels = listOf( mockChannelPublic, mockChannelPrivate ) ) ) ) val mockChannelPublic: Channel get() { val id = Random.nextInt(0, 20).toString() return Channel( id = id, name = "測試頻道 $id", privacy = ChannelPrivacy.public, tabs = listOf( IChannelTab( type = ChannelTabType.bulletinboard ), IChannelTab( type = ChannelTabType.chatRoom ) ), channelType = ChannelTabType.bulletinboard ) } val mockChannelPrivate: Channel get() = mockChannelPublic.copy( privacy = ChannelPrivacy.private ) val mockNotificationSettingItem: PushNotificationSetting = PushNotificationSetting( settingType = PushNotificationSettingType.newPost, title = "有任何新動態都提醒我", description = "所有新內容,與我的內容有人回饋時請提醒我", shortTitle = "新動態都提醒我" ) val mockNotificationSettingItemWrapList: List<PushNotificationSettingWrap> = listOf( PushNotificationSettingWrap( pushNotificationSetting = mockNotificationSettingItem, isChecked = true ), PushNotificationSettingWrap( pushNotificationSetting = mockNotificationSettingItem, isChecked = false ), PushNotificationSettingWrap( pushNotificationSetting = mockNotificationSettingItem, isChecked = false ) ) /** * 推播中心 假資料 */ val mockNotificationCenter: List<NotificationCenterData> get() { return if (BuildConfig.DEBUG) { val kindSize = mockNotificationCenterKind.size (1..Random.nextInt(2, 20)).map { mockNotificationCenterKind[Random.nextInt(0, kindSize)] } } else { emptyList() } } /** * 所有 推播 種類 */ private val mockNotificationCenterKind = listOf<NotificationCenterData>( NotificationCenterData( notificationId = "", image = "https://picsum.photos/${ Random.nextInt( 100, 300 ) }/${Random.nextInt(100, 300)}", title = "聊天室有新訊息", description = "[藝術學院小公主的小畫廊\uD83C\uDFA8] 社團有新訊息", deepLink = "{\"targetType\": 2, \"serialNumber\" : \"2455\" , \"groupId\" : \"27444\", \"channelId\": \"31913\"}", isRead = Random.nextBoolean(), displayTime = "剛剛" ), NotificationCenterData( notificationId = "", image = "https://picsum.photos/${ Random.nextInt( 100, 300 ) }/${Random.nextInt(100, 300)}", title = "邀請加入社團", description = "[藝術學院小公主的小畫廊\uD83C\uDFA8] 社團", deepLink = "{\"targetType\": 1, \"groupId\": \"27444\"}", isRead = Random.nextBoolean(), displayTime = "剛剛" ), NotificationCenterData( notificationId = "", image = "https://picsum.photos/${ Random.nextInt( 100, 300 ) }/${Random.nextInt(100, 300)}", title = "有新文章", description = "[藝術學院小公主的小畫廊\uD83C\uDFA8] 社團有新文章", deepLink = "{\"targetType\": 3, \"messageId\" : \"151547560\" , \"groupId\" : \"27444\", \"channelId\": \"31913\"}", isRead = Random.nextBoolean(), displayTime = "剛剛" ), NotificationCenterData( notificationId = "", image = "https://picsum.photos/${ Random.nextInt( 100, 300 ) }/${Random.nextInt(100, 300)}", title = "社團解散", description = " [XLAB-405] 社團解散了", deepLink = "{\"targetType\": 4, \"groupId\" : \"28557\"}", isRead = Random.nextBoolean(), displayTime = "剛剛" ) ) /** * 會員 假資料 */ val mockGroupMember: GroupMember get() { return if (BuildConfig.DEBUG) { GroupMember( name = RandomStringUtils.randomAlphabetic(10), thumbNail = "https://picsum.photos/${ Random.nextInt( 100, 300 ) }/${Random.nextInt(100, 300)}", isGroupVip = Random.nextBoolean(), roleInfos = listOf( FanciRole( name = "Role", color = "" ) ) ) } else { GroupMember() } } val mockListMessage: List<ChatMessage> get() { return if (BuildConfig.DEBUG) { (1..Random.nextInt(2, 10)).map { mockReplyMessage }.apply { // val mutableList = this.toMutableList() // mutableList.add(mockReplyMessage) } } else { emptyList() } } //聊天室訊息 val mockMessage: ChatMessage get() { return if (BuildConfig.DEBUG) { ChatMessage( id = Random.nextInt(1, 999).toString(), author = mockGroupMember, emojiCount = IEmojiCount( like = Random.nextInt(1, 999), laugh = Random.nextInt(1, 999), money = Random.nextInt(1, 999), shock = Random.nextInt(1, 999), cry = Random.nextInt(1, 999), think = Random.nextInt(1, 999), angry = Random.nextInt(1, 999) ), content = MediaIChatContent( text = "大學時期時想像的出社會的我\n" + "就是這個樣子吧!!\n" + "穿著西裝匆忙地走在大樓間\n" + "再來有一個幻想是:(這是真的哈哈哈)\n" + "因為我發現很多台灣人都有自己的水壺 (韓國以前沒有這個文化)\n" + "心裡想…我以後也要有一個哈哈哈哈在辦公室喝嘻嘻\n" + "最近水壺越來越厲害了也\n" + "WOKY的水壺也太好看了吧!!!\n" + "不僅有9個顏色 選項超多\n" + "它是770ML大大的容量\n" + "超適合外帶手搖飲在辦公喝哈哈\n" + "再來是我最重視的!\n" + "它的口很大\n" + "而且是鈦陶瓷的關係容易清潔\n" + "裝咖啡、果汁都不沾色不卡味\n" + "我命名為~Fancy Cutie 一波呦 渾圓杯\n" + "太好看了 我不會忘記帶它出門的^^\n" + "最近還有在持續執行多喝水計畫\n" + "大家如果也剛好有需要水壺\n" + "可以參考看看一起多喝水", medias = (1..Random.nextInt(2, 10)).map { Media( resourceLink = "https://picsum.photos/${ Random.nextInt( 100, 300 ) }/${Random.nextInt(100, 300)}", type = AttachmentType.Image.name ) } ), createUnixTime = System.currentTimeMillis().div(1000), serialNumber = Random.nextLong(1, 65536), votings = listOf( mockSingleVoting ) ) } else { ChatMessage() } } val mockReplyMessage: ChatMessage get() { return if (BuildConfig.DEBUG) { ChatMessage( author = mockGroupMember, emojiCount = IEmojiCount( like = Random.nextInt(1, 999), laugh = Random.nextInt(1, 999), money = Random.nextInt(1, 999), shock = Random.nextInt(1, 999), cry = Random.nextInt(1, 999), think = Random.nextInt(1, 999), angry = Random.nextInt(1, 999) ), content = MediaIChatContent( text = "回覆訊息", medias = (1..Random.nextInt(2, 10)).map { Media( resourceLink = "https://picsum.photos/${ Random.nextInt( 100, 300 ) }/${Random.nextInt(100, 300)}", type = AttachmentType.Image.name ) } ), createUnixTime = System.currentTimeMillis().div(1000), serialNumber = Random.nextLong(1, 65536), votings = listOf( mockSingleVoting ), replyMessage = IReplyMessage( author = mockGroupMember, content = MediaIChatContent( text = "訊息內文" ), replyVotings = listOf( IReplyVoting( title = "✈️ 投票決定我去哪裡玩!史丹利這" ) ) ) ) } else { ChatMessage() } } //貼文 val mockBulletinboardMessage: BulletinboardMessage get() = BulletinboardMessage( replyMessage = null, votings = listOf( mockSingleVoting, mockMultiVoting ), messageFromType = MessageServiceType.bulletinboard, author = GroupMember( id = "637447b722171bd081b1521b", name = "Boring12", thumbNail = "https://cm-176-test.s3-ap-northeast-1.amazonaws.com/images/d230fca7-d202-4208-8547-2c20016ee99d.jpeg", serialNumber = 23122246, roleInfos = emptyList(), isGroupVip = false ), content = MediaIChatContent( text = "「 小説を音楽にするユニット 」 であるYOASOBIの結成以降初となるCD作品であり [12]、2019 年以降にリリースされた 「 夜に駆ける 」 から 「 群青 」 までのシングル5曲 [注1]と新曲が収録される[13]。7thシングル「怪物」と同時リリースされたが[12]、同曲は収録されていない。", medias = listOf( Media( resourceLink = "https://image.cmoney.tw/attachment/blog/1700150400/0d9e81d5-4870-4af9-be5a-8f6e6dd600b6.jpg", type = "Image", isNeedAuthenticate = false, image = ImageContent(width = 0, height = 0), ) ) ), emojiCount = IEmojiCount( like = 0, dislike = 0, laugh = 0, money = 0, shock = 0, cry = 0, think = 0, angry = 0 ), id = "151628405", isDeleted = false, createUnixTime = 1700201671, updateUnixTime = 1700201671, serialNumber = 1300, deleteStatus = DeleteStatus.none, commentCount = 0 ) val mockListBulletinboardMessage: List<BulletinboardMessage> get() { return (1..Random.nextInt(2, 10)).map { mockBulletinboardMessage } } val mockBulletinboardMessageWrapper: PostViewModel.BulletinboardMessageWrapper get() = PostViewModel.BulletinboardMessageWrapper( message = mockBulletinboardMessage, isPin = false ) //單選題 val mockSingleVoting: Voting get() = Voting( id = System.currentTimeMillis().toString(), title = RandomStringUtils.randomAlphabetic(10), votingOptionStatistics = listOf( IVotingOptionStatistic( optionId = "1", voteCount = 2, text = RandomStringUtils.randomAlphabetic(10) ), IVotingOptionStatistic( optionId = "2", voteCount = 3, text = RandomStringUtils.randomAlphabetic(10) ), IVotingOptionStatistic( optionId = "3", voteCount = 1, text = RandomStringUtils.randomAlphabetic(10) ), IVotingOptionStatistic( optionId = "4", voteCount = 4, text = RandomStringUtils.randomAlphabetic(10) ) ), isMultipleChoice = false, userVote = IUserVoteInfo() ) //多選題 val mockMultiVoting: Voting get() = mockSingleVoting.copy( id = "123", isMultipleChoice = true ) val mockIVotingOptionStatisticsWithVoterList: List<IVotingOptionStatisticWithVoter> get() = listOf( IVotingOptionStatisticWithVoter( voterIds = listOf("1", "2", "3"), optionId = "1", text = RandomStringUtils.randomAlphabetic(10) ), IVotingOptionStatisticWithVoter( voterIds = listOf("1", "2", "3"), optionId = "2", text = RandomStringUtils.randomAlphabetic(10) ), IVotingOptionStatisticWithVoter( voterIds = listOf("1", "2", "3"), optionId = "3", text = RandomStringUtils.randomAlphabetic(10) ), IVotingOptionStatisticWithVoter( voterIds = listOf("1", "2", "3"), optionId = "4", text = RandomStringUtils.randomAlphabetic(10) ) ) }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/mock/MockData.kt
3838084675
package com.cmoney.kolfanci.model.remoteconfig import com.cmoney.remoteconfig_library.model.key.RemoteConfigKey object PollingFrequencyKey : RemoteConfigKey<Long>("chatroomLongPollingFrequencySeconds")
Fanci/app/src/main/java/com/cmoney/kolfanci/model/remoteconfig/PollingFrequencyKey.kt
3281552875
package com.cmoney.kolfanci.model.remoteconfig import com.cmoney.remoteconfig_library.model.key.RemoteConfigKey object BaseDomainKey : RemoteConfigKey<String>("baseDomain") //second
Fanci/app/src/main/java/com/cmoney/kolfanci/model/remoteconfig/BaseDomainKey.kt
3366081193
package com.cmoney.kolfanci.model import com.cmoney.fanciapi.fanci.model.ChatMessage import com.cmoney.kolfanci.ui.screens.chat.message.viewmodel.ImageAttachState data class ChatMessageWrapper( val message: ChatMessage = ChatMessage(), val haveNextPage: Boolean = false, val uploadAttachPreview: List<ImageAttachState> = emptyList(), val isBlocking: Boolean = false, //我封鎖 val isBlocker: Boolean = false, //我被封鎖 val isPendingSendMessage: Boolean = false, //未送出的訊息 val messageType: MessageType = MessageType.Default ) { /** * 聊天室 呈現內容 類型 */ sealed class MessageType { object TimeBar : MessageType() //時間 Bar object Blocking : MessageType() //用戶已被你封鎖 object Blocker : MessageType() //用戶已將您封鎖 object Delete : MessageType() //被刪除 object RecycleMessage : MessageType() //收回訊息 object Default : MessageType() //聊天室內文 } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/ChatMessageWrapper.kt
1674788483
package com.cmoney.kolfanci.model import android.content.Context import com.cmoney.fanciapi.fanci.model.ChannelPermission import com.cmoney.fanciapi.fanci.model.GroupPermission import com.cmoney.fanciapi.fanci.model.User import com.cmoney.fanciapi.fanci.model.UserBuffInformation import com.cmoney.kolfanci.BuildConfig import com.cmoney.kolfanci.MyApplication import com.cmoney.kolfanci.R import com.cmoney.remoteconfig_library.IRemoteConfig import com.cmoney.remoteconfig_library.model.config.AppStatus import org.koin.core.context.GlobalContext object Constant { //錄音存放的路徑 val absoluteCachePath = MyApplication.instance.applicationContext.externalCacheDir?.absolutePath ?: "" //是否開啟 Mock 模式 (ex: server 壞掉下還可以使用) val isOpenMock = (false && BuildConfig.DEBUG) //我的個人資訊 var MyInfo: User? = null //我在目前社團的權限 var MyGroupPermission: GroupPermission = GroupPermission() //TODO: test // var MyGroupPermission: GroupPermission = GroupPermission( // editGroup = true, // createOrEditApplyQuestions = true, // rearrangeChannelCategory = true, // setGroupPublicity = true, // createOrEditCategory = true, // deleteCategory = true, // createOrEditChannel = true, // setAnnouncement = true, // deleteChannel = true, // createOrEditRole = true, // deleteRole = true, // rearrangeRoles = true, // assignRole = true, // approveJoinApplies = true, // deleteMemberMessage = true, // banOrKickMember = true // ) //我在目前頻道的權限 // var MyChannelPermission: ChannelPermission = ChannelPermission() //todo TEST var MyChannelPermission: ChannelPermission = ChannelPermission( canRead = true, canPost = true, canReply = true, canEmoji = true, canManage = true, canCopy = true, canBlock = true, canReport = true, canTakeback = true ) //我在目前頻道的Buffer var MyChannelBuff: UserBuffInformation = UserBuffInformation() /** * 目前 app 是否不是審核中 * */ fun isAppNotInReview(): Boolean { val iRemoteConfig = GlobalContext.get().get<IRemoteConfig>() return when (iRemoteConfig.getAppStatus()) { is AppStatus.IsUnderReview -> false else -> true } } /** * 是否出現 上傳檔案功能 */ fun isShowUploadFile(): Boolean { //因為之前server 還未完成, app 先送審, 先隱藏起來 // val iRemoteConfig = GlobalContext.get().get<IRemoteConfig>() // return when (iRemoteConfig.getAppStatus()) { // is AppStatus.IsUnderReview -> false // else -> true // } return true } /** * 是否可以管理 vip 方案 */ fun isShowVipManager(): Boolean = (MyGroupPermission.editVipRole == true && isAppNotInReview()) /** * 是否可以管理 加入申請 */ fun isShowApproval(): Boolean = MyGroupPermission.approveJoinApplies == true /** * 是否呈現 社團管理 區塊 */ fun isShowGroupManage(): Boolean { return (MyGroupPermission.editGroup == true) || (MyGroupPermission.createOrEditChannel == true) || (MyGroupPermission.createOrEditCategory == true) || (MyGroupPermission.setGroupPublicity == true) || (MyGroupPermission.rearrangeChannelCategory == true) || (MyGroupPermission.deleteCategory == true) || (MyGroupPermission.deleteChannel == true) } /** * 是否可以編輯 頻道 */ fun isEnterChannelEditPermission(): Boolean = (MyGroupPermission.createOrEditChannel == true || MyGroupPermission.deleteChannel == true) /** * 是否可以刪除頻道 */ fun isCanDeleteChannel(): Boolean = (MyGroupPermission.deleteChannel == true) /** * 是否可以 增加頻道 */ fun isAddChannelPermission(): Boolean = (MyGroupPermission.createOrEditChannel == true) /** * 是否可以進入編輯分類 新增/刪除 */ fun isEnterEditCategoryPermission(): Boolean = (MyGroupPermission.createOrEditCategory == true || MyGroupPermission.deleteCategory == true) /** * 是否可以編輯分類 新增 */ fun isCanEditCategoryPermission(): Boolean = (MyGroupPermission.createOrEditCategory == true) /** * 是否 可以刪除分類 */ fun isCanDeleteCategory(): Boolean = (MyGroupPermission.deleteCategory == true) /** * 是否可以進入 新增/編輯/刪除 角色 */ fun isCanEnterEditRole(): Boolean = ( MyGroupPermission.createOrEditRole == true || MyGroupPermission.deleteRole == true || MyGroupPermission.rearrangeRoles == true) /** * 是否可以 新增/編輯 角色 */ fun isCanEditRole(): Boolean = (MyGroupPermission.createOrEditRole == true) /** * 是否可以 進入成員管理 */ fun isCanEnterMemberManager(): Boolean = (MyGroupPermission.createOrEditRole == true || MyGroupPermission.assignRole == true || MyGroupPermission.banOrKickMember == true) /** * 是否可以 刪除 角色 */ fun isCanDeleteRole(): Boolean = (MyGroupPermission.deleteRole == true) /** * 是否可以 禁言/踢出 社團 */ fun isCanBanKickMember(): Boolean = (MyGroupPermission.banOrKickMember == true) /** * 是否可以按 Emoji */ fun isCanEmoji(): Boolean = (MyChannelPermission.canEmoji == true) /** * 是否可以 回覆訊息 */ fun isCanReply(): Boolean = (MyChannelPermission.canReply == true) /** * 是否可以 收回訊息 */ fun isCanTakeBack(): Boolean = (MyChannelPermission.canTakeback == true) /** * 是否可以 複製 */ fun isCanCopy(): Boolean = (MyChannelPermission.canCopy == true) /** * 是否可以 置頂/刪除 訊息 */ fun isCanManage(): Boolean = (MyChannelPermission.canManage == true) /** * 是否可以 封鎖用戶 */ fun isCanBlock(): Boolean = (MyChannelPermission.canBlock == true) /** * 是否可以 檢舉用戶 */ fun isCanReport(): Boolean = (MyChannelPermission.canReport == true) /** * 是否可以讀取聊天室內容 */ fun canReadMessage(): Boolean = (MyChannelPermission.canRead == true) /** * 是否可以發文 */ fun canPostMessage(): Boolean = (MyChannelPermission.canPost == true) /** * channel 下 是否被禁言 */ fun isBuffSilence(): Boolean { return MyChannelBuff.buffs?.let { buff -> buff.forEach { status -> if (status.name == "禁言") { return@let true } } return@let false } ?: false } /** * 取得 頻道無法發言 原因 */ fun getChannelSilenceDesc( context: Context, default: String = context.getString(R.string.silence_result_desc) ): String { return MyChannelBuff.buffs?.let { buff -> buff.forEach { status -> if (status.name == "禁言") { return@let status.description.orEmpty() } } return@let context.getString(R.string.silence_result_desc) } ?: default } val emojiLit = listOf( R.drawable.emoji_money, R.drawable.emoji_shock, R.drawable.emoji_laugh, R.drawable.emoji_angry, R.drawable.emoji_think, R.drawable.emoji_cry, R.drawable.emoji_like, ) }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/Constant.kt
721126588
package com.cmoney.kolfanci.model.state //TODO @Deprecated("") data class LoadingState( val isLoading: Boolean )
Fanci/app/src/main/java/com/cmoney/kolfanci/model/state/LoadingState.kt
3544896830
package com.cmoney.kolfanci.model import android.net.Uri import com.google.common.net.MediaType data class MediaItem( val uri: Uri, val mediaType: MediaType )
Fanci/app/src/main/java/com/cmoney/kolfanci/model/MediaItem.kt
155565374
package com.cmoney.kolfanci.model.persistence import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.preferencesDataStore import com.cmoney.kolfanci.model.Constant import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map val Context.dataStore: DataStore<Preferences> by preferencesDataStore( name = "fanci_preferences" ) class SettingsDataStore(private val preference_datastore: DataStore<Preferences>) { private val IS_TUTORIAL = booleanPreferencesKey("is_tutorial") //是否新手導引過 private val hasNotifyAllowNotificationPermissionKey get() = booleanPreferencesKey(getHasNotifyAllowNotificationPermissionKey()) private val IS_SHOW_BUBBLE = booleanPreferencesKey("is_show_bubble") //建立社團後 是否出現 buble val isTutorial: Flow<Boolean> = preference_datastore.data.map { it[IS_TUTORIAL] ?: false } val isShowBubble: Flow<Boolean> = preference_datastore.data.map { it[IS_SHOW_BUBBLE] ?: false } suspend fun onTutorialOpen() { preference_datastore.edit { preferences -> preferences[IS_TUTORIAL] = true } } /** * 取得是否通知過使用者允許通知權限 * * @return true 已經通知過, false 未通知或是未處理 */ suspend fun hasNotifyAllowNotificationPermission(): Boolean { return preference_datastore.data.first()[hasNotifyAllowNotificationPermissionKey] ?: false } /** * 已經通知過使用者允許通知權限 */ suspend fun alreadyNotifyAllowNotificationPermission() { preference_datastore.edit { preferences -> preferences[hasNotifyAllowNotificationPermissionKey] = true } } private fun getHasNotifyAllowNotificationPermissionKey(): String { return "${Constant.MyInfo?.id}_has_notify_allow_notification_permission" } suspend fun setHomeBubbleShow() { preference_datastore.edit { preferences -> preferences[IS_SHOW_BUBBLE] = true } } suspend fun alreadyShowHomeBubble() { preference_datastore.edit { preferences -> preferences[IS_SHOW_BUBBLE] = false } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/persistence/SettingsDataStore.kt
213862201
package com.cmoney.kolfanci.model /** * User 對於該社團狀態 */ sealed class GroupJoinStatus { /** * 已加入 */ object Joined : GroupJoinStatus() /** * 未加入 */ object NotJoin : GroupJoinStatus() /** * 審核中 */ object InReview : GroupJoinStatus() }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/GroupJoinStatus.kt
4180454894
package com.cmoney.kolfanci.model.usecase import com.cmoney.fanciapi.fanci.api.GroupApi import com.cmoney.fanciapi.fanci.api.GroupApplyApi import com.cmoney.fanciapi.fanci.model.ApplyStatus import com.cmoney.fanciapi.fanci.model.GroupApplyParam import com.cmoney.fanciapi.fanci.model.GroupApplyStatusParam import com.cmoney.fanciapi.fanci.model.GroupRequirementAnswer import com.cmoney.kolfanci.extension.checkResponseBody class GroupApplyUseCase(private val groupApplyApi: GroupApplyApi, private val groupApi: GroupApi) { /** * 審核加入社團 * * @param groupId 社團id * @param applyId 要處理的申請單id * @param applyStatus 審核狀態, 允許 or 拒絕 */ suspend fun approval(groupId: String, applyId: List<String>, applyStatus: ApplyStatus) = kotlin.runCatching { groupApplyApi.apiV1GroupApplyGroupGroupIdApprovalPut( groupId = groupId, groupApplyStatusParam = GroupApplyStatusParam( status = applyStatus, applyIds = applyId ) ).checkResponseBody() } /** * 查詢未處理的入社申請筆數 * * @param groupId 社團id * @param applyStauts 查詢審核狀態, 預設 未審核 */ suspend fun getUnApplyCount( groupId: String, applyStauts: ApplyStatus = ApplyStatus.unConfirmed ) = kotlin.runCatching { groupApplyApi.apiV1GroupApplyGroupGroupIdCountGet(groupId = groupId).checkResponseBody() } /** * 申請加入審核社團 * * @param groupId 社團id * @param groupRequirementAnswer 問題及答案 */ suspend fun joinGroupWithQuestion( groupId: String, groupRequirementAnswer: List<GroupRequirementAnswer> ) = kotlin.runCatching { groupApplyApi.apiV1GroupApplyGroupGroupIdPut( groupId = groupId, groupApplyParam = GroupApplyParam( groupRequirementAnswer ) ).checkResponseBody() } /** * 抓取社團申請 清單, * @param groupId 社團 id * @param startWeight 起始權重 (分頁錨點用) * @param applyStatus 審核狀態, 預設為未審核 */ suspend fun fetchGroupApplyList( groupId: String, startWeight: Long = 0, applyStatus: ApplyStatus = ApplyStatus.unConfirmed ) = kotlin.runCatching { groupApplyApi.apiV1GroupApplyGroupGroupIdGet( groupId = groupId, applyStatus = applyStatus, startWeight = startWeight ).checkResponseBody() } /** * 取得 我申請的社團-審核中 */ suspend fun fetchAllMyGroupApplyUnConfirmed() = kotlin.runCatching { groupApplyApi.apiV1GroupApplyGroupAllMeGet().checkResponseBody().filter { it.apply?.status == ApplyStatus.unConfirmed }.mapNotNull { val groupId = it.apply?.groupId ?: return@mapNotNull null groupApi.apiV1GroupGroupIdGet(groupId = groupId).checkResponseBody() } } /** * 取得 我的社團申請狀態 * @param groupId 社團 id */ suspend fun fetchMyApply(groupId: String) = kotlin.runCatching { groupApplyApi.apiV1GroupApplyGroupGroupIdMeGet( groupId = groupId ).checkResponseBody() } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/GroupApplyUseCase.kt
1628029466
package com.cmoney.kolfanci.model.usecase import com.cmoney.fanciapi.fanci.api.ChannelApi import com.cmoney.fanciapi.fanci.api.GroupApi import com.cmoney.fanciapi.fanci.api.RoleUserApi import com.cmoney.fanciapi.fanci.api.VipApi import com.cmoney.fanciapi.fanci.model.AccessorTypes import com.cmoney.fanciapi.fanci.model.ChannelAuthType import com.cmoney.fanciapi.fanci.model.FanciRole import com.cmoney.fanciapi.fanci.model.Group import com.cmoney.fanciapi.fanci.model.GroupMember import com.cmoney.fanciapi.fanci.model.PutAuthTypeRequest import com.cmoney.fanciapi.fanci.model.RoleChannelAuthType import com.cmoney.fanciapi.fanci.model.RoleParam import com.cmoney.kolfanci.extension.checkResponseBody import com.cmoney.kolfanci.extension.isVip import com.cmoney.kolfanci.ui.screens.group.setting.vip.model.VipPlanInfoModel import com.cmoney.kolfanci.ui.screens.group.setting.vip.model.VipPlanModel import com.cmoney.kolfanci.ui.screens.group.setting.vip.model.VipPlanPermissionModel import com.cmoney.kolfanci.ui.screens.group.setting.vip.model.VipPlanPermissionOptionModel import kotlin.random.Random class VipManagerUseCase( private val groupApi: GroupApi, private val vipApi: VipApi, private val roleUserApi: RoleUserApi, private val channelApi: ChannelApi ) { /** * 取得用戶所購買的所有方案 */ suspend fun getUserAllVipPlan(userId: String) = kotlin.runCatching { vipApi.apiV1VipPurchasedSaleUserIdGet(userId).checkResponseBody() } /** * 取得 vip 方案清單 * * @param groupId 社團Id */ suspend fun getVipPlan(groupId: String) = kotlin.runCatching { groupApi.apiV1GroupGroupIdVipRoleGet(groupId = groupId).checkResponseBody() } /** * 取得該vip 的銷售方案 * * @param roleId 角色 id (vip相當於角色) */ suspend fun getVipSales(roleId: String) = kotlin.runCatching { vipApi.apiV1VipVipSalesRoleIdGet(roleId = roleId).checkResponseBody() } /** * 取得該 vip 方案 詳細資訊, 過濾掉非vip 的成員 * * @param vipPlanModel 選擇的方案 */ suspend fun getVipPlanInfo(vipPlanModel: VipPlanModel) = kotlin.runCatching { val mockData = getVipPlanInfoMockData() val filterPlanModel = mockData.copy( members = mockData.members.filter { it.isVip() } ) filterPlanModel } /** * 取得某社團下該 vip 方案的詳細資訊 * * @param group 指定社團 * @param vipPlanModel 選擇的方案 * @return 社團所有頻道此方案下的權限設定 */ suspend fun getPermissions( group: Group, vipPlanModel: VipPlanModel ) = kotlin.runCatching { //取得該角色 在此社團下 所有頻道的權限 groupApi.apiV1GroupGroupIdRoleIdChannelAuthTypeGet( groupId = group.id.orEmpty(), roleId = vipPlanModel.id ).checkResponseBody().map { roleChannelAuthType -> VipPlanPermissionModel( id = roleChannelAuthType.channelId.orEmpty(), name = roleChannelAuthType.channelName.orEmpty(), canEdit = roleChannelAuthType.isPublic != true, permissionTitle = "", authType = roleChannelAuthType.authType ?: ChannelAuthType.noPermission ) } } /** * 取得某社團下該 vip 方案的詳細資訊 * * @param group 指定社團 * @param vipPlanModel 選擇的方案 * @return 社團所有頻道此方案下的權限設定 */ suspend fun getPermissionWithAuthTitle( group: Group, vipPlanModel: VipPlanModel ) = kotlin.runCatching { //權限清單表 val permissionList = getPermissionOptions(vipPlanModel = vipPlanModel).getOrNull().orEmpty() //取得該角色 在此社團下 所有頻道的權限 groupApi.apiV1GroupGroupIdRoleIdChannelAuthTypeGet( groupId = group.id.orEmpty(), roleId = vipPlanModel.id ).checkResponseBody().map { roleChannelAuthType -> val authType = roleChannelAuthType.authType ?: ChannelAuthType.noPermission VipPlanPermissionModel( id = roleChannelAuthType.channelId.orEmpty(), name = roleChannelAuthType.channelName.orEmpty(), canEdit = roleChannelAuthType.isPublic != true, permissionTitle = getPermissionTitle( roleChannelAuthType = roleChannelAuthType, authType = authType, permissionList = permissionList ), authType = authType ) } } /** * 取得 authType 對應的顯示名稱 * @param authType * @param permissionList 權限表 */ private fun getPermissionTitle( authType: ChannelAuthType, permissionList: List<VipPlanPermissionOptionModel>, roleChannelAuthType: RoleChannelAuthType ): String { return if (roleChannelAuthType.isPublic == true) { "公開頻道" } else { permissionList.first { it.authType == authType }.name } } /** * 取得選擇的VIP方案下可選的權限選項 * * @param vipPlanModel 選擇的方案 * @return 選項 */ suspend fun getPermissionOptions(vipPlanModel: VipPlanModel): Result<List<VipPlanPermissionOptionModel>> { return kotlin.runCatching { channelApi.apiV2ChannelAccessTypeGet( isWithNoPermission = true ).checkResponseBody().map { channelAccessOptionV2 -> VipPlanPermissionOptionModel( name = channelAccessOptionV2.title.orEmpty(), description = channelAccessOptionV2.allowedAction.orEmpty(), authType = channelAccessOptionV2.authType ?: ChannelAuthType.noPermission ) } } } /** * 設定 vip角色 在此頻道 的權限 * * @param channelId 頻道id * @param vipRoleId 要設定的vip角色id * @param authType 權限 */ suspend fun setChannelVipRolePermission( channelId: String, vipRoleId: String, authType: ChannelAuthType ) = kotlin.runCatching { channelApi.apiV1ChannelChannelIdWhiteListAccessorTypeAccessorIdPut( channelId = channelId, accessorType = AccessorTypes.vipRole, accessorId = vipRoleId, putAuthTypeRequest = PutAuthTypeRequest( authType = authType ) ).checkResponseBody() } /** * 取得該會員已購買的vip方案清單 * * @param groupId 所在的社團 * @param groupMember 要查的會員 * @return vip 方案清單 */ suspend fun getAlreadyPurchasePlan(groupId: String, groupMember: GroupMember) = kotlin.runCatching { roleUserApi.apiV1RoleUserGroupGroupIdUserIdVipRoleGet( groupId = groupId, userId = groupMember.id.orEmpty() ).checkResponseBody() } /** * 更換 vip 名稱 * * @param groupId 社團 id * @param roleId 角色 id (vip 方案 id) * @param name 要更改的名稱 */ suspend fun changeVipRoleName(groupId: String, roleId: String, name: String) = kotlin.runCatching { groupApi.apiV1GroupGroupIdRoleRoleIdPut( groupId = groupId, roleId = roleId, roleParam = RoleParam( name = name ) ) } /** * 取得該vip 方案下的成員清單 * * @param groupId 社團 id * @param roleId 角色 id (vip 方案 id) */ suspend fun getVipPlanMember(groupId: String, roleId: String) = kotlin.runCatching { roleUserApi.apiV1RoleUserGroupGroupIdRoleRoleIdGet( groupId = groupId, roleId = roleId ).checkResponseBody() } companion object { fun getVipPlanMockData() = listOf( VipPlanModel( id = "1", name = "高級學員", memberCount = 10, description = "99元月訂閱方案" ), VipPlanModel( id = "2", name = "進階學員", memberCount = 5, description = "120元月訂閱方案" ), VipPlanModel( id = "3", name = "初階學員", memberCount = 0, description = "30 元月訂閱方案" ) ) fun getVipPlanInfoMockData() = VipPlanInfoModel( name = "高級學員", memberCount = 10, planSourceDescList = listOf( "・30元訂閱促銷方案", "・99元月訂閱方案" ), members = listOf( GroupMember( name = "王力宏", thumbNail = "https://picsum.photos/${ Random.nextInt( 100, 300 ) }/${Random.nextInt(100, 300)}", serialNumber = Random.nextLong( 1000, 3000 ), roleInfos = listOf( FanciRole( name = "高級學員", userCount = 10 ) ) ), GroupMember( name = "王力宏1", thumbNail = "https://picsum.photos/${ Random.nextInt( 100, 300 ) }/${Random.nextInt(100, 300)}", serialNumber = Random.nextLong( 1000, 3000 ), roleInfos = listOf( FanciRole( name = "高級學員", userCount = 10 ) ) ), GroupMember( name = "王力宏2", thumbNail = "https://picsum.photos/${ Random.nextInt( 100, 300 ) }/${Random.nextInt(100, 300)}", serialNumber = Random.nextLong( 1000, 3000 ), roleInfos = listOf( FanciRole( name = "高級學員", userCount = 10 ) ) ), GroupMember( name = "Kevin", thumbNail = "https://picsum.photos/${ Random.nextInt( 100, 300 ) }/${Random.nextInt(100, 300)}", serialNumber = Random.nextLong( 1000, 3000 ), roleInfos = listOf( FanciRole( name = "高級學員", userCount = 10 ) ) ), GroupMember( name = "Kevin1", thumbNail = "https://picsum.photos/${ Random.nextInt( 100, 300 ) }/${Random.nextInt(100, 300)}", serialNumber = Random.nextLong( 1000, 3000 ), roleInfos = listOf( FanciRole( name = "高級學員", userCount = 10 ) ) ), GroupMember( name = "Kevin2", thumbNail = "https://picsum.photos/${ Random.nextInt( 100, 300 ) }/${Random.nextInt(100, 300)}", serialNumber = Random.nextLong( 1000, 3000 ), roleInfos = listOf( FanciRole( name = "高級學員", userCount = 10 ) ) ) ) ) fun getVipPlanPermissionOptionsMockData(): List<VipPlanPermissionOptionModel> { return listOf( VipPlanPermissionOptionModel( name = "無權限", description = "不可進入此頻道", authType = ChannelAuthType.noPermission ), VipPlanPermissionOptionModel( name = "基本權限", description = "可以進入此頻道,並且瀏覽", authType = ChannelAuthType.basic ), VipPlanPermissionOptionModel( name = "中階權限", description = "可以進入此頻道,並在貼文留言", authType = ChannelAuthType.inter ), VipPlanPermissionOptionModel( name = "進階權限", description = "可以進入此頻道,可以聊天、發文與留言", authType = ChannelAuthType.advance ) ) } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/VipManagerUseCase.kt
3039910538
package com.cmoney.kolfanci.model.usecase import com.cmoney.kolfanci.extension.checkResponseBody import com.cmoney.kolfanci.ui.screens.group.setting.group.groupsetting.theme.model.GroupTheme import com.cmoney.kolfanci.ui.theme.* import com.cmoney.fanciapi.fanci.api.GroupApi import com.cmoney.fanciapi.fanci.api.ThemeColorApi import com.cmoney.fanciapi.fanci.model.ColorTheme import com.cmoney.fanciapi.fanci.model.EditGroupParam import com.cmoney.fanciapi.fanci.model.Group import com.cmoney.fanciapi.fanci.model.Theme import com.socks.library.KLog class ThemeUseCase(private val themeColorApi: ThemeColorApi, val groupApi: GroupApi) { private val TAG = ThemeUseCase::class.java.simpleName /** * 抓取 角色顏色設定檔 */ suspend fun fetchRoleColor(colorTheme: ColorTheme) = kotlin.runCatching { themeColorApi.apiV1ThemeColorColorThemeGet(colorTheme).checkResponseBody().let { val colors = it.categoryColors?.let { categoryColors -> categoryColors["RoleColor"] }.orEmpty() RoleColor( colors = colors ) } } /** * 更換 社團主題顏色 */ suspend fun changeGroupTheme(group: Group, groupTheme: GroupTheme) = kotlin.runCatching { groupApi.apiV1GroupGroupIdPut( group.id.orEmpty(), EditGroupParam( name = group.name.orEmpty(), description = group.description.orEmpty(), coverImageUrl = group.coverImageUrl.orEmpty(), thumbnailImageUrl = group.thumbnailImageUrl.orEmpty(), colorSchemeGroupKey = ColorTheme.decode(groupTheme.id) ) ).checkResponseBody() } /** * 抓取 所有 主題設定檔 */ suspend fun fetchAllThemeConfig() = kotlin.runCatching { KLog.i(TAG, "fetchAllThemeConfig") themeColorApi.apiV1ThemeColorGet().checkResponseBody().toList().map { val id = it.first val theme = serverColorTransfer(it.second) val name = it.second.displayName val preview = it.second.previewImage GroupTheme( id = id, isSelected = false, theme = theme, name = name.orEmpty(), preview = preview.orEmpty() ) } } /** * 抓取 特定 主題設定檔 */ suspend fun fetchThemeConfig(colorTheme: ColorTheme) = kotlin.runCatching { KLog.i(TAG, "fetchThemeConfig") themeColorApi.apiV1ThemeColorColorThemeGet(colorTheme).checkResponseBody().let { GroupTheme( id = colorTheme.value, isSelected = false, theme = serverColorTransfer(it), name = it.displayName.orEmpty(), preview = it.previewImage.orEmpty() ) } } /** * 將 Server 回傳的 Model 轉換成 app theme model */ private fun serverColorTransfer(theme: Theme): FanciColor { val colors = theme.categoryColors?.toList()?.map { it.second }?.flatten().orEmpty() val primary = colors.first { it.name == "Env_Theme" }.hexColorCode.orEmpty() val background = colors.first { it.name == "Env_Base" }.hexColorCode.orEmpty() val env_40 = colors.first { it.name == "Env_Env40" }.hexColorCode.orEmpty() val env_60 = colors.first { it.name == "Env_Env60" }.hexColorCode.orEmpty() val env_80 = colors.first { it.name == "Env_Env80" }.hexColorCode.orEmpty() val env_100 = colors.first { it.name == "Env_Env100" }.hexColorCode.orEmpty() val inputFrame = colors.first { it.name == "Env_InputField" }.hexColorCode.orEmpty() val tabUnSelect = colors.first { it.name == "Component_tabNotSelected" }.hexColorCode.orEmpty() val tabSelected = colors.first { it.name == "Component_tabIsSelected" }.hexColorCode.orEmpty() val other = colors.first { it.name == "Component_OtherDisplay" }.hexColorCode.orEmpty() val default_30 = colors.first { it.name == "Text_Display_DefaultDisplay30" }.hexColorCode.orEmpty() val default_50 = colors.first { it.name == "Text_Display_DefaultDisplay50" }.hexColorCode.orEmpty() val default_80 = colors.first { it.name == "Text_Display_DefaultDisplay80" }.hexColorCode.orEmpty() val default_100 = colors.first { it.name == "Text_Display_DefaultDisplay100" }.hexColorCode.orEmpty() val textOther = colors.first { it.name == "Text_Display_OtherDisplay" }.hexColorCode.orEmpty() val input_30 = colors.first { it.name == "Text_InputField_30" }.hexColorCode.orEmpty() val input_50 = colors.first { it.name == "Text_InputField_50" }.hexColorCode.orEmpty() val input_80 = colors.first { it.name == "Text_InputField_80" }.hexColorCode.orEmpty() val input_100 = colors.first { it.name == "Text_InputField_100" }.hexColorCode.orEmpty() val blue = colors.first { it.name == "SpecialColor_Blue" }.hexColorCode.orEmpty() val blueGreen = colors.first { it.name == "SpecialColor_BlueGreen" }.hexColorCode.orEmpty() val green = colors.first { it.name == "SpecialColor_Green" }.hexColorCode.orEmpty() val hintRed = colors.first { it.name == "SpecialColor_Hint_Red" }.hexColorCode.orEmpty() val orange = colors.first { it.name == "SpecialColor_Orange" }.hexColorCode.orEmpty() val pink = colors.first { it.name == "SpecialColor_Pink" }.hexColorCode.orEmpty() val purple = colors.first { it.name == "SpecialColor_Purple" }.hexColorCode.orEmpty() val red = colors.first { it.name == "SpecialColor_Red" }.hexColorCode.orEmpty() val yellow = colors.first { it.name == "SpecialColor_Yellow" }.hexColorCode.orEmpty() return FanciColor( primary = androidx.compose.ui.graphics.Color(primary.toLong(16)), background = androidx.compose.ui.graphics.Color(background.toLong(16)), env_40 = androidx.compose.ui.graphics.Color(env_40.toLong(16)), env_60 = androidx.compose.ui.graphics.Color(env_60.toLong(16)), env_80 = androidx.compose.ui.graphics.Color(env_80.toLong(16)), env_100 = androidx.compose.ui.graphics.Color(env_100.toLong(16)), inputFrame = androidx.compose.ui.graphics.Color(inputFrame.toLong(16)), component = FanciComponentColor( tabUnSelect = androidx.compose.ui.graphics.Color(tabUnSelect.toLong(16)), tabSelected = androidx.compose.ui.graphics.Color(tabSelected.toLong(16)), other = androidx.compose.ui.graphics.Color(other.toLong(16)) ), text = FanciTextColor( default_30 = androidx.compose.ui.graphics.Color(default_30.toLong(16)), default_50 = androidx.compose.ui.graphics.Color(default_50.toLong(16)), default_80 = androidx.compose.ui.graphics.Color(default_80.toLong(16)), default_100 = androidx.compose.ui.graphics.Color(default_100.toLong(16)), other = androidx.compose.ui.graphics.Color(textOther.toLong(16)) ), inputText = FanciInputText( input_30 = androidx.compose.ui.graphics.Color(input_30.toLong(16)), input_50 = androidx.compose.ui.graphics.Color(input_50.toLong(16)), input_80 = androidx.compose.ui.graphics.Color(input_80.toLong(16)), input_100 = androidx.compose.ui.graphics.Color(input_100.toLong(16)), ), specialColor = SpecialColor( blue = androidx.compose.ui.graphics.Color(blue.toLong(16)), blueGreen = androidx.compose.ui.graphics.Color(blueGreen.toLong(16)), green = androidx.compose.ui.graphics.Color(green.toLong(16)), hintRed = androidx.compose.ui.graphics.Color(hintRed.toLong(16)), orange = androidx.compose.ui.graphics.Color(orange.toLong(16)), pink = androidx.compose.ui.graphics.Color(pink.toLong(16)), purple = androidx.compose.ui.graphics.Color(purple.toLong(16)), red = androidx.compose.ui.graphics.Color(red.toLong(16)), yellow = androidx.compose.ui.graphics.Color(yellow.toLong(16)) ), roleColor = RoleColor( theme.categoryColors?.let { categoryColors -> categoryColors["RoleColor"] }.orEmpty() ) ) } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/ThemeUseCase.kt
1908595822
package com.cmoney.kolfanci.model.usecase import android.app.Application import android.content.Context import android.net.Uri import com.bumptech.glide.Glide import com.cmoney.kolfanci.BuildConfig import com.cmoney.kolfanci.extension.getUploadFileType import com.cmoney.kolfanci.extension.toUploadFileItem import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem import com.cmoney.kolfanci.model.attachment.AttachmentType import com.cmoney.kolfanci.model.vote.VoteModel import com.cmoney.kolfanci.repository.Network import com.cmoney.kolfanci.ui.destinations.AudioPreviewScreenDestination import com.cmoney.kolfanci.ui.destinations.CreateChoiceQuestionScreenDestination import com.cmoney.kolfanci.ui.destinations.PdfPreviewScreenDestination import com.cmoney.kolfanci.ui.destinations.TextPreviewScreenDestination import com.cmoney.kolfanci.ui.screens.media.audio.AudioViewModel import com.ramcosta.composedestinations.navigation.DestinationsNavigator import com.socks.library.KLog import com.stfalcon.imageviewer.StfalconImageViewer import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow class AttachmentUseCase( val context: Application, private val network: Network ) { private val TAG = AttachmentUseCase::class.java.simpleName suspend fun uploadFile(uri: Uri) = network.uploadFile(uri) suspend fun uploadFile(uris: List<Uri>): Flow<AttachmentInfoItem> = flow { KLog.i(TAG, "uploadFile") uris.forEach { uri -> emit( uri.toUploadFileItem( context = context, status = AttachmentInfoItem.Status.Uploading ) ) network.uploadFile(uri) .onSuccess { fileUploadResponse -> val externalId = fileUploadResponse.externalId KLog.i(TAG, "uploadFile step1 success:$uri, id=$externalId") //polling status emit( checkFileStatus( externalId = externalId, uri = uri ) ) } .onFailure { KLog.e(TAG, "uploadFile step1 fail:$it") emit( AttachmentInfoItem( uri = uri, status = AttachmentInfoItem.Status.Failed("upload step1 failed.") ) ) } } } /** * 檢查 檔案上傳 狀態 */ private suspend fun checkFileStatus(externalId: String, uri: Uri): AttachmentInfoItem { val uploadFileType = uri.getUploadFileType(context) val whileLimit = 10 var whileCount = 0 var delayTime: Long var pre = 0L var current = 1L while (whileCount < whileLimit) { delayTime = pre + current pre = current current = delayTime whileCount += 1 val fileUploadStatusResponse = network.checkUploadFileStatus( externalId = externalId, fileType = uploadFileType ).getOrNull() KLog.i(TAG, "fileUploadStatusResponse:$fileUploadStatusResponse") fileUploadStatusResponse?.let { statusResponse -> val status = when (statusResponse.status) { "uploading" -> { AttachmentInfoItem.Status.Uploading } "success" -> { AttachmentInfoItem.Status.Success } else -> { AttachmentInfoItem.Status.Failed("checkFileStatus fail") } } if (whileCount > whileLimit || status == AttachmentInfoItem.Status.Success) { return uri.toUploadFileItem( context = context, status = status, serverUrl = if (status == AttachmentInfoItem.Status.Success) { BuildConfig.CM_COMMON_URL + "/files/%s/%s".format( uploadFileType, externalId ) } else { "" } ) } } ?: kotlin.run { if (whileCount > whileLimit) { return AttachmentInfoItem( uri = uri, status = AttachmentInfoItem.Status.Failed("checkFileStatus fail, is null response.") ) } } delay(delayTime * 1000) } return AttachmentInfoItem( uri = uri, status = AttachmentInfoItem.Status.Failed("upload failed.") ) } /** * 取得 Url 內容 */ suspend fun getUrlContent(url: String) = network.getContent(url) } object AttachmentController { private val TAG = "AttachmentController" /** * 點擊附加檔案預覽 * @param onRecordClick 當點擊的是錄音檔的回調,預設為使用player播放器播放。可透過傳遞lambda改為使用錄音的介面播放 */ fun onAttachmentClick( navController: DestinationsNavigator, attachmentInfoItem: AttachmentInfoItem, context: Context, fileName: String = "", duration: Long = 0, audioViewModel: AudioViewModel? = null, onRecordClick: ()->Unit = { val uri = attachmentInfoItem.uri audioViewModel?.apply { playSilence( uri = uri, duration = duration, title = "錄音" ) openBottomPlayer() } ?: kotlin.run { navController.navigate( AudioPreviewScreenDestination( uri = uri, duration = duration, title = "錄音" ) ) } } ) { val type = attachmentInfoItem.attachmentType KLog.i(TAG, "onAttachmentClick:$attachmentInfoItem type:$type") when (type) { AttachmentType.VoiceMessage -> { onRecordClick() } AttachmentType.Audio -> { val uri = attachmentInfoItem.uri audioViewModel?.apply { playSilence( uri = uri, duration = duration, title = fileName ) openBottomPlayer() } ?: kotlin.run { navController.navigate( AudioPreviewScreenDestination( uri = uri, duration = duration, title = fileName ) ) } } AttachmentType.Image -> { val uri = attachmentInfoItem.uri StfalconImageViewer .Builder( context, listOf(uri) ) { imageView, image -> Glide .with(context) .load(image) .into(imageView) } .show() } AttachmentType.Pdf -> { val uri = attachmentInfoItem.uri navController.navigate( PdfPreviewScreenDestination( uri = uri, title = fileName ) ) } AttachmentType.Txt -> { val uri = attachmentInfoItem.uri navController.navigate( TextPreviewScreenDestination( uri = uri, fileName = fileName ) ) } AttachmentType.Unknown -> { } AttachmentType.Choice -> { attachmentInfoItem.other?.let { if (it is VoteModel) { navController.navigate( CreateChoiceQuestionScreenDestination( voteModel = it ) ) } } } else -> { } } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/AttachmentUseCase.kt
1983018209
package com.cmoney.kolfanci.model.usecase import com.cmoney.kolfanci.extension.checkResponseBody import com.cmoney.fanciapi.fanci.api.UserApi import com.cmoney.fanciapi.fanci.model.UserParam import com.cmoney.xlogin.XLoginHelper class UserUseCase(private val userApi: UserApi) { /** * 取得我的個人資訊 */ suspend fun fetchMyInfo() = kotlin.runCatching { userApi.apiV1UserMeGet().checkResponseBody() } suspend fun registerUser() = kotlin.runCatching { userApi.apiV1UserMePut( UserParam( name = XLoginHelper.nickName, thumbNail = XLoginHelper.headImagePath ) ) } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/UserUseCase.kt
3630857979
package com.cmoney.kolfanci.model.usecase import android.content.Context import com.cmoney.fanciapi.fanci.api.ChatRoomApi import com.cmoney.fanciapi.fanci.api.MessageApi import com.cmoney.fanciapi.fanci.api.UserReportApi import com.cmoney.fanciapi.fanci.model.ChannelTabType import com.cmoney.fanciapi.fanci.model.ChatMessage import com.cmoney.fanciapi.fanci.model.ChatMessagePaging import com.cmoney.fanciapi.fanci.model.ChatMessageParam import com.cmoney.fanciapi.fanci.model.EmojiParam import com.cmoney.fanciapi.fanci.model.Emojis import com.cmoney.fanciapi.fanci.model.MessageIdParam import com.cmoney.fanciapi.fanci.model.MessageServiceType import com.cmoney.fanciapi.fanci.model.OrderType import com.cmoney.fanciapi.fanci.model.ReportParm import com.cmoney.fanciapi.fanci.model.ReportReason import com.cmoney.kolfanci.extension.checkResponseBody import com.cmoney.kolfanci.model.Constant import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem import com.cmoney.kolfanci.model.attachment.AttachmentType import com.cmoney.kolfanci.model.attachment.toUploadMedia import com.cmoney.kolfanci.model.mock.MockData import com.cmoney.kolfanci.model.vote.VoteModel import com.socks.library.KLog class ChatRoomUseCase( val context: Context, private val chatRoomApi: ChatRoomApi, private val messageApi: MessageApi, private val userReport: UserReportApi ) { private val TAG = ChatRoomUseCase::class.java.simpleName /** * 取得單一訊息 */ suspend fun getSingleMessage(messageId: String, messageServiceType: MessageServiceType) = kotlin.runCatching { messageApi.apiV2MessageMessageTypeMessageIdGet( messageType = messageServiceType, messageId = messageId ).checkResponseBody() } /** * 更新訊息 * * @param messageServiceType 更新訊息 or 貼文 * @param messageId 訊息 id * @param text 內文 * @param attachment 附加檔案 */ suspend fun updateMessage( messageServiceType: MessageServiceType, messageId: String, text: String, attachment: List<Pair<AttachmentType, AttachmentInfoItem>> ) = kotlin.runCatching { val medias = attachment.toUploadMedia(context) //投票 id val votingIds = attachment.filter { it.first == AttachmentType.Choice && it.second.other is VoteModel }.map { (it.second.other as VoteModel).id } val chatMessageParam = ChatMessageParam( text = text, medias = medias, votingIds = votingIds ) messageApi.apiV2MessageMessageTypeMessageIdPut( messageType = messageServiceType, messageId = messageId, chatMessageParam = chatMessageParam ).checkResponseBody() } /** * 刪除他人訊息 */ suspend fun deleteOtherMessage(messageServiceType: MessageServiceType, messageId: String) = kotlin.runCatching { messageApi.apiV2MessageRoleMessageTypeMessageIdDelete( messageType = messageServiceType, messageId = messageId ).checkResponseBody() } /** * 刪除自己發送的訊息 */ suspend fun takeBackMyMessage(messageServiceType: MessageServiceType, messageId: String) = kotlin.runCatching { messageApi.apiV2MessageMeMessageTypeMessageIdDelete( messageType = messageServiceType, messageId = messageId ).checkResponseBody() } /** * 檢舉內容 * @param channelId 頻道 id * @param contentId 哪一篇文章 * @param reason 原因 * @param tabType 聊天室 or 貼文 */ suspend fun reportContent( channelId: String, contentId: String, reason: ReportReason, tabType: ChannelTabType = ChannelTabType.chatRoom ) = kotlin.runCatching { userReport.apiV1UserReportChannelChannelIdPost( channelId = channelId, reportParm = ReportParm( contentId = contentId, reason = reason, tabType = tabType ) ).checkResponseBody() } /** * 取得 公告 訊息 * @param channelId 頻道id */ suspend fun getAnnounceMessage(channelId: String) = kotlin.runCatching { chatRoomApi.apiV1ChatRoomChatRoomChannelIdPinnedMessageGet( chatRoomChannelId = channelId ).checkResponseBody() } /** * 設定 公告 訊息 * @param chatMessage 訊息 */ suspend fun setAnnounceMessage(channelId: String, chatMessage: ChatMessage) = kotlin.runCatching { chatRoomApi.apiV1ChatRoomChatRoomChannelIdPinnedMessagePut( chatRoomChannelId = channelId, messageIdParam = MessageIdParam( messageId = chatMessage.id.orEmpty() ) ).checkResponseBody() } /** * 取消 聊天室 公告 */ suspend fun cancelAnnounceMessage(channelId: String) = kotlin.runCatching { chatRoomApi.apiV1ChatRoomChatRoomChannelIdPinnedMessageDelete( chatRoomChannelId = channelId, ).checkResponseBody() } /** * 針對指定訊息 發送 Emoji * @param messageId 針對的訊息Id * @param emoji 要發送的 Emoji */ suspend fun sendEmoji( messageServiceType: MessageServiceType, messageId: String, emoji: Emojis ) = kotlin.runCatching { messageApi.apiV2MessageMessageTypeMessageIdEmojiPut( messageType = messageServiceType, messageId = messageId, emojiParam = EmojiParam( emoji = emoji ) ).checkResponseBody() } /** * 收回 Emoji * @param messageId 訊息 id */ suspend fun deleteEmoji(messageServiceType: MessageServiceType, messageId: String) = kotlin.runCatching { messageApi.apiV2MessageMessageTypeMessageIdEmojiDelete( messageType = messageServiceType, messageId = messageId ).checkResponseBody() } /** * 點擊 emoji */ suspend fun clickEmoji( messageServiceType: MessageServiceType, messageId: String, emojiCount: Int, clickEmoji: Emojis ) = kotlin.runCatching { if (emojiCount == -1) { //收回 deleteEmoji(messageServiceType, messageId).fold({ KLog.e(TAG, "delete emoji success.") }, { KLog.e(TAG, it) }) } else { //增加 sendEmoji(messageServiceType, messageId, clickEmoji).fold({ KLog.i(TAG, "sendEmoji success.") }, { KLog.e(TAG, it) }) } } /** * 讀取更多 分頁訊息 * @param chatRoomChannelId 聊天室 id * @param fromSerialNumber 從哪一個序列號開始往回找 (若為Null 則從最新開始拿) */ suspend fun fetchMoreMessage( chatRoomChannelId: String, fromSerialNumber: Long?, order: OrderType = OrderType.latest ) = kotlin.runCatching { if (Constant.isOpenMock) { ChatMessagePaging( items = MockData.mockListMessage ) } else { chatRoomApi.apiV1ChatRoomChatRoomChannelIdMessageGet( chatRoomChannelId = chatRoomChannelId, fromSerialNumber = fromSerialNumber, order = order ).checkResponseBody() } } /** * 發送訊息 * * @param chatRoomChannelId 聊天室 id * @param text 內文 * @param attachment 附加檔案 * @param replyMessageId 回覆訊息的id */ suspend fun sendMessage( chatRoomChannelId: String, text: String, attachment: List<Pair<AttachmentType, AttachmentInfoItem>>, replyMessageId: String = "" ) = kotlin.runCatching { val votingIds = attachment.filter { it.first == AttachmentType.Choice }.mapNotNull { (it.second.other as VoteModel).id } chatRoomApi.apiV1ChatRoomChatRoomChannelIdMessagePost( chatRoomChannelId = chatRoomChannelId, chatMessageParam = ChatMessageParam( text = text, medias = attachment.toUploadMedia(context), replyMessageId = replyMessageId, votingIds = votingIds ) ).checkResponseBody() } /** * 收回訊息 * @param messageId 訊息 id */ suspend fun recycleMessage( messageServiceType: MessageServiceType, messageId: String ) = takeBackMyMessage( messageServiceType, messageId ) }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/ChatRoomUseCase.kt
4090944913
package com.cmoney.kolfanci.model.usecase import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.withStyle import com.cmoney.fanciapi.fanci.api.ChatRoomApi import com.cmoney.fanciapi.fanci.api.MessageApi import com.cmoney.fanciapi.fanci.model.ChatMessage import com.cmoney.fanciapi.fanci.model.MessageServiceType import com.cmoney.fanciapi.fanci.model.OrderType import com.cmoney.kolfanci.extension.checkResponseBody import com.cmoney.kolfanci.model.mock.MockData import com.cmoney.kolfanci.ui.screens.search.model.SearchChatMessage import com.cmoney.kolfanci.ui.screens.search.model.SearchType import com.cmoney.kolfanci.utils.Utils import kotlin.random.Random class SearchUseCase( private val messageApi: MessageApi, private val chatRoomApi: ChatRoomApi ) { /** * 搜尋 * * @param keyword 關鍵字 */ suspend fun doSearch(keyword: String): Result<List<SearchChatMessage>> { return Result.success( MockData.mockListMessage.map { val randomType = Random.nextBoolean() val searchType = if (randomType) { SearchType.Chat } else { SearchType.Post } SearchChatMessage( searchKeyword = keyword, searchType = searchType, message = it, subTitle = getSearchMessageSubTitle( searchType = searchType, message = it ), highlightMessage = getHighlightTxt( message = it.content?.text.orEmpty(), keyword = keyword ) ) } ) } /** * 取得搜尋結果的 subtitle * ex: 聊天・2023.01.13 */ private fun getSearchMessageSubTitle(searchType: SearchType, message: ChatMessage): String { val typeString = when (searchType) { SearchType.Chat -> "聊天" SearchType.Post -> "貼文" } val createTime = message.createUnixTime?.div(1000) ?: 0 val displayTime = Utils.getSearchDisplayTime(createTime) return "%s・%s".format(typeString, displayTime) } /** * 將關鍵字highlight動作 * * @param message 原始訊息 * @param keyword 要 highlight 的關鍵字 */ private fun getHighlightTxt(message: String, keyword: String): AnnotatedString { val span = SpanStyle( color = Color.Red, fontWeight = FontWeight.Bold ) return buildAnnotatedString { var start = 0 while (message.indexOf( keyword, start, ignoreCase = true ) != -1 && keyword.isNotBlank() ) { val firstIndex = message.indexOf(keyword, start, true) val end = firstIndex + keyword.length append(message.substring(start, firstIndex)) withStyle(style = span) { append(message.substring(firstIndex, end)) } start = end } append(message.substring(start, message.length)) toAnnotatedString() } } /** * 取得單一貼文訊息 */ suspend fun getSinglePostMessage(messageId: String) = kotlin.runCatching { messageApi.apiV2MessageMessageTypeMessageIdGet( messageType = MessageServiceType.bulletinboard, messageId = messageId ).checkResponseBody() } /** * 根據原始訊息,抓取上下文各10則訊息串起來 * * @param channelId 頻道id * @param message 要查詢的訊息 */ suspend fun getChatMessagePreload(channelId: String, message: ChatMessage): List<ChatMessage> { val preMessage = getPreMessage( channelId = channelId, serialNumber = message.serialNumber ?: 0L ).getOrNull().orEmpty() val backMessage = getBackMessage( channelId = channelId, serialNumber = message.serialNumber ?: 0L ).getOrNull().orEmpty() return buildList { addAll(preMessage) add(message) addAll(backMessage) } } /** * 往前抓取10則訊息 */ private suspend fun getPreMessage(channelId: String, serialNumber: Long) = kotlin.runCatching { //TODO // chatRoomApi.apiV1ChatRoomChatRoomChannelIdMessageGet( // chatRoomChannelId = channelId, // fromSerialNumber = serialNumber, // order = OrderType.oldest, // take = 10 // ).checkResponseBody().items.orEmpty() MockData.mockListMessage } /** * 往後抓取10則訊息 */ private suspend fun getBackMessage(channelId: String, serialNumber: Long) = kotlin.runCatching { //TODO // chatRoomApi.apiV1ChatRoomChatRoomChannelIdMessageGet( // chatRoomChannelId = channelId, // fromSerialNumber = serialNumber, // order = OrderType.latest, // take = 10 // ).checkResponseBody().items.orEmpty() MockData.mockListMessage } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/SearchUseCase.kt
4113702569
package com.cmoney.kolfanci.model.usecase import com.cmoney.fanciapi.fanci.api.VotingApi import com.cmoney.fanciapi.fanci.model.CastVoteParam import com.cmoney.fanciapi.fanci.model.DeleteVotingsParam import com.cmoney.fanciapi.fanci.model.VotingOption import com.cmoney.fanciapi.fanci.model.VotingParam import com.cmoney.kolfanci.extension.checkResponseBody import com.cmoney.kolfanci.model.Constant import com.cmoney.kolfanci.model.mock.MockData import com.cmoney.kolfanci.model.vote.VoteModel import com.socks.library.KLog import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow /** * 投票相關 */ class VoteUseCase( private val votingApi: VotingApi ) { private val TAG = VoteUseCase::class.java.simpleName /** * 建立多筆 投票 * * @param channelId 頻道 id * @param voteModels 投票 modes */ suspend fun createVotes(channelId: String, voteModels: List<VoteModel>): Flow<VoteModel> = flow { voteModels.forEach { voteModel -> try { val votingId = voteModel.id.ifEmpty { createVote( channelId = channelId, voteModel = voteModel ).getOrNull()?.id.orEmpty() } emit( voteModel.copy(id = votingId) ) } catch (e: Exception) { KLog.e(TAG, e) } } } /** * 建立投票 * * @param channelId 頻道id * @param voteModel 投票model */ private suspend fun createVote(channelId: String, voteModel: VoteModel) = kotlin.runCatching { KLog.i(TAG, "createVote:$voteModel") val votingParam = VotingParam( title = voteModel.question, votingOptions = voteModel.choice.map { VotingOption(text = it) }, isMultipleChoice = !voteModel.isSingleChoice, isAnonymous = false ) votingApi.apiV1VotingPost( channelId = channelId, votingParam = votingParam ).checkResponseBody() } /** * 刪除投票 * @param channelId 頻道id * @param voteIds 投票id */ suspend fun deleteVote(channelId: String, voteIds: List<String>): Result<Unit> { KLog.i(TAG, "deleteVote:$channelId") return kotlin.runCatching { votingApi.apiV1VotingDelete( channelId = channelId, deleteVotingsParam = DeleteVotingsParam( votingIds = voteIds ) ).checkResponseBody() } } /** * 頻道投票動作 * * @param channelId 頻道 id * @param votingId 投票 id * @param choice 所選擇的項目 */ suspend fun choiceVote( channelId: String, votingId: String, choice: List<String> ) = kotlin.runCatching { votingApi.apiV1VotingVotingIdCastVotePost( channelId = channelId, votingId = votingId, castVoteParam = CastVoteParam( choice ) ).checkResponseBody() } /** * 結束 投票 */ suspend fun closeVote(channelId: String, votingId: String) = kotlin.runCatching { votingApi.apiV1VotingVotingIdEndPut( votingId = votingId, channelId = channelId ).checkResponseBody() } /** * 取得 投票 統計 * * @param channelId 頻道 id * @param votingId 投票 id */ suspend fun summaryVote(channelId: String, votingId: String) = kotlin.runCatching { if (Constant.isOpenMock) { MockData.mockIVotingOptionStatisticsWithVoterList } else { votingApi.apiV1VotingVotingIdStatisticsGet( channelId = channelId, votingId = votingId ).checkResponseBody() } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/VoteUseCase.kt
2000494044
package com.cmoney.kolfanci.model.usecase import com.cmoney.kolfanci.extension.checkResponseBody import com.cmoney.fanciapi.fanci.api.RelationApi import com.cmoney.fanciapi.fanci.model.Relation import com.cmoney.fanciapi.fanci.model.User import com.cmoney.fanciapi.fanci.model.UserPaging class RelationUseCase(private val relationApi: RelationApi) { /** * 取得 我封鎖 以及 封鎖我 的清單 * @return Pair<Blocking, Blocker> */ suspend fun getMyRelation(): Pair<List<User>, List<User>> { val blockingList = mutableListOf<UserPaging>() val firstBlocking = getBlockingRelation() blockingList.add(firstBlocking) var hasNextBlockingPage = firstBlocking.haveNextPage == true while (hasNextBlockingPage) { val blockingPage = getBlockingRelation(skip = blockingList.size) blockingList.add(blockingPage) hasNextBlockingPage = blockingPage.haveNextPage == true } val blockerList = mutableListOf<UserPaging>() val firstBlocker = getBlockerRelation() blockerList.add(firstBlocker) var hasNextBlockerPage = firstBlocker.haveNextPage == true while (hasNextBlockerPage) { val blockerPage = getBlockingRelation(skip = blockerList.size) blockerList.add(blockerPage) hasNextBlockerPage = blockerPage.haveNextPage == true } return Pair( blockingList.distinctBy { it.items }.map { it.items.orEmpty() }.flatten(), blockerList.distinctBy { it.items }.map { it.items.orEmpty() }.flatten() ) } /** * 取得 我封鎖的清單 */ private suspend fun getBlockingRelation(skip: Int = 0) = relationApi.apiV1RelationRelationMeGet( skip = skip, relation = Relation.blocking ).checkResponseBody() /** * 取得 封鎖我的清單 */ private suspend fun getBlockerRelation(skip: Int = 0) = relationApi.apiV1RelationRelationMeGet( skip = skip, relation = Relation.blocker ).checkResponseBody() /** * 封鎖對方 * @param userId 被封鎖的人 */ suspend fun blocking(userId: String) = kotlin.runCatching { relationApi.apiV1RelationRelationMeBlockUserIdPut( relation = Relation.blocking, blockUserId = userId ).checkResponseBody() } /** * 解除封鎖對方 * @param userId 被封鎖的人 */ suspend fun disBlocking(userId: String) = kotlin.runCatching { relationApi.apiV1RelationRelationMeBlockUserIdDelete( relation = Relation.blocking, blockUserId = userId ).checkResponseBody() } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/RelationUseCase.kt
3119216666
package com.cmoney.kolfanci.model.usecase import com.cmoney.kolfanci.extension.checkResponseBody import com.cmoney.fanciapi.fanci.api.BanApi import com.cmoney.fanciapi.fanci.model.BanParam import com.cmoney.fanciapi.fanci.model.BanPeriodOption import com.cmoney.fanciapi.fanci.model.UseridsParam class BanUseCase( private val banApi: BanApi ) { /** * 取得 使用者 禁言狀態 * @param groupId 社團id * @param userId 查詢的 user */ suspend fun fetchBanInfo(groupId: String, userId: String) = kotlin.runCatching { banApi.apiV1BanGroupGroupIdUserIdGet( groupId = groupId, userId = userId ).checkResponseBody() } /** * 解除 禁言 * @param groupId 社團id * @param userIds 解除禁言 user */ suspend fun liftBanUser(groupId: String, userIds: List<String>) = kotlin.runCatching { banApi.apiV1BanGroupGroupIdDelete( groupId = groupId, useridsParam = UseridsParam( userIds = userIds ) ) } /** * 取得 社團 禁言清單 * @param groupId 社團 id */ suspend fun fetchBanList(groupId: String) = kotlin.runCatching { banApi.apiV1BanGroupGroupIdGet(groupId).checkResponseBody() } /** * 禁言使用者 * @param groupId 社團 id * @param userId * @param banPeriodOption 被ban週期 */ suspend fun banUser(groupId: String, userId: String, banPeriodOption: BanPeriodOption) = kotlin.runCatching { banApi.apiV1BanGroupGroupIdPut( groupId = groupId, banParam = BanParam( userid = userId, periodOption = banPeriodOption ) ).checkResponseBody() } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/BanUseCase.kt
3462963363
package com.cmoney.kolfanci.model.usecase import com.cmoney.fanciapi.fanci.api.BulletinBoardApi import com.cmoney.fanciapi.fanci.api.MessageApi import com.cmoney.fanciapi.fanci.model.BulletinboardMessagePaging import com.cmoney.fanciapi.fanci.model.MessageServiceType import com.cmoney.fanciapi.fanci.model.OrderType import com.cmoney.kolfanci.extension.checkResponseBody import com.cmoney.kolfanci.extension.toBulletinboardMessage import com.socks.library.KLog import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.flowOn class PostPollUseCase( private val bulletinBoardApi: BulletinBoardApi, private val messageApi: MessageApi, private val dispatcher: CoroutineDispatcher = Dispatchers.IO ) { private val TAG = ChatRoomPollUseCase::class.java.simpleName private var isScopeClose = false fun pollScope( delay: Long, channelId: String, fromSerialNumber: Long?, fetchCount: Int, messageId: String, ): Flow<BulletinboardMessagePaging> { KLog.i(TAG, "pollScope") isScopeClose = false return channelFlow { while (!isScopeClose) { kotlin.runCatching { bulletinBoardApi.apiV1BulletinBoardChannelIdMessageGet( channelId = channelId, take = fetchCount, order = OrderType.latest, fromSerialNumber = fromSerialNumber ).checkResponseBody() }.onSuccess { send(it) }.onFailure { KLog.e(TAG, it) } //取得單篇文章, 因為取得一系列的資料, 不會包含自己 kotlin.runCatching { messageApi.apiV2MessageMessageTypeMessageIdGet( messageType = MessageServiceType.bulletinboard, messageId = messageId ).checkResponseBody() }.onSuccess { chatMessage -> chatMessage.toBulletinboardMessage() send(BulletinboardMessagePaging(items = listOf(chatMessage.toBulletinboardMessage()))) }.onFailure { KLog.e(TAG, it) } delay(delay) } }.flowOn(dispatcher) } fun closeScope() { isScopeClose = true } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/PostPollUseCase.kt
482727727
package com.cmoney.kolfanci.model.usecase import android.app.Application import android.content.Intent import android.net.Uri import com.cmoney.kolfanci.BuildConfig import com.cmoney.kolfanci.R import com.cmoney.kolfanci.model.notification.NotificationHelper import com.cmoney.kolfanci.model.notification.Payload import com.google.firebase.dynamiclinks.FirebaseDynamicLinks import com.google.firebase.dynamiclinks.ShortDynamicLink import com.google.firebase.dynamiclinks.ktx.androidParameters import com.google.firebase.dynamiclinks.ktx.dynamicLinks import com.google.firebase.dynamiclinks.ktx.iosParameters import com.google.firebase.dynamiclinks.ktx.shortLinkAsync import com.google.firebase.dynamiclinks.ktx.socialMetaTagParameters import com.google.firebase.ktx.Firebase import com.socks.library.KLog import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class DynamicLinkUseCase( private val context: Application, private val notificationHelper: NotificationHelper ) { private val TAG = DynamicLinkUseCase::class.java.simpleName suspend fun createInviteGroupLink(groupId: String, ogImage: String): String? = suspendCoroutine { cont -> val baseLink = context.getString(R.string.deeplink_baseLink).format(groupId) Firebase.dynamicLinks.shortLinkAsync(ShortDynamicLink.Suffix.SHORT) { link = Uri.parse(baseLink) domainUriPrefix = context.getString(R.string.deeplink_domain_prefix) androidParameters(BuildConfig.APPLICATION_ID) { } iosParameters("CMoney.KOLfanci") { appStoreId = "6443794078" } socialMetaTagParameters { title = context.getString(R.string.deeplink_title) description = context.getString(R.string.deeplink_description) imageUrl = Uri.parse(ogImage) } }.addOnSuccessListener { KLog.i(TAG, "createInviteTeamLink:" + it.shortLink) cont.resume(it.shortLink.toString()) }.addOnFailureListener { KLog.e(TAG, "createInviteTeamLink error:$it") cont.resume(null) } } suspend fun getDynamicsLinksParam(intent: Intent): Payload? = suspendCoroutine { cont -> var intentParam: Payload? = null FirebaseDynamicLinks.getInstance() .getDynamicLink(intent) .addOnCompleteListener { if (it.isSuccessful) { it.result?.link?.let { deepLink -> intentParam = notificationHelper.getShareIntentPayload(deepLink) } } cont.resume(intentParam) } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/DynamicLinkUseCase.kt
3461912445
package com.cmoney.kolfanci.model.usecase import android.content.Context import android.graphics.Bitmap import android.net.Uri import android.os.Environment import com.cmoney.backend2.centralizedimage.service.CentralizedImageWeb import com.cmoney.backend2.centralizedimage.service.api.upload.GenreAndSubGenre import com.cmoney.backend2.centralizedimage.service.api.upload.UploadResponseBody import com.cmoney.compress_image.CompressSetting import com.cmoney.compress_image.resizeAndCompressAndRotateImage import com.cmoney.kolfanci.extension.getFileType import com.cmoney.kolfanci.extension.toUploadFileItem import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem import com.socks.library.KLog import kotlinx.coroutines.flow.flow import java.io.File import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException import java.io.InputStream import java.util.Calendar private const val IMAGE_SIZE = 1024 * 1024 //1MB class UploadImageUseCase( val context: Context, private val centralizedImageWeb: CentralizedImageWeb ) { private val TAG = UploadImageUseCase::class.java.simpleName suspend fun uploadImage2(uriLis: List<Uri>) = flow { uriLis.forEach { uri -> val uploadResponseBody = fetchImageUrl(uri) uploadResponseBody?.let { uploadResponse -> KLog.i(TAG, "uploadImage success:$uploadResponse") emit( uri.toUploadFileItem( context = context, status = AttachmentInfoItem.Status.Success, serverUrl = uploadResponse.url.orEmpty() ) ) } ?: kotlin.run { emit( AttachmentInfoItem( uri = uri, status = AttachmentInfoItem.Status.Failed("uploadImage failed.") ) ) } } } suspend fun uploadImage(uriLis: List<Uri>) = flow { uriLis.forEach { uri -> val uploadResponseBody = fetchImageUrl(uri) uploadResponseBody?.let { uploadResponse -> KLog.i(TAG, "uploadImage success:$uploadResponse") emit(Pair(uri, uploadResponse.url.orEmpty())) } ?: kotlin.run { val errMsg = "Upload error." throw Exception(errMsg) } } } private suspend fun fetchImageUrl(uri: Uri): UploadResponseBody? { val imageFile = createUploadFile(uri, context) imageFile?.let { val fileType = uri.getFileType(context) val compressSetting = if (fileType == "image/png") { CompressSetting( contentFile = imageFile, format = Bitmap.CompressFormat.PNG, compressedFileName = "%s.png".format( "CMoney_${Calendar.getInstance().timeInMillis}" ), compressedFolder = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)!!, maxImageSize = IMAGE_SIZE ) } else { CompressSetting( contentFile = imageFile, compressedFolder = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)!!, maxImageSize = IMAGE_SIZE ) } val compressFile = resizeAndCompressAndRotateImage(compressSetting) return centralizedImageWeb.upload( GenreAndSubGenre.AttachmentBlog, compressFile ).getOrNull() } ?: kotlin.run { val errMsg = "File not exists error!" throw Exception(errMsg) } } /** * change uri to file. */ private fun createUploadFile(uri: Uri, context: Context): File? { var tempFile: File? = null try { val storageDir: File? = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) tempFile = File.createTempFile("IMG_", ".jpg", storageDir) val outputStream = FileOutputStream(tempFile ?: return null) val inputStream: InputStream? = context.contentResolver.openInputStream(uri) val buffer = ByteArray(inputStream?.available() ?: return null) inputStream.read(buffer) outputStream.write(buffer) inputStream.close() outputStream.close() } catch (e: FileNotFoundException) { KLog.e(TAG, e) } catch (e: IOException) { KLog.e(TAG, e) } finally { tempFile?.deleteOnExit() } return tempFile } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/UploadImageUseCase.kt
3062358947
package com.cmoney.kolfanci.model.usecase import com.cmoney.kolfanci.extension.checkResponseBody import com.cmoney.fanciapi.fanci.api.OrderApi import com.cmoney.fanciapi.fanci.model.Category import com.cmoney.fanciapi.fanci.model.CategoryOrder import com.cmoney.fanciapi.fanci.model.OrderParam import com.cmoney.fanciapi.fanci.model.RoleOrderParam class OrderUseCase( private val orderApi: OrderApi ) { /** * 排序 分類/頻道 * * @param groupId 社團id * @param category 分類 */ suspend fun orderCategoryOrChannel( groupId: String, category: List<Category> ) = kotlin.runCatching { val orderParam = category.map { CategoryOrder( categoryId = it.id.orEmpty(), channelIds = it.channels?.map { channel -> channel.id.orEmpty() } ) } orderApi.apiV1OrderGroupGroupIdPut( groupId = groupId, orderParam = OrderParam( categoryOrders = orderParam ) ).checkResponseBody() } /** * 重新排序 角色清單 */ suspend fun orderRole( groupId: String, roleIds: List<String> ) = kotlin.runCatching { orderApi.apiV1OrderGroupGroupIdRoleOrderPut( groupId = groupId, roleOrderParam = RoleOrderParam( roleIds = roleIds ) ).checkResponseBody() } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/OrderUseCase.kt
3918739881
package com.cmoney.kolfanci.model.usecase import android.content.Context import android.net.Uri import com.cmoney.fanciapi.fanci.api.DefaultImageApi import com.cmoney.fanciapi.fanci.api.GroupApi import com.cmoney.fanciapi.fanci.api.GroupMemberApi import com.cmoney.fanciapi.fanci.api.GroupRequirementApi import com.cmoney.fanciapi.fanci.api.PermissionApi import com.cmoney.fanciapi.fanci.api.RoleUserApi import com.cmoney.fanciapi.fanci.api.UserReportApi import com.cmoney.fanciapi.fanci.model.Color import com.cmoney.fanciapi.fanci.model.ColorTheme import com.cmoney.fanciapi.fanci.model.EditGroupParam import com.cmoney.fanciapi.fanci.model.Group import com.cmoney.fanciapi.fanci.model.GroupParam import com.cmoney.fanciapi.fanci.model.GroupRequirementParam import com.cmoney.fanciapi.fanci.model.GroupRequirementQuestion import com.cmoney.fanciapi.fanci.model.GroupRequirementQuestionType import com.cmoney.fanciapi.fanci.model.OrderType import com.cmoney.fanciapi.fanci.model.ReportProcessStatus import com.cmoney.fanciapi.fanci.model.ReportStatusUpdateParam import com.cmoney.fanciapi.fanci.model.RoleColor import com.cmoney.fanciapi.fanci.model.RoleIdsParam import com.cmoney.fanciapi.fanci.model.RoleParam import com.cmoney.fanciapi.fanci.model.UpdateIsNeedApprovalParam import com.cmoney.fanciapi.fanci.model.UseridsParam import com.cmoney.kolfanci.extension.checkResponseBody import com.cmoney.kolfanci.model.Constant import com.cmoney.kolfanci.model.mock.MockData import com.cmoney.kolfanci.ui.screens.follow.model.GroupItem import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.withContext class GroupUseCase( val context: Context, private val groupApi: GroupApi, private val groupMemberApi: GroupMemberApi, private val defaultImageApi: DefaultImageApi, private val permissionApi: PermissionApi, private val roleUserApi: RoleUserApi, private val groupRequirement: GroupRequirementApi, private val userReport: UserReportApi, private val uploadImageUseCase: UploadImageUseCase ) { /** * 取得會員資訊 * * @param groupId 社團 id * @param userIds 會員 ids */ suspend fun getGroupMembers(groupId: String, userIds: List<String>) = kotlin.runCatching { if (Constant.isOpenMock) { listOf( MockData.mockGroupMember, MockData.mockGroupMember, MockData.mockGroupMember, MockData.mockGroupMember ) } else { groupMemberApi.apiV1GroupMemberGroupGroupIdUsersPost( groupId = groupId, useridsParam = UseridsParam( userIds = userIds ) ).checkResponseBody() } } /** * 取得特定 group */ suspend fun getGroupById(groupId: String) = kotlin.runCatching { groupApi.apiV1GroupGroupIdGet( groupId = groupId ).checkResponseBody() } /** * 刪除/解散 社團 */ suspend fun deleteGroup(groupId: String) = kotlin.runCatching { groupApi.apiV1GroupGroupIdDelete(groupId = groupId).checkResponseBody() } /** * 刪除 角色 * @param groupId 社團id * @param roleId 角色 id */ suspend fun deleteRole(groupId: String, roleId: String) = kotlin.runCatching { groupApi.apiV1GroupGroupIdRoleRoleIdDelete( groupId = groupId, roleId = roleId ).checkResponseBody() } /** * 更新 處理狀態 * @param channelId 頻道 * @param reportId 檢舉 id * @param reportProcessStatus 檢舉狀態 */ suspend fun handlerReport( channelId: String, reportId: String, reportProcessStatus: ReportProcessStatus ) = kotlin.runCatching { userReport.apiV1UserReportChannelChannelIdIdPut( channelId = channelId, id = reportId, reportStatusUpdateParam = ReportStatusUpdateParam( status = reportProcessStatus ) ).checkResponseBody() } /** * 取得 檢舉審核清單 */ suspend fun getReportList(groupId: String) = kotlin.runCatching { userReport.apiV1UserReportGroupGroupIdGet( groupId = groupId ).checkResponseBody() } /** * 建立社團 * * @param name 社團名稱 * @param description 社團描述, 一開始建立時,可以不用輸入 (需求) * @param isNeedApproval 是否需要認證 * @param coverImageUrl 背景圖 * @param thumbnailImageUrl 小圖 * @param themeId 背景主題Id */ suspend fun createGroup( name: String, description: String = "", isNeedApproval: Boolean, coverImageUrl: String, logoImageUrl: String, thumbnailImageUrl: String, themeId: String ) = kotlin.runCatching { groupApi.apiV1GroupPost( groupParam = GroupParam( name = name, description = description, isNeedApproval = isNeedApproval, coverImageUrl = coverImageUrl, thumbnailImageUrl = thumbnailImageUrl, logoImageUrl = logoImageUrl, colorSchemeGroupKey = ColorTheme.decode(themeId) ) ).checkResponseBody() } /** * 設定 加入社團 問題清單 * @param groupId 社團 id * @param question 問題清單 */ suspend fun setGroupRequirementQuestion(groupId: String, question: List<String>) = kotlin.runCatching { groupRequirement.apiV1GroupRequirementGroupGroupIdPut( groupId = groupId, groupRequirementParam = GroupRequirementParam( questions = question.map { GroupRequirementQuestion( question = it, type = GroupRequirementQuestionType.written ) } ) ).checkResponseBody() } /** * 抓取 加入要求題目 */ suspend fun fetchGroupRequirement(groupId: String) = kotlin.runCatching { groupRequirement.apiV1GroupRequirementGroupGroupIdGet(groupId = groupId).checkResponseBody() } /** * * 設定 社團 是否需要審核 * * @param groupId 社團 id * @param isNeedApproval 是否需要審核 */ suspend fun setGroupNeedApproval(groupId: String, isNeedApproval: Boolean) = kotlin.runCatching { groupApi.apiV1GroupGroupIdIsNeedApprovalPut( groupId = groupId, updateIsNeedApprovalParam = UpdateIsNeedApprovalParam( isNeedApproval = isNeedApproval ) ).checkResponseBody() } /** * 剔除成員 * @param groupId 社團id * @param userId 要被踢除的會員 id */ suspend fun kickOutMember(groupId: String, userId: String) = kotlin.runCatching { groupMemberApi.apiV1GroupMemberGroupGroupIdUserIdDelete( groupId, userId ).checkResponseBody() } /** * 取得 具有該角色權限的使用者清單 * @param groupId 社團id * @param roleId 角色id */ suspend fun fetchRoleMemberList( groupId: String, roleId: String ) = kotlin.runCatching { roleUserApi.apiV1RoleUserGroupGroupIdRoleRoleIdGet( groupId = groupId, roleId = roleId ).checkResponseBody() } /** * 移除使用者多個 角色權限 * * @param groupId 社團 id * @param userId 使用者id * @param roleIds 角色清單 */ suspend fun removeRoleFromUser(groupId: String, userId: String, roleIds: List<String>) = kotlin.runCatching { roleUserApi.apiV1RoleUserGroupGroupIdMemberUserIdDelete( groupId = groupId, userId = userId, roleIdsParam = RoleIdsParam(roleIds = roleIds) ).checkResponseBody() } /** * 移除多個使用者的角色 * @param groupId 群組id * @param roleId 角色id * @param userId 要移除的 user 清單 */ suspend fun removeUserRole( groupId: String, roleId: String, userId: List<String> ) = kotlin.runCatching { roleUserApi.apiV1RoleUserGroupGroupIdRoleRoleIdDelete( groupId = groupId, roleId = roleId, useridsParam = UseridsParam( userIds = userId ) ).checkResponseBody() } /** * 指派 使用者 多個角色 * @param groupId 社團 id * @param userId 使用者id * @param roleIds 角色清單 */ suspend fun addRoleToMember(groupId: String, userId: String, roleIds: List<String>) = kotlin.runCatching { roleUserApi.apiV1RoleUserGroupGroupIdMemberUserIdPut( groupId = groupId, userId = userId, roleIdsParam = RoleIdsParam( roleIds = roleIds ) ).checkResponseBody() } /** * 指派 角色身份 給 多個使用者 * @param groupId 社團 id * @param roleId 要分配的角色 id * @param memberList 多個使用者 */ suspend fun addMemberToRole( groupId: String, roleId: String, memberList: List<String> ) = kotlin.runCatching { roleUserApi.apiV1RoleUserGroupGroupIdRoleRoleIdPut( groupId = groupId, roleId = roleId, useridsParam = UseridsParam( userIds = memberList ) ).checkResponseBody() } /** * 社團 新增角色 * * @param groupId 社團 id * @param name 角色名稱 * @param permissionIds 權限清單 * @param colorCode 色碼代碼 */ suspend fun addGroupRole( groupId: String, name: String, permissionIds: List<String>, colorCode: Color ) = kotlin.runCatching { groupApi.apiV1GroupGroupIdRolePost( groupId = groupId, roleParam = RoleParam( name = name, permissionIds = permissionIds, color = RoleColor.decode(colorCode.name) ) ).checkResponseBody() } /** * 社團 編輯角色 * * @param groupId 社團 id * @param roleId 要編輯的角色id * @param name 角色名稱 * @param permissionIds 權限清單 * @param colorCode 色碼代碼 */ suspend fun editGroupRole( groupId: String, roleId: String, name: String, permissionIds: List<String>, colorCode: Color ) = kotlin.runCatching { groupApi.apiV1GroupGroupIdRoleRoleIdPut( groupId = groupId, roleId = roleId, roleParam = RoleParam( name = name, permissionIds = permissionIds, color = RoleColor.decode(colorCode.name) ) ).checkResponseBody() } /** * 取得群組會員清單, 預設抓取20筆 * * @param groupId 群組id * @param skipCount 因為分頁關係,要跳過前幾筆 * @param search 關鍵字搜尋 */ suspend fun getGroupMember(groupId: String, skipCount: Int = 0, search: String? = null) = kotlin.runCatching { groupMemberApi.apiV1GroupMemberGroupGroupIdGet( groupId = groupId, skip = skipCount, search = if (search?.isEmpty() == true) { null } else { search } ).checkResponseBody() } /** * 取得管理權限清單 */ suspend fun fetchPermissionList() = kotlin.runCatching { permissionApi.apiV1PermissionGet().checkResponseBody() } /** * 取得 群組角色列表 */ suspend fun fetchGroupRole(groupId: String) = kotlin.runCatching { groupApi.apiV1GroupGroupIdRoleGet(groupId).checkResponseBody() } /** * 抓取 預設 社團Logo圖庫 */ suspend fun fetchGroupLogoLib() = kotlin.runCatching { defaultImageApi.apiV1DefaultImageGet().checkResponseBody().defaultImages?.get("003") ?: emptyList() } /** * 抓取 預設 大頭貼圖庫 */ suspend fun fetchGroupAvatarLib() = kotlin.runCatching { defaultImageApi.apiV1DefaultImageGet().checkResponseBody().defaultImages?.get("001") ?: emptyList() } /** * 抓取 預設 背景圖庫 */ suspend fun fetchGroupCoverLib() = kotlin.runCatching { defaultImageApi.apiV1DefaultImageGet().checkResponseBody().defaultImages?.get("002") ?: emptyList() } /** * 更換 社團背景圖 * @param uri 圖片Uri * @param group 社團 model */ suspend fun changeGroupBackground(uri: Any, group: Group): Flow<String> { return changeGroupImage(uri, group) { imageUrl -> createEditGroupParam(group, coverImageUrl = imageUrl) } } /** * 更換 社團縮圖 * @param uri 圖片Uri, or 網址 (Fanci 預設) * @param group 社團 model */ suspend fun changeGroupAvatar(uri: Any, group: Group): Flow<String> { return changeGroupImage(uri, group) { imageUrl -> createEditGroupParam(group, thumbnailImageUrl = imageUrl) } } /** * 更換 社團 Logo * @param uri 圖片Uri, or 網址 (Fanci 預設) * @param group 社團 model */ suspend fun changeGroupLogo(uri: Any, group: Group): Flow<String> { return changeGroupImage(uri, group) { imageUrl -> createEditGroupParam(group, logoImageUrl = imageUrl) } } /** * 更換 社團簡介 * @param desc 更換的簡介 * @param group 社團 model */ suspend fun changeGroupDesc(desc: String, group: Group) = kotlin.runCatching { groupApi.apiV1GroupGroupIdPut( groupId = group.id.orEmpty(), editGroupParam = createEditGroupParam(group, desc = desc) ).checkResponseBody() } /** * 更換 社團名字 * @param name 更換的名字 * @param group 社團 model */ suspend fun changeGroupName(name: String, group: Group) = kotlin.runCatching { groupApi.apiV1GroupGroupIdPut( groupId = group.id.orEmpty(), editGroupParam = createEditGroupParam(group, name = name) ).checkResponseBody() } /** * 加入社團 */ suspend fun joinGroup(group: Group) = kotlin.runCatching { groupMemberApi.apiV1GroupMemberGroupGroupIdMePut(group.id.orEmpty()) .checkResponseBody() } /** * 取得 最新 社團列表 */ suspend fun getNewestGroup(pageSize: Int = 100, startWeight: Long = Long.MAX_VALUE) = kotlin.runCatching { groupApi.apiV1GroupGet( startWeight = startWeight, orderType = OrderType.latest, pageSize = pageSize ).checkResponseBody() } /** * 取得 熱門 社團列表 */ suspend fun getPopularGroup(pageSize: Int = 100, startWeight: Long = Long.MAX_VALUE) = kotlin.runCatching { groupApi.apiV1GroupGet( startWeight = startWeight, orderType = OrderType.popular, pageSize = pageSize ).checkResponseBody() } /** * 取得我加入的社團頻道清單 */ private suspend fun getMyJoinGroup() = kotlin.runCatching { groupApi.apiV1GroupMeGet(pageSize = 100).checkResponseBody() } /** * 取得我加入的社團頻道清單, 並設定第一個為目前選中的社團 */ suspend fun groupToSelectGroupItem() = kotlin.runCatching { if (Constant.isOpenMock) { listOf( MockData.mockGroup, MockData.mockGroup, MockData.mockGroup ).mapIndexed { index, group -> GroupItem(group, index == 0) } } else { getMyJoinGroup().getOrNull()?.items?.mapIndexed { index, group -> GroupItem(group, index == 0) }.orEmpty() } } /** * 退出社團 * * @param id 欲退出的社團編號 * @return Result.success 表示退出成功,Result.failure 表示退出失敗 */ suspend fun leaveGroup(id: String): Result<Unit> = withContext(Dispatchers.IO) { kotlin.runCatching { groupMemberApi.apiV1GroupMemberGroupGroupIdMeDelete(groupId = id) .checkResponseBody() } } private fun createEditGroupParam( group: Group, name: String? = null, desc: String? = null, coverImageUrl: String? = null, logoImageUrl: String? = null, thumbnailImageUrl: String? = null ): EditGroupParam { return EditGroupParam( name = name ?: group.name.orEmpty(), description = desc ?: group.description, coverImageUrl = coverImageUrl ?: group.coverImageUrl, thumbnailImageUrl = thumbnailImageUrl ?: group.thumbnailImageUrl, colorSchemeGroupKey = ColorTheme.decode(group.colorSchemeGroupKey?.value), logoImageUrl = logoImageUrl ?: group.logoImageUrl ) } private suspend fun processUriAndGetImageUrl(uri: Any): String { return when (uri) { is Uri -> { val uploadResult = uploadImageUseCase.uploadImage(listOf(uri)).first() uploadResult.second } is String -> uri else -> "" } } private suspend fun changeGroupImage( uri: Any, group: Group, editParam: (String) -> EditGroupParam ): Flow<String> { return flow { val imageUrl = processUriAndGetImageUrl(uri) if (imageUrl.isNotEmpty()) { emit(imageUrl) groupApi.apiV1GroupGroupIdPut( groupId = group.id.orEmpty(), editGroupParam = editParam(imageUrl) ) } }.flowOn(Dispatchers.IO) } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/GroupUseCase.kt
3360248936
package com.cmoney.kolfanci.model.usecase import android.content.Context import com.cmoney.fanciapi.fanci.api.BulletinBoardApi import com.cmoney.fanciapi.fanci.model.BulletinboardMessage import com.cmoney.fanciapi.fanci.model.BulletinboardMessagePaging import com.cmoney.fanciapi.fanci.model.BulletingBoardMessageParam import com.cmoney.fanciapi.fanci.model.MessageIdParam import com.cmoney.fanciapi.fanci.model.OrderType import com.cmoney.kolfanci.extension.checkResponseBody import com.cmoney.kolfanci.model.Constant import com.cmoney.kolfanci.model.attachment.AttachmentInfoItem import com.cmoney.kolfanci.model.attachment.AttachmentType import com.cmoney.kolfanci.model.attachment.toUploadMedia import com.cmoney.kolfanci.model.mock.MockData import com.cmoney.kolfanci.model.vote.VoteModel class PostUseCase( private val context: Context, private val bulletinBoardApi: BulletinBoardApi ) { /** * 取得 置頂貼文 */ suspend fun getPinMessage(channelId: String) = kotlin.runCatching { bulletinBoardApi.apiV1BulletinBoardChannelIdPinnedMessageGet(channelId).checkResponseBody() } /** * 取消置頂貼文 */ suspend fun unPinPost(channelId: String) = kotlin.runCatching { bulletinBoardApi.apiV1BulletinBoardChannelIdPinnedMessageDelete( channelId = channelId ).checkResponseBody() } /** * 置頂貼文 */ suspend fun pinPost(channelId: String, messageId: String) = kotlin.runCatching { bulletinBoardApi.apiV1BulletinBoardChannelIdPinnedMessagePut( channelId = channelId, messageIdParam = MessageIdParam( messageId = messageId ) ).checkResponseBody() } /** * 撰寫po 文 * * @param channelId 頻道 id * @param text 內文 * @param attachment 附加檔案 */ suspend fun writePost( channelId: String, text: String, attachment: List<Pair<AttachmentType, AttachmentInfoItem>> ): Result<BulletinboardMessage> { val medias = attachment.toUploadMedia(context) //投票 id val votingIds = attachment.filter { it.first == AttachmentType.Choice && it.second.other is VoteModel }.map { (it.second.other as VoteModel).id } val bulletingBoardMessageParam = BulletingBoardMessageParam( text = text, medias = medias, votingIds = votingIds ) return kotlin.runCatching { bulletinBoardApi.apiV1BulletinBoardChannelIdMessagePost( channelId = channelId, bulletingBoardMessageParam = bulletingBoardMessageParam ).checkResponseBody() } } /** * 取得貼文 * * @param channelId 頻道id * @param order 排序 (預設新到舊) * @param fromSerialNumber 分頁序號 */ suspend fun getPost( channelId: String, order: OrderType = OrderType.latest, fromSerialNumber: Long? = null ): Result<BulletinboardMessagePaging> { return kotlin.runCatching { if (Constant.isOpenMock) { BulletinboardMessagePaging( items = listOf(MockData.mockBulletinboardMessage) ) } else { bulletinBoardApi.apiV1BulletinBoardChannelIdMessageGet( channelId = channelId, order = order, fromSerialNumber = fromSerialNumber ).checkResponseBody() } } } /** * 取得 該貼文 留言 * * @param channelId 頻道id * @param messageId 原始貼文id * @param order 排序 (預設舊到新) * @param fromSerialNumber 分頁序號 */ suspend fun getComments( channelId: String, messageId: String, order: OrderType = OrderType.oldest, fromSerialNumber: Long? = null ): Result<BulletinboardMessagePaging> { return kotlin.runCatching { bulletinBoardApi.apiV1BulletinBoardChannelIdMessageMessageIdCommentsGet( channelId = channelId, messageId = messageId, order = order, fromSerialNumber = fromSerialNumber ).checkResponseBody() } } /** * 取得 該留言 的回覆 * * @param channelId 頻道id * @param commentId 原始留言id * @param order 排序 (預設舊到新) * @param fromSerialNumber 分頁序號 */ suspend fun getCommentReply( channelId: String, commentId: String, order: OrderType = OrderType.oldest, fromSerialNumber: Long? = null ): Result<BulletinboardMessagePaging> { return kotlin.runCatching { bulletinBoardApi.apiV1BulletinBoardChannelIdMessageMessageIdCommentsGet( channelId = channelId, messageId = commentId, order = order, fromSerialNumber = fromSerialNumber ).checkResponseBody() } } /** * 針對貼文 留言 * * @param channelId 頻道id * @param messageId 原始貼文id * @param text message * @param attachment attach */ suspend fun writeComment( channelId: String, messageId: String, text: String, attachment: List<Pair<AttachmentType, AttachmentInfoItem>> ): Result<BulletinboardMessage> { val medias = attachment.toUploadMedia(context) val bulletingBoardMessageParam = BulletingBoardMessageParam( text = text, medias = medias ) return kotlin.runCatching { bulletinBoardApi.apiV1BulletinBoardChannelIdMessageMessageIdCommentPost( channelId = channelId, messageId = messageId, bulletingBoardMessageParam = bulletingBoardMessageParam ).checkResponseBody() } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/PostUseCase.kt
1531296660
package com.cmoney.kolfanci.model.usecase import com.cmoney.fanciapi.fanci.api.ChatRoomApi import com.cmoney.fanciapi.fanci.model.ChatMessagePaging import com.cmoney.fanciapi.fanci.model.OrderType import com.cmoney.kolfanci.extension.checkResponseBody import com.socks.library.KLog import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.flowOn class ChatRoomPollUseCase( private val chatRoomApi: ChatRoomApi, private val dispatcher: CoroutineDispatcher = Dispatchers.IO ) : Poller { private val TAG = ChatRoomPollUseCase::class.java.simpleName private var isClose = false private var isScopeClose = false private var index: Long? = null private val messageTakeSize = 20 /** * Latest: 往回取 * Oldest: 往後取 */ override fun poll(delay: Long, channelId: String, fromIndex: Long?): Flow<ChatMessagePaging> { isClose = false fromIndex?.apply { index = this } return channelFlow { while (!isClose) { kotlin.runCatching { chatRoomApi.apiV1ChatRoomChatRoomChannelIdMessageGet( chatRoomChannelId = channelId, fromSerialNumber = index, order = OrderType.oldest, take = messageTakeSize ).checkResponseBody() }.fold({ //當沒有結果, server 會回傳 -1, 確定這次分頁數量拿滿了, 才拿下一頁, 或是 server 跟前端說有下一頁 if (it.nextWeight != -1L && it.items?.size?.equals(messageTakeSize) == true || it.haveNextPage == true) { index = it.nextWeight } send(it) }, { KLog.e(TAG, it) }) delay(delay) } }.flowOn(dispatcher) } override fun pollScope( delay: Long, channelId: String, fromSerialNumber: Long?, fetchCount: Int ): Flow<ChatMessagePaging> { isScopeClose = false return channelFlow { while (!isScopeClose) { kotlin.runCatching { chatRoomApi.apiV1ChatRoomChatRoomChannelIdMessageGet( chatRoomChannelId = channelId, fromSerialNumber = fromSerialNumber, order = OrderType.latest, take = fetchCount ).checkResponseBody() }.onSuccess { send(it) }.onFailure { KLog.e(TAG, it) } delay(delay) } }.flowOn(dispatcher) } override fun close() { isClose = true closeScope() } fun closeScope() { isScopeClose = true } } interface Poller { fun poll(delay: Long, channelId: String, fromIndex: Long? = null): Flow<ChatMessagePaging> /** * 範圍內刷新 * * @param delay 延遲多久 millisecond * @param channelId 頻道id * @param fromSerialNumber find index * @param fetchCount 抓取筆數 */ fun pollScope( delay: Long, channelId: String, fromSerialNumber: Long? = null, fetchCount: Int ): Flow<ChatMessagePaging> fun close() }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/ChatRoomPollUseCase.kt
3153388640
package com.cmoney.kolfanci.model.usecase import android.app.Application import com.cmoney.fanciapi.fanci.api.BulletinBoardApi import com.cmoney.fanciapi.fanci.api.ChatRoomApi import com.cmoney.fanciapi.fanci.api.PushNotificationApi import com.cmoney.fanciapi.fanci.model.PushNotificationSettingType import com.cmoney.kolfanci.extension.checkResponseBody import com.cmoney.kolfanci.model.persistence.SettingsDataStore import com.cmoney.kolfanci.repository.Network import com.cmoney.kolfanci.repository.request.NotificationClick import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class NotificationUseCase( private val context: Application, private val network: Network, private val settingsDataStore: SettingsDataStore, private val pushNotificationApi: PushNotificationApi, private val chatRoomApi: ChatRoomApi, private val bulletinBoardApi: BulletinBoardApi, private val dispatcher: CoroutineDispatcher = Dispatchers.IO ) { /** * 取得 推播中心 資料 */ suspend fun getNotificationCenter() = network.getNotificationHistory() /** * 取得 下一頁 推播歷史訊息 */ suspend fun getNextPageNotificationCenter(nextPageUrl: String) = network.getNextPageNotificationHistory(nextPageUrl = nextPageUrl) /** * 點擊 通知中心 item */ suspend fun setNotificationClick(notificationId: String) = network.setNotificationHistoryClick( NotificationClick( notificationIds = listOf(notificationId) ) ) /** * 是否通知過使用者允許通知權限 * * @return Result.success true 表示已通知, false 未通知, Result.failure 有例外發生 */ suspend fun hasNotifyAllowNotificationPermission(): Result<Boolean> = withContext(dispatcher) { kotlin.runCatching { settingsDataStore.hasNotifyAllowNotificationPermission() } } /** * 已通知過使用者允許通知權限 */ suspend fun alreadyNotifyAllowNotificationPermission() = withContext(dispatcher) { kotlin.runCatching { settingsDataStore.alreadyNotifyAllowNotificationPermission() } } /** * 取得該社團的推播設定 */ suspend fun getNotificationSetting(groupId: String) = withContext(dispatcher) { kotlin.runCatching { pushNotificationApi.apiV1PushNotificationUserGroupIdSettingTypeGet(groupId = groupId) .checkResponseBody() } } /** * 設定指定社團的推播設定值 */ suspend fun setNotificationSetting( groupId: String, pushNotificationSettingType: PushNotificationSettingType ) = withContext(dispatcher) { kotlin.runCatching { pushNotificationApi.apiV1PushNotificationUserGroupIdSettingTypeSettingTypePut( groupId = groupId, settingType = pushNotificationSettingType ).checkResponseBody() } } /** * 取得所有推播設定檔 */ suspend fun getAllNotificationSetting() = withContext(dispatcher) { kotlin.runCatching { pushNotificationApi.apiV1PushNotificationSettingTypeAllGet().checkResponseBody() } } /** * 清除 聊天室 未讀數量 */ suspend fun clearChatUnReadCount(channelId: String) = withContext(dispatcher) { kotlin.runCatching { chatRoomApi.apiV1ChatRoomChatRoomChannelIdResetUnreadCountPut( chatRoomChannelId = channelId ).checkResponseBody() } } /** * 清除 貼文 未讀數量 */ suspend fun clearPostUnReadCount(channelId: String) = withContext(dispatcher) { kotlin.runCatching { bulletinBoardApi.apiV1BulletinBoardChannelIdResetUnreadCountPut( channelId = channelId ).checkResponseBody() } } /** * 取得 通知中心 未讀數量 */ suspend fun getNotificationUnReadCount() = network.getNotificationUnreadCount() /** * 通知中心 已讀 */ suspend fun setNotificationSeen() = network.setNotificationSeen() }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/NotificationUseCase.kt
2795974183
package com.cmoney.kolfanci.model.usecase import com.cmoney.fanciapi.fanci.api.BuffInformationApi import com.cmoney.kolfanci.extension.checkResponseBody import com.cmoney.fanciapi.fanci.api.PermissionApi import com.cmoney.kolfanci.model.Constant class PermissionUseCase( private val permissionApi: PermissionApi, private val buffInformationApi: BuffInformationApi ) { /** * 更新 在此channel的permission 以及 身上的 buff */ suspend fun updateChannelPermissionAndBuff(channelId: String) = kotlin.runCatching { Constant.MyChannelPermission = permissionApi.apiV1PermissionChannelChannelIdGet(channelId = channelId) .checkResponseBody() Constant.MyChannelBuff = buffInformationApi.apiV1BuffInformationChannelChannelIdMeGet(channelId = channelId) .checkResponseBody() } suspend fun getPermissionByChannel(channelId: String) = kotlin.runCatching { permissionApi.apiV1PermissionChannelChannelIdGet(channelId = channelId).checkResponseBody() } /** * 取得在此群組下的權限 */ suspend fun getPermissionByGroup(groupId: String) = kotlin.runCatching { permissionApi.apiV1PermissionGroupGroupIdGet( groupId = groupId ).checkResponseBody() } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/PermissionUseCase.kt
886282376
package com.cmoney.kolfanci.model.usecase import com.cmoney.fanciapi.fanci.api.BuffInformationApi import com.cmoney.fanciapi.fanci.api.CategoryApi import com.cmoney.fanciapi.fanci.api.ChannelApi import com.cmoney.fanciapi.fanci.api.ChannelTabApi import com.cmoney.fanciapi.fanci.api.GroupApi import com.cmoney.fanciapi.fanci.model.* import com.cmoney.kolfanci.extension.checkResponseBody class ChannelUseCase( private val categoryApi: CategoryApi, private val groupApi: GroupApi, private val channelApi: ChannelApi, private val buffInformationApi: BuffInformationApi, private val channelTabApi: ChannelTabApi ) { /** * 取得User在此頻道 的狀態 */ suspend fun getChannelBuffer(channelId: String) = kotlin.runCatching { buffInformationApi.apiV1BuffInformationChannelChannelIdMeGet(channelId = channelId) .checkResponseBody() } /** * 取得頻道 tab order */ suspend fun getChannelTabOrder(channelId: String) = kotlin.runCatching { channelTabApi.apiV1ChannelTabChannelIdTabsGet( channelId = channelId ).checkResponseBody() } /** * 設定 tab 順序 * * @param channelId 頻道id * @param tabs tab 順序 */ suspend fun setChannelTabOrder(channelId: String, tabs: List<ChannelTabType>) = kotlin.runCatching { val channelTabsSortParam = ChannelTabsSortParam( tabs = tabs ) channelTabApi.apiV1ChannelTabChannelIdTabsSortPut( channelId = channelId, channelTabsSortParam = channelTabsSortParam ) } /** * 取得 私密頻道 不重複用戶總數 */ suspend fun getPrivateChannelUserCount(roleIds: List<String>, userIds: List<String>) = kotlin.runCatching { channelApi.apiV1ChannelWhiteListUsersCountPost( getWhiteListCountParam = GetWhiteListCountParam( roleIds = roleIds, userIds = userIds ) ).checkResponseBody() } /** * 取得 私密頻道 白名單 */ suspend fun getPrivateChannelWhiteList(channelId: String) = kotlin.runCatching { channelApi.apiV1ChannelChannelIdWhiteListGet( channelId ).checkResponseBody() } /** * 設定 私密頻道 白名單 (用戶/角色) */ suspend fun putPrivateChannelWhiteList( channelId: String, authType: ChannelAuthType, accessorList: List<AccessorParam> ) = kotlin.runCatching { channelApi.apiV1ChannelChannelIdWhiteListAuthTypePut( channelId = channelId, authType = authType, putWhiteListRequest = PutWhiteListRequest( parameter = accessorList ) ).checkResponseBody() } /** * 抓取 私密頻道 權限類型清單, 不包含 無權限 */ suspend fun getChanelAccessTypeWithoutNoPermission() = kotlin.runCatching { channelApi.apiV2ChannelAccessTypeGet(isWithNoPermission = false).checkResponseBody() } /** * 頻道 移除多個角色 * @param channelId 頻道id * @param roleIds 角色id清單 */ suspend fun deleteRoleFromChannel(channelId: String, roleIds: List<String>) = kotlin.runCatching { channelApi.apiV1ChannelChannelIdRoleDelete( channelId = channelId, roleIdsParam = RoleIdsParam( roleIds = roleIds ) ).checkResponseBody() } /** * 頻道 新增多個角色 * @param channelId 頻道id * @param roleIds 角色id清單 */ suspend fun addRoleToChannel(channelId: String, roleIds: List<String>) = kotlin.runCatching { channelApi.apiV1ChannelChannelIdRolePut( channelId = channelId, roleIdsParam = RoleIdsParam( roleIds = roleIds ) ).checkResponseBody() } /** * 刪除 分類 */ suspend fun deleteCategory(categoryId: String) = kotlin.runCatching { categoryApi.apiV1CategoryCategoryIdDelete(categoryId = categoryId).checkResponseBody() } /** * 編輯 分類名稱 */ suspend fun editCategoryName(categoryId: String, name: String) = kotlin.runCatching { categoryApi.apiV1CategoryCategoryIdNamePut( categoryId = categoryId, categoryParam = CategoryParam( name ) ).checkResponseBody() } /** * 刪除 頻道 */ suspend fun deleteChannel(channelId: String) = kotlin.runCatching { channelApi.apiV1ChannelChannelIdDelete(channelId = channelId).checkResponseBody() } /** * 編輯 頻道名稱 */ suspend fun editChannelName(channelId: String, name: String, privacy: ChannelPrivacy) = kotlin.runCatching { channelApi.apiV1ChannelChannelIdPut( channelId = channelId, editChannelParam = EditChannelParam( name, privacy ) ).checkResponseBody() } /** * 取得 頻道角色清單 */ suspend fun getChannelRole(channelId: String) = kotlin.runCatching { channelApi.apiV1ChannelChannelIdRoleGet(channelId).checkResponseBody() } /** * 新增 分類 * @param groupId 群組id, 要在此群組下建立 * @param name 分類名稱 */ suspend fun addCategory(groupId: String, name: String) = kotlin.runCatching { groupApi.apiV1GroupGroupIdCategoryPost( groupId = groupId, categoryParam = CategoryParam( name = name ) ).checkResponseBody() } /** * 新增 頻道 * @param categoryId 分類id, 在此分類下建立 * @param name 頻道名稱 * @param privacy 公開/私密 * @param tabs tab 排序 */ suspend fun addChannel( categoryId: String, name: String, privacy: ChannelPrivacy, tabs: List<ChannelTabType> ) = kotlin.runCatching { categoryApi.apiV1CategoryCategoryIdChannelPost( categoryId = categoryId, channelParam = ChannelParam( tabs = tabs, name = name, privacy = privacy ) ).checkResponseBody() } /** * 查看 該 channel tab 狀態 */ suspend fun fetchChannelTabStatus(channelId: String) = kotlin.runCatching { channelTabApi.apiV1ChannelTabChannelIdTabGet(channelId = channelId).checkResponseBody() } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/usecase/ChannelUseCase.kt
1273749148
package com.cmoney.kolfanci.model.analytics import android.util.Log import com.cmoney.analytics.user.model.event.UserEvent import com.cmoney.application_user_behavior.AnalyticsAgent import com.cmoney.application_user_behavior.model.event.logClicked import com.cmoney.application_user_behavior.model.event.logPageViewed import com.cmoney.fancylog.model.data.Clicked import com.cmoney.fancylog.model.data.From import com.cmoney.fancylog.model.data.Page import com.cmoney.kolfanci.BuildConfig import com.cmoney.kolfanci.model.Constant import com.cmoney.xlogin.XLoginHelper import com.mixpanel.android.mpmetrics.MixpanelAPI import org.json.JSONException import org.koin.core.component.KoinComponent import org.koin.core.component.inject class AppUserLogger : KoinComponent { private val mixpanel: MixpanelAPI by inject() companion object { private val _instance by lazy { AppUserLogger() } fun getInstance(): AppUserLogger { return _instance } } fun log(event: UserEvent) { logMixpanel(event) debugLog(event.name, event.getParameters()) } fun log(page: Page, from: From? = null) { val descriptions = from?.asParameters() val event = PageUserEvent(page = page.eventName, parameters = descriptions) // logMixpanel(event) logCM(page) debugLog(event.name, event.getParameters()) } fun log(clicked: Clicked, from: From? = null) { val descriptions = from?.asParameters() val event = ClickedUserEvent(clicked = clicked.eventName, parameters = descriptions) logCM(clicked = clicked, descriptions = descriptions) debugLog(event.name, event.getParameters()) } fun log(eventName: String, parameters: Map<String, Any>? = null) { val event = OtherEvent( eventName, parameters ) logCM(eventName = eventName, descriptions = parameters) debugLog(event.name, event.getParameters()) } class PageUserEvent(val page: String, parameters: Map<String, Any>? = null) : UserEvent() { override val name: String get() = page init { parameters?.let { val ps = it.toList().map { (key, value) -> key to value.toString() }.toTypedArray() setParameters(*ps) } } } class ClickedUserEvent(private val clicked: String, parameters: Map<String, Any>? = null) : UserEvent() { override val name: String get() = clicked init { parameters?.let { val ps = it.toList().map { (key, value) -> key to value.toString() }.toTypedArray() setParameters(*ps) } } } class OtherEvent(private val eventName: String, parameters: Map<String, Any>? = null) : UserEvent() { override val name: String get() = eventName init { parameters?.let { val ps = it.toList().map { (key, value) -> key to value.toString() }.toTypedArray() setParameters(*ps) } } } /** * Mixpanel 紀錄使用者 info */ fun recordUserInfo() { Constant.MyInfo?.apply { mixpanel.identify(this.id) mixpanel.people.identify(this.id) mixpanel.people.set("\$name", this.name) } mixpanel.people.set("\$email", XLoginHelper.mail) mixpanel.people.set("\$memberPk", XLoginHelper.memberPk) } /** * log to CMoney */ private fun logCM(page: Page) { AnalyticsAgent.getInstance().logPageViewed(page.eventName) } /** * Log to CMoney */ private fun logCM(clicked: Clicked, descriptions: Map<String, Any>? = null) { AnalyticsAgent.getInstance().logClicked( name = clicked.eventName, descriptions = descriptions ) } /** * Log to CMoney */ private fun logCM(eventName: String, descriptions: Map<String, Any>? = null) { AnalyticsAgent.getInstance().logEvent( name = eventName, descriptions = descriptions ) } /** * 記錄到 mixPanel */ private fun logMixpanel(event: UserEvent) { val map = HashMap<String, Any>() try { val params = event.getParameters() params.forEach { map[it.key] = it.value } } catch (e: JSONException) { } // log到Mixpanel if (map.isEmpty()) { mixpanel.track(event.name) } else { mixpanel.trackMap(event.name, map) } } /** * 用來進行Debug時的事件紀錄輸出 */ private fun debugLog( eventName: String, eventParams: Set<UserEvent.Parameter> ) { if (!BuildConfig.DEBUG) { return } var message = eventName if (eventParams.isNotEmpty()) { val stringBuild = StringBuilder() eventParams.forEach { pair -> stringBuild.append(pair.key + ":") stringBuild.append(pair.value) } message = "$eventName, $stringBuild" } Log.d("LogEventListener", message) } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/analytics/AppUserLogger.kt
1352055933
package com.cmoney.kolfanci.model.analytics.data @Deprecated("改為使用 fancilog module") /** * 頁面 * * @property eventName 事件名稱 */ sealed class Page(val eventName: String) { /** * 首頁_觀看 */ object Home : Page(eventName = "Home") /** * 會員頁_觀看 */ object MemberPage : Page(eventName = "MemberPage") { /** * 會員頁.未登入頁_觀看 */ object NotLoggedInPage : Page(eventName = "MemberPage.NotLoggedInPage") /** * 會員頁.信箱登入_觀看 */ object EmailLogin : Page(eventName = "MemberPage.EmailLogin") /** * 會員頁.社群帳號登入_觀看 */ object SocialAccountLogin : Page(eventName = "MemberPage.SocialAccountLogin") /** * 會員頁.頭像與暱稱_觀看 */ object AvatarAndNickname : Page(eventName = "MemberPage.AvatarAndNickname") { /** * 頭像與暱稱.頭像_觀看 */ object Avatar : Page(eventName = "AvatarAndNickname.Avatar") /** * 頭像與暱稱.暱稱_觀看 */ object Nickname : Page(eventName = "AvatarAndNickname.Nickname") } /** * 會員頁.帳號管理_觀看 */ object AccountManagement : Page(eventName = "MemberPage.AccountManagement") { /** * 帳號管理.登出帳號_觀看 */ object Logout : Page(eventName = "AccountManagement.Logout") /** * 帳號管理.刪除帳號_觀看 */ object DeleteAccount : Page(eventName = "AccountManagement.DeleteAccount") } /** * 會員頁.服務條款_觀看 */ object TermsOfService : Page(eventName = "MemberPage.TermsOfService") /** * 會員頁.隱私權政策_觀看 */ object PrivacyPolicy : Page(eventName = "MemberPage.PrivacyPolicy") /** * 會員頁.著作權政策_觀看 */ object CopyrightPolicy : Page(eventName = "MemberPage.CopyrightPolicy") /** * 會員頁.意見回饋_觀看 */ object Feedback : Page(eventName = "MemberPage.Feedback") } /** * 探索社團 */ object ExploreGroup { /** * 探索社團.熱門社團_觀看 */ object PopularGroups : Page(eventName = "ExploreGroup.PopularGroups") /** * 探索社團.最新社團_觀看 */ object NewestGroups : Page(eventName = "ExploreGroup.NewestGroups") } /** * 社團_觀看 */ object Group : Page(eventName = "Group") { /** * 社團.設定 */ object Settings { /** * 社團.設定.社團設定 */ object GroupSettings { /** * 社團.設定.社團設定.社團名稱_觀看 */ object GroupName : Page(eventName = "Group.Settings.GroupSettings.GroupName") /** * 社團.設定.社團設定.社團簡介_觀看 */ object GroupIntroduction : Page(eventName = "Group.Settings.GroupSettings.GroupIntroduction") /** * 社團.設定.社團設定.社團圖示_觀看 */ object GroupIcon : Page(eventName = "Group.Settings.GroupSettings.GroupIcon") /** * 社團.設定.社團設定.首頁背景_觀看 */ object HomeBackground : Page(eventName = "Group.Settings.GroupSettings.HomeBackground") /** * 社團.設定.社團設定.主題色彩_觀看 */ object ThemeColor : Page(eventName = "Group.Settings.GroupSettings.ThemeColor") } /** * 社團.設定.社團公開度 */ object GroupOpenness { /** * 社團.設定.社團公開度.完全公開_觀看 */ object FullyOpen : Page(eventName = "Group.Settings.GroupOpenness.FullyOpen") /** * 社團.設定.社團公開度.不公開 */ object NonPublic { /** * 社團.設定.社團公開度.不公開.審核題目 */ object ReviewQuestion { /** * 社團.設定.社團公開度.不公開.審核題目.新增審核題目_觀看 */ object AddReviewQuestion : Page(eventName = "Group.Settings.GroupOpenness.NonPublic.ReviewQuestion.AddReviewQuestion") /** * 社團.設定.社團公開度.不公開.審核題目.編輯_觀看 */ object Edit : Page(eventName = "Group.Settings.GroupOpenness.NonPublic.ReviewQuestion.Edit") /** * 社團.設定.社團公開度.不公開.審核題目.移除_觀看 */ object Remove : Page(eventName = "Group.Settings.GroupOpenness.NonPublic.ReviewQuestion.Remove") } } } /** * 社團.設定.頻道管理_觀看 */ object ChannelManagement : Page(eventName = "Group.Settings.ChannelManagement") { /** * 社團.設定.頻道管理.新增分類_觀看 */ object AddCategory : Page(eventName = "Group.Settings.ChannelManagement.AddCategory") /** * 社團.設定.頻道管理.編輯分類_觀看 */ object EditCategory : Page(eventName = "Group.Settings.ChannelManagement.EditCategory") /** * 社團.設定.頻道管理.刪除分類_觀看 */ object DeleteCategory : Page(eventName = "Group.Settings.ChannelManagement.DeleteCategory") /** * 社團.設定.頻道管理.新增頻道_觀看 */ object AddChannel : Page(eventName = "Group.Settings.ChannelManagement.AddChannel") /** * 社團.設定.頻道管理.編輯頻道_觀看 */ object EditChannel : Page(eventName = "Group.Settings.ChannelManagement.EditChannel") /** * 社團.設定.頻道管理.樣式_觀看 */ object Style : Page(eventName = "Group.Settings.ChannelManagement.Style") { /** * 社團.設定.頻道管理.樣式.頻道名稱_觀看 */ object ChannelName : Page(eventName = "Group.Settings.ChannelManagement.Style.ChannelName") } /** * 社團.設定.頻道管理.權限 */ object Permissions { /** * 社團.設定.頻道管理.權限.完全公開_觀看 */ object Public : Page(eventName = "Group.Settings.ChannelManagement.Permissions.Public") /** * 社團.設定.頻道管理.權限.不公開 */ object Private { /** * 社團.設定.頻道管理.權限.不公開.成員_觀看 */ object Members : Page(eventName = "Group.Settings.ChannelManagement.Permissions.Private.Members") /** * 社團.設定.頻道管理.權限.不公開.新增成員_觀看 */ object AddMember : Page(eventName = "Group.Settings.ChannelManagement.Permissions.Private.AddMember") /** * 社團.設定.頻道管理.權限.不公開.角色_觀看 */ object Roles : Page(eventName = "Group.Settings.ChannelManagement.Permissions.Private.Roles") /** * 社團.設定.頻道管理.權限.不公開.新增角色_觀看 */ object AddRole : Page(eventName = "Group.Settings.ChannelManagement.Permissions.Private.AddRole") /** * 社團.設定.頻道管理.權限.不公開.VIP_觀看 */ object VIP : Page(eventName = "Group.Settings.ChannelManagement.Permissions.Private.VIP") /** * 社團.設定.頻道管理.權限.不公開.新增方案_觀看 */ object AddPlan : Page(eventName = "Group.Settings.ChannelManagement.Permissions.Private.AddPlan") } } /** * 社團.設定.頻道管理.管理員_觀看 */ object Admin : Page(eventName = "Group.Settings.ChannelManagement.Admin") { /** * 社團.設定.頻道管理.管理員.新增角色_觀看 */ object AddRole : Page(eventName = "Group.Settings.ChannelManagement.Admin.AddRole") } /** * 社團.設定.頻道管理.刪除頻道_觀看 */ object DeleteChannel : Page(eventName = "Group.Settings.ChannelManagement.DeleteChannel") } /** * 社團.設定.角色管理 */ object RoleManagement { /** * 社團.設定.角色管理.新增角色 */ object AddRole { /** * 社團.設定.角色管理.新增角色.樣式_觀看 */ object Style : Page(eventName = "Group.Settings.RoleManagement.AddRole.Style") /** * 社團.設定.角色管理.新增角色.權限_觀看 */ object Permissions : Page(eventName = "Group.Settings.RoleManagement.AddRole.Permissions") /** * 社團.設定.角色管理.新增角色.成員_觀看 */ object Members : Page(eventName = "Group.Settings.RoleManagement.AddRole.Members") } /** * 社團.設定.角色管理.編輯角色 */ object EditRole { /** * 社團.設定.角色管理.編輯角色.樣式_觀看 */ object Style : Page(eventName = "Group.Settings.RoleManagement.EditRole.Style") /** * 社團.設定.角色管理.編輯角色.權限_觀看 */ object Permissions : Page(eventName = "Group.Settings.RoleManagement.EditRole.Permissions") /** * 社團.設定.角色管理.編輯角色.成員_觀看 */ object Members : Page(eventName = "Group.Settings.RoleManagement.EditRole.Members") /** * 社團.設定.角色管理.編輯角色.刪除_觀看 */ object Delete : Page(eventName = "Group.Settings.RoleManagement.EditRole.Delete") } } /** * 社團.設定.所有成員_觀看 */ object AllMembers : Page(eventName = "Group.Settings.AllMembers") { /** * 社團.設定.所有成員.管理_觀看 */ object Manage : Page(eventName = "Group.Settings.AllMembers.Manage") } /** * 社團.設定.加入申請_觀看 */ object JoinApplication : Page(eventName = "Group.Settings.JoinApplication") /** * 社團.設定.檢舉審核_觀看 */ object ReportReview : Page(eventName = "Group.Settings.ReportReview") { /** * 社團.設定.檢舉審核.禁言_觀看 */ object Mute : Page(eventName = "Group.Settings.ReportReview.Mute") /** * 社團.設定.檢舉審核.踢除_觀看 */ object KickOut : Page(eventName = "Group.Settings.ReportReview.KickOut") } /** * 社團.設定.VIP */ object Vip { /** * 社團.設定.VIP.方案管理_觀看 */ object PlanMNG : Page(eventName = "Group.SET.VIP.PlanMNG") /** * 社團.設定.VIP.資訊_觀看 */ object INF : Page(eventName = "Group.SET.VIP.INF") /** * 社團.設定.VIP.權限_觀看 */ object Permission : Page(eventName = "Group.SET.VIP.Permission") /** * 社團.設定.VIP.成員_觀看 */ object Members : Page(eventName = "Group.SET.VIP.Members") } } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/model/analytics/data/Page.kt
3224916186
package com.cmoney.kolfanci.service import android.Manifest import android.app.PendingIntent import android.content.Intent import android.content.pm.PackageManager import androidx.core.app.ActivityCompat import androidx.core.app.NotificationManagerCompat import com.cmoney.kolfanci.extension.isActivityRunning import com.cmoney.kolfanci.model.notification.CustomNotification import com.cmoney.kolfanci.model.notification.NotificationHelper import com.cmoney.kolfanci.model.notification.Payload import com.cmoney.kolfanci.ui.SplashActivity import com.cmoney.kolfanci.ui.main.MainActivity import com.cmoney.notify_library.fcm.CMoneyBaseMessagingService import com.cmoney.notify_library.variable.CommonNotification import com.google.firebase.messaging.RemoteMessage import com.socks.library.KLog import org.koin.android.ext.android.inject class FcmMessagingService : CMoneyBaseMessagingService() { private val TAG = FcmMessagingService::class.java.simpleName private val notificationHelper by inject<NotificationHelper>() override fun dealWithCommonNotification( notification: CommonNotification, message: RemoteMessage ) { KLog.i(TAG, "dealWithCommonNotification:${message.data}") val customNotification = CustomNotification(message) handleNow(customNotification) } private fun handleNow(data: CustomNotification) { val payload = notificationHelper.getPayloadFromForeground(data) val title = payload.title.orEmpty() val message = payload.message.orEmpty() val sn = System.currentTimeMillis().toString().hashCode() createNotification(title, message, sn, payload) } private fun createNotification( title: String, message: String, sn: Int, payload: Payload ) { val intent = if (this.isActivityRunning(MainActivity::class.java.name)) { MainActivity.createIntent(this, payload) } else { SplashActivity.createIntent(this, payload) } intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP val pendingIntent = PendingIntent.getActivity( this, sn, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) val notification = notificationHelper.getStyle0(title, message) .setContentIntent(pendingIntent) .build() with(NotificationManagerCompat.from(this)) { if (ActivityCompat.checkSelfPermission( this@FcmMessagingService, Manifest.permission.POST_NOTIFICATIONS ) != PackageManager.PERMISSION_GRANTED ) { return } notify(sn, notification) } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/service/FcmMessagingService.kt
2064689578
package com.cmoney.kolfanci.service.media import android.content.Context import android.media.MediaPlayer import android.media.MediaRecorder import android.net.Uri import android.os.Build import com.cmoney.kolfanci.model.Constant import com.socks.library.KLog import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import java.io.File import java.io.IOException import kotlin.coroutines.CoroutineContext private const val TAG = "MyMediaRecorderImpl" /** * 錄音與播放介面的實現 */ class RecorderAndPlayerImpl(private val context: Context) : RecorderAndPlayer { private var recorder: MediaRecorder? = null private var player: MediaPlayer? = null private var filePath: String? = null //目前錄製的秒數 private var _currentRecordSeconds = MutableStateFlow(0L) private var _playingCurrentMilliseconds = MutableStateFlow(0L) private val _progress = MutableStateFlow(0f) private var recordJob: Job? = null private var playingJob: Job? = null //最大錄音秒數 private val maxRecordingDuration = 45000L //錄音時長 private var recordingDuration = 0L private val coroutineContext: CoroutineContext get() = Dispatchers.Default + Job() @Suppress("DEPRECATION") override fun startRecording() { _playingCurrentMilliseconds.value = 0 recorder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { MediaRecorder(context) } else { MediaRecorder() } recorder?.apply { filePath = "${Constant.absoluteCachePath}/錄音_${System.currentTimeMillis()}.aac" setAudioSource(MediaRecorder.AudioSource.MIC) setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS) setOutputFile(filePath) setAudioEncoder(MediaRecorder.AudioEncoder.AAC) try { prepare() } catch (e: IOException) { KLog.e(TAG, "prepare() failed") } start() } startRecordingTimer() } override fun stopRecording() { recorder?.apply { stop() release() } recorder = null stopRecordingTimer() } override fun startPlaying(uri: Uri) { _playingCurrentMilliseconds.value = 0 player = MediaPlayer().apply { try { setDataSource(uri.toString()) prepare() start() } catch (e: IOException) { KLog.e(TAG, "prepare() failed") } } } override fun startPlaying() { _playingCurrentMilliseconds.value = 0 player = MediaPlayer().apply { try { setDataSource(filePath) prepare() start() } catch (e: IOException) { KLog.e(TAG, "prepare() failed") } } } override fun pausePlaying() { if (player?.isPlaying == true) { player!!.pause() } } override fun resumePlaying() { if (!player?.isPlaying!!) { player?.start() } } override fun stopPlaying() { player?.stop() _playingCurrentMilliseconds.value = 0 } override fun dismiss() { recordJob?.cancel() _currentRecordSeconds.value = 0 recordingDuration = 0 recorder?.release() recorder = null player?.release() player = null } override fun getPlayingDuration(): Long { return player?.duration?.toLong() ?: 0 } override fun getPlayingCurrentMilliseconds(): StateFlow<Long> { playingJob?.cancel() playingJob = CoroutineScope(coroutineContext).launch { player?.let { mediaPlayer -> try { while (mediaPlayer.isPlaying) { val currentPosition = mediaPlayer.currentPosition.toLong() _playingCurrentMilliseconds.emit(currentPosition) delay(200) } if (mediaPlayer.currentPosition == mediaPlayer.duration) { _playingCurrentMilliseconds.emit(mediaPlayer.duration.toLong()) } } catch (e: IllegalStateException) { KLog.e(TAG, "MediaPlayer is in an invalid state", e) } } } return _playingCurrentMilliseconds.asStateFlow() } override fun getRecordingCurrentMilliseconds(): StateFlow<Long> = _currentRecordSeconds private fun startRecordingTimer() { recordJob = CoroutineScope(coroutineContext).launch { while (_currentRecordSeconds.value < maxRecordingDuration) { delay(200L) _currentRecordSeconds.value += 200 _progress.value = _currentRecordSeconds.value / maxRecordingDuration.toFloat() } if (_currentRecordSeconds.value >= maxRecordingDuration) { stopRecording() } } } private fun stopRecordingTimer() { recordingDuration = _currentRecordSeconds.value recordJob?.cancel() } override fun getRecordingDuration() = recordingDuration override fun getFileUri(): Uri? { KLog.i(TAG, "fileName: $filePath, Uri: ${Uri.fromFile(filePath?.let { File(it) })}") return Uri.fromFile(filePath?.let { File(it) }) } override fun deleteFile() { filePath?.let { File(it).delete() } } override fun deleteFile(uri: Uri) { filePath?.let { File(uri.toString()).delete() } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/service/media/RecorderAndPlayerImpl.kt
2578801557
package com.cmoney.kolfanci.service.media import android.app.Notification import android.app.PendingIntent import android.content.Intent import android.net.Uri import android.os.Bundle import android.os.ResultReceiver import android.support.v4.media.MediaBrowserCompat import android.support.v4.media.MediaDescriptionCompat import android.support.v4.media.MediaMetadataCompat import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat import android.util.Log import androidx.core.content.ContextCompat import androidx.core.net.toUri import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.media.MediaBrowserServiceCompat import com.cmoney.kolfanci.extension.getFileName import com.cmoney.kolfanci.extension.isURL import com.cmoney.xlogin.XLoginHelper import com.google.android.exoplayer2.BuildConfig import com.google.android.exoplayer2.C import com.google.android.exoplayer2.ExoPlayer import com.google.android.exoplayer2.MediaItem import com.google.android.exoplayer2.PlaybackException import com.google.android.exoplayer2.Player import com.google.android.exoplayer2.audio.AudioAttributes import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector.ALL_PLAYBACK_ACTIONS import com.google.android.exoplayer2.ext.mediasession.TimelineQueueNavigator import com.google.android.exoplayer2.source.ConcatenatingMediaSource import com.google.android.exoplayer2.source.ProgressiveMediaSource import com.google.android.exoplayer2.ui.PlayerNotificationManager import com.google.android.exoplayer2.upstream.DataSource import com.google.android.exoplayer2.upstream.DefaultHttpDataSource import com.google.android.exoplayer2.upstream.HttpDataSource import com.socks.library.KLog import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch const val BROWSABLE_ROOT = "/" const val EMPTY_ROOT = "@empty@" private const val MUSIC_USER_AGENT = "music.agent" const val BUNDLE_STORIES = "stories" const val BUNDLE_START_PLAY_POSITION = "start_position" const val PLAY_ERROR_RESPONSE_CODE_KEY = "PLAY_ERROR_CODE_KEY" const val PLAY_ERROR_STORY_ID_KEY = "PLAY_ERROR_STORY_ID_KEY" class MusicMediaService : MediaBrowserServiceCompat(), CoroutineScope by MainScope() { private val TAG = MusicMediaService::class.java.simpleName private lateinit var mediaSessionConnector: MediaSessionConnector private lateinit var currentPlayer: Player private lateinit var notificationManager: MusicNotificationManager private val playerListener = PlayerEventListener() private var isForegroundService = false private var mediaSession: MediaSessionCompat? = null private var currentPlaylistItems: List<MediaMetadataCompat> = emptyList() //record playlist // private val lastListenStoryDatabase by inject<LastListenStoryDatabase>() // private val lastListenStoryDao: LastListenStoryDao by lazy { // lastListenStoryDatabase.lastListenStoryDao() // } private val exoPlayer: ExoPlayer by lazy { ExoPlayer.Builder(this).build().apply { setAudioAttributes(musicAudioAttributes, true) setHandleAudioBecomingNoisy(true) addListener(playerListener) } } private val musicAudioAttributes = AudioAttributes.Builder() .setContentType(C.AUDIO_CONTENT_TYPE_MUSIC) .setUsage(C.USAGE_MEDIA) .build() private fun getDataSourceFactor(): DefaultHttpDataSource.Factory { return DefaultHttpDataSource.Factory() .setUserAgent("exoplayer-codelab") .setTransferListener(null) .setConnectTimeoutMs(30000) .setReadTimeoutMs(30000) .setDefaultRequestProperties(HashMap<String, String>().apply { if (XLoginHelper.isLogin) { put("Authorization", "Bearer ${XLoginHelper.accessToken}") } }) } override fun onCreate() { super.onCreate() //Notification 使用 val sessionActivityPendingIntent = packageManager?.getLaunchIntentForPackage(packageName)?.let { sessionIntent -> PendingIntent.getActivity(this, 0, sessionIntent, PendingIntent.FLAG_IMMUTABLE) } mediaSession = MediaSessionCompat(this, TAG) .apply { setSessionActivity(sessionActivityPendingIntent) isActive = true setSessionToken(sessionToken) // ExoPlayer 套件 mediaSessionConnector = MediaSessionConnector(this) mediaSessionConnector.setPlaybackPreparer(MusicPlaybackPreparer()) mediaSessionConnector.setQueueNavigator(MusicQueueNavigator(this)) mediaSessionConnector.setEnabledPlaybackActions(ALL_PLAYBACK_ACTIONS) } switchToPlayer(previousPlayer = null, newPlayer = exoPlayer) notificationManager = MusicNotificationManager( this, mediaSession!!.sessionToken, PlayerNotificationListener() ) notificationManager.showNotificationForPlayer(currentPlayer) } private inner class PlayerNotificationListener : PlayerNotificationManager.NotificationListener { override fun onNotificationPosted( notificationId: Int, notification: Notification, ongoing: Boolean ) { if (ongoing && !isForegroundService) { ContextCompat.startForegroundService( applicationContext, Intent(applicationContext, [email protected]) ) startForeground(notificationId, notification) isForegroundService = true } } override fun onNotificationCancelled(notificationId: Int, dismissedByUser: Boolean) { stopForeground(true) isForegroundService = false stopSelf() } } override fun onGetRoot( clientPackageName: String, clientUid: Int, rootHints: Bundle? ): BrowserRoot? { val isKnownCaller = allowBrowsing(clientPackageName) return if (isKnownCaller) { BrowserRoot(BROWSABLE_ROOT, null) } else { if (BuildConfig.DEBUG) { BrowserRoot(EMPTY_ROOT, null) } else { null } } } private fun allowBrowsing(clientPackageName: String): Boolean { return clientPackageName == packageName } /** * 屬於瀏覽歌曲相關,可以看到會傳入 parentId, * 然後再將 result 傳出,在 uamp 專案內點擊專輯後, * 會顯示專輯內的歌曲,收到 Id 後,去 local 的 repository 尋找相關的歌曲, * 然後將結果透過 result.sendResult(items) 回傳 */ override fun onLoadChildren( parentId: String, result: Result<MutableList<MediaBrowserCompat.MediaItem>> ) { // TODO: } private fun switchToPlayer(previousPlayer: Player?, newPlayer: Player) { if (previousPlayer == newPlayer) { return } currentPlayer = newPlayer if (previousPlayer != null) { val playbackState = previousPlayer.playbackState if (currentPlaylistItems.isEmpty()) { // We are joining a playback session. Loading the session from the new player is // not supported, so we stop playback. currentPlayer.stop(/* reset= */true) } else if (playbackState != Player.STATE_IDLE && playbackState != Player.STATE_ENDED) { preparePlaylist( metadataList = currentPlaylistItems, itemToPlay = currentPlaylistItems[previousPlayer.currentWindowIndex], playWhenReady = previousPlayer.playWhenReady, playbackStartPositionMs = previousPlayer.currentPosition ) } } mediaSessionConnector.setPlayer(newPlayer) previousPlayer?.stop(/* reset= */true) } private fun preparePlaylist( metadataList: List<MediaMetadataCompat>, itemToPlay: MediaMetadataCompat?, playWhenReady: Boolean, playbackStartPositionMs: Long ) { KLog.i(TAG, "preparePlaylist") val initialWindowIndex = if (itemToPlay == null) 0 else metadataList.indexOfFirst { it.id == itemToPlay?.id } currentPlaylistItems = metadataList currentPlayer.playWhenReady = playWhenReady currentPlayer.stop(/* reset= */ true) if (currentPlayer == exoPlayer) { itemToPlay?.mediaUri?.let { mediaUri -> if (mediaUri.isURL()) { val mediaSource = metadataList.toMediaSource(getDataSourceFactor()) exoPlayer.setMediaSource(mediaSource) } else { exoPlayer.setMediaItem(MediaItem.fromUri(mediaUri)) } } exoPlayer.prepare() exoPlayer.seekTo(initialWindowIndex, playbackStartPositionMs) } } /** * 播放器 相關狀態事件處理 */ private inner class PlayerEventListener : Player.Listener { override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) { KLog.i(TAG, "onPlayerStateChanged:$playbackState") when (playbackState) { Player.STATE_BUFFERING, Player.STATE_READY -> { //TODO: show notification notificationManager.showNotificationForPlayer(currentPlayer) // If playback is paused we remove the foreground state which allows the // notification to be dismissed. An alternative would be to provide a "close" // button in the notification which stops playback and clears the notification. if (playbackState == Player.STATE_READY) { if (!playWhenReady) stopForeground(false) } } else -> { //TODO: hide notification notificationManager.hideNotification() } } } override fun onPlayerError(error: PlaybackException) { super.onPlayerError(error) KLog.e(TAG, "onPlayerError:${error.errorCode}") KLog.e(TAG, "onPlayerError:${error.errorCodeName}") KLog.e(TAG, "onPlayerError:${error.cause}") val currentPlayItem = currentPlaylistItems[currentPlayer.currentMediaItemIndex] KLog.e(TAG, "onPlayerError:${currentPlayItem.displayTitle}") KLog.e(TAG, "onPlayerError:${currentPlayItem.mediaUri}") val intent = Intent(com.cmoney.kolfanci.BuildConfig.APPLICATION_ID) val responseCode = (error.cause as? HttpDataSource.InvalidResponseCodeException)?.responseCode ?: -1 intent.putExtra(PLAY_ERROR_RESPONSE_CODE_KEY, responseCode) intent.putExtra(PLAY_ERROR_STORY_ID_KEY, currentPlayItem.id) LocalBroadcastManager.getInstance(this@MusicMediaService).sendBroadcast(intent) } } /** * 設定準備要播放的音樂 */ private inner class MusicPlaybackPreparer : MediaSessionConnector.PlaybackPreparer { override fun onCommand( player: Player, command: String, extras: Bundle?, cb: ResultReceiver? ): Boolean = false override fun getSupportedPrepareActions(): Long = PlaybackStateCompat.ACTION_PREPARE_FROM_MEDIA_ID or PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID or PlaybackStateCompat.ACTION_PREPARE_FROM_SEARCH or PlaybackStateCompat.ACTION_PLAY_FROM_URI override fun onPrepare(playWhenReady: Boolean) { Log.i(TAG, "onPrepare") } /** * @param mediaId 準備要播放的id * @param extras binder List music 進來 */ override fun onPrepareFromMediaId( mediaId: String, playWhenReady: Boolean, extras: Bundle? ) { Log.i(TAG, "onPrepareFromMediaId:$mediaId") } override fun onPrepareFromSearch(query: String, playWhenReady: Boolean, extras: Bundle?) { } override fun onPrepareFromUri(uri: Uri, playWhenReady: Boolean, extras: Bundle?) { val playItem = MediaMetadataCompat.Builder().also { it.id = uri.toString() it.mediaUri = uri.toString() it.displaySubtitle = " " if (uri.isURL()) { val title = extras?.getString("title").orEmpty() it.displayTitle = title } else { it.displayTitle = uri.getFileName(applicationContext) } }.build() val metadataList = listOf(playItem) preparePlaylist( metadataList = metadataList, itemToPlay = playItem, playWhenReady = true, playbackStartPositionMs = 0L ) } } private inner class MusicQueueNavigator( mediaSession: MediaSessionCompat ) : TimelineQueueNavigator(mediaSession) { /** * 現在播放歌曲的描述,讓 Notification 顯示使用 * MediaMetadataCompat 為 Android 所內建的資料結構 */ override fun getMediaDescription( player: Player, windowIndex: Int ): MediaDescriptionCompat { return currentPlaylistItems[windowIndex].description } } } /** * Extension method for building a [ConcatenatingMediaSource] given a [List] * of [MediaMetadataCompat] objects. */ fun List<MediaMetadataCompat>.toMediaSource( dataSourceFactory: DataSource.Factory ): ConcatenatingMediaSource { val concatenatingMediaSource = ConcatenatingMediaSource() forEach { concatenatingMediaSource.addMediaSource( it.toMediaSource(dataSourceFactory, it) ) } return concatenatingMediaSource } /** * Extension method for building an [ExtractorMediaSource] from a [MediaMetadataCompat] object. * * For convenience, place the [MediaDescriptionCompat] into the tag so it can be retrieved later. */ private fun MediaMetadataCompat.toMediaSource( dataSourceFactory: DataSource.Factory, mediaMetadataCompat: MediaMetadataCompat ) = ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(MediaItem.fromUri(mediaUri)) inline val MediaMetadataCompat.mediaUri: Uri get() = this.getString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI).toUri()
Fanci/app/src/main/java/com/cmoney/kolfanci/service/media/MusicMediaService.kt
1285398441
package com.cmoney.kolfanci.service.media import android.content.Context import android.media.MediaMetadataRetriever import android.media.MediaPlayer import android.media.MediaRecorder import android.net.Uri import android.os.Build import android.support.v4.media.session.PlaybackStateCompat import android.support.v4.media.session.PlaybackStateCompat.STATE_PAUSED import android.support.v4.media.session.PlaybackStateCompat.STATE_PLAYING import android.support.v4.media.session.PlaybackStateCompat.STATE_STOPPED import androidx.lifecycle.Observer import com.cmoney.kolfanci.model.Constant import com.socks.library.KLog import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import java.io.File import java.io.IOException import kotlin.coroutines.CoroutineContext private const val TAG = "MyMediaRecorderImpl2" /** * 錄音與播放介面的實現 */ class RecorderAndPlayerImpl2(private val context: Context,private val musicServiceConnection:MusicServiceConnection) : RecorderAndPlayer { private var playbackState: PlaybackStateCompat = EMPTY_PLAYBACK_STATE private val playbackStateObserver = Observer<PlaybackStateCompat> { playbackState = it val metadata = musicServiceConnection.nowPlaying.value ?: NOTHING_PLAYING when(it.state){ STATE_PLAYING -> { CoroutineScope(coroutineContext).launch { val currentPosition = playbackState.currentPlayBackPosition _playingCurrentMilliseconds.emit(currentPosition) delay(200) } } STATE_PAUSED -> {} STATE_STOPPED -> { //正在播的歌曲 val nowPlaying = musicServiceConnection.nowPlaying.value val duration = nowPlaying?.duration ?: 0L CoroutineScope(coroutineContext).launch { _playingCurrentMilliseconds.emit(duration) } } else -> {} } } private var recorder: MediaRecorder? = null private var filePath: String? = null //目前錄製的秒數 private var _currentRecordSeconds = MutableStateFlow(0L) private var _playingCurrentMilliseconds = MutableStateFlow(0L) private val _progress = MutableStateFlow(0f) private var recordJob: Job? = null //最大錄音秒數 private val maxRecordingDuration = 45000L //錄音時長 private var recordingDuration = 0L private val coroutineContext: CoroutineContext get() = Dispatchers.Default + Job() init { musicServiceConnection.also { it.playbackState.observeForever(playbackStateObserver) } } @Suppress("DEPRECATION") override fun startRecording() { _playingCurrentMilliseconds.value = 0 recorder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { MediaRecorder(context) } else { MediaRecorder() } recorder?.apply { filePath = "${Constant.absoluteCachePath}/錄音_${System.currentTimeMillis()}.aac" setAudioSource(MediaRecorder.AudioSource.MIC) setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS) setOutputFile(filePath) setAudioEncoder(MediaRecorder.AudioEncoder.AAC) try { prepare() } catch (e: IOException) { KLog.e(TAG, "prepare() failed") } start() } startRecordingTimer() } override fun stopRecording() { recorder?.apply { stop() release() } recorder = null stopRecordingTimer() } override fun startPlaying(uri: Uri) { _playingCurrentMilliseconds.value = 0 if (musicServiceConnection.isConnected.value == true) { val transportControls = musicServiceConnection.transportControls transportControls.playFromUri(uri, null) } else { KLog.e(TAG, "musicServiceConnection is not connect.") } } override fun startPlaying() { startPlaying(Uri.parse(filePath)) } override fun pausePlaying() { if (musicServiceConnection.isConnected.value == true) { val transportControls = musicServiceConnection.transportControls musicServiceConnection.playbackState.value?.let { playbackState -> when { playbackState.isPlaying -> transportControls.pause() playbackState.isPlayEnabled -> transportControls.play() else -> { KLog.w( TAG, "Playable item clicked but neither play nor pause are enabled!" ) } } } } } override fun resumePlaying() { if (musicServiceConnection.isConnected.value == true) { val transportControls = musicServiceConnection.transportControls musicServiceConnection.playbackState.value?.let { playbackState -> when { playbackState.isPlayEnabled -> transportControls.play() else -> { KLog.w( TAG, "Playable item clicked but neither play nor pause are enabled!" ) } } } } } override fun stopPlaying() { musicServiceConnection.transportControls.stop() _playingCurrentMilliseconds.value = 0 } override fun dismiss() { recordJob?.cancel() _currentRecordSeconds.value = 0 recordingDuration = 0 recorder?.release() recorder = null musicServiceConnection.transportControls.stop() musicServiceConnection.playbackState.removeObserver(playbackStateObserver) } override fun getPlayingDuration(): Long { val mmr = MediaMetadataRetriever() mmr.setDataSource(filePath) val durationStr = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION) val millSecond = durationStr?.toLong() ?: 0L return millSecond } override fun getPlayingCurrentMilliseconds(): StateFlow<Long> { return _playingCurrentMilliseconds.asStateFlow() } override fun getRecordingCurrentMilliseconds(): StateFlow<Long> = _currentRecordSeconds private fun startRecordingTimer() { recordJob = CoroutineScope(coroutineContext).launch { while (_currentRecordSeconds.value < maxRecordingDuration) { delay(200L) _currentRecordSeconds.value += 200 _progress.value = _currentRecordSeconds.value / maxRecordingDuration.toFloat() } if (_currentRecordSeconds.value >= maxRecordingDuration) { stopRecording() } } } private fun stopRecordingTimer() { recordingDuration = _currentRecordSeconds.value recordJob?.cancel() } override fun getRecordingDuration() = recordingDuration override fun getFileUri(): Uri? { KLog.i(TAG, "fileName: $filePath, Uri: ${Uri.fromFile(filePath?.let { File(it) })}") return Uri.fromFile(filePath?.let { File(it) }) } override fun deleteFile() { filePath?.let { File(it).delete() } } override fun deleteFile(uri: Uri) { filePath?.let { File(uri.toString()).delete() } } }
Fanci/app/src/main/java/com/cmoney/kolfanci/service/media/RecorderAndPlayerImpl2.kt
1130566581