content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.nitc.projectsgc.composable.news import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ViewModelComponent import dagger.hilt.android.scopes.ViewModelScoped import javax.inject.Qualifier @Module @InstallIn(ViewModelComponent::class) object NewsModule { @Provides @ViewModelScoped fun provideNewsRepo():NewsRepo{ return NewsRepo() } @Provides @ViewModelScoped fun provideNewsViewModel(newsRepo: NewsRepo):NewsViewModel{ return NewsViewModel(newsRepo) } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/news/NewsModule.kt
2763335872
package com.nitc.projectsgc.composable.news.screens import android.content.Context import android.widget.Toast import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource import androidx.compose.ui.tooling.preview.Preview import com.nitc.projectsgc.R import com.nitc.projectsgc.composable.components.BasicButton import com.nitc.projectsgc.composable.components.BasicButtonWithEnabled import com.nitc.projectsgc.composable.components.BasicButtonWithState import com.nitc.projectsgc.composable.components.CardInputFieldWithValue import com.nitc.projectsgc.composable.news.NewsViewModel import com.nitc.projectsgc.composable.util.UserRole import com.nitc.projectsgc.models.News import java.text.SimpleDateFormat import java.util.Date import java.util.Locale @Preview @Composable fun AddNewsScreenPreview() { } @OptIn(ExperimentalMaterial3Api::class) @Composable fun AddNewsScreen( newsViewModel: NewsViewModel, mentorID: String, onDismiss: () -> Unit ) { val newsState = remember { mutableStateOf( News( mentorID = mentorID, publishDate = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(Date()) ) ) } val submitState = remember { mutableStateOf(false) } val newsContext = LocalContext.current LaunchedEffect(key1 = submitState.value) { if(submitState.value){ val added = newsViewModel.addNews(UserRole.Mentor,newsState.value) if(added){ showToast("Added",newsContext) }else{ showToast("Could not add news",newsContext) } submitState.value = false } } ModalBottomSheet( sheetState = rememberModalBottomSheetState(), containerColor = Color.White, modifier = Modifier.fillMaxWidth(), onDismissRequest = { onDismiss() }) { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.SpaceEvenly ) { CardInputFieldWithValue( hint = "News for students", text = newsState.value.news, isPassword = false, modifier = Modifier ) { newsInput -> newsState.value = newsState.value.copy(news = newsInput) } BasicButtonWithEnabled( enabled = newsState.value.news.isNotEmpty(), text = "Submit", colors = ButtonDefaults.buttonColors( containerColor = colorResource(id = R.color.navy_blue) ), tc = Color.White, modifier = Modifier) { submitState.value = true } } } } fun showToast(message: String, context: Context) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/news/screens/AddNewsScreen.kt
3517509408
package com.nitc.projectsgc.composable.news.screens import android.content.Context import android.widget.Toast import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.Text 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.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import arrow.core.Either import com.nitc.projectsgc.R import com.nitc.projectsgc.composable.components.NewsCard import com.nitc.projectsgc.composable.components.SubHeadingText import com.nitc.projectsgc.composable.news.NewsViewModel import com.nitc.projectsgc.composable.util.UserRole import com.nitc.projectsgc.models.News @Composable fun NewsScreen( newsViewModel: NewsViewModel, userType: Int, username: String, ) { val newsListState = remember { mutableStateOf(emptyList<News>()) } val newsContext = LocalContext.current LaunchedEffect(Unit) { newsViewModel.getNews() } val newsEitherState by newsViewModel.news.collectAsState() LaunchedEffect(key1 = newsEitherState) { when (val newsEither = newsEitherState) { is Either.Right -> { newsListState.value = newsEither.value } is Either.Left -> { showToast(newsEither.value, newsContext) } } } val deleteNewsState = remember { mutableStateOf<String?>(null) } LaunchedEffect(key1 = deleteNewsState.value) { if (deleteNewsState.value != null) { val deleted = newsViewModel.deleteNews(userType, deleteNewsState.value!!) if (deleted) { showToast("Deleted news", newsContext) newsViewModel.getNews() } else { showToast("Could not delete news", newsContext) } deleteNewsState.value = null } } val addNewsState = remember { mutableStateOf(false) } Box(modifier = Modifier.fillMaxSize()) { LazyColumn( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(4.dp) ) { items(newsListState.value.size) { index -> Box { NewsCard( date = newsListState.value[index].publishDate, mentorName = if (newsListState.value[index].mentorID.contains('_')) newsListState.value[index].mentorID.substring( 0, newsListState.value[index].mentorID.indexOfFirst { it == '_' }).replaceFirstChar(Char::titlecase) else newsListState.value[index].mentorID.replaceFirstChar(Char::titlecase), body = newsListState.value[index].news, clickCallback = { if (userType == UserRole.Admin || (userType == UserRole.Mentor && username == newsListState.value[index].mentorID)) { deleteNewsState.value = newsListState.value[index].newsID } } ) } } } if (userType != UserRole.Student) { FloatingActionButton( containerColor = colorResource(id = R.color.navy_blue), modifier = Modifier .align(Alignment.BottomEnd) .padding(10.dp), onClick = { addNewsState.value = true }) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(7.dp), modifier = Modifier.padding(20.dp) ) { Icon( Icons.Filled.Add, contentDescription = "Add News Button", tint = Color.White ) Text( text = "Add \nNews", color = Color.White, modifier = Modifier, textAlign = TextAlign.Center ) } } } } if (addNewsState.value) { AddNewsScreen(newsViewModel = newsViewModel, mentorID = username, onDismiss = { addNewsState.value = false }) } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/news/screens/NewsScreen.kt
1542506000
package com.nitc.projectsgc.composable.news import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import arrow.core.Either import com.nitc.projectsgc.models.News import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject @HiltViewModel class NewsViewModel @Inject constructor( private val newsRepo:NewsRepo ) : ViewModel(){ private val _news = MutableStateFlow<Either<String,List<News>>>(Either.Right(emptyList())) val news = _news.asStateFlow() fun getNews(){ viewModelScope.launch { _news.value = newsRepo.getNews() } } suspend fun deleteNews(userType:Int,newsID:String):Boolean{ val deleted = withContext(Dispatchers.Main){ newsRepo.deleteNews(userType,newsID) } return deleted } suspend fun addNews(userType: Int,news: News):Boolean{ val added = withContext(Dispatchers.Main){ newsRepo.addNews(userType,news) } return added } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/news/NewsViewModel.kt
3618024811
package com.nitc.projectsgc.composable.login import android.util.Log import arrow.core.Either import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.nitc.projectsgc.composable.util.PathUtils import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class LoginRepo { suspend fun login( username: String, userType: Int, password: String ): Either<String, Boolean> { return suspendCoroutine { continuation -> // var dataAccess = DataAccess(context, parentFragment, sharedViewModel) var isResumed = false var database: FirebaseDatabase = FirebaseDatabase.getInstance() var reference: DatabaseReference = database.reference var auth: FirebaseAuth = FirebaseAuth.getInstance() Log.d( "loginCredentials", "Credentials : $username and password : $password and usertype = $userType" ) auth.signInWithEmailAndPassword(username, password).addOnSuccessListener { authResult -> if (authResult != null) { Log.d("loginSuccess", "Login is successful with username and password") when (userType) { 1 -> { when(val rollNoEither = PathUtils.getUsernameFromEmail(userType,username)){ is Either.Left->{ if(!isResumed){ isResumed = true continuation.resume(Either.Left(rollNoEither.value.message!!)) } } is Either.Right->{ val rollNo = rollNoEither.value reference.child("students").child(rollNo) .addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { Log.d( "loginSuccess", "Login is successful with database" ) if (snapshot.exists()) { if (!isResumed) { isResumed = true continuation.resume(Either.Right(true)) } }else{ auth.currentUser!!.delete() .addOnCompleteListener { deleteTask -> if (!isResumed) { isResumed = true continuation.resume(Either.Left("User not found")) } } .addOnFailureListener { excDelete -> Log.d( "deleteAccount", "Exception - $excDelete" ) if (!isResumed) { isResumed = true continuation.resume(Either.Left("User not found")) } } } } override fun onCancelled(error: DatabaseError) { Log.d("loginError", "Database error : $error") if (!isResumed) { isResumed = true continuation.resume(Either.Left("Database error : $error")) } } }) } } } 2 -> { Log.d("login", "Usertype is 2") when (val mentorTypeEither = PathUtils.getMentorType(username)) { is Either.Left -> { Log.d( "login", "Error in mentor username : ${mentorTypeEither.value.message!!}" ) if (!isResumed) { isResumed = true continuation.resume(Either.Left(mentorTypeEither.value.message!!)) } } is Either.Right -> { Log.d("login", "In either right for mentor") val derivedUsername = PathUtils.getUsernameFromEmailSure(2, username) Log.d("login", "Username = $derivedUsername") reference.child("types").child(mentorTypeEither.value) .child(derivedUsername) .addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { if (snapshot.exists()) { Log.d( "loginSuccess", "Login is successful with database" ) if (!isResumed) { isResumed = true continuation.resume(Either.Right(true)) } } else { if (!isResumed) { isResumed = true continuation.resume(Either.Left("User not found")) } } } override fun onCancelled(error: DatabaseError) { Log.d("login", "Error in getting data : $error") if (!isResumed) { isResumed = true continuation.resume(Either.Left("Error in getting data : $error")) } } }) } } } 0 -> { reference.child("admin") .addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { if (snapshot.exists()) { Log.d( "loginSuccess", "Login is successful with database" ) if (!isResumed) { isResumed = true continuation.resume(Either.Right(true)) } } else { if (!isResumed) { isResumed = true continuation.resume(Either.Left("User not found")) } } } override fun onCancelled(error: DatabaseError) { Log.d("login", "Error in getting data : $error") if (!isResumed) { isResumed = true continuation.resume(Either.Left("Error in getting data : $error")) } } }) } } } }.addOnFailureListener { excAuth -> Log.d("login", "Error in login : $excAuth") if (!isResumed) { isResumed = true continuation.resume(Either.Left("Error in login : $excAuth")) } } } } } //fun logout(): Boolean { //// auth.signOut() // // var deleted = DataAccess( // context, // parentFragment, // sharedViewModel // ).deleteData() // return deleted //}
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/login/LoginRepo.kt
1474994416
package com.nitc.projectsgc.composable.login import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import arrow.core.Either import arrow.core.right import com.nitc.projectsgc.composable.util.PathUtils import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class LoginViewModel @Inject constructor( private val loginRepo: LoginRepo ) : ViewModel() { private val _username = MutableStateFlow("") val username: StateFlow<String> = _username private val _userType = MutableStateFlow(0) val userType: StateFlow<Int> = _userType private val _password = MutableStateFlow("") val password: StateFlow<String> = _password private val _loginCredential = MutableStateFlow(LoginCredential()) val loginCredential: StateFlow<LoginCredential> = _loginCredential private val _isAuthenticated = MutableStateFlow<Either<String, Boolean>?>(null) val isAuthenticated: StateFlow<Either<String, Boolean>?> = _isAuthenticated fun setUsername(username: String) { _username.value = username } fun setUserType(userType: Int) { _userType.value = userType } fun setPassword(password: String) { _password.value = password } fun authenticate() { viewModelScope.launch { _isAuthenticated.value = loginRepo.login(username.value, userType.value, password.value) _loginCredential.value = LoginCredential( userType.value, PathUtils.getUsernameFromEmailSure(userType.value,username.value), password.value ) Log.d("loginSuccess","Authenticated value updated") } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/login/LoginViewModel.kt
1414631907
package com.nitc.projectsgc.composable.login import android.util.Log import android.widget.Toast import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CardDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.navigation.NavController import arrow.core.Either import com.nitc.projectsgc.R import com.nitc.projectsgc.composable.components.BasicButton import com.nitc.projectsgc.composable.components.BasicCard import com.nitc.projectsgc.composable.components.BasicInputField import com.nitc.projectsgc.composable.components.CardInputFieldWithValue import com.nitc.projectsgc.composable.components.LoginCard import com.nitc.projectsgc.composable.util.storage.StorageViewModel @Composable fun LoginScreen( navController: NavController, loginViewModel: LoginViewModel, storageViewModel: StorageViewModel, loginCallback: (userType: Int) -> Unit ) { val screenContext = LocalContext.current val authenticatedEitherState by loginViewModel.isAuthenticated.collectAsState() LaunchedEffect(authenticatedEitherState) { // if(loginState.value){ Log.d("loginSuccess", "in launched effect") when (val authenticated = loginViewModel.isAuthenticated.value) { is Either.Left -> { Toast.makeText(screenContext, authenticated.value, Toast.LENGTH_SHORT).show() } is Either.Right -> { storageViewModel.storeUserData( loginViewModel.loginCredential.value.userType, loginViewModel.loginCredential.value.username, loginViewModel.loginCredential.value.password, ) loginCallback(loginViewModel.userType.value) } null -> { // Toast.makeText(screenContext,"Error in logging you in",Toast.LENGTH_LONG).show() Log.d("loginSuccess", "Authenticated state is null") } } // }else Log.d("loginSuccess","value is false") } Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, ) { // HeadingText(text = "Login", Color.Black) Image( modifier = Modifier.fillMaxSize(0.3F), contentScale = ContentScale.Fit, painter = painterResource(id = R.drawable.sgc_logo_blue_1), contentDescription = "NITC SGC" ) LoginCard() { userType -> loginViewModel.setUserType(userType) } // Spacer(modifier = Modifier.height(10.dp)) LazyColumn( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, ) { items(1) { Spacer(modifier = Modifier.size(50.dp)) CardInputFieldWithValue( hint = "Email", isPassword = false, text = "", modifier = Modifier ) { loginViewModel.setUsername(it) } Spacer(modifier = Modifier.size(20.dp)) CardInputFieldWithValue( hint = "Password", isPassword = true, text = "", modifier = Modifier ) { loginViewModel.setPassword(it) } Spacer(modifier = Modifier.size(50.dp)) BasicButton( text = "Login", colors = ButtonDefaults.buttonColors( containerColor = colorResource(id = R.color.navy_blue) ), modifier = Modifier, tc = Color.White ) { loginViewModel.authenticate() } } } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/login/LoginScreen.kt
2825817841
package com.nitc.projectsgc.composable.login import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ViewModelComponent import dagger.hilt.android.scopes.ViewModelScoped @Module @InstallIn(ViewModelComponent::class) object LoginModule { @Provides @ViewModelScoped fun provideLoginRepo():LoginRepo{ return LoginRepo() } @Provides @ViewModelScoped fun provideLoginViewModel(loginRepo: LoginRepo):LoginViewModel{ return LoginViewModel(loginRepo) } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/login/LoginModule.kt
1585259070
package com.nitc.projectsgc.composable.login data class LoginCredential( val userType:Int = -1, val username:String = "", val password:String = "" )
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/login/LoginCredential.kt
1445765495
package com.nitc.projectsgc.models data class Admin( var username:String? = null, var email:String? = null, var password:String? = null )
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/models/Admin.kt
1918230183
package com.nitc.projectsgc.models data class News( var newsID:String = "", var news:String = "", var mentorID:String = "", var publishDate:String = "", var mentorName:String = "" )
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/models/News.kt
2641171895
package com.nitc.projectsgc.models data class Student( var rollNo:String = "", var name:String = "", var userName:String = "", var dateOfBirth:String = "", var emailId:String = "", var gender:String = "", var password:String = "", var phoneNumber:String = "", )
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/models/Student.kt
1052150585
package com.nitc.projectsgc.models data class Appointment( var date:String = "", var timeSlot:String = "", var mentorType:String = "", var rescheduled:Boolean = false, var mentorID:String = "", var studentID:String = "", var mentorName:String = "", var studentName:String = "", var completed:Boolean = false, var status:String = "", var remarks:String = "", var cancelled:Boolean = false, var expanded:Boolean = false, var id:String = "", var problemDescription:String = "" )
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/models/Appointment.kt
3078471291
package com.nitc.projectsgc.models data class Institution( var institutionName:String? = null, var username:String? = null, var emailSuffix:String? = null )
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/models/Institution.kt
2514944412
package com.nitc.projectsgc.models data class ConsultationType( var type:String ? = null, var mentor: Mentor? )
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/models/ConsultationType.kt
750321201
package com.nitc.projectsgc.models data class Mentor( val name: String = "", val phone: String = "", val email: String = "", val type: String = "", val password: String = "", val userName: String = "", )
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/models/Mentor.kt
1670862224
package com.nitc.projectsgc.models data class Event( var id:String = "", var heading:String? = null, var venue:String? = null, var eventDate:String? = null, var eventTime:String? = null, var link:String = "", var mentorID:String? = null, var type:String = "", var publishDate:String? = null, var mentorName:String? = null )
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/models/Event.kt
576075975
package com.nitc.projectsgc import android.content.Context import androidx.fragment.app.Fragment class DataAccess( var context: Context, var parentFragment: Fragment, var sharedViewModel: SharedViewModel ) { fun saveUsername( password: String, userType: Int, mentorType: String, email:String, username: String, institutionUsername:String ):Boolean{ var saved = false var sharedPreferences = parentFragment.activity?.getSharedPreferences( "sgcLogin", Context.MODE_PRIVATE ) val editor = sharedPreferences?.edit() if (editor != null) { editor.putBoolean("loggedIn", true) editor.putString("password", password) editor.putInt("userType", userType) editor.putString("mentorType", mentorType) editor.putString("email", email) editor.putString("institutionUsername", institutionUsername) editor.putString("username", username) editor.apply() saved = true } return saved } fun deleteData():Boolean{ var sharedPreferences = parentFragment.activity?.getSharedPreferences("sgcLogin",Context.MODE_PRIVATE) if(sharedPreferences == null) return false val editor = sharedPreferences.edit() if (editor != null) { editor.remove("password") editor.remove("mentorType") editor.remove("userType") editor.remove("username") editor.remove("emailSuffix") editor.remove("email") editor.putBoolean("loggedIn",false) editor.apply() sharedViewModel.rescheduling = false sharedViewModel.mentorTypeForProfile = "NA" sharedViewModel.viewAppointmentStudentID = "NA" sharedViewModel.pastRecordStudentID = "NA" sharedViewModel.userType = 1 sharedViewModel.currentUserID = "NA" return true }else return false } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/DataAccess.kt
1680578027
package com.nitc.projectsgc import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.navigation.fragment.findNavController import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.FirebaseDatabase import com.nitc.projectsgc.databinding.FragmentForgotPasswordBinding class ForgotPasswordFragment : Fragment() { lateinit var forgotPasswordBinding: FragmentForgotPasswordBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment forgotPasswordBinding = FragmentForgotPasswordBinding.inflate(inflater,container,false) forgotPasswordBinding.forgotPasswordButtonInForgotPasswordFragment.setOnClickListener { var emailInput = forgotPasswordBinding.emailInputInForgotPasswordFragment.text.toString() var domain = emailInput.substring(emailInput.indexOf("@")+1,emailInput.length) if(domain != "nitc.ac.in"){ forgotPasswordBinding.emailInputInForgotPasswordFragment.error = "Invalid email" Toast.makeText(context, "Please give your valid nitc email", Toast.LENGTH_SHORT).show() forgotPasswordBinding.emailInputInForgotPasswordFragment.requestFocus() } var userId = emailInput.substring(emailInput.indexOf("_")+1,emailInput.indexOf("@")) var auth = FirebaseAuth.getInstance() var reference = FirebaseDatabase.getInstance().reference.child("students") auth.sendPasswordResetEmail(emailInput) .addOnSuccessListener { Toast.makeText(context, "Please check your email and click the link to reset the password", Toast.LENGTH_SHORT).show() // findNavController().navigate(R.id.loginFragment) } .addOnFailureListener { Toast.makeText(context,"You are not registered , please sign up to proceed further", Toast.LENGTH_SHORT).show() } } return forgotPasswordBinding.root } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/ForgotPasswordFragment.kt
1156371688
package com.nitc.projectsgc import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.lifecycle.ViewModel import com.nitc.projectsgc.composable.login.LoginCredential import com.nitc.projectsgc.models.Admin import com.nitc.projectsgc.models.Appointment import com.nitc.projectsgc.models.Event import com.nitc.projectsgc.models.Institution import com.nitc.projectsgc.models.Mentor import com.nitc.projectsgc.models.Student import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject class SharedViewModel:ViewModel() { lateinit var currentInstitution: Institution // var institutionUsername:String = "NA" lateinit var currentMentor: Mentor lateinit var currentAdmin: Admin lateinit var currentStudent: Student lateinit var idForStudentProfile:String lateinit var mentorIDForProfile:String lateinit var mentorTypeForProfile:String var currentUserID = "NA" var userType = 1 lateinit var loginCredential:LoginCredential var rescheduling:Boolean = false lateinit var viewAppointmentStudentID:String var reschedulingMentorName = "NA" lateinit var pastRecordStudentID:String lateinit var reschedulingAppointment: Appointment var isUpdatingEvent:Boolean = false lateinit var updatingOldEvent: Event }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/SharedViewModel.kt
4209666196
package com.example.myapplication import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.myapplication", appContext.packageName) } }
TMX_Android_No1/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt
1188990709
package com.example.myapplication import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
TMX_Android_No1/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt
2019423820
package com.example.myapplication import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
TMX_Android_No1/app/src/main/java/com/example/myapplication/MainActivity.kt
665038924
package com.example.myfirebasechat import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.myfirebasechat", appContext.packageName) } }
MyFirebaseChat/app/src/androidTest/java/com/example/myfirebasechat/ExampleInstrumentedTest.kt
3518746760
package com.example.myfirebasechat import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
MyFirebaseChat/app/src/test/java/com/example/myfirebasechat/ExampleUnitTest.kt
1792994421
package com.example.myfirebasechat.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.myfirebasechat.model.repository.SignUpRepository import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class SignUpViewModel @Inject constructor(private val mSignUpRepository: SignUpRepository) : ViewModel() { private val _registrationResult = MutableLiveData<Boolean>() val registrationResult: LiveData<Boolean> get() = _registrationResult private val _loginResult = MutableLiveData<Boolean>() val loginResult: LiveData<Boolean> get() = _loginResult fun registerUser(userName: String, email: String, password: String) { mSignUpRepository.registerUser(userName, email, password) .observeForever { isSuccess -> _registrationResult.value = isSuccess } } fun loginUser(email: String, password: String) { mSignUpRepository.loginUser(email, password) .observeForever { isSuccess -> _loginResult.value = isSuccess } } }
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/viewmodel/SignUpViewModel.kt
610063539
package com.example.myfirebasechat.viewmodel import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.myfirebasechat.data.Chat import com.example.myfirebasechat.data.User import com.example.myfirebasechat.model.repository.ChatRepository import com.example.myfirebasechat.model.repository.ChatRepositoryImpl import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class ChatViewModel @Inject constructor(private val mChatRepository: ChatRepository) : ViewModel() { private val _user = MutableLiveData<User?>() val user: LiveData<User?> get() = _user private val _error = MutableLiveData<String>() val error: LiveData<String> get() = _error private val _chatList = MutableLiveData<ArrayList<Chat>>() val chatList: LiveData<ArrayList<Chat>> get() = _chatList fun getUserData(userId: String) { mChatRepository.getUserData( userId = userId, callback = { user -> _user.postValue(user) }, errorCallback = { errorMessage -> _error.postValue(errorMessage) } ) } fun readChatMessages(senderId: String, receiverId: String) { mChatRepository.readChatMessages( senderId = senderId, receiverId = receiverId, callback = { chatList -> _chatList.postValue(ArrayList(chatList)) Log.d("ChatViewModel", "Chat messages loaded successfully: $chatList") }, errorCallback = { errorMessage -> _error.postValue(errorMessage) Log.e("ChatViewModel", "Error loading chat messages: $errorMessage") } ) } }
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/viewmodel/ChatViewModel.kt
2542715908
package com.example.myfirebasechat.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.myfirebasechat.data.User import com.example.myfirebasechat.model.repository.UsersRepository import com.example.myfirebasechat.model.repository.UsersRepositoryImpl import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class UsersViewModel @Inject constructor(private val mUsersRepository: UsersRepository) : ViewModel() { private val _userList = MutableLiveData<ArrayList<User>>() val userList: LiveData<ArrayList<User>> get() = _userList private val _error = MutableLiveData<String>() val error: LiveData<String> get() = _error fun fetchUsersList() { mUsersRepository.getUsersList( callback = { userList -> _userList.postValue(userList) }, errorCallback = { errorMessage -> _error.postValue(errorMessage) } ) } }
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/viewmodel/UsersViewModel.kt
937308217
package com.example.myfirebasechat.di import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class MyApplication: Application() { }
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/di/MyApplication.kt
1858012823
package com.example.myfirebasechat.di import com.example.myfirebasechat.model.repository.ChatRepository import com.example.myfirebasechat.model.repository.ChatRepositoryImpl import com.example.myfirebasechat.model.repository.SignUpRepository import com.example.myfirebasechat.model.repository.SignUpRepositoryImpl import com.example.myfirebasechat.model.repository.UsersRepository import com.example.myfirebasechat.model.repository.UsersRepositoryImpl import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class AppModule { @Provides @Singleton fun provideDatabaseReference(): DatabaseReference { return FirebaseDatabase.getInstance().getReference("Users") } @Provides @Singleton fun provideFirebaseAuth(): FirebaseAuth { return FirebaseAuth.getInstance() } @Provides fun provideChatRepository(databaseReference: DatabaseReference): ChatRepository { return ChatRepositoryImpl(databaseReference = databaseReference) } @Provides fun provideSignUpRepository( databaseReference: DatabaseReference, auth: FirebaseAuth ): SignUpRepository { return SignUpRepositoryImpl(databaseReference = databaseReference, auth = auth) } @Provides fun provideUsersRepository( databaseReference: DatabaseReference, auth: FirebaseAuth ): UsersRepository { return UsersRepositoryImpl(databaseReference = databaseReference, auth = auth) } }
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/di/AppModule.kt
3046811674
package com.example.myfirebasechat.model.repository import com.example.myfirebasechat.data.Chat import com.example.myfirebasechat.data.User interface ChatRepository { fun getUserData(userId: String, callback: (User?) -> Unit, errorCallback: (String) -> Unit) fun readChatMessages( senderId: String, receiverId: String, callback: (List<Chat>) -> Unit, errorCallback: (String) -> Unit ) }
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/model/repository/ChatRepository.kt
1012605713
package com.example.myfirebasechat.model.repository import com.example.myfirebasechat.data.User import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.ValueEventListener import javax.inject.Inject class UsersRepositoryImpl @Inject constructor( private val databaseReference: DatabaseReference, private val auth: FirebaseAuth ) : UsersRepository { override fun getUsersList( callback: (ArrayList<User>) -> Unit, errorCallback: (String) -> Unit ) { val firebaseUser: FirebaseUser? = auth.currentUser if (firebaseUser != null) { val databaseReference: DatabaseReference = databaseReference databaseReference.addValueEventListener(object : ValueEventListener { override fun onCancelled(error: DatabaseError) { errorCallback(error.message) } override fun onDataChange(snapshot: DataSnapshot) { val userList = mutableListOf<User>() for (dataSnapShot: DataSnapshot in snapshot.children) { val user = dataSnapShot.getValue(User::class.java) if (user != null && user.userId != firebaseUser.uid) { userList.add(user) } } callback(ArrayList(userList)) } }) } else { errorCallback("User not authenticated") } } }
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/model/repository/UsersRepositoryImpl.kt
3423935581
package com.example.myfirebasechat.model.repository import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.example.myfirebasechat.data.User import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.database.DatabaseReference import javax.inject.Inject class SignUpRepositoryImpl @Inject constructor( private val databaseReference: DatabaseReference, private val auth: FirebaseAuth ) : SignUpRepository { override fun registerUser( userName: String, email: String, password: String ): LiveData<Boolean> { val resultLiveData = MutableLiveData<Boolean>() auth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener { task -> if (task.isSuccessful) { val user: FirebaseUser? = auth.currentUser val userId: String = user!!.uid val userObject = User(userId, userName, "") databaseReference.child(userId).setValue(userObject) .addOnCompleteListener { databaseTask -> resultLiveData.value = databaseTask.isSuccessful } } else { resultLiveData.value = false } } return resultLiveData } override fun loginUser(email: String, password: String): LiveData<Boolean> { val resultLiveData = MutableLiveData<Boolean>() auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener { task -> resultLiveData.value = task.isSuccessful } return resultLiveData } }
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/model/repository/SignUpRepositoryImpl.kt
695322771
package com.example.myfirebasechat.model.repository import android.util.Log import com.example.myfirebasechat.data.Chat import com.example.myfirebasechat.data.User import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import javax.inject.Inject class ChatRepositoryImpl @Inject constructor(private val databaseReference: DatabaseReference) : ChatRepository { override fun getUserData( userId: String, callback: (User?) -> Unit, errorCallback: (String) -> Unit ) { databaseReference.child(userId).addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val user = snapshot.getValue(User::class.java) callback(user) } override fun onCancelled(error: DatabaseError) { errorCallback(error.message) } }) } override fun readChatMessages( senderId: String, receiverId: String, callback: (List<Chat>) -> Unit, errorCallback: (String) -> Unit ) { val databaseReference: DatabaseReference = FirebaseDatabase.getInstance().getReference("Chat") databaseReference.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val chatList = mutableListOf<Chat>() for (dataSnapShot: DataSnapshot in snapshot.children) { val chat = dataSnapShot.getValue(Chat::class.java) if (chat != null) { if ((chat.senderId == senderId && chat.receiverId == receiverId) || (chat.senderId == receiverId && chat.receiverId == senderId) ) { chatList.add(chat) } } } Log.d("ChatRepository", "Loaded ${chatList.size} chat messages") callback(chatList) } override fun onCancelled(error: DatabaseError) { Log.e("ChatRepository", "Error reading chat messages: ${error.message}") errorCallback(error.message) } }) } }
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/model/repository/ChatRepositoryImpl.kt
272576627
package com.example.myfirebasechat.model.repository import com.example.myfirebasechat.data.User interface UsersRepository { fun getUsersList(callback: (ArrayList<User>) -> Unit, errorCallback: (String) -> Unit) }
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/model/repository/UsersRepository.kt
3230689520
package com.example.myfirebasechat.model.repository import androidx.lifecycle.LiveData interface SignUpRepository { fun registerUser(userName:String,email:String,password:String): LiveData<Boolean> fun loginUser(email: String, password: String): LiveData<Boolean> }
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/model/repository/SignUpRepository.kt
3124378589
package com.example.myfirebasechat.view import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import com.example.myfirebasechat.R import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setupNavigation() } private fun setupNavigation() { val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment navController = navHostFragment.navController } }
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/view/MainActivity.kt
3694355089
package com.example.myfirebasechat.view.fragments import android.os.Bundle import android.text.TextUtils import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.example.myfirebasechat.R import com.example.myfirebasechat.databinding.FragmentSignUpBinding import com.example.myfirebasechat.viewmodel.SignUpViewModel import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class SignUpFragment : Fragment() { private var _binding: FragmentSignUpBinding? = null private val mBinding get() = _binding!! private val mSignUpViewModel: SignUpViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment _binding = FragmentSignUpBinding.inflate(inflater, container, false) val view = mBinding.root navigateToLogin() return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) observerRegistrationResult() signUpButtonClick() } private fun observerRegistrationResult() { mSignUpViewModel.registrationResult.observe(viewLifecycleOwner) { isSuccess -> if (isSuccess) { findNavController().navigate(R.id.action_signUpFragment_to_usersFragment) } else { Toast.makeText(context, "Registration failed", Toast.LENGTH_SHORT) .show() } } } private fun signUpButtonClick() { mBinding.apply { mBinding.btnSignUp.setOnClickListener { val userName = etName.text.toString() val email = etEmail.text.toString() val password = etPassword.text.toString() val confirmPassword = etConfirmPassword.text.toString() if (TextUtils.isEmpty(userName)) { Toast.makeText(context, "username is required", Toast.LENGTH_SHORT) .show() } if (TextUtils.isEmpty(email)) { Toast.makeText(context, "email is required", Toast.LENGTH_SHORT) .show() } if (TextUtils.isEmpty(password)) { Toast.makeText(context, "password is required", Toast.LENGTH_SHORT) .show() } if (TextUtils.isEmpty(confirmPassword)) { Toast.makeText( context, "confirm password is required", Toast.LENGTH_SHORT ).show() } if (password != confirmPassword) { Toast.makeText(context, "password not match", Toast.LENGTH_SHORT) .show() } mSignUpViewModel.registerUser(userName, email, password) } } } private fun navigateToLogin() { mBinding.btnLogin.setOnClickListener { findNavController().navigate(R.id.action_signUpFragment_to_loginFragment) } } }
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/view/fragments/SignUpFragment.kt
1692658737
package com.example.myfirebasechat.view.fragments import android.os.Bundle import android.text.TextUtils import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.example.myfirebasechat.R import com.example.myfirebasechat.databinding.FragmentLoginBinding import com.example.myfirebasechat.viewmodel.SignUpViewModel import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class LoginFragment : Fragment() { private var _binding: FragmentLoginBinding? = null private val mBinding get() = _binding!! private val mSignUpViewModel: SignUpViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment _binding = FragmentLoginBinding.inflate(inflater, container, false) val view = mBinding.root navigateToSignUp() return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) loginButtonClick() observerLoginResult() } private fun loginButtonClick() { mBinding.btnLogin.setOnClickListener { val email = mBinding.etEmail.text.toString() val password = mBinding.etPassword.text.toString() if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) { showToast("Email and password are required") } else { mSignUpViewModel.loginUser(email, password) } } } private fun observerLoginResult() { mSignUpViewModel.loginResult.observe(viewLifecycleOwner) { isSuccess -> if (isSuccess) { clearFields() findNavController().navigate(R.id.action_loginFragment_to_usersFragment) } else { showToast("Email or password invalid") } } } private fun navigateToSignUp() { mBinding.btnSignUp.setOnClickListener { findNavController().navigate(R.id.action_loginFragment_to_signUpFragment) } } private fun showToast(message: String) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() } private fun clearFields() { mBinding.etEmail.setText("") mBinding.etPassword.setText("") } }
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/view/fragments/LoginFragment.kt
1212053511
package com.example.myfirebasechat.view.fragments import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.myfirebasechat.R import com.example.myfirebasechat.data.Chat import com.example.myfirebasechat.databinding.FragmentChatBinding import com.example.myfirebasechat.view.adapter.ChatAdapter import com.example.myfirebasechat.viewmodel.ChatViewModel import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class ChatFragment : Fragment() { private var _binding: FragmentChatBinding? = null private val mBinding get() = _binding!! private val mChatViewModel: ChatViewModel by viewModels() private var firebaseUser: FirebaseUser? = null private var reference: DatabaseReference? = null private var topic = "" override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment _binding = FragmentChatBinding.inflate(inflater, container, false) val view = mBinding.root return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val userId = arguments?.getString("userId") Log.d("userId", "Received user ID: $userId") firebaseUser = FirebaseAuth.getInstance().currentUser reference = FirebaseDatabase.getInstance().getReference("Users").child(userId!!) setupUserRecyclerView() onBackBtnListener() initObservers() mChatViewModel.getUserData(userId) sendMessageButtonClick(userId) mChatViewModel.readChatMessages(firebaseUser!!.uid, userId) } private fun setupUserRecyclerView() { mBinding.chatRecyclerView.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false) } private fun onBackBtnListener() { mBinding.imgBack.setOnClickListener { findNavController().navigate(R.id.action_chatFragment_to_usersFragment) } } private fun initObservers() { mChatViewModel.error.observe(viewLifecycleOwner) { errorMessage -> Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show() } mChatViewModel.chatList.observe(viewLifecycleOwner) { chatList -> val chatAdapter = ChatAdapter(requireContext(), chatList) mBinding.chatRecyclerView.adapter = chatAdapter } mChatViewModel.user.observe(viewLifecycleOwner) { user -> mBinding.tvUserName.text = user?.userName if (user?.profileImage == "") { mBinding.imgProfile.setImageResource(R.drawable.profile_image) } else { context?.let { Glide.with(it).load(user?.profileImage).into(mBinding.imgProfile) } } } } private fun sendMessageButtonClick(userId: String?) { mBinding.btnSendMessage.setOnClickListener { val message: String = mBinding.etMessage.text.toString() if (message.isEmpty()) { Toast.makeText(context, "message is empty", Toast.LENGTH_SHORT).show() mBinding.etMessage.setText("") } else { if (userId != null) { sendMessage(firebaseUser!!.uid, userId, message) } mBinding.etMessage.setText("") topic = "/topics/$userId" } } } private fun sendMessage(senderId: String, receiverId: String, message: String) { val reference: DatabaseReference = FirebaseDatabase.getInstance().reference val chat = Chat(senderId, receiverId, message) reference.child("Chat").push().setValue(chat) } }
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/view/fragments/ChatFragment.kt
3895034260
package com.example.myfirebasechat.view.fragments import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.os.bundleOf import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.myfirebasechat.R import com.example.myfirebasechat.databinding.FragmentUsersBinding import com.example.myfirebasechat.view.adapter.UserAdapter import com.example.myfirebasechat.viewmodel.UsersViewModel import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class UsersFragment : Fragment(), UserAdapter.UserClickListener { private var _binding: FragmentUsersBinding? = null private val mBinding get() = _binding!! private val mUsersViewModel: UsersViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment _binding = FragmentUsersBinding.inflate(inflater, container, false) val view = mBinding.root return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupUserRecyclerView() initObservers() mUsersViewModel.fetchUsersList() } private fun setupUserRecyclerView() { mBinding.userRecyclerView.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false) } private fun initObservers() { mUsersViewModel.userList.observe(viewLifecycleOwner) { userList -> val userAdapter = context?.let { UserAdapter(it, userList) } if (userAdapter != null) { mBinding.userRecyclerView.adapter = userAdapter.setUserClickListener(this) } } mUsersViewModel.error.observe(viewLifecycleOwner) { errorMessage -> Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show() } } override fun onUserClicked(userId: String, userName: String) { val bundle = Bundle().apply { putString("userId", userId) putString("userName", userName) } findNavController().navigate(R.id.action_usersFragment_to_chatFragment, bundle) } }
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/view/fragments/UsersFragment.kt
4015501495
package com.example.myfirebasechat.view.adapter import android.content.Context import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.myfirebasechat.R import com.example.myfirebasechat.data.Chat import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import de.hdodenhof.circleimageview.CircleImageView class ChatAdapter(private val context: Context, private val chatList: ArrayList<Chat>) : RecyclerView.Adapter<ChatAdapter.ViewHolder>() { private var firebaseUser: FirebaseUser? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return if (viewType == MESSAGE_TYPE_RIGHT) { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_right, parent, false) ViewHolder(view) } else { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_left, parent, false) ViewHolder(view) } } override fun getItemCount(): Int { return chatList.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val chat = chatList[position] Log.d("ChatAdapter", "Message: ${chat.message}") holder.txtUserName.text = chat.message //Glide.with(context).load(user.profileImage).placeholder(R.drawable.profile_image).into(holder.imgUser) } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val txtUserName: TextView = view.findViewById(R.id.tvMessage) val imgUser: CircleImageView = view.findViewById(R.id.userImage) } override fun getItemViewType(position: Int): Int { firebaseUser = FirebaseAuth.getInstance().currentUser return if (chatList[position].senderId == firebaseUser!!.uid) { MESSAGE_TYPE_RIGHT } else { MESSAGE_TYPE_LEFT } } } const val MESSAGE_TYPE_LEFT = 0 const val MESSAGE_TYPE_RIGHT = 1
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/view/adapter/ChatAdapter.kt
89897015
package com.example.myfirebasechat.view.adapter import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.FragmentActivity import androidx.navigation.Navigation.findNavController import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.myfirebasechat.R import com.example.myfirebasechat.data.User import com.example.myfirebasechat.view.fragments.ChatFragment import com.example.myfirebasechat.view.fragments.UsersFragmentDirections import de.hdodenhof.circleimageview.CircleImageView class UserAdapter(private val context: Context, private val userList: ArrayList<User>) : RecyclerView.Adapter<UserAdapter.ViewHolder>() { private var userClickListener: UserClickListener? = null fun setUserClickListener(listener: UserClickListener): UserAdapter { userClickListener = listener return this } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_user, parent, false) return ViewHolder(view) } override fun getItemCount(): Int { return userList.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val user = userList[position] holder.txtUserName.text = user.userName Glide.with(context).load(user.profileImage).placeholder(R.drawable.profile_image) .into(holder.imgUser) holder.layoutUser.setOnClickListener { userClickListener?.onUserClicked(user.userId, user.userName) } } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val txtUserName: TextView = view.findViewById(R.id.userName) val txtTemp: TextView = view.findViewById(R.id.temp) val imgUser: CircleImageView = view.findViewById(R.id.userImage) val layoutUser: LinearLayout = view.findViewById(R.id.layoutUser) } interface UserClickListener { fun onUserClicked(userId: String, userName: String) } }
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/view/adapter/UserAdapter.kt
4000668648
package com.example.myfirebasechat.data data class Chat(val senderId: String = "", val receiverId: String = "", val message: String = "")
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/data/Chat.kt
3760057853
package com.example.myfirebasechat.data data class User(val userId: String = "", val userName: String = "", val profileImage: String = "")
MyFirebaseChat/app/src/main/java/com/example/myfirebasechat/data/User.kt
4095728216
package com.example.examapp import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.examapp", appContext.packageName) } }
MCQ-Exam-App-Layout-/app/src/androidTest/java/com/example/examapp/ExampleInstrumentedTest.kt
4094984237
package com.example.examapp import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
MCQ-Exam-App-Layout-/app/src/test/java/com/example/examapp/ExampleUnitTest.kt
969170710
package com.example.examapp import android.content.DialogInterface import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AlertDialog import com.example.examapp.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.btn1.setOnClickListener { val answers = arrayOf("Narmada","Mahanadi","Son","Netravati") val builder1 = AlertDialog.Builder(this) builder1.setTitle("Choose the correct Answer") builder1.setSingleChoiceItems(answers, 0, DialogInterface.OnClickListener { dialog, which -> Toast.makeText(this, "You have selected ${answers[which]}", Toast.LENGTH_SHORT).show() }) builder1.setPositiveButton("Submit",DialogInterface.OnClickListener { dialog, which -> }) builder1.setNegativeButton("Decline",DialogInterface.OnClickListener { dialog, which -> }) builder1.show() } binding.btn2.setOnClickListener { val answers = arrayOf("Chennai","Cuttack","Bangalore","Quilion") val builder2 = AlertDialog.Builder(this) builder2.setTitle("Choose the correct Answer") builder2.setSingleChoiceItems(answers, 0, DialogInterface.OnClickListener { dialog, which -> Toast.makeText(this, "You have selected ${answers[which]}", Toast.LENGTH_SHORT).show() }) builder2.setPositiveButton("Submit",DialogInterface.OnClickListener { dialog, which -> }) builder2.setNegativeButton("Decline",DialogInterface.OnClickListener { dialog, which -> }) builder2.show() } binding.btn3.setOnClickListener { val answers = arrayOf("Kalidasa","Charak","Panini","Aryabhatt") val builder3 = AlertDialog.Builder(this) builder3.setTitle("Choose the correct Answer") builder3.setSingleChoiceItems(answers, 0, DialogInterface.OnClickListener { dialog, which -> Toast.makeText(this, "You have selected ${answers[which]}", Toast.LENGTH_SHORT).show() }) builder3.setPositiveButton("Submit",DialogInterface.OnClickListener { dialog, which -> }) builder3.setNegativeButton("Decline",DialogInterface.OnClickListener { dialog, which -> }) builder3.show() } binding.btn4.setOnClickListener { val answers = arrayOf("Alaknanda","Pindar","Mandakini","Bhagirathi") val builder4 = AlertDialog.Builder(this) builder4.setTitle("Choose the correct Answer") builder4.setSingleChoiceItems(answers, 0, DialogInterface.OnClickListener { dialog, which -> Toast.makeText(this, "You have selected ${answers[which]}", Toast.LENGTH_SHORT).show() }) builder4.setPositiveButton("Submit",DialogInterface.OnClickListener { dialog, which -> }) builder4.setNegativeButton("Decline",DialogInterface.OnClickListener { dialog, which -> }) builder4.show() } binding.btn5.setOnClickListener { val answers = arrayOf("Pennar","Cauvery","Krishna","Tapti") val builder5 = AlertDialog.Builder(this) builder5.setTitle("Choose the correct Answer") builder5.setSingleChoiceItems(answers, 0, DialogInterface.OnClickListener { dialog, which -> Toast.makeText(this, "You have selected ${answers[which]}", Toast.LENGTH_SHORT).show() }) builder5.setPositiveButton("Submit",DialogInterface.OnClickListener { dialog, which -> }) builder5.setNegativeButton("Decline",DialogInterface.OnClickListener { dialog, which -> }) builder5.show() } } }
MCQ-Exam-App-Layout-/app/src/main/java/com/example/examapp/MainActivity.kt
3108207700
package com.example.socketbuzzchat import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.socketbuzzchat", appContext.packageName) } }
SocketBuzzChat/app/src/androidTest/java/com/example/socketbuzzchat/ExampleInstrumentedTest.kt
696423388
package com.example.socketbuzzchat import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
SocketBuzzChat/app/src/test/java/com/example/socketbuzzchat/ExampleUnitTest.kt
522141584
package com.example.socketbuzzchat import android.util.Log import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import okhttp3.WebSocket import okhttp3.WebSocketListener import org.json.JSONException import org.json.JSONObject class WebSocketClient (private val mainActivity: MainActivity){ private val url: String = "wss://buzzmehi.com/socketChat/?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFzaHdpbkBhZG1pbi5jb20iLCJpYXQiOjE3MDcyMDA2MzEsImV4cCI6MTcwNzIyOTQzMX0.843xcAMbZr0u_URly_zUlOKIDdX9zNdCQWA1pHLQwEY"; private val authToken: String = "token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im11ekBhZG1pbi5jb20iLCJpYXQiOjE3MDcxMTg1MzMsImV4cCI6MTcwNzE0NzMzM30.5C_rPRI8w_MVrzRRLvHLVaaae_84vCxXYl0fHp7OAnU"; private val client = OkHttpClient() private var webSocket: WebSocket? = null fun connect() { val request = Request.Builder() .url(url) //.addHeader("Authorization", "Bearer $authToken") .build() webSocket = client.newWebSocket(request, MyWebSocketListener()) } fun disconnect() { webSocket?.close(1000, "User disconnect") } fun sendMessage(message: String): Boolean { return webSocket?.send(message) == true } inner class MyWebSocketListener : WebSocketListener() { override fun onOpen(webSocket: WebSocket, response: Response) { super.onOpen(webSocket, response) Log.d("WebSocket", "WebSocket connection opened") Log.d("WebSocket", "Response: $response") Log.d("WebSocket", "Request: "+response.request.toString()) Log.d("WebSocket", "Headers: "+response.headers.toString()) Log.d("WebSocket", "Message: "+response.message.toString()) mainActivity.updateStatus("Connected to Server") } override fun onMessage(webSocket: WebSocket, text: String) { super.onMessage(webSocket, text) Log.d("WebSocket", "Received message: $text") } override fun onClosed(webSocket: WebSocket, code: Int, reason: String) { Log.d("WebSocket", "WebSocket connection closed. Code: $code, Reason: $reason") mainActivity.updateStatus("Disconnected from Server") } override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { Log.e("WebSocket", "WebSocket connection failure", t) } } }
SocketBuzzChat/app/src/main/java/com/example/socketbuzzchat/WebSocketClient.kt
2428314237
package com.example.socketbuzzchat import android.annotation.SuppressLint import android.os.Bundle import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.AppCompatButton import io.socket.client.IO import io.socket.client.Socket import java.net.URISyntaxException class MainActivity : AppCompatActivity() { private lateinit var tvStatus: TextView; private val webSocket = WebSocketClient(this); @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) tvStatus = findViewById(R.id.tvStatus); val btnConnect: AppCompatButton = findViewById(R.id.btnConnect); val btnSendMessage: AppCompatButton = findViewById(R.id.btnSendMessage); val btnDisconnect: AppCompatButton = findViewById(R.id.btnDisconnect); btnConnect.setOnClickListener { webSocket.connect(); } btnSendMessage.setOnClickListener { val message = "Hey Dev" if (webSocket.sendMessage(message)) { Toast.makeText(this, "Message sent: $message", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, "Failed to send message", Toast.LENGTH_SHORT).show() } } btnDisconnect.setOnClickListener { webSocket.disconnect(); } } override fun onDestroy() { super.onDestroy() webSocket.disconnect() } fun updateStatus(status: String) { runOnUiThread { tvStatus.text = status } } } //private var socket: Socket? = null //socket!!.on(Socket.EVENT_CONNECT) { args: Array<Any?>? -> // Toast.makeText(this, "Connected to server", Toast.LENGTH_LONG).show() // tvStatus.text = "Connected to Server" //} //socket!!.on(Socket.EVENT_DISCONNECT) { args: Array<Any?>? -> // Toast.makeText(this, "Disconnected from server", Toast.LENGTH_LONG).show() // tvStatus.text = "Disconnected" //} //private fun connectToSocket() { // try { // val options = IO.Options() // options.query = "" // socket = IO.socket("") // socket!!.connect() // // } catch (e: URISyntaxException) { // e.printStackTrace() // } //} // //private fun disconnectFromSocket() { // if (socket?.connected() == true) { // socket?.disconnect() // } //}
SocketBuzzChat/app/src/main/java/com/example/socketbuzzchat/MainActivity.kt
1032555854
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.mcauth.msa import net.sharedwonder.mc.ptbridge.mcauth.MCAuth import net.sharedwonder.mc.ptbridge.utils.GSON import net.sharedwonder.mc.ptbridge.utils.HTTPRequestUtils import net.sharedwonder.mc.ptbridge.utils.PlayerProfile import net.sharedwonder.mc.ptbridge.utils.UUIDUtils import java.net.URI import com.google.gson.JsonArray import com.google.gson.JsonObject class MCAuthWithMSA(tokenType: MSAAuthTokenType, authToken: String) : MCAuth { override val accessToken: String override val expirationTime: Long val msaRefreshToken: String init { val (msaAccessToken, msaRefreshToken) = msaAuthStep(tokenType, authToken) val (xboxLiveToken, xboxUserHash) = xboxLiveAuthStep(msaAccessToken) val xstsToken = xstsAuthStep(xboxLiveToken) val startTime = System.currentTimeMillis() val (accessToken, expiresIn) = mcAuthStep(xstsToken, xboxUserHash) this.accessToken = accessToken expirationTime = startTime + expiresIn * 1000 this.msaRefreshToken = msaRefreshToken } override fun refresh(): MCAuthWithMSA = MCAuthWithMSA(MSAAuthTokenType.REFRESH_TOKEN, msaRefreshToken) override fun createProfile(): PlayerProfile { val response = HTTPRequestUtils.request(MC_QUERY_PROFILE_URL) { setRequestProperty("Authorization", "Bearer $accessToken") }.onFailure { throw buildException("Failed to query the player profile") }.response.contentAsUtf8String val jsonResponse = GSON.fromJson(response, JsonObject::class.java) return PlayerProfile(jsonResponse["name"].asString, UUIDUtils.stringToUuid(jsonResponse["id"].asString), this) } } private val MSA_AUTH_URL = URI("https://login.live.com/oauth20_token.srf").toURL() private val XBOX_LIVE_AUTH_URL = URI("https://user.auth.xboxlive.com/user/authenticate").toURL() private val XSTS_AUTH_URL = URI("https://xsts.auth.xboxlive.com/xsts/authorize").toURL() private val MC_AUTH_URL = URI("https://api.minecraftservices.com/authentication/login_with_xbox").toURL() private val MC_QUERY_PROFILE_URL = URI("https://api.minecraftservices.com/minecraft/profile").toURL() private fun msaAuthStep(tokenType: MSAAuthTokenType, authToken: String): MSAAuthResponse { val body = mapOf( "client_id" to "00000000402b5328", "grant_type" to tokenType.value, "scope" to "service::user.auth.xboxlive.com::MBI_SSL", "redirect_uri" to "https://login.live.com/oauth20_desktop.srf", tokenType.queryParamName to authToken ) val content = HTTPRequestUtils.request(MSA_AUTH_URL, "POST", "application/x-www-form-urlencoded; charset=utf-8", HTTPRequestUtils.encodeMap(body)) .onFailure { throw buildException("Failed to get the MSA access token") }.response.contentAsUtf8String return GSON.fromJson(content, MSAAuthResponse::class.java) } private fun xboxLiveAuthStep(msaToken: String): Pair<String, String> { val body = JsonObject() body.add("Properties", JsonObject().apply { addProperty("AuthMethod", "RPS") addProperty("SiteName", "user.auth.xboxlive.com") addProperty("RpsTicket", msaToken) }) body.addProperty("RelyingParty", "http://auth.xboxlive.com") body.addProperty("TokenType", "JWT") val content = HTTPRequestUtils.request(XBOX_LIVE_AUTH_URL, "POST", "application/json; charset=utf-8", GSON.toJson(body)) .onFailure { throw buildException("Failed to get the Xbox access token") }.response.contentAsUtf8String val json = GSON.fromJson(content, JsonObject::class.java) val token = json["Token"].asString val userHash = json["DisplayClaims"].asJsonObject["xui"].asJsonArray[0].asJsonObject["uhs"].asString return token to userHash } private fun xstsAuthStep(xboxToken: String): String { val body = JsonObject() body.add("Properties", JsonObject().apply { addProperty("SandboxId", "RETAIL") add("UserTokens", JsonArray().apply { add(xboxToken) }) }) body.addProperty("RelyingParty", "rp://api.minecraftservices.com/") body.addProperty("TokenType", "JWT") val content = HTTPRequestUtils.request(XSTS_AUTH_URL, "POST", "application/json; charset=utf-8", GSON.toJson(body)) .onFailure { throw buildException("Failed to get the XSTS access token") }.response.contentAsUtf8String return GSON.fromJson(content, JsonObject::class.java)["Token"].asString } private fun mcAuthStep(xstsToken: String, xboxUserHash: String): MCAuthResponse { val body = JsonObject() body.addProperty("identityToken", "XBL3.0 x=$xboxUserHash;$xstsToken") val content = HTTPRequestUtils.request(MC_AUTH_URL, "POST", "application/json; charset=utf-8", GSON.toJson(body)) .onFailure { throw buildException("Failed to get the Minecraft access token") }.response.contentAsUtf8String return GSON.fromJson(content, MCAuthResponse::class.java) }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/mcauth/msa/MCAuthWithMSA.kt
2532738264
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.mcauth.msa import com.google.gson.annotations.SerializedName data class MCAuthResponse( @SerializedName("access_token") val accessToken: String, @SerializedName("expires_in") val expiresIn: Int )
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/mcauth/msa/MCAuthResponse.kt
4207976383
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.mcauth.msa enum class MSAAuthTokenType(val value: String, val queryParamName: String) { AUTHORIZATION_CODE("authorization_code", "code"), REFRESH_TOKEN("refresh_token", "refresh_token") }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/mcauth/msa/MSAAuthTokenType.kt
2642031689
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.mcauth.msa import com.google.gson.annotations.SerializedName data class MSAAuthResponse( @SerializedName("access_token") val accessToken: String, @SerializedName("refresh_token") val refreshToken: String, @SerializedName("expires_in") val expiresIn: Int )
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/mcauth/msa/MSAAuthResponse.kt
2355112194
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.mcauth import net.sharedwonder.mc.ptbridge.utils.PlayerProfile interface MCAuth { val accessToken: String val expirationTime: Long fun refresh(): MCAuth fun createProfile(): PlayerProfile }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/mcauth/MCAuth.kt
2347788149
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.config import java.io.File class ConfigManager private constructor(private val configDir: File) { fun getConfigFile(name: String): File = File(configDir, name) companion object { @JvmStatic private var instance: ConfigManager? = null @JvmStatic fun getInstance(): ConfigManager = instance!! @JvmStatic @PublishedApi internal fun createInstance(configDir: File) { instance = ConfigManager(configDir) } } }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/config/ConfigManager.kt
3384578111
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge import net.sharedwonder.mc.ptbridge.addon.ExternalContext import net.sharedwonder.mc.ptbridge.crypt.EncryptionContext import net.sharedwonder.mc.ptbridge.utils.ConnectionState import net.sharedwonder.mc.ptbridge.utils.PlayerProfile import kotlin.collections.component1 import kotlin.collections.component2 import kotlin.collections.set import java.util.Queue import java.util.concurrent.LinkedBlockingQueue import java.util.function.Function import java.util.function.Supplier import io.netty.buffer.ByteBuf import org.apache.logging.log4j.LogManager class ConnectionContext internal constructor(proxyServer: ProxyServer) { @JvmField val bindPort: Int = proxyServer.bindPort @JvmField val remoteAddress: String = proxyServer.remoteAddress @JvmField val remotePort: Int = proxyServer.remotePort @JvmField val minecraftAccounts: Map<String, PlayerProfile>? = proxyServer.minecraftAccounts @JvmField internal val toServerPacketQueue: Queue<ByteBuf> = LinkedBlockingQueue() @JvmField internal val toClientPacketQueue: Queue<ByteBuf> = LinkedBlockingQueue() private val externalContexts: Map<Class<out ExternalContext>, ExternalContext> = buildMap { for ((type, generator) in EXTERNAL_CONTEXT_TYPES) { put(type, generator(this@ConnectionContext)) } } var encryptionContext: EncryptionContext = EncryptionContext.disabled() var connectionState: ConnectionState = ConnectionState.HANDSHAKE var compressionThreshold: Int = -1 private var _clientAddress: String? = null var clientAddress: String get() = checkNotNull(_clientAddress) { "clientAddress is not set" } set(value) { _clientAddress = value } private var _protocolVersion: Int? = null var protocolVersion: Int get() = checkNotNull(_protocolVersion) { "protocolVersion is not set" } set(value) { _protocolVersion = value } private var _playerUsername: String? = null var playerUsername: String get() = checkNotNull(_playerUsername) { "playerUsername is not set" } set(value) { _playerUsername = value } fun <T : ExternalContext> getExternalContext(type: Class<T>): T = type.cast(externalContexts[type]) fun sendToClient(packet: ByteBuf) { toClientPacketQueue.add(packet) } fun sendToServer(packet: ByteBuf) { toServerPacketQueue.add(packet) } @PublishedApi internal fun onConnect() { val threads = ArrayList<Thread>(externalContexts.size) for (externalContext in externalContexts.values) { threads.add(Thread { try { externalContext.onConnect() } catch (exception: Throwable) { LOGGER.error("An error occurred while calling onConnect on ${externalContext.javaClass.typeName}", exception) } }.apply { start() }) } threads.forEach { it.join() } } @PublishedApi internal fun onDisconnect() { val threads = ArrayList<Thread>(externalContexts.size) for (externalContext in externalContexts.values) { threads.add(Thread { try { externalContext.onDisconnect() } catch (exception: Throwable) { LOGGER.error("An error occurred while calling onDisconnect on ${externalContext.javaClass.typeName}", exception) } }.apply { start() }) } threads.forEach { it.join() } } companion object { private val LOGGER = LogManager.getLogger(ConnectionContext::class.java) private val EXTERNAL_CONTEXT_TYPES: MutableMap<Class<out ExternalContext>, (ConnectionContext) -> ExternalContext> = HashMap() @JvmStatic @JvmSynthetic fun <T : ExternalContext> registerExternalContextType(type: Class<T>, generator: (ConnectionContext) -> T) { EXTERNAL_CONTEXT_TYPES[type] = generator } @JvmStatic fun <T : ExternalContext> registerExternalContextType(type: Class<T>, generator: Supplier<out T>) { EXTERNAL_CONTEXT_TYPES[type] = { generator.get() } } @JvmStatic fun <T : ExternalContext> registerExternalContextType(type: Class<T>, generator: Function<ConnectionContext, out T>) { EXTERNAL_CONTEXT_TYPES[type] = generator::apply } @JvmStatic fun <T : ExternalContext> unregisterExternalContextType(type: Class<T>) { EXTERNAL_CONTEXT_TYPES.remove(type) } } }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/ConnectionContext.kt
1183649854
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge import net.sharedwonder.mc.ptbridge.addon.AddonLoader import net.sharedwonder.mc.ptbridge.config.ConfigManager import net.sharedwonder.mc.ptbridge.packet.PacketHandlers import net.sharedwonder.mc.ptbridge.utils.AccountsFileUtils import net.sharedwonder.mc.ptbridge.utils.PlayerProfile import java.io.File import java.util.Hashtable import javax.naming.NamingException import javax.naming.directory.DirContext import javax.naming.directory.InitialDirContext import io.netty.bootstrap.ServerBootstrap import io.netty.channel.ChannelInitializer import io.netty.channel.ChannelOption import io.netty.channel.EventLoopGroup import io.netty.channel.nio.NioEventLoopGroup import io.netty.channel.socket.SocketChannel import io.netty.channel.socket.nio.NioServerSocketChannel import org.apache.logging.log4j.LogManager class ProxyServer(val bindPort: Int, host: String, port: Int, accountsFile: File, private val addonsDir: File, private val configDir: File) { val remoteAddress: String val remotePort: Int val minecraftAccounts: MutableMap<String, PlayerProfile>? init { try { LOGGER.info("Initializing...") ConfigManager.createInstance(configDir) PacketHandlers.registerDefaultHandlers() AddonLoader.init(addonsDir) var minecraftAccounts: MutableMap<String, PlayerProfile>? = null try { if (accountsFile.isFile) { minecraftAccounts = AccountsFileUtils.readFile(accountsFile) if (refreshTokensIfExpired(minecraftAccounts)) { AccountsFileUtils.writeFile(accountsFile, minecraftAccounts) } } } catch (exception: Exception) { LOGGER.error("An error occurred while processing Minecraft accounts data: $exception") } this.minecraftAccounts = minecraftAccounts val lookupResult = if (port == 25565) { try { lookupServer(host) } catch (exception: Exception) { null } } else null remoteAddress = lookupResult?.first ?: host remotePort = lookupResult?.second ?: port if (LOGGER.isInfoEnabled) { LOGGER.info("Remote server: ${if (':' in remoteAddress) "[$remoteAddress]" else remoteAddress}:$remotePort") } } catch (exception: Throwable) { LOGGER.fatal("A fatal exception occurred when initializing", exception) throw RuntimeException(exception) } } fun run(): Int { LOGGER.info("Starting Minecraft proxy server...") val bossGroup: EventLoopGroup = NioEventLoopGroup() val workerGroup: EventLoopGroup = NioEventLoopGroup() try { val serverBootstrap = ServerBootstrap() serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel::class.java) .childOption(ChannelOption.TCP_NODELAY, true) .childHandler(object : ChannelInitializer<SocketChannel>() { override fun initChannel(channel: SocketChannel) { channel.pipeline().addLast(ProxyServerHandler(this@ProxyServer)) } }) val channelFuture = serverBootstrap.bind(bindPort).sync() LOGGER.info("Listening on the port $bindPort") channelFuture.channel().closeFuture().sync() return 0 } catch (exception: Throwable) { LOGGER.fatal("A fatal exception occurred", exception) return 1 } finally { workerGroup.shutdownGracefully() bossGroup.shutdownGracefully() } } companion object { private val LOGGER = LogManager.getLogger(ProxyServer::class.java) @JvmStatic fun start(bindPort: Int, remoteAddress: String, remotePort: Int, accountsFile: File, addonsDir: File, configDir: File): Int { val server: ProxyServer try { server = ProxyServer(bindPort, remoteAddress, remotePort, accountsFile, addonsDir, configDir) } catch (exception: RuntimeException) { return 2 } return server.run() } @Throws(NamingException::class) private fun lookupServer(hostname: String): Pair<String, Int> { val environment = Hashtable<String, String>() environment[DirContext.INITIAL_CONTEXT_FACTORY] = "com.sun.jndi.dns.DnsContextFactory" val dirContext = InitialDirContext(environment) val domain = "_minecraft._tcp.$hostname" val attributes = dirContext.getAttributes(domain, arrayOf("SRV")) dirContext.close() val srv = attributes["srv"].get().toString() LOGGER.info("Found a SRV record on $domain: $srv") val content = srv.split(' ') return content[3] to content[2].toInt() } @JvmStatic private fun refreshTokensIfExpired(accounts: MutableMap<String, PlayerProfile>): Boolean { var isModified = false for (entry in accounts) { val (username, uuid, auth) = entry.value if (System.currentTimeMillis() >= (auth ?: continue).expirationTime) { isModified = true LOGGER.info("The access token of the Minecraft account '${entry.key}' is expired, refreshing...") try { entry.setValue(PlayerProfile(username, uuid, auth.refresh())) } catch (exception: RuntimeException) { LOGGER.error("Failed to refresh the access token of the Minecraft account '${entry.key}'", exception) } } } return isModified } } }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/ProxyServer.kt
3273563365
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.utils sealed class HTTPRequestResult { val response: Response get() = if (this is Response) this else error("Not a response") @JvmSynthetic inline fun <R> onSuccess(block: SuccessResponse.() -> R): HTTPRequestResult { if (this is SuccessResponse) { block(this) } return this } @JvmSynthetic inline fun <R> onFailure(block: Failure.() -> R): HTTPRequestResult { if (this is Failure) { block(this) } return this } @JvmSynthetic inline fun <R> ifErrorResponse(block: ErrorResponse.() -> R): HTTPRequestResult { if (this is ErrorResponse) { block(this) } return this } @JvmSynthetic inline fun <R> ifInterruptedByException(block: InterruptedByException.() -> R): HTTPRequestResult { if (this is InterruptedByException) { block(this) } return this } sealed interface Response { val status: Int val content: ByteArray val contentAsUtf8String: String get() = content.toString(Charsets.UTF_8) } sealed interface Failure { fun buildException(message: String? = null): HTTPRequestException } class SuccessResponse(override val status: Int, override val content: ByteArray) : HTTPRequestResult(), Response class ErrorResponse(override val status: Int, override val content: ByteArray) : HTTPRequestResult(), Response, Failure { override fun buildException(message: String?): HTTPRequestException = HTTPRequestException(message, status, contentAsUtf8String) } class InterruptedByException(val exception: Throwable) : HTTPRequestResult(), Failure { override fun buildException(message: String?): HTTPRequestException = HTTPRequestException(message, exception) } }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/utils/HTTPRequestResult.kt
832291763
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("GsonInstance") package net.sharedwonder.mc.ptbridge.utils import com.google.gson.Gson @get:JvmName("getGson") val GSON: Gson = Gson()
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/utils/GsonInstance.kt
3608219605
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.utils import net.sharedwonder.mc.ptbridge.mcauth.MCAuth import java.lang.reflect.Type import java.math.BigInteger import java.net.HttpURLConnection import java.net.URI import java.net.URL import java.util.UUID import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonNull import com.google.gson.JsonObject import com.google.gson.JsonParseException import com.google.gson.JsonSerializationContext import com.google.gson.JsonSerializer import com.google.gson.annotations.JsonAdapter @JsonAdapter(PlayerProfile.JsonTypeAdapter::class) data class PlayerProfile @JvmOverloads constructor(val username: String, val uuid: UUID, val auth: MCAuth? = null) { fun joinServer(serverId: ByteArray) { if (auth == null) throw UnsupportedOperationException("This player profile has no authentication information") val body = JsonObject() body.addProperty("accessToken", auth.accessToken) body.addProperty("selectedProfile", uuid.toString()) body.addProperty("serverId", BigInteger(serverId).toString(16)) HTTPRequestUtils.request(JOIN_SERVER_URL, "POST", "application/json; charset=utf-8", GSON.toJson(body)) .onFailure { throw buildException("Failed to request to join the server for player the '$username/${UUIDUtils.uuidToString(uuid)}' on the Minecraft session service") } } @JvmOverloads fun hasJoinedServer(serverId: ByteArray, clientIp: String? = null): Boolean { val p1 = "username" to username val p2 = "serverId" to BigInteger(serverId).toString(16) val args = if (clientIp != null) mapOf(p1, p2, "ip" to clientIp) else mapOf(p1, p2) return (HTTPRequestUtils.request(HTTPRequestUtils.joinParameters("https://sessionserver.mojang.com/session/minecraft/hasJoined", args)) .onFailure { throw buildException("Failed to determine the player '$username/${UUIDUtils.uuidToString(uuid)}' has joined the server on the Minecraft session service") } .response).status == HttpURLConnection.HTTP_OK } internal class JsonTypeAdapter : JsonSerializer<PlayerProfile>, JsonDeserializer<PlayerProfile> { override fun serialize(src: PlayerProfile?, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { if (src == null) { return JsonNull.INSTANCE } val json = JsonObject() json.addProperty("username", src.username) json.addProperty("uuid", src.uuid.toString()) if (src.auth != null) { json.add("auth", JsonObject().apply { addProperty("impl", src.auth.javaClass.typeName) add("data", context.serialize(src.auth)) }) } return json } override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): PlayerProfile { try { json as JsonObject val username = json["username"].asString val uuid = UUID.fromString(json["uuid"].asString) val auth = json["auth"]?.let { if (!it.isJsonNull) { it as JsonObject val impl = it["impl"].asString val content = it["data"] try { context.deserialize<MCAuth>(content, Class.forName(impl)) } catch (exception: ClassCastException) { throw RuntimeException("Not a MCAuth implementation: $impl") } catch (exception: ClassNotFoundException) { throw RuntimeException("MCAuth implementation not found: $impl") } } else null } return PlayerProfile(username, uuid, auth) } catch (exception: Exception) { throw JsonParseException("Invalid player profile: $json", exception) } } } private companion object { private val JOIN_SERVER_URL: URL = URI("https://sessionserver.mojang.com/session/minecraft/join").toURL() } }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/utils/PlayerProfile.kt
2413332628
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.utils import java.io.File import java.io.IOException import com.google.gson.reflect.TypeToken object AccountsFileUtils { fun readFile(file: File): MutableMap<String, PlayerProfile> { return if (file.isFile) { file.reader().use { @Suppress("UNCHECKED_CAST") GSON.fromJson(it, TypeToken.getParameterized(Map::class.java, String::class.java, PlayerProfile::class.java)) as MutableMap<String, PlayerProfile> } } else mutableMapOf() } @Throws(IOException::class) fun writeFile(file: File, accounts: Map<String, PlayerProfile>) { val jsonWriter = GSON.newJsonWriter(file.writer()) jsonWriter.setIndent(" ") jsonWriter.use { GSON.toJson(accounts, Map::class.java, it) } } }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/utils/AccountsFileUtils.kt
1322756770
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.utils import java.io.Serial class HTTPRequestException : RuntimeException { val responseCode: Int? val responseContent: String? override val message: String? get() = if (super.message == null) additionalInfo() else super.message + (additionalInfo() ?: "") constructor(message: String?, responseCode: Int, responseContent: String) : super(message) { this.responseCode = responseCode this.responseContent = responseContent } constructor(message: String?, cause: Throwable?) : super(message, cause) { responseCode = null responseContent = null } private fun additionalInfo(): String? = if (responseCode != null) { "\n- Response code: $responseCode" + (if (responseContent != null) "\n- Response content: $responseContent" else "") } else null private companion object { @Serial private const val serialVersionUID = 3653710697125111531L } }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/utils/HTTPRequestException.kt
3751724518
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.utils object FormattedText { const val BLACK: String = "§0" const val DARK_BLUE: String = "§1" const val DARK_GREEN: String = "§2" const val DARK_AQUA: String = "§3" const val DARK_RED: String = "§4" const val DARK_PURPLE: String = "§5" const val GOLD: String = "§6" const val GRAY: String = "§7" const val DARK_GRAY: String = "§8" const val BLUE: String = "§9" const val GREEN: String = "§a" const val AQUA: String = "§b" const val RED: String = "§c" const val LIGHT_PURPLE: String = "§d" const val YELLOW: String = "§e" const val WHITE: String = "§f" const val OBFUSCATED: String = "§k" const val BOLD: String = "§l" const val STRIKETHROUGH: String = "§m" const val UNDERLINE: String = "§n" const val ITALIC: String = "§o" const val RESET: String = "§r" }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/utils/FormattedText.kt
3044367686
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.utils enum class ConnectionState(val id: Int) { HANDSHAKE(-1), PLAY(0), STATUS(1), LOGIN(2); companion object { @JvmStatic fun getById(id: Int): ConnectionState { return when (id) { -1 -> HANDSHAKE 0 -> PLAY 1 -> STATUS 2 -> LOGIN else -> throw IllegalArgumentException("Invalid id: $id") } } } }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/utils/ConnectionState.kt
1277301193
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.utils import java.util.UUID object UUIDUtils { @JvmStatic @OptIn(ExperimentalStdlibApi::class) fun stringToUuid(uuid: String): UUID = UUID(uuid.take(16).hexToLong(), uuid.substring(16).hexToLong()) @JvmStatic @OptIn(ExperimentalStdlibApi::class) fun uuidToString(uuid: UUID): String = "${uuid.mostSignificantBits.toHexString()}${uuid.leastSignificantBits.toHexString()}" }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/utils/UUIDUtils.kt
3335153163
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.utils import java.net.HttpURLConnection import java.net.MalformedURLException import java.net.URI import java.net.URL import java.net.URLEncoder import java.util.function.Consumer object HTTPRequestUtils { @JvmStatic @JvmSynthetic fun request(url: String, method: String = "GET", contentType: String? = null, body: Any? = null, block: HttpURLConnection.() -> Unit = {}): HTTPRequestResult = request(stringToUrl(url), method, contentType, body, block) @JvmStatic @JvmSynthetic fun request(url: URL, method: String = "GET", contentType: String? = null, body: Any? = null, block: HttpURLConnection.() -> Unit = {}): HTTPRequestResult { require(url.protocol == "http" || url.protocol == "https") { "Protocol of the URL should be HTTP/HTTPS, but was ${url.protocol.uppercase()}" } val bytes = when (body) { null -> null is ByteArray -> body is String -> body.toByteArray() is CharSequence -> body.toString().toByteArray() else -> throw IllegalArgumentException("Cannot convert thr argument 'body' to a byte array, type of 'body': ${body.javaClass.typeName}") } val connection: HttpURLConnection try { connection = url.openConnection() as HttpURLConnection try { connection.requestMethod = method if (contentType != null) { connection.setRequestProperty("Content-Type", contentType) } if (bytes != null) { connection.doOutput = true connection.outputStream.use { it.write(bytes) it.flush() } } block.invoke(connection) val status = connection.responseCode return if (status >= 400) { HTTPRequestResult.ErrorResponse(status, connection.errorStream?.use { it.readBytes() } ?: byteArrayOf()) } else { HTTPRequestResult.SuccessResponse(status, connection.inputStream.use { it.readBytes() }) } } finally { connection.disconnect() } } catch (exception: Throwable) { return HTTPRequestResult.InterruptedByException(exception) } } @JvmStatic @JvmOverloads @JvmName("request") fun _request(url: String, method: String = "GET", contentType: String? = null, body: Any? = null, block: Consumer<in HttpURLConnection> = Consumer {}): HTTPRequestResult = request(url, method, contentType, body) { block.accept(this) } @JvmStatic @JvmOverloads @JvmName("request") fun _request(url: URL, method: String = "GET", contentType: String? = null, body: Any? = null, block: Consumer<in HttpURLConnection> = Consumer {}): HTTPRequestResult = request(url, method, contentType, body) { block.accept(this) } @JvmStatic fun joinParameters(baseUrl: String, params: Map<String, String>): String = baseUrl + '?' + encodeMap(params) @JvmStatic fun encodeMap(params: Map<String, String>): String { val builder = StringBuilder() for ((key, value) in params) { if (builder.isNotEmpty()) { builder.append("&") } builder.append(URLEncoder.encode(key, Charsets.UTF_8)) builder.append("=") builder.append(URLEncoder.encode(value, Charsets.UTF_8)) } return builder.toString() } @JvmStatic private fun stringToUrl(string: String): URL { try { return URI.create(string).toURL() } catch (exception: MalformedURLException) { throw IllegalArgumentException("Invalid URL: $string", exception) } } }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/utils/HTTPRequestUtils.kt
1590299592
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.utils import com.google.gson.JsonObject object TextUtils { @JvmField val FORMATTING_REGEX: Regex = Regex("§[0-9a-fk-or]", RegexOption.IGNORE_CASE) @JvmStatic fun serialize(text: String): String { val obj = JsonObject() obj.addProperty("text", text) return GSON.toJson(obj) } @JvmStatic fun colorOfId(colorId: Byte): String { return when (colorId.toInt()) { 0 -> FormattedText.BLACK 1 -> FormattedText.DARK_BLUE 2 -> FormattedText.DARK_GREEN 3 -> FormattedText.DARK_AQUA 4 -> FormattedText.DARK_RED 5 -> FormattedText.DARK_PURPLE 6 -> FormattedText.GOLD 7 -> FormattedText.GRAY 8 -> FormattedText.DARK_GRAY 9 -> FormattedText.BLUE 10 -> FormattedText.GREEN 11 -> FormattedText.AQUA 12 -> FormattedText.RED 13 -> FormattedText.LIGHT_PURPLE 14 -> FormattedText.YELLOW 15 -> FormattedText.WHITE else -> throw IllegalArgumentException("Invalid color: $colorId") } } @JvmStatic fun toPlaintext(text: String): String = text.replace(FORMATTING_REGEX, "") @JvmStatic fun alignTextTable(table: List<Array<String>>, separator: String): Array<String> { val aligned = arrayOfNulls<String>(table.size) val maxColumnLengths = ArrayList<Int>() for (row in table) { for ((index, text) in row.withIndex()) { val length = toPlaintext(text).length if (index >= maxColumnLengths.size) { maxColumnLengths.add(length) } else { maxColumnLengths[index] = maxOf(maxColumnLengths[index], length) } } } for ((rowIndex, row) in table.withIndex()) { val builder = StringBuilder() for ((index, text) in row.withIndex()) { builder.append(FormattedText.RESET).append(text).append(" ".repeat(maxColumnLengths[index] - toPlaintext(text).length)) if (index < row.lastIndex) { builder.append(separator) } } aligned[rowIndex] = builder.toString() } @Suppress("UNCHECKED_CAST") return aligned as Array<String> } }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/utils/TextUtils.kt
1618273783
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("Constants") package net.sharedwonder.mc.ptbridge.utils const val PID_CH_HANDSHAKE: Int = 0x0 const val PID_CL_REQUEST_LOGIN: Int = 0x0 const val PID_CL_ENCRYPTION_RESPONSE: Int = 0x1 const val PID_SL_REQUEST_ENCRYPTION: Int = 0x1 const val PID_SL_LOGIN_SUCCESS: Int = 0x2 const val PID_SL_ENABLE_COMPRESSION: Int = 0x3 const val PID_SP_V47_SET_COMPRESSION_LEVEL: Int = 0x46
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/utils/Constants.kt
3964802174
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("Main") package net.sharedwonder.mc.ptbridge import kotlin.system.exitProcess import java.io.File import com.beust.jcommander.JCommander import com.beust.jcommander.Parameter import com.beust.jcommander.ParameterException import com.beust.jcommander.UnixStyleUsageFormatter private object MainArguments { @Parameter(names = ["-h", "--help"], help = true, description = "Show the help message") var help: Boolean = false @Parameter(names = ["-v", "--version"], description = "Show the version") var version: Boolean = false @Parameter(names = ["-b", "--bind-port"], description = "Specifies the proxy server binding port") var bindPort: Int = 25565 @Parameter(names = ["-a", "--address"], description = "Specifies the origin Minecraft server address") var remoteAddress: String? = null @Parameter(names = ["-p", "--port"], description = "Specifies the origin Minecraft server port") var remotePort: Int = 25565 @Parameter(names = ["-u", "--accounts-file"], description = "Specifies the Minecraft accounts file") var accountsFile: String = "accounts.json" @Parameter(names = ["-d", "--addons-dir"], description = "Specifies the directory where the addons will be loaded") var addonsDir: String = "addons" @Parameter(names = ["-c", "--config-dir"], description = "Specifies the configuration directory") var configDir: String = "config" @Parameter(names = ["-i", "--login"], description = "Prompts to add a Minecraft account to the accounts file, requires an account type") var login: String? = null @Parameter(names = ["-o", "--logout"], description = "Remove a Minecraft account from the accounts file, requires a username") var logout: String? = null @Parameter(names = ["-l", "--list-accounts"], description = "Lists the Minecraft accounts that are logged in") var listAccounts: Boolean = false } fun main(args: Array<String>) { val commander = JCommander() commander.addObject(MainArguments) commander.programName = MetaInfo.ID try { commander.parse(*args) } catch (exception: ParameterException) { println("Invalid arguments: ${exception.message}") exitProcess(-1) } exitProcess(MainArguments.run { when { help -> showHelp(commander) version -> showVersion() else -> { remoteAddress?.let { ProxyServer.start(bindPort, it, remotePort, File(accountsFile), File(addonsDir), File(configDir)) } ?: login?.let { addMinecraftAccount(File(accountsFile), it) } ?: logout?.let { removeMinecraftAccount(File(accountsFile), it) } ?: if (listAccounts) { listMinecraftAccounts(File(accountsFile)) } else { showHelp(commander) } } } }) } private fun showHelp(commander: JCommander): Int { println("PTBridge - A Lightweight Minecraft Server Proxy") println("Copyright (C) 2024 sharedwonder (Liu Baihao).") println() val builder = StringBuilder() UnixStyleUsageFormatter(commander).usage(builder) println(builder.toString()) return 0 } private fun showVersion(): Int { println("PTBridge version ${MetaInfo.VERSION}") return 0 }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/Main.kt
318124399
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge import net.sharedwonder.mc.ptbridge.mcauth.msa.MCAuthWithMSA import net.sharedwonder.mc.ptbridge.mcauth.msa.MSAAuthTokenType import net.sharedwonder.mc.ptbridge.utils.AccountsFileUtils import java.io.File import java.util.regex.Pattern private const val MSA_LOGIN_URL = "https://login.live.com/oauth20_authorize.srf?client_id=00000000402b5328&response_type=code" + "&scope=service::user.auth.xboxlive.com::MBI_SSL&redirect_uri=https://login.live.com/oauth20_desktop.srf" private val MSA_LOGIN_REDIRECT_URL_PATTERN = Pattern.compile("^http(s)?://login\\.live\\.com/oauth20_desktop\\.srf\\?code=([^&]+)(&.+)?\$") fun addMinecraftAccount(accountsFile: File, accountType: String): Int { try { when (accountType) { "msa" -> { println("Open '$MSA_LOGIN_URL' to login your Microsoft Account.") println("Then input the authorization code or the redirect URL here:") val input = readlnOrNull() if (input.isNullOrBlank()) { System.err.println("You didn't input anything") return 1 } val matcher = MSA_LOGIN_REDIRECT_URL_PATTERN.matcher(input) val code = if (matcher.matches()) matcher.group(2) else input val profile = MCAuthWithMSA(MSAAuthTokenType.AUTHORIZATION_CODE, code).createProfile() val accounts = AccountsFileUtils.readFile(accountsFile) if (accounts.containsKey(profile.username)) { System.err.println("Account of the username '${profile.username}' already exists") return 1 } accounts[profile.username] = profile AccountsFileUtils.writeFile(accountsFile, accounts) println("Successfully added a new Minecraft account: ${profile.username}/${profile.uuid}") return 0 } "mojang" -> { println("Mojang accounts are no longer available") return 1 } else -> { System.err.println("Unknown account type '$accountType', it must be one of: 'msa', 'mojang'") return 1 } } } catch (exception: Throwable) { System.err.println("An error occurred while adding a Minecraft account") exception.printStackTrace() return 1 } } fun removeMinecraftAccount(accountsFile: File, username: String): Int { try { val accounts = AccountsFileUtils.readFile(accountsFile) if (accounts.remove(username) == null) { System.err.println("Account of the username '$username' was not found") } else { AccountsFileUtils.writeFile(accountsFile, accounts) } println("Successfully removed the specified Minecraft account") return 0 } catch (exception: Throwable) { System.err.println("An error occurred while removing a Minecraft account") exception.printStackTrace() return 1 } } fun listMinecraftAccounts(accountsFile: File): Int { try { val accounts = AccountsFileUtils.readFile(accountsFile) for ((_, profile) in accounts) { println("${profile.username}/${profile.uuid}") } return 0 } catch (exception: Throwable) { exception.printStackTrace() return 1 } }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/AccountsTool.kt
1025881185
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge import net.sharedwonder.mc.ptbridge.utils.GSON object MetaInfo { const val ID = "ptbridge" @JvmField val VERSION: String = GSON.fromJson(javaClass.classLoader.getResourceAsStream("META-INF/net.sharedwonder.mc.ptbridge.json")!! .reader(Charsets.UTF_8), Map::class.java)["version"] as String }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/MetaInfo.kt
3718259797
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.addon data class AddonInfo( val id: String, val name: String, val version: String, val description: String?, val author: String?, val initializer: String )
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/addon/AddonInfo.kt
3669412663
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.addon import net.sharedwonder.mc.ptbridge.utils.GSON import java.io.File import java.net.URLClassLoader import java.util.jar.JarFile import org.apache.logging.log4j.LogManager object AddonLoader { private const val INFO_FILE_NAME: String = "ptbridge-addon.json" private val LOGGER = LogManager.getLogger(AddonLoader::class.java) private val ADDONS = HashMap<String, AddonInfo>() @JvmStatic fun getAddonInfo(id: String): AddonInfo { val info = ADDONS[id] checkNotNull(info) { "The addon of $id is not loaded" } return info } @JvmStatic @PublishedApi internal fun init(addonsDir: File) { if (addonsDir.exists()) { val addons = addonsDir.walk().maxDepth(1).filter { it.isFile && it.extension == "jar" }.toList() if (addons.isNotEmpty()) { if (LOGGER.isInfoEnabled) { LOGGER.info("The following addon(s) will be loaded:\n${addons.joinToString("\n - ", prefix = " - ") { it.name }}") } addons.forEach { load(it) } } } } @JvmStatic private fun load(file: File): Boolean { if (!file.exists()) { LOGGER.error("Addon file not found: ${file.name}") return false } val info: AddonInfo try { JarFile(file).use { it.getInputStream(it.getJarEntry(INFO_FILE_NAME)).reader().use { reader -> info = GSON.fromJson(reader, AddonInfo::class.java) } } } catch (exception: Exception) { LOGGER.error("Failed to read addon info: ${file.name}", exception) return false } val initializer: AddonInitializer try { val classLoader = URLClassLoader(arrayOf(file.toURI().toURL())) initializer = classLoader.loadClass(info.initializer).getConstructor().newInstance() as AddonInitializer } catch (exception: NullPointerException) { LOGGER.error("Invalid addon info: ${file.name}", exception) return false } catch (exception: ClassNotFoundException) { LOGGER.error("Addon initializer class not found: ${file.name}", exception) return false } catch (exception: ReflectiveOperationException) { LOGGER.error("Invalid addon initializer class: ${file.name}", exception) return false } catch (exception: ClassCastException) { LOGGER.error("Not an addon initializer class: ${file.name}", exception) return false } catch (exception: Exception) { LOGGER.error("Unknown error while loading the addon: ${file.name}", exception) return false } try { ADDONS[info.id] = info initializer.init() } catch (exception: Throwable) { LOGGER.error("Exception thrown while initializing the addon: ${file.name}", exception) ADDONS.remove(info.id) return false } return true } }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/addon/AddonLoader.kt
2124906791
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.packet enum class HandledFlag { PASSED, TRANSFORMED, BLOCKED }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/packet/HandledFlag.kt
198654799
/* * Copyright (C) 2024 sharedwonder (Liu Baihao). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sharedwonder.mc.ptbridge.packet import net.sharedwonder.mc.ptbridge.utils.ConnectionState import net.sharedwonder.mc.ptbridge.utils.PID_CH_HANDSHAKE enum class PacketType { C2S { @OptIn(ExperimentalStdlibApi::class) override fun getPacketHandler(connectionState: ConnectionState, id: Int): C2SPacketHandler? { return when (connectionState) { ConnectionState.HANDSHAKE -> { require(id == PID_CH_HANDSHAKE) { "The connection state is 'HANDSHAKE' but the packet ID is ${id.toHexString()}, expected 0x0" } PacketHandlers.getHandshakePacketHandler() } ConnectionState.PLAY -> PacketHandlers.C2S_PLAY_PACKET_HANDLERS[id] ConnectionState.LOGIN -> PacketHandlers.C2S_LOGIN_PACKET_HANDLERS[id] ConnectionState.STATUS -> PacketHandlers.C2S_STATUS_PACKET_HANDLERS[id] } } }, S2C { override fun getPacketHandler(connectionState: ConnectionState, id: Int): S2CPacketHandler? { return when (connectionState) { ConnectionState.HANDSHAKE -> throw IllegalArgumentException("The connection state 'HANDSHAKE' is not available for S2C (server to client) packets") ConnectionState.PLAY -> PacketHandlers.S2C_PLAY_PACKET_HANDLERS[id] ConnectionState.LOGIN -> PacketHandlers.S2C_LOGIN_PACKET_HANDLERS[id] ConnectionState.STATUS -> PacketHandlers.S2C_STATUS_PACKET_HANDLERS[id] } } }; abstract fun getPacketHandler(connectionState: ConnectionState, id: Int): PacketHandler? }
ptbridge/src/main/kotlin/net/sharedwonder/mc/ptbridge/packet/PacketType.kt
3396207486
package com.ren.mvvmandroid15 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.ren.mvvmandroid15", appContext.packageName) } }
MVVMAndroid15/app/src/androidTest/java/com/ren/mvvmandroid15/ExampleInstrumentedTest.kt
2924550526
package com.ren.mvvmandroid15 import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
MVVMAndroid15/app/src/test/java/com/ren/mvvmandroid15/ExampleUnitTest.kt
508865435
package com.ren.mvvmandroid15.ui.viewmodels import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.ren.mvvmandroid15.data.models.User import com.ren.mvvmandroid15.data.preferences.PreferencesHelper import com.ren.mvvmandroid15.utils.UiState class SharedPreferencesViewModel : ViewModel() { private val _userInfoLiveData = MutableLiveData<UiState<User>>() val userInfoLiveData: LiveData<UiState<User>> = _userInfoLiveData fun saveUserInfo(user: User) = with(user) { PreferencesHelper.name = name PreferencesHelper.age = age } fun getUserInfo() = with(PreferencesHelper) { val user = User( name = name ?: "", age = age ) userInfoLiveData.value?.copy(isLoading = false, success = user)?.let { newValue -> _userInfoLiveData.value = newValue } } }
MVVMAndroid15/app/src/main/java/com/ren/mvvmandroid15/ui/viewmodels/SharedPreferencesViewModel.kt
165061308
package com.ren.mvvmandroid15.ui.viewmodels import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.ren.mvvmandroid15.data.models.Box import com.ren.mvvmandroid15.data.repositories.BoxRepository class BoxViewModel : ViewModel() { private val boxRepository = BoxRepository() private val _boxesLiveData = MutableLiveData<BoxUiState<List<Box>>>() val boxLiveData: LiveData<BoxUiState<List<Box>>> = _boxesLiveData private val _editBoxLiveData = MutableLiveData<EditBox>() val editBoxLiveData: LiveData<EditBox> = _editBoxLiveData init { Log.i("ViewModel", "initialize") getBoxes() } fun getBoxes() { android.os.Handler().postDelayed( { val boxes = boxRepository.getBoxes() if (boxes.size <= 10) { _boxesLiveData.value = BoxUiState(isLoading = false, success = boxes) } else { _boxesLiveData.value = BoxUiState(isLoading = false, error = "very large amount of data") } }, 3000 ) } fun addBox(box: Box) { boxRepository.addBox(box) } fun passBoxToEdit(index: Int, box: Box) { _editBoxLiveData.value = EditBox( index = index, box = box ) } fun editBox(index: Int, box: Box) { boxRepository.editBox(index, box) } override fun onCleared() { super.onCleared() Log.i("ViewModel", "cleared") } } data class EditBox( val index: Int, val box: Box ) data class BoxUiState<T>( val isLoading: Boolean = true, val error: String? = null, val success: T? = null )
MVVMAndroid15/app/src/main/java/com/ren/mvvmandroid15/ui/viewmodels/BoxViewModel.kt
2036759523
package com.ren.mvvmandroid15.ui.adapters import android.content.res.ColorStateList import android.graphics.Color import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Toast import androidx.recyclerview.widget.RecyclerView import com.ren.mvvmandroid15.data.models.Box import com.ren.mvvmandroid15.databinding.ItemBoxBinding class BoxesAdapter( private val onItemClick: (box: Box) -> Unit, private val onItemEditClick: (index: Int, box: Box) -> Unit ) : RecyclerView.Adapter<BoxesAdapter.BoxViewHolder>() { private var boxes = emptyList<Box>() fun setBoxes(boxes: List<Box>) { this.boxes = boxes notifyDataSetChanged() } inner class BoxViewHolder(private val binding: ItemBoxBinding) : RecyclerView.ViewHolder(binding.root) { init { binding.tvItemEdit.setTextColor( ColorStateList( arrayOf( intArrayOf(android.R.attr.state_pressed), intArrayOf(-android.R.attr.state_pressed), ), intArrayOf( Color.YELLOW, Color.BLACK ) ) ) binding.root.setOnClickListener { onItemClick(boxes[adapterPosition]) } binding.tvItemEdit.setOnClickListener { onItemEditClick(adapterPosition, boxes[adapterPosition]) } } fun onBind(box: Box) = with(binding) { try { root.setCardBackgroundColor(ColorStateList.valueOf(Color.parseColor(box.color))) } catch (e: Exception) { Toast.makeText(root.context, "Такого цвета не существует", Toast.LENGTH_SHORT).show() } tvItemText.text = box.text } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BoxViewHolder { val binding = ItemBoxBinding.inflate(LayoutInflater.from(parent.context), parent, false) return BoxViewHolder(binding) } override fun getItemCount() = boxes.size override fun onBindViewHolder(holder: BoxViewHolder, position: Int) { holder.onBind(boxes[position]) } }
MVVMAndroid15/app/src/main/java/com/ren/mvvmandroid15/ui/adapters/BoxesAdapter.kt
3612256220
package com.ren.mvvmandroid15.ui.views.fragments import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.ren.mvvmandroid15.R import com.ren.mvvmandroid15.data.models.Box import com.ren.mvvmandroid15.databinding.FragmentBoxBinding import com.ren.mvvmandroid15.ui.adapters.BoxesAdapter import com.ren.mvvmandroid15.ui.viewmodels.BoxViewModel class BoxFragment : Fragment() { private var _binding: FragmentBoxBinding? = null private val binding get() = _binding!! private val viewModel by activityViewModels<BoxViewModel>() private val boxesAdapter = BoxesAdapter(::onItemClick, ::onItemEditClick) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.i("Fragment", "onCreate") } private fun onItemClick(box: Box) { Log.i("onItemClick", "click") } private fun onItemEditClick(index: Int, box: Box) { viewModel.passBoxToEdit(index, box) findNavController().navigate(R.id.editBoxFragment) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentBoxBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initialize() addNewBox() subscribeToBoxes() } private fun initialize() { binding.rvBoxes.adapter = boxesAdapter } private fun addNewBox() { binding.fabAdd.setOnClickListener { val newBox = Box("Ocean Box", "#FF22B9FD") viewModel.addBox(newBox) } } private fun subscribeToBoxes() { viewModel.boxLiveData.observe(viewLifecycleOwner) { boxUiState -> boxUiState?.let { binding.progressBar.isVisible = it.isLoading if (it.success != null) { boxesAdapter.setBoxes(it.success) } else { Toast.makeText(requireContext(), it.error, Toast.LENGTH_SHORT).show() } } } } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onDestroy() { super.onDestroy() Log.i("Fragment", "onDestroy") } }
MVVMAndroid15/app/src/main/java/com/ren/mvvmandroid15/ui/views/fragments/BoxFragment.kt
251062535
package com.ren.mvvmandroid15.ui.views.fragments import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.ren.mvvmandroid15.data.models.Box import com.ren.mvvmandroid15.databinding.FragmentDetailBinding import com.ren.mvvmandroid15.databinding.FragmentEditBoxBinding import com.ren.mvvmandroid15.ui.adapters.BoxesAdapter import com.ren.mvvmandroid15.ui.viewmodels.BoxViewModel class EditBoxFragment : Fragment() { private var _binding: FragmentEditBoxBinding? = null private val binding get() = _binding!! private val viewModel by activityViewModels<BoxViewModel>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentEditBoxBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) onSavePressed() subscribeToEditBox() } private fun onSavePressed() = with(binding) { btnSave.setOnClickListener { val editBox = viewModel.editBoxLiveData.value val newBoxName = etBoxName.text.toString().trim() val newBoxColor = etBoxColor.text.toString().trim() if (editBox != null) { val box = Box( text = newBoxName, color = newBoxColor ) viewModel.editBox(editBox.index, box) } findNavController().navigateUp() } } private fun subscribeToEditBox() = with(binding) { viewModel.editBoxLiveData.observe(viewLifecycleOwner) { editBox -> editBox?.let { etBoxName.setText(it.box.text) etBoxColor.setText(it.box.color) } } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
MVVMAndroid15/app/src/main/java/com/ren/mvvmandroid15/ui/views/fragments/EditBoxFragment.kt
1726176912
package com.ren.mvvmandroid15.ui.views.fragments import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.ren.mvvmandroid15.data.models.Box import com.ren.mvvmandroid15.databinding.FragmentDetailBinding import com.ren.mvvmandroid15.ui.adapters.BoxesAdapter import com.ren.mvvmandroid15.ui.viewmodels.BoxViewModel class DetailFragment : Fragment() { private var _binding: FragmentDetailBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentDetailBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) } override fun onDestroyView() { super.onDestroyView() _binding = null } }
MVVMAndroid15/app/src/main/java/com/ren/mvvmandroid15/ui/views/fragments/DetailFragment.kt
3817358232
package com.ren.mvvmandroid15.ui.views.activity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.ren.mvvmandroid15.R class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
MVVMAndroid15/app/src/main/java/com/ren/mvvmandroid15/ui/views/activity/MainActivity.kt
2777106928
package com.ren.mvvmandroid15 import android.app.Application import com.ren.mvvmandroid15.data.preferences.PreferencesHelper class App : Application() { override fun onCreate() { super.onCreate() PreferencesHelper.init(this) } }
MVVMAndroid15/app/src/main/java/com/ren/mvvmandroid15/App.kt
1485119358
package com.ren.mvvmandroid15.utils data class UiState<T>( val isLoading: Boolean = true, val error: String? = null, val success: T? = null )
MVVMAndroid15/app/src/main/java/com/ren/mvvmandroid15/utils/UiState.kt
3876874231
package com.ren.mvvmandroid15.data.preferences import android.content.Context import android.content.SharedPreferences import com.ren.mvvmandroid15.R object PreferencesHelper { private const val NAME_PREFERENCE_KEY = "name" private const val AGE_PREFERENCE_KEY = "age" private lateinit var sharedPreferences: SharedPreferences fun init(context: Context) { sharedPreferences = context.getSharedPreferences( context.getString(R.string.shared_preferences_name), Context.MODE_PRIVATE ) } var name: String? get() = sharedPreferences.getString(NAME_PREFERENCE_KEY, "") set(value) = sharedPreferences.edit().putString(NAME_PREFERENCE_KEY, value).apply() var age: Int get() = sharedPreferences.getInt(AGE_PREFERENCE_KEY, 0) set(value) = sharedPreferences.edit().putInt(AGE_PREFERENCE_KEY, value).apply() }
MVVMAndroid15/app/src/main/java/com/ren/mvvmandroid15/data/preferences/PreferencesHelper.kt
3242482498
package com.ren.mvvmandroid15.data.repositories import com.ren.mvvmandroid15.data.models.Box class BoxRepository { private val boxes = mutableListOf( Box(text = "Black Box", color = "#FF000000"), Box(text = "White Box", color = "#FFFFFFFF"), Box(text = "Red Box", color = "#F44336"), Box(text = "Blue Box", color = "#3F51B5"), Box(text = "Green Box", color = "#4CAF50"), Box(text = "Orange Box", color = "#FF9800"), Box(text = "Pink Box", color = "#FD578F"), Box(text = "Yellow Box", color = "#FFEB3B"), Box(text = "Purple Box", color = "#9C27B0"), Box(text = "Lime Box", color = "#8BC34A"), ) fun getBoxes() = boxes fun addBox(box: Box) { boxes.add(box) } fun editBox(index: Int, box: Box) { boxes[index] = box } }
MVVMAndroid15/app/src/main/java/com/ren/mvvmandroid15/data/repositories/BoxRepository.kt
388445817
package com.ren.mvvmandroid15.data.models data class Box( val text: String, val color: String )
MVVMAndroid15/app/src/main/java/com/ren/mvvmandroid15/data/models/Box.kt
1366011062
package com.ren.mvvmandroid15.data.models data class User( val name: String, val age: Int )
MVVMAndroid15/app/src/main/java/com/ren/mvvmandroid15/data/models/User.kt
2502421569
package com.example.vaccine import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.vaccine", appContext.packageName) } }
Vaccine_recyclerview/app/src/androidTest/java/com/example/vaccine/ExampleInstrumentedTest.kt
3123918688
package com.example.vaccine import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Vaccine_recyclerview/app/src/test/java/com/example/vaccine/ExampleUnitTest.kt
4074598364
package com.example.vaccine import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // 1- AdapterView: RecyclerView val recyclerView: RecyclerView = findViewById(R.id.recyclerview) recyclerView.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false) // 2- Dta source: List of VaccineModel val vaccineList: ArrayList<VaccineModel> = ArrayList() val v1 = VaccineModel("Covaxin",R.drawable.cavaxin) val v2 = VaccineModel("Covishield",R.drawable.covishield) val v3 = VaccineModel("Phzer",R.drawable.covid) val v4 = VaccineModel("Measles",R.drawable.measles) val v5 = VaccineModel("Hepatitis",R.drawable.hepatitis) val v6 = VaccineModel("Rotavirus",R.drawable.rotavirus) val v7 = VaccineModel("Tetanus",R.drawable.tetanus) val v8 = VaccineModel("Polio",R.drawable.polio) vaccineList.add(v1) vaccineList.add(v2) vaccineList.add(v3) vaccineList.add(v4) vaccineList.add(v5) vaccineList.add(v6) vaccineList.add(v7) vaccineList.add(v8) // 3- Adapter val adapter = MyAdapter(vaccineList) recyclerView.adapter = adapter } }
Vaccine_recyclerview/app/src/main/java/com/example/vaccine/MainActivity.kt
24430379
package com.example.vaccine data class VaccineModel(val name:String, val image: Int)
Vaccine_recyclerview/app/src/main/java/com/example/vaccine/VaccineModel.kt
4170448778
package com.example.vaccine import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.recyclerview.widget.RecyclerView class MyAdapter(private val vaccineList: ArrayList<VaccineModel>): RecyclerView.Adapter<MyAdapter.MyViewHolder>() { inner class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { var vaccineImage: ImageView var vaccineTitle: TextView init { vaccineImage = itemView.findViewById(R.id.imageview) vaccineTitle = itemView.findViewById(R.id.title) itemView.setOnClickListener { Toast.makeText(itemView.context,"You clicked: ${vaccineTitle.text}",Toast.LENGTH_SHORT).show() } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val v = LayoutInflater.from(parent.context) .inflate(R.layout.recycler_item_lyout,parent,false) return MyViewHolder(v) } override fun getItemCount(): Int { return vaccineList.size } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { holder.vaccineTitle.text = vaccineList[position].name holder.vaccineImage.setImageResource(vaccineList[position].image) } }
Vaccine_recyclerview/app/src/main/java/com/example/vaccine/MyAdapter.kt
1840245740
import androidx.compose.ui.window.ComposeUIViewController actual fun getPlatformName(): String = "iOS" fun MainViewController() = ComposeUIViewController { App() }
furniture-app-2.0/shared/src/iosMain/kotlin/main.ios.kt
169375472
import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource @OptIn(ExperimentalResourceApi::class) @Composable fun App() { MaterialTheme { var greetingText by remember { mutableStateOf("Hello, World!") } var showImage by remember { mutableStateOf(false) } Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { Button(onClick = { greetingText = "Hello, ${getPlatformName()}" showImage = !showImage }) { Text(greetingText) } AnimatedVisibility(showImage) { Image( painterResource("compose-multiplatform.xml"), contentDescription = "Compose Multiplatform icon" ) } } } } expect fun getPlatformName(): String
furniture-app-2.0/shared/src/commonMain/kotlin/App.kt
2739348563